Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(macos): stop repeated Keychain control-key prompts
Ruben Lütkefaf7e0596d75
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8052c16bc4..5014985e79 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,15 @@ versioning per [SemVer](https://semver.org/lang/de/).### Fixed+- **macOS: the repeated Keychain password-dialog storm is stopped.** A Control+ key created by an older direct Python launch could make macOS ask for the+ login-keychain password again on every protected request — often dozens of+ identical dialogs, with **Always Allow** unavailable because that Python+ executable had no verifiable signature. Jarvis now performs one serialized+ credential read per process and, after the one necessary approval, safely+ re-creates that legacy item under the verified installed app identity. Normal+ restarts and source updates then reuse the app-owned item without asking+ again; direct development launches cannot weaken or claim its access rules.- **macOS: the uninstall command works again.** On a Mac, the documentedone-liner `bash ~/.personal-jarvis/install/uninstall.sh` printed a syntaxerror and did nothing at all — no prompt, no removal. macOS still ships adiff --git a/docs/BUGS.md b/docs/BUGS.mdindex 61323f1d63..2d8c70d3c6 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -6302,3 +6302,103 @@ shell script: the Mac is a full bash MAJOR VERSION behind, and the failuremode is not a runtime bug but a dead file. Any shell artifact we ship to endusers must be parse-checked against 3.2 — the same OS-parity disciplineCLAUDE.md section 3 demands of Python and OS-specific backends.++---++## BUG-092: macOS asks for the login-keychain password on every Control API request (HIGH, FIXED 2026-07-19)++**Symptom (live macOS field report).** Launching Jarvis produced ten to thirty+indistinguishable login-keychain dialogs. Each said that `python3.12` wanted to+access the `personal-jarvis` item; **Always Allow** was disabled because macOS+could not verify that executable. Approving one dialog did not stop the next.+The ordinary onboarding permission rows were already complete, so this looked+like one global permission that macOS had forgotten repeatedly.++**Forensic evidence.** No credential values were read or printed during the+investigation.++1. The login Keychain contained three generic-password items for service+ `personal-jarvis`. The two provider items were created during the current+ native-app onboarding. The older `jarvis_control_api_key` item predated that+ app and was the only legacy item.+2. The Python 3.12 executable used by the earlier direct launch was completely+ unsigned (`codesign`: no signature; Gatekeeper: no usable signature), which+ exactly explains both the `python3.12` label and the unavailable persistent+ approval button.+3. The installed app now has the canonical bundle id+ `com.personal-jarvis.desktop` and a valid local ad-hoc signature. Its native+ Mach-O stub embeds Python without replacing the main process, and ordinary+ managed updates preserve that bundle byte-for-byte.+4. `verify_control_key()` called `get_control_key()` for every presented Bearer+ credential. That method decrypted `jarvis_control_api_key` through Python+ `keyring` every time. Startup also called `ensure_control_key()` from several+ paths. There was no cache and no single-flight lock, so concurrent browser,+ CLI, and status requests could each open their own native dialog.+5. The earlier macOS uninstaller prompt-storm fix had already proved the+ decisive distinction: attribute queries and item deletion do not request+ secret data, while a value read produces one authorization dialog per item+ and caller. The runtime path was still doing exactly the dangerous operation+ repeatedly.++**Root cause.** macOS Keychain access is not a TCC-style global toggle. A+generic-password item has its own ACL and normally trusts the code-signing+designated requirement of the process that created it. The legacy Control key+therefore trusted an unverifiable Python interpreter rather than the stable+Jarvis app. Clicking **Allow** authorized one read; it neither changed the+item's creator ACL nor fixed the next read. Jarvis multiplied that one ownership+problem into a dialog storm by reading the same secret on every authentication+check. The permissions screen could report the Keychain backend as available,+but backend availability cannot prove an individual item's ACL.++**Fix (two layers, no ACL weakening).**++- `get_control_key()` now protects the first successful lookup with a process+ `RLock` and caches it with `config.secret_revision()` invalidation. Twenty-four+ concurrent callers in the regression test perform exactly one credential+ read. Rotation and custom-key replacement update the cache immediately.+ Missing values are not cached, so a user-initiated Keychain recovery remains+ visible without a restart.+- Forked children discard both the cached value and inherited lock. The Control+ key is still never exported into the environment, and a worker cannot use the+ parent's Python cache through the supported API.+- After the first successful legacy read, Jarvis verifies that the current+ process really is the canonical app at+ `~/Applications/Personal Jarvis.app`, verifies its code signature, and+ fingerprints the exact `codesign` designated requirement. It also confirms+ the old item exists using `security find-generic-password` **without** `-w`+ (attributes only, never secret data). Only then does it re-save the same value,+ making the stable app the new item creator.+- A private non-secret owner stamp records that designated requirement. A+ Developer-ID build therefore remains stable across signed releases; the local+ ad-hoc build uses its CDHash requirement and re-adopts once after an actual+ bundle rebuild. A direct/unsigned Python launch has no accepted app identity,+ never migrates the item, and clears a stale stamp if it explicitly replaces+ the key.+- The repair does not use `set-generic-password-partition-list`, does not grant+ all applications access, and does not modify or sign the user's Python+ installation. Fresh credentials saved through the native app already receive+ the correct creator ACL and need no repair.++**Distribution boundary.** The managed local bundle is deliberately ad-hoc+signed. Preserving it byte-for-byte makes ordinary source updates stable, but a+rebuild changes its CDHash. The permanent public-distribution solution remains+Developer-ID signing and notarization, whose designated requirement stays+stable across app versions. The repository cannot manufacture or embed the+maintainer's private Apple signing identity; this runtime migration is the safe+local-install bridge, not a claim that ad-hoc signing equals distribution+signing.++**Guards.** `tests/unit/core/test_control_key.py` covers one read per process,+24-way concurrent single-flight, revision invalidation, fork-cache reset,+same-requirement one-time adoption, re-adoption after a requirement change,+direct-Python refusal, and non-promotion of a file seed. The adjacent Control+API, surface-security, CLI-tool, and auth suites cover request semantics and key+rotation end to end.++**Class rule.** Never decrypt an OS credential in a per-request authentication+dependency. Load it once through a serialized path, invalidate it on deliberate+replacement, and clear it across process-boundary inheritance. On macOS, never+model Keychain as one global permission: ownership is per item and anchored to+the caller's designated requirement. Repair legacy ownership only after one+user-approved read and only from the verified canonical app; never solve a+prompt by broadening an ACL to unsigned tools or all applications.diff --git a/docs/jarvis-control-api.md b/docs/jarvis-control-api.mdindex e9a0e0c7ee..0ccb01ae45 100644--- a/docs/jarvis-control-api.md+++ b/docs/jarvis-control-api.md@@ -24,8 +24,17 @@ gets a unique key.daemon the keyring silently fails, so the key falls back to a `0600` file at`data/.control_api_key` (or `$JARVIS_DATA_DIR`). Read order:keyring → file → `JARVIS_CONTROL_API_KEY` env seed.+- **Runtime reads:** a successful lookup is serialized and cached for the life+ of the Jarvis process, then invalidated by an in-process key replacement.+ Forked children drop the cache. This keeps per-request Bearer checks from+ repeatedly decrypting the same operating-system credential.+- **macOS upgrade repair:** if the item was created by an older direct-Python+ launcher, the first approved read re-creates the same value under the+ verified canonical `Personal Jarvis.app` code-signing requirement. A private,+ non-secret owner stamp prevents repeat migrations. An unsigned development+ process is never allowed to perform or claim that repair.- **Never exported into `os.environ`** during normal operation (a spawned worker- would inherit it and leak it via `/proc/<pid>/environ`). Read on demand.+ would inherit it and leak it via `/proc/<pid>/environ`).- **Where the user finds it:** desktop app → **API Keys → Access &Integrations → Control Key** (masked by default, Show/Hide, one-click Copy,Regenerate behind a confirm dialog, or replace it with a user-chosen key —diff --git a/docs/product/privacy-safety-and-support/control-key.md b/docs/product/privacy-safety-and-support/control-key.mdindex 1f3069ae25..a0ebe8d7bc 100644--- a/docs/product/privacy-safety-and-support/control-key.md+++ b/docs/product/privacy-safety-and-support/control-key.md@@ -61,6 +61,13 @@ with a restricted file in the Jarvis data directory as the fallback on systemswithout such a store. No two installations share a key, and the key neverleaves your machine by itself.+On macOS, an installation upgraded from an older Python-based launcher may ask+for the login-keychain password once when it first reads that existing item.+After you approve that read, Jarvis transfers the item to the installed app's+verified identity; subsequent app starts and ordinary updates should not ask+again. Start Jarvis through **Personal Jarvis.app**, not by running its Python+module directly, so macOS sees the stable app identity.+## Find the KeyThe key lives in its own section, named after your assistant: if your wakediff --git a/jarvis/core/control_key.py b/jarvis/core/control_key.pyindex 8b3707858b..1b9c79513b 100644--- a/jarvis/core/control_key.py+++ b/jarvis/core/control_key.py@@ -19,17 +19,22 @@ mandatory; the key must never be lost on restart. Read order: keyring -> fileSecurity: the key is NEVER exported into ``os.environ`` during normal operation(a spawned worker would inherit it and leak it via ``/proc/<pid>/environ`` on-Linux). It is read on demand inside the auth dependency. Logs/UI lists show only-the masked form (``jctl_…last4``); the clear value crosses the wire solely on the-dedicated key-reveal endpoint.+Linux). It is read once per process and the cache is cleared in forked children.+Logs/UI lists show only the masked form (``jctl_…last4``); the clear value+crosses the wire solely on the dedicated key-reveal endpoint."""+from __future__ import annotations+import hashlibimport loggingimport osimport reimport secretsimport stat+import subprocess+import sys+import threadingfrom pathlib import Pathfrom jarvis.core import config as cfg@@ -40,7 +45,19 @@ KEY_PREFIX = "jctl_"KEYRING_SLOT = "jarvis_control_api_key"ENV_VAR = "JARVIS_CONTROL_API_KEY"_FILE_NAME = ".control_api_key"+_MACOS_OWNER_FILE_NAME = ".control_api_key.macos-owner"_TOKEN_BYTES = 32 # 256-bit+_MACOS_APP_NAME = "Personal Jarvis"+_MACOS_BUNDLE_ID = "com.personal-jarvis.desktop"++# Authentication runs on every protected HTTP request. Reading a macOS+# Keychain item's secret data on every comparison used to produce one password+# dialog per request when the item's ACL belonged to an older Python launcher.+# Serialize the first read and retain the successful result for this process.+# ``cfg.secret_revision`` invalidates the cache after any in-process write.+_control_key_lock = threading.RLock()+_cached_control_key: str | None = None+_cached_secret_revision = -1# User-chosen key rules. The key doubles as an RFC-6750 Bearer token (CLI /# local agents) and as the value typed into the browser unlock form, so it@@ -54,6 +71,7 @@ _CUSTOM_KEY_RE = re.compile(r"^[A-Za-z0-9._~-]+$")class ControlKeyValidationError(ValueError):"""A user-chosen control key failed the format/strength rules."""+# The literal value shipped as the default in docker-compose.yml. It is# world-known (public repo, public image) the moment it is ever used# unmodified, so it must never be accepted as a real key — wherever it is@@ -64,6 +82,26 @@ SHIPPED_PLACEHOLDER_KEY = "jctl_local_sandbox_change_me_before_any_real_use"_warned_shipped_placeholder = False+def _clear_control_key_cache() -> None:+ """Forget the in-process key without touching persistent storage."""+ global _cached_control_key, _cached_secret_revision+ with _control_key_lock:+ _cached_control_key = None+ _cached_secret_revision = -1+++def _after_fork_in_child() -> None:+ """Do not make a forked worker an accidental holder of the parent key."""+ global _control_key_lock, _cached_control_key, _cached_secret_revision+ _control_key_lock = threading.RLock()+ _cached_control_key = None+ _cached_secret_revision = -1+++if hasattr(os, "register_at_fork"):+ os.register_at_fork(after_in_child=_after_fork_in_child)++def _warn_shipped_placeholder_once() -> None:"""Log a single, clear warning the first time the placeholder is seen.@@ -118,6 +156,175 @@ def control_key_file() -> Path:return data_dir / _FILE_NAME+def _macos_owner_file() -> Path:+ """Non-secret stamp recording which app requirement owns the Keychain item."""+ return control_key_file().with_name(_MACOS_OWNER_FILE_NAME)+++def _macos_app_identity_token() -> str | None:+ """Return the canonical app's designated-requirement fingerprint.++ Keychain item ACLs trust the creating process by its code-signing+ designated requirement. A Developer-ID build keeps that requirement across+ releases; the locally generated ad-hoc bundle has a CDHash requirement that+ changes only when the bundle is rebuilt. Mirroring that value lets us know+ when a legacy item needs one ownership migration without weakening its ACL.+ """+ if sys.platform != "darwin":+ return None+ try:+ from Foundation import NSBundle # type: ignore[import-not-found, import-untyped]++ bundle = NSBundle.mainBundle()+ bundle_id = str(bundle.bundleIdentifier() or "")+ bundle_path = Path(str(bundle.bundlePath() or "")).resolve()+ executable = Path(str(bundle.executablePath() or "")).resolve()+ expected = (Path.home() / "Applications" / f"{_MACOS_APP_NAME}.app").resolve()+ executable_root = bundle_path / "Contents" / "MacOS"+ if (+ bundle_id != _MACOS_BUNDLE_ID+ or bundle_path != expected+ or not executable.is_file()+ or not executable.is_relative_to(executable_root)+ ):+ return None++ verified = subprocess.run(+ ["/usr/bin/codesign", "--verify", str(bundle_path)],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ check=False,+ timeout=3,+ )+ if verified.returncode != 0:+ return None+ displayed = subprocess.run(+ ["/usr/bin/codesign", "--display", "--requirements", "-", str(executable)],+ capture_output=True,+ text=True,+ check=False,+ timeout=3,+ )+ if displayed.returncode != 0:+ return None+ requirement = next(+ (+ line.partition("designated =>")[2].strip()+ for line in (displayed.stderr + displayed.stdout).splitlines()+ if "designated =>" in line+ ),+ "",+ )+ if not requirement:+ return None+ digest = hashlib.sha256(requirement.encode("utf-8")).hexdigest()+ return f"designated-requirement-v1:{digest}"+ except Exception: # noqa: BLE001 - identity discovery must fail closed+ return None+++def _read_macos_owner() -> str | None:+ try:+ value = _macos_owner_file().read_text(encoding="utf-8").strip()+ return value or None+ except OSError:+ return None+++def _write_macos_owner(value: str) -> bool:+ """Atomically persist the non-secret owner stamp with private permissions."""+ path = _macos_owner_file()+ temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary.write_text(value, encoding="utf-8")+ if os.name == "posix":+ os.chmod(temporary, stat.S_IRUSR | stat.S_IWUSR)+ os.replace(temporary, path)+ return True+ except OSError:+ return False+ finally:+ try:+ temporary.unlink(missing_ok=True)+ except OSError:+ pass+++def _remove_macos_owner() -> None:+ try:+ _macos_owner_file().unlink(missing_ok=True)+ except OSError:+ pass+++def _macos_keychain_item_exists() -> bool:+ """Check item attributes without requesting its protected secret data."""+ if sys.platform != "darwin":+ return False+ try:+ result = subprocess.run(+ [+ "/usr/bin/security",+ "find-generic-password",+ "-s",+ cfg.KEYRING_SERVICE,+ "-a",+ KEYRING_SLOT,+ ],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ check=False,+ timeout=3,+ )+ return result.returncode == 0+ except (OSError, subprocess.SubprocessError):+ return False+++def _platform_credential_store_active() -> bool:+ try:+ return cfg.credential_store_backend() == "platform"+ except Exception: # noqa: BLE001 - ownership metadata is best-effort+ return False+++def _record_macos_owner_after_write(*, keyring_ok: bool) -> None:+ """Record a canonical app write, or invalidate a stale ownership claim."""+ if sys.platform != "darwin":+ return+ identity = _macos_app_identity_token()+ if keyring_ok and identity and _platform_credential_store_active():+ _write_macos_owner(identity)+ else:+ # A direct Python/dev write creates an ACL for that process, not for the+ # installed app. Keeping an older app stamp would suppress migration.+ _remove_macos_owner()+++def _adopt_legacy_macos_keychain_item(key: str) -> None:+ """Re-create one readable legacy item under the canonical app identity.++ The first successful legacy read is the one unavoidable user approval.+ Re-saving the same value makes the current stable app the item's creator,+ so subsequent launches no longer ask. The attribute-only existence probe+ prevents an environment/file seed from being promoted into Keychain.+ """+ identity = _macos_app_identity_token()+ if (+ identity is None+ or _read_macos_owner() == identity+ or not _platform_credential_store_active()+ or not _macos_keychain_item_exists()+ ):+ return+ if not cfg.set_secret(KEYRING_SLOT, key):+ logger.warning("Could not migrate the legacy Control key to the stable macOS app identity.")+ return+ if _platform_credential_store_active() and _write_macos_owner(identity):+ logger.info("Migrated the legacy Control key to the stable macOS app identity.")++def _read_file_key() -> str | None:try:path = control_key_file()@@ -161,6 +368,10 @@ def _store(key: str) -> None:_write_file_key(key)elif control_key_file().exists():_write_file_key(key)+ _record_macos_owner_after_write(keyring_ok=keyring_ok)+ global _cached_control_key, _cached_secret_revision+ _cached_control_key = key+ _cached_secret_revision = cfg.secret_revision(KEYRING_SLOT)def get_control_key() -> str | None:@@ -171,29 +382,48 @@ def get_control_key() -> str | None:it is treated exactly as if that layer held nothing, and resolution keepsfalling through the chain."""- saw_placeholder = False-- value = cfg.get_secret(KEYRING_SLOT) # keyring only (no env fallback here)- if value:- if value != SHIPPED_PLACEHOLDER_KEY:- return value- saw_placeholder = True-- value = _read_file_key()- if value:- if value != SHIPPED_PLACEHOLDER_KEY:- return value- saw_placeholder = True-- value = _env_key()- if value:- if value != SHIPPED_PLACEHOLDER_KEY:- return value- saw_placeholder = True-- if saw_placeholder:- _warn_shipped_placeholder_once()- return None+ global _cached_control_key, _cached_secret_revision+ with _control_key_lock:+ revision = cfg.secret_revision(KEYRING_SLOT)+ if _cached_control_key is not None and _cached_secret_revision == revision:+ return _cached_control_key++ saw_placeholder = False++ # The shared config store includes its own protected-file fallback; the+ # dedicated file/env checks below preserve this module's older contract.+ value = cfg.get_secret(KEYRING_SLOT)+ if value:+ if value != SHIPPED_PLACEHOLDER_KEY:+ _adopt_legacy_macos_keychain_item(value)+ _cached_control_key = value+ # Migration is itself a secret write, so capture the revision+ # after it finishes rather than the pre-read value above.+ _cached_secret_revision = cfg.secret_revision(KEYRING_SLOT)+ return value+ saw_placeholder = True++ value = _read_file_key()+ if value:+ if value != SHIPPED_PLACEHOLDER_KEY:+ _cached_control_key = value+ _cached_secret_revision = cfg.secret_revision(KEYRING_SLOT)+ return value+ saw_placeholder = True++ value = _env_key()+ if value:+ if value != SHIPPED_PLACEHOLDER_KEY:+ _cached_control_key = value+ _cached_secret_revision = cfg.secret_revision(KEYRING_SLOT)+ return value+ saw_placeholder = True++ _cached_control_key = None+ _cached_secret_revision = -1+ if saw_placeholder:+ _warn_shipped_placeholder_once()+ return Nonedef ensure_control_key() -> str:@@ -204,12 +434,13 @@ def ensure_control_key() -> str:that would lock out every agent that cached it (and an operator-supplied envseed is respected, not overwritten)."""- existing = get_control_key()- if existing:- return existing- key = generate_control_key()- _store(key)- return key+ with _control_key_lock:+ existing = get_control_key()+ if existing:+ return existing+ key = generate_control_key()+ _store(key)+ return keydef _replace_key_everywhere(key: str) -> str:@@ -219,17 +450,22 @@ def _replace_key_everywhere(key: str) -> str:separate revocation list). The file copy is overwritten too so a stale filecannot resurrect the previous key on the next boot."""- keyring_ok = cfg.set_secret(KEYRING_SLOT, key)- file_ok = _write_file_key(key)- if not keyring_ok and not file_ok:- # Neither store accepted the new key. Returning it would lock out the- # caller: the NEXT get_control_key() reads the OLD key, so verify() of- # the just-returned key fails. Fail loudly instead — the old key stays.- raise RuntimeError(- "Control key replacement failed: neither the OS keyring nor the "- "file fallback accepted the new key. The previous key remains active."- )- return key+ with _control_key_lock:+ keyring_ok = cfg.set_secret(KEYRING_SLOT, key)+ file_ok = _write_file_key(key)+ if not keyring_ok and not file_ok:+ # Neither store accepted the new key. Returning it would lock out the+ # caller: the NEXT get_control_key() reads the OLD key, so verify() of+ # the just-returned key fails. Fail loudly instead — the old key stays.+ raise RuntimeError(+ "Control key replacement failed: neither the OS keyring nor the "+ "file fallback accepted the new key. The previous key remains active."+ )+ _record_macos_owner_after_write(keyring_ok=keyring_ok)+ global _cached_control_key, _cached_secret_revision+ _cached_control_key = key+ _cached_secret_revision = cfg.secret_revision(KEYRING_SLOT)+ return keydef rotate_control_key() -> str:diff --git a/tests/unit/core/test_control_key.py b/tests/unit/core/test_control_key.pyindex adc772e152..3fa80fa07c 100644--- a/tests/unit/core/test_control_key.py+++ b/tests/unit/core/test_control_key.py@@ -6,15 +6,32 @@ restarts even when the OS keyring is unavailable (headless Linux VPS), beidempotent on boot, and be rotatable. These tests inject a fake keyring so thereal Credential Manager is never touched."""+from __future__ import annotationsimport sys+import threading+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespaceimport pytestfrom jarvis.core import config as cfgfrom jarvis.core import control_key as ck+_REAL_MACOS_APP_IDENTITY_TOKEN = ck._macos_app_identity_token++[email protected](autouse=True)+def reset_process_cache(monkeypatch):+ """No test may inherit another test's in-process credential cache."""+ ck._clear_control_key_cache()+ # Unit tests must never inspect or mutate the developer machine's real app+ # identity, even when this suite itself runs on macOS.+ monkeypatch.setattr(ck, "_macos_app_identity_token", lambda: None)+ yield+ ck._clear_control_key_cache()+@pytest.fixturedef isolated(monkeypatch, tmp_path):@@ -63,6 +80,71 @@ def test_get_returns_none_when_nothing_stored(isolated) -> None:assert ck.get_control_key() is None+def test_successful_keyring_read_is_cached_for_the_process(isolated, monkeypatch) -> None:+ calls = 0+ isolated[ck.KEYRING_SLOT] = "jctl_cached-key"++ def fake_get(key: str, env_fallback: str | None = None) -> str | None:+ nonlocal calls+ calls += 1+ return isolated.get(key)++ monkeypatch.setattr(cfg, "get_secret", fake_get)+ assert ck.get_control_key() == "jctl_cached-key"+ assert ck.get_control_key() == "jctl_cached-key"+ assert calls == 1+++def test_concurrent_auth_checks_share_one_keyring_read(isolated, monkeypatch) -> None:+ calls = 0+ entered = threading.Event()+ release = threading.Event()+ isolated[ck.KEYRING_SLOT] = "jctl_one-dialog"++ def slow_get(key: str, env_fallback: str | None = None) -> str | None:+ nonlocal calls+ calls += 1+ entered.set()+ assert release.wait(timeout=2)+ return isolated.get(key)++ monkeypatch.setattr(cfg, "get_secret", slow_get)+ with ThreadPoolExecutor(max_workers=12) as pool:+ futures = [pool.submit(ck.get_control_key) for _ in range(24)]+ assert entered.wait(timeout=2)+ release.set()+ assert [future.result(timeout=2) for future in futures] == ["jctl_one-dialog"] * 24+ assert calls == 1+++def test_cache_is_invalidated_by_secret_revision(isolated, monkeypatch) -> None:+ revision = 0+ isolated[ck.KEYRING_SLOT] = "jctl_first-value"+ monkeypatch.setattr(cfg, "secret_revision", lambda _key: revision)++ assert ck.get_control_key() == "jctl_first-value"+ isolated[ck.KEYRING_SLOT] = "jctl_second-value"+ assert ck.get_control_key() == "jctl_first-value"+ revision += 1+ assert ck.get_control_key() == "jctl_second-value"+++def test_forked_child_drops_the_parent_cache(isolated, monkeypatch) -> None:+ calls = 0+ isolated[ck.KEYRING_SLOT] = "jctl_parent-value"++ def fake_get(key: str, env_fallback: str | None = None) -> str | None:+ nonlocal calls+ calls += 1+ return isolated.get(key)++ monkeypatch.setattr(cfg, "get_secret", fake_get)+ assert ck.get_control_key() == "jctl_parent-value"+ ck._after_fork_in_child()+ assert ck.get_control_key() == "jctl_parent-value"+ assert calls == 2++def test_ensure_is_idempotent(isolated) -> None:first = ck.ensure_control_key()second = ck.ensure_control_key()@@ -84,6 +166,7 @@ def test_headless_fallback_writes_file(monkeypatch, tmp_path) -> None:assert key_file.is_file()assert key_file.read_text(encoding="utf-8").strip() == key# And it is read back from the file on the next access.+ ck._clear_control_key_cache()assert ck.get_control_key() == keyif sys.platform != "win32":mode = key_file.stat().st_mode & 0o777@@ -114,6 +197,177 @@ def test_env_seed_used_when_no_keyring_no_file(isolated, monkeypatch) -> None:assert ck.KEYRING_SLOT not in isolated+# --- one-time macOS Keychain ownership migration ---+++def test_macos_identity_uses_verified_canonical_designated_requirement(+ monkeypatch, tmp_path+) -> None:+ bundle_path = tmp_path / "Applications" / "Personal Jarvis.app"+ executable = bundle_path / "Contents" / "MacOS" / "PersonalJarvis"+ executable.parent.mkdir(parents=True)+ executable.write_bytes(b"Mach-O test fixture")+ bundle = SimpleNamespace(+ bundleIdentifier=lambda: "com.personal-jarvis.desktop",+ bundlePath=lambda: str(bundle_path),+ executablePath=lambda: str(executable),+ )+ foundation = SimpleNamespace(NSBundle=SimpleNamespace(mainBundle=lambda: bundle))+ commands: list[list[str]] = []++ def fake_run(command: list[str], **kwargs):+ commands.append(command)+ if "--verify" in command:+ return SimpleNamespace(returncode=0)+ return SimpleNamespace(+ returncode=0,+ stderr='# designated => identifier "com.personal-jarvis.desktop"\n',+ stdout="",+ )++ monkeypatch.setattr(ck.sys, "platform", "darwin")+ monkeypatch.setattr(ck.Path, "home", classmethod(lambda _cls: tmp_path))+ monkeypatch.setitem(sys.modules, "Foundation", foundation)+ monkeypatch.setattr(ck.subprocess, "run", fake_run)++ identity = _REAL_MACOS_APP_IDENTITY_TOKEN()+ assert identity is not None+ assert identity.startswith("designated-requirement-v1:")+ assert commands[0][:2] == ["/usr/bin/codesign", "--verify"]+ assert commands[1][:4] == [+ "/usr/bin/codesign",+ "--display",+ "--requirements",+ "-",+ ]+++def test_macos_identity_rejects_direct_python_before_codesign(monkeypatch, tmp_path) -> None:+ bundle = SimpleNamespace(+ bundleIdentifier=lambda: "org.python.python",+ bundlePath=lambda: str(tmp_path),+ executablePath=lambda: str(tmp_path / "python3.12"),+ )+ foundation = SimpleNamespace(NSBundle=SimpleNamespace(mainBundle=lambda: bundle))+ monkeypatch.setattr(ck.sys, "platform", "darwin")+ monkeypatch.setitem(sys.modules, "Foundation", foundation)+ monkeypatch.setattr(+ ck.subprocess,+ "run",+ lambda *args, **kwargs: pytest.fail("codesign must not run for direct Python"),+ )++ assert _REAL_MACOS_APP_IDENTITY_TOKEN() is None+++def test_legacy_macos_item_is_adopted_once(isolated, monkeypatch) -> None:+ identity = "designated-requirement-v1:stable-app"+ writes: list[tuple[str, str]] = []+ isolated[ck.KEYRING_SLOT] = "jctl_legacy-value"+ original_set = cfg.set_secret++ def recording_set(key: str, value: str) -> bool:+ writes.append((key, value))+ return original_set(key, value)++ monkeypatch.setattr(ck.sys, "platform", "darwin")+ monkeypatch.setattr(ck, "_macos_app_identity_token", lambda: identity)+ monkeypatch.setattr(ck, "_platform_credential_store_active", lambda: True)+ monkeypatch.setattr(ck, "_macos_keychain_item_exists", lambda: True)+ monkeypatch.setattr(cfg, "set_secret", recording_set)++ assert ck.get_control_key() == "jctl_legacy-value"+ assert writes == [(ck.KEYRING_SLOT, "jctl_legacy-value")]+ assert ck._macos_owner_file().read_text(encoding="utf-8") == identity++ # A new process under the same designated requirement reads the item but+ # does not delete/re-create it again.+ ck._clear_control_key_cache()+ assert ck.get_control_key() == "jctl_legacy-value"+ assert writes == [(ck.KEYRING_SLOT, "jctl_legacy-value")]+++def test_new_macos_app_requirement_readopts_legacy_item(isolated, monkeypatch) -> None:+ identity = ["designated-requirement-v1:first-build"]+ writes: list[str] = []+ isolated[ck.KEYRING_SLOT] = "jctl_legacy-value"+ original_set = cfg.set_secret++ def recording_set(key: str, value: str) -> bool:+ writes.append(identity[0])+ return original_set(key, value)++ monkeypatch.setattr(ck.sys, "platform", "darwin")+ monkeypatch.setattr(ck, "_macos_app_identity_token", lambda: identity[0])+ monkeypatch.setattr(ck, "_platform_credential_store_active", lambda: True)+ monkeypatch.setattr(ck, "_macos_keychain_item_exists", lambda: True)+ monkeypatch.setattr(cfg, "set_secret", recording_set)++ assert ck.get_control_key() == "jctl_legacy-value"+ identity[0] = "designated-requirement-v1:rebuilt-app"+ ck._clear_control_key_cache()+ assert ck.get_control_key() == "jctl_legacy-value"+ assert writes == [+ "designated-requirement-v1:first-build",+ "designated-requirement-v1:rebuilt-app",+ ]+++def test_direct_python_read_never_changes_keychain_acl(isolated, monkeypatch) -> None:+ writes = 0+ isolated[ck.KEYRING_SLOT] = "jctl_legacy-value"++ def unexpected_set(key: str, value: str) -> bool:+ nonlocal writes+ writes += 1+ return True++ monkeypatch.setattr(ck, "_macos_app_identity_token", lambda: None)+ monkeypatch.setattr(cfg, "set_secret", unexpected_set)+ assert ck.get_control_key() == "jctl_legacy-value"+ assert writes == 0+++def test_file_seed_is_not_promoted_into_macos_keychain(isolated, monkeypatch) -> None:+ writes = 0+ ck.control_key_file().write_text("jctl_file-value", encoding="utf-8")+ monkeypatch.setattr(ck.sys, "platform", "darwin")+ monkeypatch.setattr(+ ck,+ "_macos_app_identity_token",+ lambda: "designated-requirement-v1:stable-app",+ )+ monkeypatch.setattr(ck, "_platform_credential_store_active", lambda: True)+ monkeypatch.setattr(ck, "_macos_keychain_item_exists", lambda: False)++ def unexpected_set(key: str, value: str) -> bool:+ nonlocal writes+ writes += 1+ return True++ monkeypatch.setattr(cfg, "set_secret", unexpected_set)+ assert ck.get_control_key() == "jctl_file-value"+ assert writes == 0+++def test_macos_owner_stamp_requires_a_successful_platform_write(+ isolated, monkeypatch+) -> None:+ identity = "designated-requirement-v1:stable-app"+ monkeypatch.setattr(ck.sys, "platform", "darwin")+ monkeypatch.setattr(ck, "_macos_app_identity_token", lambda: identity)+ monkeypatch.setattr(ck, "_platform_credential_store_active", lambda: True)++ ck.set_control_key("correct-horse-battery")+ assert ck._macos_owner_file().read_text(encoding="utf-8") == identity++ # A failed Keychain write can still succeed via the dedicated 0600 file,+ # but it must not retain a false claim that the app owns a Keychain item.+ monkeypatch.setattr(cfg, "set_secret", lambda *args, **kwargs: False)+ ck.set_control_key("another-correct-key")+ assert not ck._macos_owner_file().exists()++# --- user-chosen key (set_control_key) ---