Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(macos): sign the app bundle with a per-user certificate so TCC grants survive rebuilds

Harald Herz89e230b68d38
diff --git a/install/installer.py b/install/installer.py
index deac08801f..f1866aac7b 100644
--- a/install/installer.py
+++ b/install/installer.py
@@ -565,16 +565,27 @@ def step_desktop_integration(*, enabled: bool, dry_run: bool) -> bool:
return True
result = None
report = {}
+ argv = [
+ str(venv_python()),
+ "-m",
+ "jarvis.setup.desktop_integration",
+ "--install-dir",
+ str(repo_root()),
+ "--json",
+ ]
+ if sys.platform == "darwin":
+ # The per-user signing certificate keeps the app's macOS permissions
+ # across every future update. Trusting it is the one step macOS
+ # guards with a password dialog — say so before it appears.
+ argv.append("--create-signing-identity")
+ console.print(
+ "[muted]│ macOS may ask for your login password once: it trusts the "
+ f"local signing certificate that keeps {PRODUCT_NAME}'s permissions "
+ "across updates[/]"
+ )
try:
result = run_captured(
- [
- str(venv_python()),
- "-m",
- "jarvis.setup.desktop_integration",
- "--install-dir",
- str(repo_root()),
- "--json",
- ],
+ argv,
cwd=repo_root(),
label="registering the desktop app (a macOS first run can take a few minutes)",
# py2app build + icon conversion + signing + LaunchServices import
diff --git a/jarvis/core/branding.py b/jarvis/core/branding.py
index 71dbffd6c7..2ddcacaa4b 100644
--- a/jarvis/core/branding.py
+++ b/jarvis/core/branding.py
@@ -43,6 +43,9 @@ MACOS_APP_DIR_NAME = f"{MACOS_APP_NAME}.app"
MACOS_EXECUTABLE_NAME = PRODUCT_COMPACT_NAME
MACOS_BUNDLE_ID = f"com.{PRODUCT_SLUG}.desktop"
MACOS_AUTOSTART_LABEL = f"com.{PRODUCT_SLUG}.autostart"
+# Common name of the per-user self-signed code-signing certificate the
+# installer creates so the app bundle keeps one TCC identity across rebuilds.
+MACOS_SIGNING_IDENTITY_LABEL = f"{MACOS_APP_NAME} Local Signing"
LINUX_APP_NAME = PRODUCT_NAME
LINUX_DESKTOP_ENTRY_FILE_NAME = f"{PRODUCT_SLUG}.desktop"
@@ -92,6 +95,7 @@ __all__ = [
"MACOS_AUTOSTART_LABEL",
"MACOS_BUNDLE_ID",
"MACOS_EXECUTABLE_NAME",
+ "MACOS_SIGNING_IDENTITY_LABEL",
"MANAGED_INSTALL_MARKER",
"OFFICIAL_RELEASES_LATEST_API_URL",
"OFFICIAL_REPO_GIT_URL",
diff --git a/jarvis/setup/desktop_integration.py b/jarvis/setup/desktop_integration.py
index 0c24498a20..2bc5c8f262 100644
--- a/jarvis/setup/desktop_integration.py
+++ b/jarvis/setup/desktop_integration.py
@@ -318,11 +318,15 @@ def ensure_desktop_integration(
windows_aumid: str = WINDOWS_APP_USER_MODEL_ID,
macos_applications_dir: Path | None = None,
linux_applications_dir: Path | None = None,
+ macos_create_signing_identity: bool = False,
) -> DesktopIntegrationReport:
"""Install or repair the current platform's desktop-shell artifacts.
Returns an ``attempted=False`` report on a frozen build: the native
installer already registered the app and nothing here may touch it.
+ ``macos_create_signing_identity`` permits the one-time trust dialog for
+ the per-user signing certificate — the installer's call only, never the
+ app's background repair.
"""
plat = _platform(platform)
@@ -410,6 +414,7 @@ def ensure_desktop_integration(
bundle = macos_app_bundle.ensure_macos_app_bundle(
install_dir=root,
applications_dir=macos_applications_dir,
+ create_signing_identity=macos_create_signing_identity,
)
if bundle is not None:
artifacts.append("applications_bundle")
@@ -556,6 +561,11 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--remove", action="store_true")
parser.add_argument("--allow-unmanaged", action="store_true")
parser.add_argument("--json", action="store_true")
+ parser.add_argument(
+ "--create-signing-identity",
+ action="store_true",
+ help="macOS: create and trust the per-user signing certificate (one password dialog)",
+ )
args = parser.parse_args(argv)
report = (
@@ -564,6 +574,7 @@ def main(argv: list[str] | None = None) -> int:
else ensure_desktop_integration(
install_dir=args.install_dir,
require_managed=not args.allow_unmanaged,
+ macos_create_signing_identity=args.create_signing_identity,
)
)
if args.json:
diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.py
index d5922d5317..a5fcd52054 100644
--- a/jarvis/setup/macos_app_bundle.py
+++ b/jarvis/setup/macos_app_bundle.py
@@ -9,16 +9,21 @@ the app process and runs the managed entry script, so it works with framework
AND non-framework interpreters (for example uv-managed standalone builds)
while the source and dependencies remain in the managed checkout.
-The locally generated app is ad-hoc signed and is preserved byte-for-byte on
-ordinary source updates so its local TCC identity does not churn. When a
-rebuild is unavoidable (format bump, broken bundle), the ad-hoc code signature
-changes and macOS orphans every previously recorded TCC grant — the old rows
-then read as silently DENIED for the "new" app and macOS never prompts again
-(BUG-083). After such a signature change this module therefore resets the
-stale TCC rows for our bundle id via ``tccutil`` so the app can prompt fresh.
-Public binary distribution still requires the separate Developer-ID signing
-and notarization pipeline; this module never claims an ad-hoc app is a
-notarized artifact.
+The locally generated app is signed with the per-user code-signing identity
+from ``macos_signing_identity`` whenever one exists. macOS then pins the TCC
+grants to ``identifier + certificate`` instead of to the code-directory hash,
+so the bundle can be rebuilt as often as needed without losing a single
+permission. Without that identity (no GUI session at install time, the user
+declined the one trust dialog) the app falls back to an ad-hoc signature and
+is preserved byte-for-byte on ordinary source updates so its identity does
+not churn. When the TCC identity does change (ad-hoc rebuild, or the one-time
+migration from ad-hoc to the certificate), macOS orphans every previously
+recorded grant — the old rows then read as silently DENIED for the "new" app
+and macOS never prompts again (BUG-083). After such a change this module
+resets the stale TCC rows for our bundle id via ``tccutil`` so the app can
+prompt fresh. Public binary distribution still requires the separate
+Developer-ID signing and notarization pipeline; this module never claims a
+locally signed app is a notarized artifact.
"""
from __future__ import annotations
@@ -49,6 +54,7 @@ from jarvis.core.branding import (
MACOS_EXECUTABLE_NAME,
)
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.setup.macos_signing_identity import ensure_local_signing_identity
log = logging.getLogger(__name__)
@@ -67,6 +73,11 @@ _TCC_SERVICES: tuple[str, ...] = (
"Accessibility",
"ListenEvent",
"PostEvent",
+ # Automation consent for the Music/Spotify ducking scripts. It is keyed to
+ # our code requirement exactly like the rows above, so a stale row here
+ # made the Music prompt "come back" after every rebuild while never
+ # showing up in any permission view.
+ "AppleEvents",
)
_MACHO_MAGICS = frozenset(
{
@@ -198,16 +209,51 @@ def _bundle_cdhash(bundle: Path) -> str | None:
return match.group(1) if match else None
-def _tcc_reset_needed(previous_cdhash: str | None, current_cdhash: str | None) -> bool:
- """A signature change (or an unknowable previous one) orphans TCC rows."""
- return current_cdhash is not None and previous_cdhash != current_cdhash
+def _bundle_tcc_identity(bundle: Path) -> str | None:
+ """Return the bundle's designated requirement — what TCC pins grants to.
+
+ ``cdhash H"..."`` for an ad-hoc signature (a new one per rebuild) and
+ ``identifier "..." and certificate leaf = H"..."`` for a certificate
+ signature (the same one for every rebuild). ``None`` when unreadable.
+ """
+ if sys.platform != "darwin":
+ return None
+ try:
+ result = subprocess.run(
+ ["/usr/bin/codesign", "--display", "-r-", str(bundle)],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ return _parse_designated_requirement(f"{result.stdout or ''}\n{result.stderr or ''}")
+
+
+def _parse_designated_requirement(text: str) -> str | None:
+ """Pull the ``designated => ...`` requirement out of ``codesign -r-`` output."""
+ match = re.search(r"^(?:#\s*)?designated\s*=>\s*(.+?)\s*$", text, re.MULTILINE)
+ return match.group(1) if match else None
+
+
+def _signed_with_certificate(bundle: Path) -> bool:
+ """Whether the bundle's TCC identity is certificate-bound (rebuild-proof)."""
+ identity = _bundle_tcc_identity(bundle)
+ return identity is not None and "certificate leaf" in identity
+
+
+def _tcc_reset_needed(previous_identity: str | None, current_identity: str | None) -> bool:
+ """An identity change (or an unknowable previous one) orphans TCC rows."""
+ return current_identity is not None and previous_identity != current_identity
def _reset_stale_tcc_grants(runner=subprocess.run) -> None:
"""Drop this app's orphaned TCC rows so macOS can prompt fresh (BUG-083).
- After a signature change the recorded grants belong to the OLD CDHash: the
- rebuilt app reads them as DENIED and macOS suppresses every further prompt,
+ After an identity change the recorded grants belong to the OLD code
+ requirement: the app reads them as DENIED and macOS suppresses every prompt,
so permissions appear "auto-rejected" without the user ever being asked.
Resetting is scoped to our bundle id, is best-effort per service, and never
raises — a failed reset leaves behavior no worse than before. The caller
@@ -246,23 +292,31 @@ def _rebuild_marker_path() -> Path:
return user_data_dir() / _REBUILD_MARKER_FILENAME
-def _rebuild_fingerprint(bundle: Path, *, install_root: Path) -> dict[str, str | None]:
+def _rebuild_fingerprint(
+ bundle: Path, *, install_root: Path, identity: str | None = None
+) -> dict[str, str | None]:
"""Everything that decides whether a fresh build could come out different."""
return {
"cdhash": _bundle_cdhash(bundle),
"install_root": str(install_root),
"python": f"{sys.version_info.major}.{sys.version_info.minor}",
"machine": platform.machine(),
+ # A signing identity that appeared since the last build is a reason to
+ # build again: the result carries a rebuild-proof TCC identity.
+ "identity": identity,
}
-def _record_rebuild(bundle: Path, *, install_root: Path) -> None:
+def _record_rebuild(bundle: Path, *, install_root: Path, identity: str | None = None) -> None:
"""Note what this rebuild produced, so a repeat of it can be recognized."""
marker = _rebuild_marker_path()
try:
marker.parent.mkdir(parents=True, exist_ok=True)
marker.write_text(
- json.dumps(_rebuild_fingerprint(bundle, install_root=install_root), sort_keys=True),
+ json.dumps(
+ _rebuild_fingerprint(bundle, install_root=install_root, identity=identity),
+ sort_keys=True,
+ ),
encoding="utf-8",
)
except OSError:
@@ -271,16 +325,17 @@ def _record_rebuild(bundle: Path, *, install_root: Path) -> None:
log.debug("Could not record the macOS bundle rebuild fingerprint.", exc_info=True)
-def _rebuild_would_repeat(bundle: Path, *, install_root: Path) -> bool:
+def _rebuild_would_repeat(bundle: Path, *, install_root: Path, identity: str | None = None) -> bool:
"""Whether rebuilding now would reproduce the build that just failed a probe.
- Same sources, same interpreter, same machine, and the bundle on disk is
- still byte-identical to what the last rebuild signed: a fresh build can
- only produce the same app and fail the same probe again. Doing it anyway
- changes the ad-hoc signature, and macOS answers a changed signature by
- orphaning every recorded TCC grant — the "I allow everything, restart, and
- it asks again" loop (BUG-161). A launchable bundle is worth more than a
- probe verdict that no rebuild can satisfy.
+ Same sources, same interpreter, same machine, same signing identity, and
+ the bundle on disk is still byte-identical to what the last rebuild
+ signed: a fresh build can only produce the same app and fail the same
+ probe again. Doing it anyway changes an ad-hoc signature, and macOS
+ answers a changed signature by orphaning every recorded TCC grant — the
+ "I allow everything, restart, and it asks again" loop (BUG-161). A
+ launchable bundle is worth more than a probe verdict that no rebuild can
+ satisfy.
"""
try:
recorded = json.loads(_rebuild_marker_path().read_text(encoding="utf-8"))
@@ -290,7 +345,7 @@ def _rebuild_would_repeat(bundle: Path, *, install_root: Path) -> bool:
return False
if not isinstance(recorded, dict):
return False
- current = _rebuild_fingerprint(bundle, install_root=install_root)
+ current = _rebuild_fingerprint(bundle, install_root=install_root, identity=identity)
if current["cdhash"] is None:
# Without a readable signature we cannot prove the bundle is the one
# the last rebuild produced, so the guard must not suppress a repair.
@@ -381,23 +436,32 @@ _LSREGISTER = (
def register_with_launch_services(bundle: Path) -> bool:
- """Announce the bundle to LaunchServices so Spotlight can find it.
-
- Writing the ``.app`` is only half the job. Spotlight, Launchpad and the
- ``open -a`` name lookup all resolve through the LaunchServices database,
- which is rebuilt from directory scans that are not immediate — a bundle
- written into ``~/Applications`` is routinely unsearchable until the next
- login. ``lsregister`` is the documented way to register one bundle right
- away, and it is the macOS counterpart of the Windows Start-Menu shell
- notification and the Linux ``update-desktop-database`` call: without it the
- freshly installed app is on disk but absent from the user's search.
-
- Best-effort and idempotent: re-registering an already-known bundle is a
- no-op for LaunchServices. Returns ``True`` only when the tool ran cleanly;
- a failure degrades to "appears after the next login", never to an error.
+ """Announce the bundle to LaunchServices AND Spotlight.
+
+ Writing the ``.app`` is only half the job. Launchpad and the ``open -a``
+ name lookup resolve through the LaunchServices database, which is rebuilt
+ from directory scans that are not immediate. ``lsregister`` registers one
+ bundle right away — the macOS counterpart of the Windows Start-Menu shell
+ notification and the Linux ``update-desktop-database`` call.
+
+ Spotlight is NOT that database: its search field answers from the per-volume
+ metadata store, so a bundle LaunchServices knows can still be missing from
+ Spotlight (the 2026-09-16 report). The bundle is therefore also imported
+ into Spotlight, which warns with the admin repair command when the volume's
+ index itself is broken (``macos_search_index``).
+
+ Best-effort and idempotent. Returns ``True`` only when ``lsregister`` ran
+ cleanly; a failure degrades to "appears after the next login", never to an
+ error.
"""
if sys.platform != "darwin":
return False
+ from jarvis.setup.macos_search_index import announce_to_spotlight
+
+ try:
+ announce_to_spotlight(bundle)
+ except Exception as exc: # noqa: BLE001 - search registration is best-effort
+ log.debug("Spotlight import skipped: %s", exc)
tool = Path(_LSREGISTER)
if not tool.is_file():
log.debug("lsregister not present; relying on the periodic rescan")
@@ -693,9 +757,11 @@ def _build_native_bundle(install_root: Path, work_dir: Path) -> Path:
return bundle
-def _sign_bundle(bundle: Path) -> None:
+def _sign_bundle(bundle: Path, identity: str | None = None) -> None:
+ """Sign with the local identity (rebuild-proof TCC) or ad-hoc (``None``)."""
+ signer = identity or "-"
result = subprocess.run(
- ["/usr/bin/codesign", "--force", "--deep", "--sign", "-", str(bundle)],
+ ["/usr/bin/codesign", "--force", "--deep", "--sign", signer, str(bundle)],
capture_output=True,
text=True,
timeout=60,
@@ -704,7 +770,8 @@ def _sign_bundle(bundle: Path) -> None:
)
if result.returncode != 0:
detail = (result.stderr or result.stdout or "unknown codesign error").strip()
- raise RuntimeError(f"ad-hoc code signing failed: {detail[-1200:]}")
+ kind = "ad-hoc" if identity is None else f"identity {identity}"
+ raise RuntimeError(f"code signing ({kind}) failed: {detail[-1200:]}")
issue = _codesign_issue(bundle)
if issue is not None:
raise RuntimeError(
@@ -833,15 +900,17 @@ def _running_managed_bundle(
return None
-def _install_native_bundle(install_root: Path, bundle: Path) -> Path:
+def _install_native_bundle(
+ install_root: Path, bundle: Path, *, identity: str | None = None
+) -> Path:
"""Build beside the destination and replace it atomically with rollback."""
parent = bundle.parent
parent.mkdir(parents=True, exist_ok=True)
- previous_cdhash = _bundle_cdhash(bundle) if bundle.exists() else None
+ previous_identity = _bundle_tcc_identity(bundle) if bundle.exists() else None
with tempfile.TemporaryDirectory(prefix=".jarvis-native-", dir=parent) as raw_work:
work = Path(raw_work)
built = _build_native_bundle(install_root, work)
- _sign_bundle(built)
+ _sign_bundle(built, identity)
previous = work / "previous.app"
if bundle.exists() or bundle.is_symlink():
bundle.rename(previous)
@@ -865,13 +934,50 @@ def _install_native_bundle(install_root: Path, bundle: Path) -> Path:
if previous.exists() or previous.is_symlink():
previous.rename(bundle)
raise
- # The rebuild changed the app's TCC identity: every recorded grant is now
- # orphaned and would read as silently DENIED (BUG-083).
- _reset_or_explain(bundle, previous_cdhash)
+ # An ad-hoc rebuild changed the app's TCC identity: every recorded grant
+ # is now orphaned and would read as silently DENIED (BUG-083). With the
+ # certificate identity the requirement is unchanged and nothing is reset.
+ _reset_or_explain(bundle, previous_identity)
+ return bundle
+
+
+def _resign_bundle_in_place(bundle: Path, identity: str) -> Path:
+ """Move a healthy ad-hoc bundle onto the certificate identity.
+
+ Same files, new signature: a copy is signed beside the original and
+ swapped in atomically, so a running instance keeps its own (old) inode
+ and nothing is ever half-signed on disk. This is the ONE remaining
+ identity change the user pays for with a final round of re-granting —
+ after it, no rebuild can orphan a grant again.
+ """
+ parent = bundle.parent
+ previous_identity = _bundle_tcc_identity(bundle)
+ with tempfile.TemporaryDirectory(prefix=".jarvis-resign-", dir=parent) as raw_work:
+ work = Path(raw_work)
+ staged = work / bundle.name
+ shutil.copytree(bundle, staged, symlinks=True)
+ _sign_bundle(staged, identity)
+ if not _signed_with_certificate(staged):
+ raise RuntimeError("re-signing produced a bundle without a certificate identity")
+ previous = work / "previous.app"
+ bundle.rename(previous)
+ try:
+ staged.rename(bundle)
+ if not macos_app_bundle_is_launchable(bundle):
+ raise RuntimeError(
+ "the re-signed macOS application bundle failed the launchable check"
+ )
+ except Exception:
+ _remove_path(bundle)
+ if previous.exists() or previous.is_symlink():
+ previous.rename(bundle)
+ raise
+ log.info("Moved the macOS app bundle onto the local signing identity: %s", bundle)
+ _reset_or_explain(bundle, previous_identity)
return bundle
-def _reset_or_explain(bundle: Path, previous_cdhash: str | None) -> None:
+def _reset_or_explain(bundle: Path, previous_identity: str | None) -> None:
"""Reset the orphaned TCC rows once — never in a loop (BUG-159).
A rebuild that keeps recurring (a failing identity probe, a churning
@@ -887,7 +993,7 @@ def _reset_or_explain(bundle: Path, previous_cdhash: str | None) -> None:
record_identity_reset,
)
- if not _tcc_reset_needed(previous_cdhash, _bundle_cdhash(bundle)):
+ if not _tcc_reset_needed(previous_identity, _bundle_tcc_identity(bundle)):
return
if identity_reset_pending():
log.warning(
@@ -908,12 +1014,16 @@ def ensure_macos_app_bundle(
*,
install_dir: Path | None = None,
applications_dir: Path | None = None,
+ create_signing_identity: bool = False,
) -> Path | None:
"""Ensure ``~/Applications/Personal Jarvis.app`` has a stable identity.
A valid existing bundle is preserved byte-for-byte so normal source
- updates cannot churn its local TCC identity. Off macOS, this is a no-op
- unless a caller explicitly injects an applications directory for tests.
+ updates cannot churn its local TCC identity. ``create_signing_identity``
+ allows the one password dialog that trusts a fresh per-user signing
+ certificate — only the installer passes it; the running app merely looks
+ the identity up. Off macOS, this is a no-op unless a caller explicitly
+ injects an applications directory for tests.
"""
global _LAST_ERROR
_LAST_ERROR = None
@@ -926,17 +1036,41 @@ def ensure_macos_app_bundle(
install_root = (install_dir or _default_install_dir()).resolve()
bundle = macos_app_bundle_path(applications_dir=applications_dir)
diagnostics: list[str] = []
+ identity = (
+ ensure_local_signing_identity(create=create_signing_identity)
+ if sys.platform == "darwin"
+ else None
+ )
# The app running right now IS the installed app — including when the
# user keeps it in /Applications. Nothing to repair, and a rebuild
# under our bundle id here would strip the grants of the very process
- # asking the question (BUG-161).
+ # asking the question (BUG-161). The same goes for moving it onto the
+ # certificate identity: the reset that follows would hit this very
+ # process, so that migration waits for the installer.
running = _running_managed_bundle(install_root=install_root, diagnostics=diagnostics)
if running is not None:
register_with_launch_services(running)
+ if identity is not None and not _signed_with_certificate(running):
+ log.info(
+ "The running app is still ad-hoc signed; the next installer run "
+ "moves it onto the local signing identity."
+ )
return running
launchable_issue = _launchable_issue(bundle) if bundle.exists() else "bundle not installed"
if launchable_issue is None:
if _runtime_identity_valid(bundle, install_root=install_root, diagnostics=diagnostics):
+ if identity is not None and not _signed_with_certificate(bundle):
+ # Healthy but ad-hoc: same files, rebuild-proof signature.
+ # One last round of re-granting, then never again.
+ log.warning(
+ "Re-signing the macOS app bundle with the local signing identity "
+ "(this resets its macOS permissions one final time) [%s]",
+ bundle,
+ )
+ resigned = _resign_bundle_in_place(bundle, identity)
+ register_with_launch_services(resigned)
+ _record_rebuild(resigned, install_root=install_root, identity=identity)
+ return resigned
# A healthy bundle is kept byte-for-byte, but LaunchServices may
# still not know it — an interrupted earlier run, or a database
# rebuilt since. Re-registering is a no-op when it is known, and
@@ -944,7 +1078,7 @@ def ensure_macos_app_bundle(
register_with_launch_services(bundle)
return bundle
launchable_issue = "; ".join(diagnostics) or "identity probe failed without detail"
- if _rebuild_would_repeat(bundle, install_root=install_root):
+ if _rebuild_would_repeat(bundle, install_root=install_root, identity=identity):
# The last rebuild already produced exactly this bundle and the
# probe still refuses it. Building it again would only change
# the signature and cost the user every permission, so keep the
@@ -958,20 +1092,24 @@ def ensure_macos_app_bundle(
)
register_with_launch_services(bundle)
return bundle
- # A rebuild is never routine: it changes the ad-hoc signature and macOS
- # then discards every permission the user granted. Say why, at WARNING,
- # so a recurring rebuild is visible in the log instead of showing up as
- # "the app keeps forgetting my permissions".
+ # A rebuild is never routine: without the signing identity it changes
+ # the ad-hoc signature and macOS then discards every permission the
+ # user granted. Say why, at WARNING, so a recurring rebuild is visible
+ # in the log instead of showing up as "the app keeps forgetting my
+ # permissions".
log.warning(
- "Rebuilding the macOS app bundle (this resets its macOS permissions) — reason: %s [%s]",
+ "Rebuilding the macOS app bundle (%s) — reason: %s [%s]",
+ "permissions are kept: local signing identity"
+ if identity is not None
+ else "this resets its macOS permissions",
launchable_issue,
bundle,
)
if sys.platform != "darwin":
return _write_cross_platform_fixture_bundle(bundle)
- installed = _install_native_bundle(install_root, bundle)
+ installed = _install_native_bundle(install_root, bundle, identity=identity)
register_with_launch_services(installed)
- _record_rebuild(installed, install_root=install_root)
+ _record_rebuild(installed, install_root=install_root, identity=identity)
log.info("Native macOS app bundle installed: %s", installed)
return installed
except Exception as exc: # noqa: BLE001 - installer consumes the None result
diff --git a/jarvis/setup/macos_signing_identity.py b/jarvis/setup/macos_signing_identity.py
new file mode 100644
index 0000000000..d2f7a25402
--- /dev/null
+++ b/jarvis/setup/macos_signing_identity.py
@@ -0,0 +1,264 @@
+"""Per-machine code-signing identity for the managed macOS app bundle.
+
+macOS TCC pins every privacy grant (Microphone, Screen Recording, ...) to an
+app's *designated requirement*. For an ad-hoc signature that requirement is
+the code-directory hash itself, so every rebuild of the app is a brand-new
+app to TCC and every grant is orphaned (BUG-083/159/161). Signing with a
+certificate changes the requirement to ``identifier "<bundle id>" and
+certificate leaf = H"<cert hash>"`` — stable for as long as the same
+certificate signs the bundle, however often its contents change.
+
+There is no Developer ID on the source-install path, so this module creates a
+self-signed code-signing certificate ONCE per user, keeps it in the login
+keychain, and trusts it for code signing in the user's own trust domain. The
+trust step is the one place macOS asks for the login password; everything
+else is silent. Creation therefore only ever runs from the installer, where a
+dialog is expected — the app itself only *looks up* the identity.
+
+Pure stdlib + ``cryptography``; every ``security`` call is bounded and the
+whole thing degrades to ``None`` (= ad-hoc signing, the previous behaviour)
+rather than raising.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+import secrets
+import subprocess
+import sys
+import tempfile
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+
+from jarvis.core.branding import MACOS_SIGNING_IDENTITY_LABEL as IDENTITY_LABEL
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+log = logging.getLogger(__name__)
+
+_SECURITY = "/usr/bin/security"
+_CODESIGN = "/usr/bin/codesign"
+# `security find-identity -v` prints one line per identity:
+# 1) 0E147B028894D40DC98570FE8FEB4E53253E3E21 "Personal Jarvis Local Signing"
+_IDENTITY_LINE = re.compile(r'^\s*\d+\)\s+([0-9A-Fa-f]{40})\s+"(?P<label>.+)"\s*$')
+_CERT_VALIDITY = timedelta(days=365 * 10)
+# The trust dialog is answered by a human; a headless session never answers.
+_TRUST_TIMEOUT_S = 180
+_LAST_ERROR: str | None = None
+
+Runner = Callable[..., subprocess.CompletedProcess]
+
+
+def last_error() -> str | None:
+ """Why the last ``ensure_local_signing_identity`` returned ``None``."""
+ return _LAST_ERROR
+
+
+def _run(runner: Runner, argv: list[str], *, timeout: float) -> subprocess.CompletedProcess:
+ return runner(
+ argv,
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+
+
+def find_local_signing_identity(runner: Runner = subprocess.run) -> str | None:
+ """Return the SHA-1 of the valid local signing identity, or ``None``.
+
+ ``-v -p codesigning`` lists only identities macOS would actually let
+ ``codesign`` use: certificate present, private key present, trusted for
+ code signing. An untrusted leftover therefore reads as "absent", which is
+ exactly right — signing with it would fail.
+ """
+ if sys.platform != "darwin":
+ return None
+ try:
+ result = _run(runner, [_SECURITY, "find-identity", "-v", "-p", "codesigning"], timeout=30)
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ log.debug("security find-identity did not run: %s", exc)
+ return None
+ for line in (result.stdout or "").splitlines():
+ match = _IDENTITY_LINE.match(line)
+ if match and match.group("label") == IDENTITY_LABEL:
+ return match.group(1).upper()
+ return None
+
+
+def _gui_session(runner: Runner) -> bool:
+ """Only an Aqua session can show the trust-settings password dialog."""
+ try:
+ result = _run(runner, ["/bin/launchctl", "managername"], timeout=10)
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return (result.stdout or "").strip() == "Aqua"
+
+
+def _login_keychain(runner: Runner) -> str | None:
+ try:
+ result = _run(runner, [_SECURITY, "default-keychain", "-d", "user"], timeout=10)
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ path = (result.stdout or "").strip().strip('"')
+ return path or None
+
+
+def _generate_material(password: bytes) -> tuple[bytes, bytes]:
+ """``(pkcs12_bytes, cert_pem)`` for a fresh self-signed code-signing cert.
+
+ ``security import`` understands only the legacy PKCS#12 ciphers (SHA-1 +
+ 3DES); cryptography's default AES/PBKDF2-SHA256 container imports the
+ certificate but silently drops the private key, leaving no identity.
+ """
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import rsa
+ from cryptography.hazmat.primitives.serialization import pkcs12
+ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
+
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, IDENTITY_LABEL)])
+ now = datetime.now(UTC)
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(name)
+ .issuer_name(name)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - timedelta(minutes=5))
+ .not_valid_after(now + _CERT_VALIDITY)
+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
+ .add_extension(
+ x509.KeyUsage(
+ digital_signature=True,
+ content_commitment=False,
+ key_encipherment=False,
+ data_encipherment=False,
+ key_agreement=False,
+ key_cert_sign=False,
+ crl_sign=False,
+ encipher_only=False,
+ decipher_only=False,
+ ),
+ critical=True,
+ )
+ .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CODE_SIGNING]), critical=True)
+ .sign(key, hashes.SHA256())
+ )
+ encryption = (
+ serialization.PrivateFormat.PKCS12.encryption_builder()
+ .kdf_rounds(50000)
+ .key_cert_algorithm(pkcs12.PBES.PBESv1SHA1And3KeyTripleDESCBC)
+ .hmac_hash(hashes.SHA1()) # noqa: S303 — the only MAC `security import` accepts
+ .build(password)
+ )
+ bundle = pkcs12.serialize_key_and_certificates(
+ IDENTITY_LABEL.encode("utf-8"), key, cert, None, encryption
+ )
+ return bundle, cert.public_bytes(serialization.Encoding.PEM)
+
+
+def create_local_signing_identity(runner: Runner = subprocess.run) -> str | None:
+ """Create, import and trust the identity. One password dialog; else silent.
+
+ Returns the new identity's SHA-1, or ``None`` with :func:`last_error`
+ set. Never raises: a missing identity means ad-hoc signing, nothing worse.
+ """
+ global _LAST_ERROR
+ _LAST_ERROR = None
+ if sys.platform != "darwin":
+ _LAST_ERROR = "only macOS uses a code-signing identity"
+ return None
+ if not _gui_session(runner):
+ _LAST_ERROR = "no Aqua session: the trust-settings dialog cannot be shown"
+ return None
+ keychain = _login_keychain(runner)
+ if keychain is None:
+ _LAST_ERROR = "the user's login keychain could not be located"
+ return None
+ try:
+ password = secrets.token_urlsafe(24).encode("ascii")
+ p12, cert_pem = _generate_material(password)
+ except Exception as exc: # noqa: BLE001 - cryptography missing/broken → ad-hoc
+ _LAST_ERROR = f"certificate generation failed: {type(exc).__name__}: {exc}"
+ return None
+ with tempfile.TemporaryDirectory(prefix="jarvis-signing-") as raw_work:
+ work = Path(raw_work)
+ p12_path = work / "identity.p12"
+ cert_path = work / "identity.pem"
+ try:
+ fd = os.open(p12_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(fd, "wb") as stream:
+ stream.write(p12)
+ cert_path.write_bytes(cert_pem)
+ except OSError as exc:
+ _LAST_ERROR = f"could not stage the identity: {exc}"
+ return None
+ steps: list[tuple[str, list[str], float]] = [
+ (
+ "import",
+ [
+ _SECURITY,
+ "import",
+ str(p12_path),
+ "-k",
+ keychain,
+ "-P",
+ password.decode("ascii"),
+ "-T",
+ _CODESIGN,
+ "-A",
+ ],
+ 60,
+ ),
+ (
+ # The one interactive step: user-domain trust for code signing.
+ "trust",
+ [_SECURITY, "add-trusted-cert", "-p", "codeSign", "-k", keychain, str(cert_path)],
+ _TRUST_TIMEOUT_S,
+ ),
+ ]
+ for name, argv, timeout in steps:
+ try:
+ result = _run(runner, argv, timeout=timeout)
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ _LAST_ERROR = f"security {name} did not complete: {exc}"
+ return None
+ if result.returncode != 0:
+ detail = (result.stderr or result.stdout or "unknown error").strip()
+ _LAST_ERROR = f"security {name} failed (rc={result.returncode}): {detail[-300:]}"
+ return None
+ identity = find_local_signing_identity(runner)
+ if identity is None:
+ _LAST_ERROR = "the identity was imported but macOS does not list it as valid"
+ return identity
+
+
+def ensure_local_signing_identity(*, create: bool, runner: Runner = subprocess.run) -> str | None:
+ """Look the identity up; create it only when the caller allows a dialog."""
+ identity = find_local_signing_identity(runner)
+ if identity is not None or not create:
+ return identity
+ identity = create_local_signing_identity(runner)
+ if identity is None:
+ log.warning(
+ "No local code-signing identity — the app stays ad-hoc signed and its "
+ "macOS permissions will not survive a rebuild. Reason: %s",
+ last_error(),
+ )
+ else:
+ log.info("Created the local code-signing identity %s (%s).", IDENTITY_LABEL, identity)
+ return identity
+
+
+__all__ = [
+ "IDENTITY_LABEL",
+ "create_local_signing_identity",
+ "ensure_local_signing_identity",
+ "find_local_signing_identity",
+ "last_error",
+]
diff --git a/tests/unit/setup/test_macos_app_bundle.py b/tests/unit/setup/test_macos_app_bundle.py
index efe93fce0a..b0d15edb47 100644
--- a/tests/unit/setup/test_macos_app_bundle.py
+++ b/tests/unit/setup/test_macos_app_bundle.py
@@ -22,6 +22,18 @@ from jarvis.setup.macos_app_bundle import (
)
[email protected](autouse=True)
+def _no_signing_identity(monkeypatch):
+ """Default to the ad-hoc world; identity tests opt in explicitly.
+
+ Without this every ``sys.platform = "darwin"`` test would shell out to
+ the real ``security`` binary of the machine running the suite.
+ """
+ import jarvis.setup.macos_app_bundle as mab
+
+ monkeypatch.setattr(mab, "ensure_local_signing_identity", lambda *, create: None)
+
+
def _build(tmp_path: Path, monkeypatch) -> Path:
import jarvis.setup.macos_app_bundle as mab
@@ -91,7 +103,7 @@ def test_failed_runtime_probe_rebuilds_instead_of_preserving(tmp_path: Path, mon
)
rebuilt: list[tuple[Path, Path]] = []
- def _rebuild(install_root: Path, destination: Path) -> Path:
+ def _rebuild(install_root: Path, destination: Path, *, identity: str | None = None) -> Path:
rebuilt.append((install_root, destination))
return destination
@@ -194,7 +206,7 @@ def test_ensure_bundle_records_last_error_reason(tmp_path: Path, monkeypatch) ->
monkeypatch.setattr(mab.sys, "platform", "darwin")
monkeypatch.setattr(mab, "macos_app_bundle_is_launchable", lambda _bundle: False)
- def _explode(_install_root: Path, _bundle: Path) -> Path:
+ def _explode(_install_root: Path, _bundle: Path, *, identity: str | None = None) -> Path:
raise RuntimeError("stub launcher compilation failed: no cc")
monkeypatch.setattr(mab, "_install_native_bundle", _explode)
@@ -581,6 +593,9 @@ def test_reset_stale_tcc_grants_scopes_every_service_to_our_bundle_id() -> None:
"Accessibility",
"ListenEvent",
"PostEvent",
+ # The Music/Spotify Automation consent is pinned to the same code
+ # requirement; leaving it out is how the Music prompt kept coming back.
+ "AppleEvents",
}
@@ -613,18 +628,18 @@ def test_a_recurring_rebuild_wipes_the_grants_only_once(tmp_path: Path, monkeypa
marker = tmp_path / "macos-tcc-reset.json"
monkeypatch.setattr(permissions, "identity_reset_marker_path", lambda: marker)
- hashes = iter(["cdhash-two", "cdhash-three"])
- monkeypatch.setattr(mab, "_bundle_cdhash", lambda _bundle: next(hashes))
+ hashes = iter(['cdhash H"two"', 'cdhash H"three"'])
+ monkeypatch.setattr(mab, "_bundle_tcc_identity", lambda _bundle: next(hashes))
sweeps: list[int] = []
monkeypatch.setattr(mab, "_reset_stale_tcc_grants", lambda: sweeps.append(1))
bundle = tmp_path / APP_DIR_NAME
- mab._reset_or_explain(bundle, "cdhash-one")
+ mab._reset_or_explain(bundle, 'cdhash H"one"')
assert sweeps == [1]
assert marker.is_file()
# Second rebuild, first reset still unanswered: explain, never wipe again.
- mab._reset_or_explain(bundle, "cdhash-two")
+ mab._reset_or_explain(bundle, 'cdhash H"two"')
assert sweeps == [1]
assert marker.is_file()
@@ -659,7 +674,7 @@ def test_a_rebuild_that_reproduces_the_same_app_is_not_repeated(
)
rebuilds: list[Path] = []
- def _rebuild(install_root: Path, destination: Path) -> Path:
+ def _rebuild(install_root: Path, destination: Path, *, identity: str | None = None) -> Path:
rebuilds.append(destination)
return destination
@@ -706,7 +721,10 @@ def test_a_changed_interpreter_still_earns_a_fresh_rebuild(tmp_path: Path, monke
monkeypatch.setattr(
mab,
"_install_native_bundle",
- lambda install_root, destination: (rebuilds.append(destination), destination)[1],
+ lambda install_root, destination, identity=None: (
+ rebuilds.append(destination),
+ destination,
+ )[1],
)
# The recorded note carries Python 3.11; this interpreter is a different
@@ -737,7 +755,10 @@ def test_a_broken_bundle_is_always_rebuilt_however_often_it_recurs(
monkeypatch.setattr(
mab,
"_install_native_bundle",
- lambda install_root, destination: (rebuilds.append(destination), destination)[1],
+ lambda install_root, destination, identity=None: (
+ rebuilds.append(destination),
+ destination,
+ )[1],
)
install_dir = tmp_path / "install"
applications = tmp_path / "Applications"
@@ -766,7 +787,7 @@ def test_the_running_app_is_accepted_wherever_the_user_keeps_it(
monkeypatch.setattr(
mab,
"_install_native_bundle",
- lambda *_args: pytest.fail("a running managed app must never be rebuilt"),
+ lambda *_args, **_kwargs: pytest.fail("a running managed app must never be rebuilt"),
)
registered: list[Path] = []
monkeypatch.setattr(mab, "register_with_launch_services", registered.append)
@@ -818,3 +839,169 @@ def test_a_foreign_bundle_id_is_never_taken_for_the_managed_app(monkeypatch) ->
mab._running_managed_bundle(install_root=Path.cwd(), diagnostics=diagnostics) is None
)
assert any("bundle id" in reason for reason in diagnostics)
+
+
+# --- Rebuild-proof identity: certificate signature instead of ad-hoc
+
+
+def test_designated_requirement_parsing_covers_both_signature_kinds() -> None:
+ import jarvis.setup.macos_app_bundle as mab
+
+ adhoc = (
+ "Executable=/x/Personal Jarvis.app/Contents/MacOS/PersonalJarvis\n"
+ '# designated => cdhash H"aa28"\n'
+ )
+ cert = (
+ "Executable=/x\n"
+ '# designated => identifier "com.personal-jarvis.desktop" and certificate leaf = H"0e14"\n'
+ )
+ assert mab._parse_designated_requirement(adhoc) == 'cdhash H"aa28"'
+ assert (
+ mab._parse_designated_requirement(cert)
+ == 'identifier "com.personal-jarvis.desktop" and certificate leaf = H"0e14"'
+ )
+ assert mab._parse_designated_requirement("nothing here") is None
+
+
+def test_sign_bundle_uses_the_identity_when_there_is_one(tmp_path: Path, monkeypatch) -> None:
+ import jarvis.setup.macos_app_bundle as mab
+
+ commands: list[list[str]] = []
+
+ def runner(command, **_kwargs):
+ commands.append(list(command))
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(mab.subprocess, "run", runner)
+ monkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)
+
+ mab._sign_bundle(tmp_path / APP_DIR_NAME)
+ mab._sign_bundle(tmp_path / APP_DIR_NAME, "ABCDEF")
+
+ assert [command[4] for command in commands] == ["-", "ABCDEF"]
+
+
+def test_a_healthy_adhoc_bundle_is_moved_onto_the_identity_once(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """The one migration the user pays for; after it no rebuild costs a grant."""
+ import jarvis.setup.macos_app_bundle as mab
+
+ bundle = _build(tmp_path, monkeypatch)
+ monkeypatch.setattr(mab.sys, "platform", "darwin")
+ monkeypatch.setattr(mab, "ensure_local_signing_identity", lambda *, create: "ABCDEF")
+ monkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)
+ monkeypatch.setattr(mab, "_running_managed_bundle", lambda *, install_root, **_kw: None)
+ monkeypatch.setattr(
+ mab,
+ "_runtime_identity_valid",
+ lambda _bundle, *, install_root, diagnostics=None: True,
+ )
+ signed_with_certificate = iter([False, True])
+ monkeypatch.setattr(mab, "_signed_with_certificate", lambda _b: next(signed_with_certificate))
+ resigned: list[tuple[Path, str]] = []
+ monkeypatch.setattr(
+ mab,
+ "_resign_bundle_in_place",
+ lambda target, identity: (resigned.append((target, identity)), target)[1],
+ )
+ monkeypatch.setattr(
+ mab,
+ "_install_native_bundle",
+ lambda *_args, **_kwargs: pytest.fail("a healthy bundle is re-signed, never rebuilt"),
+ )
+ marker = tmp_path / "macos-bundle-rebuild.json"
+ monkeypatch.setattr(mab, "_rebuild_marker_path", lambda: marker)
+ monkeypatch.setattr(mab, "_bundle_cdhash", lambda _bundle: "cdhash-cert")
+ install_dir = tmp_path / "install"
+ applications = tmp_path / "Applications"
+
+ first = ensure_macos_app_bundle(install_dir=install_dir, applications_dir=applications)
+ second = ensure_macos_app_bundle(install_dir=install_dir, applications_dir=applications)
+
+ assert first == second == bundle
+ assert resigned == [(bundle, "ABCDEF")]
+ assert json.loads(marker.read_text(encoding="utf-8"))["identity"] == "ABCDEF"
+
+
+def test_the_running_app_is_never_resigned_underneath_itself(tmp_path: Path, monkeypatch) -> None:
+ """The reset that follows a re-sign would strip the grants of this process."""
+ import jarvis.setup.macos_app_bundle as mab
+
+ monkeypatch.setattr(mab.sys, "platform", "darwin")
+ monkeypatch.setattr(mab, "ensure_local_signing_identity", lambda *, create: "ABCDEF")
+ running = tmp_path / "Applications" / APP_DIR_NAME
+ monkeypatch.setattr(mab, "_running_managed_bundle", lambda *, install_root, **_kw: running)
+ monkeypatch.setattr(mab, "_signed_with_certificate", lambda _b: False)
+ monkeypatch.setattr(
+ mab,
+ "_resign_bundle_in_place",
+ lambda *_args: pytest.fail("the running app must not be re-signed"),
+ )
+ monkeypatch.setattr(mab, "register_with_launch_services", lambda _b: True)
+
+ assert ensure_macos_app_bundle(
+ install_dir=tmp_path / "install", applications_dir=tmp_path / "Applications"
+ ) == running
+
+
+def test_resign_in_place_keeps_the_files_and_resets_against_the_old_identity(
+ tmp_path: Path, monkeypatch
+) -> None:
+ import jarvis.setup.macos_app_bundle as mab
+
+ bundle = _build(tmp_path, monkeypatch)
+ before = (bundle / "Contents" / "Info.plist").read_bytes()
+ identities = iter(['cdhash H"old"'])
+ monkeypatch.setattr(mab, "_bundle_tcc_identity", lambda _b: next(identities, None))
+ signed: list[tuple[Path, str | None]] = []
+ monkeypatch.setattr(
+ mab, "_sign_bundle", lambda target, identity=None: signed.append((target, identity))
+ )
+ monkeypatch.setattr(mab, "_signed_with_certificate", lambda _b: True)
+ monkeypatch.setattr(mab, "macos_app_bundle_is_launchable", lambda _b: True)
+ resets: list[tuple[Path, str | None]] = []
+ monkeypatch.setattr(mab, "_reset_or_explain", lambda b, previous: resets.append((b, previous)))
+
+ result = mab._resign_bundle_in_place(bundle, "ABCDEF")
+
+ assert result == bundle
+ assert (bundle / "Contents" / "Info.plist").read_bytes() == before
+ assert len(signed) == 1 and signed[0][1] == "ABCDEF" and signed[0][0] != bundle
+ assert resets == [(bundle, 'cdhash H"old"')]
+ assert not [p for p in bundle.parent.iterdir() if p.name.startswith(".jarvis-resign-")]
+
+
+def test_resign_in_place_rolls_back_when_the_result_cannot_launch(
+ tmp_path: Path, monkeypatch
+) -> None:
+ import jarvis.setup.macos_app_bundle as mab
+
+ bundle = _build(tmp_path, monkeypatch)
+ before = (bundle / "Contents" / "Info.plist").read_bytes()
+ monkeypatch.setattr(mab, "_bundle_tcc_identity", lambda _b: None)
+ monkeypatch.setattr(mab, "_sign_bundle", lambda target, identity=None: None)
+ monkeypatch.setattr(mab, "_signed_with_certificate", lambda _b: True)
+ monkeypatch.setattr(mab, "macos_app_bundle_is_launchable", lambda _b: False)
+ monkeypatch.setattr(mab, "_reset_or_explain", lambda *_a: pytest.fail("no reset on rollback"))
+
+ with pytest.raises(RuntimeError):
+ mab._resign_bundle_in_place(bundle, "ABCDEF")
+
+ assert (bundle / "Contents" / "Info.plist").read_bytes() == before
+
+
+def test_a_rebuild_with_the_identity_never_resets_the_grants(tmp_path: Path, monkeypatch) -> None:
+ """Same certificate before and after: TCC sees the same app, nothing to reset."""
+ import jarvis.platform.permissions as permissions
+ import jarvis.setup.macos_app_bundle as mab
+
+ same ='identifier "com.personal-jarvis.desktop" and certificate leaf = H"0e14"'
+ monkeypatch.setattr(mab, "_bundle_tcc_identity", lambda _b: same)
+ monkeypatch.setattr(mab, "_reset_stale_tcc_grants", lambda: pytest.fail("must not reset"))
+ marker = tmp_path / "macos-tcc-reset.json"
+ monkeypatch.setattr(permissions, "identity_reset_marker_path", lambda: marker)
+
+ mab._reset_or_explain(tmp_path / APP_DIR_NAME, same)
+
+ assert not marker.exists()
diff --git a/tests/unit/setup/test_macos_signing_identity.py b/tests/unit/setup/test_macos_signing_identity.py
new file mode 100644
index 0000000000..826f1208e9
--- /dev/null
+++ b/tests/unit/setup/test_macos_signing_identity.py
@@ -0,0 +1,173 @@
+"""Tests for the per-user macOS code-signing identity (rebuild-proof TCC)."""
+
+from __future__ import annotations
+
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+
+import jarvis.setup.macos_signing_identity as msi
+from jarvis.setup.macos_signing_identity import (
+ IDENTITY_LABEL,
+ create_local_signing_identity,
+ ensure_local_signing_identity,
+ find_local_signing_identity,
+)
+
+_SHA1 = "0E147B028894D40DC98570FE8FEB4E53253E3E21"
+_KEYCHAIN = "/Users/x/Library/Keychains/login.keychain-db"
+_LISTING = (
+ "Policy: Code Signing\n"
+ " Matching identities\n"
+ f' 1) {_SHA1} "{IDENTITY_LABEL}"\n'
+ ' 2) AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA "Apple Development: Someone"\n'
+ " 2 identities found\n"
+)
+
+
+class _Security:
+ """Scripted ``security``/``launchctl`` runner recording every argv."""
+
+ def __init__(self, *, listing: str = "", aqua: bool = True, fail: str | None = None) -> None:
+ self.calls: list[list[str]] = []
+ self.listing = listing
+ self.aqua = aqua
+ self.fail = fail
+ self.listing_after_trust = listing
+
+ def __call__(self, argv, **_kwargs):
+ self.calls.append(list(argv))
+ verb = argv[1] if len(argv) > 1 else ""
+ if argv[0].endswith("launchctl"):
+ manager = "Aqua\n" if self.aqua else "Background\n"
+ return SimpleNamespace(returncode=0, stdout=manager, stderr="")
+ if verb == "default-keychain":
+ return SimpleNamespace(returncode=0, stdout=f' "{_KEYCHAIN}"\n', stderr="")
+ if verb == "find-identity":
+ return SimpleNamespace(returncode=0, stdout=self.listing, stderr="")
+ if verb == self.fail:
+ return SimpleNamespace(returncode=1, stdout="", stderr=f"{verb} exploded")
+ if verb == "add-trusted-cert":
+ self.listing = self.listing_after_trust
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+
[email protected](autouse=True)
+def _darwin(monkeypatch):
+ monkeypatch.setattr(msi.sys, "platform", "darwin")
+ # The real generator needs `cryptography`; the flow tests only care about
+ # the security(1) choreography around it.
+ monkeypatch.setattr(msi, "_generate_material", lambda _password: (b"p12", b"pem"))
+
+
+def test_find_returns_only_our_label() -> None:
+ runner = _Security(listing=_LISTING)
+
+ assert find_local_signing_identity(runner) == _SHA1
+ assert runner.calls == [["/usr/bin/security", "find-identity", "-v", "-p", "codesigning"]]
+
+
+def test_find_is_none_off_macos_or_without_identity(monkeypatch) -> None:
+ assert find_local_signing_identity(_Security(listing=" 0 valid identities found\n")) is None
+ monkeypatch.setattr(msi.sys, "platform", "linux")
+ assert find_local_signing_identity(_Security(listing=_LISTING)) is None
+
+
+def test_find_survives_a_missing_security_binary() -> None:
+ def runner(argv, **_kwargs):
+ raise OSError("no security")
+
+ assert find_local_signing_identity(runner) is None
+
+
+def test_create_imports_then_trusts_then_verifies() -> None:
+ runner = _Security(listing=" 0 valid identities found\n")
+ runner.listing_after_trust = _LISTING
+
+ assert create_local_signing_identity(runner) == _SHA1
+
+ verbs = [call[1] if call[0].endswith("security") else call[0] for call in runner.calls]
+ assert verbs == [
+ "/bin/launchctl",
+ "default-keychain",
+ "import",
+ "add-trusted-cert",
+ "find-identity",
+ ]
+ import_call = next(call for call in runner.calls if call[1] == "import")
+ # The key must be usable by codesign without a per-use ACL prompt.
+ assert import_call[-3:] == ["-T", "/usr/bin/codesign", "-A"]
+ assert "-k" in import_call and _KEYCHAIN in import_call
+ trust_call = next(call for call in runner.calls if call[1] == "add-trusted-cert")
+ # User-domain trust for code signing only — never `-d` (admin/system).
+ assert trust_call[2:6] == ["-p", "codeSign", "-k", _KEYCHAIN]
+ assert "-d" not in trust_call
+
+
+def test_create_refuses_without_a_gui_session() -> None:
+ runner = _Security(aqua=False)
+
+ assert create_local_signing_identity(runner) is None
+ assert msi.last_error() is not None and "Aqua" in msi.last_error()
+ assert [call[1] for call in runner.calls if call[0].endswith("security")] == []
+
+
+def test_create_reports_a_failing_trust_step() -> None:
+ runner = _Security(listing=" 0 valid identities found\n", fail="add-trusted-cert")
+
+ assert create_local_signing_identity(runner) is None
+ assert "add-trusted-cert" in (msi.last_error() or "")
+
+
+def test_create_reports_an_identity_macos_does_not_list() -> None:
+ runner = _Security(listing=" 0 valid identities found\n")
+
+ assert create_local_signing_identity(runner) is None
+ assert "does not list it as valid" in (msi.last_error() or "")
+
+
+def test_create_tolerates_a_hung_trust_dialog() -> None:
+ def runner(argv, **kwargs):
+ if argv[1:2] == ["add-trusted-cert"]:
+ raise subprocess.TimeoutExpired(argv, kwargs.get("timeout", 0))
+ return _Security(listing=" 0 valid identities found\n")(argv, **kwargs)
+
+ assert create_local_signing_identity(runner) is None
+ assert "did not complete" in (msi.last_error() or "")
+
+
+def test_ensure_never_creates_unless_allowed() -> None:
+ runner = _Security(listing=" 0 valid identities found\n")
+ runner.listing_after_trust = _LISTING
+
+ assert ensure_local_signing_identity(create=False, runner=runner) is None
+ assert [call[1] for call in runner.calls if call[0].endswith("security")] == ["find-identity"]
+
+ assert ensure_local_signing_identity(create=True, runner=runner) == _SHA1
+
+
+def test_ensure_reuses_an_existing_identity_without_a_dialog() -> None:
+ runner = _Security(listing=_LISTING)
+
+ assert ensure_local_signing_identity(create=True, runner=runner) == _SHA1
+ assert [call[1] for call in runner.calls if call[0].endswith("security")] == ["find-identity"]
+
+
+def test_generated_material_is_a_code_signing_identity(monkeypatch) -> None:
+ pytest.importorskip("cryptography")
+ monkeypatch.undo() # the autouse stub must not hide the real generator
+ from cryptography import x509
+ from cryptography.hazmat.primitives.serialization import pkcs12
+ from cryptography.x509.oid import ExtendedKeyUsageOID
+
+ p12, pem = msi._generate_material(b"secret")
+
+ key, cert, extra = pkcs12.load_key_and_certificates(p12, b"secret")
+ assert key is not None and cert is not None and not extra
+ assert cert.subject == cert.issuer
+ assert cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value == IDENTITY_LABEL
+ eku = cert.extensions.get_extension_for_class(x509.ExtendedKeyUsage)
+ assert eku.critical and ExtendedKeyUsageOID.CODE_SIGNING in eku.value
+ digest = cert.signature_hash_algorithm
+ assert x509.load_pem_x509_certificate(pem).fingerprint(digest) == cert.fingerprint(digest)