Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): refuse to publish or bake an unsigned macOS release (#4151)
Francesco Bonacci102a6c76a884
diff --git a/.github/scripts/expect_verification_result.sh b/.github/scripts/expect_verification_result.shnew file mode 100644index 0000000000..407c7da513--- /dev/null+++ b/.github/scripts/expect_verification_result.sh@@ -0,0 +1,36 @@+#!/usr/bin/env bash+# Compare a verifier's exit status with the expected outcome.+#+# expect_verification_result.sh <pass|fail> <exit-status> <description>+#+# "pass" is the release gate: the verifier must succeed. "fail" is a negative+# control: the verifier must reject a known-bad input (for example the+# withdrawn, unsigned 0.28.3 macOS archives), which proves the gate can fail.+set -euo pipefail++expect="${1:?expected outcome (pass or fail) is required}"+status="${2:?verifier exit status is required}"+description="${3:-verification}"++case "$expect" in+ pass)+ if [[ "$status" == "0" ]]; then+ echo "${description}: passed as required."+ exit 0+ fi+ echo "::error title=Release signature gate::${description} failed (exit ${status}); publication and installer baking are blocked."+ exit 1+ ;;+ fail)+ if [[ "$status" == "0" ]]; then+ echo "::error title=Negative control::${description} passed, but this input is known to be unsigned; the verifier cannot detect a broken release."+ exit 1+ fi+ echo "${description}: rejected as expected for this negative control (exit ${status})."+ exit 0+ ;;+ *)+ echo "::error::unknown expected outcome '${expect}'; use pass or fail"+ exit 2+ ;;+esacdiff --git a/.github/scripts/tests/test_cua_driver_release_safety_wiring.py b/.github/scripts/tests/test_cua_driver_release_safety_wiring.pynew file mode 100644index 0000000000..a60f2f2f6c--- /dev/null+++ b/.github/scripts/tests/test_cua_driver_release_safety_wiring.py@@ -0,0 +1,247 @@+"""Release-safety wiring for Cua Driver (#4109).++0.28.3 was published with an unsigned macOS app and then baked into the+canonical installers, breaking every fresh macOS install. These tests pin the+gates that make that sequence impossible:++1. a run that can publish must notarize, and says so before building;+2. the release job cannot start until the exact candidate archives pass the+ macOS and Windows signature verification jobs;+3. the installer bake runs only after the published assets pass signature+ verification and the canonical installers install them on every platform;+4. no path skips those gates with always() or a similar status override.+"""++from __future__ import annotations++from pathlib import Path+import re++import pytest+import yaml+++REPO_ROOT = Path(__file__).resolve().parents[3]+CD = REPO_ROOT / ".github/workflows/cd-rust-cua-driver.yml"+SIGNATURES = REPO_ROOT / ".github/workflows/cua-driver-release-signatures.yml"+SELF_TEST = REPO_ROOT / ".github/workflows/ci-cua-driver-release-signatures.yml"+DO_NOTARIZE = "${{ startsWith(github.ref, 'refs/tags/cua-driver-rs-v') || inputs.notarize == true }}"+CAN_PUBLISH = (+ "${{ (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/cua-driver-rs-v')) "+ "|| (github.event_name == 'workflow_dispatch' && inputs.publish == true) }}"+)+STATUS_OVERRIDES = ("always()", "failure()", "cancelled()", "!cancelled()")+++def load(path: Path) -> dict:+ return yaml.safe_load(path.read_text(encoding="utf-8"))++[email protected](scope="module")+def cd() -> dict:+ return load(CD)+++def needs(job: dict) -> set[str]:+ value = job.get("needs", [])+ return {value} if isinstance(value, str) else set(value)+++def step(job: dict, name: str) -> dict:+ matches = [entry for entry in job["steps"] if entry.get("name") == name]+ assert len(matches) == 1, f"expected one step named {name!r}"+ return matches[0]+++def publishing_jobs(workflow: dict) -> list[str]:+ """Jobs that upload a release or move the public installers."""+ names = []+ for name, job in workflow["jobs"].items():+ text = yaml.safe_dump(job)+ if "github_release.py" in text or "update_cua_driver_installer_version.py" in text:+ names.append(name)+ return names+++def ancestors(workflow: dict, name: str) -> set[str]:+ seen: set[str] = set()+ pending = list(needs(workflow["jobs"][name]))+ while pending:+ current = pending.pop()+ if current not in seen:+ seen.add(current)+ pending.extend(needs(workflow["jobs"][current]))+ return seen+++def test_macos_build_notarizes_every_tag_build(cd: dict) -> None:+ build = cd["jobs"]["build-macos-universal"]+ assert build["env"]["DO_NOTARIZE"] == DO_NOTARIZE+ first = build["steps"][0]+ assert first["name"] == "Assert notarization for publishable builds"+ assert first["env"]["CAN_PUBLISH"] == CAN_PUBLISH+ assert '"$GITHUB_REF" == refs/tags/cua-driver-rs-v* && "$DO_NOTARIZE" != "true"' in first["run"]+ assert '"$CAN_PUBLISH" == "true" && "$DO_NOTARIZE" != "true"' in first["run"]+ # Signing and notarization steps are all keyed on the same switch.+ for name in (+ "Import code-signing certificate",+ "Codesign bare universal binary (hardened runtime)",+ "Codesign + notarize + staple CuaDriver.app",+ ):+ assert step(build, name)["if"] == "env.DO_NOTARIZE == 'true'"+++def test_publishing_without_notarization_fails_before_any_build(cd: dict) -> None:+ preflight = cd["jobs"]["release-attribution-preflight"]+ guard = preflight["steps"][0]+ assert guard["name"] == "Refuse to publish without macOS notarization"+ assert guard["env"] == {"CAN_PUBLISH": CAN_PUBLISH, "DO_NOTARIZE": DO_NOTARIZE}+ assert "exit 1" in guard["run"]+ for name in ("build-linux", "build-windows", "build-macos-universal"):+ assert "release-attribution-preflight" in needs(cd["jobs"][name])+++def test_every_publishing_path_is_a_notarized_path(cd: dict) -> None:+ """The release job's trigger must imply CAN_PUBLISH, which implies DO_NOTARIZE via the guard."""+ release = cd["jobs"]["release"]+ condition = release["if"]+ assert condition in (+ "github.event_name == 'workflow_dispatch' && inputs.publish == true",+ "github.event_name == 'push' && startsWith(github.ref, 'refs/tags/cua-driver-rs-v')",+ )+ guard = release["steps"][0]+ assert guard["name"] == "Refuse to publish unverified or unnotarized artifacts"+ assert guard["env"]["DO_NOTARIZE"] == DO_NOTARIZE+ assert guard["env"]["MACOS_SIGNATURES"] == "${{ needs.verify-macos-release-signatures.result }}"+ assert guard["env"]["WINDOWS_SIGNATURES"] == "${{ needs.verify-windows-release-signatures.result }}"+ assert '"$DO_NOTARIZE" != "true"' in guard["run"]+++def test_signature_jobs_verify_exact_candidate_archives(cd: dict) -> None:+ macos = cd["jobs"]["verify-macos-release-signatures"]+ windows = cd["jobs"]["verify-windows-release-signatures"]+ for job in (macos, windows):+ assert job["uses"] == "./.github/workflows/cua-driver-release-signatures.yml"+ assert job["with"]["source"] == "artifacts"+ assert job["with"]["version"] == "${{ needs.release-attribution-preflight.outputs.version }}"+ assert "expect_macos" not in job["with"] and "expect_windows" not in job["with"]+ assert needs(macos) == {"release-attribution-preflight", "build-macos-universal"}+ assert needs(windows) == {"release-attribution-preflight", "build-windows"}+ assert macos["with"]["verify_macos"] is True and macos["with"]["verify_windows"] is False+ assert windows["with"]["verify_macos"] is False and windows["with"]["verify_windows"] is True+ # The macOS gate runs for exactly the builds that notarize.+ assert "${{ " + macos["if"] + " }}" == DO_NOTARIZE+ assert "if" not in windows+++def test_release_job_needs_signature_verification(cd: dict) -> None:+ release = cd["jobs"]["release"]+ assert {+ "verify-release-artifacts",+ "verify-macos-release-signatures",+ "verify-windows-release-signatures",+ } <= needs(release)+ assert not any(override in release["if"] for override in STATUS_OVERRIDES)+ publish = step(release, "Publish the verified Release Please draft")+ assert release["steps"].index(step(release, "Refuse to publish unverified or unnotarized artifacts")) < release["steps"].index(publish)+ assert release["outputs"]["version"] == "${{ steps.version.outputs.version }}"+++def test_installer_bake_needs_post_publication_verification(cd: dict) -> None:+ jobs = cd["jobs"]+ signatures = jobs["verify-published-signatures"]+ installers = jobs["verify-published-installers"]+ bake = jobs["advance-installer-version"]++ assert signatures["uses"] == "./.github/workflows/cua-driver-release-signatures.yml"+ assert signatures["with"] == {"version": "${{ needs.release.outputs.version }}", "source": "release"}+ assert installers["uses"] == "./.github/workflows/ci-cua-driver-installer-compat.yml"+ assert installers["with"] == {"versions": "${{ needs.release.outputs.version }}"}+ for job in (signatures, installers):+ assert needs(job) == {"release"}+ assert "if" not in job++ assert needs(bake) == {"release", "verify-published-signatures", "verify-published-installers"}+ assert "if" not in bake+ advance = step(bake, "Advance public installer version on main")+ assert advance["env"]["VERSION"] == "${{ needs.release.outputs.version }}"+ assert "--withdrawn-path \"$UPDATE_ROOT/.github/release-state/cua-driver-rs-withdrawn-versions\"" in advance["run"]+ assert "validate_release_versions.py" in advance["run"]+++def test_only_the_gated_bake_job_moves_the_public_installers(cd: dict) -> None:+ assert sorted(publishing_jobs(cd)) == ["advance-installer-version", "release"]+ release_text = yaml.safe_dump(cd["jobs"]["release"])+ assert "--state-path" not in release_text+ assert "refs/heads/main" not in release_text+ staged = step(cd["jobs"]["release"], "Stage release files")["run"]+ assert "--withdrawn-path release-control/.github/release-state/cua-driver-rs-withdrawn-versions" in staged+ assert {+ "verify-macos-release-signatures",+ "verify-windows-release-signatures",+ "verify-published-signatures",+ "verify-published-installers",+ } <= ancestors(cd, "advance-installer-version")+++def test_no_gate_is_bypassed_by_a_status_override(cd: dict) -> None:+ for name in (+ "release",+ "verify-macos-release-signatures",+ "verify-windows-release-signatures",+ "verify-published-signatures",+ "verify-published-installers",+ "advance-installer-version",+ ):+ condition = str(cd["jobs"][name].get("if", ""))+ assert not any(override in condition for override in STATUS_OVERRIDES), name+++def test_signature_workflow_checks_what_the_operating_systems_check() -> None:+ workflow = load(SIGNATURES)+ trigger = workflow[True]["workflow_call"]["inputs"] # PyYAML parses `on` as True+ assert set(trigger) == {"version", "source", "verify_macos", "verify_windows", "expect_macos", "expect_windows"}+ assert trigger["expect_macos"]["default"] == "pass"+ assert trigger["expect_windows"]["default"] == "pass"+ assert workflow["permissions"] == {"contents": "read"}++ macos = workflow["jobs"]["macos"]+ windows = workflow["jobs"]["windows"]+ assert macos["runs-on"].startswith("macos-")+ assert windows["runs-on"].startswith("windows-")+ macos_verify = step(macos, "Verify macOS signatures, notarization, and stapling")["run"]+ assert "verify_cua_driver_release_signatures.py macos" in macos_verify+ assert "--team-id YCK386LBJ7" in macos_verify+ windows_verify = step(windows, "Verify Windows Authenticode signatures")["run"]+ assert "verify_cua_driver_release_signatures.py windows" in windows_verify+ assert '--signer "Cua AI, Inc."' in windows_verify+ for run in (macos_verify, windows_verify):+ # GitHub runs `bash -e`; the status must be captured, not aborted on.+ assert '${ANNOTATE[@]+"${ANNOTATE[@]}"} || STATUS=$?' in run+ assert run.index("STATUS=0") < run.index("|| STATUS=$?")+ assert "expect_verification_result.sh \"$EXPECT\" \"$STATUS\"" in run+ assert step(macos, "Download candidate darwin archives")["with"]["name"] == "cua-driver-rs-darwin"+ assert step(windows, "Download candidate Windows archives")["with"]["pattern"] == "cua-driver-rs-windows-*"+++def test_signature_team_matches_the_pinned_signing_team() -> None:+ cd_text = CD.read_text(encoding="utf-8")+ pinned = re.search(r"test \"\$TEAM_ID\" = '([A-Z0-9]{10})'", cd_text).group(1)+ assert pinned == "YCK386LBJ7"+ assert f"--team-id {pinned}" in SIGNATURES.read_text(encoding="utf-8")+ script = (REPO_ROOT / ".github/scripts/verify_cua_driver_release_signatures.py").read_text()+ assert f'RELEASE_TEAM_ID = "{pinned}"' in script+++def test_self_test_proves_the_gate_in_both_directions() -> None:+ workflow = load(SELF_TEST)+ jobs = workflow["jobs"]+ assert jobs["signed-release"]["with"] == {"version": "0.28.2", "source": "release"}+ assert jobs["unsigned-release"]["with"] == {+ "version": "0.28.3",+ "source": "release",+ "expect_macos": "fail",+ "expect_windows": "pass",+ }+ withdrawn = (REPO_ROOT / ".github/release-state/cua-driver-rs-withdrawn-versions").read_text()+ assert re.search(r"^0\.28\.3 #", withdrawn, re.MULTILINE)diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.pyindex aa1d4a1031..e0fbc212c0 100644--- a/.github/scripts/tests/test_cua_driver_release_wiring.py+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py@@ -471,8 +471,9 @@ fiverify_public = workflow.index("- name: Verify the release and every staged asset are public", publish)+ bake_job = workflow.index(" advance-installer-version:", verify_public)app_token = workflow.index(- "- name: Generate post-publication GitHub App token", verify_public+ "- name: Generate post-publication GitHub App token", bake_job)advance = workflow.index("- name: Advance public installer version on main", app_token@@ -484,7 +485,8 @@ fiself.assertLess(staged_shell, staged_powershell)self.assertLess(staged_powershell, publish)self.assertLess(publish, verify_public)- self.assertLess(verify_public, app_token)+ self.assertLess(verify_public, bake_job)+ self.assertLess(bake_job, app_token)self.assertLess(app_token, advance)self.assertIn("ref: ${{ github.workflow_sha }}", workflow)self.assertIn("path: release-control", workflow)@@ -847,7 +849,8 @@ fiself.assertIn("[build-linux, build-windows, build-macos-universal, ""verify-windows-node-runtime, "- "verify-release-artifacts, verify-mcp-client-discovery, build-hyprland-plugin-source]",+ "verify-release-artifacts, verify-mcp-client-discovery, build-hyprland-plugin-source, "+ "verify-macos-release-signatures, verify-windows-release-signatures]",workflow,)diff --git a/.github/scripts/tests/test_update_cua_driver_installer_version.py b/.github/scripts/tests/test_update_cua_driver_installer_version.pyindex 47d7a39d1a..64ae14bed0 100644--- a/.github/scripts/tests/test_update_cua_driver_installer_version.py+++ b/.github/scripts/tests/test_update_cua_driver_installer_version.py@@ -6,6 +6,7 @@ from update_cua_driver_installer_version import (InstallerVersionError,POWERSHELL_VERSION,SHELL_VERSION,+ main,read_version,update_installer_versions,)@@ -108,3 +109,89 @@ def test_accepts_legacy_release_please_sentinels_for_tag_recovery(assert changed == (shell, powershell)assert "# x-release-please-version" in shell.read_text()assert "# x-release-please-version" in powershell.read_text()+++def write_withdrawn(tmp_path: Path, text: str) -> Path:+ path = tmp_path / "withdrawn-versions"+ path.write_text(text, encoding="utf-8")+ return path+++def test_refuses_to_bake_a_withdrawn_version(tmp_path: Path) -> None:+ shell, powershell, state = copy_installers(tmp_path)+ before = (shell.read_bytes(), powershell.read_bytes(), state.read_bytes())+ withdrawn = write_withdrawn(+ tmp_path, "# header\n999.998.997 # macOS app published unsigned\n"+ )++ with pytest.raises(+ InstallerVersionError,+ match="refusing to bake withdrawn release 999.998.997.*published unsigned",+ ):+ update_installer_versions(+ shell,+ powershell,+ "999.998.997",+ state_path=state,+ withdrawn_path=withdrawn,+ allow_newer=True,+ )++ assert (shell.read_bytes(), powershell.read_bytes(), state.read_bytes()) == before+++def test_bakes_a_version_that_is_not_withdrawn(tmp_path: Path) -> None:+ shell, powershell, state = copy_installers(tmp_path)+ withdrawn = write_withdrawn(tmp_path, "999.998.996 # withdrawn\n")++ changed = update_installer_versions(+ shell, powershell, "999.998.997", state_path=state, withdrawn_path=withdrawn+ )++ assert changed == (shell, powershell, state)+++def test_missing_or_malformed_withdrawn_list_fails_closed(tmp_path: Path) -> None:+ shell, powershell, state = copy_installers(tmp_path)++ with pytest.raises(InstallerVersionError, match="does not exist"):+ update_installer_versions(+ shell,+ powershell,+ "999.998.997",+ state_path=state,+ withdrawn_path=tmp_path / "absent",+ )+ with pytest.raises(InstallerVersionError, match="invalid"):+ update_installer_versions(+ shell,+ powershell,+ "999.998.997",+ state_path=state,+ withdrawn_path=write_withdrawn(tmp_path, "latest # not a version\n"),+ )+++def test_cli_refuses_the_checked_in_withdrawn_release(tmp_path: Path, capsys) -> None:+ shell, powershell, state = copy_installers(tmp_path)+ withdrawn = REPO_ROOT / ".github/release-state/cua-driver-rs-withdrawn-versions"++ with pytest.raises(SystemExit) as exit_info:+ main(+ [+ "--version",+ "0.28.3",+ "--shell-path",+ str(shell),+ "--powershell-path",+ str(powershell),+ "--state-path",+ str(state),+ "--withdrawn-path",+ str(withdrawn),+ "--allow-newer",+ ]+ )++ assert exit_info.value.code == 2+ assert "refusing to bake withdrawn release 0.28.3" in capsys.readouterr().errdiff --git a/.github/scripts/tests/test_validate_release_versions.py b/.github/scripts/tests/test_validate_release_versions.pyindex e963a5c3a7..995fab7471 100644--- a/.github/scripts/tests/test_validate_release_versions.py+++ b/.github/scripts/tests/test_validate_release_versions.py@@ -5,7 +5,13 @@ import shutilimport pytest-from validate_release_versions import VersionError, main, validate+from validate_release_versions import (+ VersionError,+ driver_installer_withdrawn_versions,+ driver_withdrawn_versions,+ main,+ validate,+)REPO_ROOT = Path(__file__).resolve().parents[3]@@ -20,9 +26,8 @@ def copy_release_sources(destination: Path) -> None:relative = Path("libs/python/cua-sandbox") / filename(destination / relative).parent.mkdir(parents=True, exist_ok=True)shutil.copy(REPO_ROOT / relative, destination / relative)- release_state = ".github/release-state/cua-driver-rs-published-version"- (destination / release_state).parent.mkdir(parents=True, exist_ok=True)- shutil.copy(REPO_ROOT / release_state, destination / release_state)+ release_state = ".github/release-state"+ shutil.copytree(REPO_ROOT / release_state, destination / release_state)for relative in ("libs/cua-driver", "libs/lume"):source = REPO_ROOT / relativetarget = destination / relative@@ -207,3 +212,56 @@ def test_checked_in_withdrawn_versions_are_exact_and_explained():version, _, reason = line.partition("#")assert re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version.strip())assert reason.strip(), f"withdrawn {version.strip()} needs a reason"+++def test_installer_withdrawn_lists_mirror_release_state():+ listed = sorted(driver_withdrawn_versions(REPO_ROOT))+ baked = driver_installer_withdrawn_versions(REPO_ROOT)+ assert "0.28.3" in listed+ assert baked == {+ "scripts/_install-rust.sh": listed,+ "scripts/install.ps1": listed,+ }+++ ("relative", "old", "new"),+ [+ (+ "libs/cua-driver/scripts/_install-rust.sh",+ 'CUA_DRIVER_RS_WITHDRAWN_VERSIONS="0.28.3"',+ 'CUA_DRIVER_RS_WITHDRAWN_VERSIONS=""',+ ),+ (+ "libs/cua-driver/scripts/install.ps1",+ "$Script:CuaDriverRsWithdrawnVersions = @('0.28.3')",+ "$Script:CuaDriverRsWithdrawnVersions = @('0.28.3', '0.28.1')",+ ),+ ],+)+def test_installer_withdrawn_list_drift_fails(tmp_path: Path, relative: str, old: str, new: str):+ copy_release_sources(tmp_path)+ path = tmp_path / relative+ source = path.read_text(encoding="utf-8-sig")+ assert old in source+ path.write_text(source.replace(old, new), encoding="utf-8")+ with pytest.raises(VersionError, match="withdraws"):+ validate(tmp_path, "driver")+++def test_release_state_withdrawal_without_installer_update_fails(tmp_path: Path):+ copy_release_sources(tmp_path)+ withdrawn = tmp_path / ".github/release-state/cua-driver-rs-withdrawn-versions"+ withdrawn.write_text(+ withdrawn.read_text(encoding="utf-8") + "0.1.0 # test withdrawal\n", encoding="utf-8"+ )+ with pytest.raises(VersionError, match=r"withdraws \['0.28.3'\], but"):+ validate(tmp_path, "driver")+++def test_malformed_withdrawn_version_fails(tmp_path: Path):+ copy_release_sources(tmp_path)+ withdrawn = tmp_path / ".github/release-state/cua-driver-rs-withdrawn-versions"+ withdrawn.write_text("v0.28.3 # prefixed\n", encoding="utf-8")+ with pytest.raises(VersionError, match="exact stable"):+ validate(tmp_path, "driver")diff --git a/.github/scripts/tests/test_verify_cua_driver_release_signatures.py b/.github/scripts/tests/test_verify_cua_driver_release_signatures.pynew file mode 100644index 0000000000..6a836faf54--- /dev/null+++ b/.github/scripts/tests/test_verify_cua_driver_release_signatures.py@@ -0,0 +1,313 @@+"""Contract tests for the Cua Driver release signature gate.++The fake tool runner below reproduces the real outputs of codesign, spctl,+stapler, and Get-AuthenticodeSignature observed on the published 0.28.2+(notarized) and 0.28.3 (unsigned CuaDriver.app, #4109) archives.+"""++from __future__ import annotations++import io+import json+from pathlib import Path+import subprocess+import tarfile+import zipfile++import pytest++import verify_cua_driver_release_signatures as gate+from verify_cua_driver_release_signatures import CommandResult, main, verify_macos, verify_windows+++VERSION = "1.2.3"+TEAM = "YCK386LBJ7"+SIGNED_DETAILS = f"""Executable=/x+Identifier=com.trycua.driver+CodeDirectory v=20500 size=62557 flags=0x10000(runtime) hashes=1944+7 location=embedded+Authority=Developer ID Application: Cua AI, Inc. ({TEAM})+Authority=Developer ID Certification Authority+Authority=Apple Root CA+TeamIdentifier={TEAM}+"""+ADHOC_DETAILS = """Identifier=cua_driver-98a9f20745f8bdbc+CodeDirectory v=20400 size=264984 flags=0x20002(adhoc,linker-signed) hashes=8277+0 location=embedded+TeamIdentifier=not set+"""+ACCEPTED = f"""x: accepted+source=Notarized Developer ID+origin=Developer ID Application: Cua AI, Inc. ({TEAM})+"""+++def _add(tar: tarfile.TarFile, name: str, data: bytes = b"\xcf\xfa\xed\xfe") -> None:+ info = tarfile.TarInfo(name)+ info.size = len(data)+ info.mode = 0o755+ tar.addfile(info, io.BytesIO(data))+++def make_darwin_artifacts(root: Path, version: str = VERSION, *, omit: str = "") -> Path:+ root.mkdir(parents=True, exist_ok=True)+ for label in ("darwin-arm64", "darwin-x86_64", "darwin-universal"):+ stage = f"cua-driver-rs-{version}-{label}"+ with tarfile.open(root / f"{stage}.tar.gz", "w:gz") as tar:+ for name in ("cua-driver", "cua-cursor-theme", "libcua_driver_sdk.dylib"):+ if name != omit:+ _add(tar, f"{stage}/{name}")+ _add(tar, f"{stage}/cua_driver_node_runtime.node")+ if omit != "CuaDriver.app":+ _add(tar, f"{stage}/CuaDriver.app/Contents/Info.plist", b"<plist/>")+ _add(tar, f"{stage}/CuaDriver.app/Contents/MacOS/cua-driver")+ _add(tar, f"{stage}/CuaDriver.app/Contents/MacOS/cua-cursor-theme")+ with tarfile.open(root / f"cua-driver-rs-{version}-darwin-universal-binary.tar.gz", "w:gz") as tar:+ for name in ("cua-driver", "cua-cursor-theme", "libcua_driver_sdk.dylib"):+ _add(tar, name)+ return root+++class FakeMacTools:+ """codesign/spctl/stapler outputs for a signed, ad hoc, or partially valid release."""++ def __init__(+ self,+ *,+ signed: bool = True,+ notarized: bool = True,+ stapled: bool = True,+ adhoc_names: tuple[str, ...] = (),+ team: str = TEAM,+ ) -> None:+ self.signed = signed+ self.notarized = notarized+ self.stapled = stapled+ self.adhoc_names = adhoc_names+ self.team = team+ self.calls: list[list[str]] = []++ def __call__(self, argv) -> CommandResult:+ argv = list(argv)+ self.calls.append(argv)+ tool, target = argv[0], Path(argv[-1])+ if tool == "tar":+ with tarfile.open(argv[2]) as tar:+ tar.extractall(argv[4])+ return CommandResult(0, "")+ adhoc = not self.signed or target.name in self.adhoc_names+ if tool == "codesign" and "--verify" in argv:+ if not self.signed:+ return CommandResult(1, f"{target}: code object is not signed at all")+ return CommandResult(0, f"{target}: valid on disk")+ if tool == "codesign":+ details = ADHOC_DETAILS if adhoc else SIGNED_DETAILS.replace(TEAM, self.team)+ return CommandResult(0, details)+ if tool == "spctl":+ if not self.notarized:+ return CommandResult(3, f"{target}: rejected\nsource=Unnotarized Developer ID\n")+ return CommandResult(0, ACCEPTED.replace(TEAM, self.team))+ if argv[:3] == ["xcrun", "stapler", "validate"]:+ if not self.stapled:+ return CommandResult(65, f"{target.name} does not have a ticket stapled to it.")+ return CommandResult(0, "The validate action worked!")+ raise AssertionError(f"unexpected command {argv}")+++def test_notarized_release_passes(tmp_path: Path) -> None:+ tools = FakeMacTools()+ report = verify_macos(make_darwin_artifacts(tmp_path / "a"), VERSION, run=tools)++ assert report.failures == []+ spctl = [call for call in tools.calls if call[0] == "spctl"]+ assert len(spctl) == 3+ assert all(call[:5] == ["spctl", "-a", "-vvv", "-t", "exec"] for call in spctl)+ deep = [call for call in tools.calls if "--deep" in call]+ assert all(Path(call[-1]).name == "CuaDriver.app" for call in deep) and len(deep) == 3+ # Every archive's standalone Mach-O copies are checked too.+ verified = {Path(call[-1]).name for call in tools.calls if "--verify" in call}+ assert {"cua-driver", "cua-cursor-theme", "libcua_driver_sdk.dylib"} <= verified+ assert "cua_driver_node_runtime.node" not in verified+++def test_unsigned_release_like_0_28_3_fails(tmp_path: Path) -> None:+ report = verify_macos(+ make_darwin_artifacts(tmp_path / "a"), VERSION, run=FakeMacTools(signed=False)+ )++ assert any(+ "darwin-universal.tar.gz:CuaDriver.app: codesign --verify failed" in failure+ and "not signed at all" in failure+ for failure in report.failures+ )+ assert any("darwin-universal-binary.tar.gz:cua-driver" in f for f in report.failures)+++ ("tools", "message"),+ [+ (FakeMacTools(notarized=False), "Gatekeeper source is not 'Notarized Developer ID'"),+ (FakeMacTools(stapled=False), "no valid stapled notarization ticket"),+ (FakeMacTools(team="ZZZZZZZZZZ"), "team identifier is not YCK386LBJ7"),+ (FakeMacTools(adhoc_names=("CuaDriver.app",)), "signature is ad hoc"),+ (FakeMacTools(adhoc_names=("libcua_driver_sdk.dylib",)), "hardened runtime is not enabled"),+ ],+)+def test_each_macos_signature_requirement_is_enforced(+ tmp_path: Path, tools: FakeMacTools, message: str+) -> None:+ report = verify_macos(make_darwin_artifacts(tmp_path / "a"), VERSION, run=tools)+ assert any(message in failure for failure in report.failures), report.failures++[email protected]("omit", ["CuaDriver.app", "cua-driver", "libcua_driver_sdk.dylib"])+def test_missing_bundle_or_binary_fails(tmp_path: Path, omit: str) -> None:+ report = verify_macos(+ make_darwin_artifacts(tmp_path / "a", omit=omit), VERSION, run=FakeMacTools()+ )+ assert any(f": {omit} is missing" in failure or f"{omit} is missing" in failure for failure in report.failures)+++def test_missing_darwin_archive_fails(tmp_path: Path) -> None:+ root = make_darwin_artifacts(tmp_path / "a")+ (root / f"cua-driver-rs-{VERSION}-darwin-x86_64.tar.gz").unlink()+ report = verify_macos(root, VERSION, run=FakeMacTools())+ assert f"missing darwin archive cua-driver-rs-{VERSION}-darwin-x86_64.tar.gz" in report.failures+++def test_pkg_and_dmg_assets_must_be_notarized(tmp_path: Path) -> None:+ root = make_darwin_artifacts(tmp_path / "a")+ (root / "CuaDriver.pkg").write_bytes(b"pkg")+ (root / "CuaDriver.dmg").write_bytes(b"dmg")+ tools = FakeMacTools()+ assert verify_macos(root, VERSION, run=tools).failures == []+ assessments = [call[4] for call in tools.calls if call[0] == "spctl"]+ assert assessments.count("install") == 1 and assessments.count("open") == 1++ report = verify_macos(root, VERSION, run=FakeMacTools(notarized=False))+ assert any(f.startswith("CuaDriver.pkg:") for f in report.failures)+ assert any(f.startswith("CuaDriver.dmg:") for f in report.failures)+++def make_windows_artifacts(root: Path, version: str = VERSION) -> Path:+ for arch in ("x86_64", "arm64"):+ stage = f"cua-driver-rs-{version}-windows-{arch}"+ folder = root / f"cua-driver-rs-windows-{arch}"+ folder.mkdir(parents=True, exist_ok=True)+ names = ("cua-driver.exe", "cua-cursor-theme.exe", "cua-driver-uia.exe", "cua_driver_sdk.dll", "cua_driver_node_runtime.node")+ with zipfile.ZipFile(folder / f"{stage}.zip", "w") as bundle:+ for name in names:+ bundle.writestr(f"{stage}/{name}", b"MZ")+ bundle.writestr(f"{stage}/LICENSE", b"license")+ with zipfile.ZipFile(folder / f"{stage}-binary.zip", "w") as bundle:+ for name in names:+ bundle.writestr(name, b"MZ")+ return root+++class FakeAuthenticode:+ def __init__(self, overrides: dict[str, dict] | None = None) -> None:+ self.overrides = overrides or {}+ self.paths: list[str] = []++ def __call__(self, argv) -> CommandResult:+ argv = list(argv)+ assert Path(argv[-2]).name == "authenticode.ps1"+ assert "Get-AuthenticodeSignature -LiteralPath" in Path(argv[-2]).read_text()+ self.paths = Path(argv[-1]).read_text().split()+ rows = []+ for path in self.paths:+ row = {+ "Path": path,+ "Status": "Valid",+ "StatusMessage": "Signature verified.",+ "Subject": "CN=\"Cua AI, Inc.\", O=\"Cua AI, Inc.\", L=San Francisco, C=US",+ "Timestamped": True,+ }+ row.update(self.overrides.get(Path(path).name, {}))+ rows.append(row)+ return CommandResult(0, json.dumps(rows))+++def test_signed_windows_release_passes(tmp_path: Path) -> None:+ tools = FakeAuthenticode()+ report = verify_windows(make_windows_artifacts(tmp_path / "a"), VERSION, run=tools)+ assert report.failures == []+ assert len(tools.paths) == 20+ assert all(Path(path).suffix in {".exe", ".dll", ".node"} for path in tools.paths)+++ ("override", "message"),+ [+ ({"Status": "NotSigned", "StatusMessage": "The file is not signed."}, "status NotSigned"),+ ({"Status": "HashMismatch"}, "status HashMismatch"),+ ({"Subject": "CN=Someone Else"}, "unexpected signer CN=Someone Else"),+ ({"Timestamped": False}, "not timestamped"),+ ],+)+def test_each_windows_signature_requirement_is_enforced(+ tmp_path: Path, override: dict, message: str+) -> None:+ tools = FakeAuthenticode({"cua_driver_sdk.dll": override})+ report = verify_windows(make_windows_artifacts(tmp_path / "a"), VERSION, run=tools)+ assert len(report.failures) == 4+ assert all("cua_driver_sdk.dll" in f and message in f for f in report.failures)+++def test_missing_windows_archive_fails(tmp_path: Path) -> None:+ root = make_windows_artifacts(tmp_path / "a")+ (root / "cua-driver-rs-windows-arm64" / f"cua-driver-rs-{VERSION}-windows-arm64-binary.zip").unlink()+ report = verify_windows(root, VERSION, run=FakeAuthenticode())+ assert report.failures == [f"missing Windows archive cua-driver-rs-{VERSION}-windows-arm64-binary.zip"]+++def test_powershell_failure_fails_closed(tmp_path: Path) -> None:+ report = verify_windows(+ make_windows_artifacts(tmp_path / "a"),+ VERSION,+ run=lambda argv: CommandResult(1, "Get-AuthenticodeSignature is not available"),+ )+ assert report.failures and "Get-AuthenticodeSignature failed" in report.failures[0]+++def test_cli_exit_status_and_annotations(tmp_path: Path, monkeypatch, capsys) -> None:+ root = make_darwin_artifacts(tmp_path / "a")+ monkeypatch.setattr(gate, "run_command", FakeMacTools())+ assert main(["macos", "--artifacts", str(root), "--version", VERSION]) == 0+ monkeypatch.setattr(gate, "run_command", FakeMacTools(signed=False))+ assert main(["macos", "--artifacts", str(root), "--version", VERSION]) == 1+ err = capsys.readouterr().err+ assert "::error title=Cua Driver release signature::" in err+ assert "must not be published or installed" in err+ assert main(["macos", "--artifacts", str(root), "--version", VERSION, "--no-annotations"]) == 1+ err = capsys.readouterr().err+ assert "::error" not in err+ assert "must not be published or installed" in err+++def test_cli_fails_when_no_archive_matches(tmp_path: Path) -> None:+ (tmp_path / "empty").mkdir()+ assert main(["windows", "--artifacts", str(tmp_path / "empty"), "--version", VERSION]) == 1+++REPO_ROOT = Path(__file__).resolve().parents[3]+EXPECT = REPO_ROOT / ".github/scripts/expect_verification_result.sh"+++ ("expect", "status", "exit_code", "text"),+ [+ ("pass", "0", 0, "passed as required"),+ ("pass", "1", 1, "publication and installer baking are blocked"),+ ("fail", "1", 0, "rejected as expected"),+ ("fail", "0", 1, "cannot detect a broken release"),+ ("maybe", "0", 2, "unknown expected outcome"),+ ],+)+def test_expected_outcome_helper(expect: str, status: str, exit_code: int, text: str) -> None:+ result = subprocess.run(+ ["bash", str(EXPECT), expect, status, "macOS signatures"],+ capture_output=True,+ text=True,+ )+ assert result.returncode == exit_code+ assert text in result.stdoutdiff --git a/.github/scripts/update_cua_driver_installer_version.py b/.github/scripts/update_cua_driver_installer_version.pyindex 94ba4804f2..5536cea8ca 100644--- a/.github/scripts/update_cua_driver_installer_version.py+++ b/.github/scripts/update_cua_driver_installer_version.py@@ -8,6 +8,8 @@ from pathlib import Pathimport refrom typing import Sequence+from validate_release_versions import VersionError, read_withdrawn_versions+class InstallerVersionError(RuntimeError):"""Raised when installer version state cannot be updated safely."""@@ -73,9 +75,22 @@ def update_installer_versions(version: str,*,state_path: Path | None = None,+ withdrawn_path: Path | None = None,allow_newer: bool = False,) -> tuple[Path, ...]:requested = version_tuple(version)+ if withdrawn_path is not None:+ if not withdrawn_path.is_file():+ raise InstallerVersionError(f"withdrawn-versions file {withdrawn_path} does not exist")+ try:+ withdrawn = read_withdrawn_versions(withdrawn_path)+ except VersionError as error:+ raise InstallerVersionError(f"invalid {withdrawn_path}: {error}") from error+ if version in withdrawn:+ raise InstallerVersionError(+ f"refusing to bake withdrawn release {version} into the installers: "+ f"{withdrawn[version]}"+ )current = {shell_path: read_version(shell_path, SHELL_VERSION),powershell_path: read_version(powershell_path, POWERSHELL_VERSION),@@ -119,6 +134,11 @@ def main(argv: Sequence[str] | None = None) -> int:type=Path,help="published-version state file to update with the public installers",)+ parser.add_argument(+ "--withdrawn-path",+ type=Path,+ help="withdrawn-versions file; refuse to bake any version it lists",+ )parser.add_argument("--allow-newer",action="store_true",@@ -132,6 +152,7 @@ def main(argv: Sequence[str] | None = None) -> int:args.powershell_path,args.version,state_path=args.state_path,+ withdrawn_path=args.withdrawn_path,allow_newer=args.allow_newer,)except (InstallerVersionError, OSError) as error:diff --git a/.github/scripts/validate_release_versions.py b/.github/scripts/validate_release_versions.pyindex c6dc6b049d..78f499a7cf 100644--- a/.github/scripts/validate_release_versions.py+++ b/.github/scripts/validate_release_versions.py@@ -59,9 +59,46 @@ def driver_installer_versions(root: Path) -> dict[str, str]:}+WITHDRAWN_VERSIONS_PATH = ".github/release-state/cua-driver-rs-withdrawn-versions"+# The installers run from `curl | bash` and `irm | iex` and cannot read repo+# files, so each carries a baked copy of the withdrawn list that must mirror+# WITHDRAWN_VERSIONS_PATH exactly.+SHELL_WITHDRAWN_VERSIONS = re.compile(+ r'^CUA_DRIVER_RS_WITHDRAWN_VERSIONS="([^"]*)" # withdrawn-installer-versions$',+ re.MULTILINE,+)+POWERSHELL_WITHDRAWN_VERSIONS = re.compile(+ r"^\$Script:CuaDriverRsWithdrawnVersions\s*=\s*@\(([^)]*)\) # withdrawn-installer-versions$",+ re.MULTILINE,+)++def driver_withdrawn_versions(root: Path) -> dict[str, str]:"""Releases that must never be installed, baked, or certified."""- path = root / ".github/release-state/cua-driver-rs-withdrawn-versions"+ return read_withdrawn_versions(root / WITHDRAWN_VERSIONS_PATH)+++def _single_match(path: Path, pattern: re.Pattern[str]) -> str:+ matches = list(pattern.finditer(path.read_text(encoding="utf-8-sig")))+ if len(matches) != 1:+ raise VersionError(+ f"expected exactly one withdrawn-versions sentinel in {path}, found {len(matches)}"+ )+ return matches[0].group(1)+++def driver_installer_withdrawn_versions(root: Path) -> dict[str, list[str]]:+ """Withdrawn lists baked into each installer."""+ base = root / "libs/cua-driver/scripts"+ shell = _single_match(base / "_install-rust.sh", SHELL_WITHDRAWN_VERSIONS).split()+ powershell = re.findall(+ r"'([^']*)'", _single_match(base / "install.ps1", POWERSHELL_WITHDRAWN_VERSIONS)+ )+ return {"scripts/_install-rust.sh": shell, "scripts/install.ps1": powershell}+++def read_withdrawn_versions(path: Path) -> dict[str, str]:+ """Parse a withdrawn-versions file: one ``x.y.z # reason`` entry per line."""if not path.exists():return {}withdrawn: dict[str, str] = {}@@ -200,6 +237,15 @@ def validate(root: Path, product: str) -> None:f"Cua Driver baked installers advertise withdrawn release {installer_version}: "f"{withdrawn[installer_version]}")+ expected_withdrawn = sorted(withdrawn, key=stable_version_tuple)+ for name, baked in driver_installer_withdrawn_versions(root).items():+ for version in baked:+ stable_version_tuple(version)+ if sorted(baked, key=stable_version_tuple) != expected_withdrawn:+ raise VersionError(+ f"Cua Driver {name} withdraws {baked or 'nothing'}, but "+ f"{WITHDRAWN_VERSIONS_PATH} withdraws {expected_withdrawn or 'nothing'}"+ )if stable_version_tuple(installer_version) > stable_version_tuple(expected):raise VersionError(f"Cua Driver baked installers advertise {installer_version}, "diff --git a/.github/scripts/verify_cua_driver_release_signatures.py b/.github/scripts/verify_cua_driver_release_signatures.pynew file mode 100644index 0000000000..2b69ce041c--- /dev/null+++ b/.github/scripts/verify_cua_driver_release_signatures.py@@ -0,0 +1,379 @@+#!/usr/bin/env python3+"""Verify that Cua Driver release archives are signed before and after publication.++The installer refuses a macOS app that fails ``codesign --verify``. A release+whose archive ships an unsigned or unnotarized app therefore breaks every fresh+macOS install (see #4109). This verifier runs the checks the operating systems+run, on the exact archives that a release uploads or has uploaded:++macOS (``macos``, run on a macOS runner)+ Every ``CuaDriver.app`` inside a darwin directory archive must pass+ ``codesign --verify --deep --strict``, carry a hardened-runtime Developer ID+ signature from the pinned team, be accepted by ``spctl -a -t exec`` with+ source ``Notarized Developer ID``, and have a stapled notarization ticket+ (``xcrun stapler validate``). The standalone ``cua-driver``,+ ``cua-cursor-theme``, and ``libcua_driver_sdk.dylib`` copies must carry the+ same team's hardened-runtime signature. Any ``.pkg`` or ``.dmg`` asset must+ be notarized and stapled too.++Windows (``windows``, run on a Windows runner)+ Every PE file (``.exe``, ``.dll``, ``.node``) inside a Windows archive must+ have a ``Valid`` timestamped Authenticode signature whose signer is the+ expected organization.++The command exits non-zero with every failure listed when any check fails.+"""++from __future__ import annotations++import argparse+import json+from dataclasses import dataclass, field+from pathlib import Path+import re+import shutil+import subprocess+import sys+import tempfile+import zipfile+from typing import Callable, Sequence+++RELEASE_TEAM_ID = "YCK386LBJ7"+RELEASE_SIGNER = "Cua AI, Inc."+DARWIN_LABELS = ("darwin-arm64", "darwin-x86_64", "darwin-universal")+WINDOWS_ARCHES = ("x86_64", "arm64")+# Mach-O files that the release pipeline signs with the Developer ID identity.+# cua_driver_node_runtime.node is loaded by Node and is not Developer ID signed+# by the current pipeline, so it is intentionally not listed here.+SIGNED_MACHO_FILES = ("cua-driver", "cua-cursor-theme", "libcua_driver_sdk.dylib")+APP_EXECUTABLES = ("Contents/MacOS/cua-driver", "Contents/MacOS/cua-cursor-theme")+PE_SUFFIXES = (".exe", ".dll", ".node")+++@dataclass+class CommandResult:+ returncode: int+ output: str+++Runner = Callable[[Sequence[str]], CommandResult]+++def run_command(argv: Sequence[str]) -> CommandResult:+ completed = subprocess.run(+ list(argv),+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ check=False,+ )+ return CommandResult(completed.returncode, completed.stdout)+++@dataclass+class Report:+ checked: list[str] = field(default_factory=list)+ failures: list[str] = field(default_factory=list)++ def ok(self, message: str) -> None:+ self.checked.append(message)+ print(f"ok: {message}")++ def fail(self, message: str) -> None:+ self.failures.append(message)+ print(f"FAIL: {message}")+++def _indent(output: str) -> str:+ return "\n".join(f" {line}" for line in output.strip().splitlines())+++def _team_pattern(team_id: str) -> re.Pattern[str]:+ return re.compile(+ rf"^origin=Developer ID Application: .+ \({re.escape(team_id)}\)$",+ re.MULTILINE,+ )+++def check_developer_id_signature(+ path: Path, label: str, team_id: str, run: Runner, report: Report, *, deep: bool+) -> bool:+ """codesign --verify plus identity details shared by apps and bare Mach-O."""+ verify = ["codesign", "--verify", "--strict", "--verbose=2"]+ if deep:+ verify.insert(2, "--deep")+ result = run([*verify, str(path)])+ if result.returncode != 0:+ report.fail(f"{label}: codesign --verify failed\n{_indent(result.output)}")+ return False++ details = run(["codesign", "-dvv", str(path)])+ problems = []+ if details.returncode != 0:+ problems.append("codesign -dvv failed")+ if not re.search(rf"^TeamIdentifier={re.escape(team_id)}$", details.output, re.MULTILINE):+ problems.append(f"team identifier is not {team_id}")+ if not re.search(+ rf"^Authority=Developer ID Application: .+ \({re.escape(team_id)}\)$",+ details.output,+ re.MULTILINE,+ ):+ problems.append("leaf authority is not a Developer ID Application certificate")+ if not re.search(r"^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*\bruntime\b", details.output, re.MULTILINE):+ problems.append("hardened runtime is not enabled")+ if re.search(r"^CodeDirectory .*\badhoc\b", details.output, re.MULTILINE):+ problems.append("signature is ad hoc")+ if problems:+ report.fail(f"{label}: " + "; ".join(problems) + f"\n{_indent(details.output)}")+ return False+ report.ok(f"{label}: Developer ID signature from {team_id}")+ return True+++def check_notarized(+ path: Path, label: str, team_id: str, run: Runner, report: Report, *, assessment: str+) -> None:+ """Gatekeeper acceptance as a notarized Developer ID item plus a stapled ticket."""+ argv = ["spctl", "-a", "-vvv", "-t", assessment]+ if assessment == "open":+ argv += ["--context", "context:primary-signature"]+ result = run([*argv, str(path)])+ problems = []+ if result.returncode != 0 or not re.search(r": accepted$", result.output, re.MULTILINE):+ problems.append(f"spctl -t {assessment} did not accept it")+ if not re.search(r"^source=Notarized Developer ID$", result.output, re.MULTILINE):+ problems.append("Gatekeeper source is not 'Notarized Developer ID'")+ if not _team_pattern(team_id).search(result.output):+ problems.append(f"Gatekeeper origin is not the {team_id} Developer ID")+ if problems:+ report.fail(f"{label}: " + "; ".join(problems) + f"\n{_indent(result.output)}")+ else:+ report.ok(f"{label}: Gatekeeper accepts it as Notarized Developer ID ({team_id})")++ stapled = run(["xcrun", "stapler", "validate", str(path)])+ if stapled.returncode != 0:+ report.fail(f"{label}: no valid stapled notarization ticket\n{_indent(stapled.output)}")+ else:+ report.ok(f"{label}: stapled notarization ticket is valid")+++def _extract_tar(archive: Path, destination: Path, run: Runner) -> bool:+ # System tar matches what the installer runs and preserves bundle metadata.+ result = run(["tar", "-xzf", str(archive), "-C", str(destination)])+ return result.returncode == 0+++def verify_macos(+ artifacts: Path,+ version: str,+ team_id: str = RELEASE_TEAM_ID,+ *,+ run: Runner | None = None,+ workdir: Path | None = None,+) -> Report:+ run = run or run_command+ report = Report()+ archives = sorted(artifacts.rglob(f"cua-driver-rs-{version}-darwin-*.tar.gz"))+ by_name = {archive.name: archive for archive in archives}+ expected = [f"cua-driver-rs-{version}-{label}.tar.gz" for label in DARWIN_LABELS]+ expected.append(f"cua-driver-rs-{version}-darwin-universal-binary.tar.gz")+ for name in expected:+ if name not in by_name:+ report.fail(f"missing darwin archive {name}")++ scratch = Path(tempfile.mkdtemp(prefix="cua-driver-signatures-", dir=workdir))+ try:+ for name in expected:+ archive = by_name.get(name)+ if archive is None:+ continue+ destination = scratch / name.removesuffix(".tar.gz")+ destination.mkdir(parents=True)+ if not _extract_tar(archive, destination, run):+ report.fail(f"{name}: could not be extracted")+ continue+ if name.endswith("-binary.tar.gz"):+ root = destination+ else:+ root = destination / name.removesuffix(".tar.gz")+ app = root / "CuaDriver.app"+ if not app.is_dir():+ report.fail(f"{name}: CuaDriver.app is missing")+ else:+ label = f"{name}:CuaDriver.app"+ if check_developer_id_signature(+ app, label, team_id, run, report, deep=True+ ):+ check_notarized(app, label, team_id, run, report, assessment="exec")+ for executable in APP_EXECUTABLES:+ inner = app / executable+ if inner.is_file():+ check_developer_id_signature(+ inner, f"{label}/{executable}", team_id, run, report, deep=False+ )+ else:+ report.fail(f"{label}: {executable} is missing")+ for file_name in SIGNED_MACHO_FILES:+ target = root / file_name+ if not target.is_file():+ report.fail(f"{name}: {file_name} is missing")+ continue+ check_developer_id_signature(+ target, f"{name}:{file_name}", team_id, run, report, deep=False+ )+ finally:+ shutil.rmtree(scratch, ignore_errors=True)++ for installer in sorted(artifacts.rglob("*.pkg")):+ check_notarized(installer, installer.name, team_id, run, report, assessment="install")+ for image in sorted(artifacts.rglob("*.dmg")):+ check_notarized(image, image.name, team_id, run, report, assessment="open")+ return report+++POWERSHELL_AUTHENTICODE = r"""+$ErrorActionPreference = 'Stop'+$paths = Get-Content -LiteralPath $args[0] | Where-Object { $_ }+$rows = foreach ($path in $paths) {+ $signature = Get-AuthenticodeSignature -LiteralPath $path+ [pscustomobject]@{+ Path = $path+ Status = $signature.Status.ToString()+ StatusMessage = $signature.StatusMessage+ Subject = if ($signature.SignerCertificate) { $signature.SignerCertificate.Subject } else { '' }+ Timestamped = [bool]$signature.TimeStamperCertificate+ }+}+ConvertTo-Json -InputObject @($rows) -Depth 3+"""+++def authenticode_signatures(paths: Sequence[Path], run: Runner, scratch: Path) -> list[dict]:+ listing = scratch / "authenticode-paths.txt"+ listing.write_text("\n".join(str(path) for path in paths) + "\n", encoding="utf-8")+ script = scratch / "authenticode.ps1"+ script.write_text(POWERSHELL_AUTHENTICODE, encoding="utf-8")+ shell = shutil.which("pwsh") or shutil.which("powershell") or "pwsh"+ result = run([shell, "-NoProfile", "-NonInteractive", "-File", str(script), str(listing)])+ if result.returncode != 0:+ raise RuntimeError(f"Get-AuthenticodeSignature failed:\n{_indent(result.output)}")+ return json.loads(result.output)+++def verify_windows(+ artifacts: Path,+ version: str,+ signer: str = RELEASE_SIGNER,+ *,+ run: Runner | None = None,+ workdir: Path | None = None,+) -> Report:+ run = run or run_command+ report = Report()+ expected = []+ for arch in WINDOWS_ARCHES:+ expected += [+ f"cua-driver-rs-{version}-windows-{arch}.zip",+ f"cua-driver-rs-{version}-windows-{arch}-binary.zip",+ ]+ by_name = {+ archive.name: archive+ for archive in artifacts.rglob(f"cua-driver-rs-{version}-windows-*.zip")+ }+ subject = re.compile(rf"(^|,\s*)CN=\"?{re.escape(signer)}\"?(,|$)")++ scratch = Path(tempfile.mkdtemp(prefix="cua-driver-authenticode-", dir=workdir))+ try:+ pe_files: list[tuple[str, Path]] = []+ for name in expected:+ archive = by_name.get(name)+ if archive is None:+ report.fail(f"missing Windows archive {name}")+ continue+ destination = scratch / name.removesuffix(".zip")+ with zipfile.ZipFile(archive) as bundle:+ bundle.extractall(destination)+ found = sorted(+ path for path in destination.rglob("*")+ if path.is_file() and path.suffix.lower() in PE_SUFFIXES+ )+ if not any(path.name.lower() == "cua-driver.exe" for path in found):+ report.fail(f"{name}: cua-driver.exe is missing")+ pe_files += [(f"{name}:{path.relative_to(destination).as_posix()}", path) for path in found]++ if pe_files:+ try:+ rows = authenticode_signatures([path for _, path in pe_files], run, scratch)+ except (RuntimeError, json.JSONDecodeError) as error:+ report.fail(str(error))+ rows = []+ by_path = {str(row.get("Path")): row for row in rows}+ for label, path in pe_files:+ row = by_path.get(str(path))+ if row is None:+ if rows:+ report.fail(f"{label}: no Authenticode result")+ continue+ problems = []+ if row.get("Status") != "Valid":+ problems.append(f"status {row.get('Status')}: {row.get('StatusMessage')}")+ if not subject.search(str(row.get("Subject", ""))):+ problems.append(f"unexpected signer {row.get('Subject') or '<none>'}")+ if not row.get("Timestamped"):+ problems.append("signature is not timestamped")+ if problems:+ report.fail(f"{label}: " + "; ".join(problems))+ else:+ report.ok(f"{label}: valid timestamped Authenticode signature from {signer}")+ finally:+ shutil.rmtree(scratch, ignore_errors=True)+ return report+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])+ subcommands = parser.add_subparsers(dest="platform", required=True)+ macos = subcommands.add_parser("macos", help="verify darwin archives (run on macOS)")+ macos.add_argument("--team-id", default=RELEASE_TEAM_ID)+ windows = subcommands.add_parser("windows", help="verify Windows archives (run on Windows)")+ windows.add_argument("--signer", default=RELEASE_SIGNER)+ for command in (macos, windows):+ command.add_argument("--artifacts", type=Path, required=True)+ command.add_argument("--version", required=True)+ command.add_argument(+ "--no-annotations",+ action="store_true",+ help="omit GitHub error annotations (for negative controls that must fail)",+ )+ args = parser.parse_args(argv)++ if not args.artifacts.is_dir():+ print(f"error: artifact directory {args.artifacts} does not exist", file=sys.stderr)+ return 2+ if args.platform == "macos":+ report = verify_macos(args.artifacts, args.version, args.team_id)+ else:+ report = verify_windows(args.artifacts, args.version, args.signer)++ if not report.checked and not report.failures:+ report.fail("no signature checks ran")+ if report.failures:+ print(+ f"\n{len(report.failures)} signature check(s) failed for Cua Driver "+ f"{args.version} ({args.platform}); this release must not be published or installed.",+ file=sys.stderr,+ )+ if not args.no_annotations:+ for failure in report.failures:+ print(+ f"::error title=Cua Driver release signature::{failure.splitlines()[0]}",+ file=sys.stderr,+ )+ return 1+ print(f"\nAll {len(report.checked)} {args.platform} signature checks passed for {args.version}.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.ymlindex 17a2d06839..a409b077e2 100644--- a/.github/workflows/cd-rust-cua-driver.yml+++ b/.github/workflows/cd-rust-cua-driver.yml@@ -88,7 +88,39 @@ jobs:release-attribution-preflight:name: release attribution preflightruns-on: ubuntu-latest+ outputs:+ version: ${{ steps.candidate.outputs.version }}steps:+ # Release safety (#4109): a run that can publish must produce notarized+ # macOS artifacts. 0.28.3 shipped an unsigned CuaDriver.app because a+ # publishing run disabled notarization, which broke every fresh macOS+ # install. Fail before any build instead of discovering it afterwards.+ - name: Refuse to publish without macOS notarization+ env:+ CAN_PUBLISH: ${{ (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/cua-driver-rs-v')) || (github.event_name == 'workflow_dispatch' && inputs.publish == true) }}+ DO_NOTARIZE: ${{ startsWith(github.ref, 'refs/tags/cua-driver-rs-v') || inputs.notarize == true }}+ run: |+ echo "can publish: ${CAN_PUBLISH}; notarize macOS: ${DO_NOTARIZE}"+ if [[ "$CAN_PUBLISH" == "true" && "$DO_NOTARIZE" != "true" ]]; then+ echo "::error title=Release safety::This run can publish a Cua Driver release, but macOS notarization is disabled. Publishing requires signed, notarized macOS artifacts (#4109)."+ exit 1+ fi++ - name: Resolve candidate version+ id: candidate+ env:+ CHANNEL: ${{ inputs.channel }}+ INPUT_VERSION: ${{ inputs.version }}+ run: |+ if [[ "$CHANNEL" == "nightly" ]]; then+ VERSION="$INPUT_VERSION"+ elif [[ "$GITHUB_REF" == refs/tags/cua-driver-rs-v* ]]; then+ VERSION="${GITHUB_REF#refs/tags/cua-driver-rs-v}"+ else+ VERSION="$INPUT_VERSION"+ fi+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"+- uses: actions/checkout@v4with:fetch-depth: 0@@ -546,6 +578,19 @@ jobs:DO_NOTARIZE: ${{ startsWith(github.ref, 'refs/tags/cua-driver-rs-v') || inputs.notarize == true }}KEYCHAIN_PASSWORD: temporary-cd-keychain-pwdsteps:+ - name: Assert notarization for publishable builds+ env:+ CAN_PUBLISH: ${{ (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/cua-driver-rs-v')) || (github.event_name == 'workflow_dispatch' && inputs.publish == true) }}+ run: |+ if [[ "$GITHUB_REF" == refs/tags/cua-driver-rs-v* && "$DO_NOTARIZE" != "true" ]]; then+ echo "::error title=Release safety::Tag builds must notarize the macOS artifacts."+ exit 1+ fi+ if [[ "$CAN_PUBLISH" == "true" && "$DO_NOTARIZE" != "true" ]]; then+ echo "::error title=Release safety::A publishable build must notarize the macOS artifacts (#4109)."+ exit 1+ fi+ echo "notarize macOS: ${DO_NOTARIZE}"- uses: actions/checkout@v4with:ref: ${{ inputs.source_ref || github.event_name == 'workflow_dispatch' && inputs.publish && format('refs/tags/cua-driver-rs-v{0}', inputs.version) || github.ref }}@@ -1085,6 +1130,34 @@ jobs:CUA_DRIVER_EXPECTED_VERSION: ${{ steps.version.outputs.version }}run: npm run verify+ # ── Release signature gate ──────────────────────────────────────────────────+ # Release safety (#4109): verify the exact uploaded archives the way the+ # operating systems do, on their own runners, before the release job can+ # upload anything. The release job needs both jobs and has no always()+ # bypass, so a skipped or failed verification blocks publication. macOS+ # verification runs whenever the build is notarized; a non-notarized manual+ # build skips it and therefore can never reach the release job.+ verify-macos-release-signatures:+ name: macOS release signatures+ needs: [release-attribution-preflight, build-macos-universal]+ if: startsWith(github.ref, 'refs/tags/cua-driver-rs-v') || inputs.notarize == true+ uses: ./.github/workflows/cua-driver-release-signatures.yml+ with:+ version: ${{ needs.release-attribution-preflight.outputs.version }}+ source: artifacts+ verify_macos: true+ verify_windows: false++ verify-windows-release-signatures:+ name: Windows release signatures+ needs: [release-attribution-preflight, build-windows]+ uses: ./.github/workflows/cua-driver-release-signatures.yml+ with:+ version: ${{ needs.release-attribution-preflight.outputs.version }}+ source: artifacts+ verify_macos: false+ verify_windows: true+# ── Release ──────────────────────────────────────────────────────────────────# Tag pushes build immutable candidate artifacts only. Publishing is an# explicit second step after the exact tag SHA passes the interactive E2E@@ -1093,10 +1166,24 @@ jobs:# evidence exists.release:needs:- [build-linux, build-windows, build-macos-universal, verify-windows-node-runtime, verify-release-artifacts, verify-mcp-client-discovery, build-hyprland-plugin-source]+ [build-linux, build-windows, build-macos-universal, verify-windows-node-runtime, verify-release-artifacts, verify-mcp-client-discovery, build-hyprland-plugin-source, verify-macos-release-signatures, verify-windows-release-signatures]if: github.event_name == 'workflow_dispatch' && inputs.publish == trueruns-on: ubuntu-latest+ outputs:+ version: ${{ steps.version.outputs.version }}steps:+ - name: Refuse to publish unverified or unnotarized artifacts+ env:+ DO_NOTARIZE: ${{ startsWith(github.ref, 'refs/tags/cua-driver-rs-v') || inputs.notarize == true }}+ MACOS_SIGNATURES: ${{ needs.verify-macos-release-signatures.result }}+ WINDOWS_SIGNATURES: ${{ needs.verify-windows-release-signatures.result }}+ run: |+ echo "notarize: ${DO_NOTARIZE}; macOS signatures: ${MACOS_SIGNATURES}; Windows signatures: ${WINDOWS_SIGNATURES}"+ if [[ "$DO_NOTARIZE" != "true" || "$MACOS_SIGNATURES" != "success" || "$WINDOWS_SIGNATURES" != "success" ]]; then+ echo "::error title=Release safety::Publishing requires notarized macOS artifacts and passing signature verification (#4109)."+ exit 1+ fi+- uses: actions/checkout@v4with:fetch-depth: 0@@ -1168,7 +1255,8 @@ jobs:python3 release-control/.github/scripts/update_cua_driver_installer_version.py \--version "$VERSION" \--shell-path release-upload/_install-rust.sh \- --powershell-path release-upload/install.ps1+ --powershell-path release-upload/install.ps1 \+ --withdrawn-path release-control/.github/release-state/cua-driver-rs-withdrawn-versions# Uninstaller scripts — single canonical file per shell (no# `_uninstall-rust.sh` helper). uninstall.sh handles Rust (the only@@ -1351,6 +1439,41 @@ jobs:fiexit 1+ # ── Post-publication verification ───────────────────────────────────────────+ # Release safety (#4109): the canonical installers resolve the baked version,+ # so it may only advance to a release whose real published bytes install.+ # Verify the public assets' signatures and run the canonical installers,+ # pinned to the new version, on macOS, Linux, and Windows. The installer+ # bake below needs both and has no always() bypass.+ verify-published-signatures:+ name: published release signatures+ needs: release+ uses: ./.github/workflows/cua-driver-release-signatures.yml+ with:+ version: ${{ needs.release.outputs.version }}+ source: release++ verify-published-installers:+ name: published release installers+ needs: release+ uses: ./.github/workflows/ci-cua-driver-installer-compat.yml+ with:+ versions: ${{ needs.release.outputs.version }}++ advance-installer-version:+ name: advance public installer version+ needs: [release, verify-published-signatures, verify-published-installers]+ runs-on: ubuntu-latest+ steps:+ # The orchestration helpers and the withdrawn list come from the exact+ # workflow revision; the installer files come from the latest main.+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0+ ref: ${{ github.workflow_sha }}+ path: release-control+ persist-credentials: false+- name: Generate post-publication GitHub App tokenid: post-publish-app-tokenuses: actions/create-github-app-token@v1@@ -1361,9 +1484,10 @@ jobs:repositories: ${{ github.event.repository.name }}- name: Advance public installer version on main+ working-directory: release-controlenv:GH_TOKEN: ${{ steps.post-publish-app-token.outputs.token }}- VERSION: ${{ steps.version.outputs.version }}+ VERSION: ${{ needs.release.outputs.version }}run: |git remote set-url origin \"https://x-access-token:${GH_TOKEN}@github.com/${{ github.repository }}.git"@@ -1375,11 +1499,12 @@ jobs:UPDATE_ROOT="${RUNNER_TEMP}/cua-installer-version-${ATTEMPT}"git worktree add --detach "$UPDATE_ROOT" origin/main- python3 release-control/.github/scripts/update_cua_driver_installer_version.py \+ python3 .github/scripts/update_cua_driver_installer_version.py \--version "$VERSION" \--shell-path "$UPDATE_ROOT/libs/cua-driver/scripts/_install-rust.sh" \--powershell-path "$UPDATE_ROOT/libs/cua-driver/scripts/install.ps1" \--state-path "$UPDATE_ROOT/.github/release-state/cua-driver-rs-published-version" \+ --withdrawn-path "$UPDATE_ROOT/.github/release-state/cua-driver-rs-withdrawn-versions" \--allow-newerif git -C "$UPDATE_ROOT" diff --quiet -- \@@ -1391,7 +1516,7 @@ jobs:fibash -n "$UPDATE_ROOT/libs/cua-driver/scripts/_install-rust.sh"- python3 release-control/.github/scripts/validate_release_versions.py \+ python3 .github/scripts/validate_release_versions.py \--repo-root "$UPDATE_ROOT" \--product drivergit -C "$UPDATE_ROOT" diff --checkdiff --git a/.github/workflows/ci-cua-driver-release-signatures.yml b/.github/workflows/ci-cua-driver-release-signatures.ymlnew file mode 100644index 0000000000..64ef8e5fc2--- /dev/null+++ b/.github/workflows/ci-cua-driver-release-signatures.yml@@ -0,0 +1,39 @@+name: "CI: Cua Driver release signature gate"++# Proves the release signature gate in both directions against real published+# assets: 0.28.2 (notarized) must pass, and 0.28.3 (published with an unsigned+# macOS app, see #4109, now withdrawn) must be rejected on macOS. Its Windows+# binaries are Authenticode-signed, so Windows must pass for both.++on:+ pull_request:+ paths:+ - ".github/scripts/verify_cua_driver_release_signatures.py"+ - ".github/scripts/expect_verification_result.sh"+ - ".github/workflows/cua-driver-release-signatures.yml"+ - ".github/workflows/ci-cua-driver-release-signatures.yml"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: ci-cua-driver-release-signatures-${{ github.ref }}+ cancel-in-progress: true++jobs:+ signed-release:+ name: signed 0.28.2 passes+ uses: ./.github/workflows/cua-driver-release-signatures.yml+ with:+ version: "0.28.2"+ source: release++ unsigned-release:+ name: unsigned 0.28.3 is rejected+ uses: ./.github/workflows/cua-driver-release-signatures.yml+ with:+ version: "0.28.3"+ source: release+ expect_macos: fail+ expect_windows: passdiff --git a/.github/workflows/cua-driver-release-signatures.yml b/.github/workflows/cua-driver-release-signatures.ymlnew file mode 100644index 0000000000..3995a1a223--- /dev/null+++ b/.github/workflows/cua-driver-release-signatures.yml@@ -0,0 +1,146 @@+name: "Release gate: Cua Driver signatures"++# Verifies that Cua Driver release archives carry the signatures the operating+# systems require, on the same kind of runner an end user has:+#+# macOS every CuaDriver.app is Developer ID signed by the pinned team,+# accepted by Gatekeeper as "Notarized Developer ID", and stapled;+# bare Mach-O binaries carry the same hardened-runtime signature.+# Windows every PE file in every zip has a valid, timestamped Authenticode+# signature from Cua AI, Inc.+#+# Callers:+# cd-rust-cua-driver.yml `source: artifacts` before the release job+# uploads anything, and `source: release` against+# the published assets before the installers bake+# the new version.+# ci-cua-driver-release-signatures.yml+# self-test against a known signed and a known+# unsigned published release.++on:+ workflow_call:+ inputs:+ version:+ description: "Exact Cua Driver version whose archives are verified"+ required: true+ type: string+ source:+ description: "artifacts (this workflow run) or release (published GitHub release assets)"+ required: false+ default: artifacts+ type: string+ verify_macos:+ required: false+ default: true+ type: boolean+ verify_windows:+ required: false+ default: true+ type: boolean+ expect_macos:+ description: "pass, or fail for a negative control"+ required: false+ default: pass+ type: string+ expect_windows:+ description: "pass, or fail for a negative control"+ required: false+ default: pass+ type: string++permissions:+ contents: read++jobs:+ macos:+ name: macOS notarization (${{ inputs.version }}, expect ${{ inputs.expect_macos }})+ if: inputs.verify_macos+ runs-on: macos-26+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v4+ with:+ persist-credentials: false+ sparse-checkout: .github/scripts+ - name: Download candidate darwin archives+ if: inputs.source == 'artifacts'+ uses: actions/download-artifact@v4+ with:+ name: cua-driver-rs-darwin+ path: signature-artifacts+ - name: Download published darwin archives+ if: inputs.source == 'release'+ env:+ GH_TOKEN: ${{ github.token }}+ VERSION: ${{ inputs.version }}+ run: |+ set -euo pipefail+ gh release download "cua-driver-rs-v${VERSION}" \+ --repo "$GITHUB_REPOSITORY" \+ --dir signature-artifacts \+ --pattern "cua-driver-rs-${VERSION}-darwin-*.tar.gz" \+ --pattern "*.pkg" \+ --pattern "*.dmg"+ - name: Verify macOS signatures, notarization, and stapling+ env:+ VERSION: ${{ inputs.version }}+ EXPECT: ${{ inputs.expect_macos }}+ run: |+ set -euo pipefail+ ls -l signature-artifacts+ ANNOTATE=()+ if [[ "$EXPECT" == "fail" ]]; then ANNOTATE=(--no-annotations); fi+ STATUS=0+ python3 .github/scripts/verify_cua_driver_release_signatures.py macos \+ --artifacts signature-artifacts \+ --version "$VERSION" \+ --team-id YCK386LBJ7 \+ ${ANNOTATE[@]+"${ANNOTATE[@]}"} || STATUS=$?+ bash .github/scripts/expect_verification_result.sh "$EXPECT" "$STATUS" "macOS signatures for $VERSION"++ windows:+ name: Windows Authenticode (${{ inputs.version }}, expect ${{ inputs.expect_windows }})+ if: inputs.verify_windows+ runs-on: windows-latest+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v4+ with:+ persist-credentials: false+ sparse-checkout: .github/scripts+ - name: Download candidate Windows archives+ if: inputs.source == 'artifacts'+ uses: actions/download-artifact@v4+ with:+ pattern: cua-driver-rs-windows-*+ path: signature-artifacts+ - name: Download published Windows archives+ if: inputs.source == 'release'+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ VERSION: ${{ inputs.version }}+ run: |+ set -euo pipefail+ gh release download "cua-driver-rs-v${VERSION}" \+ --repo "$GITHUB_REPOSITORY" \+ --dir signature-artifacts \+ --pattern "cua-driver-rs-${VERSION}-windows-*.zip"+ - name: Verify Windows Authenticode signatures+ shell: bash+ env:+ VERSION: ${{ inputs.version }}+ EXPECT: ${{ inputs.expect_windows }}+ run: |+ set -euo pipefail+ ls -lR signature-artifacts+ ANNOTATE=()+ if [[ "$EXPECT" == "fail" ]]; then ANNOTATE=(--no-annotations); fi+ STATUS=0+ python .github/scripts/verify_cua_driver_release_signatures.py windows \+ --artifacts signature-artifacts \+ --version "$VERSION" \+ --signer "Cua AI, Inc." \+ ${ANNOTATE[@]+"${ANNOTATE[@]}"} || STATUS=$?+ bash .github/scripts/expect_verification_result.sh "$EXPECT" "$STATUS" "Windows signatures for $VERSION"diff --git a/libs/cua-driver/scripts/_install-rust.sh b/libs/cua-driver/scripts/_install-rust.shindex 0ffbc79b75..2619fcd1d5 100644--- a/libs/cua-driver/scripts/_install-rust.sh+++ b/libs/cua-driver/scripts/_install-rust.sh@@ -617,6 +617,23 @@ done# ~~~ BAKED_VERSION: auto-updated after release publication — do not edit ~~~CUA_DRIVER_RS_BAKED_VERSION="0.28.2" # published-installer-version# ~~~ END_BAKED_VERSION ~~~+#+# Withdrawn releases (for example, a macOS archive published unsigned) are+# never selected: an explicit pin is refused, and API resolution skips them.+# Space-separated exact versions. This must mirror+# .github/release-state/cua-driver-rs-withdrawn-versions, which records the+# reasons; validate_release_versions.py enforces the match.+# ~~~ WITHDRAWN_VERSIONS: mirrors the release-state list — do not edit alone ~~~+CUA_DRIVER_RS_WITHDRAWN_VERSIONS="0.28.3" # withdrawn-installer-versions+# ~~~ END_WITHDRAWN_VERSIONS ~~~++is_withdrawn_version() {+ local candidate="$1" withdrawn+ for withdrawn in ${CUA_DRIVER_RS_WITHDRAWN_VERSIONS:-}; do+ [[ "$withdrawn" == "$candidate" ]] && return 0+ done+ return 1+}# Run API requests with an optional token. Keep the header construction here# (rather than in loggable command text) so neither GH_TOKEN nor GITHUB_TOKEN@@ -697,9 +714,18 @@ resolve_latest_version_from_api() {fidone- local version+ # Withdrawn releases stay published for audit, but must never be chosen.+ local version candidate eligible=""+ while IFS= read -r candidate; do+ [[ -n "$candidate" ]] || continue+ if is_withdrawn_version "$candidate"; then+ printf 'note: skipping withdrawn release %s%s\n' "$TAG_PREFIX" "$candidate" >&2+ continue+ fi+ eligible="${eligible}${eligible:+$'\n'}${candidate}"+ done <<< "$versions"version="$(- printf '%s\n' "$versions" \+ printf '%s\n' "$eligible" \| sed '/^$/d' \| sort -t. -k1,1nr -k2,2nr -k3,3nr -k4,4nr -k5,5nr \| head -n 1@@ -766,7 +792,13 @@ if [[ -n "${CUA_DRIVER_RS_VERSION:-}" ]]; thenexit 1filog "using version from CUA_DRIVER_RS_VERSION: $TAG"-elif [[ "$SELECTED_CHANNEL" == "stable" && -n "${CUA_DRIVER_RS_BAKED_VERSION:-}" ]]; then+ if is_withdrawn_version "${TAG#${TAG_PREFIX}}"; then+ err "$TAG was withdrawn and must not be installed; pin a different release"+ err " or unset CUA_DRIVER_RS_VERSION to install the current release."+ exit 1+ fi+elif [[ "$SELECTED_CHANNEL" == "stable" && -n "${CUA_DRIVER_RS_BAKED_VERSION:-}" ]] \+ && ! is_withdrawn_version "${CUA_DRIVER_RS_BAKED_VERSION#v}"; thenVERSION_SOURCE="baked"if ! [[ "$CUA_DRIVER_RS_BAKED_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; thenerr "baked Cua Driver version must be an exact stable x.y.z version"@@ -775,6 +807,13 @@ elif [[ "$SELECTED_CHANNEL" == "stable" && -n "${CUA_DRIVER_RS_BAKED_VERSION:-}"TAG="${TAG_PREFIX}${CUA_DRIVER_RS_BAKED_VERSION#v}"log "using baked release: $TAG"else+ # Release validation never lets a withdrawn version be baked; an old or+ # hand-edited installer copy that still names one resolves through the API,+ # which skips every withdrawn release.+ if [[ "$SELECTED_CHANNEL" == "stable" && -n "${CUA_DRIVER_RS_BAKED_VERSION:-}" ]]; then+ printf 'warning: baked release %s%s was withdrawn; resolving the newest eligible release instead\n' \+ "$TAG_PREFIX" "${CUA_DRIVER_RS_BAKED_VERSION#v}" >&2+ fiVERSION_SOURCE="api"log "resolving latest $SELECTED_CHANNEL release via GitHub API"if ! API_VERSION="$(resolve_latest_version_from_api)"; then@@ -1071,6 +1110,10 @@ if [[ "$OS" == "Darwin" && -n "$SRC_APP" && -d "$SRC_APP" ]]; thenfiif ! codesign --verify --deep --strict "$SRC_APP" 2>/dev/null; thenerr "downloaded CuaDriver.app failed signature verification; the installed app was not changed"+ # Fail closed. Automatically installing an older release here would+ # hide a broken or tampered release, so recovery stays an explicit pin.+ err " $TAG cannot be installed safely on macOS. Please report it at https://github.com/$REPO/issues;"+ err " to install an earlier signed release instead, set CUA_DRIVER_RS_VERSION=<x.y.z>."exit 1fiSTAGED_BUNDLE_ID=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' \diff --git a/libs/cua-driver/scripts/install.ps1 b/libs/cua-driver/scripts/install.ps1index 34ca1450ea..a12b7c34b5 100644--- a/libs/cua-driver/scripts/install.ps1+++ b/libs/cua-driver/scripts/install.ps1@@ -125,6 +125,15 @@ $ThemeBinaryName = "cua-cursor-theme.exe"# ~~~ BAKED_VERSION: auto-updated after release publication — do not edit ~~~$Script:CuaDriverRsBakedVersion = "0.28.2" # published-installer-version# ~~~ END_BAKED_VERSION ~~~+#+# Withdrawn releases (for example, a release published without valid+# signatures) are never selected: an explicit pin is refused, and API+# resolution skips them. This must mirror+# .github/release-state/cua-driver-rs-withdrawn-versions, which records the+# reasons; validate_release_versions.py enforces the match.+# ~~~ WITHDRAWN_VERSIONS: mirrors the release-state list — do not edit alone ~~~+$Script:CuaDriverRsWithdrawnVersions = @('0.28.3') # withdrawn-installer-versions+# ~~~ END_WITHDRAWN_VERSIONS ~~~$CursorThemeRequiredFrom = [version]"0.12.7"# ---------- Path resolution ------------------------------------------------@@ -913,6 +922,18 @@ function Resolve-ExplicitRelease([string]$value, [string]$source) {exit 1}+function Test-WithdrawnVersion([string]$version) {+ return [bool]($Script:CuaDriverRsWithdrawnVersions -contains $version)+}++function Assert-NotWithdrawnPin([hashtable]$release) {+ if (Test-WithdrawnVersion $release.Version) {+ Write-ErrorStep "$($release.Tag) was withdrawn and must not be installed; pin a different release"+ Write-ErrorStep " or remove the pin to install the current release."+ exit 1+ }+}+function Get-LatestVersionFromApi {# Highest SemVer $TagPrefix* version published on the repo, or $null when# the API is unreachable or has no matching tag. Never exits: callers@@ -946,7 +967,15 @@ function Get-LatestVersionFromApi {if ($Script:CuaDriverRsSelectedChannel -eq 'nightly') {return $_.tag_name -match "^$([regex]::Escape($selectedPrefix))([0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[1-9][0-9]*)$"}- return $_.tag_name -match "^$([regex]::Escape($selectedPrefix))([0-9]+\.[0-9]+\.[0-9]+)$"+ if ($_.tag_name -notmatch "^$([regex]::Escape($selectedPrefix))([0-9]+\.[0-9]+\.[0-9]+)$") {+ return $false+ }+ # Withdrawn releases stay published for audit, but must never be chosen.+ if (Test-WithdrawnVersion $_.tag_name.Substring($selectedPrefix.Length)) {+ Write-WarningStep "skipping withdrawn release $($_.tag_name)"+ return $false+ }+ return $true})if ($batch.Count -lt 100) { break }}@@ -1020,6 +1049,7 @@ function Resolve-Version {$v = $release.Version$Script:CuaDriverRsReleaseTag = $release.TagWrite-Step "using version from `$env:CUA_DRIVER_RS_VERSION: $($release.Tag)"+ Assert-NotWithdrawnPin $release$Script:CuaDriverRsVersionSource = 'env'return $v}@@ -1028,6 +1058,7 @@ function Resolve-Version {$v = $release.Version$Script:CuaDriverRsReleaseTag = $release.TagWrite-Step "using -Release $($release.Tag)"+ Assert-NotWithdrawnPin $release$Script:CuaDriverRsVersionSource = 'release-arg'return $v}@@ -1037,10 +1068,18 @@ function Resolve-Version {if ($Script:CuaDriverRsSelectedChannel -eq 'stable' -and $Script:CuaDriverRsBakedVersion) {$v = $Script:CuaDriverRsBakedVersion -replace '^v', ''Assert-StableVersion $v 'baked release'- Write-Step "using baked release: $TagPrefix$v"- $Script:CuaDriverRsReleaseTag = "$TagPrefix$v"- $Script:CuaDriverRsVersionSource = 'baked'- return $v+ if (Test-WithdrawnVersion $v) {+ # Release validation never lets a withdrawn version be baked; an old+ # or hand-edited installer copy that still names one resolves through+ # the API, which skips every withdrawn release.+ Write-WarningStep "baked release $TagPrefix$v was withdrawn; resolving the newest eligible release instead"+ }+ else {+ Write-Step "using baked release: $TagPrefix$v"+ $Script:CuaDriverRsReleaseTag = "$TagPrefix$v"+ $Script:CuaDriverRsVersionSource = 'baked'+ return $v+ }}$v = Get-LatestVersionFromApiif (-not $v) {diff --git a/libs/cua-driver/scripts/tests/test_install_version_fallback.py b/libs/cua-driver/scripts/tests/test_install_version_fallback.pyindex 4f7418eaaf..f23530484f 100644--- a/libs/cua-driver/scripts/tests/test_install_version_fallback.py+++ b/libs/cua-driver/scripts/tests/test_install_version_fallback.py@@ -293,7 +293,7 @@ def test_windows_api_resolver_filters_drafts_but_accepts_stable_prereleases(source = _windows_source()functions = "\n\n".join(_extract_powershell_function(source, name)- for name in ("Get-GitHubApiHeaders", "Get-LatestVersionFromApi")+ for name in ("Test-WithdrawnVersion", "Get-GitHubApiHeaders", "Get-LatestVersionFromApi"))result = _run_powershell(tmp_path,@@ -387,7 +387,9 @@ def _extract_shell_function(source: str, name: str) -> str:return match.group(0)-def _run_resolver(tmp_path: Path, releases_json: str, epilogue: str, strict: bool) -> str:+def _run_resolver(+ tmp_path: Path, releases_json: str, epilogue: str, strict: bool, withdrawn: str = ""+) -> str:"""Runs the real resolver function with curl shadowed by a shell function.A function shim beats a PATH shim here: it needs no exec bit and no PATH@@ -405,6 +407,8 @@ def _run_resolver(tmp_path: Path, releases_json: str, epilogue: str, strict: booREPO="trycua/cua"TAG_PREFIX="cua-driver-rs-v"curl() {{ cat "{fixture}"; }}+ CUA_DRIVER_RS_WITHDRAWN_VERSIONS="{withdrawn}"+ {is_withdrawn}{github_api_curl}{published_versions}{resolver}@@ -415,6 +419,8 @@ def _run_resolver(tmp_path: Path, releases_json: str, epilogue: str, strict: boo# which -e would otherwise turn into an abort before the assertion.flags="e" if strict else "",fixture=fixture.as_posix(),+ withdrawn=withdrawn,+ is_withdrawn=_extract_shell_function(_unix_source(), "is_withdrawn_version"),github_api_curl=_extract_shell_function(_unix_source(), "github_api_curl"),published_versions=_extract_shell_function(_unix_source(), "extract_published_release_versions"@@ -826,3 +832,218 @@ def test_unix_non_fallback_download_failure_makes_zero_api_calls()assert result.returncode == 1assert calls == ["download:1.2.3"]+++# ---------- Withdrawn releases ----------------------------------------------+#+# A withdrawn release (for example 0.28.3, whose macOS app was published+# unsigned) stays published for audit but must never be selected. The+# installers cannot read repository files at runtime, so each carries a baked+# list that validate_release_versions.py keeps equal to+# .github/release-state/cua-driver-rs-withdrawn-versions.+++@requires_posix_bash+def test_unix_api_resolver_skips_withdrawn_releases(tmp_path: Path) -> None:+ releases = """+ [+ {+ "tag_name": "cua-driver-rs-v0.28.3",+ "draft": false+ },+ {+ "tag_name": "cua-driver-rs-v0.28.2",+ "draft": false+ }+ ]+ """+ assert (+ _run_resolver(tmp_path, releases, "resolve_latest_version_from_api", strict=True)+ == "0.28.3"+ )+ assert (+ _run_resolver(+ tmp_path,+ releases,+ "resolve_latest_version_from_api",+ strict=True,+ withdrawn="0.28.1 0.28.3",+ )+ == "0.28.2"+ )+++@requires_posix_bash+def test_unix_api_resolver_fails_when_only_withdrawn_releases_remain(tmp_path: Path) -> None:+ resolved = _run_resolver(+ tmp_path,+ '[\n {\n "tag_name": "cua-driver-rs-v0.28.3",\n "draft": false\n }\n]',+ epilogue="if resolve_latest_version_from_api; then echo RESOLVED; else echo NOMATCH; fi",+ strict=False,+ withdrawn="0.28.3",+ )+ assert resolved == "NOMATCH"+++def _run_resolution_flow(+ tmp_path: Path, *, pin: str = "", baked: str = "", withdrawn: str = ""+) -> tuple[subprocess.CompletedProcess[str], list[str]]:+ """Execute the installer's real release-tag resolution block."""+ source = _unix_source()+ start = source.index('if [[ -n "${CUA_DRIVER_RS_VERSION:-}" ]]; then\n VERSION_SOURCE="pin"')+ end = source.index('if [[ "$TAG" == "$NIGHTLY_TAG_PREFIX"* ]]; then', start)+ calls = tmp_path / "resolution-calls"+ calls.write_text("", encoding="utf-8")+ script = tmp_path / "run-resolution.sh"+ script.write_text(+ textwrap.dedent(+ f"""\+ set -uo pipefail+ REPO="trycua/cua"+ TAG_PREFIX="cua-driver-rs-v"+ NIGHTLY_TAG_PREFIX="nightly-cua-driver-rs-v"+ SELECTED_CHANNEL="stable"+ SELECTED_TAG_PREFIX="$TAG_PREFIX"+ CUA_DRIVER_RS_VERSION="{pin}"+ CUA_DRIVER_RS_BAKED_VERSION="{baked}"+ CUA_DRIVER_RS_WITHDRAWN_VERSIONS="{withdrawn}"+ log() {{ printf 'log: %s\\n' "$*" >&2; }}+ err() {{ printf 'error: %s\\n' "$*" >&2; }}+ resolve_latest_version_from_api() {{+ printf 'api\\n' >> "{calls.as_posix()}"+ printf '0.28.2'+ }}+ """+ )+ + _extract_shell_function(source, "is_withdrawn_version")+ + "\n"+ + _extract_shell_function(source, "resolve_explicit_release_tag")+ + "\n"+ + source[start:end]+ + '\nprintf \'resolved:%s:%s\\n\' "$VERSION_SOURCE" "$TAG"\n',+ encoding="utf-8",+ )+ result = subprocess.run(["bash", script.as_posix()], capture_output=True, text=True)+ return result, calls.read_text(encoding="utf-8").splitlines()+++@requires_posix_bash+def test_unix_installer_refuses_an_explicit_withdrawn_pin(tmp_path: Path) -> None:+ result, calls = _run_resolution_flow(+ tmp_path, pin="0.28.3", baked="0.28.2", withdrawn="0.28.3"+ )+ assert result.returncode == 1+ assert "cua-driver-rs-v0.28.3 was withdrawn and must not be installed" in result.stderr+ assert "resolved:" not in result.stdout+ assert calls == []+++@requires_posix_bash+def test_unix_installer_resolves_past_a_withdrawn_baked_version(tmp_path: Path) -> None:+ result, calls = _run_resolution_flow(tmp_path, baked="0.28.3", withdrawn="0.28.3")+ assert result.returncode == 0, result.stderr+ assert result.stdout == "resolved:api:cua-driver-rs-v0.28.2\n"+ assert "baked release cua-driver-rs-v0.28.3 was withdrawn" in result.stderr+ assert calls == ["api"]+++@requires_posix_bash+def test_unix_installer_uses_an_eligible_baked_version_without_api(tmp_path: Path) -> None:+ result, calls = _run_resolution_flow(tmp_path, baked="0.28.2", withdrawn="0.28.3")+ assert result.returncode == 0, result.stderr+ assert result.stdout == "resolved:baked:cua-driver-rs-v0.28.2\n"+ assert calls == []+++def test_unix_installer_fails_closed_on_macos_signature_failure() -> None:+ """A bad signature never triggers an automatic downgrade to another release."""+ source = _unix_source()+ failure = source.index(+ 'err "downloaded CuaDriver.app failed signature verification; the installed app was not changed"'+ )+ exit_line = source.index("exit 1", failure)+ between = source[failure:exit_line]+ assert "resolve_latest_version_from_api" not in between+ assert "download_release_tarball" not in between+ assert "CUA_DRIVER_RS_VERSION=<x.y.z>" in between+++def test_windows_installer_rejects_withdrawn_pins_and_baked_versions() -> None:+ source = _windows_source()+ resolve = source[+ source.index("function Resolve-Version") : source.index("# ---------- Download + extract")+ ]+ env_pin = resolve.index("$Script:CuaDriverRsVersionSource = 'env'")+ release_pin = resolve.index("$Script:CuaDriverRsVersionSource = 'release-arg'")+ assert resolve.index("Assert-NotWithdrawnPin $release") < env_pin+ assert resolve.index("Assert-NotWithdrawnPin $release", env_pin) < release_pin+ baked = resolve.index("$Script:CuaDriverRsVersionSource = 'baked'")+ assert resolve.index("if (Test-WithdrawnVersion $v) {") < baked++ api = source[+ source.index("function Get-LatestVersionFromApi") : source.index(+ "function Resolve-SelectedChannel"+ )+ ]+ assert "Test-WithdrawnVersion $_.tag_name.Substring($selectedPrefix.Length)" in api+++@requires_powershell+def test_windows_api_resolver_skips_withdrawn_releases(tmp_path: Path) -> None:+ source = _windows_source()+ functions = "\n\n".join(+ _extract_powershell_function(source, name)+ for name in ("Test-WithdrawnVersion", "Get-GitHubApiHeaders", "Get-LatestVersionFromApi")+ )+ result = _run_powershell(+ tmp_path,+ f"""+$Repo = 'trycua/cua'+$TagPrefix = 'cua-driver-rs-v'+$Script:CuaDriverRsWithdrawnVersions = @('0.28.3')+function Write-Step {{ param([string]$Message) }}+function Write-WarningStep {{ param([string]$Message) }}+function Invoke-RestMethod {{+ param([string]$Uri, [hashtable]$Headers, [switch]$UseBasicParsing)+ @(+ [pscustomobject]@{{ tag_name = 'cua-driver-rs-v0.28.3'; draft = $false; prerelease = $true }}+ [pscustomobject]@{{ tag_name = 'cua-driver-rs-v0.28.2'; draft = $false; prerelease = $true }}+ )+}}++{functions}++Get-LatestVersionFromApi+""",+ )+ assert result.stdout.strip() == "0.28.2"+++@requires_powershell+def test_windows_installer_refuses_an_explicit_withdrawn_pin(tmp_path: Path) -> None:+ source = _windows_source()+ functions = "\n\n".join(+ _extract_powershell_function(source, name)+ for name in ("Test-WithdrawnVersion", "Assert-NotWithdrawnPin")+ )+ script = tmp_path / "withdrawn-pin.ps1"+ script.write_text(+ f"""+$Script:CuaDriverRsWithdrawnVersions = @('0.28.3')+function Write-ErrorStep {{ param([string]$Message) [Console]::Error.WriteLine($Message) }}+{functions}+Assert-NotWithdrawnPin @{{ Version = '0.28.2'; Tag = 'cua-driver-rs-v0.28.2' }}+Write-Output 'eligible'+Assert-NotWithdrawnPin @{{ Version = '0.28.3'; Tag = 'cua-driver-rs-v0.28.3' }}+Write-Output 'unreachable'+""",+ encoding="utf-8",+ )+ result = subprocess.run(+ [str(POWERSHELL), "-NoProfile", "-NonInteractive", "-File", str(script)],+ capture_output=True,+ text=True,+ )+ assert result.returncode == 1+ assert result.stdout.split() == ["eligible"]+ assert "cua-driver-rs-v0.28.3 was withdrawn" in result.stderr