Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(desktop): Developer ID sign and notarize every macOS release build (#3005)

Call White0b0241fe7909
diff --git a/.github/workflows/desktop-package.yml b/.github/workflows/desktop-package.yml
index 9a5bc9764..c79d00433 100644
--- a/.github/workflows/desktop-package.yml
+++ b/.github/workflows/desktop-package.yml
@@ -1,7 +1,9 @@
name: desktop-self-contained-package
-# Manual artifacts retain optional Apple identity signing. Reusable TEST builds
-# use ad-hoc OS signatures. Updater keys come only from desktop-updater.
+# Release (tag) builds Developer ID sign and notarize every macOS layer and fail
+# without the complete Apple credential set; manual builds sign when the whole
+# set is configured and stay ad-hoc when none of it is. Apple and updater keys
+# come only from desktop-updater.
on:
workflow_dispatch:
inputs:
@@ -23,7 +25,7 @@ on:
type: boolean
default: false
release_tag:
- description: Canonical gh-vX.Y.ZrcN TEST tag
+ description: Canonical gh-vX.Y.ZrcN TEST or vX.Y.Z stable tag
required: true
type: string
@@ -121,6 +123,28 @@ jobs:
python scripts/desktop_updater.py configure \
--config desktop/tauri.release.conf.json --env-file "$GITHUB_ENV" ${args[@]+"${args[@]}"}
+ # Signing must exist before the Runtime is built: every Mach-O inside
+ # runtime.zip is signed before the archive and its hashes exist. A tag
+ # build fails here on a missing or partial credential set; a manual build
+ # accepts the complete set or none of it. Only identity, keychain, and
+ # notary key locations leave this step, under names Tauri never reads.
+ - name: Import Apple signing identity
+ if: runner.os == 'macOS'
+ env:
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
+ APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
+ APPLE_API_PRIVATE_KEY: ${{ secrets.APPLE_API_PRIVATE_KEY }}
+ run: >
+ python desktop/scripts/macos_signing.py import-identity
+ --release-tag "$RELEASE_TAG" --env-file "$GITHUB_ENV"
+ --work-dir "$RUNNER_TEMP/apple-signing"
+
+ # Reads AVIBE_CODESIGN_IDENTITY/KEYCHAIN when the identity was imported.
- name: Build verified private Runtime
run: >
python desktop/scripts/build-runtime-bundle.py
@@ -142,74 +166,6 @@ jobs:
shell: bash
run: rm -rf desktop/target/release/bundle
- # Secrets that are unset expand to the empty string, which tauri-bundler
- # would read as a present-but-empty certificate and fail on. Export each
- # variable only when its secret is non-empty, so absence keeps the
- # unsigned acceptance path exactly as before.
- - name: Export Apple signing credentials when configured
- if: runner.os == 'macOS' && inputs.release_tag == ''
- shell: bash
- env:
- APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
- APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
- APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
- APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
- APPLE_API_PRIVATE_KEY: ${{ secrets.APPLE_API_PRIVATE_KEY }}
- APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
- run: |
- set -eu
- # Validate the credential set atomically. Half-configured sets must
- # fail the build rather than silently produce a lesser artifact:
- # certificate without notarization credentials would ship
- # Developer-ID-signed but unnotarized; notarization credentials
- # without the certificate would submit the unsigned acceptance
- # build to Apple. All-or-nothing.
- # Any-set implies all-set within each group; then the two groups
- # must agree. A partially populated group is an operator error and
- # fails loudly instead of silently passing as "absent".
- cert_vars="APPLE_CERTIFICATE:$APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD:$APPLE_CERTIFICATE_PASSWORD"
- api_vars="APPLE_API_KEY:$APPLE_API_KEY APPLE_API_ISSUER:$APPLE_API_ISSUER APPLE_API_PRIVATE_KEY:$APPLE_API_PRIVATE_KEY"
- check_group() {
- group_name="$1"; shift
- set_count=0; total=0; missing=""
- for pair in "$@"; do
- name="${pair%%:*}"; value="${pair#*:}"
- total=$((total + 1))
- if [ -n "$value" ]; then set_count=$((set_count + 1)); else missing="$missing $name"; fi
- done
- if [ "$set_count" -gt 0 ] && [ "$set_count" -ne "$total" ]; then
- echo "::error::${group_name} credential group is partially configured; missing:$missing. Set the whole group, or none of it."
- exit 1
- fi
- [ "$set_count" -eq "$total" ]
- }
- if check_group "Apple signing" $cert_vars; then have_cert=1; else have_cert=0; fi
- if check_group "Apple notarization" $api_vars; then have_api=1; else have_api=0; fi
- if [ "$have_cert" != "$have_api" ]; then
- echo "::error::Apple credentials are half-configured: the signing group (APPLE_CERTIFICATE + APPLE_CERTIFICATE_PASSWORD) and the notarization group (APPLE_API_KEY + APPLE_API_ISSUER + APPLE_API_PRIVATE_KEY) must be set together or omitted together."
- exit 1
- fi
- if [ "$have_cert" = "1" ]; then
- echo "APPLE_CERTIFICATE=$APPLE_CERTIFICATE" >> "$GITHUB_ENV"
- echo "APPLE_CERTIFICATE_PASSWORD=$APPLE_CERTIFICATE_PASSWORD" >> "$GITHUB_ENV"
- if [ -n "${APPLE_SIGNING_IDENTITY:-}" ]; then
- echo "APPLE_SIGNING_IDENTITY=$APPLE_SIGNING_IDENTITY" >> "$GITHUB_ENV"
- fi
- # The ApiKey notarization auth needs the .p8 private key ON DISK at
- # APPLE_API_KEY_PATH; without it tauri-bundler falls back to
- # searching ./private_keys and $HOME, which the runner never has,
- # and notarization is skipped with only a warning.
- key_dir="$(mktemp -d)"
- key_file="$key_dir/AuthKey_${APPLE_API_KEY}.p8"
- printf '%s' "$APPLE_API_PRIVATE_KEY" > "$key_file"
- echo "APPLE_API_KEY=$APPLE_API_KEY" >> "$GITHUB_ENV"
- echo "APPLE_API_ISSUER=$APPLE_API_ISSUER" >> "$GITHUB_ENV"
- echo "APPLE_API_KEY_PATH=$key_file" >> "$GITHUB_ENV"
- echo "apple_signing=enabled" >> "$GITHUB_ENV"
- else
- echo "apple_signing=absent" >> "$GITHUB_ENV"
- fi
-
- name: Verify prepared Cua Driver provenance
if: runner.os == 'macOS'
run: >
@@ -227,16 +183,17 @@ jobs:
--features bundled-runtime
--config tauri.release.conf.json
- # Assert the inner app matches the credentials that were exported. NOTE
- # the layer boundary recorded here: this describes the .app INSIDE the
- # DMG only. The DMG image itself and the Mach-O binaries inside the
- # embedded runtime.zip are NOT signed/notarized by this workflow yet —
- # those layers are tracked in the distribution-signing-completion issue
- # and remain release gates.
- - name: Verify macOS app signature matches the signing path
+ # The .app inside the DMG. A signed build signs the Cua Driver helper and
+ # then the app with the Team's Developer ID, pins both code identities,
+ # and notarizes and staples the app. The smoke test, the DMG, and the
+ # updater archive all use this final app. Only a manual build without
+ # credentials reaches the ad-hoc branch.
+ - name: Sign macOS app
if: runner.os == 'macOS'
working-directory: desktop
shell: bash
+ env:
+ RELEASE_TAG: ${{ inputs.release_tag }}
run: |
set -eu
app="target/release/bundle/macos/Avibe.app"
@@ -247,27 +204,12 @@ jobs:
echo "stale Cua Driver copy found in Contents/MacOS" >&2
exit 1
}
- # Same detection as create-macos-dmg.sh: identity signatures print
- # `Signature size=...` and Authority lines (verbose=4); only ad-hoc
- # prints `Signature=adhoc`.
- adhoc="$(codesign -dv "$app" 2>&1 | sed -n 's/^Signature=adhoc$/p' || true)"
- authority="$(codesign -dv --verbose=4 "$app" 2>&1 | sed -n 's/^Authority=//p' | head -1 || true)"
if [ "${apple_signing:-absent}" = "enabled" ]; then
- if [ -n "$adhoc" ] || [ -z "$authority" ]; then
- echo "signing credentials were exported but Avibe.app is not identity-signed" >&2
- exit 1
- fi
- driver_authority="$(codesign -dv --verbose=4 "$driver" 2>&1 | sed -n 's/^Authority=//p' | head -1 || true)"
- app_team="$(codesign -dv --verbose=4 "$app" 2>&1 | sed -n 's/^TeamIdentifier=//p' | head -1 || true)"
- driver_team="$(codesign -dv --verbose=4 "$driver" 2>&1 | sed -n 's/^TeamIdentifier=//p' | head -1 || true)"
- if [ -z "$driver_authority" ] || [ "$driver_authority" != "$authority" ] \
- || [ -z "$app_team" ] || [ "$driver_team" != "$app_team" ]; then
- echo "Cua Driver helper does not match the outer app signing identity" >&2
- exit 1
- fi
- codesign --verify --strict "$driver"
- codesign --verify --deep --strict "$app"
- echo "signature_state=app-identity-signed (${authority})" >> "$GITHUB_ENV"
+ python scripts/macos_signing.py sign-app "$app"
+ python scripts/macos_signing.py notarize "$app"
+ elif [ -n "$RELEASE_TAG" ]; then
+ echo "release builds must be Developer ID signed" >&2
+ exit 1
else
# Sign nested code from the inside out. `--deep` is deliberately a
# verification option only; it must not choose what gets signed.
@@ -281,7 +223,6 @@ jobs:
codesign --verify --deep --strict "$app"
codesign -dv "$app" 2>&1 | grep -q '^Signature=adhoc$'
codesign -dv "$driver" 2>&1 | grep -q '^Signature=adhoc$'
- echo "signature_state=app-adhoc" >> "$GITHUB_ENV"
fi
APP_PATH="$app" python - <<'PY'
import os
@@ -359,6 +300,22 @@ jobs:
target/release/bundle/macos/Avibe.app
"target/release/bundle/dmg/Avibe_${{ inputs.version }}_${{ matrix.target }}.dmg"
+ # The DMG carries the stapled app; it is signed, notarized, and stapled
+ # itself, then the shipped shapes are checked the way Gatekeeper sees a
+ # download: staples, spctl verdicts, and both pinned code identities,
+ # including those of the app inside the mounted image.
+ - name: Sign and notarize macOS DMG
+ if: runner.os == 'macOS' && env.apple_signing == 'enabled'
+ working-directory: desktop
+ shell: bash
+ run: |
+ set -eu
+ dmg="target/release/bundle/dmg/Avibe_${{ inputs.version }}_${{ matrix.target }}.dmg"
+ python scripts/macos_signing.py sign-dmg "$dmg"
+ python scripts/macos_signing.py notarize "$dmg"
+ python scripts/macos_signing.py verify-release \
+ --app target/release/bundle/macos/Avibe.app --dmg "$dmg"
+
- name: Verify unsigned Windows installer
if: runner.os == 'Windows'
shell: pwsh
@@ -381,7 +338,9 @@ jobs:
[ "${#installers[@]}" -eq 1 ] || { echo "Expected exactly one installer" >&2; exit 1; }
driver_args=()
if [ "$RUNNER_OS" = "macOS" ]; then
- signing="${signature_state}"$'\ndmg-unsigned-unnotarized'
+ # Every signing step fails the job, so `enabled` here means the
+ # Runtime, app, and DMG were all signed, notarized, and verified.
+ if [ "${apple_signing:-absent}" = "enabled" ]; then signing=developer-id; else signing=ad-hoc; fi
driver_args=(
--prepared-driver "desktop/src-tauri/binaries/cua-driver-${{ matrix.target }}"
--driver "$driver_packaged_path"
@@ -389,7 +348,7 @@ jobs:
--driver-cdhash "$driver_packaged_cdhash"
)
else
- signing="installer-unsigned"
+ signing=unsigned
fi
python scripts/desktop_release.py record \
--version "$AVIBE_DESKTOP_VERSION" --target "$TARGET" --tag "$RELEASE_TAG" \
@@ -417,3 +376,7 @@ jobs:
path: desktop-package/
if-no-files-found: error
retention-days: 14
+
+ - name: Remove Apple signing material
+ if: always() && runner.os == 'macOS'
+ run: python desktop/scripts/macos_signing.py cleanup --work-dir "$RUNNER_TEMP/apple-signing"
diff --git a/.github/workflows/release_ai.yml b/.github/workflows/release_ai.yml
index c46a1fea2..644fcac95 100644
--- a/.github/workflows/release_ai.yml
+++ b/.github/workflows/release_ai.yml
@@ -77,8 +77,9 @@ jobs:
release_tag: ${{ needs.resolve-desktop-release.outputs.tag }}
updater_enabled: ${{ needs.resolve-desktop-release.outputs.updater_enabled == 'true' }}
# A called job's Environment secrets resolve empty unless the caller inherits
- # (actions/runner#4453). On this path the callee reads only the updater pair from
- # desktop-updater; Apple identities stay gated to manual dispatch.
+ # (actions/runner#4453). The callee reads the updater pair and, on macOS, the
+ # Apple set from desktop-updater: every tag build is Developer ID signed and
+ # notarized, and fails without the complete set.
secrets: inherit
resolve-show-runtime-ref:
diff --git a/desktop/README.md b/desktop/README.md
index 4bdabd5b3..e010e01c1 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -131,27 +131,93 @@ is not part of the application or private Runtime.
- Intel macOS (`x86_64-apple-darwin`);
- Windows x64 (`x86_64-pc-windows-msvc`).
-The manual macOS path is credential-gated; whichever state it produces is recorded
-in a target-qualified `.SIGNATURE` metadata file next to the artifact hashes:
-
-- **With repository secrets configured** (`APPLE_CERTIFICATE` +
- `APPLE_CERTIFICATE_PASSWORD`, `APPLE_API_KEY` + `APPLE_API_ISSUER` +
- `APPLE_API_PRIVATE_KEY`, optional `APPLE_SIGNING_IDENTITY`) the workflow
- Developer ID signs the .app, notarizes it through the App Store Connect
- API key, staples the ticket, and verifies the produced signature
- (`SIGNATURE: app-identity-signed`). The credential set must be complete —
- a partially populated set fails the build rather than silently producing a
- signed-but-unnotarized artifact.
-- **Without those secrets** the app inside the DMG is ad-hoc signed so macOS can
- verify its complete app/resource structure; it has no trusted developer
- identity. The outer DMG is unsigned and unnotarized.
-
-Two signing layers are deliberately NOT in this workflow yet and remain
-tracked release gates (see [#1976](https://github.com/avibe-bot/avibe/issues/1976)):
-signing/notarizing the outer DMG image itself, and signing the Mach-O
-binaries inside the embedded `runtime.zip` before archiving. Windows
-signing is likewise not yet implemented; NSIS artifacts remain unsigned
-acceptance builds. Windows ARM64 stays outside the current product gate.
+Windows NSIS artifacts remain unsigned acceptance builds; Authenticode is
+tracked in [#1976](https://github.com/avibe-bot/avibe/issues/1976). Windows ARM64
+stays outside the current product gate.
+
+### macOS signing and notarization
+
+Every macOS tag build (`gh-vX.Y.ZrcN` TEST and `vX.Y.Z` stable) is Developer ID
+signed and notarized, and fails rather than publish an ad-hoc app. The
+`desktop-updater` Environment holds the Apple set: `APPLE_CERTIFICATE` (base64
+`.p12`), `APPLE_CERTIFICATE_PASSWORD`, `APPLE_SIGNING_IDENTITY`, `APPLE_TEAM_ID`,
+`APPLE_API_KEY`, `APPLE_API_ISSUER`, and `APPLE_API_PRIVATE_KEY` (the raw `.p8`
+App Store Connect key). `scripts/macos_signing.py` owns every step. Tauri seals
+the bundle ad hoc and never receives Apple credentials, so it cannot sign or
+notarize on its own.
+
+1. **Credentials.** The identity goes into a temporary runner keychain and the
+ notary key into a `0600` file; both are deleted when the job ends. A tag build
+ with a missing or partial set fails before anything is built. A manual build
+ accepts the complete set or none of it. `APPLE_TEAM_ID` must equal the pinned
+ Team.
+2. **Runtime.** `build-runtime-bundle.py` signs every Mach-O of the private
+ Runtime with the hardened runtime and a secure timestamp after compiling its
+ bytecode, and before the startup probe, `runtime.zip`, its manifest, and the
+ tree hash. The notary service opens nested archives, so one unsigned binary
+ there rejects the whole app. Libraries carry no entitlements. Python and Node
+ are signed with fixed identifiers and the entitlements in `entitlements/`,
+ each of which records the evidence for every key it holds. An executable
+ without a reviewed identity fails the build. Signatures are embedded in each
+ file, so first-launch extraction is unchanged: the archive and tree hashes
+ simply cover the signed bytes.
+3. **App.** The Cua Driver helper and then Avibe.app are signed, the app is
+ notarized with `notarytool` through the API key, and its ticket is stapled.
+ The launch smoke test, the DMG, and the updater archive all use this final
+ app.
+4. **DMG.** The image is signed, notarized, and stapled, then checked the way a
+ download is: `stapler validate`, `spctl -a -t open --context
+ context:primary-signature`, `spctl -a -t exec` on the app, and both code
+ identities on the app inside the mounted image.
+
+**Code identity. These identifiers and the Team must never change.** macOS binds
+Accessibility and Screen Recording grants, and Keychain item approvals, to each
+program's designated requirement (DR). Signed releases keep them across updates
+only while the identifier and Team stay the same; changing either drops every
+user's grants. The signer compares each DR exactly with:
+
+```text
+designated => identifier "<identifier>" and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */ and certificate leaf[subject.OU] = "68B2SQ6YK3"
+```
+
+| Code | Identifier |
+| --- | --- |
+| Avibe.app | `bot.avibe.desktop` |
+| Cua Driver helper | `bot.avibe.desktop.cua-driver` |
+| Runtime Python | `bot.avibe.desktop.runtime.python` |
+| Runtime Node | `bot.avibe.desktop.runtime.node` |
+
+Ad-hoc builds had a per-build DR, so macOS treats the first signed build as a new
+program: users grant Computer Use permissions and Keychain access once more, and
+later signed updates keep them.
+
+**Entitlements.** The app keeps only microphone input (`src-tauri/Entitlements.plist`).
+Node needs a code-generation exception (`allow-jit` on Apple silicon,
+`allow-unsigned-executable-memory` on Intel, whose V8 does not use `MAP_JIT`) and
+`disable-library-validation`, because the Show Runtime and npm-installed Agent
+backends load native addons this Team did not sign. Python on Intel needs
+`allow-unsigned-executable-memory`: its libffi builds ctypes and cffi callbacks
+in writable executable memory without `MAP_JIT`, and without the entitlement the
+first callback hangs. Python on Apple silicon and the helper need none. GitHub's
+macOS runners enforce neither library validation nor the JIT restriction, so CI
+proves signing and notarization but not that entitlements are sufficient. Check
+an entitlement change on a Mac with System Integrity Protection enabled, for
+example by running the release-signed `python` and `node` from an extracted
+`runtime.zip` in a scratch directory, the Intel ones under Rosetta
+(`arch -x86_64`). An ad-hoc re-signed copy is no substitute: it needs
+`disable-library-validation` to load the Team-signed tree, and that changes what
+the hardened runtime allows.
+
+**Manual builds** (`workflow_dispatch`) sign and notarize the same way when the
+complete set is configured. With none of it, the app is ad-hoc signed, the
+Runtime keeps its upstream signatures, and the DMG is unsigned. The
+target-qualified `.SIGNATURE` metadata file records what was produced:
+
+| Build | `.SIGNATURE` layers |
+| --- | --- |
+| Signed (every tag build) | `runtime-developer-id-signed`, `app-developer-id-notarized-stapled`, `dmg-developer-id-notarized-stapled` |
+| Manual without credentials | `runtime-unsigned`, `app-adhoc`, `dmg-unsigned-unnotarized` |
+| Windows | `installer-unsigned` |
### Initial test distribution
@@ -162,35 +228,37 @@ All three native builds must succeed before the existing release job publishes
the GitHub prerelease. Official stable `vX.Y.Z` releases use the same desktop builder only when the G2
stable signing gate below is enabled; PyPI publication retains its sole finalizer.
-TEST builds never receive Apple or Windows signing credentials, even when the
-repository has them configured. The macOS app is ad-hoc signed, its outer DMG
-is unsigned/unnotarized, and the Windows NSIS installer is unsigned. Each raw
+The macOS app and DMG are Developer ID signed, notarized, and stapled as
+described above; the Windows NSIS installer is unsigned. Each raw
DMG/EXE download has a target-qualified `.SHA256SUMS`, `.SIGNATURE`,
`.SOURCE.json`, and `.runtime-manifest.json` alongside it. `SIGNATURE` describes
the verified layer; it is not a cryptographic signature. Hashes and source
metadata are checked before upload and downloaded desktop bytes are checked
-again before publication. New `.SOURCE.json` records use schema 2; every macOS
-record includes the pinned Cua Driver source archive, patch, tool snapshot,
-prepared binary, packaged binary, and code-signing provenance. The verifier
-still accepts already published schema-1 records as legacy input. A failed
+again before publication. New `.SOURCE.json` records use schema 3, which
+requires the signed macOS layers; every macOS record includes the pinned Cua
+Driver source archive, patch, tool snapshot, prepared binary, packaged binary,
+and code-signing provenance. The verifier still accepts already published
+schema-1 and schema-2 records, with their ad-hoc macOS layers, as legacy input.
+A failed
build or check leaves the release unpublished.
Existing asset bytes cannot be overwritten; a changed build requires a new rc.
Already-published releases cannot be retrofitted with missing desktop assets.
The manual workflow remains available for artifact-only builds: select a source
-ref and SemVer version in Actions. It retains optional Developer ID signing and
-notarization when its complete Apple secret set is configured. Actions artifacts
+ref and SemVer version in Actions. It signs and notarizes when the complete
+Apple set is configured and stays ad-hoc when none of it is. Actions artifacts
are retained for 14 days; automatic update metadata is disabled unless the G2 signing gate below is configured.
See [Desktop TEST installation](../docs/desktop-test-installation.md) for
-architecture selection, hash checks, app-specific Gatekeeper/SmartScreen
-approval, signed and manual upgrades that preserve `~/.avibe`, and removal.
+architecture selection, hash and Gatekeeper checks, SmartScreen approval,
+signed and manual upgrades that preserve `~/.avibe`, and removal.
Python, Avibe, Node, and npm are bundled; no separate installation is required.
Release operators need the existing `OPENAI_API_KEY` for AI notes, Actions
permissions to read runtime sources and write GitHub Releases, and all three
-hosted native runners. Apple/Windows signing credentials are not prerequisites
-for TEST publication. Do not create a tag or dispatch a release without owner
+hosted native runners, plus the complete Apple set in `desktop-updater`; a tag
+build without it fails. Windows signing credentials are not prerequisites. Do
+not create a tag or dispatch a release without owner
authorization. Start with a new rc on the approved source; wait for all runtime,
package, and desktop builds plus the sole `release_ai` finalizer. A rerun may
reuse identical bytes in a draft, but native rebuilds are not guaranteed to be
@@ -482,8 +550,8 @@ Security → Microphone. `tests/notarization_preflight.rs` pins both facts.
`cargo clippy -D warnings`, `cargo test`, `cargo build`. It does not bundle or
sign. `.github/workflows/desktop-package.yml` builds architecture-specific,
self-contained DMG and NSIS artifacts, both manually and as the reusable TEST
-build unit for `.github/workflows/release_ai.yml`. The manual signing policy and
-the deterministic TEST policy are described above. Native packaging and a real
+build unit for `.github/workflows/release_ai.yml`. Its signing policy is
+described above. Native packaging and a real
installation on each supported architecture remain separate acceptance gates
from unit/contract tests.
diff --git a/desktop/entitlements/cua-driver.plist b/desktop/entitlements/cua-driver.plist
new file mode 100644
index 000000000..d751b8463
--- /dev/null
+++ b/desktop/entitlements/cua-driver.plist
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- The Cua Driver helper (Contents/Helpers/cua-driver). Every entitlement
+ here must carry evidence that this process needs it; today there is
+ none.
+
+ The shell starts the driver in embedded mode, which never disclaims
+ responsibility: Avibe.app stays the responsible process, so macOS
+ attributes Accessibility, Screen Recording, and any Automation consent
+ to the app's code identity, not to this helper's entitlements.
+
+ Deliberately absent: com.apple.security.automation.apple-events and
+ com.apple.security.device.screen-capture, which upstream signs its
+ standalone driver with. Screen capture has no hardened-runtime
+ entitlement; TCC alone grants it. launch_app attaches an oapp Apple
+ Event to an NSWorkspace launch, and a hardened process with no
+ entitlements, even as its own responsible process, launches an app
+ with that event attached. AppleScript that set_value runs goes
+ through a separate /usr/bin/osascript process. -->
+</dict>
+</plist>
diff --git a/desktop/entitlements/runtime-node-aarch64.plist b/desktop/entitlements/runtime-node-aarch64.plist
new file mode 100644
index 000000000..b121af9e4
--- /dev/null
+++ b/desktop/entitlements/runtime-node-aarch64.plist
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- The private Runtime's Node.js on Apple silicon. Every entitlement here
+ must carry evidence that this process needs it.
+
+ allow-jit: V8 compiles JavaScript and WebAssembly into MAP_JIT memory.
+ Under the hardened runtime without it, Node aborts with SIGTRAP as
+ soon as a function is hot enough to compile, which includes npm. This
+ is the narrower of the two code-generation exceptions; Intel needs the
+ wider one (see runtime-node-x86_64.plist).
+
+ disable-library-validation: Node loads native addons that npm installs
+ after release, which this Team did not sign. The Show Runtime that
+ renders Show Pages requires rollup, lightningcss, and
+ @tailwindcss/oxide addons that their publishers ship ad-hoc signed;
+ with library validation on, each require() fails with "mapping process
+ and mapped file (non-platform) have different Team IDs". Agent
+ backends and their dependencies are installed by npm into the mutable
+ backend root the same way.
+
+ Deliberately absent: allow-unsigned-executable-memory,
+ disable-executable-page-protection, allow-dyld-environment-variables,
+ and get-task-allow, which upstream Node's own signature carries. -->
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.cs.disable-library-validation</key>
+ <true/>
+</dict>
+</plist>
diff --git a/desktop/entitlements/runtime-node-x86_64.plist b/desktop/entitlements/runtime-node-x86_64.plist
new file mode 100644
index 000000000..970818f09
--- /dev/null
+++ b/desktop/entitlements/runtime-node-x86_64.plist
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- The private Runtime's Node.js on Intel. Every entitlement here must
+ carry evidence that this process needs it.
+
+ allow-unsigned-executable-memory: on x86_64, V8 does not allocate its
+ code space with MAP_JIT; it flips ordinary pages to executable. Under
+ the hardened runtime that mprotect fails and Node aborts in
+ v8::base::OS::SetPermissions on its first compiled function, with
+ allow-jit alone too. This entitlement is the minimum that runs
+ JavaScript, WebAssembly, and npm. Apple silicon needs only allow-jit
+ (see runtime-node-aarch64.plist).
+
+ disable-library-validation: Node loads native addons that npm installs
+ after release, which this Team did not sign. The Show Runtime that
+ renders Show Pages requires rollup, lightningcss, and
+ @tailwindcss/oxide addons that their publishers ship unsigned or
+ ad-hoc signed; with library validation on, each require() fails with
+ "mapping process and mapped file (non-platform) have different Team
+ IDs". Agent backends and their dependencies are installed by npm into
+ the mutable backend root the same way.
+
+ Deliberately absent: disable-executable-page-protection,
+ allow-dyld-environment-variables, and get-task-allow, which upstream
+ Node's own signature carries. -->
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+ <key>com.apple.security.cs.disable-library-validation</key>
+ <true/>
+</dict>
+</plist>
diff --git a/desktop/entitlements/runtime-python-aarch64.plist b/desktop/entitlements/runtime-python-aarch64.plist
new file mode 100644
index 000000000..71895d9a7
--- /dev/null
+++ b/desktop/entitlements/runtime-python-aarch64.plist
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- The private Runtime's Python interpreter on Apple silicon. Every
+ entitlement here must carry evidence that this process needs it; today
+ there is none.
+
+ Library validation stays on. The interpreter loads only libraries from
+ its own Runtime tree, which the release signs with the same Team
+ before archiving, plus Apple's system frameworks (the Keychain store
+ reaches Security.framework through ctypes). Desktop builds never run
+ pip or uv against this interpreter, and Agent backends and user tools
+ run as separate processes, so no third-party library is ever mapped
+ into it.
+
+ No executable-memory exception. On arm64, libffi builds ctypes and
+ cffi callbacks (curl_cffi's transfer-progress hook in web fetch) from
+ prepared trampoline pages, never writable executable memory, so both
+ run under the hardened runtime with no entitlement. Intel differs (see
+ runtime-python-x86_64.plist).
+
+ The fixed identifier bot.avibe.desktop.runtime.python, not the
+ versioned file name, keeps this interpreter's designated requirement
+ and therefore its Keychain item access stable across Python upgrades. -->
+</dict>
+</plist>
diff --git a/desktop/entitlements/runtime-python-x86_64.plist b/desktop/entitlements/runtime-python-x86_64.plist
new file mode 100644
index 000000000..e9fbfce4b
--- /dev/null
+++ b/desktop/entitlements/runtime-python-x86_64.plist
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- The private Runtime's Python interpreter on Intel. Every entitlement
+ here must carry evidence that this process needs it.
+
+ allow-unsigned-executable-memory: on x86_64, libffi allocates each
+ ctypes and cffi callback closure (curl_cffi's transfer-progress hook
+ in web fetch) in anonymous memory that is writable and executable,
+ without MAP_JIT. The hardened runtime denies that mapping (EACCES), and
+ libffi falls back to a temporary-file double mapping, which fails too
+ and which it retries forever: the first callback hangs the process.
+ allow-jit does not help, because libffi does not ask for MAP_JIT. This entitlement is the minimum that runs both kinds of
+ callback. Apple silicon needs none (see runtime-python-aarch64.plist).
+
+ Library validation stays on, for the reasons recorded in
+ runtime-python-aarch64.plist: the interpreter maps only its own
+ Team-signed Runtime tree and Apple's system frameworks.
+
+ The fixed identifier bot.avibe.desktop.runtime.python, not the
+ versioned file name, keeps this interpreter's designated requirement
+ and therefore its Keychain item access stable across Python upgrades. -->
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+</dict>
+</plist>
diff --git a/desktop/scripts/build-runtime-bundle.py b/desktop/scripts/build-runtime-bundle.py
index 849c7bce2..4098027f3 100755
--- a/desktop/scripts/build-runtime-bundle.py
+++ b/desktop/scripts/build-runtime-bundle.py
@@ -899,11 +899,49 @@ def compile_payload(private_python: Path, library: Path) -> None:
raise SystemExit(f"{len(missing)} Runtime sources have no bytecode, including {missing[0]}.py")
+def sign_payload(target_config: dict[str, Any], payload: Path, identity: str, keychain: str | None) -> None:
+ """Sign every Mach-O in the payload before anything hashes or archives it.
+
+ Signing rewrites each binary, so it precedes the probe that runs the
+ shipped tree, the archive, and the tree hash. CI runners do not enforce
+ library validation or the JIT restriction, so the probe proves the signed
+ tree still runs, not that its entitlements suffice (see entitlements/).
+ """
+ if target_config["os"] != "macos":
+ raise SystemExit("Only macOS Runtime payloads are code signed here")
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ import macos_signing
+
+ try:
+ count = macos_signing.sign_runtime(
+ payload,
+ arch=target_config["arch"],
+ python_executable=payload / target_config["python_entrypoint"],
+ node_executable=payload / target_config["node_entrypoint"],
+ identity=identity,
+ keychain=keychain,
+ )
+ except macos_signing.SigningError as error:
+ raise SystemExit(f"Runtime code signing failed: {error}") from None
+ print(f"--- signed {count} Runtime Mach-O files ---", file=sys.stderr, flush=True)
+
+
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--target", required=True)
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
parser.add_argument("--cache", type=Path, default=DESKTOP_DIR / "target" / "runtime-cache")
+ # A signed packaging run exports these after importing its Developer ID.
+ parser.add_argument(
+ "--codesign-identity",
+ default=os.environ.get("AVIBE_CODESIGN_IDENTITY"),
+ help="macOS: sign every Runtime Mach-O with this Developer ID identity before archiving",
+ )
+ parser.add_argument(
+ "--codesign-keychain",
+ default=os.environ.get("AVIBE_CODESIGN_KEYCHAIN"),
+ help="keychain that holds --codesign-identity",
+ )
args = parser.parse_args()
sources = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))
@@ -963,7 +1001,10 @@ def main() -> int:
prune_payload(payload)
private_python = payload / target_config["python_entrypoint"]
compile_payload(private_python, python_library(private_python, payload))
- # Probe the tree as it ships, bytecode included, with no network calls.
+ if args.codesign_identity:
+ sign_payload(target_config, payload, args.codesign_identity, args.codesign_keychain)
+ # Probe the tree as it ships, bytecode and signatures included, with no
+ # network calls.
verify_fetch_dependencies(private_python, work_dir, required_binary_wheels)
verify_payload(target_config, payload, work_dir, sources["npm_version"])
diff --git a/desktop/scripts/macos_signing.py b/desktop/scripts/macos_signing.py
new file mode 100644
index 000000000..3165b9ef5
--- /dev/null
+++ b/desktop/scripts/macos_signing.py
@@ -0,0 +1,625 @@
+#!/usr/bin/env python3
+"""Developer ID signing, notarization, and code identity for macOS desktop builds.
+
+A signed build signs every Mach-O it ships with the Team's Developer ID, under
+the hardened runtime and with a secure timestamp, from the inside out:
+
+1. the private Runtime's executables and libraries, before `runtime.zip`, its
+ manifest, and its tree hash exist (`sign_runtime`, called by
+ build-runtime-bundle.py). The notary service opens nested archives, so one
+ unsigned binary in runtime.zip rejects the whole app;
+2. the Cua Driver helper, then Avibe.app, which is notarized and stapled
+ (`sign-app`, `notarize`);
+3. the DMG that carries the stapled app, which is notarized and stapled too
+ (`sign-dmg`, `notarize`, `verify-release`).
+
+There is no ad-hoc mode. Under the hardened runtime, library validation admits
+only libraries signed by the executable's own Team, and an ad-hoc signature has
+no Team, so an ad-hoc-signed Runtime could not load its own extension modules.
+Builds without credentials keep the Runtime's original signatures instead.
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import binascii
+import json
+import os
+import plistlib
+import re
+import secrets
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import time
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+
+DESKTOP_DIR = Path(__file__).resolve().parents[1]
+ENTITLEMENTS_DIR = DESKTOP_DIR / "entitlements"
+
+# The code identity of every release. TCC grants (Accessibility, Screen
+# Recording), Keychain item ACLs, and the updater's code-seal check bind to the
+# designated requirement (DR) built from these values. Changing any of them, or
+# signing with another Team, makes every installed user's grants and Keychain
+# trust stop applying after the next update. Never change them.
+TEAM_ID = "68B2SQ6YK3"
+APP_IDENTIFIER = "bot.avibe.desktop"
+HELPER_IDENTIFIER = "bot.avibe.desktop.cua-driver"
+PYTHON_IDENTIFIER = "bot.avibe.desktop.runtime.python"
+NODE_IDENTIFIER = "bot.avibe.desktop.runtime.node"
+
+APP_ENTITLEMENTS = DESKTOP_DIR / "src-tauri" / "Entitlements.plist"
+HELPER_ENTITLEMENTS = ENTITLEMENTS_DIR / "cua-driver.plist"
+# libffi (Python) and V8 (Node) each generate code differently per architecture.
+PYTHON_ENTITLEMENTS = {
+ "aarch64": ENTITLEMENTS_DIR / "runtime-python-aarch64.plist",
+ "x86_64": ENTITLEMENTS_DIR / "runtime-python-x86_64.plist",
+}
+NODE_ENTITLEMENTS = {
+ "aarch64": ENTITLEMENTS_DIR / "runtime-node-aarch64.plist",
+ "x86_64": ENTITLEMENTS_DIR / "runtime-node-x86_64.plist",
+}
+
+# Every secret the desktop-updater Environment must hold for a signed build.
+APPLE_SECRETS = (
+ "APPLE_CERTIFICATE",
+ "APPLE_CERTIFICATE_PASSWORD",
+ "APPLE_SIGNING_IDENTITY",
+ "APPLE_TEAM_ID",
+ "APPLE_API_KEY",
+ "APPLE_API_ISSUER",
+ "APPLE_API_PRIVATE_KEY",
+)
+
+KEYCHAIN_NAME = "avibe-signing.keychain-db"
+
+MH_EXECUTE = 2
+MH_DYLIB = 6
+MH_BUNDLE = 8
+_THIN_MAGIC = {b"\xcf\xfa\xed\xfe": "<", b"\xce\xfa\xed\xfe": "<", b"\xfe\xed\xfa\xcf": ">", b"\xfe\xed\xfa\xce": ">"}
+_FAT_MAGIC = {b"\xca\xfe\xba\xbe": 20, b"\xca\xfe\xba\xbf": 32}
+# A fat header and a Java class file share 0xcafebabe; the class file's major
+# version (45 or more) sits where a fat header keeps its small slice count.
+_MAX_FAT_SLICES = 45
+SIGN_WORKERS = 8
+# codesign reports this when Apple's timestamp service drops a request; the
+# same invocation succeeds on retry.
+TIMESTAMP_UNAVAILABLE = "timestamp service is not available"
+TIMESTAMP_ATTEMPTS = 3
+# stapler fetches and checks tickets through Apple's CloudKit service; a dropped
+# connection there fails the action with an NSURLErrorDomain error and Error 68.
+STAPLER_NETWORK_ERROR = "NSURLErrorDomain"
+STAPLER_ATTEMPTS = 3
+STAPLER_RETRY_SECONDS = 15
+
+
+class SigningError(RuntimeError):
+ pass
+
+
+def designated_requirement(identifier: str, team: str = TEAM_ID) -> str:
+ """The default Developer ID DR, in the requirement language codesign prints."""
+
+ return (
+ f'designated => identifier "{identifier}" and anchor apple generic'
+ " and certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */"
+ " and certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */"
+ f' and certificate leaf[subject.OU] = "{team}"'
+ )
+
+
+def run(command: list[str], *, redacted: str | None = None, capture: bool = False) -> subprocess.CompletedProcess[str]:
+ """Run a tool; a failure names the tool (or `redacted`), never its arguments.
+
+ Arguments can carry passwords or key paths, and a CalledProcessError would
+ print them with the traceback.
+ """
+
+ result = subprocess.run(command, check=False, capture_output=capture, text=True)
+ if result.returncode != 0:
+ detail = ""
+ if capture:
+ detail = "\n" + "\n".join(part for part in (result.stdout, result.stderr) if part).strip()
+ raise SigningError(f"{redacted or Path(command[0]).name} exited {result.returncode}{detail}")
+ return result
+
+
+def macho_filetype(path: Path) -> int | None:
+ """The Mach-O file type of a thin or universal binary, else None."""
+
+ with path.open("rb") as stream:
+ header = stream.read(32)
+ if len(header) < 16:
+ return None
+ if header[:4] in _THIN_MAGIC:
+ return struct.unpack(_THIN_MAGIC[header[:4]] + "I", header[12:16])[0]
+ if header[:4] not in _FAT_MAGIC:
+ return None
+ count = struct.unpack(">I", header[4:8])[0]
+ if count == 0 or count >= _MAX_FAT_SLICES:
+ return None
+ entry = _FAT_MAGIC[header[:4]]
+ stream.seek(8)
+ table = stream.read(count * entry)
+ types = set()
+ for index in range(count):
+ fields = table[index * entry : (index + 1) * entry]
+ offset = struct.unpack(">Q" if entry == 32 else ">I", fields[8:16] if entry == 32 else fields[8:12])[0]
+ stream.seek(offset)
+ slice_header = stream.read(16)
+ if slice_header[:4] not in _THIN_MAGIC:
+ raise SigningError(f"{path}: universal binary slice is not Mach-O")
+ types.add(struct.unpack(_THIN_MAGIC[slice_header[:4]] + "I", slice_header[12:16])[0])
+ if len(types) != 1:
+ raise SigningError(f"{path}: universal binary slices disagree on their file type")
+ return types.pop()
+
+
+def macho_files(root: Path) -> list[tuple[Path, int]]:
+ """Every regular Mach-O file below root. Links are skipped: the archive
+ stores a link as a copy of its target, which is signed in place."""
+
+ found = []
+ for directory, _dirnames, filenames in os.walk(root):
+ for name in filenames:
+ path = Path(directory) / name
+ if path.is_symlink() or not path.is_file():
+ continue
+ filetype = macho_filetype(path)
+ if filetype is not None:
+ found.append((path, filetype))
+ return sorted(found)
+
+
+def codesign_command(identity: str, keychain: str | None) -> list[str]:
+ command = ["codesign", "--force", "--sign", identity, "--options", "runtime", "--timestamp"]
+ if keychain:
+ command.extend(["--keychain", keychain])
+ return command
+
+
+def codesign(command: list[str], *, label: str) -> None:
+ for attempt in range(1, TIMESTAMP_ATTEMPTS + 1):
+ try:
+ run(command, redacted=f"codesign {label}", capture=True)
+ return
+ except SigningError as error:
+ if TIMESTAMP_UNAVAILABLE not in str(error) or attempt == TIMESTAMP_ATTEMPTS:
+ raise
+ print(f"timestamp service unavailable signing {label}; retrying ({attempt}/{TIMESTAMP_ATTEMPTS})", flush=True)
+
+
+def signature_details(path: Path) -> dict[str, str]:
+ result = subprocess.run(
+ ["codesign", "--display", "--verbose=4", str(path)], check=False, capture_output=True, text=True
+ )
+ if result.returncode != 0:
+ raise SigningError(f"{path}: no readable code signature")
+ details: dict[str, str] = {}
+ for line in result.stderr.splitlines():
+ key, separator, value = line.partition("=")
+ if separator and key not in details:
+ details[key] = value
+ if line.startswith("CodeDirectory "):
+ match = re.search(r"flags=(0x[0-9a-fA-F]+)", line)
+ details["flags"] = match.group(1) if match else "0x0"
+ return details
+
+
+def signed_entitlements(path: Path) -> dict:
+ result = subprocess.run(
+ ["codesign", "--display", "--entitlements", "-", "--xml", str(path)],
+ check=False,
+ capture_output=True,
+ )
+ if result.returncode != 0:
+ raise SigningError(f"{path}: entitlements are unreadable")
+ return plistlib.loads(result.stdout) if result.stdout.strip() else {}
+
+
+def actual_requirement(path: Path) -> str:
+ result = subprocess.run(
+ ["codesign", "--display", "--requirements", "-", str(path)], check=False, capture_output=True, text=True
+ )
+ lines = [line for line in result.stdout.splitlines() if line.startswith("designated => ")]
+ return lines[0] if result.returncode == 0 and len(lines) == 1 else "<unreadable>"
+
+
+def expected_requirement(identifier: str, team: str) -> str:
+ """Normalize through csreq, which shares codesign's decompiler: a Team ID
+ that starts with a digit is printed quoted, any other one bare."""
+
+ result = run(["csreq", "-t", "-r", "=" + designated_requirement(identifier, team)], capture=True)
+ return result.stdout.strip()
+
+
+def verify_code(
+ path: Path,
+ *,
+ identifier: str | None = None,
+ entitlements: Path | None = None,
+ deep: bool = False,
+) -> None:
+ """Check one signed item: strict seal, hardened runtime, secure timestamp,
+ and Team, and, where given, its exact DR and entitlements."""
+
+ verify = ["codesign", "--verify", "--strict", "--verbose=2"]
+ if deep:
+ verify.append("--deep")
+ run([*verify, str(path)], capture=True)
+ details = signature_details(path)
+ if not int(details.get("flags", "0x0"), 16) & 0x10000:
+ raise SigningError(f"{path}: hardened runtime flag is missing")
+ if details.get("TeamIdentifier") != TEAM_ID:
+ raise SigningError(f"{path}: signed by Team {details.get('TeamIdentifier')!r}, expected {TEAM_ID}")
+ if not details.get("Timestamp"):
+ raise SigningError(f"{path}: signature has no secure timestamp")
+ if identifier is not None:
+ if details.get("Identifier") != identifier:
+ raise SigningError(f"{path}: identifier {details.get('Identifier')!r}, expected {identifier}")
+ actual, expected = actual_requirement(path), expected_requirement(identifier, TEAM_ID)
+ if actual != expected:
+ raise SigningError(f"{path}: designated requirement differs\n expected: {expected}\n actual: {actual}")
+ if entitlements is not None:
+ wanted = plistlib.loads(entitlements.read_bytes())
+ if signed_entitlements(path) != wanted:
+ raise SigningError(f"{path}: entitlements differ from {entitlements.name}")
+
+
+def sign_runtime(
+ payload: Path,
+ *,
+ arch: str,
+ python_executable: Path,
+ node_executable: Path,
+ identity: str,
+ keychain: str | None = None,
+) -> int:
+ """Sign every Mach-O in the private Runtime; return how many were signed.
+
+ Libraries carry no entitlements: only a process's main executable grants
+ them. Each executable is listed with its own identifier and entitlements,
+ and an unreviewed executable stops the build rather than ship with
+ entitlements nobody decided on.
+ """
+
+ executables = {
+ python_executable.resolve(): (PYTHON_IDENTIFIER, PYTHON_ENTITLEMENTS[arch]),
+ node_executable.resolve(): (NODE_IDENTIFIER, NODE_ENTITLEMENTS[arch]),
+ }
+ libraries, programs = [], []
+ for path, filetype in macho_files(payload):
+ if filetype in (MH_DYLIB, MH_BUNDLE):
+ libraries.append(path)
+ elif filetype == MH_EXECUTE and path.resolve() in executables:
+ programs.append(path)
+ elif filetype == MH_EXECUTE:
+ raise SigningError(f"Runtime executable has no reviewed identity and entitlements: {path.relative_to(payload)}")
+ else:
+ raise SigningError(f"Runtime contains Mach-O type {filetype} that cannot be signed: {path.relative_to(payload)}")
+ if {path.resolve() for path in programs} != set(executables):
+ raise SigningError("Runtime is missing its Python or Node executable")
+
+ base = codesign_command(identity, keychain)
+
+ def sign_library(path: Path) -> None:
+ codesign([*base, str(path)], label=str(path.relative_to(payload)))
+ verify_code(path)
+
+ # Inside out: the libraries an executable loads are sealed before it is.
+ with ThreadPoolExecutor(max_workers=SIGN_WORKERS) as pool:
+ list(pool.map(sign_library, libraries))
+ for path in programs:
+ identifier, entitlements = executables[path.resolve()]
+ codesign(
+ [*base, "--identifier", identifier, "--entitlements", str(entitlements), str(path)],
+ label=str(path.relative_to(payload)),
+ )
+ verify_code(path, identifier=identifier, entitlements=entitlements)
+ return len(libraries) + len(programs)
+
+
+def unexpected_app_code(app: Path) -> list[Path]:
+ """Mach-O files in the bundle besides its main executable and the helper."""
+
+ expected = {app / "Contents/Helpers/cua-driver"}
+ executable = plistlib.loads((app / "Contents/Info.plist").read_bytes())["CFBundleExecutable"]
+ expected.add(app / "Contents/MacOS" / executable)
+ return [path for path, _type in macho_files(app) if path not in expected]
+
+
+def sign_app(app: Path, *, identity: str, keychain: str | None) -> None:
+ info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
+ if info.get("CFBundleIdentifier") != APP_IDENTIFIER:
+ raise SigningError(f"Avibe.app bundle identifier must stay {APP_IDENTIFIER}")
+ helper = app / "Contents/Helpers/cua-driver"
+ if not helper.is_file() or helper.is_symlink():
+ raise SigningError("Avibe.app is missing Contents/Helpers/cua-driver")
+ if extra := unexpected_app_code(app):
+ raise SigningError(f"Avibe.app contains unreviewed nested code: {[str(path.relative_to(app)) for path in extra]}")
+ base = codesign_command(identity, keychain)
+ codesign(
+ [*base, "--identifier", HELPER_IDENTIFIER, "--entitlements", str(HELPER_ENTITLEMENTS), str(helper)],
+ label="Contents/Helpers/cua-driver",
+ )
+ # The bundle signature seals the main executable and the signed helper; its
+ # identifier comes from Info.plist.
+ codesign([*base, "--entitlements", str(APP_ENTITLEMENTS), str(app)], label="Avibe.app")
+ verify_app(app)
+
+
+def verify_app(app: Path) -> None:
+ verify_code(app / "Contents/Helpers/cua-driver", identifier=HELPER_IDENTIFIER, entitlements=HELPER_ENTITLEMENTS)
+ verify_code(app, identifier=APP_IDENTIFIER, entitlements=APP_ENTITLEMENTS, deep=True)
+
+
+def sign_dmg(dmg: Path, *, identity: str, keychain: str | None) -> None:
+ command = ["codesign", "--force", "--sign", identity, "--timestamp"]
+ if keychain:
+ command.extend(["--keychain", keychain])
+ codesign([*command, str(dmg)], label=dmg.name)
+ verify_dmg_signature(dmg)
+
+
+def verify_dmg_signature(dmg: Path) -> None:
+ run(["codesign", "--verify", "--strict", "--verbose=2", str(dmg)], capture=True)
+ details = signature_details(dmg)
+ if details.get("TeamIdentifier") != TEAM_ID or not details.get("Timestamp"):
+ raise SigningError(f"{dmg.name}: not signed by Team {TEAM_ID} with a secure timestamp")
+
+
+def notary_credentials(key_path: str, key_id: str, issuer: str) -> list[str]:
+ return ["--key", key_path, "--key-id", key_id, "--issuer", issuer]
+
+
+def notarize(path: Path, *, key_path: str, key_id: str, issuer: str) -> None:
+ """Submit to the notary service, require `Accepted`, then staple and validate.
+
+ An app is submitted as a ditto zip of the bundle; the ticket is stapled to
+ the bundle itself. The submission log is printed either way: it lists every
+ rejected or warned binary, and contains no credentials.
+ """
+
+ credentials = notary_credentials(key_path, key_id, issuer)
+ with tempfile.TemporaryDirectory(prefix="avibe-notary-") as temporary:
+ submission = path
+ if path.suffix == ".app":
+ submission = Path(temporary) / f"{path.stem}.zip"
+ run(["ditto", "-c", "-k", "--keepParent", str(path), str(submission)])
+ result = subprocess.run(
+ ["xcrun", "notarytool", "submit", str(submission), *credentials,
+ "--wait", "--timeout", "2h", "--output-format", "json"],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ try:
+ outcome = json.loads(result.stdout)
+ except json.JSONDecodeError:
+ raise SigningError(f"notarytool submit failed for {path.name}: {result.stderr.strip()}") from None
+ submission_id, status = outcome.get("id"), outcome.get("status")
+ print(f"notarization {path.name}: id={submission_id} status={status}", flush=True)
+ if submission_id:
+ log = subprocess.run(
+ ["xcrun", "notarytool", "log", str(submission_id), *credentials],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ try:
+ issues = json.loads(log.stdout).get("issues")
+ except json.JSONDecodeError:
+ issues = log.stdout.strip() or log.stderr.strip()
+ print(f"notary issues for {path.name}: {json.dumps(issues, indent=2)}", flush=True)
+ if status != "Accepted":
+ raise SigningError(f"notarization of {path.name} ended {status!r}, not Accepted")
+ stapler("staple", path)
+ stapler("validate", path)
+
+
+def stapler(action: str, path: Path) -> None:
+ for attempt in range(1, STAPLER_ATTEMPTS + 1):
+ try:
+ run(["xcrun", "stapler", action, str(path)], redacted=f"stapler {action} {path.name}", capture=True)
+ return
+ except SigningError as error:
+ if STAPLER_NETWORK_ERROR not in str(error) or attempt == STAPLER_ATTEMPTS:
+ raise
+ print(f"stapler {action} {path.name} lost its connection to Apple; retrying ({attempt}/{STAPLER_ATTEMPTS})", flush=True)
+ time.sleep(STAPLER_RETRY_SECONDS)
+
+
+def assess(path: Path, *, kind: str) -> None:
+ """Gatekeeper's verdict, as a quarantined download would receive it."""
+
+ command = ["spctl", "--assess", "--type", kind, "-vvv"]
+ if kind == "open":
+ command.extend(["--context", "context:primary-signature"])
+ result = subprocess.run([*command, str(path)], check=False, capture_output=True, text=True)
+ report = result.stderr.strip()
+ print(report, flush=True)
+ if result.returncode != 0 or "accepted" not in report or "source=Notarized Developer ID" not in report:
+ raise SigningError(f"Gatekeeper does not accept {path.name} as notarized Developer ID code")
+
+
+def verify_release(app: Path, dmg: Path) -> None:
+ """The shipped shapes: the stapled app, and the stapled DMG with the same
+ app inside it."""
+
+ verify_dmg_signature(dmg)
+ for path, kind in ((app, "exec"), (dmg, "open")):
+ stapler("validate", path)
+ assess(path, kind=kind)
+ verify_app(app)
+ with tempfile.TemporaryDirectory(prefix="avibe-dmg-verify-") as mountpoint:
+ run(["hdiutil", "attach", "-nobrowse", "-readonly", "-noautoopen", "-mountpoint", mountpoint, str(dmg)], capture=True)
+ try:
+ inner = Path(mountpoint) / "Avibe.app"
+ verify_app(inner)
+ stapler("validate", inner)
+ assess(inner, kind="exec")
+ finally:
+ subprocess.run(["hdiutil", "detach", mountpoint], check=False)
+
+
+def append_env(env_file: Path, values: dict[str, str]) -> None:
+ for key, value in values.items():
+ if "\n" in value or "\r" in value:
+ raise SigningError(f"{key} must be a single line")
+ with env_file.open("a", encoding="utf-8") as stream:
+ stream.write("".join(f"{key}={value}\n" for key, value in values.items()))
+
+
+def credential_policy(environment: dict[str, str], release_tag: str) -> bool:
+ """Whether to sign. A release requires the complete set; a manual build
+ accepts the complete set or none of it. A partial set always fails."""
+
+ missing = [name for name in APPLE_SECRETS if not environment.get(name)]
+ if len(missing) == len(APPLE_SECRETS) and not release_tag:
+ return False
+ if missing:
+ scope = "Release builds require" if release_tag else "A partially configured set fails; set"
+ raise SigningError(f"{scope} the complete Apple credential set; missing: {', '.join(missing)}")
+ team = environment["APPLE_TEAM_ID"]
+ if team != TEAM_ID:
+ raise SigningError(f"APPLE_TEAM_ID must be the pinned desktop Team {TEAM_ID}; the code identity never changes")
+ identity = environment["APPLE_SIGNING_IDENTITY"]
+ if not identity.startswith("Developer ID Application: ") or not identity.endswith(f" ({TEAM_ID})"):
+ raise SigningError(f"APPLE_SIGNING_IDENTITY must name the Developer ID Application identity of Team {TEAM_ID}")
+ if "BEGIN PRIVATE KEY" not in environment["APPLE_API_PRIVATE_KEY"]:
+ raise SigningError("APPLE_API_PRIVATE_KEY must be the raw .p8 App Store Connect key")
+ if re.fullmatch(r"[A-Z0-9]{8,12}", environment["APPLE_API_KEY"]) is None:
+ raise SigningError("APPLE_API_KEY must be the App Store Connect key ID")
+ if re.fullmatch(r"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", environment["APPLE_API_ISSUER"]) is None:
+ raise SigningError("APPLE_API_ISSUER must be the App Store Connect issuer UUID")
+ return True
+
+
+def import_identity(environment: dict[str, str], *, release_tag: str, env_file: Path, work_dir: Path) -> None:
+ """Install the Developer ID identity in a temporary keychain and the notary
+ key in a private file, and export only their locations and names.
+
+ Tauri never receives Apple credentials: none of the exported names is one
+ that tauri-bundler reads, so it can neither sign nor notarize on its own.
+ """
+
+ if not credential_policy(environment, release_tag):
+ append_env(env_file, {"apple_signing": "absent"})
+ print("Apple signing credentials are absent; this manual build stays ad-hoc.", flush=True)
+ return
+ work_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
+ keychain = work_dir / KEYCHAIN_NAME
+ password = secrets.token_urlsafe(32)
+ run(["security", "create-keychain", "-p", password, str(keychain)], redacted="security create-keychain")
+ run(["security", "set-keychain-settings", "-lut", "21600", str(keychain)])
+ run(["security", "unlock-keychain", "-p", password, str(keychain)], redacted="security unlock-keychain")
+ certificate = work_dir / "certificate.p12"
+ try:
+ certificate_bytes = base64.b64decode(environment["APPLE_CERTIFICATE"], validate=False)
+ except binascii.Error:
+ raise SigningError("APPLE_CERTIFICATE must be a base64 .p12") from None
+ descriptor = os.open(certificate, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(certificate_bytes)
+ try:
+ run(
+ ["security", "import", str(certificate), "-k", str(keychain),
+ "-P", environment["APPLE_CERTIFICATE_PASSWORD"], "-T", "/usr/bin/codesign"],
+ redacted="security import (check APPLE_CERTIFICATE and APPLE_CERTIFICATE_PASSWORD)",
+ )
+ finally:
+ certificate.unlink(missing_ok=True)
+ run(
+ ["security", "set-key-partition-list", "-S", "apple-tool:,apple:,codesign:", "-s", "-k", password, str(keychain)],
+ redacted="security set-key-partition-list",
+ capture=True,
+ )
+ listed = run(["security", "list-keychains", "-d", "user"], capture=True).stdout
+ search = [line.strip().strip('"') for line in listed.splitlines() if line.strip()]
+ run(["security", "list-keychains", "-d", "user", "-s", str(keychain), *search])
+ identities = run(["security", "find-identity", "-v", "-p", "codesigning", str(keychain)], capture=True).stdout
+ if f'"{environment["APPLE_SIGNING_IDENTITY"]}"' not in identities:
+ raise SigningError("The imported certificate does not provide a valid APPLE_SIGNING_IDENTITY")
+ key = work_dir / f"AuthKey_{environment['APPLE_API_KEY']}.p8"
+ descriptor = os.open(key, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ stream.write(environment["APPLE_API_PRIVATE_KEY"])
+ append_env(
+ env_file,
+ {
+ "apple_signing": "enabled",
+ "AVIBE_CODESIGN_IDENTITY": environment["APPLE_SIGNING_IDENTITY"],
+ "AVIBE_CODESIGN_KEYCHAIN": str(keychain),
+ "AVIBE_NOTARY_KEY_PATH": str(key),
+ "AVIBE_NOTARY_KEY_ID": environment["APPLE_API_KEY"],
+ "AVIBE_NOTARY_ISSUER": environment["APPLE_API_ISSUER"],
+ },
+ )
+ print(f"Developer ID identity of Team {TEAM_ID} is ready in a temporary keychain.", flush=True)
+
+
+def cleanup(work_dir: Path) -> None:
+ keychain = work_dir / KEYCHAIN_NAME
+ if keychain.exists():
+ # Deleting the keychain also drops it from the search list.
+ subprocess.run(["security", "delete-keychain", str(keychain)], check=False)
+ shutil.rmtree(work_dir, ignore_errors=True)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = parser.add_subparsers(dest="command", required=True)
+ importer = sub.add_parser("import-identity", help="validate Apple secrets from the environment and install them")
+ importer.add_argument("--release-tag", default="")
+ importer.add_argument("--env-file", type=Path, required=True)
+ importer.add_argument("--work-dir", type=Path, required=True)
+ cleaner = sub.add_parser("cleanup", help="delete the temporary keychain and key files")
+ cleaner.add_argument("--work-dir", type=Path, required=True)
+ for name in ("sign-app", "sign-dmg"):
+ signer = sub.add_parser(name)
+ signer.add_argument("path", type=Path)
+ signer.add_argument("--identity", default=os.environ.get("AVIBE_CODESIGN_IDENTITY"))
+ signer.add_argument("--keychain", default=os.environ.get("AVIBE_CODESIGN_KEYCHAIN"))
+ notarizer = sub.add_parser("notarize", help="submit, require Accepted, staple, and validate")
+ notarizer.add_argument("path", type=Path)
+ releaser = sub.add_parser("verify-release", help="Gatekeeper, staple, and code identity checks of the shipped app and DMG")
+ releaser.add_argument("--app", type=Path, required=True)
+ releaser.add_argument("--dmg", type=Path, required=True)
+ args = parser.parse_args()
+ try:
+ if args.command == "import-identity":
+ import_identity(dict(os.environ), release_tag=args.release_tag, env_file=args.env_file, work_dir=args.work_dir)
+ elif args.command == "cleanup":
+ cleanup(args.work_dir)
+ elif args.command in ("sign-app", "sign-dmg"):
+ if not args.identity:
+ raise SigningError("No signing identity: run import-identity first")
+ if args.command == "sign-app":
+ sign_app(args.path, identity=args.identity, keychain=args.keychain)
+ else:
+ sign_dmg(args.path, identity=args.identity, keychain=args.keychain)
+ elif args.command == "notarize":
+ names = ("AVIBE_NOTARY_KEY_PATH", "AVIBE_NOTARY_KEY_ID", "AVIBE_NOTARY_ISSUER")
+ if any(not os.environ.get(name) for name in names):
+ raise SigningError("No notary credentials: run import-identity first")
+ notarize(
+ args.path,
+ key_path=os.environ["AVIBE_NOTARY_KEY_PATH"],
+ key_id=os.environ["AVIBE_NOTARY_KEY_ID"],
+ issuer=os.environ["AVIBE_NOTARY_ISSUER"],
+ )
+ else:
+ verify_release(args.app, args.dmg)
+ except SigningError as error:
+ print(f"::error::{error}", file=sys.stderr, flush=True)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/docs/desktop-computer-use.md b/docs/desktop-computer-use.md
index dc9ba4bb3..cb5ad8548 100644
--- a/docs/desktop-computer-use.md
+++ b/docs/desktop-computer-use.md
@@ -72,9 +72,12 @@ startup initialization cannot be opened. Avibe reports the failure in the
control and continues starting the rest of the desktop app; it does not make
the optional feature failure prevent Avibe from launching.
-An ad-hoc app update can change the app's code identity, so macOS may no longer
-apply the old grants. Turn on the updated installed app in the same two Privacy
-& Security panes. On some macOS 26 ad-hoc builds, ScreenCaptureKit can be
+Release builds are Developer ID signed with a fixed code identity, so macOS
+keeps both grants across updates. An ad-hoc build (a manual build without
+signing credentials, or a release from before signing) has a different identity
+each time, so macOS may no longer apply the old grants; the first signed build
+after one also needs them once more. Turn on the updated installed app in the
+same two Privacy & Security panes. On some macOS 26 ad-hoc builds, ScreenCaptureKit can be
denied while macOS refuses to create the Screen Recording row. Avibe opens the
pane and guides you to click **+** or drag the exact Avibe app into the list,
then enable it. This manual addition is the accepted Phase 1 workaround; it
diff --git a/docs/desktop-test-installation.md b/docs/desktop-test-installation.md
index 61a06f620..a30aef4cb 100644
--- a/docs/desktop-test-installation.md
+++ b/docs/desktop-test-installation.md
@@ -13,16 +13,28 @@ downloaded `.SHA256SUMS` filename in the directory containing all five files.
On Windows, use `Get-FileHash -Algorithm SHA256 <installer.exe>` and compare it
with the installer entry in `.SHA256SUMS`. The source record identifies the tag,
commit, desktop version, and bundled Avibe package version; the Runtime manifest
-records the embedded archive and toolchain hashes. On macOS, a current schema-2
-source record also identifies the pinned Cua Driver source and its archive,
-extracted, thinned, packaged, and code-signing hashes. `SIGNATURE` is
-descriptive metadata, **not a cryptographic signature file**. Hashes detect
-changed downloads; they do not establish a trusted developer identity.
-
-The macOS **app inside the DMG is ad-hoc signed**. The outer DMG is unsigned and
-unnotarized; this is not Developer ID distribution. Open the DMG, drag Avibe to
-Applications, and launch it. If macOS blocks this verified test app, use System
-Settings → Privacy & Security → Open Anyway for this app and confirm the prompt.
+records the embedded archive and toolchain hashes. On macOS, the source record
+also identifies the pinned Cua Driver source and its archive, extracted,
+thinned, packaged, and code-signing hashes. `SIGNATURE` is descriptive
+metadata naming the signed layers, **not a cryptographic signature file**.
+Hashes detect changed downloads; on macOS, Apple's signature and notarization
+establish the developer identity.
+
+On macOS, the DMG, the app inside it, and every program bundled with the app are
+signed with Avibe's Developer ID (Team `68B2SQ6YK3`) and notarized by Apple,
+with the tickets stapled. Open the DMG, drag Avibe to Applications, and launch
+it; macOS opens it after its usual first-launch confirmation, with no Privacy &
+Security override. If macOS instead says Avibe is damaged or cannot be verified, do not
+override it: delete the download and fetch it again. To check a download
+yourself, `spctl --assess --type open --context context:primary-signature -v
+<file>.dmg` and, after installing, `spctl --assess -v /Applications/Avibe.app`
+both report `source=Notarized Developer ID`.
+
+Every signed release keeps the same code identity, so macOS keeps Computer Use's
+Accessibility and Screen Recording permissions, and Keychain access you allowed,
+across updates. Earlier ad-hoc builds changed identity with every build: after
+moving from one of them to a signed build, grant those permissions once more.
+
The Windows NSIS installer is unsigned and may show SmartScreen or an unknown
publisher prompt. After checking the download, use More info → Run anyway only
if your machine's policy permits it. Keep Gatekeeper, SmartScreen, and antivirus
@@ -59,5 +71,5 @@ not perform that cleanup. Sessions, settings, credentials, and projects under
`~/.avibe` remain available for reinstall; external backend installations are
untouched. Closing the window alone does not stop the Runtime.
-Trusted distribution, including the remaining signing layers, is tracked in
+Windows installer signing (Authenticode) is tracked in
[#1976](https://github.com/avibe-bot/avibe/issues/1976).
diff --git a/docs/plans/desktop-product-gaps.md b/docs/plans/desktop-product-gaps.md
index 4051bfaba..27b4b20f9 100644
--- a/docs/plans/desktop-product-gaps.md
+++ b/docs/plans/desktop-product-gaps.md
@@ -22,10 +22,11 @@ A Tauri v2 thin shell (window + bootstrap screen) that adopts or starts one
local Avibe Runtime, hands the window to the Workbench, and verifies integrity
of the installed private Runtime on every launch. Self-contained packages
embed CPython, the Avibe wheel, locked Python dependencies, Node, and npm.
-CI produces unsigned acceptance artifacts for macOS arm/x64 and Windows x64.
+Release builds produce Developer ID signed and notarized macOS arm/x64 DMGs and
+an unsigned Windows x64 acceptance installer.
-What the baseline deliberately does **not** have: production distribution
-signing (G1 remaining layers), auto-update, notifications, deep links,
+What the baseline deliberately does **not** have: Windows Authenticode signing
+(the remaining G1 layer), auto-update, notifications, deep links,
native multi-window, or persisted window state. Tray / Runtime lifecycle
visibility and launch-at-login **shipped** in #1975.
@@ -33,6 +34,13 @@ visibility and launch-at-login **shipped** in #1975.
### G1. Code signing and notarization
+- Status: macOS is done. Every tag build Developer ID signs the private
+ Runtime's Mach-O files before archiving, the Cua Driver helper, the app, and
+ the DMG; it notarizes and staples the app and the DMG, pins each code identity
+ to its designated requirement, and fails without the complete Apple
+ credential set. See "macOS signing and notarization" in the desktop README.
+ Windows Authenticode remains open in
+ [#1976](https://github.com/avibe-bot/avibe/issues/1976).
- Problem: unsigned artifacts are stopped by Gatekeeper (macOS) and flagged by
SmartScreen (Windows). There is currently no way to ship to a real user.
- Work: introduce a `desktop-package-sign.yml`-style manual workflow or extend
@@ -197,7 +205,7 @@ visibility and launch-at-login **shipped** in #1975.
## Suggested sequencing
-1. G1 remaining signing layers + certificate procurement (longest lead)
+1. G1 Windows Authenticode + certificate procurement (macOS layers done)
2. G2 auto-update (needs G1; ship with the first signed release)
3. G6 window state + G5 deep links (in flight; no G1 dependency)
4. G4 notifications (depends on shipped tray)
diff --git a/docs/plans/tauri-desktop-vertical-slice.md b/docs/plans/tauri-desktop-vertical-slice.md
index 92052e09b..bfa681da1 100644
--- a/docs/plans/tauri-desktop-vertical-slice.md
+++ b/docs/plans/tauri-desktop-vertical-slice.md
@@ -534,16 +534,16 @@ interactive shell startup file.
Development builds retain the installed-`vibe` resolver. A distributable build
must enable the Rust `bundled-runtime` feature; producing a consumer installer
without it is a release failure. `desktop-self-contained-package` builds the
-artifacts and signs them credential-gated: with the Apple secrets configured it
-Developer ID signs and notarizes the macOS app (`SIGNATURE:
-app-identity-signed`); without them the macOS app copy receives only an ad-hoc
-structural signature and all artifacts remain unsigned acceptance builds. The
-manual workflow requires a SemVer input and stamps it into Tauri metadata and
-artifact names. Remaining signing layers are tracked release gates (see the
-distribution-signing-completion issue): sign executable code inside the
-private Runtime before archiving it, sign and notarize the outer DMG, and
-apply the corresponding Authenticode coverage on Windows. Signing,
-notarization, and publication are separate release gates.
+artifacts. Every macOS tag build signs executable code inside the private
+Runtime before archiving it, then the Cua Driver helper and the app, with the
+Team's Developer ID under the hardened runtime; it notarizes and staples the app
+and the outer DMG and verifies each pinned code identity. A tag build without
+the complete Apple credential set fails. A manual build signs the same way with
+the complete set and otherwise stays ad-hoc, and its `.SIGNATURE` names what it
+produced. The manual workflow requires a SemVer input and stamps it into Tauri
+metadata and artifact names. Authenticode coverage on Windows remains a tracked
+release gate (#1976). Signing, notarization, and publication are separate
+release gates.
The D11 clean-install gate uses a fresh VM with Python, `uv`, Node, npm, and all
Agent backends absent from `PATH`. It must prove:
diff --git a/scripts/desktop_release.py b/scripts/desktop_release.py
index 07e5a95da..00114e917 100644
--- a/scripts/desktop_release.py
+++ b/scripts/desktop_release.py
@@ -18,7 +18,9 @@ from runpy import run_path
_versions = run_path(str(Path(__file__).with_name("release_package_version.py")))
package_version_from_release_tag = _versions["package_version_from_release_tag"]
_github = run_path(str(Path(__file__).with_name("github_release.py")))
-DESKTOP_SOURCE_SCHEMA_VERSION = 2
+# Schema 3 marks records whose macOS artifacts are Developer ID signed and
+# notarized. Schema 1 and 2 records were published with ad-hoc macOS apps.
+DESKTOP_SOURCE_SCHEMA_VERSION = 3
CUA_DRIVER_SOURCES = Path(__file__).resolve().parents[1] / "desktop" / "cua-driver" / "sources.json"
TARGETS = {
"aarch64-apple-darwin": ("macos", "aarch64", ".dmg"),
@@ -27,6 +29,23 @@ TARGETS = {
}
RC_TAG = re.compile(r"gh-v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)rc(0|[1-9][0-9]*)")
SHA = re.compile(r"[0-9a-f]{40}")
+# The OS-signing layers a `.SIGNATURE` file names, by signing profile. A tag
+# build must record its target's release profile; a manual build records the
+# profile it actually produced.
+SIGNING_PROFILES = {
+ "macos": {
+ "developer-id": (
+ "runtime-developer-id-signed",
+ "app-developer-id-notarized-stapled",
+ "dmg-developer-id-notarized-stapled",
+ ),
+ "ad-hoc": ("runtime-unsigned", "app-adhoc", "dmg-unsigned-unnotarized"),
+ },
+ "windows": {"unsigned": ("installer-unsigned",)},
+}
+RELEASE_SIGNING_PROFILE = {"macos": "developer-id", "windows": "unsigned"}
+# The layers already-published schema 1 and 2 records carry.
+LEGACY_SIGNATURE = {"macos": "app-adhoc\ndmg-unsigned-unnotarized\n", "windows": "installer-unsigned\n"}
SEMVER = re.compile(
r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
r"(?:-(?P<pre>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?"
@@ -76,8 +95,9 @@ def prepare(
resolved = resolve(tag, source_sha)
if git_output("rev-parse", "HEAD") != source_sha or version != resolved["version"]:
raise ValueError("desktop checkout/version does not match the release tag")
- # The reusable TEST path receives no secrets and overrides any identity
- # configuration. The manual path retains its optional credential policy.
+ # Tauri never signs with an identity: macOS Developer ID signing and
+ # notarization belong to desktop/scripts/macos_signing.py, and Windows
+ # installers stay unsigned.
override["bundle"] = {
"macOS": {"signingIdentity": "-"},
"windows": {"certificateThumbprint": None, "signCommand": None},
@@ -91,6 +111,9 @@ def prepare(
if TARGETS[target][0] == "macos":
bundle = override.setdefault("bundle", {})
macos = bundle.setdefault("macOS", {})
+ # Tauri seals the bundle ad hoc with the hardened runtime and the
+ # checked-in entitlements; a signed build then re-signs it.
+ macos["signingIdentity"] = "-"
macos["files"] = {
"Helpers/cua-driver": f"binaries/cua-driver-{target}",
}
@@ -115,10 +138,12 @@ def digest(path: Path) -> str:
return result.hexdigest()
-def signature(target: str) -> str:
- if TARGETS[target][0] == "macos":
- return "app-adhoc\ndmg-unsigned-unnotarized\n"
- return "installer-unsigned\n"
+def signature(target: str, profile: str | None = None) -> str:
+ system = TARGETS[target][0]
+ layers = SIGNING_PROFILES[system].get(profile or RELEASE_SIGNING_PROFILE[system])
+ if layers is None:
+ raise ValueError("Unknown signing profile for this desktop target")
+ return "".join(f"{layer}\n" for layer in layers)
def asset_names(version: str, target: str) -> list[str]:
@@ -223,8 +248,9 @@ def record(*, version: str, target: str, tag: str, source_sha: str,
driver_cdhash: str | None = None) -> None:
if SHA.fullmatch(source_sha) is None:
raise ValueError("Invalid source SHA")
- if tag and (version != desktop_version_from_tag(tag) or signing != signature(target).strip()):
- raise ValueError("TEST version/signature policy mismatch")
+ signature_text = signature(target, signing)
+ if tag and (version != desktop_version_from_tag(tag) or signature_text != signature(target)):
+ raise ValueError("Release version/signature policy mismatch")
manifest_path = runtime / "runtime-manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
validate_manifest(manifest, target, tag)
@@ -260,7 +286,7 @@ def record(*, version: str, target: str, tag: str, source_sha: str,
elif any(value is not None for value in driver_values):
raise ValueError("Windows desktop artifacts cannot carry macOS Cua Driver provenance")
(output / names[2]).write_text(json.dumps(source, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- (output / names[3]).write_text(signing + "\n", encoding="utf-8")
+ (output / names[3]).write_text(signature_text, encoding="utf-8")
(output / names[4]).write_text(
"".join(f"{digest(output / name)} {name}\n" for name in sorted(names[:4])), encoding="utf-8",
)
@@ -295,7 +321,7 @@ def verify(directory: Path, tag: str, source_sha: str, *, updater_enabled: bool
raise ValueError("Desktop asset hash mismatch")
source = json.loads((directory / names[2]).read_text(encoding="utf-8"))
schema_version = source.get("schema_version")
- if schema_version not in {1, DESKTOP_SOURCE_SCHEMA_VERSION}:
+ if schema_version not in {1, 2, DESKTOP_SOURCE_SCHEMA_VERSION}:
raise ValueError("Desktop source provenance schema mismatch")
expected_source = {"schema_version": schema_version, "tag": tag, "source_sha": source_sha,
"version": version, "target": target,
@@ -360,7 +386,7 @@ def verify(directory: Path, tag: str, source_sha: str, *, updater_enabled: bool
)
):
raise ValueError("Desktop Cua Driver provenance mismatch")
- elif driver.get("schema_version") == 2:
+ elif driver.get("schema_version") == 2: # driver provenance schema, not the record's
if (
any(driver.get(field) != pinned[field] for field in patched_fields)
or driver.get("target") != target
@@ -383,8 +409,13 @@ def verify(directory: Path, tag: str, source_sha: str, *, updater_enabled: bool
raise ValueError("Windows desktop source unexpectedly carries Cua Driver provenance")
if source != expected_source:
raise ValueError("Desktop source provenance mismatch")
- if (directory / names[3]).read_text(encoding="utf-8") != signature(target):
- raise ValueError("Desktop TEST signature policy mismatch")
+ expected_signature = (
+ signature(target)
+ if schema_version == DESKTOP_SOURCE_SCHEMA_VERSION
+ else LEGACY_SIGNATURE[TARGETS[target][0]]
+ )
+ if (directory / names[3]).read_text(encoding="utf-8") != expected_signature:
+ raise ValueError("Desktop release signature policy mismatch")
validate_manifest(json.loads((directory / names[1]).read_text(encoding="utf-8")), target, tag)
return [directory / name for name in sorted(expected)]
@@ -443,7 +474,7 @@ def main() -> None:
producer.add_argument("--installer", type=Path, required=True)
producer.add_argument("--runtime", type=Path, required=True)
producer.add_argument("--output", type=Path, required=True)
- producer.add_argument("--signing", required=True)
+ producer.add_argument("--signing", required=True, help="signing profile: developer-id or ad-hoc (macOS), unsigned (Windows)")
producer.add_argument("--prepared-driver", type=Path)
producer.add_argument("--driver", type=Path)
producer.add_argument("--driver-provenance-path", type=Path)
diff --git a/tests/test_desktop_macos_signing.py b/tests/test_desktop_macos_signing.py
new file mode 100644
index 000000000..fd811c7f5
--- /dev/null
+++ b/tests/test_desktop_macos_signing.py
@@ -0,0 +1,193 @@
+from __future__ import annotations
+
+import json
+import os
+import plistlib
+import stat
+import struct
+import sys
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "desktop" / "scripts"))
+import macos_signing as signing # noqa: E402
+
+
+COMPLETE = {
+ "APPLE_CERTIFICATE": "Y2VydGlmaWNhdGU=",
+ "APPLE_CERTIFICATE_PASSWORD": "certificate-password",
+ "APPLE_SIGNING_IDENTITY": f"Developer ID Application: Example Owner ({signing.TEAM_ID})",
+ "APPLE_TEAM_ID": signing.TEAM_ID,
+ "APPLE_API_KEY": "ABCDE12345",
+ "APPLE_API_ISSUER": "01234567-89ab-cdef-0123-456789abcdef",
+ "APPLE_API_PRIVATE_KEY": "-----BEGIN PRIVATE KEY-----\nfixture\n-----END PRIVATE KEY-----\n",
+}
+
+
+def test_release_code_identity_is_the_pinned_developer_id_requirement():
+ # TCC grants and Keychain ACLs bind to exactly this text; it must never drift.
+ assert signing.designated_requirement(signing.APP_IDENTIFIER) == (
+ 'designated => identifier "bot.avibe.desktop" and anchor apple generic and '
+ "certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */ and "
+ "certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */ and "
+ 'certificate leaf[subject.OU] = "68B2SQ6YK3"'
+ )
+ config = json.loads((ROOT / "desktop/src-tauri/tauri.conf.json").read_text(encoding="utf-8"))
+ assert config["identifier"] == signing.APP_IDENTIFIER
+ assert config["bundle"]["macOS"]["entitlements"] == signing.APP_ENTITLEMENTS.name
+ assert signing.HELPER_IDENTIFIER == "bot.avibe.desktop.cua-driver"
+
+
+def test_each_binary_carries_only_its_evidenced_entitlements():
+ def keys(path):
+ return set(plistlib.loads(path.read_bytes()))
+
+ assert keys(signing.PYTHON_ENTITLEMENTS["aarch64"]) == set()
+ assert keys(signing.PYTHON_ENTITLEMENTS["x86_64"]) == {
+ "com.apple.security.cs.allow-unsigned-executable-memory",
+ }
+ assert keys(signing.HELPER_ENTITLEMENTS) == set()
+ assert keys(signing.NODE_ENTITLEMENTS["aarch64"]) == {
+ "com.apple.security.cs.allow-jit",
+ "com.apple.security.cs.disable-library-validation",
+ }
+ assert keys(signing.NODE_ENTITLEMENTS["x86_64"]) == {
+ "com.apple.security.cs.allow-unsigned-executable-memory",
+ "com.apple.security.cs.disable-library-validation",
+ }
+
+
+ ("tag", "environment", "error"),
+ [
+ ("", {}, None),
+ ("gh-v3.2.4rc1", {}, "Release builds require the complete Apple credential set"),
+ ("v3.2.4", {}, "Release builds require the complete Apple credential set"),
+ ("", {**COMPLETE, "APPLE_TEAM_ID": ""}, "missing: APPLE_TEAM_ID"),
+ ("gh-v3.2.4rc1", {**COMPLETE, "APPLE_API_PRIVATE_KEY": ""}, "missing: APPLE_API_PRIVATE_KEY"),
+ ("gh-v3.2.4rc1", {**COMPLETE, "APPLE_TEAM_ID": "ABCDE12345"}, "pinned desktop Team"),
+ (
+ "gh-v3.2.4rc1",
+ {**COMPLETE, "APPLE_SIGNING_IDENTITY": "Developer ID Application: Someone Else (ABCDE12345)"},
+ "APPLE_SIGNING_IDENTITY",
+ ),
+ ("gh-v3.2.4rc1", {**COMPLETE, "APPLE_SIGNING_IDENTITY": "Apple Development: x (68B2SQ6YK3)"}, "APPLE_SIGNING_IDENTITY"),
+ ("gh-v3.2.4rc1", {**COMPLETE, "APPLE_API_PRIVATE_KEY": "not a key"}, "raw .p8"),
+ ],
+)
+def test_releases_fail_closed_and_manual_builds_accept_all_or_nothing(tmp_path, tag, environment, error):
+ env_file = tmp_path / "env"
+ if error is None:
+ signing.import_identity(environment, release_tag=tag, env_file=env_file, work_dir=tmp_path / "work")
+ assert env_file.read_text() == "apple_signing=absent\n"
+ assert not (tmp_path / "work").exists()
+ return
+ with pytest.raises(signing.SigningError, match=error):
+ signing.import_identity(environment, release_tag=tag, env_file=env_file, work_dir=tmp_path / "work")
+ assert not env_file.exists()
+
+
[email protected](os.name == "nt", reason="fake security tool is a POSIX script")
+def test_import_exports_locations_only_and_leaves_no_certificate(tmp_path, monkeypatch):
+ calls = tmp_path / "calls.jsonl"
+ security = tmp_path / "bin" / "security"
+ security.parent.mkdir()
+ security.write_text(
+ f"#!{sys.executable}\n"
+ "import json, sys\n"
+ f"open({str(calls)!r}, 'a').write(json.dumps(sys.argv[1:]) + '\\n')\n"
+ "if sys.argv[1] == 'list-keychains' and '-s' not in sys.argv:\n"
+ " print(' \"/Users/runner/Library/Keychains/login.keychain-db\"')\n"
+ "if sys.argv[1] == 'find-identity':\n"
+ f" print(' 1) 0123456789ABCDEF \"{COMPLETE['APPLE_SIGNING_IDENTITY']}\"')\n"
+ )
+ security.chmod(0o755)
+ monkeypatch.setenv("PATH", f"{security.parent}{os.pathsep}{os.environ['PATH']}")
+ env_file, work = tmp_path / "env", tmp_path / "work"
+
+ signing.import_identity(COMPLETE, release_tag="gh-v3.2.4rc1", env_file=env_file, work_dir=work)
+
+ exported = dict(line.split("=", 1) for line in env_file.read_text().splitlines())
+ assert exported == {
+ "apple_signing": "enabled",
+ "AVIBE_CODESIGN_IDENTITY": COMPLETE["APPLE_SIGNING_IDENTITY"],
+ "AVIBE_CODESIGN_KEYCHAIN": str(work / signing.KEYCHAIN_NAME),
+ "AVIBE_NOTARY_KEY_PATH": str(work / "AuthKey_ABCDE12345.p8"),
+ "AVIBE_NOTARY_KEY_ID": COMPLETE["APPLE_API_KEY"],
+ "AVIBE_NOTARY_ISSUER": COMPLETE["APPLE_API_ISSUER"],
+ }
+ key = Path(exported["AVIBE_NOTARY_KEY_PATH"])
+ assert key.read_text() == COMPLETE["APPLE_API_PRIVATE_KEY"]
+ assert stat.S_IMODE(key.stat().st_mode) == 0o600
+ assert sorted(path.name for path in work.iterdir()) == ["AuthKey_ABCDE12345.p8"]
+ commands = [json.loads(line) for line in calls.read_text().splitlines()]
+ assert [command[0] for command in commands] == [
+ "create-keychain", "set-keychain-settings", "unlock-keychain", "import",
+ "set-key-partition-list", "list-keychains", "list-keychains", "find-identity",
+ ]
+ assert commands[6][-2:] == [str(work / signing.KEYCHAIN_NAME), "/Users/runner/Library/Keychains/login.keychain-db"]
+
+
+def thin(filetype: int) -> bytes:
+ return struct.pack("<IIIII", 0xFEEDFACF, 0x0100000C, 0, filetype, 0) + bytes(12)
+
+
+def fat(filetype: int) -> bytes:
+ header = struct.pack(">II", 0xCAFEBABE, 2)
+ header += struct.pack(">IIIII", 0x01000007, 3, 4096, 32, 12)
+ header += struct.pack(">IIIII", 0x0100000C, 0, 8192, 32, 14)
+ body = bytearray(header.ljust(8192 + 32, b"\0"))
+ body[4096 : 4096 + 32] = thin(filetype)
+ body[8192 : 8192 + 32] = thin(filetype)
+ return bytes(body)
+
+
+def test_every_thin_and_universal_mach_o_is_found_and_nothing_else(tmp_path):
+ files = {
+ "python/bin/python3.12": thin(signing.MH_EXECUTE),
+ "python/lib/libpython3.12.dylib": thin(signing.MH_DYLIB),
+ "python/lib/site-packages/_native.so": fat(signing.MH_BUNDLE),
+ "python/lib/site-packages/Archive.class": struct.pack(">IHH", 0xCAFEBABE, 0, 52) + bytes(24),
+ "python/lib/libstub.a": b"!<arch>\n" + bytes(32),
+ "tools/npm/bin/npm-cli.js": b"#!/usr/bin/env node\n" + bytes(32),
+ "empty": b"",
+ }
+ for relative, content in files.items():
+ path = tmp_path / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(content)
+ (tmp_path / "python/bin/python3").symlink_to("python3.12")
+
+ found = {path.relative_to(tmp_path).as_posix(): filetype for path, filetype in signing.macho_files(tmp_path)}
+
+ assert found == {
+ "python/bin/python3.12": signing.MH_EXECUTE,
+ "python/lib/libpython3.12.dylib": signing.MH_DYLIB,
+ "python/lib/site-packages/_native.so": signing.MH_BUNDLE,
+ }
+
+
+def test_an_unreviewed_runtime_executable_stops_signing_before_any_codesign(tmp_path, monkeypatch):
+ for relative, filetype in {
+ "python/bin/python3.12": signing.MH_EXECUTE,
+ "tools/bin/node": signing.MH_EXECUTE,
+ "python/lib/libpython3.12.dylib": signing.MH_DYLIB,
+ "python/lib/site-packages/vendor/bin/helper": signing.MH_EXECUTE,
+ }.items():
+ path = tmp_path / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(thin(filetype))
+ (tmp_path / "python/bin/python3").symlink_to("python3.12")
+ monkeypatch.setattr(signing, "run", lambda *_args, **_kwargs: pytest.fail("nothing may be signed"))
+
+ with pytest.raises(signing.SigningError, match="vendor/bin/helper"):
+ signing.sign_runtime(
+ tmp_path,
+ arch="aarch64",
+ python_executable=tmp_path / "python/bin/python3",
+ node_executable=tmp_path / "tools/bin/node",
+ identity=COMPLETE["APPLE_SIGNING_IDENTITY"],
+ )
diff --git a/tests/test_desktop_release.py b/tests/test_desktop_release.py
index e7acf3aa0..4a7f91c40 100644
--- a/tests/test_desktop_release.py
+++ b/tests/test_desktop_release.py
@@ -114,12 +114,26 @@ def assemble_assets(root, source=SOURCE):
}
release.record(version=VERSION, target=target, tag=TAG, source_sha=source,
installer=installer, runtime=runtime, output=output,
- signing=release.signature(target).strip(), **driver_args)
+ signing=release.RELEASE_SIGNING_PROFILE[system], **driver_args)
for path in output.iterdir():
shutil.copyfile(path, directory / path.name)
return directory
+def rewrite_record(directory, target, *, source=None, signature=None):
+ """Replace a target's source record and/or SIGNATURE and re-hash, so only
+ the semantic checks can tell."""
+ names = release.asset_names(VERSION, target)
+ if source is not None:
+ (directory / names[2]).write_text(json.dumps(source, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ if signature is not None:
+ (directory / names[3]).write_text(signature, encoding="utf-8")
+ (directory / names[4]).write_text(
+ "".join(f"{release.digest(directory / name)} {name}\n" for name in sorted(names[:4])),
+ encoding="utf-8",
+ )
+
+
def git(directory, *args):
return subprocess.check_output(["git", "-C", str(directory), *args], text=True).strip()
@@ -183,6 +197,7 @@ def test_manual_prepare_retains_optional_signing_and_native_version(tmp_path):
"files": {
"Helpers/cua-driver": "binaries/cua-driver-aarch64-apple-darwin",
},
+ "signingIdentity": "-",
},
"resources": {
"../cua-driver/policy.yaml": "computer-use/policy.yaml",
@@ -215,30 +230,40 @@ def test_real_assembled_assets_pass_the_release_consumer(tmp_path):
source = json.loads(
(directory / release.asset_names(VERSION, target)[2]).read_text()
)
- assert source["schema_version"] == 2
+ assert source["schema_version"] == 3
+ signature = (directory / release.asset_names(VERSION, target)[3]).read_text()
+ if "darwin" in target:
+ assert signature == (
+ "runtime-developer-id-signed\n"
+ "app-developer-id-notarized-stapled\n"
+ "dmg-developer-id-notarized-stapled\n"
+ )
+ else:
+ assert signature == "installer-unsigned\n"
-def test_verify_accepts_published_schema_one_macos_metadata_without_driver(tmp_path):
[email protected]("schema", [1, 2])
+def test_verify_accepts_published_legacy_records_with_their_adhoc_layers(tmp_path, schema):
directory = assemble_assets(tmp_path)
for target, (system, _arch, _suffix) in release.TARGETS.items():
- if system != "macos":
- continue
names = release.asset_names(VERSION, target)
- source_path = directory / names[2]
- source = json.loads(source_path.read_text(encoding="utf-8"))
- source["schema_version"] = 1
- source.pop("computer_use_driver", None)
- source_path.write_text(json.dumps(source, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- (directory / names[4]).write_text(
- "".join(
- f"{release.digest(directory / name)} {name}\n"
- for name in sorted(names[:4])
- ),
- encoding="utf-8",
- )
+ source = json.loads((directory / names[2]).read_text(encoding="utf-8"))
+ source["schema_version"] = schema
+ if schema == 1:
+ source.pop("computer_use_driver", None)
+ legacy = "app-adhoc\ndmg-unsigned-unnotarized\n" if system == "macos" else None
+ rewrite_record(directory, target, source=source, signature=legacy)
assert len(release.verify(directory, TAG, SOURCE)) == 15
+def test_verify_requires_signed_macos_layers_on_current_records(tmp_path):
+ directory = assemble_assets(tmp_path)
+ target = "aarch64-apple-darwin"
+ rewrite_record(directory, target, signature="app-adhoc\ndmg-unsigned-unnotarized\n")
+ with pytest.raises(ValueError, match="signature policy"):
+ release.verify(directory, TAG, SOURCE)
+
+
def test_verify_rejects_schema_two_macos_metadata_without_driver(tmp_path):
directory = assemble_assets(tmp_path)
target = next(
@@ -249,7 +274,7 @@ def test_verify_rejects_schema_two_macos_metadata_without_driver(tmp_path):
names = release.asset_names(VERSION, target)
source_path = directory / names[2]
source = json.loads(source_path.read_text(encoding="utf-8"))
- assert source["schema_version"] == 2
+ assert source["schema_version"] == 3
source.pop("computer_use_driver")
source_path.write_text(
json.dumps(source, indent=2, sort_keys=True) + "\n",
@@ -399,7 +424,7 @@ def test_workflow_record_command_feeds_the_release_consumer(tmp_path, target):
env={**os.environ, "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
"AVIBE_DESKTOP_VERSION": VERSION, "RELEASE_TAG": TAG, "TARGET": target,
"RUNNER_OS": "macOS" if "darwin" in target else "Windows",
- "signature_state": "app-adhoc",
+ "apple_signing": "enabled",
"driver_packaged_path": str(work / "cua-driver"),
"driver_provenance_path": str(work / "driver-provenance.json"),
"driver_packaged_cdhash": "5" * 40},
@@ -443,7 +468,7 @@ def test_consumer_rejects_incomplete_or_mismatched_release(tmp_path, mutation):
release.verify(directory, TAG, SOURCE)
[email protected]("mutation", ["archive", "version", "signing"])
[email protected]("mutation", ["archive", "version", "signing", "ad-hoc-release"])
def test_producer_rejects_incorrect_runtime_or_signing(tmp_path, mutation):
assemble_assets(tmp_path)
target = next(iter(release.TARGETS))
@@ -466,12 +491,26 @@ def test_producer_rejects_incorrect_runtime_or_signing(tmp_path, mutation):
}
release.record(version=VERSION, target=target, tag=TAG, source_sha=SOURCE,
installer=work / "native installer.dmg", runtime=work / "runtime",
- output=work / "rejected", signing="identity" if mutation == "signing"
- else release.signature(target).strip(), **driver_args)
+ output=work / "rejected", signing={"signing": "identity", "ad-hoc-release": "ad-hoc"}.get(
+ mutation, "developer-id"), **driver_args)
assert not (work / "rejected").exists()
-def test_workflow_preserves_manual_path_and_isolates_test_signing():
[email protected](("profile", "layers"), [
+ ("developer-id", "runtime-developer-id-signed\napp-developer-id-notarized-stapled\ndmg-developer-id-notarized-stapled\n"),
+ ("ad-hoc", "runtime-unsigned\napp-adhoc\ndmg-unsigned-unnotarized\n"),
+])
+def test_manual_record_names_the_layers_it_produced(tmp_path, profile, layers):
+ assemble_assets(tmp_path)
+ work = tmp_path / "aarch64-apple-darwin"
+ release.record(version="3.1.2-dev.1", target="aarch64-apple-darwin", tag="", source_sha=SOURCE,
+ installer=work / "native installer.dmg", runtime=work / "runtime", output=work / "manual",
+ signing=profile, prepared_driver=work / "prepared-cua-driver", driver=work / "cua-driver",
+ driver_provenance_path=work / "driver-provenance.json", driver_cdhash="5" * 40)
+ assert (work / "manual" / "Avibe_3.1.2-dev.1_aarch64-apple-darwin.SIGNATURE").read_text() == layers
+
+
+def test_workflow_signs_every_macos_layer_before_recording():
package = workflow("desktop-package.yml")
triggers = package.get("on", package.get(True))
assert set(triggers) == {"workflow_dispatch", "workflow_call"}
@@ -486,26 +525,46 @@ def test_workflow_preserves_manual_path_and_isolates_test_signing():
steps = build["steps"]
assert steps[0]["with"]["ref"] == "${{ inputs.source_sha || github.sha }}"
assert {entry["target"] for entry in build["strategy"]["matrix"]["include"]} == set(release.TARGETS)
- assert steps.index(step("Prepare package version")) < steps.index(step("Build verified private Runtime"))
- credentials = step("Export Apple signing credentials when configured")
- assert credentials["if"] == "runner.os == 'macOS' && inputs.release_tag == ''"
+ assert not any("continue-on-error" in item for item in steps)
+ order = [
+ "Prepare package version",
+ "Import Apple signing identity",
+ "Build verified private Runtime",
+ "Verify prepared Cua Driver provenance",
+ "Build self-contained installer",
+ "Sign macOS app",
+ "Smoke-test macOS app launch",
+ "Create headless-safe DMG",
+ "Sign and notarize macOS DMG",
+ "Record artifact hashes",
+ "Sign and verify final updater artifacts",
+ ]
+ assert [steps.index(step(name)) for name in order] == sorted(steps.index(step(name)) for name in order)
+ # Every macOS build imports: a tag build fails there without the complete set.
+ identity = step("Import Apple signing identity")
+ assert identity["if"] == "runner.os == 'macOS'"
+ assert identity["env"]["RELEASE_TAG"] == "${{ inputs.release_tag }}"
+ assert "import-identity" in identity["run"]
prepared_driver = step("Verify prepared Cua Driver provenance")
assert prepared_driver["if"] == "runner.os == 'macOS'"
assert "verify-driver-prepared" in prepared_driver["run"]
- assert steps.index(prepared_driver) + 1 == steps.index(
- step("Build self-contained installer")
- )
- signing = step("Verify macOS app signature matches the signing path")["run"]
- assert signing.count(
- "--preserve-metadata=identifier,entitlements,flags,runtime"
- ) == 2
- assert "\"$driver\"" in signing
- assert "\"$app\"" in signing
+ assert steps.index(prepared_driver) + 1 == steps.index(step("Build self-contained installer"))
+ signing = step("Sign macOS app")["run"]
+ assert "macos_signing.py sign-app" in signing and "macos_signing.py notarize" in signing
+ assert "release builds must be Developer ID signed" in signing
+ # The manual no-credential branch keeps the ad-hoc, inside-out seal.
+ assert signing.count("--preserve-metadata=identifier,entitlements,flags,runtime") == 2
assert "--deep --sign" not in signing
assert "Contents/Helpers/cua-driver" in signing
assert "Contents/MacOS/cua-driver" in signing
+ dmg = step("Sign and notarize macOS DMG")
+ assert dmg["if"] == "runner.os == 'macOS' && env.apple_signing == 'enabled'"
+ for command in ("sign-dmg", "notarize", "verify-release"):
+ assert f"macos_signing.py {command}" in dmg["run"]
assert "NotSigned" in step("Verify unsigned Windows installer")["run"]
- assert steps[-1]["uses"] == "actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f"
+ assert steps[-2]["uses"] == "actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f"
+ assert steps[-1]["name"] == "Remove Apple signing material"
+ assert steps[-1]["if"] == "always() && runner.os == 'macOS'"
workflow_text = (ROOT / ".github/workflows/desktop-package.yml").read_text(encoding="utf-8")
assert "computer-use-test-overrides" not in workflow_text
assert "AVIBE_COMPUTER_USE_DRIVER_PATH" not in workflow_text
@@ -545,40 +604,31 @@ def test_secret_scanner_fails_closed_on_every_noncanonical_form(value, names):
assert secret_references({"env": {"VALUE": value}}) == names
-def test_inherited_secrets_reach_test_builds_only_as_the_updater_pair():
+def test_apple_secrets_reach_only_the_identity_import_and_never_tauri():
package = workflow("desktop-package.yml")
assert package["on" if "on" in package else True]["workflow_call"]["inputs"]["release_tag"]["required"] is True
assert secret_references({key: value for key, value in package.items() if key != "jobs"}) == set()
updater = {"TAURI_SIGNING_PRIVATE_KEY", "TAURI_SIGNING_PRIVATE_KEY_PASSWORD"}
- reachable = set()
+ apple = {
+ "APPLE_CERTIFICATE", "APPLE_CERTIFICATE_PASSWORD", "APPLE_SIGNING_IDENTITY", "APPLE_TEAM_ID",
+ "APPLE_API_KEY", "APPLE_API_ISSUER", "APPLE_API_PRIVATE_KEY",
+ }
+ by_step = {}
for job in package["jobs"].values():
assert secret_references({key: value for key, value in job.items() if key != "steps"}) == set()
for item in job["steps"]:
names = secret_references(item)
assert None not in names, item.get("name")
- if names - updater:
- condition = item.get("if", "")
- assert "||" not in condition, item.get("name")
- assert re.fullmatch(r"(.+ && )?inputs\.release_tag == ''", condition), item.get("name")
- else:
- reachable |= names
- assert reachable == updater
-
-
[email protected]("configured", [False, True])
-def test_manual_apple_export_still_consumes_complete_optional_credentials(tmp_path, configured):
- export = step("Export Apple signing credentials when configured")
- env = {**os.environ, **{key: "" for key in export["env"]},
- "GITHUB_ENV": str(tmp_path / "env"), "TMPDIR": str(tmp_path)}
- if configured:
- env.update({key: "fixture-value" for key in export["env"]})
- result = subprocess.run(["bash", "-e", "-c", export["run"]], env=env, capture_output=True, text=True)
- assert result.returncode == 0, result.stderr
- exported = (tmp_path / "env").read_text()
- assert f"apple_signing={'enabled' if configured else 'absent'}" in exported
- if configured:
- key = next(line.split("=", 1)[1] for line in exported.splitlines() if line.startswith("APPLE_API_KEY_PATH="))
- assert Path(key).read_text() == "fixture-value"
+ if names:
+ by_step[item["name"]] = names
+ assert by_step.pop("Import Apple signing identity") == apple
+ assert set().union(*by_step.values()) == updater
+ # Exported names stay outside what tauri-bundler reads, so the bundler can
+ # never sign or notarize with an identity on its own.
+ import_run = step("Import Apple signing identity")["run"]
+ assert "--env-file \"$GITHUB_ENV\"" in import_run
+ installer = step("Build self-contained installer")
+ assert not any(key.startswith("APPLE_") for key in installer.get("env", {}))
@pytest.mark.parametrize("state", ["new", "draft-partial", "published-identical", "published-legacy",