diff --git a/.github/workflows/desktop-release-artifacts.yml b/.github/workflows/desktop-release-artifacts.yml index 3d0b489f69..280d50c55b 100644 --- a/.github/workflows/desktop-release-artifacts.yml +++ b/.github/workflows/desktop-release-artifacts.yml @@ -8,7 +8,9 @@ on: - "apps/presentation/dashboard/**" - "examples/desktop-icon-alpha-smoke.py" - "examples/desktop-release-workflow-smoke.py" + - "scripts/desktop_macos_signing.py" - "scripts/desktop_release_artifacts.py" + - "tests/desktop/test_desktop_signing_workflow.py" release: types: [published] workflow_dispatch: @@ -75,6 +77,19 @@ jobs: fi echo "release-tag=${release_tag}" >> "${GITHUB_OUTPUT}" + - name: Resolve macOS signing mode + id: macos-signing + if: github.event_name != 'pull_request' && runner.os == 'macOS' + env: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + run: python3 scripts/desktop_macos_signing.py resolve-mode + - name: Set up Node uses: actions/setup-node@v6 with: @@ -125,11 +140,19 @@ jobs: working-directory: apps/desktop/loopx-control-plane run: npm run build -- --bundles ${{ matrix.bundles }} --no-sign - - name: Build integrity-signed macOS release bundles + - name: Build macOS release bundles if: github.event_name != 'pull_request' && runner.os == 'macOS' working-directory: apps/desktop/loopx-control-plane env: RELEASE_TAG: ${{ steps.identity.outputs.release-tag }} + EXPECTED_SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }} + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} run: | set -euo pipefail release_version="${RELEASE_TAG#v}" @@ -137,8 +160,22 @@ jobs: echo "::error title=Invalid desktop release version::${RELEASE_TAG} is not a supported release tag" exit 1 fi - npm run build -- --bundles ${{ matrix.bundles }} \ - --config "{\"version\":\"${release_version}\",\"bundle\":{\"macOS\":{\"signingIdentity\":\"-\"}}}" + python3 ../../../scripts/desktop_macos_signing.py build \ + --version "${release_version}" \ + --bundles ${{ matrix.bundles }} \ + --expected-mode "${EXPECTED_SIGNING_MODE}" + + - name: Notarize macOS disk image + if: github.event_name != 'pull_request' && runner.os == 'macOS' && steps.macos-signing.outputs.signing-mode == 'developer_id' + env: + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + run: | + set -euo pipefail + dmg_path="$(find apps/desktop/loopx-control-plane/src-tauri/target/release/bundle/dmg -maxdepth 1 -name '*.dmg' -print -quit)" + test -n "${dmg_path}" + python3 scripts/desktop_macos_signing.py notarize-dmg --dmg "${dmg_path}" - name: Build Windows release bundles if: github.event_name != 'pull_request' && runner.os == 'Windows' @@ -159,15 +196,17 @@ jobs: - name: Verify macOS desktop bundles if: github.event_name != 'pull_request' && runner.os == 'macOS' shell: bash + env: + SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }} run: | set -euo pipefail app_path="apps/desktop/loopx-control-plane/src-tauri/target/release/bundle/macos/LoopX.app" dmg_path="$(find apps/desktop/loopx-control-plane/src-tauri/target/release/bundle/dmg -maxdepth 1 -name '*.dmg' -print -quit)" test -n "${dmg_path}" - codesign --verify --deep --strict --verbose=2 "${app_path}" - codesign --display --verbose=4 "${app_path}" 2>&1 \ - | grep -q '^Signature=adhoc$' - hdiutil verify "${dmg_path}" + python3 scripts/desktop_macos_signing.py verify \ + --signing-mode "${SIGNING_MODE}" \ + --app "${app_path}" \ + --dmg "${dmg_path}" - name: Collect macOS desktop bundles if: runner.os == 'macOS' diff --git a/.github/workflows/desktop-updater.yml b/.github/workflows/desktop-updater.yml index ab1b6dde90..e2092ffca7 100644 --- a/.github/workflows/desktop-updater.yml +++ b/.github/workflows/desktop-updater.yml @@ -5,6 +5,7 @@ on: paths: - 'apps/desktop/**' - 'scripts/desktop_*' + - 'tests/desktop/**' - '.github/workflows/desktop-updater.yml' release: types: [published] @@ -107,6 +108,17 @@ jobs: - uses: actions/setup-python@v6 with: python-version: "3.12" + - name: Resolve macOS signing mode + id: macos-signing + env: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + run: python3 scripts/desktop_macos_signing.py resolve-mode - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 with: @@ -120,12 +132,38 @@ jobs: env: TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} TAURI_SIGNING_PRIVATE_KEY_PASSWORD: "" + EXPECTED_SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }} + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} VERSION: ${{ needs.identity.outputs.version }} BUNDLE: app run: | set -euo pipefail test -n "$TAURI_SIGNING_PRIVATE_KEY" - npm run build -- --bundles "$BUNDLE" --config "{\"version\":\"$VERSION\",\"bundle\":{\"createUpdaterArtifacts\":true,\"macOS\":{\"signingIdentity\":\"-\"}}}" + python3 ../../../scripts/desktop_macos_signing.py build \ + --version "$VERSION" \ + --bundles "$BUNDLE" \ + --create-updater-artifacts \ + --expected-mode "$EXPECTED_SIGNING_MODE" + - name: Verify macOS updater bundle + if: runner.os == 'macOS' + shell: bash + env: + SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }} + run: | + set -euo pipefail + app_path="apps/desktop/loopx-control-plane/src-tauri/target/release/bundle/macos/LoopX.app" + updater_tar_gz="$(find apps/desktop/loopx-control-plane/src-tauri/target/release/bundle -type f -name '*.app.tar.gz' -print -quit)" + test -n "${updater_tar_gz}" + python3 scripts/desktop_macos_signing.py verify \ + --signing-mode "${SIGNING_MODE}" \ + --app "${app_path}" \ + --updater-tar-gz "${updater_tar_gz}" - name: Collect native updater artifacts shell: bash env: diff --git a/apps/desktop/loopx-control-plane/README.md b/apps/desktop/loopx-control-plane/README.md index deac5411c4..b120f85a01 100644 --- a/apps/desktop/loopx-control-plane/README.md +++ b/apps/desktop/loopx-control-plane/README.md @@ -499,11 +499,13 @@ serves your terminal runtime) checks that host's installation. It cannot diagnose this Mac App's local bootstrap; only the App's own diagnostics do. The updater accepts only fixed official HTTPS channels, not browser-provided -commands, paths or download URLs. Its signing private key is confined to the -release secret; the App embeds the public key. PR validation has no signing -secret. Updater signing does not provide Apple notarization. It also does not -change Goal authority, grant capabilities, or stop running agents on behalf of -the user. Services may briefly disconnect during reconciliation. +commands, paths or download URLs. Its minisign private key +(`TAURI_SIGNING_PRIVATE_KEY`) is confined to the release secret; the App embeds +the public key. PR validation has no signing secret and keeps `--no-sign` +preview builds. Updater minisign signing is distinct from Apple Developer ID +signing and notarization; it also does not change Goal authority, grant +capabilities, or stop running agents on behalf of the user. Services may +briefly disconnect during reconciliation. The background feed check has a thirty-second deadline and is outside local workspace startup. A manual **Check for updates** allows 45 seconds for the same @@ -513,10 +515,45 @@ A timeout remains an explicit retryable error, never a claim that the App is current. Archive downloads use the separate connection, idle-read and total deadlines described above. Installation and recovery boundaries are unchanged. -Published macOS preview artifacts use ad-hoc code signing to verify bundle -integrity without requiring an Apple Developer account. They are not signed -with a Developer ID and are not notarized, so macOS may require the operator -to approve the first launch in System Settings > Privacy & Security. +On non-PR official macOS builds (`desktop-release-artifacts.yml` and +`desktop-updater.yml`), signing and notarization depend on the five core Apple +secrets (`APPLE_CERTIFICATE`, `APPLE_CERTIFICATE_PASSWORD`, `APPLE_ID`, +`APPLE_PASSWORD`, `APPLE_TEAM_ID`; plus optional `KEYCHAIN_PASSWORD`, which +defaults to an ephemeral random password per build if unset, and optional +`APPLE_SIGNING_IDENTITY`): + +- **Developer ID + Apple Notarization (all 5 core secrets set):** Tauri signs + `LoopX.app` with Developer ID Application and Hardened Runtime, notarizes and + staples `LoopX.app` before zipping `LoopX.app.zip` or packing the updater's + `.app.tar.gz`, and the release workflow notarizes and staples the `.dmg` with + `xcrun notarytool` / `xcrun stapler`. Both `.app` and `.dmg` are verified with + `codesign --verify --deep --strict`, `Authority=Developer ID Application:`, + `spctl --assess`, `xcrun stapler validate`, and `hdiutil verify`. +- **Ad-hoc integrity signing (all 5 core secrets unset):** Non-PR builds keep + `"signingIdentity": "-"` (`Signature=adhoc` verified via + `codesign --verify --deep --strict` and `hdiutil verify`). Partial + configurations (1–4 of 5 core secrets) fail closed instead of downgrading. +- **Updater signature compatibility across transitions:** `src-tauri` verifies + updater archives with the embedded minisign key and validates both staged + candidates and rollback backups with `codesign --verify --deep --strict` + (`installed_bundle_verifies` / `replace_bundle`), with no ad-hoc-only check. + Existing ad-hoc installations can upgrade in-app to Developer ID + notarized + releases (and between Developer ID releases) through the normal updater flow. + +When running an ad-hoc-signed or unsigned preview build on macOS Sequoia 15+, +Gatekeeper's initial dialog offers **Move to Trash** by default instead of an +inline **Open Anyway** button. Do not click **Move to Trash**; approve the first +launch using either option below: + +1. Click **Done** to dismiss the Gatekeeper dialog, open **System Settings → + Privacy & Security**, scroll to the Security section, click **Open Anyway** + next to the `LoopX` prompt, and confirm launch. +2. Or, after verifying the download against `DESKTOP-SHA256SUMS`, clear the + quarantine attribute in Terminal: + + ```bash + xattr -dr com.apple.quarantine /Applications/LoopX.app + ``` ## Runtime Model @@ -824,8 +861,11 @@ comparison; they do not certify an installed update or an executing task's recov `src-tauri/target/release/bundle/`. The release workflow builds macOS `.dmg` and `.app.zip` artifacts on macOS, Windows `.msi` and `.exe` artifacts on Windows, and uploads them to the GitHub Release that triggered the workflow. -It verifies the ad-hoc macOS app signature and disk-image integrity before -upload. A separate `DESKTOP-SHA256SUMS` manifest covers all desktop artifacts +When the Apple signing and notarization secrets are configured, it verifies +Developer ID signing, Gatekeeper assessment (`spctl`), stapled notarization +tickets (`xcrun stapler validate`), and disk-image integrity before upload; +when all five core Apple secrets are unset, it verifies the ad-hoc macOS app +signature and disk-image integrity instead. A separate `DESKTOP-SHA256SUMS` manifest covers all desktop artifacts attached by the workflow, and release builds use the Git tag as the desktop bundle version. A manual rerun for an existing tag is an explicit full desktop republish: it rebuilds both macOS and Windows assets, preserves the previous diff --git a/examples/desktop-release-workflow-smoke.py b/examples/desktop-release-workflow-smoke.py index a6f69a25ad..73a1785082 100644 --- a/examples/desktop-release-workflow-smoke.py +++ b/examples/desktop-release-workflow-smoke.py @@ -4,21 +4,32 @@ from __future__ import annotations import importlib.util +import json import os import subprocess import sys import tempfile +from types import ModuleType from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] WORKFLOW = REPO_ROOT / ".github" / "workflows" / "desktop-release-artifacts.yml" ARTIFACT_SCRIPT = REPO_ROOT / "scripts" / "desktop_release_artifacts.py" -SPEC = importlib.util.spec_from_file_location("desktop_release_artifacts", ARTIFACT_SCRIPT) -assert SPEC is not None and SPEC.loader is not None -desktop_release_artifacts = importlib.util.module_from_spec(SPEC) -sys.modules[SPEC.name] = desktop_release_artifacts -SPEC.loader.exec_module(desktop_release_artifacts) +SIGNING_SCRIPT = REPO_ROOT / "scripts" / "desktop_macos_signing.py" + + +def load_module(name: str, path: Path) -> ModuleType: + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +desktop_release_artifacts = load_module("desktop_release_artifacts", ARTIFACT_SCRIPT) +desktop_macos_signing = load_module("desktop_macos_signing", SIGNING_SCRIPT) def assert_contains(text: str, needle: str) -> None: @@ -28,7 +39,158 @@ def assert_contains(text: str, needle: str) -> None: def assert_absent(text: str, needle: str) -> None: if needle in text: - raise AssertionError(f"desktop preview release must not require {needle}") + raise AssertionError(f"unexpected desktop release contract token: {needle}") + + +def workflow_step(text: str, step_name: str) -> str: + marker = f"- name: {step_name}" + if marker not in text: + raise AssertionError(f"missing workflow step: {step_name}") + after = text.split(marker, 1)[1] + for terminator in ("\n - name:", "\n upload-release:"): + if terminator in after: + after = after.split(terminator, 1)[0] + return after + + +def verify_macos_signing_contracts(text: str) -> None: + pr_step = workflow_step(text, "Build unsigned desktop preview bundles") + assert_contains(pr_step, "if: github.event_name == 'pull_request'") + assert_contains(pr_step, "npm run build -- --bundles ${{ matrix.bundles }} --no-sign") + for forbidden in ( + "secrets.", + "APPLE_CERTIFICATE", + "APPLE_ID", + "APPLE_PASSWORD", + "APPLE_TEAM_ID", + "KEYCHAIN_PASSWORD", + ): + assert_absent(pr_step, forbidden) + + resolve_step = workflow_step(text, "Resolve macOS signing mode") + assert_contains(resolve_step, "id: macos-signing") + assert_contains(resolve_step, "if: github.event_name != 'pull_request' && runner.os == 'macOS'") + assert_contains(resolve_step, "scripts/desktop_macos_signing.py resolve-mode") + for var in desktop_macos_signing.ALL_APPLE_VARS: + assert_contains(resolve_step, f"{var}: ${{{{ secrets.{var} }}}}") + + build_step = workflow_step(text, "Build macOS release bundles") + assert_contains(build_step, "if: github.event_name != 'pull_request' && runner.os == 'macOS'") + assert_absent(build_step, "--no-sign") + assert_contains(build_step, "scripts/desktop_macos_signing.py build") + assert_contains(build_step, "--bundles ${{ matrix.bundles }}") + assert_contains(build_step, '--expected-mode "${EXPECTED_SIGNING_MODE}"') + assert_contains(build_step, "EXPECTED_SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }}") + for var in desktop_macos_signing.ALL_APPLE_VARS: + assert_contains(build_step, f"{var}: ${{{{ secrets.{var} }}}}") + + notarize_step = workflow_step(text, "Notarize macOS disk image") + assert_contains( + notarize_step, + "if: github.event_name != 'pull_request' && runner.os == 'macOS' " + "&& steps.macos-signing.outputs.signing-mode == 'developer_id'", + ) + assert_contains(notarize_step, "scripts/desktop_macos_signing.py notarize-dmg") + for var in desktop_macos_signing.NOTARIZATION_APPLE_SECRETS: + assert_contains(notarize_step, f"{var}: ${{{{ secrets.{var} }}}}") + + verify_step = workflow_step(text, "Verify macOS desktop bundles") + assert_contains(verify_step, "if: github.event_name != 'pull_request' && runner.os == 'macOS'") + assert_contains(verify_step, "SIGNING_MODE: ${{ steps.macos-signing.outputs.signing-mode }}") + assert_contains(verify_step, "scripts/desktop_macos_signing.py verify") + assert_contains(verify_step, '--signing-mode "${SIGNING_MODE}"') + assert_contains(verify_step, '--app "${app_path}"') + assert_contains(verify_step, '--dmg "${dmg_path}"') + + assert ( + text.index("- name: Resolve macOS signing mode") + < text.index("- name: Build macOS release bundles") + < text.index("- name: Notarize macOS disk image") + < text.index("- name: Verify macOS desktop bundles") + < text.index("- name: Collect macOS desktop bundles") + ) + + # Developer ID contract: all 5 core secrets -> developer_id, no ad-hoc identity, + # ephemeral KEYCHAIN_PASSWORD fallback, notarization + Gatekeeper + stapler checks. + dev_env = { + "APPLE_CERTIFICATE": "base64-p12", + "APPLE_CERTIFICATE_PASSWORD": "p12-password", + "APPLE_ID": "release@example.com", + "APPLE_PASSWORD": "app-specific-password", + "APPLE_TEAM_ID": "TEAM123456", + "APPLE_SIGNING_IDENTITY": "", + } + dev_res = desktop_macos_signing.resolve_apple_signing(dev_env) + assert dev_res.signing_mode == "developer_id" + assert dev_res.generated_keychain_password is True + assert dev_res.keychain_password + assert dev_res.signing_identity is None + dev_cfg = json.loads(desktop_macos_signing.tauri_build_config("0.5.4", "developer_id")) + assert dev_cfg == {"version": "0.5.4"} + sanitized_dev_env = desktop_macos_signing.prepare_build_env(dev_env, dev_res) + assert sanitized_dev_env["KEYCHAIN_PASSWORD"] == dev_res.keychain_password + assert "APPLE_SIGNING_IDENTITY" not in sanitized_dev_env + + app_path = Path("LoopX.app") + dmg_path = Path("LoopX_0.5.4_aarch64.dmg") + dev_checks = desktop_macos_signing.verification_commands("developer_id", app_path, dmg_path) + dev_joined = "\n".join(" ".join(c.argv) for c in dev_checks) + for required in ( + "codesign --verify --deep --strict --verbose=2 LoopX.app", + "codesign --display --verbose=4 LoopX.app", + "spctl --assess --type execute --verbose=4 LoopX.app", + "xcrun stapler validate LoopX.app", + "codesign --verify --verbose=2 LoopX_0.5.4_aarch64.dmg", + "spctl --assess --type open --context context:primary-signature --verbose=4 LoopX_0.5.4_aarch64.dmg", + "xcrun stapler validate LoopX_0.5.4_aarch64.dmg", + "hdiutil verify LoopX_0.5.4_aarch64.dmg", + ): + assert_contains(dev_joined, required) + assert any( + c.required_line_pattern == desktop_macos_signing.DEVELOPER_ID_AUTHORITY_PATTERN + for c in dev_checks + ) + + notarize_cmds = desktop_macos_signing.notarize_dmg_commands( + dmg_path, dev_env["APPLE_ID"], dev_env["APPLE_PASSWORD"], dev_env["APPLE_TEAM_ID"] + ) + assert notarize_cmds[0][:4] == ("xcrun", "notarytool", "submit", str(dmg_path)) + assert "--wait" in notarize_cmds[0] + assert notarize_cmds[1] == ("xcrun", "stapler", "staple", str(dmg_path)) + + # Ad-hoc contract: all 5 core secrets absent -> adhoc with signingIdentity="-". + adhoc_res = desktop_macos_signing.resolve_apple_signing({}) + assert adhoc_res.signing_mode == "adhoc" + adhoc_cfg = json.loads(desktop_macos_signing.tauri_build_config("0.5.4", "adhoc")) + assert adhoc_cfg == {"version": "0.5.4", "bundle": {"macOS": {"signingIdentity": "-"}}} + adhoc_checks = desktop_macos_signing.verification_commands("adhoc", app_path, dmg_path) + adhoc_joined = "\n".join(" ".join(c.argv) for c in adhoc_checks) + assert_contains(adhoc_joined, "codesign --verify --deep --strict --verbose=2 LoopX.app") + assert_contains(adhoc_joined, "codesign --display --verbose=4 LoopX.app") + assert_contains(adhoc_joined, "hdiutil verify LoopX_0.5.4_aarch64.dmg") + assert_absent(adhoc_joined, "notarytool") + assert_absent(adhoc_joined, "stapler") + assert_absent(adhoc_joined, "spctl") + assert any( + c.required_line_pattern == desktop_macos_signing.ADHOC_SIGNATURE_PATTERN + for c in adhoc_checks + ) + + # Partial configuration (1-4 of 5 core secrets) must fail closed. + partial_env = { + "APPLE_CERTIFICATE": "base64-p12", + "APPLE_TEAM_ID": "TEAM123456", + } + proc = subprocess.run( + [sys.executable, str(SIGNING_SCRIPT), "resolve-mode"], + env={"PATH": os.environ.get("PATH", ""), **partial_env}, + capture_output=True, + text=True, + check=False, + timeout=15, + ) + assert proc.returncode == 1 + assert "::error title=Incomplete Apple signing configuration::" in proc.stderr def main() -> int: @@ -39,13 +201,8 @@ def main() -> int: "github.event_name != 'pull_request'", "- name: Validate desktop release workflow\n if: github.event_name == 'pull_request'", 'npm run build -- --bundles ${{ matrix.bundles }} --no-sign', - 'npm run build -- --bundles ${{ matrix.bundles }}', 'RELEASE_TAG: ${{ steps.identity.outputs.release-tag }}', 'release_version="${RELEASE_TAG#v}"', - r'\"signingIdentity\":\"-\"', - 'codesign --verify --deep --strict --verbose=2', - "grep -q '^Signature=adhoc$'", - 'hdiutil verify', 'bundle/macos/LoopX.app', 'dist/desktop/LoopX.app.zip', 'Check out release workflow source', @@ -63,21 +220,7 @@ def main() -> int: ]: assert_contains(text, required) - signed_step = text.split("- name: Build integrity-signed macOS release bundles", 1)[1].split( - "- name:", 1 - )[0] - if "--no-sign" in signed_step: - raise AssertionError("integrity-signed macOS release build must not use --no-sign") - - for forbidden in [ - "APPLE_CERTIFICATE", - "APPLE_ID", - "KEYCHAIN_PASSWORD", - "notarytool", - "stapler", - "spctl", - ]: - assert_absent(text, forbidden) + verify_macos_signing_contracts(text) binary_upload = text.split("- name: Replace complete desktop binary set", 1)[1].split( "- name:", 1 diff --git a/scripts/desktop_macos_signing.py b/scripts/desktop_macos_signing.py new file mode 100644 index 0000000000..6f64455317 --- /dev/null +++ b/scripts/desktop_macos_signing.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Shared macOS Developer ID signing, notarization, and verification helper.""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import json +import os +from pathlib import Path +import re +import secrets +import shutil +import subprocess +import sys +import tarfile +from typing import Literal, Mapping, Sequence + + +SigningMode = Literal["developer_id", "adhoc"] + +CORE_APPLE_SECRETS: tuple[str, ...] = ( + "APPLE_CERTIFICATE", + "APPLE_CERTIFICATE_PASSWORD", + "APPLE_ID", + "APPLE_PASSWORD", + "APPLE_TEAM_ID", +) +NOTARIZATION_APPLE_SECRETS: tuple[str, ...] = ( + "APPLE_ID", + "APPLE_PASSWORD", + "APPLE_TEAM_ID", +) +OPTIONAL_APPLE_VARS: tuple[str, ...] = ( + "KEYCHAIN_PASSWORD", + "APPLE_SIGNING_IDENTITY", +) +ALL_APPLE_VARS: tuple[str, ...] = CORE_APPLE_SECRETS + OPTIONAL_APPLE_VARS + +SEMVER_RE = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+([+-][0-9A-Za-z.-]+)?$") +DEVELOPER_ID_AUTHORITY_PATTERN = r"^Authority=Developer ID Application:" +ADHOC_SIGNATURE_PATTERN = r"^Signature=adhoc$" + + +class AppleSigningConfigError(ValueError): + """Raised when Apple signing or notarization credentials are incomplete.""" + + +class DesktopMacOSSigningError(RuntimeError): + """Raised when macOS signing, notarization, or verification fails.""" + + +@dataclass(frozen=True) +class AppleSigningResolution: + """Resolved macOS signing configuration derived from environment secrets.""" + + signing_mode: SigningMode + present_core_secrets: tuple[str, ...] + missing_core_secrets: tuple[str, ...] + keychain_password: str | None = None + generated_keychain_password: bool = False + signing_identity: str | None = None + + +@dataclass(frozen=True) +class VerificationCheck: + """Single external command check for a macOS bundle or disk image.""" + + argv: tuple[str, ...] + combine_output: bool = False + required_line_pattern: str | None = None + + +def resolve_apple_signing( + env: Mapping[str, str] | None = None, +) -> AppleSigningResolution: + """Classify Apple signing mode from the 5 core secrets plus optional vars.""" + + source = os.environ if env is None else env + present = tuple(name for name in CORE_APPLE_SECRETS if source.get(name, "").strip()) + missing = tuple(name for name in CORE_APPLE_SECRETS if not source.get(name, "").strip()) + + if not present: + return AppleSigningResolution( + signing_mode="adhoc", + present_core_secrets=present, + missing_core_secrets=missing, + ) + + if missing: + raise AppleSigningConfigError( + "Apple Developer ID signing requires all 5 core secrets " + f"({', '.join(CORE_APPLE_SECRETS)}); " + f"present=[{', '.join(present)}], missing=[{', '.join(missing)}]" + ) + + raw_keychain_password = source.get("KEYCHAIN_PASSWORD", "") + if raw_keychain_password.strip(): + keychain_password = raw_keychain_password + generated_keychain_password = False + else: + keychain_password = secrets.token_urlsafe(32) + generated_keychain_password = True + + raw_identity = source.get("APPLE_SIGNING_IDENTITY", "").strip() + signing_identity = raw_identity if raw_identity else None + + return AppleSigningResolution( + signing_mode="developer_id", + present_core_secrets=present, + missing_core_secrets=missing, + keychain_password=keychain_password, + generated_keychain_password=generated_keychain_password, + signing_identity=signing_identity, + ) + + +def tauri_build_config( + version: str, + signing_mode: SigningMode, + *, + create_updater_artifacts: bool = False, +) -> str: + """Build the Tauri `--config` JSON payload for the resolved signing mode.""" + + if not SEMVER_RE.fullmatch(version): + raise AppleSigningConfigError( + f"Invalid desktop release version {version!r}; expected semantic version" + ) + bundle: dict[str, object] = {} + if create_updater_artifacts: + bundle["createUpdaterArtifacts"] = True + if signing_mode == "adhoc": + bundle["macOS"] = {"signingIdentity": "-"} + elif signing_mode != "developer_id": + raise AppleSigningConfigError(f"Unsupported signing mode: {signing_mode!r}") + + payload: dict[str, object] = {"version": version} + if bundle: + payload["bundle"] = bundle + return json.dumps(payload, separators=(",", ":")) + + +def prepare_build_env( + base_env: Mapping[str, str], + resolution: AppleSigningResolution, +) -> dict[str, str]: + """Return a sanitized subprocess environment for `tauri build`.""" + + env = dict(base_env) + if resolution.signing_mode == "adhoc": + for name in ALL_APPLE_VARS: + env.pop(name, None) + return env + + if not resolution.keychain_password: + raise AppleSigningConfigError("KEYCHAIN_PASSWORD could not be resolved") + env["KEYCHAIN_PASSWORD"] = resolution.keychain_password + if resolution.signing_identity: + env["APPLE_SIGNING_IDENTITY"] = resolution.signing_identity + else: + # Unset empty GitHub Actions secret placeholders so Tauri auto-detects + # the Developer ID certificate imported from APPLE_CERTIFICATE. + env.pop("APPLE_SIGNING_IDENTITY", None) + return env + + +def notarize_dmg_commands( + dmg_path: Path, + apple_id: str, + apple_password: str, + apple_team_id: str, +) -> tuple[tuple[str, ...], ...]: + """Return the `notarytool` submission and `stapler` commands for a DMG.""" + + target = str(dmg_path) + return ( + ( + "xcrun", + "notarytool", + "submit", + target, + "--apple-id", + apple_id, + "--password", + apple_password, + "--team-id", + apple_team_id, + "--wait", + ), + ("xcrun", "stapler", "staple", target), + ) + + +def verification_commands( + signing_mode: SigningMode, + app_path: Path, + dmg_path: Path | None = None, +) -> tuple[VerificationCheck, ...]: + """Build the ordered codesign/Gatekeeper/stapler/disk-image checks.""" + + app_str = str(app_path) + if signing_mode == "developer_id": + checks: list[VerificationCheck] = [ + VerificationCheck(("codesign", "--verify", "--deep", "--strict", "--verbose=2", app_str)), + VerificationCheck( + ("codesign", "--display", "--verbose=4", app_str), + combine_output=True, + required_line_pattern=DEVELOPER_ID_AUTHORITY_PATTERN, + ), + VerificationCheck(("spctl", "--assess", "--type", "execute", "--verbose=4", app_str)), + VerificationCheck(("xcrun", "stapler", "validate", app_str)), + ] + if dmg_path is not None: + dmg_str = str(dmg_path) + checks.extend( + [ + VerificationCheck(("codesign", "--verify", "--verbose=2", dmg_str)), + VerificationCheck( + ( + "spctl", + "--assess", + "--type", + "open", + "--context", + "context:primary-signature", + "--verbose=4", + dmg_str, + ) + ), + VerificationCheck(("xcrun", "stapler", "validate", dmg_str)), + VerificationCheck(("hdiutil", "verify", dmg_str)), + ] + ) + return tuple(checks) + + if signing_mode == "adhoc": + checks = [ + VerificationCheck(("codesign", "--verify", "--deep", "--strict", "--verbose=2", app_str)), + VerificationCheck( + ("codesign", "--display", "--verbose=4", app_str), + combine_output=True, + required_line_pattern=ADHOC_SIGNATURE_PATTERN, + ), + ] + if dmg_path is not None: + checks.append(VerificationCheck(("hdiutil", "verify", str(dmg_path)))) + return tuple(checks) + + raise AppleSigningConfigError(f"Unsupported signing mode: {signing_mode!r}") + + +def verify_updater_tar_gz(tar_gz_path: Path, signing_mode: SigningMode) -> None: + """Verify updater archive presence, `.sig` pair, signature seal, and ticket.""" + + if not tar_gz_path.is_file() or tar_gz_path.stat().st_size <= 0: + raise DesktopMacOSSigningError(f"Updater archive is missing or empty: {tar_gz_path}") + sig_path = Path(f"{tar_gz_path}.sig") + if not sig_path.is_file() or sig_path.stat().st_size <= 0: + raise DesktopMacOSSigningError(f"Updater signature is missing or empty: {sig_path}") + + with tarfile.open(tar_gz_path, "r:gz") as archive: + members = {member.name.lstrip("./") for member in archive.getmembers()} + + required = { + "LoopX.app/Contents/Info.plist", + "LoopX.app/Contents/_CodeSignature/CodeResources", + } + if signing_mode == "developer_id": + required.add("LoopX.app/Contents/CodeResources") + + missing = sorted(required - members) + if missing: + raise DesktopMacOSSigningError( + f"Updater archive {tar_gz_path} is missing expected bundle files for {signing_mode}: {missing}" + ) + + +def _resolve_single_dmg(dmg: Path | None, dmg_dir: Path | None) -> Path | None: + if dmg is not None: + if not dmg.is_file(): + raise DesktopMacOSSigningError(f"macOS DMG does not exist: {dmg}") + return dmg + if dmg_dir is None: + return None + matches = sorted(dmg_dir.glob("*.dmg")) + if len(matches) != 1: + raise DesktopMacOSSigningError( + f"Expected exactly 1 DMG in {dmg_dir}, found {len(matches)}" + ) + return matches[0] + + +def _redact_argv(argv: Sequence[str]) -> str: + redacted: list[str] = [] + redact_next = False + for token in argv: + if redact_next: + redacted.append("***") + redact_next = False + continue + redacted.append(token) + if token in {"--password"}: + redact_next = True + return " ".join(redacted) + + +def _run_checked( + argv: Sequence[str], + *, + cwd: Path | None = None, + env: Mapping[str, str] | None = None, + combine_output: bool = False, +) -> str: + run_env = dict(env) if env is not None else None + if combine_output: + completed_text = subprocess.run( + list(argv), + cwd=cwd, + env=run_env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + if completed_text.stdout: + sys.stdout.write(completed_text.stdout) + if completed_text.returncode != 0: + raise DesktopMacOSSigningError( + f"Command exited {completed_text.returncode}: {_redact_argv(argv)}" + ) + return completed_text.stdout + + completed = subprocess.run( + list(argv), + cwd=cwd, + env=run_env, + check=False, + ) + if completed.returncode != 0: + raise DesktopMacOSSigningError( + f"Command exited {completed.returncode}: {_redact_argv(argv)}" + ) + return "" + + +def cmd_resolve_mode(args: argparse.Namespace) -> int: + resolution = resolve_apple_signing(os.environ) + output_path = args.github_output or os.environ.get("GITHUB_OUTPUT") + if output_path: + with Path(output_path).open("a", encoding="utf-8") as stream: + stream.write(f"signing-mode={resolution.signing_mode}\n") + print(f"signing_mode={resolution.signing_mode}") + return 0 + + +def cmd_build(args: argparse.Namespace) -> int: + resolution = resolve_apple_signing(os.environ) + if args.expected_mode and resolution.signing_mode != args.expected_mode: + raise AppleSigningConfigError( + f"Resolved signing_mode={resolution.signing_mode!r} does not match expected {args.expected_mode!r}" + ) + if resolution.generated_keychain_password and os.environ.get("GITHUB_ACTIONS") == "true": + print(f"::add-mask::{resolution.keychain_password}", flush=True) + + config_json = tauri_build_config( + args.version, + resolution.signing_mode, + create_updater_artifacts=args.create_updater_artifacts, + ) + build_env = prepare_build_env(os.environ, resolution) + npm_bin = shutil.which("npm") or "npm" + cmd = [ + npm_bin, + "run", + "build", + "--", + "--bundles", + *args.bundles, + "--config", + config_json, + ] + print(f"macOS build signing_mode={resolution.signing_mode} config={config_json}", flush=True) + _run_checked(cmd, cwd=args.working_directory, env=build_env) + return 0 + + +def cmd_notarize_dmg(args: argparse.Namespace) -> int: + missing = [name for name in NOTARIZATION_APPLE_SECRETS if not os.environ.get(name, "").strip()] + if missing: + raise AppleSigningConfigError( + f"DMG notarization requires {', '.join(NOTARIZATION_APPLE_SECRETS)}; missing={missing}" + ) + dmg_path = _resolve_single_dmg(args.dmg, args.dmg_dir) + if dmg_path is None: + raise AppleSigningConfigError("notarize-dmg requires --dmg or --dmg-dir") + + commands = notarize_dmg_commands( + dmg_path, + os.environ["APPLE_ID"], + os.environ["APPLE_PASSWORD"], + os.environ["APPLE_TEAM_ID"], + ) + for argv in commands: + _run_checked(argv) + return 0 + + +def cmd_verify(args: argparse.Namespace) -> int: + if not args.app.is_dir(): + raise DesktopMacOSSigningError(f"macOS app bundle does not exist: {args.app}") + dmg_path = _resolve_single_dmg(args.dmg, args.dmg_dir) + checks = verification_commands(args.signing_mode, args.app, dmg_path) + for check in checks: + output = _run_checked(check.argv, combine_output=check.combine_output) + if check.required_line_pattern is not None: + pattern = re.compile(check.required_line_pattern, re.MULTILINE) + if not pattern.search(output): + raise DesktopMacOSSigningError( + f"Output of {_redact_argv(check.argv)} did not match {check.required_line_pattern!r}" + ) + if args.updater_tar_gz is not None: + verify_updater_tar_gz(args.updater_tar_gz, args.signing_mode) + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + subparsers = parser.add_subparsers(dest="command", required=True) + + resolve_cmd = subparsers.add_parser("resolve-mode") + resolve_cmd.add_argument("--github-output", type=Path, default=None) + + build_cmd = subparsers.add_parser("build") + build_cmd.add_argument("--version", required=True) + build_cmd.add_argument("--bundles", nargs="+", required=True) + build_cmd.add_argument("--create-updater-artifacts", action="store_true") + build_cmd.add_argument( + "--expected-mode", + choices=("developer_id", "adhoc"), + default=None, + ) + build_cmd.add_argument("--working-directory", type=Path, default=None) + + notarize_cmd = subparsers.add_parser("notarize-dmg") + notarize_cmd.add_argument("--dmg", type=Path, default=None) + notarize_cmd.add_argument("--dmg-dir", type=Path, default=None) + + verify_cmd = subparsers.add_parser("verify") + verify_cmd.add_argument( + "--signing-mode", + choices=("developer_id", "adhoc"), + required=True, + ) + verify_cmd.add_argument("--app", type=Path, required=True) + verify_cmd.add_argument("--dmg", type=Path, default=None) + verify_cmd.add_argument("--dmg-dir", type=Path, default=None) + verify_cmd.add_argument("--updater-tar-gz", type=Path, default=None) + + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + try: + if args.command == "resolve-mode": + return cmd_resolve_mode(args) + if args.command == "build": + return cmd_build(args) + if args.command == "notarize-dmg": + return cmd_notarize_dmg(args) + if args.command == "verify": + return cmd_verify(args) + except AppleSigningConfigError as exc: + print(f"::error title=Incomplete Apple signing configuration::{exc}", file=sys.stderr) + return 1 + except DesktopMacOSSigningError as exc: + print(f"::error title=macOS signing or verification failed::{exc}", file=sys.stderr) + return 1 + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/desktop/test_desktop_signing_workflow.py b/tests/desktop/test_desktop_signing_workflow.py new file mode 100644 index 0000000000..18e28208dc --- /dev/null +++ b/tests/desktop/test_desktop_signing_workflow.py @@ -0,0 +1,572 @@ +"""Unit and workflow-structure tests for macOS desktop signing and notarization.""" + +from __future__ import annotations + +import importlib +import importlib.util +from itertools import combinations +import json +import os +from pathlib import Path +import stat +import subprocess +import sys +import tarfile +import tempfile +from types import ModuleType +import unittest + + +REPO_ROOT = Path(__file__).resolve().parents[2] +SIGNING_SCRIPT = REPO_ROOT / "scripts" / "desktop_macos_signing.py" +RELEASE_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "desktop-release-artifacts.yml" +UPDATER_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "desktop-updater.yml" + + +def load_signing_module() -> ModuleType: + spec = importlib.util.spec_from_file_location("desktop_macos_signing", SIGNING_SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +signing = load_signing_module() + + +def full_core_env(**overrides: str) -> dict[str, str]: + env = { + "APPLE_CERTIFICATE": "cGtjczEyLWRhdGE=", + "APPLE_CERTIFICATE_PASSWORD": "secret-p12-password", + "APPLE_ID": "ci-signer@example.com", + "APPLE_PASSWORD": "abcd-efgh-ijkl-mnop", + "APPLE_TEAM_ID": "ABCDE12345", + } + env.update(overrides) + return env + + +def extract_job_block(workflow_text: str, job_name: str) -> str: + marker = f"\n {job_name}:\n" + if marker not in workflow_text: + raise AssertionError(f"missing job {job_name!r}") + rest = workflow_text.split(marker, 1)[1] + lines = rest.splitlines() + collected: list[str] = [] + for line in lines: + if line and not line.startswith(" ") and line.startswith(" ") and line.rstrip().endswith(":"): + break + collected.append(line) + return "\n".join(collected) + + +def extract_steps(job_block: str) -> list[dict[str, str]]: + lines = job_block.splitlines() + steps: list[dict[str, str]] = [] + current: list[str] | None = None + in_steps = False + for line in lines: + if line == " steps:": + in_steps = True + continue + if not in_steps: + continue + if line.startswith(" - "): + if current is not None: + steps.append(_parse_step_block(current)) + current = [line] + elif current is not None: + current.append(line) + if current is not None: + steps.append(_parse_step_block(current)) + return steps + + +def _parse_step_block(lines: list[str]) -> dict[str, str]: + body = "\n".join(lines) + name = "" + for line in lines: + stripped = line.strip() + if stripped.startswith("- name:"): + name = stripped.split(":", 1)[1].strip() + break + if stripped.startswith("name:"): + name = stripped.split(":", 1)[1].strip() + break + return {"name": name, "body": body} + + +class MacOSSigningHelperTests(unittest.TestCase): + def test_all_core_secrets_absent_resolves_to_adhoc(self) -> None: + for env in ({}, {name: " \n" for name in signing.CORE_APPLE_SECRETS}): + with self.subTest(env=env): + resolved = signing.resolve_apple_signing(env) + self.assertEqual(resolved.signing_mode, "adhoc") + self.assertEqual(resolved.present_core_secrets, ()) + self.assertEqual(resolved.missing_core_secrets, signing.CORE_APPLE_SECRETS) + self.assertIsNone(resolved.keychain_password) + self.assertFalse(resolved.generated_keychain_password) + self.assertIsNone(resolved.signing_identity) + + def test_all_core_secrets_present_resolves_to_developer_id_with_ephemeral_keychain_password( + self, + ) -> None: + resolved = signing.resolve_apple_signing(full_core_env()) + self.assertEqual(resolved.signing_mode, "developer_id") + self.assertEqual(resolved.present_core_secrets, signing.CORE_APPLE_SECRETS) + self.assertEqual(resolved.missing_core_secrets, ()) + self.assertTrue(resolved.generated_keychain_password) + self.assertIsNotNone(resolved.keychain_password) + self.assertGreaterEqual(len(resolved.keychain_password), 32) + self.assertIsNone(resolved.signing_identity) + + second = signing.resolve_apple_signing(full_core_env(KEYCHAIN_PASSWORD=" ")) + self.assertTrue(second.generated_keychain_password) + self.assertNotEqual(resolved.keychain_password, second.keychain_password) + + def test_explicit_optional_keychain_password_and_signing_identity_are_preserved( + self, + ) -> None: + resolved = signing.resolve_apple_signing( + full_core_env( + KEYCHAIN_PASSWORD="explicit-keychain-pass", + APPLE_SIGNING_IDENTITY=" Developer ID Application: LoopX (ABCDE12345) ", + ) + ) + self.assertEqual(resolved.signing_mode, "developer_id") + self.assertFalse(resolved.generated_keychain_password) + self.assertEqual(resolved.keychain_password, "explicit-keychain-pass") + self.assertEqual( + resolved.signing_identity, + "Developer ID Application: LoopX (ABCDE12345)", + ) + + def test_partial_core_secrets_fail_fast_without_leaking_values(self) -> None: + base = full_core_env() + for count in range(1, len(signing.CORE_APPLE_SECRETS)): + for present_names in combinations(signing.CORE_APPLE_SECRETS, count): + env = {name: base[name] for name in present_names} + with self.subTest(present=present_names): + with self.assertRaises(signing.AppleSigningConfigError) as ctx: + signing.resolve_apple_signing(env) + message = str(ctx.exception) + for name in present_names: + self.assertIn(name, message) + for secret_val in base.values(): + self.assertNotIn(secret_val, message) + + whitespace_env = full_core_env(APPLE_TEAM_ID=" ") + with self.assertRaises(signing.AppleSigningConfigError) as ctx: + signing.resolve_apple_signing(whitespace_env) + self.assertIn("missing=[APPLE_TEAM_ID]", str(ctx.exception)) + + def test_tauri_build_config_for_both_modes_and_updater(self) -> None: + self.assertEqual( + json.loads(signing.tauri_build_config("2.4.0", "developer_id")), + {"version": "2.4.0"}, + ) + self.assertEqual( + json.loads( + signing.tauri_build_config( + "0.0.0-main.123.1", + "developer_id", + create_updater_artifacts=True, + ) + ), + {"version": "0.0.0-main.123.1", "bundle": {"createUpdaterArtifacts": True}}, + ) + self.assertEqual( + json.loads(signing.tauri_build_config("2.4.0", "adhoc")), + {"version": "2.4.0", "bundle": {"macOS": {"signingIdentity": "-"}}}, + ) + self.assertEqual( + json.loads( + signing.tauri_build_config( + "2.4.0", "adhoc", create_updater_artifacts=True + ) + ), + { + "version": "2.4.0", + "bundle": {"createUpdaterArtifacts": True, "macOS": {"signingIdentity": "-"}}, + }, + ) + for bad in ("v2.4.0", "preview-1234567890ab", "2.4.0;echo"): + with self.assertRaises(signing.AppleSigningConfigError): + signing.tauri_build_config(bad, "adhoc") + + def test_prepare_build_env_sanitizes_adhoc_and_empty_identity(self) -> None: + adhoc_res = signing.resolve_apple_signing({}) + adhoc_env = signing.prepare_build_env( + {"PATH": "/usr/bin", "APPLE_SIGNING_IDENTITY": "", "KEYCHAIN_PASSWORD": "old"}, + adhoc_res, + ) + for var in signing.ALL_APPLE_VARS: + self.assertNotIn(var, adhoc_env) + + dev_env_input = full_core_env(APPLE_SIGNING_IDENTITY="", PATH="/usr/bin") + dev_res = signing.resolve_apple_signing(dev_env_input) + dev_env = signing.prepare_build_env(dev_env_input, dev_res) + self.assertEqual(dev_env["KEYCHAIN_PASSWORD"], dev_res.keychain_password) + self.assertNotIn("APPLE_SIGNING_IDENTITY", dev_env) + for var in signing.CORE_APPLE_SECRETS: + self.assertEqual(dev_env[var], dev_env_input[var]) + + +class MacOSSigningCLITests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.bin_dir = self.root / "bin" + self.bin_dir.mkdir() + + def _write_stub(self, name: str, script: str) -> Path: + path = self.bin_dir / name + path.write_text(f"#!/bin/sh\nset -eu\n{script}\n", encoding="utf-8") + path.chmod(path.stat().st_mode | stat.S_IXUSR) + return path + + def _run_cli(self, args: list[str], env: dict[str, str]) -> subprocess.CompletedProcess[str]: + merged = { + "PATH": f"{self.bin_dir}{os.pathsep}{os.environ.get('PATH', '')}", + **env, + } + return subprocess.run( + [sys.executable, str(SIGNING_SCRIPT), *args], + env=merged, + capture_output=True, + text=True, + check=False, + timeout=20, + ) + + def test_resolve_mode_cli_outputs_and_fails_on_partial(self) -> None: + github_output = self.root / "github_output.txt" + res_adhoc = self._run_cli( + ["resolve-mode", "--github-output", str(github_output)], + {}, + ) + self.assertEqual(res_adhoc.returncode, 0, res_adhoc.stderr) + self.assertEqual(github_output.read_text(encoding="utf-8"), "signing-mode=adhoc\n") + + github_output.unlink() + res_dev = self._run_cli( + ["resolve-mode", "--github-output", str(github_output)], + full_core_env(), + ) + self.assertEqual(res_dev.returncode, 0, res_dev.stderr) + self.assertEqual( + github_output.read_text(encoding="utf-8"), + "signing-mode=developer_id\n", + ) + + res_partial = self._run_cli( + ["resolve-mode", "--github-output", str(github_output)], + {"APPLE_ID": "ci@example.com", "APPLE_TEAM_ID": "TEAM123456"}, + ) + self.assertEqual(res_partial.returncode, 1) + self.assertIn("::error title=Incomplete Apple signing configuration::", res_partial.stderr) + self.assertNotIn("ci@example.com", res_partial.stderr) + + def test_build_cli_masks_generated_keychain_password_and_invokes_npm(self) -> None: + captured = self.root / "npm_captured.json" + npm_stub = self.bin_dir / "npm" + npm_stub.write_text( + f"#!{sys.executable}\n" + "import json, os, sys\n" + "with open(os.environ['LOOPX_TEST_CAPTURED'], 'w', encoding='utf-8') as fh:\n" + " json.dump({\n" + " 'argv': sys.argv[1:],\n" + " 'keychain_password': os.environ.get('KEYCHAIN_PASSWORD'),\n" + " 'apple_signing_identity': os.environ.get('APPLE_SIGNING_IDENTITY'),\n" + " 'apple_id': os.environ.get('APPLE_ID'),\n" + " }, fh)\n", + encoding="utf-8", + ) + npm_stub.chmod(npm_stub.stat().st_mode | stat.S_IXUSR) + res = self._run_cli( + [ + "build", + "--version", + "2.4.0", + "--bundles", + "app", + "--create-updater-artifacts", + "--expected-mode", + "developer_id", + ], + { + **full_core_env(APPLE_SIGNING_IDENTITY=""), + "GITHUB_ACTIONS": "true", + "LOOPX_TEST_CAPTURED": str(captured), + }, + ) + self.assertEqual(res.returncode, 0, res.stderr) + payload = json.loads(captured.read_text(encoding="utf-8")) + self.assertEqual( + payload["argv"], + [ + "run", + "build", + "--", + "--bundles", + "app", + "--config", + '{"version":"2.4.0","bundle":{"createUpdaterArtifacts":true}}', + ], + ) + self.assertTrue(payload["keychain_password"]) + self.assertIn(f"::add-mask::{payload['keychain_password']}", res.stdout) + self.assertIsNone(payload["apple_signing_identity"]) + + res_adhoc = self._run_cli( + ["build", "--version", "2.4.0", "--bundles", "dmg", "app", "--expected-mode", "adhoc"], + {"APPLE_SIGNING_IDENTITY": "", "LOOPX_TEST_CAPTURED": str(captured)}, + ) + self.assertEqual(res_adhoc.returncode, 0, res_adhoc.stderr) + adhoc_payload = json.loads(captured.read_text(encoding="utf-8")) + self.assertEqual( + adhoc_payload["argv"], + [ + "run", + "build", + "--", + "--bundles", + "dmg", + "app", + "--config", + '{"version":"2.4.0","bundle":{"macOS":{"signingIdentity":"-"}}}', + ], + ) + self.assertIsNone(adhoc_payload["keychain_password"]) + + def test_notarize_dmg_cli_runs_notarytool_and_stapler_and_redacts_errors(self) -> None: + log_file = self.root / "xcrun.log" + dmg = self.root / "LoopX_2.4.0_aarch64.dmg" + dmg.write_bytes(b"dmg") + self._write_stub( + "xcrun", + f'printf "%s\\n" "$*" >> {str(log_file)!r}', + ) + res = self._run_cli( + ["notarize-dmg", "--dmg", str(dmg)], + { + "APPLE_ID": "ci@example.com", + "APPLE_PASSWORD": "super-secret-password", + "APPLE_TEAM_ID": "TEAM123456", + }, + ) + self.assertEqual(res.returncode, 0, res.stderr) + lines = log_file.read_text(encoding="utf-8").splitlines() + self.assertEqual(len(lines), 2) + self.assertIn(f"notarytool submit {dmg}", lines[0]) + self.assertIn("--wait", lines[0]) + self.assertEqual(lines[1], f"stapler staple {dmg}") + + self._write_stub("xcrun", "exit 1") + failed = self._run_cli( + ["notarize-dmg", "--dmg", str(dmg)], + { + "APPLE_ID": "ci@example.com", + "APPLE_PASSWORD": "super-secret-password", + "APPLE_TEAM_ID": "TEAM123456", + }, + ) + self.assertEqual(failed.returncode, 1) + self.assertNotIn("super-secret-password", failed.stderr) + + def test_verify_cli_and_updater_tarball_contracts(self) -> None: + app = self.root / "LoopX.app" + (app / "Contents").mkdir(parents=True) + dmg = self.root / "LoopX_2.4.0_aarch64.dmg" + dmg.write_bytes(b"dmg") + tar_gz = self.root / "LoopX.app.tar.gz" + Path(f"{tar_gz}.sig").write_text("sig", encoding="utf-8") + + def build_updater_tar(include_ticket: bool) -> None: + with tarfile.open(tar_gz, "w:gz") as archive: + for rel in ( + ["LoopX.app/Contents/Info.plist", "LoopX.app/Contents/_CodeSignature/CodeResources"] + + (["LoopX.app/Contents/CodeResources"] if include_ticket else []) + ): + file_path = self.root / "src_tar" / rel + file_path.parent.mkdir(parents=True, exist_ok=True) + file_path.write_text("stub", encoding="utf-8") + archive.add(file_path, arcname=rel) + + log_file = self.root / "verify.log" + self._write_stub( + "codesign", + f'printf "codesign %s\\n" "$*" >> {str(log_file)!r}\n' + 'if [ "$1" = "--display" ]; then\n' + ' echo "Authority=Developer ID Application: LoopX (ABCDE12345)"\n' + "fi", + ) + self._write_stub("spctl", f'printf "spctl %s\\n" "$*" >> {str(log_file)!r}') + self._write_stub("xcrun", f'printf "xcrun %s\\n" "$*" >> {str(log_file)!r}') + self._write_stub("hdiutil", f'printf "hdiutil %s\\n" "$*" >> {str(log_file)!r}') + + build_updater_tar(include_ticket=False) + missing_ticket = self._run_cli( + [ + "verify", + "--signing-mode", + "developer_id", + "--app", + str(app), + "--dmg", + str(dmg), + "--updater-tar-gz", + str(tar_gz), + ], + {}, + ) + self.assertEqual(missing_ticket.returncode, 1) + self.assertIn("LoopX.app/Contents/CodeResources", missing_ticket.stderr) + + log_file.unlink() + build_updater_tar(include_ticket=True) + dev_ok = self._run_cli( + [ + "verify", + "--signing-mode", + "developer_id", + "--app", + str(app), + "--dmg", + str(dmg), + "--updater-tar-gz", + str(tar_gz), + ], + {}, + ) + self.assertEqual(dev_ok.returncode, 0, dev_ok.stderr) + dev_lines = log_file.read_text(encoding="utf-8").splitlines() + self.assertEqual( + dev_lines, + [ + f"codesign --verify --deep --strict --verbose=2 {app}", + f"codesign --display --verbose=4 {app}", + f"spctl --assess --type execute --verbose=4 {app}", + f"xcrun stapler validate {app}", + f"codesign --verify --verbose=2 {dmg}", + f"spctl --assess --type open --context context:primary-signature --verbose=4 {dmg}", + f"xcrun stapler validate {dmg}", + f"hdiutil verify {dmg}", + ], + ) + + # Ad-hoc verification rejects Developer ID display output and accepts Signature=adhoc. + bad_adhoc = self._run_cli( + ["verify", "--signing-mode", "adhoc", "--app", str(app)], + {}, + ) + self.assertEqual(bad_adhoc.returncode, 1) + + log_file.unlink() + self._write_stub( + "codesign", + f'printf "codesign %s\\n" "$*" >> {str(log_file)!r}\n' + 'if [ "$1" = "--display" ]; then\n' + ' echo "Signature=adhoc"\n' + "fi", + ) + adhoc_ok = self._run_cli( + ["verify", "--signing-mode", "adhoc", "--app", str(app), "--dmg", str(dmg)], + {}, + ) + self.assertEqual(adhoc_ok.returncode, 0, adhoc_ok.stderr) + self.assertEqual( + log_file.read_text(encoding="utf-8").splitlines(), + [ + f"codesign --verify --deep --strict --verbose=2 {app}", + f"codesign --display --verbose=4 {app}", + f"hdiutil verify {dmg}", + ], + ) + + +class WorkflowStructureTests(unittest.TestCase): + def test_release_workflow_yaml_structure_and_signing_order(self) -> None: + text = RELEASE_WORKFLOW.read_text(encoding="utf-8") + try: + yaml = importlib.import_module("yaml") + except ImportError: + yaml = None + if yaml is not None: + parsed = yaml.safe_load(text) + self.assertIn("build", parsed["jobs"]) + self.assertIn("upload-release", parsed["jobs"]) + + build_job = extract_job_block(text, "build") + steps = extract_steps(build_job) + names = [step["name"] for step in steps] + expected_order = [ + "Resolve macOS signing mode", + "Build unsigned desktop preview bundles", + "Build macOS release bundles", + "Notarize macOS disk image", + "Verify macOS desktop bundles", + "Collect macOS desktop bundles", + ] + positions = [names.index(name) for name in expected_order] + self.assertEqual(positions, sorted(positions)) + + by_name = {step["name"]: step["body"] for step in steps} + self.assertIn("if: github.event_name == 'pull_request'", by_name["Build unsigned desktop preview bundles"]) + self.assertIn("--no-sign", by_name["Build unsigned desktop preview bundles"]) + self.assertNotIn("secrets.", by_name["Build unsigned desktop preview bundles"]) + + self.assertIn("id: macos-signing", by_name["Resolve macOS signing mode"]) + self.assertIn("scripts/desktop_macos_signing.py resolve-mode", by_name["Resolve macOS signing mode"]) + + self.assertNotIn("--no-sign", by_name["Build macOS release bundles"]) + self.assertIn("scripts/desktop_macos_signing.py build", by_name["Build macOS release bundles"]) + self.assertIn( + "steps.macos-signing.outputs.signing-mode == 'developer_id'", + by_name["Notarize macOS disk image"], + ) + self.assertIn("scripts/desktop_macos_signing.py notarize-dmg", by_name["Notarize macOS disk image"]) + self.assertIn("scripts/desktop_macos_signing.py verify", by_name["Verify macOS desktop bundles"]) + for secret in signing.CORE_APPLE_SECRETS: + self.assertIn(f"secrets.{secret}", by_name["Resolve macOS signing mode"]) + self.assertIn(f"secrets.{secret}", by_name["Build macOS release bundles"]) + + def test_updater_workflow_yaml_structure_and_macos_verification(self) -> None: + text = UPDATER_WORKFLOW.read_text(encoding="utf-8") + try: + yaml = importlib.import_module("yaml") + except ImportError: + yaml = None + if yaml is not None: + parsed = yaml.safe_load(text) + self.assertIn("build-macos", parsed["jobs"]) + self.assertIn("build-windows", parsed["jobs"]) + + macos_job = extract_job_block(text, "build-macos") + steps = extract_steps(macos_job) + names = [step["name"] for step in steps] + expected_order = [ + "Resolve macOS signing mode", + "Build signed macOS App and exact bundled runtime", + "Verify macOS updater bundle", + "Collect native updater artifacts", + ] + positions = [names.index(name) for name in expected_order] + self.assertEqual(positions, sorted(positions)) + + by_name = {step["name"]: step["body"] for step in steps} + self.assertIn("id: macos-signing", by_name["Resolve macOS signing mode"]) + self.assertIn("scripts/desktop_macos_signing.py resolve-mode", by_name["Resolve macOS signing mode"]) + self.assertIn("scripts/desktop_macos_signing.py build", by_name["Build signed macOS App and exact bundled runtime"]) + self.assertIn("--create-updater-artifacts", by_name["Build signed macOS App and exact bundled runtime"]) + self.assertIn("scripts/desktop_macos_signing.py verify", by_name["Verify macOS updater bundle"]) + self.assertIn("--updater-tar-gz", by_name["Verify macOS updater bundle"]) + for secret in signing.ALL_APPLE_VARS: + self.assertIn(f"secrets.{secret}", by_name["Resolve macOS signing mode"]) + self.assertIn(f"secrets.{secret}", by_name["Build signed macOS App and exact bundled runtime"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/desktop/test_update_feed.py b/tests/desktop/test_update_feed.py index dcaa7bd67b..dc8e572844 100644 --- a/tests/desktop/test_update_feed.py +++ b/tests/desktop/test_update_feed.py @@ -126,8 +126,9 @@ def test_workflow_gates_the_signed_windows_build_and_checks_its_version(self): "- name: Build signed Windows NSIS updater installer", 1 )[1].split("- name: Collect native updater artifacts", 1)[0] self.assertIn("if: runner.os == 'macOS'", macos_step) - self.assertIn('\\"createUpdaterArtifacts\\":true', macos_step) - self.assertIn('\\"signingIdentity\\":\\"-\\"', macos_step) + self.assertIn("scripts/desktop_macos_signing.py build", macos_step) + self.assertIn("--create-updater-artifacts", macos_step) + self.assertIn("Verify macOS updater bundle", macos_step) self.assertIn("if: runner.os == 'Windows'", windows_step) self.assertIn('\\"createUpdaterArtifacts\\":true', windows_step) self.assertNotIn("signingIdentity", windows_step)