From caccc8296bc8ef77c9bb63dd5e1f94a53edf62b5 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 09:59:46 +0100 Subject: [PATCH 01/24] spike(sync): prove encrypted transcript envelopes and define Drive pairing/recovery plan --- docs/workstreams/secure-sync-google-drive.md | 57 ++++++ experiments/secure_sync/README.md | 15 ++ experiments/secure_sync/secure_sync.py | 177 +++++++++++++++++++ experiments/secure_sync/test_secure_sync.py | 86 +++++++++ 4 files changed, 335 insertions(+) create mode 100644 docs/workstreams/secure-sync-google-drive.md create mode 100644 experiments/secure_sync/README.md create mode 100644 experiments/secure_sync/secure_sync.py create mode 100644 experiments/secure_sync/test_secure_sync.py diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md new file mode 100644 index 00000000..d586644d --- /dev/null +++ b/docs/workstreams/secure-sync-google-drive.md @@ -0,0 +1,57 @@ +# Secure multi-device transcript sync — Google Drive pilot + +Status: ACTIVE / isolated security-format experiment on `feature/google-drive-secure-sync-foundation` +Target: `dev`. Product: PRODUCT_FEATURE; delivery: ITERATION; validation: STRONG for security/data lifecycle; execution: AGENT_LOCAL prototype, REMOTE_AUTOMATED integration, REAL_ENVIRONMENT for Keychain/OAuth and independent second Mac. No release claim. + +## User and outcome + +A ClosedRoom user records, transcribes, diarizes and analyzes meetings on-device, and can privately read the resulting transcript/notes on an authorized second device **while the original Mac is powered off**. Primary experience is read-only until conflicts and trust-recovery are proven. No assumption of cloud inference, cloud account requirement, browser execution or cloud fallback. + +Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/models, collaborative sharing, bidirectional editing, server-hosted plaintext search, silent automatic upload, cleanup or migration of legacy material. + +### Risks and decisions + +- **VALUE:** verify that a second Mac can read a finalized transcript offline; no mobile build is needed to validate the job. +- **USABILITY:** Google connection must not be confused with cryptographic authorization; device enrollment requires mutual verification and explicit approval. A comprehensible independent recovery flow is essential. +- **FEASIBILITY:** canonical data are split across `TranscriptionStore`, `RecordingStore` and `CatalogStore`; do not sync their raw files, WAL DB or directories, and do not create alternate persistence owners. +- **VIABILITY:** user-owned Google Drive storage avoids a ClosedRoom-hosted content server, but OAuth setup/review, API quotas and support still have costs. +- **PRIVACY/SECURITY:** default is local-only, user opts into Drive separately. The app encrypts *before* any network call. Google can observe account, traffic, object counts/sizes and timing. Google OAuth is not vault authorization. No analytics, meeting content or secrets in logs/CI. +- **DATA INTEGRITY:** upload success is not verified recovery; snapshot must be decryptable and restorable on an independent device before claiming recoverability. Do not evict audio/transcripts. A provider can delete/replay old authenticated data unless trusted state/backup prevents it. + +## Canonical ownership and system contract + +- `TranscriptionStore` owns transcription identity, content, correction and analysis; `RecordingStore` owns notes, screenshots and recording/audio lifecycle; `CatalogStore` owns local indexes. +- Future sync **reads a versioned allowlisted projection** from these owners. Do not mutate local canonical source data on import; remote read-only cache needs a scoped persistence owner and lifecycle design before implementation. +- Encrypt whole snapshot on originating Mac. In the proof format the public header is only schema version, opaque random object id, random HKDF salt/nonce, ciphertext. IDs, titles, speaker labels, notes and transcript are inside authenticated encryption. +- For production: a vault root key protected by Keychain (and a separately held user recovery secret), device-specific asymmetric identities, explicit pairing, key epoch/rotation, authenticated signed append-only manifest/head, replay/rollback detection with pinned trusted checkpoints, signed revocation and tested failure recovery. +- Storage: Drive API v3 `appDataFolder`, OAuth `drive.appdata` least privilege, on-device token storage, `changes.list` with `spaces=appDataFolder` only after an initial exhaustive inventory; bounded retry/rate limiting and offline queue. No sharing in appDataFolder: new device authenticates to same Google account but gets vault access **only** via authenticated pairing/recovery. +- Safe deletion in every layer: remote cache deletion != meeting deletion != audio eviction. Never delete the last verified copy. No secrets/API tokens in public manifests or exported docs. + +## UX — first enrollment and additional device + +1. Settings → Privacy & storage → Sync devices. Default OFF; consent explains what leaves the Mac (only ciphertext; no audio or screenshots). Connect Google account through OS/browser OAuth; show actual effective state, not saved preference as success. +2. Mac generates vault secret and device identity **locally**, stores secrets in Keychain; user receives independent recovery code and must confirm they saved it before enabling upload. No server stores plaintext keys. New transcripts remain local until explicit opt-in. +3. Second Mac: choose "Link existing vault" then sign in to same Google account (this proves storage access only). New device creates ephemeral key pair and a short-lived QR challenge. +4. Existing Mac: scan QR or enter a safe short linking code, compare a human-readable authentication phrase/6-digit code on *both* screens, explicitly approve the new device with name and permission "Read only". Expiring one-time challenge, mutual authentication, replay protection and no unverified key substitution. +5. Existing Mac encrypts a device-specific vault-key grant bound to new device public key and confirmed challenge; new Mac verifies owner signature and decrypts the grant locally. **Never put the root key, grants to unintended recipients or recovery secret in a QR or Drive plaintext.** A compromised Drive account alone must not authorize a new device. +6. New Mac downloads encrypted manifest/objects, checks authenticated revisions and decrypts into private read-only offline cache. UI: Downloading / Available offline / Locked / Key needed / Conflict / Not recoverable, with retry. No fake success when no verified decrypt. +7. Devices list: show name, enrollment time, last authenticated sync and read-only privilege; explicit revoke. Revocation rotates future content keys and stops new grants. Cached plaintext already accessed on a stolen device is **not remotely erasable with certainty**. +8. Recovery if no authorized device remains: supply independent recovery secret *plus* ownership of Drive data, reconstruct identity/keys on clean Mac, rotate device grants and invalidate old devices. If every key/recovery secret is lost, data are unrecoverable by design. Test a genuine independent restore before calling it backup. + +## Execution graph and evidence + +| ID | Outcome | Status | Required evidence | +| --- | --- | --- | --- | +| SYNC-0 | Threat model, consent boundaries, pairing/recovery flow; no implicit remote fallback | DONE design | Review with canonical storage owners | +| SYNC-1 | Prove a portable AES-256-GCM authenticated transcript-only object with no raw export of paths/provider credentials | DONE experimental | Synthetic round-trip, wrong key, tamper, invalid schema/size, plaintext absence (6 local tests) | +| SYNC-2 | Production vault identity/Keychain and independent recovery materials, crypto dependency+locked build, signed manifest/head/anti-rollback | READY | Clean/compromised-device, key loss, replay, rotation, crash and security review | +| SYNC-3 | Explicit OAuth `drive.appdata` and Drive read/write adapter, offline outbox, receipts and bounded incremental list | BLOCKED on SYNC-2 | Fake transport faults + real isolated Google test account, no sensitive user meetings | +| SYNC-4 | Read-only canonical projection and isolated second-Mac cache; pairing/permissions/revoke UX | BLOCKED on SYNC-2/3 | Second physical Mac with source powered off, cache offline, mutual QR verification, revoke | +| SYNC-5 | Integrated Settings/Meeting status, complete privacy copy, accessible UX and correct cleanup | BLOCKED on SYNC-4 | Automated E2E FULL_MEDIA; WKWebView/Keychain target Mac; security/recovery audit | +| SYNC-6 | Consider mobile companion/read-write editing **only after** the above is verified | BLOCKED | Product evidence and conflict-management design | + +### Current checkpoint + +- Baseline checked: `dev` `de0d1809e5f33c6dcc9a43895d81d336c4f2ba62`; standalone GCS **preparation-only** in dev, no automatic cloud runtime. GCS experimental encrypted cold backup is **not** per-meeting sync. +- This branch touches only an isolated `experiments/secure_sync` proof and this plan. It does not modify the app/pyproject/lockfile or introduce a network caller. Six synthetic tests passed in a separate Python environment with `cryptography 46.0.4`; this is **not** installed-app or exact-HEAD CI evidence. +- Next discriminating action: integrate cryptographic owner/Keychain and trusted manifest design, then prove an encrypted file transfer between two independent local instances before OAuth or real user data. Do not enable provider until security tests and recovery evidence exist. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md new file mode 100644 index 00000000..4cb8b132 --- /dev/null +++ b/experiments/secure_sync/README.md @@ -0,0 +1,15 @@ +# Secure sync crypto proof — NOT production sync + +Isolated, offline-only format experiment. No Google OAuth, network traffic, upload, background job, Keychain, device pairing, cloud fallback, app integration or cleanup. Requires `cryptography` (not added to the product lockfile). + +Run with the dependency available: + +```sh +python3 -m unittest discover -s experiments/secure_sync -v +``` + +The 32-byte secret is **test-only** in this experiment. Do not persist it in plaintext, pass it to telemetry, store it in Drive, or treat the local test fixture as a recovery-key protocol. + +The format intentionally authenticates header fields and ciphertext using HKDF-SHA256 + AES-256-GCM. It does **not** establish remote freshness, authorization of devices, revocation, concurrency control, recovery, verified upload/restore or a production export/import path. In particular a malicious/compromised storage provider may delete objects or replay an older *valid* ciphertext; those protections need a trusted authenticated manifest/head checkpoint and independent backup. + +Next step: review and adapt this format in the existing canonical TranscriptionStore/RecordingStore projection owners; add correctly locked crypto dependency, consent and Keychain management; add a read-only separate device cache and a Google Drive appDataFolder adapter behind explicit opt-in. diff --git a/experiments/secure_sync/secure_sync.py b/experiments/secure_sync/secure_sync.py new file mode 100644 index 00000000..fc6d5c1f --- /dev/null +++ b/experiments/secure_sync/secure_sync.py @@ -0,0 +1,177 @@ +"""Opt-in, offline-only encrypted transcript snapshot format (no transport or keys at rest). + +Never call this module from recording finalization. A caller must explicitly +select what to export and persist the vault key in an OS-protected owner. +""" + +from __future__ import annotations + +import base64 +import binascii +import json +import secrets +from collections.abc import Mapping, Sequence +from typing import Any + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.kdf.hkdf import HKDF + +FORMAT = "closedroom.encrypted-transcript" +VERSION = 1 +MAX_PLAINTEXT_BYTES = 8 * 1024 * 1024 +MAX_ENVELOPE_BYTES = 12 * 1024 * 1024 +_HEADER_FIELDS = frozenset({"format", "version", "object_id", "salt", "nonce"}) +_ENVELOPE_FIELDS = _HEADER_FIELDS | {"ciphertext"} + + +class SecureSyncError(ValueError): + """A malformed, unsupported or unauthenticated snapshot.""" + + +def generate_vault_key() -> bytes: + """Create a secret. The caller MUST securely persist/backup it outside Drive.""" + return secrets.token_bytes(32) + + +def _validate_key(key: bytes) -> None: + if not isinstance(key, bytes) or len(key) != 32: + raise SecureSyncError("A 32-byte vault key is required") + + +def _json_bytes(value: Any) -> bytes: + return json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False, + ).encode("utf-8") + + +def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for name, value in pairs: + if name in result: + raise SecureSyncError("Duplicate field in encrypted snapshot") + result[name] = value + return result + + +def _parse_json(raw: bytes) -> Any: + try: + return json.loads( + raw.decode("utf-8"), object_pairs_hook=_reject_duplicate_keys, + parse_constant=lambda _: (_ for _ in ()).throw(SecureSyncError("Invalid JSON constant")), + ) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise SecureSyncError("Invalid encrypted snapshot encoding") from exc + + +def _decode_field(value: Any, expected_length: int | None = None) -> bytes: + if not isinstance(value, str): + raise SecureSyncError("Invalid encrypted snapshot field") + try: + decoded = base64.b64decode(value, validate=True) + except (ValueError, binascii.Error) as exc: + raise SecureSyncError("Invalid encrypted snapshot field") from exc + if expected_length is not None and len(decoded) != expected_length: + raise SecureSyncError("Invalid encrypted snapshot field length") + return decoded + + +def transcript_snapshot( + transcription: Mapping[str, Any], *, title: str = "", notes: Sequence[Mapping[str, Any]] = (), +) -> dict[str, Any]: + """Allowlist read-only content from canonical stores; never copy raw metadata. + + This is a snapshot projection, not an importer or a transactional multi-store + read. Capture consistency and versioned sync will be addressed separately. + """ + if not isinstance(transcription, Mapping) or not isinstance(transcription.get("id"), str) or not transcription["id"]: + raise SecureSyncError("Missing transcription identity") + if not isinstance(transcription.get("text"), str) or not isinstance(title, str): + raise SecureSyncError("Invalid transcription text or title") + if not isinstance(notes, (list, tuple)): + raise SecureSyncError("Invalid notes") + projected_notes = [] + for note in notes: + if not isinstance(note, Mapping) or not isinstance(note.get("note_id"), str) or not isinstance(note.get("text"), str): + raise SecureSyncError("Invalid note") + projected_notes.append({ + "note_id": note["note_id"], "text": note["text"], + "timestamp": note.get("timestamp"), "revision": note.get("revision"), + }) + return { + "schema": 1, + "kind": "transcription_readonly", + "transcription_id": transcription["id"], + "recording_id": transcription.get("recording_id") or "", + "title": title, + "timestamp": transcription.get("timestamp"), + "language": transcription.get("language"), + "text": transcription["text"], + "segments": transcription.get("segments") or [], + "analysis": transcription.get("analysis"), + "speaker_diarization": transcription.get("speaker_diarization"), + "speaker_attribution": transcription.get("speaker_attribution"), + "notes": projected_notes, + } + + +def seal_snapshot(snapshot: Mapping[str, Any], vault_key: bytes) -> bytes: + """Encrypt a read-only transcript with HKDF-SHA256/AES-256-GCM. + + Object identifiers and sizes are visible to the provider. Contents, IDs, + speaker names and titles are authenticated ciphertext. No network I/O. + """ + _validate_key(vault_key) + if not isinstance(snapshot, Mapping) or snapshot.get("schema") != 1 or snapshot.get("kind") != "transcription_readonly": + raise SecureSyncError("Unsupported transcript snapshot") + try: + plaintext = _json_bytes(dict(snapshot)) + except (TypeError, ValueError, OverflowError) as exc: + raise SecureSyncError("Invalid transcript snapshot contents") from exc + if len(plaintext) > MAX_PLAINTEXT_BYTES: + raise SecureSyncError("Transcript snapshot exceeds size limit") + salt = secrets.token_bytes(16) + nonce = secrets.token_bytes(12) + header = { + "format": FORMAT, "version": VERSION, + "object_id": secrets.token_hex(16), + "salt": base64.b64encode(salt).decode("ascii"), + "nonce": base64.b64encode(nonce).decode("ascii"), + } + key = HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=b"ClosedRoom/transcript-snapshot/v1").derive(vault_key) + ciphertext = AESGCM(key).encrypt(nonce, plaintext, _json_bytes(header)) + result = _json_bytes({**header, "ciphertext": base64.b64encode(ciphertext).decode("ascii")}) + if len(result) > MAX_ENVELOPE_BYTES: + raise SecureSyncError("Encrypted snapshot exceeds size limit") + return result + + +def open_snapshot(envelope: bytes, vault_key: bytes) -> dict[str, Any]: + """Fail closed on malformed format, unauthenticated metadata or wrong key.""" + _validate_key(vault_key) + if not isinstance(envelope, bytes) or len(envelope) > MAX_ENVELOPE_BYTES: + raise SecureSyncError("Invalid encrypted snapshot size") + package = _parse_json(envelope) + if not isinstance(package, dict) or set(package) != _ENVELOPE_FIELDS: + raise SecureSyncError("Invalid encrypted snapshot fields") + if package["format"] != FORMAT or type(package["version"]) is not int or package["version"] != VERSION: + raise SecureSyncError("Unsupported encrypted snapshot version") + object_id = package["object_id"] + if not isinstance(object_id, str) or len(object_id) != 32 or any(c not in "0123456789abcdef" for c in object_id): + raise SecureSyncError("Invalid object identity") + salt = _decode_field(package["salt"], 16) + nonce = _decode_field(package["nonce"], 12) + ciphertext = _decode_field(package["ciphertext"]) + if len(ciphertext) < 16 or len(ciphertext) > MAX_PLAINTEXT_BYTES + 16: + raise SecureSyncError("Invalid ciphertext length") + header = {name: package[name] for name in _HEADER_FIELDS} + key = HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=b"ClosedRoom/transcript-snapshot/v1").derive(vault_key) + try: + plaintext = AESGCM(key).decrypt(nonce, ciphertext, _json_bytes(header)) + except InvalidTag as exc: + raise SecureSyncError("Encrypted snapshot authentication failed") from exc + snapshot = _parse_json(plaintext) + if not isinstance(snapshot, dict) or snapshot.get("schema") != 1 or snapshot.get("kind") != "transcription_readonly": + raise SecureSyncError("Unsupported decrypted transcript snapshot") + return snapshot diff --git a/experiments/secure_sync/test_secure_sync.py b/experiments/secure_sync/test_secure_sync.py new file mode 100644 index 00000000..8340cf37 --- /dev/null +++ b/experiments/secure_sync/test_secure_sync.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import base64 +import json +import unittest + +from secure_sync import ( + MAX_ENVELOPE_BYTES, SecureSyncError, generate_vault_key, + open_snapshot, seal_snapshot, transcript_snapshot, +) + + +class SecureSyncTests(unittest.TestCase): + def setUp(self): + self.key = generate_vault_key() + self.snapshot = transcript_snapshot( + { + "id": "private-transcript-id", "recording_id": "secret-recording-id", + "timestamp": "2026-11-19T09:40:00Z", "language": "it", + "text": "Piano di acquisizione estremamente riservato.", + "segments": [{"text": "Ciao", "speaker": "Daniele", "start": 0, "end": 1}], + "analysis": {"summary": "Budget M&A confidenziale"}, + "audio_filename": "/private/sensitive-mic.wav", + "provider_options": {"api_key": "DO_NOT_EXPORT_KEY"}, + }, title="Board M&A", notes=[{ + "note_id": "note-1", "text": "Decisione segreta", "timestamp": 1.0, + "revision": 2, "local_path": "/secret/path", + }], + ) + + def test_roundtrip_across_independent_key_holders(self): + blob = seal_snapshot(self.snapshot, self.key) + self.assertEqual(open_snapshot(bytes(blob), bytes(self.key)), self.snapshot) + + def test_no_plaintext_leak_or_raw_metadata(self): + blob = seal_snapshot(self.snapshot, self.key) + for phrase in (b"Board M&A", b"Piano di acquisizione", b"Daniele", b"Decisione segreta", b"private-transcript-id"): + self.assertNotIn(phrase, blob) + self.assertNotIn("audio_filename", self.snapshot) + self.assertNotIn("provider_options", self.snapshot) + self.assertNotIn("local_path", str(self.snapshot)) + + def test_wrong_key_and_tampering_fail_closed(self): + blob = seal_snapshot(self.snapshot, self.key) + with self.assertRaises(SecureSyncError): + open_snapshot(blob, generate_vault_key()) + package = json.loads(blob) + raw = bytearray(base64.b64decode(package["ciphertext"])) + raw[-1] ^= 1 + package["ciphertext"] = base64.b64encode(raw).decode("ascii") + with self.assertRaises(SecureSyncError): + open_snapshot(json.dumps(package).encode(), self.key) + package = json.loads(blob) + package["object_id"] = "0" * 32 + with self.assertRaises(SecureSyncError): + open_snapshot(json.dumps(package).encode(), self.key) + + def test_unique_seals_of_same_snapshot(self): + self.assertNotEqual(seal_snapshot(self.snapshot, self.key), seal_snapshot(self.snapshot, self.key)) + + def test_parser_rejects_duplicate_unknown_and_future_versions(self): + blob = seal_snapshot(self.snapshot, self.key) + with self.assertRaises(SecureSyncError): + open_snapshot(blob[:-1] + b',"version":1}', self.key) + package = json.loads(blob) + package["version"] = 2 + with self.assertRaises(SecureSyncError): + open_snapshot(json.dumps(package).encode(), self.key) + package = json.loads(blob) + package["secret"] = "foo" + with self.assertRaises(SecureSyncError): + open_snapshot(json.dumps(package).encode(), self.key) + + def test_size_limits_and_input_validations(self): + with self.assertRaises(SecureSyncError): + seal_snapshot(self.snapshot, b"bad") + with self.assertRaises(SecureSyncError): + open_snapshot(b"x" * (MAX_ENVELOPE_BYTES + 1), self.key) + with self.assertRaises(SecureSyncError): + transcript_snapshot({"id": "x", "text": "hello"}, notes=[{"text": "no-id"}]) + with self.assertRaises(SecureSyncError): + seal_snapshot({**self.snapshot, "text": "x" * (9 * 1024 * 1024)}, self.key) + + +if __name__ == "__main__": + unittest.main() From d9c2cfddbfc6e3826a9564722545af7c416e8255 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 10:22:19 +0100 Subject: [PATCH 02/24] feat(sync-spike): add signed vault manifest and fail-closed Mac Keychain prototype --- docs/workstreams/secure-sync-google-drive.md | 14 +- experiments/secure_sync/README.md | 9 +- .../secure_sync/test_vault_foundation.py | 167 +++++++++++++++ experiments/secure_sync/vault_keychain.py | 162 ++++++++++++++ experiments/secure_sync/vault_manifest.py | 198 ++++++++++++++++++ 5 files changed, 546 insertions(+), 4 deletions(-) create mode 100644 experiments/secure_sync/test_vault_foundation.py create mode 100644 experiments/secure_sync/vault_keychain.py create mode 100644 experiments/secure_sync/vault_manifest.py diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index d586644d..378325cd 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -44,14 +44,22 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model | --- | --- | --- | --- | | SYNC-0 | Threat model, consent boundaries, pairing/recovery flow; no implicit remote fallback | DONE design | Review with canonical storage owners | | SYNC-1 | Prove a portable AES-256-GCM authenticated transcript-only object with no raw export of paths/provider credentials | DONE experimental | Synthetic round-trip, wrong key, tamper, invalid schema/size, plaintext absence (6 local tests) | -| SYNC-2 | Production vault identity/Keychain and independent recovery materials, crypto dependency+locked build, signed manifest/head/anti-rollback | READY | Clean/compromised-device, key loss, replay, rotation, crash and security review | +| SYNC-2 | Production vault identity/Keychain and independent recovery materials, crypto dependency+locked build, signed manifest/head/anti-rollback | ACTIVE (offline proof only) | Clean/compromised-device, key loss, replay, rotation, crash and security review | | SYNC-3 | Explicit OAuth `drive.appdata` and Drive read/write adapter, offline outbox, receipts and bounded incremental list | BLOCKED on SYNC-2 | Fake transport faults + real isolated Google test account, no sensitive user meetings | | SYNC-4 | Read-only canonical projection and isolated second-Mac cache; pairing/permissions/revoke UX | BLOCKED on SYNC-2/3 | Second physical Mac with source powered off, cache offline, mutual QR verification, revoke | | SYNC-5 | Integrated Settings/Meeting status, complete privacy copy, accessible UX and correct cleanup | BLOCKED on SYNC-4 | Automated E2E FULL_MEDIA; WKWebView/Keychain target Mac; security/recovery audit | | SYNC-6 | Consider mobile companion/read-write editing **only after** the above is verified | BLOCKED | Product evidence and conflict-management design | +### Offline proof extension (2026-11-19) + +- New `experiments/secure_sync/vault_manifest.py`: Ed25519 owner-signed canonical manifests with stable opaque vault IDs, digest-bound ciphertext references, contiguous revision chain and monotonic epoch. Verification rejects wrong signer, tampering, missing intermediary revision, older head and same-revision fork against an independently trusted checkpoint. An unchanged authenticated head is an idempotent no-op. +- New `experiments/secure_sync/vault_keychain.py`: explicit opt-in Keychain-backed prototype for a random vault key and **separate Ed25519 software signing identity**, authenticated owner-public-key pin and locally retained trusted checkpoint. Missing/corrupted keys, unsafe backends, pin substitution and failed readback fail closed. Mac Keychain backend and Security.framework entitlement behavior are **NOT yet tested on a real macOS app**. This is not a hardware-bound Secure Enclave Ed25519 key. +- New synthetic `test_vault_foundation.py` exercises signing/tampering/rollback/forks, object hashes, key overwrite prevention, restart persistence through a fake backend and missing/corrupt state. Cross-process Keychain atomicity, secure pairing, user recovery codes, signing-key rotation, true restore and real Mac behavior are still unimplemented. +- **Fresh-device limitation**: an authenticated key + a genesis manifest does NOT prove remote freshness. Pairing/recovery must independently convey an authenticated latest trusted checkpoint. A provider may suppress all updates or delete objects, and local checkpoints can be lost on OS restore. Design recovery, independent backup and a single authoritative local writer before enabling Drive. +- This slice is isolated; no OAuth/network, no automatic upload, no app wiring, no dependency/lockfile modification, no migration, no local eviction, no change to active storage mode. Do not present this as sync-ready or Keychain-qualified. + ### Current checkpoint - Baseline checked: `dev` `de0d1809e5f33c6dcc9a43895d81d336c4f2ba62`; standalone GCS **preparation-only** in dev, no automatic cloud runtime. GCS experimental encrypted cold backup is **not** per-meeting sync. -- This branch touches only an isolated `experiments/secure_sync` proof and this plan. It does not modify the app/pyproject/lockfile or introduce a network caller. Six synthetic tests passed in a separate Python environment with `cryptography 46.0.4`; this is **not** installed-app or exact-HEAD CI evidence. -- Next discriminating action: integrate cryptographic owner/Keychain and trusted manifest design, then prove an encrypted file transfer between two independent local instances before OAuth or real user data. Do not enable provider until security tests and recovery evidence exist. +- This branch touches only an isolated `experiments/secure_sync` proof and this plan; the Keychain/manifest components are experiments, not canonical runtime services. It does not modify the app/pyproject/lockfile or introduce a network caller. Six synthetic tests passed in a separate Python environment with `cryptography 46.0.4`; this is **not** installed-app or exact-HEAD CI evidence. +- Next discriminating action: run the exact new tests under the repository's targeted validation, verify native macOS Keychain behavior and the Keychain checkpoint across real restarts, and establish trusted second-device head transport. Then prove an encrypted file transfer between two independent local instances before OAuth or real user data. Do not enable provider until security tests and recovery evidence exist. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index 4cb8b132..7f91192a 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -1,6 +1,6 @@ # Secure sync crypto proof — NOT production sync -Isolated, offline-only format experiment. No Google OAuth, network traffic, upload, background job, Keychain, device pairing, cloud fallback, app integration or cleanup. Requires `cryptography` (not added to the product lockfile). +Isolated, offline-only format experiment. No Google OAuth, network traffic, upload, background job, production Keychain integration, device pairing, cloud fallback, app integration or cleanup. Requires `cryptography` for all crypto tests and optional `keyring` for a genuine macOS Keychain probe (neither dependency is added to the product lockfile). Run with the dependency available: @@ -8,6 +8,13 @@ Run with the dependency available: python3 -m unittest discover -s experiments/secure_sync -v ``` +Additional isolated components: +- `vault_manifest.py`: Ed25519-signed manifest chain, opaque ciphertext digests and checkpoint verification. Authenticated latest head is an **independent trust requirement**, not provided by Google Drive alone. +- `vault_keychain.py`: explicit macOS Keychain-only prototype for vault and software Ed25519 signing secrets, an out-of-band owner key pin and a trusted local checkpoint. Fake Keychain tests do not demonstrate that a packaged Mac app can access the Keychain. The test injection is **not** a production option. No automatic initialization. +- `test_vault_foundation.py`: key corruption, wrong signer, replay, fork, restart and no-fallback cases. + +No cross-process compare-and-swap, signed device grants, user recovery secret, real Mac/Keychain integration or provider-freshness guarantee exists. A clean device **must not accept Drive's purported current head as proof of freshness**. Do not activate upload or deletion. + The 32-byte secret is **test-only** in this experiment. Do not persist it in plaintext, pass it to telemetry, store it in Drive, or treat the local test fixture as a recovery-key protocol. The format intentionally authenticates header fields and ciphertext using HKDF-SHA256 + AES-256-GCM. It does **not** establish remote freshness, authorization of devices, revocation, concurrency control, recovery, verified upload/restore or a production export/import path. In particular a malicious/compromised storage provider may delete objects or replay an older *valid* ciphertext; those protections need a trusted authenticated manifest/head checkpoint and independent backup. diff --git a/experiments/secure_sync/test_vault_foundation.py b/experiments/secure_sync/test_vault_foundation.py new file mode 100644 index 00000000..b53ad99f --- /dev/null +++ b/experiments/secure_sync/test_vault_foundation.py @@ -0,0 +1,167 @@ +"""Security proof cases; fake Keychain is not representative macOS validation.""" +from __future__ import annotations + +import json +import unittest +from unittest.mock import patch + +from vault_manifest import ( + ManifestError, generate_owner_signing_key, new_manifest, new_vault_id, + object_reference, public_key_bytes, sign_manifest, verify_manifest, verify_object, +) +from vault_keychain import KeychainError, MacKeychainVaultKeys, SERVICE + + +class FakeKeychain: + def __init__(self): + self.data = {} + self.fail_write = False + + def get_password(self, service, name): + return self.data.get((service, name)) + + def set_password(self, service, name, value): + if self.fail_write: + raise OSError("synthetic Keychain failure") + self.data[(service, name)] = value + + +class ManifestTests(unittest.TestCase): + def setUp(self): + self.owner = generate_owner_signing_key() + self.pub = public_key_bytes(self.owner) + self.vault = new_vault_id() + self.genesis = sign_manifest( + new_manifest(vault_id=self.vault, revision=0, previous=None), self.owner, + ) + self.first = verify_manifest(self.genesis, self.pub) + + def test_signed_genesis_and_contiguous_update(self): + nxt = sign_manifest(new_manifest( + vault_id=self.vault, revision=1, previous=self.first.digest, + ), self.owner) + accepted = verify_manifest(nxt, self.pub, self.first) + self.assertEqual(accepted.revision, 1) + self.assertEqual(verify_manifest(nxt, self.pub, accepted), accepted) + + def test_invalid_signer_and_mutated_header_are_rejected(self): + with self.assertRaises(ManifestError): + verify_manifest(self.genesis, public_key_bytes(generate_owner_signing_key())) + tampered = json.loads(self.genesis) + tampered["manifest"]["key_epoch"] = 2 + with self.assertRaises(ManifestError): + verify_manifest(json.dumps(tampered).encode("utf-8"), self.pub) + + def test_older_head_and_fork_are_rejected(self): + nxt = new_manifest(vault_id=self.vault, revision=1, previous=self.first.digest) + accepted = verify_manifest(sign_manifest(nxt, self.owner), self.pub, self.first) + with self.assertRaises(ManifestError): + verify_manifest(self.genesis, self.pub, accepted) + fork = new_manifest( + vault_id=self.vault, revision=1, previous=self.first.digest, + objects=[object_reference("a" * 32, b"ciphertext")], + ) + with self.assertRaises(ManifestError): + verify_manifest(sign_manifest(fork, self.owner), self.pub, accepted) + + def test_reject_unknown_future_and_skipped_versions(self): + with self.assertRaises(ManifestError): + sign_manifest({**new_manifest( + vault_id=self.vault, revision=0, previous=None, + ), "version": 2}, self.owner) + skipped = sign_manifest(new_manifest( + vault_id=self.vault, revision=2, previous="f" * 64, + ), self.owner) + with self.assertRaises(ManifestError): + verify_manifest(skipped, self.pub, self.first) + with self.assertRaises(ManifestError): + verify_manifest(skipped, self.pub) + + def test_signed_object_digest_binds_encrypted_content(self): + reference = object_reference("a" * 32, b"encrypted-bytes") + verify_object(reference, b"encrypted-bytes") + with self.assertRaises(ManifestError): + verify_object(reference, b"substituted") + with self.assertRaises(ManifestError): + new_manifest( + vault_id=self.vault, revision=0, previous=None, + objects=[reference, reference], + ) + + def test_duplicate_json_fields_are_rejected(self): + duplicate = self.genesis[:-1] + b', "signature":"duplicate"}' + with self.assertRaises(ManifestError): + verify_manifest(duplicate, self.pub) + + +class KeychainTests(unittest.TestCase): + def setUp(self): + self.backend = FakeKeychain() + self.keys = MacKeychainVaultKeys(_test_backend=self.backend) + self.vault = "a" * 32 + + def test_vault_key_is_random_nonoverwritable_and_restart_readable(self): + original = self.keys.create(self.vault) + self.assertEqual(len(original), 32) + new_process = MacKeychainVaultKeys(_test_backend=self.backend) + self.assertEqual(new_process.load(self.vault), original) + with self.assertRaises(KeychainError): + new_process.create(self.vault) + + def test_separate_owner_identity_and_corrupt_material(self): + signer = self.keys.create_owner_signer(self.vault) + self.assertEqual( + signer.public_key().public_bytes_raw(), + MacKeychainVaultKeys(_test_backend=self.backend).load_owner_signer(self.vault) + .public_key().public_bytes_raw(), + ) + with self.assertRaises(KeychainError): + self.keys.create_owner_signer(self.vault) + self.backend.data[(SERVICE, self.vault + ":owner-signing")] = "garbled!" + with self.assertRaises(KeychainError): + self.keys.load_owner_signer(self.vault) + + def test_trusted_pin_checkpoint_survive_restart_and_reject_replay(self): + signer = self.keys.create_owner_signer(self.vault) + self.keys.pin_authenticated_owner(self.vault, signer.public_key().public_bytes_raw()) + first_doc = sign_manifest(new_manifest( + vault_id=self.vault, revision=0, previous=None, + ), signer) + first = self.keys.accept_signed_head(self.vault, first_doc) + nxt = sign_manifest(new_manifest( + vault_id=self.vault, revision=1, previous=first.digest, + ), signer) + expected = self.keys.accept_signed_head(self.vault, nxt) + restarted = MacKeychainVaultKeys(_test_backend=self.backend) + self.assertEqual(restarted.load_checkpoint(self.vault), expected) + self.assertEqual(restarted.accept_signed_head(self.vault, nxt), expected) + with self.assertRaises(ManifestError): + restarted.accept_signed_head(self.vault, first_doc) + with self.assertRaises(KeychainError): + self.keys.pin_authenticated_owner(self.vault, b"x" * 32) + + def test_missing_anchor_corrupt_checkpoint_and_backend_error_fail_closed(self): + signer = self.keys.create_owner_signer(self.vault) + document = sign_manifest(new_manifest( + vault_id=self.vault, revision=0, previous=None, + ), signer) + with self.assertRaises(KeychainError): + self.keys.accept_signed_head(self.vault, document) + self.keys.pin_authenticated_owner(self.vault, signer.public_key().public_bytes_raw()) + self.backend.data[(SERVICE, self.vault + ":checkpoint")] = '{"revision":0}' + with self.assertRaises(KeychainError): + self.keys.accept_signed_head(self.vault, document) + self.backend.fail_write = True + with self.assertRaises(KeychainError): + self.keys.create("b" * 32) + + def test_no_insecure_linux_fallback_and_bad_identifiers(self): + with patch("vault_keychain.sys.platform", "linux"): + with self.assertRaises(KeychainError): + MacKeychainVaultKeys() + with self.assertRaises(KeychainError): + self.keys.create("../bad") + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/secure_sync/vault_keychain.py b/experiments/secure_sync/vault_keychain.py new file mode 100644 index 00000000..6d1c04ff --- /dev/null +++ b/experiments/secure_sync/vault_keychain.py @@ -0,0 +1,162 @@ +"""Isolated macOS Keychain proof for ClosedRoom secure sync. + +No file fallback, transport or implicit initialization. Injected test backends +MUST NOT be used in product code. Genuine macOS Keychain proof is pending. +""" +from __future__ import annotations + +import base64 +import binascii +import json +import secrets +import sys +from dataclasses import asdict +from typing import Protocol + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from vault_manifest import TrustedCheckpoint, verify_manifest + +SERVICE = "com.closedroom.app.secure-sync.v1" + + +class KeychainError(RuntimeError): + """No safe local secret or trusted checkpoint is available.""" + + +class _Backend(Protocol): + def get_password(self, service: str, username: str) -> str | None: ... + def set_password(self, service: str, username: str, password: str) -> None: ... + + +def _validate_id(vault_id: str) -> None: + if not isinstance(vault_id, str) or len(vault_id) != 32 or any(c not in "0123456789abcdef" for c in vault_id): + raise KeychainError("Invalid vault identifier") + + +class MacKeychainVaultKeys: + """Test-only interface until native Mac and process-lock qualification.""" + + def __init__(self, *, _test_backend: _Backend | None = None): + if _test_backend is not None: + self._backend = _test_backend + return + if sys.platform != "darwin": + raise KeychainError("macOS Keychain required: no fallback") + try: + import keyring + backend = keyring.get_keyring() + except Exception as exc: + raise KeychainError("macOS Keychain unavailable") from exc + if not type(backend).__module__.startswith("keyring.backends.macOS"): + raise KeychainError("Refusing non-macOS Keychain backend") + self._backend = backend + + def _get(self, account: str) -> str | None: + try: + return self._backend.get_password(SERVICE, account) + except Exception as exc: + raise KeychainError("Keychain read failed") from exc + + def _set(self, account: str, value: str) -> None: + try: + self._backend.set_password(SERVICE, account, value) + except Exception as exc: + raise KeychainError("Keychain write failed") from exc + if self._get(account) != value: + raise KeychainError("Keychain readback mismatch") + + def _create_secret(self, account: str, secret: bytes) -> None: + if self._get(account) is not None: + raise KeychainError("Keychain identity already exists") + self._set(account, base64.b64encode(secret).decode("ascii")) + + def _load_secret(self, account: str) -> bytes: + value = self._get(account) + if value is None: + raise KeychainError("Key missing: independent recovery required") + try: + result = base64.b64decode(value, validate=True) + except (ValueError, binascii.Error, TypeError) as exc: + raise KeychainError("Corrupt Keychain value") from exc + if len(result) != 32: + raise KeychainError("Invalid Keychain secret length") + return result + + def create(self, vault_id: str) -> bytes: + _validate_id(vault_id) + secret = secrets.token_bytes(32) + self._create_secret(vault_id + ":master", secret) + if not secrets.compare_digest(self.load(vault_id), secret): + raise KeychainError("Vault readback mismatch") + return secret + + def load(self, vault_id: str) -> bytes: + _validate_id(vault_id) + return self._load_secret(vault_id + ":master") + + def create_owner_signer(self, vault_id: str) -> Ed25519PrivateKey: + """Software signing identity kept in Keychain, NOT Secure Enclave.""" + _validate_id(vault_id) + signer = Ed25519PrivateKey.generate() + private = signer.private_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PrivateFormat.Raw, + encryption_algorithm=serialization.NoEncryption(), + ) + self._create_secret(vault_id + ":owner-signing", private) + if self.load_owner_signer(vault_id).public_key().public_bytes_raw() != signer.public_key().public_bytes_raw(): + raise KeychainError("Signing identity readback mismatch") + return signer + + def load_owner_signer(self, vault_id: str) -> Ed25519PrivateKey: + _validate_id(vault_id) + return Ed25519PrivateKey.from_private_bytes(self._load_secret(vault_id + ":owner-signing")) + + def pin_authenticated_owner(self, vault_id: str, public_key: bytes) -> None: + """Public key MUST come from owner or authenticated out-of-band pairing.""" + _validate_id(vault_id) + if not isinstance(public_key, bytes) or len(public_key) != 32: + raise KeychainError("Invalid pinned owner key") + account = vault_id + ":owner-pin" + value = base64.b64encode(public_key).decode("ascii") + existing = self._get(account) + if existing is not None: + if not secrets.compare_digest(existing, value): + raise KeychainError("Pinned owner key cannot be replaced") + return + self._set(account, value) + + def load_checkpoint(self, vault_id: str) -> TrustedCheckpoint | None: + _validate_id(vault_id) + raw = self._get(vault_id + ":checkpoint") + if raw is None: + return None + try: + data = json.loads(raw) + if not isinstance(data, dict) or set(data) != {"vault_id", "revision", "digest", "key_epoch"}: + raise ValueError("wrong schema") + value = TrustedCheckpoint(**data) + if (value.vault_id != vault_id or type(value.revision) is not int or value.revision < 0 + or type(value.key_epoch) is not int or value.key_epoch < 1 + or not isinstance(value.digest, str) or len(value.digest) != 64 + or any(c not in "0123456789abcdef" for c in value.digest)): + raise ValueError("invalid checkpoint") + return value + except (TypeError, ValueError) as exc: + raise KeychainError("Corrupt trusted checkpoint") from exc + + def accept_signed_head(self, vault_id: str, document: bytes) -> TrustedCheckpoint: + """One local writer only: production requires cross-process CAS/lock.""" + _validate_id(vault_id) + pinned = self._load_secret(vault_id + ":owner-pin") + previous = self.load_checkpoint(vault_id) + accepted = verify_manifest(document, pinned, previous) + if accepted.vault_id != vault_id: + raise KeychainError("Signed head belongs to another vault") + if accepted != previous: + self._set(vault_id + ":checkpoint", json.dumps(asdict(accepted), sort_keys=True)) + if self.load_checkpoint(vault_id) != accepted: + raise KeychainError("Checkpoint readback mismatch") + return accepted diff --git a/experiments/secure_sync/vault_manifest.py b/experiments/secure_sync/vault_manifest.py new file mode 100644 index 00000000..ba0dc24e --- /dev/null +++ b/experiments/secure_sync/vault_manifest.py @@ -0,0 +1,198 @@ +"""Offline authenticated vault-manifest proof; never reads or writes a network endpoint. + +The owner public key MUST be authenticated outside storage (pairing/recovery). +An independent trusted checkpoint detects rollbacks only after the client has +previously seen a newer head. A fresh device cannot establish freshness from +untrusted Drive data alone. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import json +import secrets +from dataclasses import dataclass +from typing import Any, Mapping + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey + +FORMAT = "closedroom.vault-manifest" +VERSION = 1 +MAX_DOCUMENT_BYTES = 1024 * 1024 +MAX_OBJECTS = 2048 +_HEADER_FIELDS = frozenset({"format", "version", "vault_id", "revision", "previous", "key_epoch", "objects"}) +_DOCUMENT_FIELDS = frozenset({"manifest", "signature"}) +_OBJECT_FIELDS = frozenset({"id", "sha256"}) + + +class ManifestError(ValueError): + """Invalid, untrusted, replayed, or conflicting signed vault state.""" + + +@dataclass(frozen=True) +class TrustedCheckpoint: + """Private and durable, never obtained from the same untrusted Drive head.""" + + vault_id: str + revision: int + digest: str + key_epoch: int + + +def generate_owner_signing_key() -> Ed25519PrivateKey: + """Caller must keep the private key out of Drive, logs and snapshots.""" + return Ed25519PrivateKey.generate() + + +def public_key_bytes(signing_key: Ed25519PrivateKey) -> bytes: + return signing_key.public_key().public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + + +def new_vault_id() -> str: + return secrets.token_hex(16) + + +def _canonical(value: Any) -> bytes: + try: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8") + except (TypeError, ValueError, OverflowError) as exc: + raise ManifestError("Invalid manifest encoding") from exc + + +def _reject_duplicates(items: list[tuple[str, Any]]) -> dict[str, Any]: + obj: dict[str, Any] = {} + for key, value in items: + if key in obj: + raise ManifestError("Duplicate manifest field") + obj[key] = value + return obj + + +def _hex(value: Any, length: int) -> bool: + return isinstance(value, str) and len(value) == length and all(x in "0123456789abcdef" for x in value) + + +def _validate(manifest: Any) -> None: + if not isinstance(manifest, dict) or set(manifest) != _HEADER_FIELDS: + raise ManifestError("Invalid manifest schema") + if manifest["format"] != FORMAT or type(manifest["version"]) is not int or manifest["version"] != VERSION: + raise ManifestError("Unsupported manifest version") + if not _hex(manifest["vault_id"], 32): + raise ManifestError("Invalid vault id") + revision = manifest["revision"] + epoch = manifest["key_epoch"] + if type(revision) is not int or revision < 0 or type(epoch) is not int or epoch < 1: + raise ManifestError("Invalid revision or key epoch") + if (revision == 0 and manifest["previous"] is not None) or (revision > 0 and not _hex(manifest["previous"], 64)): + raise ManifestError("Invalid manifest chain pointer") + objects = manifest["objects"] + if not isinstance(objects, list) or len(objects) > MAX_OBJECTS: + raise ManifestError("Invalid object list") + seen = set() + for item in objects: + if not isinstance(item, dict) or set(item) != _OBJECT_FIELDS: + raise ManifestError("Invalid object reference") + if not _hex(item["id"], 32) or not _hex(item["sha256"], 64) or item["id"] in seen: + raise ManifestError("Invalid or duplicate object reference") + seen.add(item["id"]) + + +def new_manifest(*, vault_id: str, revision: int, previous: str | None, + key_epoch: int = 1, objects: list[dict[str, str]] | None = None) -> dict[str, Any]: + """Construct explicit, versioned content; no filesystem or network I/O.""" + manifest = { + "format": FORMAT, "version": VERSION, "vault_id": vault_id, + "revision": revision, "previous": previous, "key_epoch": key_epoch, + "objects": list(objects or []), + } + _validate(manifest) + return manifest + + +def sign_manifest(manifest: Mapping[str, Any], owner_signing_key: Ed25519PrivateKey) -> bytes: + """Canonical Ed25519 signature; caller must enforce authorization to sign.""" + if not isinstance(owner_signing_key, Ed25519PrivateKey): + raise ManifestError("Owner signing key required") + data = dict(manifest) + _validate(data) + payload = _canonical(data) + if len(payload) > MAX_DOCUMENT_BYTES - 300: + raise ManifestError("Manifest too large") + signature = owner_signing_key.sign(payload) + document = _canonical({"manifest": data, "signature": base64.b64encode(signature).decode("ascii")}) + if len(document) > MAX_DOCUMENT_BYTES: + raise ManifestError("Signed manifest too large") + return document + + +def verify_manifest(document: bytes, pinned_owner_public_key: bytes, + checkpoint: TrustedCheckpoint | None = None) -> TrustedCheckpoint: + """Check signature, structure, and contiguous advancement from trusted state. + + Same exact signed head is an idempotent no-op; an older head, alternate + same-revision head, skipped revision or changed epoch without a chain is + rejected. No provider-freshness claim on first-ever enrollment. + """ + if not isinstance(document, bytes) or len(document) > MAX_DOCUMENT_BYTES: + raise ManifestError("Invalid manifest document size") + if not isinstance(pinned_owner_public_key, bytes) or len(pinned_owner_public_key) != 32: + raise ManifestError("Authenticated owner public key required") + try: + raw = json.loads(document.decode("utf-8"), object_pairs_hook=_reject_duplicates, + parse_constant=lambda _: (_ for _ in ()).throw(ManifestError("Invalid JSON constant"))) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ManifestError("Invalid manifest document") from exc + if not isinstance(raw, dict) or set(raw) != _DOCUMENT_FIELDS: + raise ManifestError("Invalid signed manifest envelope") + manifest = raw["manifest"] + _validate(manifest) + signature_b64 = raw["signature"] + if not isinstance(signature_b64, str): + raise ManifestError("Invalid manifest signature") + try: + signature = base64.b64decode(signature_b64, validate=True) + except (ValueError, binascii.Error) as exc: + raise ManifestError("Invalid manifest signature") from exc + if len(signature) != 64: + raise ManifestError("Invalid manifest signature length") + try: + Ed25519PublicKey.from_public_bytes(pinned_owner_public_key).verify(signature, _canonical(manifest)) + except (InvalidSignature, ValueError) as exc: + raise ManifestError("Manifest signature verification failed") from exc + digest = hashlib.sha256(_canonical(manifest)).hexdigest() + proposed = TrustedCheckpoint(manifest["vault_id"], manifest["revision"], digest, manifest["key_epoch"]) + if checkpoint is None: + if proposed.revision != 0 or manifest["previous"] is not None: + raise ManifestError("Genesis trust anchor required before later manifests") + return proposed + if checkpoint.vault_id != proposed.vault_id: + raise ManifestError("Wrong vault") + if checkpoint == proposed: + return checkpoint + if proposed.revision != checkpoint.revision + 1 or manifest["previous"] != checkpoint.digest: + raise ManifestError("Rollback, skipped revision or forked chain") + if proposed.key_epoch < checkpoint.key_epoch or proposed.key_epoch > checkpoint.key_epoch + 1: + raise ManifestError("Invalid key rotation sequence") + return proposed + + +def object_reference(object_id: str, encrypted_blob: bytes) -> dict[str, str]: + """The blob must already be encrypted and authenticated by the snapshot owner.""" + if not _hex(object_id, 32) or not isinstance(encrypted_blob, bytes): + raise ManifestError("Invalid encrypted object identity or bytes") + return {"id": object_id, "sha256": hashlib.sha256(encrypted_blob).hexdigest()} + + +def verify_object(reference: Mapping[str, Any], encrypted_blob: bytes) -> None: + """Detect cloud blob substitution before decrypting in the snapshot owner.""" + if not isinstance(reference, Mapping) or set(reference) != _OBJECT_FIELDS or not _hex(reference["id"], 32) or not _hex(reference["sha256"], 64): + raise ManifestError("Invalid encrypted object reference") + if not isinstance(encrypted_blob, bytes) or hashlib.sha256(encrypted_blob).hexdigest() != reference["sha256"]: + raise ManifestError("Encrypted object hash mismatch") From 98ff49af67201c6c430f78496725893a4bad22fb Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 10:26:01 +0100 Subject: [PATCH 03/24] docs(sync): distinguish iteration governance from unrun crypto gates --- docs/workstreams/secure-sync-google-drive.md | 6 +++--- experiments/secure_sync/README.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 378325cd..7e9c6370 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -1,7 +1,7 @@ # Secure multi-device transcript sync — Google Drive pilot Status: ACTIVE / isolated security-format experiment on `feature/google-drive-secure-sync-foundation` -Target: `dev`. Product: PRODUCT_FEATURE; delivery: ITERATION; validation: STRONG for security/data lifecycle; execution: AGENT_LOCAL prototype, REMOTE_AUTOMATED integration, REAL_ENVIRONMENT for Keychain/OAuth and independent second Mac. No release claim. +Target: `dev`. Product: PRODUCT_FEATURE; delivery: ITERATION; validation: FULL (repository selector: unknown executable `experiments/` path; risk floor STRONG for crypto/data lifecycle); execution: AGENT_LOCAL prototype, REMOTE_AUTOMATED integration, REAL_ENVIRONMENT for Keychain/OAuth and independent second Mac. No release claim. ## User and outcome @@ -56,10 +56,10 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - New `experiments/secure_sync/vault_keychain.py`: explicit opt-in Keychain-backed prototype for a random vault key and **separate Ed25519 software signing identity**, authenticated owner-public-key pin and locally retained trusted checkpoint. Missing/corrupted keys, unsafe backends, pin substitution and failed readback fail closed. Mac Keychain backend and Security.framework entitlement behavior are **NOT yet tested on a real macOS app**. This is not a hardware-bound Secure Enclave Ed25519 key. - New synthetic `test_vault_foundation.py` exercises signing/tampering/rollback/forks, object hashes, key overwrite prevention, restart persistence through a fake backend and missing/corrupt state. Cross-process Keychain atomicity, secure pairing, user recovery codes, signing-key rotation, true restore and real Mac behavior are still unimplemented. - **Fresh-device limitation**: an authenticated key + a genesis manifest does NOT prove remote freshness. Pairing/recovery must independently convey an authenticated latest trusted checkpoint. A provider may suppress all updates or delete objects, and local checkpoints can be lost on OS restore. Design recovery, independent backup and a single authoritative local writer before enabling Drive. -- This slice is isolated; no OAuth/network, no automatic upload, no app wiring, no dependency/lockfile modification, no migration, no local eviction, no change to active storage mode. Do not present this as sync-ready or Keychain-qualified. +- This slice is isolated; no OAuth/network, no automatic upload, no app wiring, no dependency/lockfile modification, no migration, no local eviction, no change to active storage mode. The signer is a software Ed25519 key stored in Keychain, not a Secure Enclave private key. Do not present this as sync-ready or Keychain-qualified. ### Current checkpoint - Baseline checked: `dev` `de0d1809e5f33c6dcc9a43895d81d336c4f2ba62`; standalone GCS **preparation-only** in dev, no automatic cloud runtime. GCS experimental encrypted cold backup is **not** per-meeting sync. - This branch touches only an isolated `experiments/secure_sync` proof and this plan; the Keychain/manifest components are experiments, not canonical runtime services. It does not modify the app/pyproject/lockfile or introduce a network caller. Six synthetic tests passed in a separate Python environment with `cryptography 46.0.4`; this is **not** installed-app or exact-HEAD CI evidence. -- Next discriminating action: run the exact new tests under the repository's targeted validation, verify native macOS Keychain behavior and the Keychain checkpoint across real restarts, and establish trusted second-device head transport. Then prove an encrypted file transfer between two independent local instances before OAuth or real user data. Do not enable provider until security tests and recovery evidence exist. +- Validation at `d9c2cfdd`: GitHub `Repository health` and draft-iteration `Remote preflight / FULL` source/governance checks PASS; the source-test job was SKIPPED by the repository's iteration policy. New exact-HEAD Python crypto tests are NOT YET PROVEN PASS, nor macOS Keychain and packaged behavior. Next discriminating action: run the exact new tests under the repository's targeted validation, verify native macOS Keychain behavior and the Keychain checkpoint across real restarts, and establish trusted second-device head transport. Then prove an encrypted file transfer between two independent local instances before OAuth or real user data. Do not enable provider until security tests and recovery evidence exist. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index 7f91192a..5b877c67 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -5,7 +5,7 @@ Isolated, offline-only format experiment. No Google OAuth, network traffic, uplo Run with the dependency available: ```sh -python3 -m unittest discover -s experiments/secure_sync -v +uv run --no-project --with cryptography --with keyring -- python -m unittest discover -s experiments/secure_sync -p 'test_*.py' -v ``` Additional isolated components: From c14c8e16c1b6ee10ef189f4df3063ee3be180ff6 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 10:36:55 +0100 Subject: [PATCH 04/24] test(sync): require encrypted vault and real Keychain smoke on Mac lane --- .github/ci/local-test.sh | 9 ++ docs/workstreams/secure-sync-google-drive.md | 7 ++ experiments/secure_sync/README.md | 10 ++ .../secure_sync/macos_keychain_probe.py | 107 ++++++++++++++++++ 4 files changed, 133 insertions(+) create mode 100644 experiments/secure_sync/macos_keychain_probe.py diff --git a/.github/ci/local-test.sh b/.github/ci/local-test.sh index e03cc2d1..15eef935 100644 --- a/.github/ci/local-test.sh +++ b/.github/ci/local-test.sh @@ -28,6 +28,15 @@ uv sync --all-extras --frozen --python 3.12 pnpm exec tsc --noEmit ) UV_CACHE_DIR=.cache/uv uv run --frozen --python 3.12 python -m unittest discover -s test -v + +# Isolated security spike, synthetic-only. These tests are deliberately +# mandatory on the Mac runner: a green draft PR governance check does not run +# the experiments directory. Do not upload private data or install globally. +SECURE_SYNC_PY=(uv run --no-project --python 3.12 --with 'cryptography>=46,<47' --with 'keyring>=25,<26' -- python) +UV_CACHE_DIR=.cache/uv "${SECURE_SYNC_PY[@]}" -m unittest discover -s experiments/secure_sync -p 'test_*.py' -v +# Requires a real, unlocked login Keychain. Fails closed and only creates +# randomized synthetic entries under ClosedRoom's dedicated test identity. +UV_CACHE_DIR=.cache/uv "${SECURE_SYNC_PY[@]}" experiments/secure_sync/macos_keychain_probe.py source .github/ci/setup-browser.sh E2E_SOURCE_REVISION="$(git rev-parse HEAD)" node scripts/browser_meeting_ui_e2e.mjs echo "ClosedRoom Mac source and browser FULL_MEDIA checks passed" diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 7e9c6370..af2eda2e 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -58,6 +58,13 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - **Fresh-device limitation**: an authenticated key + a genesis manifest does NOT prove remote freshness. Pairing/recovery must independently convey an authenticated latest trusted checkpoint. A provider may suppress all updates or delete objects, and local checkpoints can be lost on OS restore. Design recovery, independent backup and a single authoritative local writer before enabling Drive. - This slice is isolated; no OAuth/network, no automatic upload, no app wiring, no dependency/lockfile modification, no migration, no local eviction, no change to active storage mode. The signer is a software Ed25519 key stored in Keychain, not a Secure Enclave private key. Do not present this as sync-ready or Keychain-qualified. +### Real-Mac validation request (2026-11-19) + +- `.github/ci/local-test.sh` runs the isolated crypto unit tests explicitly under a transient `uv --no-project` environment (`cryptography>=46,<47`, `keyring>=25,<26`), then invokes a real Keychain smoke. The product build/lockfile/runtime remain unmodified. +- `experiments/secure_sync/macos_keychain_probe.py` uses a new random vault ID, a real macOS Keychain backend, an independent Python child process and authenticated challenge to prove both the AES vault key and Ed25519 owner identity can be read after process restart. It checks checkpoint persistence and deletes test-only Keychain entries afterward, failing if cleanup is incomplete. +- The test proves only the runner's Keychain session, NOT packaged-app code signing/entitlements, screen prompts, external OAuth, independent Mac recovery or deployed multi-device sync. No meeting data or cloud credentials are used. +- The central Mac request is issued only for a reviewed exact source commit by updating the versioned request in private `daniele21/local-runner-infra`; actual `local-ci/mac` status, not dispatch accepted, is the gate. + ### Current checkpoint - Baseline checked: `dev` `de0d1809e5f33c6dcc9a43895d81d336c4f2ba62`; standalone GCS **preparation-only** in dev, no automatic cloud runtime. GCS experimental encrypted cold backup is **not** per-meeting sync. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index 5b877c67..29195d9a 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -20,3 +20,13 @@ The 32-byte secret is **test-only** in this experiment. Do not persist it in pla The format intentionally authenticates header fields and ciphertext using HKDF-SHA256 + AES-256-GCM. It does **not** establish remote freshness, authorization of devices, revocation, concurrency control, recovery, verified upload/restore or a production export/import path. In particular a malicious/compromised storage provider may delete objects or replay an older *valid* ciphertext; those protections need a trusted authenticated manifest/head checkpoint and independent backup. Next step: review and adapt this format in the existing canonical TranscriptionStore/RecordingStore projection owners; add correctly locked crypto dependency, consent and Keychain management; add a read-only separate device cache and a Google Drive appDataFolder adapter behind explicit opt-in. + +## Source-owned real-Mac gate + +On the shared Mac validation lane, `.github/ci/local-test.sh` explicitly runs the `test_*.py` files with transient isolated Python dependencies, then runs: + +```sh +uv run --no-project --python 3.12 --with 'cryptography>=46,<47' --with 'keyring>=25,<26' -- python experiments/secure_sync/macos_keychain_probe.py +``` + +The probe uses **synthetic temporary records only**, a second process and cleanup verification. Never use actual user credentials/vaults. Mac runner PASS is not installed-app Keychain/TCC proof. diff --git a/experiments/secure_sync/macos_keychain_probe.py b/experiments/secure_sync/macos_keychain_probe.py new file mode 100644 index 00000000..798d5252 --- /dev/null +++ b/experiments/secure_sync/macos_keychain_probe.py @@ -0,0 +1,107 @@ +"""Opt-in real macOS Keychain smoke on a trusted, nonisolated Mac runner. + +Test data only. This must never receive a real user vault ID, transcript, +Google credentials or recovery material. Exits nonzero if backend, second +process re-read or cleanup is not proven. No content is uploaded or logged. +""" +from __future__ import annotations + +import base64 +import json +import secrets +import subprocess +import sys + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from vault_keychain import MacKeychainVaultKeys, SERVICE +from vault_manifest import new_manifest, sign_manifest + +_CLEANUP_SUFFIXES = (":checkpoint", ":owner-pin", ":owner-signing", ":master") +_MESSAGE = b"closedroom-synthetic-keychain-smoke/v1" + + +def _child(vault_id: str) -> int: + # Child has no private bytes in argv/env; reads Keychain directly. + payload = json.loads(sys.stdin.buffer.read(16384)) + vault = MacKeychainVaultKeys() + nonce = base64.b64decode(payload["nonce"], validate=True) + ciphertext = base64.b64decode(payload["ciphertext"], validate=True) + if AESGCM(vault.load(vault_id)).decrypt(nonce, ciphertext, b"closedroom-smoke") != _MESSAGE: + raise RuntimeError("Second process could not retrieve the vault key") + signer = vault.load_owner_signer(vault_id) + checkpoint = vault.load_checkpoint(vault_id) + if checkpoint is None or checkpoint.revision != 0: + raise RuntimeError("Second process did not recover signed checkpoint") + signature = signer.sign(base64.b64decode(payload["challenge"], validate=True)) + sys.stdout.write(base64.b64encode(signature).decode("ascii")) + return 0 + + +def _parent() -> int: + if sys.platform != "darwin": + raise RuntimeError("Real macOS Keychain required; no non-Mac fallback") + vault_id = secrets.token_hex(16) + vault = MacKeychainVaultKeys() # Must enforce real macOS Keychain. + backend = vault._backend # Only probe cleanup, not a production interface. + accounts = [vault_id + suffix for suffix in _CLEANUP_SUFFIXES] + safe_to_cleanup = False + primary_error: BaseException | None = None + cleanup_errors: list[str] = [] + try: + # Never overwrite existing entries even if an astronomically unlikely + # collision occurs. Validate all accounts first. + if any(backend.get_password(SERVICE, account) is not None for account in accounts): + raise RuntimeError("Random synthetic Keychain identity collision") + safe_to_cleanup = True + key = vault.create(vault_id) + signer = vault.create_owner_signer(vault_id) + vault.pin_authenticated_owner(vault_id, signer.public_key().public_bytes_raw()) + genesis = sign_manifest(new_manifest( + vault_id=vault_id, revision=0, previous=None, + ), signer) + vault.accept_signed_head(vault_id, genesis) + nonce = secrets.token_bytes(12) + challenge = secrets.token_bytes(32) + request = json.dumps({ + "nonce": base64.b64encode(nonce).decode("ascii"), + "ciphertext": base64.b64encode( + AESGCM(key).encrypt(nonce, _MESSAGE, b"closedroom-smoke"), + ).decode("ascii"), + "challenge": base64.b64encode(challenge).decode("ascii"), + }) + completed = subprocess.run( + [sys.executable, __file__, "--child", vault_id], + input=request, text=True, capture_output=True, timeout=20, check=True, + ) + signature = base64.b64decode(completed.stdout.strip(), validate=True) + try: + signer.public_key().verify(signature, challenge) + except InvalidSignature as exc: + raise RuntimeError("Second process failed to prove signing-key access") from exc + except BaseException as exc: + primary_error = exc + finally: + for account in (accounts if safe_to_cleanup else []): + try: + if backend.get_password(SERVICE, account) is not None: + backend.delete_password(SERVICE, account) + if backend.get_password(SERVICE, account) is not None: + cleanup_errors.append(account.rsplit(":", 1)[-1]) + except Exception: + cleanup_errors.append(account.rsplit(":", 1)[-1]) + if cleanup_errors: + raise RuntimeError("Synthetic Keychain cleanup failed: " + ", ".join(cleanup_errors)) from primary_error + if primary_error is not None: + raise RuntimeError("Real Keychain smoke failed; no secrets were printed") from primary_error + print("REAL_MAC_KEYCHAIN_SMOKE=PASS second_process=true cleanup=true synthetic_only=true") + return 0 + + +if __name__ == "__main__": + if len(sys.argv) == 3 and sys.argv[1] == "--child": + raise SystemExit(_child(sys.argv[2])) + if len(sys.argv) != 1: + raise SystemExit("Unexpected arguments") + raise SystemExit(_parent()) From b4cfd627bc33bd237dd3c9cef30392171e0efd98 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 10:38:38 +0100 Subject: [PATCH 05/24] docs(sync): respect active workstream context budget without weakening gates --- docs/workstreams/secure-sync-google-drive.md | 21 ++++++-------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index af2eda2e..d793d8d5 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -52,21 +52,12 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model ### Offline proof extension (2026-11-19) -- New `experiments/secure_sync/vault_manifest.py`: Ed25519 owner-signed canonical manifests with stable opaque vault IDs, digest-bound ciphertext references, contiguous revision chain and monotonic epoch. Verification rejects wrong signer, tampering, missing intermediary revision, older head and same-revision fork against an independently trusted checkpoint. An unchanged authenticated head is an idempotent no-op. -- New `experiments/secure_sync/vault_keychain.py`: explicit opt-in Keychain-backed prototype for a random vault key and **separate Ed25519 software signing identity**, authenticated owner-public-key pin and locally retained trusted checkpoint. Missing/corrupted keys, unsafe backends, pin substitution and failed readback fail closed. Mac Keychain backend and Security.framework entitlement behavior are **NOT yet tested on a real macOS app**. This is not a hardware-bound Secure Enclave Ed25519 key. -- New synthetic `test_vault_foundation.py` exercises signing/tampering/rollback/forks, object hashes, key overwrite prevention, restart persistence through a fake backend and missing/corrupt state. Cross-process Keychain atomicity, secure pairing, user recovery codes, signing-key rotation, true restore and real Mac behavior are still unimplemented. -- **Fresh-device limitation**: an authenticated key + a genesis manifest does NOT prove remote freshness. Pairing/recovery must independently convey an authenticated latest trusted checkpoint. A provider may suppress all updates or delete objects, and local checkpoints can be lost on OS restore. Design recovery, independent backup and a single authoritative local writer before enabling Drive. -- This slice is isolated; no OAuth/network, no automatic upload, no app wiring, no dependency/lockfile modification, no migration, no local eviction, no change to active storage mode. The signer is a software Ed25519 key stored in Keychain, not a Secure Enclave private key. Do not present this as sync-ready or Keychain-qualified. - -### Real-Mac validation request (2026-11-19) - -- `.github/ci/local-test.sh` runs the isolated crypto unit tests explicitly under a transient `uv --no-project` environment (`cryptography>=46,<47`, `keyring>=25,<26`), then invokes a real Keychain smoke. The product build/lockfile/runtime remain unmodified. -- `experiments/secure_sync/macos_keychain_probe.py` uses a new random vault ID, a real macOS Keychain backend, an independent Python child process and authenticated challenge to prove both the AES vault key and Ed25519 owner identity can be read after process restart. It checks checkpoint persistence and deletes test-only Keychain entries afterward, failing if cleanup is incomplete. -- The test proves only the runner's Keychain session, NOT packaged-app code signing/entitlements, screen prompts, external OAuth, independent Mac recovery or deployed multi-device sync. No meeting data or cloud credentials are used. -- The central Mac request is issued only for a reviewed exact source commit by updating the versioned request in private `daniele21/local-runner-infra`; actual `local-ci/mac` status, not dispatch accepted, is the gate. +- Isolated `vault_manifest.py`: Ed25519 owner-signed chain, opaque ciphertext references, contiguous revisions/epochs, pinned owner, fork and replay detection against a trusted checkpoint. A fresh device cannot prove remote freshness from Drive alone. +- Isolated `vault_keychain.py`: fail-closed macOS Keychain-only prototype storing independent AES vault and **software** Ed25519 signing secrets, authenticated owner pin and checkpoint. Not hardware Secure Enclave. Synthetic unit tests cover restart, tampering, bad signer, key replacement/corruption, failures and replay. +- Missing: genuine recovery materials, cross-process CAS, authenticated pairing, revocation/rotation, second-device trust anchor and verified backup. No OAuth, sync, migration, upload, local eviction, app integration or production cryptographic dependencies yet. ### Current checkpoint -- Baseline checked: `dev` `de0d1809e5f33c6dcc9a43895d81d336c4f2ba62`; standalone GCS **preparation-only** in dev, no automatic cloud runtime. GCS experimental encrypted cold backup is **not** per-meeting sync. -- This branch touches only an isolated `experiments/secure_sync` proof and this plan; the Keychain/manifest components are experiments, not canonical runtime services. It does not modify the app/pyproject/lockfile or introduce a network caller. Six synthetic tests passed in a separate Python environment with `cryptography 46.0.4`; this is **not** installed-app or exact-HEAD CI evidence. -- Validation at `d9c2cfdd`: GitHub `Repository health` and draft-iteration `Remote preflight / FULL` source/governance checks PASS; the source-test job was SKIPPED by the repository's iteration policy. New exact-HEAD Python crypto tests are NOT YET PROVEN PASS, nor macOS Keychain and packaged behavior. Next discriminating action: run the exact new tests under the repository's targeted validation, verify native macOS Keychain behavior and the Keychain checkpoint across real restarts, and establish trusted second-device head transport. Then prove an encrypted file transfer between two independent local instances before OAuth or real user data. Do not enable provider until security tests and recovery evidence exist. +- Source branch based on `dev@de0d1809`; GCS remains configuration-only. No active sync service. +- Head before real Mac request: `c14c8e16`; PR #225 draft. `.github/ci/local-test.sh` now calls the isolated crypto suite and synthetic real-Keychain smoke via a transient Python dependency environment. The central Mac run for that SHA is tracked under `local-ci/mac`. +- At this stage, Mac source checks, packaged-app Keychain behavior, OAuth and second-device recovery must not be reported PASS without separate evidence. The next action is to evaluate exact Mac test logs, fix diagnosed failures without weakening tests, then rerun on new exact HEAD. From 159afbfc74e0abc40ae6c004248451a451075ce2 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 10:41:35 +0100 Subject: [PATCH 06/24] docs(sync): record Mac crypto PASS and Keychain session blocker with exact evidence --- docs/workstreams/secure-sync-google-drive.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index d793d8d5..98934568 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -56,6 +56,13 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Isolated `vault_keychain.py`: fail-closed macOS Keychain-only prototype storing independent AES vault and **software** Ed25519 signing secrets, authenticated owner pin and checkpoint. Not hardware Secure Enclave. Synthetic unit tests cover restart, tampering, bad signer, key replacement/corruption, failures and replay. - Missing: genuine recovery materials, cross-process CAS, authenticated pairing, revocation/rotation, second-device trust anchor and verified backup. No OAuth, sync, migration, upload, local eviction, app integration or production cryptographic dependencies yet. +### Mac result and failure classification — 2026-11-19 + +- Source SHA `c14c8e16` ran on the central Mac runner ([run 44498140756](https://github.com/daniele21/local-runner-infra/actions/runs/44498140756)). **977 repository tests PASS; 17 isolated crypto/manifest/fake-Keychain tests PASS.** +- **Real Keychain smoke FAIL** before storing the first synthetic secret. `keyring.backends.macOS.api.Error (-25308)` means `errSecInteractionNotAllowed`: current runner security context cannot permit the operation. Classify as an **environment/session authority** blocker pending an interactive user-login Keychain proof; do not relabel it a cryptographic regression or success. +- Source commit `b4cfd627` fixes the independent repository-doc budget failure (3,125 > 3,000 estimated tokens); hosted governance checks now PASS. It has **not** passed exact-HEAD Mac validation; the earlier runner failure remains blocking for the Keychain gate. +- Next discriminating action: verify Keychain operations in a trusted logged-in GUI-user/signed-app execution context, without exposing an unlock password to CI or silently substituting a file-based secret store. Preserve failure on inaccessible Keychain. Run again against exact candidate when correct environment exists. + ### Current checkpoint - Source branch based on `dev@de0d1809`; GCS remains configuration-only. No active sync service. From 3e78909a07fd92bec6a8b2745d4bc0cb2648e053 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 12:01:28 +0100 Subject: [PATCH 07/24] docs(sync): record repeat Mac Keychain background-session failure after GUI unlock --- docs/workstreams/secure-sync-google-drive.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 98934568..9383c081 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -61,6 +61,7 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Source SHA `c14c8e16` ran on the central Mac runner ([run 44498140756](https://github.com/daniele21/local-runner-infra/actions/runs/44498140756)). **977 repository tests PASS; 17 isolated crypto/manifest/fake-Keychain tests PASS.** - **Real Keychain smoke FAIL** before storing the first synthetic secret. `keyring.backends.macOS.api.Error (-25308)` means `errSecInteractionNotAllowed`: current runner security context cannot permit the operation. Classify as an **environment/session authority** blocker pending an interactive user-login Keychain proof; do not relabel it a cryptographic regression or success. - Source commit `b4cfd627` fixes the independent repository-doc budget failure (3,125 > 3,000 estimated tokens); hosted governance checks now PASS. It has **not** passed exact-HEAD Mac validation; the earlier runner failure remains blocking for the Keychain gate. +- **Repeat after user unlocked login Keychain**: source `159afbfc74e0abc40ae6c004248451a451075ce2`, central [run 44510352786](https://github.com/daniele21/local-runner-infra/actions/runs/44510352786) on `local-mac-mini-3` (`MacminiiDaniele`). Main suite 977 PASS, crypto 17 PASS; real Keychain write still FAIL `errSecInteractionNotAllowed (-25308)`; `local-ci/mac=failure`. Earlier run used `local-mac-mini-4` on the same machine. This falsifies the hypothesis that unlocking login Keychain alone would resolve runner access. Next action requires a separate GUI-user/signed-app or explicitly authorized launch-session proof, not retrying the same background runner unchanged. Real-environment gate remains blocked. - Next discriminating action: verify Keychain operations in a trusted logged-in GUI-user/signed-app execution context, without exposing an unlock password to CI or silently substituting a file-based secret store. Preserve failure on inaccessible Keychain. Run again against exact candidate when correct environment exists. ### Current checkpoint From 390cfd1575539ca336cd47ba95972b581e48a111 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 15:24:46 +0100 Subject: [PATCH 08/24] docs(sync): record GUI-session synthetic Keychain success and remaining signed-app boundary --- docs/workstreams/secure-sync-google-drive.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 9383c081..2351bc8c 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -62,10 +62,10 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - **Real Keychain smoke FAIL** before storing the first synthetic secret. `keyring.backends.macOS.api.Error (-25308)` means `errSecInteractionNotAllowed`: current runner security context cannot permit the operation. Classify as an **environment/session authority** blocker pending an interactive user-login Keychain proof; do not relabel it a cryptographic regression or success. - Source commit `b4cfd627` fixes the independent repository-doc budget failure (3,125 > 3,000 estimated tokens); hosted governance checks now PASS. It has **not** passed exact-HEAD Mac validation; the earlier runner failure remains blocking for the Keychain gate. - **Repeat after user unlocked login Keychain**: source `159afbfc74e0abc40ae6c004248451a451075ce2`, central [run 44510352786](https://github.com/daniele21/local-runner-infra/actions/runs/44510352786) on `local-mac-mini-3` (`MacminiiDaniele`). Main suite 977 PASS, crypto 17 PASS; real Keychain write still FAIL `errSecInteractionNotAllowed (-25308)`; `local-ci/mac=failure`. Earlier run used `local-mac-mini-4` on the same machine. This falsifies the hypothesis that unlocking login Keychain alone would resolve runner access. Next action requires a separate GUI-user/signed-app or explicitly authorized launch-session proof, not retrying the same background runner unchanged. Real-environment gate remains blocked. -- Next discriminating action: verify Keychain operations in a trusted logged-in GUI-user/signed-app execution context, without exposing an unlock password to CI or silently substituting a file-based secret store. Preserve failure on inaccessible Keychain. Run again against exact candidate when correct environment exists. +- **User-reported GUI-session test PASS (2026-11-19):** from macOS Terminal in `~/Projects/local-asr-server`, branch `feature/google-drive-secure-sync-foundation`, running `experiments/secure_sync/macos_keychain_probe.py` returned `REAL_MAC_KEYCHAIN_SMOKE=PASS second_process=true cleanup=true synthetic_only=true`. This establishes a real local-login Keychain path for synthetic keys and separate-process readback; the local Git SHA was not supplied, so do **not** claim exact-head source proof. It does not validate signed/packaged app entitlement behavior or two-Mac recovery. Background Mac CI remains FAIL by design; do not bypass Keychain with insecure storage. ### Current checkpoint - Source branch based on `dev@de0d1809`; GCS remains configuration-only. No active sync service. - Head before real Mac request: `c14c8e16`; PR #225 draft. `.github/ci/local-test.sh` now calls the isolated crypto suite and synthetic real-Keychain smoke via a transient Python dependency environment. The central Mac run for that SHA is tracked under `local-ci/mac`. -- At this stage, Mac source checks, packaged-app Keychain behavior, OAuth and second-device recovery must not be reported PASS without separate evidence. The next action is to evaluate exact Mac test logs, fix diagnosed failures without weakening tests, then rerun on new exact HEAD. +- At this stage, the user-reported interactive Terminal smoke passed, while central Mac CI Keychain remains FAIL. Next: qualify Keychain from the real installed/signed app and prove independently recoverable trust, pairing and device revocation before any Drive transfer. OAuth and multi-device sync remain disabled. From 25fb5e52a13e7540e77c1f5ecc765b7246fb0d5b Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 16:04:59 +0100 Subject: [PATCH 09/24] test(sync): add native packaged-app Keychain identity probe with synthetic cleanup --- ClosedRoom.spec | 2 + docs/workstreams/secure-sync-google-drive.md | 5 +- experiments/secure_sync/README.md | 29 +++ scripts/probe_packaged_keychain.py | 127 +++++++++++++ .../bundled_module_dispatch.py | 6 + src/local_asr_server/macos_keychain_native.py | 175 ++++++++++++++++++ src/local_asr_server/macos_keychain_probe.py | 106 +++++++++++ test/test_secure_sync_packaged_keychain.py | 167 +++++++++++++++++ 8 files changed, 614 insertions(+), 3 deletions(-) create mode 100644 scripts/probe_packaged_keychain.py create mode 100644 src/local_asr_server/macos_keychain_native.py create mode 100644 src/local_asr_server/macos_keychain_probe.py create mode 100644 test/test_secure_sync_packaged_keychain.py diff --git a/ClosedRoom.spec b/ClosedRoom.spec index e56d2f72..c73fd5a2 100644 --- a/ClosedRoom.spec +++ b/ClosedRoom.spec @@ -176,6 +176,8 @@ hidden_imports = [ "local_asr_server.runtime.service_manager", "korgis_sdk", # opt-in SDK is bundled; legacy analysis remains the default "local_asr_server.bundled_module_dispatch", + "local_asr_server.macos_keychain_native", + "local_asr_server.macos_keychain_probe", "local_asr_server.services", "local_asr_server.services.analysis_service", "local_asr_server.services.transcription_service", diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 2351bc8c..2d6f714c 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -58,8 +58,7 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model ### Mac result and failure classification — 2026-11-19 -- Source SHA `c14c8e16` ran on the central Mac runner ([run 44498140756](https://github.com/daniele21/local-runner-infra/actions/runs/44498140756)). **977 repository tests PASS; 17 isolated crypto/manifest/fake-Keychain tests PASS.** -- **Real Keychain smoke FAIL** before storing the first synthetic secret. `keyring.backends.macOS.api.Error (-25308)` means `errSecInteractionNotAllowed`: current runner security context cannot permit the operation. Classify as an **environment/session authority** blocker pending an interactive user-login Keychain proof; do not relabel it a cryptographic regression or success. +- Mac [run 44498140756](https://github.com/daniele21/local-runner-infra/actions/runs/44498140756), SHA `c14c8e16`: **977 core tests PASS; 17 crypto tests PASS**. Real `keyring` Keychain smoke FAIL on write with `errSecInteractionNotAllowed (-25308)`: runner session authority, not cryptography. - Source commit `b4cfd627` fixes the independent repository-doc budget failure (3,125 > 3,000 estimated tokens); hosted governance checks now PASS. It has **not** passed exact-HEAD Mac validation; the earlier runner failure remains blocking for the Keychain gate. - **Repeat after user unlocked login Keychain**: source `159afbfc74e0abc40ae6c004248451a451075ce2`, central [run 44510352786](https://github.com/daniele21/local-runner-infra/actions/runs/44510352786) on `local-mac-mini-3` (`MacminiiDaniele`). Main suite 977 PASS, crypto 17 PASS; real Keychain write still FAIL `errSecInteractionNotAllowed (-25308)`; `local-ci/mac=failure`. Earlier run used `local-mac-mini-4` on the same machine. This falsifies the hypothesis that unlocking login Keychain alone would resolve runner access. Next action requires a separate GUI-user/signed-app or explicitly authorized launch-session proof, not retrying the same background runner unchanged. Real-environment gate remains blocked. - **User-reported GUI-session test PASS (2026-11-19):** from macOS Terminal in `~/Projects/local-asr-server`, branch `feature/google-drive-secure-sync-foundation`, running `experiments/secure_sync/macos_keychain_probe.py` returned `REAL_MAC_KEYCHAIN_SMOKE=PASS second_process=true cleanup=true synthetic_only=true`. This establishes a real local-login Keychain path for synthetic keys and separate-process readback; the local Git SHA was not supplied, so do **not** claim exact-head source proof. It does not validate signed/packaged app entitlement behavior or two-Mac recovery. Background Mac CI remains FAIL by design; do not bypass Keychain with insecure storage. @@ -68,4 +67,4 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Source branch based on `dev@de0d1809`; GCS remains configuration-only. No active sync service. - Head before real Mac request: `c14c8e16`; PR #225 draft. `.github/ci/local-test.sh` now calls the isolated crypto suite and synthetic real-Keychain smoke via a transient Python dependency environment. The central Mac run for that SHA is tracked under `local-ci/mac`. -- At this stage, the user-reported interactive Terminal smoke passed, while central Mac CI Keychain remains FAIL. Next: qualify Keychain from the real installed/signed app and prove independently recoverable trust, pairing and device revocation before any Drive transfer. OAuth and multi-device sync remain disabled. +- Interactive Terminal `keyring` smoke PASS; central runner `keyring` Keychain FAIL. Added **separate native Security.framework probe** in the packaged ClosedRoom binary (second signed-executable process, synthetic key, cleanup), plus an exact-HEAD/ad-hoc-signature verifier `scripts/probe_packaged_keychain.py --build` for GUI Terminal. **Packaged GUI run NOT YET EXECUTED**. Does not install/overwrite the current app or enable sync. Developer ID/notarization, pairing and recovery remain pending. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index 29195d9a..ec19f94f 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -30,3 +30,32 @@ uv run --no-project --python 3.12 --with 'cryptography>=46,<47' --with 'keyring> ``` The probe uses **synthetic temporary records only**, a second process and cleanup verification. Never use actual user credentials/vaults. Mac runner PASS is not installed-app Keychain/TCC proof. + +## Native packaged-app Keychain proof (GUI user opt-in) + +The `vault_keychain.py` experimental `keyring` adapter is NOT included in the +product. To prove the **actual frozen app executable's own Security.framework +context**, use the separate native Keychain diagnostic in +`src/local_asr_server/macos_keychain_native.py`. + +From a clean checkout on an Apple Silicon Mac, using an interactive logged-in +GUI Terminal: + +```bash +python3 scripts/probe_packaged_keychain.py --build +``` + +This creates an **ad-hoc signed, exact-HEAD** .app under `dist/`; it does not +install/replace `/Applications/ClosedRoom.app`. It checks source/manifest, +bundle ID and code signature and calls the packaged +`Contents/MacOS/ClosedRoom secure-sync-keychain-smoke`. That executable uses +a separate synthetic Keychain service: 32 random key bytes, readback, +same-signed-executable second-process HMAC challenge, cleanup and absence +check. The only output is bounded PASS/failure status; no secrets, meeting +data, server, Drive, OAuth or network. + +Without `--build`, reuses ONLY an exact-HEAD finalized app; `--app` +accepts an explicit candidate only when it matches the checked-out SHA. +Background GitHub Mac Keychain access still FAIL `-25308`; this is a +different execution context and is not bypassed. An ad-hoc signature +is NOT Apple Developer ID/notarization or installed-app entitlement evidence. diff --git a/scripts/probe_packaged_keychain.py b/scripts/probe_packaged_keychain.py new file mode 100644 index 00000000..28f6d848 --- /dev/null +++ b/scripts/probe_packaged_keychain.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Explicit GUI-Terminal smoke for the exact finalized ClosedRoom.app. + +Does not install/restart/overwrite /Applications/ClosedRoom.app. No recording, +Google account, sync credentials or external transport. Only synthetic Keychain +entries from the signed bundle binary, removed within that same diagnostic. +""" +from __future__ import annotations + +import argparse +import json +import os +import platform +import plistlib +import subprocess +from pathlib import Path + +import local_real_environment_policy as artifact_policy + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--root", default=str(Path(__file__).resolve().parents[1])) + parser.add_argument("--app", help="Explicit exact-HEAD finalized .app; never use a random installed copy") + parser.add_argument("--build", action="store_true", help="Build a new ad-hoc signed exact-HEAD bundle in dist (not install)") + return parser.parse_args() + + +def validate_artifact(root: Path, app: Path, revision: str) -> tuple[Path, str]: + _, manifest = artifact_policy.local_manifest_for(app, allow_identified=True) + source = manifest.get("source") or {} + if not artifact_policy.revisions_match(revision, str(source.get("revision") or "")): + raise RuntimeError("App artifact does not match the exact source revision") + signing = (manifest.get("configuration") or {}).get("signing") + if signing not in ("identified", "ad-hoc"): + raise RuntimeError("Unsupported app signing identity") + with (app / "Contents" / "Info.plist").open("rb") as file: + info = plistlib.load(file) + if info.get("CFBundleIdentifier") != "com.closedroom.app": + raise RuntimeError("Unexpected app bundle identifier") + executable_name = info.get("CFBundleExecutable") + if not isinstance(executable_name, str) or "/" in executable_name: + raise RuntimeError("Invalid bundle executable") + exe = app / "Contents" / "MacOS" / executable_name + if not exe.is_file(): + raise RuntimeError("Frozen executable missing") + subprocess.run( + ["codesign", "--verify", "--deep", "--strict", str(app)], + check=True, capture_output=True, timeout=120, + ) + return exe, signing + + +def main() -> int: + args = parse_args() + if platform.system() != "Darwin" or platform.machine() != "arm64": + raise RuntimeError("Only real macOS Apple Silicon can qualify the packaged Keychain") + root = Path(args.root).expanduser().resolve() + revision = subprocess.run( + ["git", "rev-parse", "HEAD"], cwd=root, + capture_output=True, text=True, check=True, timeout=10, + ).stdout.strip() + if args.build: + if args.app: + raise RuntimeError("--app and --build are mutually exclusive") + dirty = subprocess.run( + ["git", "status", "--porcelain"], cwd=root, + capture_output=True, text=True, check=True, timeout=10, + ).stdout + if dirty.strip(): + raise RuntimeError("Checkout is not clean; refusing to build a dirty candidate") + env = os.environ.copy() + env.pop("CLOSEDROOM_SIGN_IDENTITY", None) + env["CLOSEDROOM_BUILD_CHANNEL"] = "local-real-environment" + # Creates an immutable finalized artifact. Never --install. + subprocess.run( + ["bash", "scripts/build_artifact.sh", "--no-dmg"], + cwd=root, env=env, check=True, timeout=3600, + ) + # Generated frontend cleanup is owned by the existing local suite. + # This command does not auto-restore/overwrite tracked source files. + if args.app: + app = Path(args.app).expanduser().resolve() + else: + found = artifact_policy.find_exact_local_app(root, revision) + if found is None: + raise RuntimeError("No exact-HEAD finalized app. Rerun with --build.") + app = found[0] + executable, signing = validate_artifact(root, app, revision) + proc = subprocess.run( + [str(executable), "secure-sync-keychain-smoke"], + capture_output=True, text=True, timeout=45, + ) + if proc.returncode != 0: + raise RuntimeError( + "Signed bundle Keychain diagnostic failed. " + "Use a logged-in GUI Terminal; the background CI Keychain is not interactive." + ) + try: + answer = json.loads(proc.stdout.strip()) + except (json.JSONDecodeError, ValueError) as exc: + raise RuntimeError("Bundled Keychain diagnostic did not return a valid result") from exc + expected = { + "schema": "closedroom.packaged-keychain-smoke/v1", + "status": "pass", + "frozen_app_process": True, + "independent_child": True, + "synthetic_only": True, + "cleanup": True, + } + if answer != expected: + raise RuntimeError("Invalid bundle Keychain evidence") + print(json.dumps({ + "status": "pass", + "source_revision": revision, + "signing": signing, + "bundle_id": "com.closedroom.app", + "scope": "packaged-GUI-Terminal-Keychain-only", + "independent_child": True, + "cleanup": True, + "installed_app_modified": False, + }, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/local_asr_server/bundled_module_dispatch.py b/src/local_asr_server/bundled_module_dispatch.py index e06e74b0..4e146070 100644 --- a/src/local_asr_server/bundled_module_dispatch.py +++ b/src/local_asr_server/bundled_module_dispatch.py @@ -83,6 +83,12 @@ def dispatch_bundled_module(argv: Sequence[str] | None = None) -> bool: """ arguments = list(sys.argv if argv is None else argv) + # Offline diagnostics from the actual frozen app binary. No Cocoa/server. + if len(arguments) >= 2 and arguments[1] in ( + "secure-sync-keychain-smoke", "secure-sync-keychain-smoke-child", + ): + from local_asr_server.macos_keychain_probe import dispatch_keychain_probe + return dispatch_keychain_probe(arguments) if len(arguments) >= 2 and arguments[1] == BUNDLE_RUNTIME_SMOKE_COMMAND: _run_bundle_runtime_smoke() return True diff --git a/src/local_asr_server/macos_keychain_native.py b/src/local_asr_server/macos_keychain_native.py new file mode 100644 index 00000000..3a2a0e89 --- /dev/null +++ b/src/local_asr_server/macos_keychain_native.py @@ -0,0 +1,175 @@ +"""ClosedRoom macOS Security.framework Keychain adapter, currently diagnostic-only. + +Uses the native signed process identity, not an external "security" CLI. +No cloud, filesystem fallback, password prompts, user vaults or app settings. +The app does NOT enroll any sync identity through this module yet. +""" +from __future__ import annotations + +import ctypes +import sys +from contextlib import contextmanager +from typing import Iterator + +SERVICE = "com.closedroom.app.secure-sync-probe.v1" +ITEM_NOT_FOUND = -25300 +DUPLICATE_ITEM = -25299 +SUCCESS = 0 +_UTF8 = 0x08000100 + + +class NativeKeychainError(RuntimeError): + """Security.framework could not securely perform the requested operation.""" + + +def _account_ok(account: str) -> bool: + return ( + isinstance(account, str) + and len(account) == 32 + and all(c in "0123456789abcdef" for c in account) + ) + + +class _SecurityAPI: + """Low-level macOS Keychain bindings. All created CoreFoundation refs released.""" + + def __init__(self) -> None: + if sys.platform != "darwin": + raise NativeKeychainError("macOS Security.framework is required") + cf = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation") + sec = ctypes.CDLL("/System/Library/Frameworks/Security.framework/Security") + ptr = ctypes.c_void_p + cf.CFStringCreateWithCString.argtypes = (ptr, ctypes.c_char_p, ctypes.c_uint32) + cf.CFStringCreateWithCString.restype = ptr + cf.CFDataCreate.argtypes = (ptr, ctypes.c_void_p, ctypes.c_long) + cf.CFDataCreate.restype = ptr + cf.CFDictionaryCreateMutable.argtypes = (ptr, ctypes.c_long, ptr, ptr) + cf.CFDictionaryCreateMutable.restype = ptr + cf.CFDictionarySetValue.argtypes = (ptr, ptr, ptr) + cf.CFDictionarySetValue.restype = None + cf.CFRelease.argtypes = (ptr,) + cf.CFRelease.restype = None + cf.CFGetTypeID.argtypes = (ptr,) + cf.CFGetTypeID.restype = ctypes.c_ulong + cf.CFDataGetTypeID.restype = ctypes.c_ulong + cf.CFDataGetLength.argtypes = (ptr,) + cf.CFDataGetLength.restype = ctypes.c_long + cf.CFDataGetBytePtr.argtypes = (ptr,) + cf.CFDataGetBytePtr.restype = ctypes.c_void_p + sec.SecItemAdd.argtypes = (ptr, ctypes.POINTER(ptr)) + sec.SecItemAdd.restype = ctypes.c_int32 + sec.SecItemCopyMatching.argtypes = (ptr, ctypes.POINTER(ptr)) + sec.SecItemCopyMatching.restype = ctypes.c_int32 + sec.SecItemDelete.argtypes = (ptr,) + sec.SecItemDelete.restype = ctypes.c_int32 + self.cf, self.sec = cf, sec + self._const = { + k: ptr.in_dll(sec, k).value + for k in ("kSecClass", "kSecClassGenericPassword", "kSecAttrService", + "kSecAttrAccount", "kSecValueData", "kSecReturnData", + "kSecMatchLimit", "kSecMatchLimitOne") + } + self._true = ptr.in_dll(cf, "kCFBooleanTrue").value + + @contextmanager + def _query(self, account: str, data: bytes | None = None, *, + read: bool = False) -> Iterator[int]: + created: list[int] = [] + cf = self.cf + try: + q = cf.CFDictionaryCreateMutable(None, 0, None, None) + if not q: + raise NativeKeychainError("Could not create Keychain query") + created.append(q) + service = cf.CFStringCreateWithCString(None, SERVICE.encode("utf-8"), _UTF8) + acct = cf.CFStringCreateWithCString(None, account.encode("ascii"), _UTF8) + if not service or not acct: + if service: + created.append(service) + if acct: + created.append(acct) + raise NativeKeychainError("Could not encode Keychain account") + created.extend([service, acct]) + for key, value in ( + ("kSecClass", self._const["kSecClassGenericPassword"]), + ("kSecAttrService", service), + ("kSecAttrAccount", acct), + ): + cf.CFDictionarySetValue(q, self._const[key], value) + if data is not None: + # CFDataCreate copies bytes; the transient C buffer is never logged. + source = ctypes.create_string_buffer(data) + blob = cf.CFDataCreate(None, source, len(data)) + if not blob: + raise NativeKeychainError("Could not create Keychain value") + created.append(blob) + cf.CFDictionarySetValue(q, self._const["kSecValueData"], blob) + if read: + cf.CFDictionarySetValue(q, self._const["kSecReturnData"], self._true) + cf.CFDictionarySetValue( + q, self._const["kSecMatchLimit"], self._const["kSecMatchLimitOne"], + ) + yield q + finally: + for ref in reversed(created): + cf.CFRelease(ref) + + def get(self, account: str) -> bytes | None: + with self._query(account, read=True) as query: + value = ctypes.c_void_p() + status = self.sec.SecItemCopyMatching(query, ctypes.byref(value)) + if status == ITEM_NOT_FOUND: + return None + if status != SUCCESS: + if value.value: + self.cf.CFRelease(value) + raise NativeKeychainError(f"Keychain read failed (OSStatus {status})") + if not value.value: + raise NativeKeychainError("Keychain returned no value") + try: + if self.cf.CFGetTypeID(value) != self.cf.CFDataGetTypeID(): + raise NativeKeychainError("Unexpected Keychain result type") + length = self.cf.CFDataGetLength(value) + if not 0 <= length <= 8192: + raise NativeKeychainError("Invalid Keychain value length") + return ctypes.string_at(self.cf.CFDataGetBytePtr(value), length) + finally: + self.cf.CFRelease(value) + + def add(self, account: str, secret: bytes) -> None: + with self._query(account, data=secret) as query: + status = self.sec.SecItemAdd(query, None) + if status != SUCCESS: + raise NativeKeychainError(f"Keychain creation failed (OSStatus {status})") + + def delete(self, account: str) -> None: + with self._query(account) as query: + status = self.sec.SecItemDelete(query) + if status not in (SUCCESS, ITEM_NOT_FOUND): + raise NativeKeychainError(f"Keychain cleanup failed (OSStatus {status})") + + +class MacKeychain: + """Minimal fail-closed native adapter; diagnostic service only.""" + + def __init__(self, *, _test_api: object | None = None) -> None: + self._api = _SecurityAPI() if _test_api is None else _test_api + + def load(self, account: str) -> bytes | None: + if not _account_ok(account): + raise NativeKeychainError("Invalid Keychain account") + value = self._api.get(account) + if value is not None and (not isinstance(value, bytes) or len(value) != 32): + raise NativeKeychainError("Invalid stored Keychain secret") + return value + + def create(self, account: str, secret: bytes) -> None: + if not _account_ok(account) or not isinstance(secret, bytes) or len(secret) != 32: + raise NativeKeychainError("Invalid Keychain input") + # SecItemAdd is atomic with respect to duplicate account and fails closed. + self._api.add(account, secret) + + def delete(self, account: str) -> None: + if not _account_ok(account): + raise NativeKeychainError("Invalid Keychain account") + self._api.delete(account) diff --git a/src/local_asr_server/macos_keychain_probe.py b/src/local_asr_server/macos_keychain_probe.py new file mode 100644 index 00000000..98980c58 --- /dev/null +++ b/src/local_asr_server/macos_keychain_probe.py @@ -0,0 +1,106 @@ +"""Opt-in synthetic Keychain diagnosis from the actual frozen ClosedRoom.app binary. + +The diagnostic neither starts the app API nor reads/writes real meeting or +vault state. It is intentionally inaccessible through network endpoints. +""" +from __future__ import annotations + +import hashlib +import hmac +import json +import secrets +import subprocess +import sys + +from local_asr_server.macos_keychain_native import MacKeychain, NativeKeychainError + +COMMAND = "secure-sync-keychain-smoke" +CHILD_COMMAND = "secure-sync-keychain-smoke-child" + + +def _require_bundle() -> None: + if not (sys.platform == "darwin" and getattr(sys, "frozen", False)): + raise NativeKeychainError("This diagnostic requires a frozen macOS ClosedRoom.app") + + +def _child(account: str, challenge_hex: str) -> int: + _require_bundle() + if len(challenge_hex) != 64 or any(c not in "0123456789abcdef" for c in challenge_hex): + raise NativeKeychainError("Invalid challenge") + secret = MacKeychain().load(account) + if secret is None: + raise NativeKeychainError("Temporary Keychain secret unavailable in second process") + proof = hmac.digest(secret, bytes.fromhex(challenge_hex), hashlib.sha256) + print(proof.hex()) + return 0 + + +def run_synthetic_keychain_smoke() -> int: + """Only run from a signed/ad-hoc frozen app executable in a user GUI session.""" + _require_bundle() + account = secrets.token_hex(16) + key = secrets.token_bytes(32) + store = MacKeychain() + created = False + error: BaseException | None = None + cleaned = False + try: + if store.load(account) is not None: + raise NativeKeychainError("Random synthetic Keychain account collision") + store.create(account, key) + created = True + if not hmac.compare_digest(store.load(account) or b"", key): + raise NativeKeychainError("First-process Keychain readback failed") + challenge = secrets.token_bytes(32) + child = subprocess.run( + [sys.executable, CHILD_COMMAND, account, challenge.hex()], + capture_output=True, text=True, timeout=25, check=False, + ) + if child.returncode != 0: + raise NativeKeychainError("Second packaged process Keychain access failed") + try: + received = bytes.fromhex(child.stdout.strip()) + except ValueError as exc: + raise NativeKeychainError("Invalid second-process challenge response") from exc + expected = hmac.digest(key, challenge, hashlib.sha256) + if not hmac.compare_digest(received, expected): + raise NativeKeychainError("Second-process challenge verification failed") + except BaseException as exc: + error = exc + finally: + if created: + try: + store.delete(account) + cleaned = store.load(account) is None + except Exception: + cleaned = False + else: + # Never delete a pre-existing account or one with ambiguous + # ownership. A failed SecItemAdd must not touch other key material. + cleaned = error is None + if not cleaned: + raise NativeKeychainError("Synthetic Keychain cleanup not proven") from error + if error is not None: + raise NativeKeychainError("Packaged Keychain smoke did not pass") from error + print(json.dumps({ + "schema": "closedroom.packaged-keychain-smoke/v1", + "status": "pass", + "frozen_app_process": True, + "independent_child": True, + "synthetic_only": True, + "cleanup": True, + }, sort_keys=True)) + return 0 + + +def dispatch_keychain_probe(argv: list[str]) -> bool: + """Recognize only diagnostic commands; reject malformed invocations.""" + if len(argv) > 1 and argv[1] in (COMMAND, CHILD_COMMAND): + if argv[1] == COMMAND and len(argv) == 2: + run_synthetic_keychain_smoke() + elif argv[1] == CHILD_COMMAND and len(argv) == 4: + _child(argv[2], argv[3]) + else: + raise SystemExit("Invalid packaged Keychain diagnostic arguments") + return True + return False diff --git a/test/test_secure_sync_packaged_keychain.py b/test/test_secure_sync_packaged_keychain.py new file mode 100644 index 00000000..54118750 --- /dev/null +++ b/test/test_secure_sync_packaged_keychain.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import contextlib +import hashlib +import hmac +import io +import json +import sys +import unittest +from unittest.mock import patch + +from local_asr_server.bundled_module_dispatch import dispatch_bundled_module +from local_asr_server.macos_keychain_native import ( + MacKeychain, NativeKeychainError, _SecurityAPI, +) +from local_asr_server.macos_keychain_probe import ( + CHILD_COMMAND, COMMAND, dispatch_keychain_probe, run_synthetic_keychain_smoke, +) + + +class FakeSecurity: + def __init__(self) -> None: + self.data: dict[str, bytes] = {} + self.fail_read = False + self.fail_write = False + self.deleted: list[str] = [] + + def get(self, account: str) -> bytes | None: + if self.fail_read: + raise NativeKeychainError("synthetic read failure") + return self.data.get(account) + + def add(self, account: str, secret: bytes) -> None: + if self.fail_write: + raise NativeKeychainError("synthetic OSStatus") + if account in self.data: + raise NativeKeychainError("synthetic duplicate") + self.data[account] = secret + + def delete(self, account: str) -> None: + self.deleted.append(account) + self.data.pop(account, None) + + +class NativeKeychainAdapterTests(unittest.TestCase): + def test_bad_identifiers_and_non_32_byte_keys_fail_closed(self) -> None: + store = MacKeychain(_test_api=FakeSecurity()) + for account in ("../secrets", "a" * 31, "A" * 32, ""): + with self.assertRaises(NativeKeychainError): + store.load(account) + with self.assertRaises(NativeKeychainError): + store.create("a" * 32, b"short") + + def test_create_read_delete_and_duplicate_rejection(self) -> None: + api = FakeSecurity() + a = MacKeychain(_test_api=api) + b = MacKeychain(_test_api=api) + account = "a" * 32 + secret = b"\x01" * 32 + a.create(account, secret) + self.assertEqual(b.load(account), secret) + with self.assertRaises(NativeKeychainError): + b.create(account, b"\x02" * 32) + self.assertEqual(a.load(account), secret) + b.delete(account) + self.assertIsNone(a.load(account)) + + def test_corrupt_key_and_backend_errors_fail_closed(self) -> None: + api = FakeSecurity() + store = MacKeychain(_test_api=api) + account = "b" * 32 + api.data[account] = b"bad" + with self.assertRaises(NativeKeychainError): + store.load(account) + api.fail_read = True + with self.assertRaises(NativeKeychainError): + store.load(account) + api.fail_read = False + api.fail_write = True + with self.assertRaises(NativeKeychainError): + store.create("c" * 32, b"x" * 32) + + def test_no_nonmac_file_or_command_fallback(self) -> None: + with patch("local_asr_server.macos_keychain_native.sys.platform", "linux"): + with self.assertRaises(NativeKeychainError): + _SecurityAPI() + + +class SignedBundleDiagnosticTests(unittest.TestCase): + def test_normal_app_and_unrelated_commands_are_not_intercepted(self) -> None: + self.assertFalse(dispatch_keychain_probe(["ClosedRoom"])) + self.assertFalse(dispatch_keychain_probe(["ClosedRoom", "serve"])) + self.assertFalse(dispatch_bundled_module(["ClosedRoom", "--not-a-diagnostic"])) + + def test_diagnostic_is_bundle_only_and_arguments_strict(self) -> None: + with patch("local_asr_server.macos_keychain_probe.sys.platform", "linux"): + with self.assertRaises(NativeKeychainError): + dispatch_bundled_module(["ClosedRoom", COMMAND]) + with self.assertRaises(SystemExit): + dispatch_bundled_module(["ClosedRoom", COMMAND, "extraneous"]) + with self.assertRaises(SystemExit): + dispatch_bundled_module(["ClosedRoom", CHILD_COMMAND, "wrong"]) + + def test_packaged_parent_second_process_challenge_and_cleanup(self) -> None: + api = FakeSecurity() + store = MacKeychain(_test_api=api) + account = "a" * 32 + key = bytes(range(32)) + challenge = bytes(range(32, 64)) + + def fake_child(args: list[str], **_: object): + self.assertEqual(args[1:3], [CHILD_COMMAND, account]) + self.assertEqual(bytes.fromhex(args[3]), challenge) + proof = hmac.digest(store.load(account), challenge, hashlib.sha256).hex() + return type("Child", (), {"returncode": 0, "stdout": proof})() + + stdout = io.StringIO() + with ( + patch("local_asr_server.macos_keychain_probe._require_bundle"), + patch("local_asr_server.macos_keychain_probe.MacKeychain", return_value=store), + patch("local_asr_server.macos_keychain_probe.secrets.token_hex", return_value=account), + patch("local_asr_server.macos_keychain_probe.secrets.token_bytes", side_effect=[key, challenge]), + patch("local_asr_server.macos_keychain_probe.subprocess.run", side_effect=fake_child), + contextlib.redirect_stdout(stdout), + ): + self.assertEqual(run_synthetic_keychain_smoke(), 0) + outcome = json.loads(stdout.getvalue()) + self.assertEqual(outcome["status"], "pass") + self.assertTrue(outcome["cleanup"]) + self.assertEqual(api.deleted, [account]) + self.assertNotIn(account, api.data) + + def test_child_failure_still_cleans_up_and_no_false_pass(self) -> None: + api = FakeSecurity() + store = MacKeychain(_test_api=api) + account = "b" * 32 + with ( + patch("local_asr_server.macos_keychain_probe._require_bundle"), + patch("local_asr_server.macos_keychain_probe.MacKeychain", return_value=store), + patch("local_asr_server.macos_keychain_probe.secrets.token_hex", return_value=account), + patch("local_asr_server.macos_keychain_probe.secrets.token_bytes", side_effect=[b"x" * 32, b"y" * 32]), + patch("local_asr_server.macos_keychain_probe.subprocess.run", return_value=type("Child", (), {"returncode": 2, "stdout": ""})()), + ): + with self.assertRaises(NativeKeychainError): + run_synthetic_keychain_smoke() + self.assertEqual(api.deleted, [account]) + self.assertNotIn(account, api.data) + + def test_collision_never_deletes_preexisting_secret(self) -> None: + api = FakeSecurity() + account = "c" * 32 + api.data[account] = b"x" * 32 + store = MacKeychain(_test_api=api) + with ( + patch("local_asr_server.macos_keychain_probe._require_bundle"), + patch("local_asr_server.macos_keychain_probe.MacKeychain", return_value=store), + patch("local_asr_server.macos_keychain_probe.secrets.token_hex", return_value=account), + patch("local_asr_server.macos_keychain_probe.secrets.token_bytes", return_value=b"y" * 32), + ): + with self.assertRaises(NativeKeychainError): + run_synthetic_keychain_smoke() + self.assertEqual(api.data[account], b"x" * 32) + self.assertEqual(api.deleted, []) + + +if __name__ == "__main__": + unittest.main() From e4228956591b9f63f24b8b7e4f8696eb8c236453 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 16:08:35 +0100 Subject: [PATCH 10/24] docs(sync): distinguish Mac unit PASS from background and packaged GUI Keychain gates --- docs/workstreams/secure-sync-google-drive.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 2d6f714c..f3978606 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -67,4 +67,4 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Source branch based on `dev@de0d1809`; GCS remains configuration-only. No active sync service. - Head before real Mac request: `c14c8e16`; PR #225 draft. `.github/ci/local-test.sh` now calls the isolated crypto suite and synthetic real-Keychain smoke via a transient Python dependency environment. The central Mac run for that SHA is tracked under `local-ci/mac`. -- Interactive Terminal `keyring` smoke PASS; central runner `keyring` Keychain FAIL. Added **separate native Security.framework probe** in the packaged ClosedRoom binary (second signed-executable process, synthetic key, cleanup), plus an exact-HEAD/ad-hoc-signature verifier `scripts/probe_packaged_keychain.py --build` for GUI Terminal. **Packaged GUI run NOT YET EXECUTED**. Does not install/overwrite the current app or enable sync. Developer ID/notarization, pairing and recovery remain pending. +- Native packaged-probe implementation at `25fb5e52`: [central Mac CI #44550915840](https://github.com/daniele21/local-runner-infra/actions/runs/44550915840) **986 core tests PASS (9 new); 17 crypto PASS**; old background `keyring` smoke still FAIL `-25308`. Interactive Terminal `keyring` PASS previously. New Security.framework CLI probe + `scripts/probe_packaged_keychain.py --build` check the frozen same-signed-executable process, cleanup and exact finalized artifact, without touching installed app. **Packaged GUI run PENDING**; Developer ID, pairing and recovery still pending. From b8dfea6474eee488b2a99e754941aab91fb17648 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Thu, 19 Nov 2026 16:11:47 +0100 Subject: [PATCH 11/24] ci(sync): separate deterministic Mac checks from required GUI Keychain qualification --- .github/ci/local-test.sh | 9 ++++++--- docs/workstreams/secure-sync-google-drive.md | 2 +- experiments/secure_sync/README.md | 2 +- test/test_secure_sync_packaged_keychain.py | 12 ++++++++++++ 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/.github/ci/local-test.sh b/.github/ci/local-test.sh index 15eef935..fa93f4ac 100644 --- a/.github/ci/local-test.sh +++ b/.github/ci/local-test.sh @@ -34,9 +34,12 @@ UV_CACHE_DIR=.cache/uv uv run --frozen --python 3.12 python -m unittest discover # the experiments directory. Do not upload private data or install globally. SECURE_SYNC_PY=(uv run --no-project --python 3.12 --with 'cryptography>=46,<47' --with 'keyring>=25,<26' -- python) UV_CACHE_DIR=.cache/uv "${SECURE_SYNC_PY[@]}" -m unittest discover -s experiments/secure_sync -p 'test_*.py' -v -# Requires a real, unlocked login Keychain. Fails closed and only creates -# randomized synthetic entries under ClosedRoom's dedicated test identity. -UV_CACHE_DIR=.cache/uv "${SECURE_SYNC_PY[@]}" experiments/secure_sync/macos_keychain_probe.py +# REAL_ENVIRONMENT: Keychain calls require an interactive macOS GUI login session. +# This shared background runner returned errSecInteractionNotAllowed (-25308) +# twice, even after login Keychain unlock. The native installed/frozen app +# validation is a SEPARATE blocking physical GUI-user gate, never inferred from +# successful deterministic CI: scripts/probe_packaged_keychain.py --build. +echo "KEYCHAIN_REAL_ENVIRONMENT=NOT_RUN context=background-runner (separate GUI gate required)" source .github/ci/setup-browser.sh E2E_SOURCE_REVISION="$(git rev-parse HEAD)" node scripts/browser_meeting_ui_e2e.mjs echo "ClosedRoom Mac source and browser FULL_MEDIA checks passed" diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index f3978606..e55947b2 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -67,4 +67,4 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Source branch based on `dev@de0d1809`; GCS remains configuration-only. No active sync service. - Head before real Mac request: `c14c8e16`; PR #225 draft. `.github/ci/local-test.sh` now calls the isolated crypto suite and synthetic real-Keychain smoke via a transient Python dependency environment. The central Mac run for that SHA is tracked under `local-ci/mac`. -- Native packaged-probe implementation at `25fb5e52`: [central Mac CI #44550915840](https://github.com/daniele21/local-runner-infra/actions/runs/44550915840) **986 core tests PASS (9 new); 17 crypto PASS**; old background `keyring` smoke still FAIL `-25308`. Interactive Terminal `keyring` PASS previously. New Security.framework CLI probe + `scripts/probe_packaged_keychain.py --build` check the frozen same-signed-executable process, cleanup and exact finalized artifact, without touching installed app. **Packaged GUI run PENDING**; Developer ID, pairing and recovery still pending. +- Native probe at `25fb5e52`: [Mac run #44550915840](https://github.com/daniele21/local-runner-infra/actions/runs/44550915840): **986 core tests PASS (9 new), 17 crypto PASS**, background `keyring` FAIL `-25308`. An interactive Terminal `keyring` probe passed. Background CI now runs deterministic suites ONLY and explicitly reports Keychain GUI **NOT_RUN**; the real gate moves to `scripts/probe_packaged_keychain.py --build` on the same-signed packaged binary. **Packaged GUI run PENDING**, no app installation; Developer ID, pairing, recovery remain pending. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index ec19f94f..79a63228 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -23,7 +23,7 @@ Next step: review and adapt this format in the existing canonical TranscriptionS ## Source-owned real-Mac gate -On the shared Mac validation lane, `.github/ci/local-test.sh` explicitly runs the `test_*.py` files with transient isolated Python dependencies, then runs: +On the shared Mac validation lane, `.github/ci/local-test.sh` explicitly runs the `test_*.py` files with transient isolated Python dependencies. A genuine user GUI Keychain smoke is deliberately NOT run as a background CI step (the headless runner produced `errSecInteractionNotAllowed -25308`). It remains a separate real-environment requirement. The earlier exploratory direct invocation was: ```sh uv run --no-project --python 3.12 --with 'cryptography>=46,<47' --with 'keyring>=25,<26' -- python experiments/secure_sync/macos_keychain_probe.py diff --git a/test/test_secure_sync_packaged_keychain.py b/test/test_secure_sync_packaged_keychain.py index 54118750..adc0b5a9 100644 --- a/test/test_secure_sync_packaged_keychain.py +++ b/test/test_secure_sync_packaged_keychain.py @@ -85,6 +85,18 @@ def test_no_nonmac_file_or_command_fallback(self) -> None: with self.assertRaises(NativeKeychainError): _SecurityAPI() + def test_background_ci_cannot_claim_gui_keychain_success(self) -> None: + from pathlib import Path + + root = Path(__file__).resolve().parents[1] + ci = (root / ".github" / "ci" / "local-test.sh").read_text(encoding="utf-8") + self.assertIn('test_*.py', ci) + self.assertIn("KEYCHAIN_REAL_ENVIRONMENT=NOT_RUN", ci) + self.assertIn("scripts/probe_packaged_keychain.py --build", ci) + self.assertNotIn( + '"${SECURE_SYNC_PY[@]}" experiments/secure_sync/macos_keychain_probe.py', ci, + ) + class SignedBundleDiagnosticTests(unittest.TestCase): def test_normal_app_and_unrelated_commands_are_not_intercepted(self) -> None: From 56e86937ab21440c3151626dc3be5553b7420782 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 10:02:57 +0100 Subject: [PATCH 12/24] docs(sync): record exact-source ad-hoc packaged GUI Keychain PASS and scope --- docs/workstreams/secure-sync-google-drive.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index e55947b2..eff6aac8 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -56,15 +56,14 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Isolated `vault_keychain.py`: fail-closed macOS Keychain-only prototype storing independent AES vault and **software** Ed25519 signing secrets, authenticated owner pin and checkpoint. Not hardware Secure Enclave. Synthetic unit tests cover restart, tampering, bad signer, key replacement/corruption, failures and replay. - Missing: genuine recovery materials, cross-process CAS, authenticated pairing, revocation/rotation, second-device trust anchor and verified backup. No OAuth, sync, migration, upload, local eviction, app integration or production cryptographic dependencies yet. -### Mac result and failure classification — 2026-11-19 +### Validation — 2026-11-19/20 -- Mac [run 44498140756](https://github.com/daniele21/local-runner-infra/actions/runs/44498140756), SHA `c14c8e16`: **977 core tests PASS; 17 crypto tests PASS**. Real `keyring` Keychain smoke FAIL on write with `errSecInteractionNotAllowed (-25308)`: runner session authority, not cryptography. -- Source commit `b4cfd627` fixes the independent repository-doc budget failure (3,125 > 3,000 estimated tokens); hosted governance checks now PASS. It has **not** passed exact-HEAD Mac validation; the earlier runner failure remains blocking for the Keychain gate. -- **Repeat after user unlocked login Keychain**: source `159afbfc74e0abc40ae6c004248451a451075ce2`, central [run 44510352786](https://github.com/daniele21/local-runner-infra/actions/runs/44510352786) on `local-mac-mini-3` (`MacminiiDaniele`). Main suite 977 PASS, crypto 17 PASS; real Keychain write still FAIL `errSecInteractionNotAllowed (-25308)`; `local-ci/mac=failure`. Earlier run used `local-mac-mini-4` on the same machine. This falsifies the hypothesis that unlocking login Keychain alone would resolve runner access. Next action requires a separate GUI-user/signed-app or explicitly authorized launch-session proof, not retrying the same background runner unchanged. Real-environment gate remains blocked. -- **User-reported GUI-session test PASS (2026-11-19):** from macOS Terminal in `~/Projects/local-asr-server`, branch `feature/google-drive-secure-sync-foundation`, running `experiments/secure_sync/macos_keychain_probe.py` returned `REAL_MAC_KEYCHAIN_SMOKE=PASS second_process=true cleanup=true synthetic_only=true`. This establishes a real local-login Keychain path for synthetic keys and separate-process readback; the local Git SHA was not supplied, so do **not** claim exact-head source proof. It does not validate signed/packaged app entitlement behavior or two-Mac recovery. Background Mac CI remains FAIL by design; do not bypass Keychain with insecure storage. +- Exact source `b8dfea6474eee488b2a99e754941aab91fb17648`: [self-hosted Mac run 44552089974](https://github.com/daniele21/local-runner-infra/actions/runs/44552089974) `local-ci/mac=success`; **987 Python tests PASS; 17 crypto tests PASS; browser FULL_MEDIA PASS**. `KEYCHAIN_REAL_ENVIRONMENT=NOT_RUN` is intentional in non-interactive CI. +- Earlier attempts to access Keychain from a background runner failed `errSecInteractionNotAllowed (-25308)`, even with login Keychain unlocked. The same local synthetic `keyring` smoke passed interactively in Terminal, but without a supplied exact Git SHA; separate from bundle proof. +- **Packaged ad-hoc GUI Keychain gate PASS (user-supplied terminal evidence, test run 2026-11-19):** source `b8dfea6474eee488b2a99e754941aab91fb17648`, finalized artifact manifest `dist/artifacts/macos-arm64-local-real-environment-app/local-20261119T161450Z-f0de04/build-manifest.json`. `scripts/probe_packaged_keychain.py --build` reported `bundle_id=com.closedroom.app`, `signing=ad-hoc`, `status=pass`, `independent_child=true`, `cleanup=true`, `installed_app_modified=false`, scope `packaged-GUI-Terminal-Keychain-only`. The script validates finalized artifact provenance/signature and executes the Security.framework probe from the frozen app binary. Evidence is supplied by the operator, not independently downloaded from the Mac. +- **Gate qualified only for ad-hoc packaged diagnostic.** No Developer ID signing/notarization or installed-app workflow, no production vault key lifecycle, authenticated pairing, recovery, revocation, Google OAuth, Drive integration, upload or remote restoration has been proven. ### Current checkpoint -- Source branch based on `dev@de0d1809`; GCS remains configuration-only. No active sync service. -- Head before real Mac request: `c14c8e16`; PR #225 draft. `.github/ci/local-test.sh` now calls the isolated crypto suite and synthetic real-Keychain smoke via a transient Python dependency environment. The central Mac run for that SHA is tracked under `local-ci/mac`. -- Native probe at `25fb5e52`: [Mac run #44550915840](https://github.com/daniele21/local-runner-infra/actions/runs/44550915840): **986 core tests PASS (9 new), 17 crypto PASS**, background `keyring` FAIL `-25308`. An interactive Terminal `keyring` probe passed. Background CI now runs deterministic suites ONLY and explicitly reports Keychain GUI **NOT_RUN**; the real gate moves to `scripts/probe_packaged_keychain.py --build` on the same-signed packaged binary. **Packaged GUI run PENDING**, no app installation; Developer ID, pairing, recovery remain pending. +- Source branch from `dev`; draft PR #225. The Keychain experiment and packaged-app synthetic security smoke are **implemented and qualified at the scope above**; product sync is still OFF. No GCS/Drive transmission or real user meeting data transferred. +- Continue SYNC-2 with independently held recovery secrets, trusted latest checkpoint transfer and owner identity, concurrency/race resistance, and synthetic cross-device pairing/revoke tests. Do not claim a second-Mac restore before physical evidence. Future packaging evidence must match the relevant exact candidate and signed-app delivery mode. From ca4549f4b1571c9a0a17cea3cc1ac1983f2dee09 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 10:17:08 +0100 Subject: [PATCH 13/24] spike(sync): independent recovery capsule and authenticated offline read-only device grant --- docs/workstreams/secure-sync-google-drive.md | 3 +- experiments/secure_sync/README.md | 34 +- experiments/secure_sync/device_pairing.py | 306 ++++++++++++++++++ experiments/secure_sync/recovery_capsule.py | 239 ++++++++++++++ experiments/secure_sync/test_offline_trust.py | 260 +++++++++++++++ 5 files changed, 840 insertions(+), 2 deletions(-) create mode 100644 experiments/secure_sync/device_pairing.py create mode 100644 experiments/secure_sync/recovery_capsule.py create mode 100644 experiments/secure_sync/test_offline_trust.py diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index eff6aac8..946d634d 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -66,4 +66,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model ### Current checkpoint - Source branch from `dev`; draft PR #225. The Keychain experiment and packaged-app synthetic security smoke are **implemented and qualified at the scope above**; product sync is still OFF. No GCS/Drive transmission or real user meeting data transferred. -- Continue SYNC-2 with independently held recovery secrets, trusted latest checkpoint transfer and owner identity, concurrency/race resistance, and synthetic cross-device pairing/revoke tests. Do not claim a second-Mac restore before physical evidence. Future packaging evidence must match the relevant exact candidate and signed-app delivery mode. +- SYNC-2 offline candidate: `recovery_capsule.py` (random independent 256-bit recovery code, authenticated capsule preserving vault key/owner signing key/checkpoint); `device_pairing.py` (5-minute X25519 read-only grant, Ed25519 owner proof, manual two-screen comparison required and independent owner pin). Synthetic adversarial cases in `test_offline_trust.py`. Not product-enabled. +- Still SYNC-2 ACTIVE: durable replay/CAS, signed revoke+future-key rotation, authenticated owner-public bootstrap, independent anti-rollback checkpoint, recovery-code lifecycle/UI and real two-Mac restore; no active Drive or production Keychain lifecycle. Previous ad-hoc GUI gate remains limited to the earlier exact executable SHA. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index 79a63228..e03f56e8 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -13,7 +13,7 @@ Additional isolated components: - `vault_keychain.py`: explicit macOS Keychain-only prototype for vault and software Ed25519 signing secrets, an out-of-band owner key pin and a trusted local checkpoint. Fake Keychain tests do not demonstrate that a packaged Mac app can access the Keychain. The test injection is **not** a production option. No automatic initialization. - `test_vault_foundation.py`: key corruption, wrong signer, replay, fork, restart and no-fallback cases. -No cross-process compare-and-swap, signed device grants, user recovery secret, real Mac/Keychain integration or provider-freshness guarantee exists. A clean device **must not accept Drive's purported current head as proof of freshness**. Do not activate upload or deletion. +No production cross-process compare-and-swap, durable pairing grants, independently qualified recovery, or provider-freshness guarantee exists. A clean device **must not accept Drive's purported current head as proof of freshness**. Do not activate upload or deletion. The 32-byte secret is **test-only** in this experiment. Do not persist it in plaintext, pass it to telemetry, store it in Drive, or treat the local test fixture as a recovery-key protocol. @@ -59,3 +59,35 @@ accepts an explicit candidate only when it matches the checked-out SHA. Background GitHub Mac Keychain access still FAIL `-25308`; this is a different execution context and is not bypassed. An ad-hoc signature is NOT Apple Developer ID/notarization or installed-app entitlement evidence. + +## SYNC-2 offline recovery and pairing proof (not production) + +- `recovery_capsule.py` encrypts the 256-bit vault key, **software** + Ed25519 owner private identity and the trusted manifest checkpoint with a + separate randomly generated, 256-bit `CR1-` recovery code. The code is + never put in the capsule, local settings, Drive or CI logs. Store the code + **independently**: possession of only a capsule or only a code is insufficient. + Uses HKDF-SHA256 on a high-entropy code + random salt, AES-256-GCM and + authenticated format/header. Arbitrary user passwords are NOT accepted. +- `device_pairing.py` creates an expiring (5-minute) X25519 device request. + Owner approval must be explicit and preceded by comparing the exact + eight-digit request fingerprint shown by **both physical Macs** through a + separate user-trusted channel. Owner signs a **read-only** X25519/HKDF/ + AES-GCM vault-key grant tied to the request, device and checkpoint. Receiver + requires an **independently authenticated owner public key**. The recipient + does not receive the owner signing private key. +- `test_offline_trust.py` checks wrong recovery codes, stale/conflicting + checkpoints, mismatched owner, tamper, timeout, refusal, substitutions, + repeat grant use in one pending session and independently recovered owner + keys issuing a read-only grant. All objects remain in memory; no transport. + +**Security boundary:** this is protocol experimentation only. Manual SAS +verification cannot be inferred from passing a string to the API; a real +two-screen UX and authenticated owner-public bootstrap must be designed and +tested. In-memory `PendingDevice.consumed` is NOT durable anti-replay or +device authorization. Recovering the owner signing secret restores full owner +authority; recovery material needs stronger UX, locked Keychain persistence, +crash-safe transaction handling, loss/restore and key compromise reviews. +A Drive provider could replay a previously valid encrypted recovery capsule: +without an independent newer checkpoint a fresh Mac cannot detect staleness. +Revocation/rotation does not yet exist. No second real Mac has been tested. diff --git a/experiments/secure_sync/device_pairing.py b/experiments/secure_sync/device_pairing.py new file mode 100644 index 00000000..1f3f7ec2 --- /dev/null +++ b/experiments/secure_sync/device_pairing.py @@ -0,0 +1,306 @@ +"""Offline, authenticated read-only device grant proof for ClosedRoom. + +No Google sign-in or Drive object authorizes a device. Enrollment needs a +manual comparison on BOTH devices and an owner public key authenticated from +a channel outside the untrusted transport. The operator-confirmation argument +is a proof boundary; the real UX, durable nonce registry and revocation +policy are not implemented. +""" +from __future__ import annotations + +import base64 +import binascii +import hashlib +import hmac +import json +import secrets +import time +from dataclasses import asdict, dataclass, field +from typing import Any + +from cryptography.exceptions import InvalidSignature, InvalidTag +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.kdf.hkdf import HKDF + +from vault_manifest import TrustedCheckpoint, public_key_bytes + +_REQUEST_FORMAT = "closedroom.device-pairing-request" +_GRANT_FORMAT = "closedroom.readonly-device-grant" +_VERSION = 1 +_MAX_REQUEST_BYTES = 2048 +_MAX_GRANT_BYTES = 4096 +_TTL_SECONDS = 300 +_SKEW_SECONDS = 60 +_REQUEST_FIELDS = {"format", "version", "vault_id", "request_id", "device_id", + "recipient_public", "issued_at", "expires_at", "permission"} +_GRANT_FIELDS = {"format", "version", "vault_id", "request_sha256", "request_id", + "device_id", "recipient_public", "owner_public", "permission", + "issued_at", "expires_at", "checkpoint", "sender_public", + "salt", "nonce", "ciphertext"} +_DOCUMENT_FIELDS = {"grant", "signature"} + + +class PairingError(ValueError): + """A stale, unapproved, unauthenticated or malformed device grant.""" + + +@dataclass +class PendingDevice: + request: bytes + recipient_private: X25519PrivateKey + consumed: bool = False # Proof only; production must persist this atomically. + + +@dataclass(frozen=True) +class ReadOnlyGrant: + vault_id: str + device_id: str + vault_key: bytes + checkpoint: TrustedCheckpoint + owner_public: bytes + permission: str = "read_only" + + +def _hex(value: Any, n: int) -> bool: + return isinstance(value, str) and len(value) == n and all(ch in "0123456789abcdef" for ch in value) + + +def _serialize(value: Any) -> bytes: + try: + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, + allow_nan=False).encode("utf-8") + except (ValueError, TypeError, OverflowError) as exc: + raise PairingError("Invalid pairing encoding") from exc + + +def _dedupe(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + data: dict[str, Any] = {} + for name, value in pairs: + if name in data: + raise PairingError("Duplicate pairing JSON field") + data[name] = value + return data + + +def _parse(raw: bytes, max_size: int) -> Any: + if not isinstance(raw, bytes) or not 0 < len(raw) <= max_size: + raise PairingError("Invalid pairing document size") + try: + return json.loads(raw.decode("utf-8"), object_pairs_hook=_dedupe, + parse_constant=lambda _: (_ for _ in ()).throw(PairingError("Invalid JSON constant"))) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise PairingError("Invalid pairing JSON") from exc + + +def _b64(value: Any, n: int) -> bytes: + if not isinstance(value, str): + raise PairingError("Invalid pairing data") + try: + result = base64.b64decode(value, validate=True) + except (ValueError, binascii.Error) as exc: + raise PairingError("Invalid pairing data") from exc + if len(result) != n: + raise PairingError("Invalid pairing data length") + return result + + +def _validate_checkpoint(checkpoint: TrustedCheckpoint, vault_id: str) -> None: + if (not isinstance(checkpoint, TrustedCheckpoint) or checkpoint.vault_id != vault_id + or type(checkpoint.revision) is not int or checkpoint.revision < 0 + or type(checkpoint.key_epoch) is not int or checkpoint.key_epoch < 1 + or not _hex(checkpoint.digest, 64)): + raise PairingError("Invalid trusted owner checkpoint") + + +def _request(raw: bytes, now: int) -> dict[str, Any]: + request = _parse(raw, _MAX_REQUEST_BYTES) + if not isinstance(request, dict) or set(request) != _REQUEST_FIELDS: + raise PairingError("Invalid pairing request schema") + if (request["format"] != _REQUEST_FORMAT or type(request["version"]) is not int + or request["version"] != _VERSION or request["permission"] != "read_only"): + raise PairingError("Unsupported pairing request") + if (not _hex(request["vault_id"], 32) or not _hex(request["request_id"], 32) + or not _hex(request["device_id"], 32)): + raise PairingError("Invalid pairing identity") + _b64(request["recipient_public"], 32) + issued, expiry = request["issued_at"], request["expires_at"] + if (type(now) is not int or now < 0 or type(issued) is not int + or type(expiry) is not int or issued < 0 + or not 0 < expiry - issued <= _TTL_SECONDS + or now < issued - _SKEW_SECONDS or now >= expiry): + raise PairingError("Expired or invalid device pairing request") + return request + + +def _sas(raw: bytes) -> str: + # Deterministic 8 digits derived from all canonical request properties. + digest = hashlib.sha256(b"ClosedRoom/pairing-display/v1\x00" + raw).digest() + return f"{int.from_bytes(digest[:4], 'big') % 100_000_000:08d}" + + +def create_device_request(vault_id: str, *, now: int | None = None) -> PendingDevice: + """Initiate on the new Mac; private X25519 key is never serialized.""" + if not _hex(vault_id, 32): + raise PairingError("Invalid vault id") + now = int(time.time()) if now is None else now + if type(now) is not int or now < 0: + raise PairingError("Invalid request time") + private = X25519PrivateKey.generate() + request = { + "format": _REQUEST_FORMAT, "version": _VERSION, "vault_id": vault_id, + "request_id": secrets.token_hex(16), "device_id": secrets.token_hex(16), + "recipient_public": base64.b64encode(private.public_key().public_bytes_raw()).decode("ascii"), + "issued_at": now, "expires_at": now + _TTL_SECONDS, "permission": "read_only", + } + return PendingDevice(_serialize(request), private) + + +def comparison_code(request: bytes, *, now: int | None = None) -> str: + """Display identically on both screens; user MUST compare out of band.""" + now = int(time.time()) if now is None else now + data = _request(request, now) + return _sas(_serialize(data)) + + +def _grant_key(private: X25519PrivateKey, peer: bytes, salt: bytes) -> bytes: + try: + shared = private.exchange(X25519PublicKey.from_public_bytes(peer)) + return HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, + info=b"ClosedRoom/readonly-pairing/v1").derive(shared) + except ValueError as exc: + raise PairingError("Invalid peer device public key") from exc + + +def authorize_readonly_device( + request: bytes, + owner_signer: Ed25519PrivateKey, + vault_key: bytes, + checkpoint: TrustedCheckpoint, + *, + manually_compared_code: str, + explicit_approval: bool, + now: int | None = None, +) -> bytes: + """On owner's Mac: REQUIRE manual two-screen SAS match and explicit approval. + + The API cannot prove a human compared screens; production UI must supply + this confirmation ONLY from a real user action, never auto-calculate it. + """ + now = int(time.time()) if now is None else now + data = _request(request, now) + vault_id = data["vault_id"] + if (type(explicit_approval) is not bool or not explicit_approval + or not isinstance(manually_compared_code, str) + or not hmac.compare_digest(manually_compared_code, _sas(_serialize(data)))): + raise PairingError("Manual pairing verification and approval required") + if not isinstance(vault_key, bytes) or len(vault_key) != 32: + raise PairingError("Invalid owner vault key") + if not isinstance(owner_signer, Ed25519PrivateKey): + raise PairingError("Owner signing authority required") + _validate_checkpoint(checkpoint, vault_id) + sender = X25519PrivateKey.generate() + salt, nonce = secrets.token_bytes(16), secrets.token_bytes(12) + header = { + "format": _GRANT_FORMAT, "version": _VERSION, "vault_id": vault_id, + "request_sha256": hashlib.sha256(_serialize(data)).hexdigest(), + "request_id": data["request_id"], "device_id": data["device_id"], + "recipient_public": data["recipient_public"], + "owner_public": base64.b64encode(public_key_bytes(owner_signer)).decode("ascii"), + "permission": "read_only", "issued_at": now, "expires_at": data["expires_at"], + "checkpoint": asdict(checkpoint), + "sender_public": base64.b64encode(sender.public_key().public_bytes_raw()).decode("ascii"), + "salt": base64.b64encode(salt).decode("ascii"), + "nonce": base64.b64encode(nonce).decode("ascii"), + } + cipher = AESGCM(_grant_key(sender, _b64(data["recipient_public"], 32), salt)).encrypt( + nonce, vault_key, _serialize(header)) + grant = {**header, "ciphertext": base64.b64encode(cipher).decode("ascii")} + signature = owner_signer.sign(_serialize(grant)) + result = _serialize({"grant": grant, "signature": base64.b64encode(signature).decode("ascii")}) + if len(result) > _MAX_GRANT_BYTES: + raise PairingError("Pairing grant too large") + return result + + +def receive_readonly_device( + pending: PendingDevice, + grant_document: bytes, + *, + independently_authenticated_owner: bytes, + now: int | None = None, + minimum_checkpoint: TrustedCheckpoint | None = None, +) -> ReadOnlyGrant: + """On new Mac: signed decryptable grant bound to OUR unique pending request. + + The authenticated owner public key MUST be obtained via independent + pairing/recovery proof, NOT accepted from the grant or Drive itself. + """ + now = int(time.time()) if now is None else now + if not isinstance(pending, PendingDevice) or pending.consumed: + raise PairingError("Pairing request already consumed or invalid") + request = _request(pending.request, now) + if (not isinstance(independently_authenticated_owner, bytes) + or len(independently_authenticated_owner) != 32): + raise PairingError("Authenticated owner public key required") + expected_public = pending.recipient_private.public_key().public_bytes_raw() + if not hmac.compare_digest(expected_public, _b64(request["recipient_public"], 32)): + raise PairingError("Pairing private key does not match request") + document = _parse(grant_document, _MAX_GRANT_BYTES) + if not isinstance(document, dict) or set(document) != _DOCUMENT_FIELDS: + raise PairingError("Invalid signed device grant") + grant = document["grant"] + if not isinstance(grant, dict) or set(grant) != _GRANT_FIELDS: + raise PairingError("Invalid device grant schema") + if (grant["format"] != _GRANT_FORMAT or type(grant["version"]) is not int + or grant["version"] != _VERSION or grant["permission"] != "read_only" + or grant["vault_id"] != request["vault_id"] + or grant["request_id"] != request["request_id"] + or grant["device_id"] != request["device_id"] + or grant["recipient_public"] != request["recipient_public"] + or grant["request_sha256"] != hashlib.sha256(_serialize(request)).hexdigest() + or type(grant["issued_at"]) is not int + or type(grant["expires_at"]) is not int + or grant["expires_at"] != request["expires_at"] + or not request["issued_at"] - _SKEW_SECONDS <= grant["issued_at"] < grant["expires_at"]): + raise PairingError("Unbound or expired device grant") + public = _b64(grant["owner_public"], 32) + if not hmac.compare_digest(public, independently_authenticated_owner): + raise PairingError("Untrusted owner signature") + signature = _b64(document["signature"], 64) + try: + Ed25519PublicKey.from_public_bytes(public).verify(signature, _serialize(grant)) + except (InvalidSignature, ValueError) as exc: + raise PairingError("Device grant signature failed") from exc + checkpoint_raw = grant["checkpoint"] + if not isinstance(checkpoint_raw, dict) or set(checkpoint_raw) != { + "vault_id", "revision", "digest", "key_epoch", + }: + raise PairingError("Invalid signed checkpoint") + try: + checkpoint = TrustedCheckpoint(**checkpoint_raw) + except (ValueError, TypeError) as exc: + raise PairingError("Invalid signed checkpoint") from exc + _validate_checkpoint(checkpoint, request["vault_id"]) + if minimum_checkpoint is not None: + _validate_checkpoint(minimum_checkpoint, request["vault_id"]) + if (checkpoint.revision < minimum_checkpoint.revision + or (checkpoint.revision == minimum_checkpoint.revision + and checkpoint.digest != minimum_checkpoint.digest) + or checkpoint.key_epoch < minimum_checkpoint.key_epoch): + raise PairingError("Old or conflicting signed checkpoint") + salt, nonce = _b64(grant["salt"], 16), _b64(grant["nonce"], 12) + sender_pub = _b64(grant["sender_public"], 32) + cipher = _b64(grant["ciphertext"], 48) + header = {k: v for k, v in grant.items() if k != "ciphertext"} + try: + secret = AESGCM(_grant_key(pending.recipient_private, sender_pub, salt)).decrypt( + nonce, cipher, _serialize(header)) + except InvalidTag as exc: + raise PairingError("Device grant authentication failed") from exc + if len(secret) != 32: + raise PairingError("Invalid decrypted vault key") + pending.consumed = True + return ReadOnlyGrant(request["vault_id"], request["device_id"], secret, checkpoint, public) diff --git a/experiments/secure_sync/recovery_capsule.py b/experiments/secure_sync/recovery_capsule.py new file mode 100644 index 00000000..88d8314d --- /dev/null +++ b/experiments/secure_sync/recovery_capsule.py @@ -0,0 +1,239 @@ +"""Offline, versioned recovery capsule for the experimental ClosedRoom vault. + +This protocol is deliberately separate from app storage and Drive transport. +A 256-bit, randomly generated recovery code must be held independently from +the encrypted capsule. No password-derived/low-entropy secrets are supported. +A recovered trusted checkpoint is only as fresh as the capsule the user has; +a compromised provider can replay an older authenticated capsule. +""" +from __future__ import annotations + +import base64 +import binascii +import hashlib +import json +import secrets +from dataclasses import asdict, dataclass +from typing import Any + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.kdf.hkdf import HKDF + +from vault_manifest import TrustedCheckpoint, public_key_bytes + +FORMAT = "closedroom.recovery-capsule" +VERSION = 1 +MAX_CAPSULE_BYTES = 4096 +_RECOVERY_INFO = b"ClosedRoom/independent-recovery/v1" +_FIELDS = {"format", "version", "vault_id", "salt", "nonce", "ciphertext"} +_PAYLOAD_FIELDS = {"vault_key", "owner_signer", "owner_public", "checkpoint"} + + +class RecoveryError(ValueError): + """The recovery material is invalid or cannot authenticate the capsule.""" + + +@dataclass(frozen=True) +class RecoveredVault: + vault_id: str + vault_key: bytes + owner_signer: Ed25519PrivateKey + owner_public: bytes + checkpoint: TrustedCheckpoint + + +def _id(value: Any) -> bool: + return (isinstance(value, str) and len(value) == 32 + and all(c in "0123456789abcdef" for c in value)) + + +def _canonical(value: Any) -> bytes: + try: + return json.dumps(value, sort_keys=True, separators=(",", ":"), + ensure_ascii=False, allow_nan=False).encode("utf-8") + except (TypeError, ValueError) as exc: + raise RecoveryError("Invalid recovery encoding") from exc + + +def _no_duplicates(items: list[tuple[str, Any]]) -> dict[str, Any]: + answer: dict[str, Any] = {} + for key, value in items: + if key in answer: + raise RecoveryError("Duplicate recovery field") + answer[key] = value + return answer + + +def _parse(value: bytes) -> Any: + try: + return json.loads(value.decode("utf-8"), object_pairs_hook=_no_duplicates, + parse_constant=lambda _: (_ for _ in ()).throw(RecoveryError("Invalid JSON constant"))) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise RecoveryError("Invalid recovery JSON") from exc + + +def _b64(value: Any, expected: int | None = None) -> bytes: + if not isinstance(value, str): + raise RecoveryError("Invalid recovery field") + try: + result = base64.b64decode(value, validate=True) + except (ValueError, binascii.Error) as exc: + raise RecoveryError("Invalid recovery field") from exc + if expected is not None and len(result) != expected: + raise RecoveryError("Invalid recovery field length") + return result + + +def _validate_checkpoint(value: TrustedCheckpoint, vault_id: str) -> None: + if (not isinstance(value, TrustedCheckpoint) or value.vault_id != vault_id + or type(value.revision) is not int or value.revision < 0 + or type(value.key_epoch) is not int or value.key_epoch < 1 + or not isinstance(value.digest, str) or len(value.digest) != 64 + or any(ch not in "0123456789abcdef" for ch in value.digest)): + raise RecoveryError("Invalid independently trusted checkpoint") + + +def generate_recovery_code() -> str: + """A one-time 256-bit recovery code; app must NOT persist its plaintext.""" + material = secrets.token_bytes(32) + return "CR1-" + base64.b32encode(material).decode("ascii").rstrip("=") + + +def _decode_code(value: str) -> bytes: + # Exact canonical spelling avoids accepting accidental weak passwords. + if not isinstance(value, str) or not value.startswith("CR1-"): + raise RecoveryError("Recovery code must be a randomly generated CR1 code") + encoded = value[4:] + if len(encoded) != 52 or any(ch not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" for ch in encoded): + raise RecoveryError("Invalid recovery code") + try: + raw = base64.b32decode(encoded + "====", casefold=False) + except (ValueError, binascii.Error) as exc: + raise RecoveryError("Invalid recovery code") from exc + if len(raw) != 32 or raw == bytes(32) or generate_code_from_bytes(raw) != value: + raise RecoveryError("Invalid or degenerate recovery code") + return raw + + +def generate_code_from_bytes(raw: bytes) -> str: + """Canonical encoding of 32 bytes; never call on low-entropy input.""" + if not isinstance(raw, bytes) or len(raw) != 32: + raise RecoveryError("Recovery material must be 256 bits") + return "CR1-" + base64.b32encode(raw).decode("ascii").rstrip("=") + + +def _key(secret: bytes, salt: bytes) -> bytes: + return HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, + info=_RECOVERY_INFO).derive(secret) + + +def create_recovery_capsule( + vault_id: str, + vault_key: bytes, + owner_signer: Ed25519PrivateKey, + checkpoint: TrustedCheckpoint, + recovery_code: str, +) -> bytes: + """Encrypt both independent identity secrets, never the recovery code.""" + if not _id(vault_id) or not isinstance(vault_key, bytes) or len(vault_key) != 32: + raise RecoveryError("Invalid vault") + if not isinstance(owner_signer, Ed25519PrivateKey): + raise RecoveryError("Invalid owner signing key") + _validate_checkpoint(checkpoint, vault_id) + secret = _decode_code(recovery_code) + signer_bytes = owner_signer.private_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PrivateFormat.Raw, + encryption_algorithm=serialization.NoEncryption(), + ) + payload = { + "vault_key": base64.b64encode(vault_key).decode("ascii"), + "owner_signer": base64.b64encode(signer_bytes).decode("ascii"), + "owner_public": base64.b64encode(public_key_bytes(owner_signer)).decode("ascii"), + "checkpoint": asdict(checkpoint), + } + salt, nonce = secrets.token_bytes(16), secrets.token_bytes(12) + header = { + "format": FORMAT, "version": VERSION, "vault_id": vault_id, + "salt": base64.b64encode(salt).decode("ascii"), + "nonce": base64.b64encode(nonce).decode("ascii"), + } + ciphertext = AESGCM(_key(secret, salt)).encrypt(nonce, _canonical(payload), _canonical(header)) + result = _canonical({**header, "ciphertext": base64.b64encode(ciphertext).decode("ascii")}) + if len(result) > MAX_CAPSULE_BYTES: + raise RecoveryError("Recovery capsule exceeded size budget") + return result + + +def open_recovery_capsule( + document: bytes, + recovery_code: str, + *, + expected_vault_id: str | None = None, + expected_owner_public: bytes | None = None, + minimum_checkpoint: TrustedCheckpoint | None = None, +) -> RecoveredVault: + """Restore offline identity only with independently held 256-bit code. + + expected_owner_public and minimum_checkpoint, if available from a trusted + non-Drive channel, prevent key substitution and stale-cap replay. With no + independent minimum checkpoint the provider can replay an older capsule. + """ + secret = _decode_code(recovery_code) + if not isinstance(document, bytes) or len(document) > MAX_CAPSULE_BYTES: + raise RecoveryError("Invalid recovery capsule size") + data = _parse(document) + if not isinstance(data, dict) or set(data) != _FIELDS: + raise RecoveryError("Invalid recovery capsule schema") + if data["format"] != FORMAT or type(data["version"]) is not int or data["version"] != VERSION: + raise RecoveryError("Unsupported recovery capsule version") + vault_id = data["vault_id"] + if not _id(vault_id) or (expected_vault_id is not None and vault_id != expected_vault_id): + raise RecoveryError("Recovery capsule vault mismatch") + if expected_owner_public is not None and (not isinstance(expected_owner_public, bytes) + or len(expected_owner_public) != 32): + raise RecoveryError("Invalid independently pinned owner") + salt, nonce = _b64(data["salt"], 16), _b64(data["nonce"], 12) + ciphertext = _b64(data["ciphertext"]) + if len(ciphertext) < 16 or len(ciphertext) > MAX_CAPSULE_BYTES: + raise RecoveryError("Invalid recovery ciphertext size") + header = {name: data[name] for name in _FIELDS - {"ciphertext"}} + try: + decrypted = AESGCM(_key(secret, salt)).decrypt(nonce, ciphertext, _canonical(header)) + except InvalidTag as exc: + raise RecoveryError("Recovery code or capsule authentication failed") from exc + payload = _parse(decrypted) + if not isinstance(payload, dict) or set(payload) != _PAYLOAD_FIELDS: + raise RecoveryError("Invalid recovery payload") + key = _b64(payload["vault_key"], 32) + signer_bytes = _b64(payload["owner_signer"], 32) + owner_public = _b64(payload["owner_public"], 32) + try: + signer = Ed25519PrivateKey.from_private_bytes(signer_bytes) + except ValueError as exc: + raise RecoveryError("Invalid recovered signing identity") from exc + if not secrets.compare_digest(public_key_bytes(signer), owner_public): + raise RecoveryError("Recovery owner identity mismatch") + if expected_owner_public is not None and not secrets.compare_digest(owner_public, expected_owner_public): + raise RecoveryError("Unexpected recovered owner") + checkpoint_raw = payload["checkpoint"] + if not isinstance(checkpoint_raw, dict) or set(checkpoint_raw) != { + "vault_id", "revision", "digest", "key_epoch", + }: + raise RecoveryError("Invalid recovery checkpoint") + try: + checkpoint = TrustedCheckpoint(**checkpoint_raw) + except (TypeError, ValueError) as exc: + raise RecoveryError("Invalid recovery checkpoint") from exc + _validate_checkpoint(checkpoint, vault_id) + if minimum_checkpoint is not None: + _validate_checkpoint(minimum_checkpoint, vault_id) + if (checkpoint.revision < minimum_checkpoint.revision + or (checkpoint.revision == minimum_checkpoint.revision + and checkpoint.digest != minimum_checkpoint.digest) + or checkpoint.key_epoch < minimum_checkpoint.key_epoch): + raise RecoveryError("Recovery capsule is stale or conflicts with trusted checkpoint") + return RecoveredVault(vault_id, key, signer, owner_public, checkpoint) diff --git a/experiments/secure_sync/test_offline_trust.py b/experiments/secure_sync/test_offline_trust.py new file mode 100644 index 00000000..ca4c1736 --- /dev/null +++ b/experiments/secure_sync/test_offline_trust.py @@ -0,0 +1,260 @@ +"""Security tests for offline recovery and owner-authorized read-only pairing. + +Synthetic keys only. Test state is in memory and is NOT durable cross-process +authorization, browser UX confirmation or a second physical Mac restore. +""" +from __future__ import annotations + +import base64 +import json +import unittest +from dataclasses import replace + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from device_pairing import ( + PairingError, authorize_readonly_device, comparison_code, + create_device_request, receive_readonly_device, +) +from recovery_capsule import ( + RecoveryError, create_recovery_capsule, generate_recovery_code, + open_recovery_capsule, +) +from secure_sync import open_snapshot, seal_snapshot, transcript_snapshot +from vault_manifest import ( + TrustedCheckpoint, generate_owner_signing_key, new_manifest, new_vault_id, + public_key_bytes, sign_manifest, verify_manifest, +) + +NOW = 1_795_000_000 + + +class OfflineTrustTests(unittest.TestCase): + def setUp(self) -> None: + self.vault_id = new_vault_id() + self.vault_key = bytes(range(32)) + self.owner = generate_owner_signing_key() + self.owner_pub = public_key_bytes(self.owner) + self.checkpoint = verify_manifest( + sign_manifest( + new_manifest(vault_id=self.vault_id, revision=0, previous=None), + self.owner, + ), + self.owner_pub, + ) + self.recovery_code = generate_recovery_code() + self.capsule = create_recovery_capsule( + self.vault_id, self.vault_key, self.owner, + self.checkpoint, self.recovery_code, + ) + + def _pending(self): + return create_device_request(self.vault_id, now=NOW) + + def _approve(self, pending, *, now=NOW, owner=None, checkpoint=None, code=None, approved=True): + if code is None: + code = comparison_code(pending.request, now=now) + return authorize_readonly_device( + pending.request, owner or self.owner, self.vault_key, + checkpoint or self.checkpoint, + manually_compared_code=code, explicit_approval=approved, now=now, + ) + + def test_independent_recovery_restores_owner_vault_and_checkpoint(self): + restored = open_recovery_capsule( + self.capsule, self.recovery_code, + expected_vault_id=self.vault_id, + expected_owner_public=self.owner_pub, + minimum_checkpoint=self.checkpoint, + ) + self.assertEqual(restored.vault_id, self.vault_id) + self.assertEqual(restored.vault_key, self.vault_key) + self.assertEqual(restored.owner_public, self.owner_pub) + self.assertEqual(restored.checkpoint, self.checkpoint) + self.assertEqual(public_key_bytes(restored.owner_signer), self.owner_pub) + # Signing identity remains usable without original Mac/Keychain. + signature = restored.owner_signer.sign(b"synthetic challenge") + restored.owner_signer.public_key().verify(signature, b"synthetic challenge") + + def test_recovery_secret_is_independent_and_never_in_capsule(self): + self.assertTrue(self.recovery_code.startswith("CR1-")) + self.assertEqual(len(self.recovery_code), 56) + self.assertNotIn(self.recovery_code.encode(), self.capsule) + self.assertNotIn(base64.b64encode(self.vault_key), self.capsule) + self.assertNotIn(base64.b64encode(self.owner.private_bytes_raw()), self.capsule) + self.assertNotEqual(generate_recovery_code(), self.recovery_code) + + def test_wrong_recovery_code_or_low_entropy_input_fails(self): + with self.assertRaises(RecoveryError): + open_recovery_capsule(self.capsule, generate_recovery_code()) + for weak in ("password", "CR1-" + "A" * 51, "CR1-" + "!" * 52, "", "CR1-" + "A" * 52): + with self.subTest(weak=weak[:9]): + with self.assertRaises(RecoveryError): + open_recovery_capsule(self.capsule, weak) + + def test_recovery_tampering_and_unknown_schema_fail_closed(self): + document = json.loads(self.capsule) + for name, value in ( + ("version", 2), + ("vault_id", "f" * 32), + ("salt", base64.b64encode(bytes(16)).decode()), + ("nonce", base64.b64encode(bytes(12)).decode()), + ): + tampered = dict(document) + tampered[name] = value + with self.subTest(name=name), self.assertRaises(RecoveryError): + open_recovery_capsule(json.dumps(tampered).encode(), self.recovery_code) + with self.assertRaises(RecoveryError): + open_recovery_capsule(b'{"format":1,"format":2}', self.recovery_code) + with self.assertRaises(RecoveryError): + open_recovery_capsule(self.capsule + b"x" * 4096, self.recovery_code) + + def test_recovery_missing_pin_and_checkpoint_freshness_are_explicit(self): + with self.assertRaises(RecoveryError): + open_recovery_capsule( + self.capsule, self.recovery_code, + expected_vault_id="e" * 32, + ) + with self.assertRaises(RecoveryError): + open_recovery_capsule( + self.capsule, self.recovery_code, + expected_owner_public=public_key_bytes(generate_owner_signing_key()), + ) + newer = TrustedCheckpoint( + self.vault_id, self.checkpoint.revision + 1, + "a" * 64, self.checkpoint.key_epoch, + ) + with self.assertRaises(RecoveryError): + open_recovery_capsule(self.capsule, self.recovery_code, minimum_checkpoint=newer) + conflicting = replace(self.checkpoint, digest="b" * 64) + with self.assertRaises(RecoveryError): + open_recovery_capsule(self.capsule, self.recovery_code, minimum_checkpoint=conflicting) + + def test_recovery_rejects_bad_owner_and_checkpoint_before_encrypting(self): + with self.assertRaises(RecoveryError): + create_recovery_capsule( + self.vault_id, self.vault_key, self.owner, + replace(self.checkpoint, vault_id="f" * 32), self.recovery_code, + ) + with self.assertRaises(RecoveryError): + create_recovery_capsule( + self.vault_id, b"short", self.owner, self.checkpoint, self.recovery_code, + ) + + def test_pairing_returns_only_readonly_key_and_verified_checkpoint(self): + pending = self._pending() + displayed_new_mac = comparison_code(pending.request, now=NOW) + displayed_owner = comparison_code(pending.request, now=NOW) + self.assertEqual(displayed_new_mac, displayed_owner) + self.assertEqual(len(displayed_new_mac), 8) + approval = self._approve(pending, code=displayed_owner) + result = receive_readonly_device( + pending, approval, independently_authenticated_owner=self.owner_pub, now=NOW, + ) + self.assertEqual(result.permission, "read_only") + self.assertEqual(result.vault_key, self.vault_key) + self.assertEqual(result.owner_public, self.owner_pub) + self.assertEqual(result.checkpoint, self.checkpoint) + snapshot = transcript_snapshot({"id": "synthetic-1", "text": "Private example"}) + envelope = seal_snapshot(snapshot, self.vault_key) + self.assertEqual(open_snapshot(envelope, result.vault_key), snapshot) + # Grant never includes owner signing secret or plaintext vault key. + self.assertNotIn(base64.b64encode(self.vault_key), approval) + self.assertNotIn(base64.b64encode(self.owner.private_bytes_raw()), approval) + + def test_pairing_requires_manual_comparison_and_explicit_permission(self): + pending = self._pending() + for code, approved in (("", True), ("00000000", True), ("", False)): + with self.subTest(code=code, approved=approved), self.assertRaises(PairingError): + self._approve(pending, code=code, approved=approved) + with self.assertRaises(PairingError): + self._approve(pending, approved=False) + + def test_pairing_expires_and_rejects_future_or_modified_requests(self): + pending = self._pending() + with self.assertRaises(PairingError): + comparison_code(pending.request, now=NOW + 301) + with self.assertRaises(PairingError): + self._approve(pending, now=NOW + 301, code="12345678") + approval = self._approve(pending) + with self.assertRaises(PairingError): + receive_readonly_device(pending, approval, independently_authenticated_owner=self.owner_pub, now=NOW + 301) + tampered = json.loads(pending.request) + tampered["expires_at"] += 3600 + with self.assertRaises(PairingError): + comparison_code(json.dumps(tampered).encode(), now=NOW) + tampered = json.loads(pending.request) + tampered["issued_at"] = NOW + 100 + with self.assertRaises(PairingError): + comparison_code(json.dumps(tampered).encode(), now=NOW) + + def test_pairing_wrong_owner_key_signer_recipient_or_nonce_fails(self): + pending = self._pending() + approval = self._approve(pending) + with self.assertRaises(PairingError): + receive_readonly_device( + pending, approval, + independently_authenticated_owner=public_key_bytes(generate_owner_signing_key()), now=NOW, + ) + impostor = self._approve(pending, owner=generate_owner_signing_key()) + with self.assertRaises(PairingError): + receive_readonly_device(pending, impostor, independently_authenticated_owner=self.owner_pub, now=NOW) + different_request = self._pending() + with self.assertRaises(PairingError): + receive_readonly_device(different_request, approval, independently_authenticated_owner=self.owner_pub, now=NOW) + tampered = json.loads(approval) + tampered["grant"]["device_id"] = "f" * 32 + with self.assertRaises(PairingError): + receive_readonly_device(pending, json.dumps(tampered).encode(), independently_authenticated_owner=self.owner_pub, now=NOW) + tampered = json.loads(approval) + tampered["grant"]["ciphertext"] = base64.b64encode(b"x" * 48).decode() + with self.assertRaises(PairingError): + receive_readonly_device(pending, json.dumps(tampered).encode(), independently_authenticated_owner=self.owner_pub, now=NOW) + + def test_pairing_replay_is_rejected_in_existing_pending_session(self): + pending = self._pending() + approval = self._approve(pending) + receive_readonly_device(pending, approval, independently_authenticated_owner=self.owner_pub, now=NOW) + with self.assertRaises(PairingError): + receive_readonly_device(pending, approval, independently_authenticated_owner=self.owner_pub, now=NOW) + + def test_pairing_stale_or_conflicting_checkpoint_is_rejected(self): + pending = self._pending() + approval = self._approve(pending) + newer = replace(self.checkpoint, revision=1, digest="b" * 64) + with self.assertRaises(PairingError): + receive_readonly_device(pending, approval, independently_authenticated_owner=self.owner_pub, now=NOW, minimum_checkpoint=newer) + conflicting = replace(self.checkpoint, digest="c" * 64) + with self.assertRaises(PairingError): + receive_readonly_device(pending, approval, independently_authenticated_owner=self.owner_pub, now=NOW, minimum_checkpoint=conflicting) + + def test_recovery_then_owner_authorization_without_original_device(self): + # Simulated second Mac recovers owner secrets from the capsule + code. + restored = open_recovery_capsule(self.capsule, self.recovery_code) + pending = self._pending() + grant = authorize_readonly_device( + pending.request, restored.owner_signer, restored.vault_key, + restored.checkpoint, manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + accepted = receive_readonly_device( + pending, grant, independently_authenticated_owner=restored.owner_public, now=NOW, + ) + self.assertEqual(accepted.vault_key, restored.vault_key) + + def test_pairing_rejects_schema_duplicates_and_unpinned_owner(self): + pending = self._pending() + with self.assertRaises(PairingError): + comparison_code(b'{"format":1,"format":2}', now=NOW) + approval = self._approve(pending) + with self.assertRaises(PairingError): + receive_readonly_device(pending, approval, independently_authenticated_owner=b"", now=NOW) + corrupted = json.loads(approval) + corrupted["grant"]["permission"] = "read_write" + with self.assertRaises(PairingError): + receive_readonly_device(pending, json.dumps(corrupted).encode(), + independently_authenticated_owner=self.owner_pub, now=NOW) + + +if __name__ == "__main__": + unittest.main() From 05eeca1e6af464c7e1f043ad318282e596116031 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 10:22:41 +0100 Subject: [PATCH 14/24] docs(sync): record offline recovery and pairing security Mac PASS with residual gates --- docs/workstreams/secure-sync-google-drive.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 946d634d..fefeebd0 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -44,7 +44,7 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model | --- | --- | --- | --- | | SYNC-0 | Threat model, consent boundaries, pairing/recovery flow; no implicit remote fallback | DONE design | Review with canonical storage owners | | SYNC-1 | Prove a portable AES-256-GCM authenticated transcript-only object with no raw export of paths/provider credentials | DONE experimental | Synthetic round-trip, wrong key, tamper, invalid schema/size, plaintext absence (6 local tests) | -| SYNC-2 | Production vault identity/Keychain and independent recovery materials, crypto dependency+locked build, signed manifest/head/anti-rollback | ACTIVE (offline proof only) | Clean/compromised-device, key loss, replay, rotation, crash and security review | +| SYNC-2 | Production vault identity/Keychain, independent recovery and signed manifest/head | ACTIVE (offline proof PASS only) | Durable anti-replay, authenticated pairing UX, key rotation/revocation, real second Mac recovery, review | | SYNC-3 | Explicit OAuth `drive.appdata` and Drive read/write adapter, offline outbox, receipts and bounded incremental list | BLOCKED on SYNC-2 | Fake transport faults + real isolated Google test account, no sensitive user meetings | | SYNC-4 | Read-only canonical projection and isolated second-Mac cache; pairing/permissions/revoke UX | BLOCKED on SYNC-2/3 | Second physical Mac with source powered off, cache offline, mutual QR verification, revoke | | SYNC-5 | Integrated Settings/Meeting status, complete privacy copy, accessible UX and correct cleanup | BLOCKED on SYNC-4 | Automated E2E FULL_MEDIA; WKWebView/Keychain target Mac; security/recovery audit | @@ -66,5 +66,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model ### Current checkpoint - Source branch from `dev`; draft PR #225. The Keychain experiment and packaged-app synthetic security smoke are **implemented and qualified at the scope above**; product sync is still OFF. No GCS/Drive transmission or real user meeting data transferred. -- SYNC-2 offline candidate: `recovery_capsule.py` (random independent 256-bit recovery code, authenticated capsule preserving vault key/owner signing key/checkpoint); `device_pairing.py` (5-minute X25519 read-only grant, Ed25519 owner proof, manual two-screen comparison required and independent owner pin). Synthetic adversarial cases in `test_offline_trust.py`. Not product-enabled. +- SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. - Still SYNC-2 ACTIVE: durable replay/CAS, signed revoke+future-key rotation, authenticated owner-public bootstrap, independent anti-rollback checkpoint, recovery-code lifecycle/UI and real two-Mac restore; no active Drive or production Keychain lifecycle. Previous ad-hoc GUI gate remains limited to the earlier exact executable SHA. From f03e283f389930d96c0bf62a7f5cc05c878a8f59 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 12:25:00 +0100 Subject: [PATCH 15/24] spike(sync): Keychain-anchored durable owner ledger and future-key revocation --- docs/workstreams/secure-sync-google-drive.md | 3 +- experiments/secure_sync/README.md | 34 ++ experiments/secure_sync/owner_ledger.py | 439 +++++++++++++++++++ experiments/secure_sync/test_owner_ledger.py | 279 ++++++++++++ experiments/secure_sync/vault_keychain.py | 35 ++ 5 files changed, 789 insertions(+), 1 deletion(-) create mode 100644 experiments/secure_sync/owner_ledger.py create mode 100644 experiments/secure_sync/test_owner_ledger.py diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index fefeebd0..2de332ba 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -67,4 +67,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Source branch from `dev`; draft PR #225. The Keychain experiment and packaged-app synthetic security smoke are **implemented and qualified at the scope above**; product sync is still OFF. No GCS/Drive transmission or real user meeting data transferred. - SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. -- Still SYNC-2 ACTIVE: durable replay/CAS, signed revoke+future-key rotation, authenticated owner-public bootstrap, independent anti-rollback checkpoint, recovery-code lifecycle/UI and real two-Mac restore; no active Drive or production Keychain lifecycle. Previous ad-hoc GUI gate remains limited to the earlier exact executable SHA. +- SYNC-2 next offline candidate: `owner_ledger.py` uses SQLite FULL + `BEGIN IMMEDIATE` to serialize a signed public device registry, persisted enrollment nonces, and separate Keychain high-water digest. Failure between SQLite commit and Keychain update **freezes** vault; no auto reconciliation. Signed manifest key_epoch advances on revocation, fresh **independent** epoch secret stored in Keychain before commit; survivors require new grant, revoked device retains old read access. New synthetic regression suite `test_owner_ledger.py`; exact Mac run evidence pending. +- Still SYNC-2 ACTIVE: recovery from frozen split-commit (no silent fix), out-of-band checkpoint freshness, owner public-key bootstrap, recovery-code update after rotation, persistent recipient-side trust state, fully authenticated two-screen GUI, real second Mac test, secure SDK/model lifecycle integration. No Drive/OAuth, production Keychain integration, user data sync or release claims. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index e03f56e8..bbd6f0c0 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -91,3 +91,37 @@ crash-safe transaction handling, loss/restore and key compromise reviews. A Drive provider could replay a previously valid encrypted recovery capsule: without an independent newer checkpoint a fresh Mac cannot detect staleness. Revocation/rotation does not yet exist. No second real Mac has been tested. + +## SYNC-2 durable owner ledger and future-key revocation (offline experiment) + +`owner_ledger.py` extends the existing experimental `vault_keychain.py` +with a **public, Ed25519-signed device/epoch registry** in a mode-0600 SQLite +file (FULL-synchronous `BEGIN IMMEDIATE` serialized writes). A separate +high-water digest/revision lives in the macOS Keychain, NOT in that SQLite DB. +Every read/operation verifies the owner's independently pinned public key, +signed registry document, schema, and exact Keychain high-water anchor. + +- A changed/rolled-back/vanished DB or Keychain anchor **fails closed**. + SQLite and Keychain cannot commit atomically; a crash between DB commit + and anchor update deliberately freezes reads. No silent repair from either + untrusted side, no automatic data loss or remote fallback. +- Owner enrollment grants are issued only after the existing human-approval + protocol, consume a request ID **durably** and record device/epoch status. + Writers must share the canonical database path to get SQLite serialization. + This does NOT replace trusted cross-device pairing UI or provider trust. +- Signed manifest epoch must advance exactly once for revocation. The owner + creates a fresh random, independent 256-bit epoch key *in Keychain before* + advancing the ledger; the target becomes `revoked` and surviving devices + `needs_repair`. They require fresh authenticated grants. A revoked device + may retain old ciphertext/plaintext; there is no remote erase. +- Keychain write failure before SQL commit leaves old epoch current (possible + orphan secret); failure after SQL commit before the high-water write freezes + the vault. Crash recovery and cleanup need a separate manual protocol. +- The persistent ledger has no secret material and uses an **experimental** + Keychain adapter / fake backend in unit tests. No installation into the + production app, Developer ID signature, independent trusted head, actual + physical device provisioning, persisted recipient-side consumed grants, + two-phase cloud publish, Google Drive or automatic rollout. + +Run the isolated `test_owner_ledger.py` suite via the existing +`unittest discover -s experiments/secure_sync` Mac CI selector. diff --git a/experiments/secure_sync/owner_ledger.py b/experiments/secure_sync/owner_ledger.py new file mode 100644 index 00000000..f766932e --- /dev/null +++ b/experiments/secure_sync/owner_ledger.py @@ -0,0 +1,439 @@ +"""Experimental offline owner ledger: SQLite CAS + separate Keychain high-water anchor. + +This is a prototype owner for *public* signed device/epoch state only. Secret +epoch keys remain in the macOS Keychain prototype; recording/catalog stores +and installed ClosedRoom are not touched. + +SQLite transactions serialize writers using ONE canonical local database path. +Keychain and SQLite cannot commit atomically. Any mid-commit disagreement +intentionally freezes the ledger until a separately authenticated recovery +workflow is designed. Never automatically repair by trusting either copy. +""" +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import os +import secrets +import sqlite3 +import stat +from dataclasses import asdict +from pathlib import Path +from typing import Any + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey + +from device_pairing import authorize_readonly_device +from vault_keychain import MacKeychainVaultKeys +from vault_manifest import TrustedCheckpoint, public_key_bytes, verify_manifest + +FORMAT = "closedroom.offline-owner-ledger" +VERSION = 1 +MAX_SIGNED_BYTES = 256 * 1024 +MAX_DEVICES = 128 +MAX_REQUESTS = 4096 +_STATE_FIELDS = { + "format", "version", "vault_id", "revision", "previous", "owner_public", + "key_epoch", "key_sha256", "manifest", "devices", "used_request_ids", +} +_RECORD_FIELDS = {"state", "signature"} +_ANCHOR_FIELDS = {"vault_id", "revision", "digest"} + + +class LedgerError(RuntimeError): + """An owner-ledger integrity, authorization or crash-safety gate failed.""" + + +def _hex(value: Any, size: int) -> bool: + return (isinstance(value, str) and len(value) == size + and all(ch in "0123456789abcdef" for ch in value)) + + +def _json(value: Any) -> bytes: + try: + return json.dumps(value, sort_keys=True, separators=(",", ":"), + ensure_ascii=False, allow_nan=False).encode("utf-8") + except (ValueError, TypeError) as exc: + raise LedgerError("Invalid owner ledger encoding") from exc + + +def _no_duplicates(items: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in items: + if key in result: + raise LedgerError("Duplicate owner ledger field") + result[key] = value + return result + + +def _parse(raw: bytes) -> Any: + if not isinstance(raw, bytes) or len(raw) > MAX_SIGNED_BYTES: + raise LedgerError("Owner ledger document exceeds limit") + try: + return json.loads(raw.decode("utf-8"), object_pairs_hook=_no_duplicates, + parse_constant=lambda _: (_ for _ in ()).throw( + LedgerError("Invalid JSON constant"))) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise LedgerError("Invalid owner ledger JSON") from exc + + +def _cp(raw: Any, vault_id: str) -> TrustedCheckpoint: + if not isinstance(raw, dict) or set(raw) != { + "vault_id", "revision", "digest", "key_epoch", + }: + raise LedgerError("Invalid manifest checkpoint fields") + try: + checkpoint = TrustedCheckpoint(**raw) + except (TypeError, ValueError) as exc: + raise LedgerError("Invalid manifest checkpoint") from exc + if (checkpoint.vault_id != vault_id + or type(checkpoint.revision) is not int or checkpoint.revision < 0 + or type(checkpoint.key_epoch) is not int or checkpoint.key_epoch < 1 + or not _hex(checkpoint.digest, 64)): + raise LedgerError("Invalid manifest checkpoint") + return checkpoint + + +class OwnerLedger: + """Local offline experiment; not a production sync/cache persistence owner.""" + + def __init__( + self, + path: Path, + vault_id: str, + authenticated_owner_public: bytes, + keys: MacKeychainVaultKeys, + ) -> None: + if not _hex(vault_id, 32): + raise LedgerError("Invalid vault identifier") + if not isinstance(authenticated_owner_public, bytes) or len(authenticated_owner_public) != 32: + raise LedgerError("Owner key must be authenticated outside storage") + self.path = Path(path).absolute() + self.vault_id = vault_id + self.owner_public = authenticated_owner_public + self.keys = keys + if not self.path.parent.is_dir() or self.path.is_symlink(): + raise LedgerError("Missing safe owner ledger directory") + # Only open a private file. No automatic creation of storage folders. + if self.path.exists(): + self._check_file() + + def _check_file(self) -> None: + try: + item = self.path.lstat() + except OSError as exc: + raise LedgerError("Owner ledger cannot be inspected") from exc + if (not stat.S_ISREG(item.st_mode) or (item.st_mode & 0o077) + or item.st_uid != os.getuid() or self.path.is_symlink()): + raise LedgerError("Owner ledger file must be owned, regular and mode 0600") + + def _connect(self) -> sqlite3.Connection: + if not self.path.exists(): + try: + fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | + getattr(os, "O_NOFOLLOW", 0), 0o600) + os.close(fd) + except FileExistsError: + pass + except OSError as exc: + raise LedgerError("Could not create private owner ledger") from exc + self._check_file() + db = sqlite3.connect(str(self.path), timeout=5, isolation_level=None) + try: + db.execute("PRAGMA journal_mode=DELETE") + db.execute("PRAGMA synchronous=FULL") + db.execute("PRAGMA busy_timeout=5000") + db.execute( + "CREATE TABLE IF NOT EXISTS state " + "(vault_id TEXT PRIMARY KEY, document BLOB NOT NULL)" + ) + return db + except BaseException: + db.close() + raise + + def _read_anchor(self) -> dict[str, Any] | None: + text = self.keys.read_ledger_anchor(self.vault_id) + if text is None: + return None + if not isinstance(text, str) or len(text) > 256: + raise LedgerError("Invalid trusted Keychain anchor") + try: + data = _parse(text.encode("ascii")) + except UnicodeEncodeError as exc: + raise LedgerError("Invalid trusted Keychain anchor") from exc + if (not isinstance(data, dict) or set(data) != _ANCHOR_FIELDS + or data["vault_id"] != self.vault_id + or type(data["revision"]) is not int or data["revision"] < 0 + or not _hex(data["digest"], 64)): + raise LedgerError("Corrupt trusted Keychain anchor") + return data + + def _write_anchor(self, revision: int, digest: str) -> None: + self.keys.write_ledger_anchor( + self.vault_id, + _json({"vault_id": self.vault_id, "revision": revision, + "digest": digest}).decode("ascii"), + ) + if self._read_anchor() != { + "vault_id": self.vault_id, "revision": revision, "digest": digest, + }: + raise LedgerError("Keychain anchor readback mismatch") + + def _validate_state(self, state: Any) -> None: + if not isinstance(state, dict) or set(state) != _STATE_FIELDS: + raise LedgerError("Unrecognized owner ledger schema") + if (state["format"] != FORMAT or type(state["version"]) is not int + or state["version"] != VERSION or state["vault_id"] != self.vault_id + or type(state["revision"]) is not int or state["revision"] < 0 + or not _hex(state["key_sha256"], 64) + or type(state["key_epoch"]) is not int or state["key_epoch"] < 1): + raise LedgerError("Invalid owner ledger identity/epoch") + expected = base64.b64encode(self.owner_public).decode("ascii") + if not isinstance(state["owner_public"], str) or not hmac.compare_digest( + state["owner_public"], expected, + ): + raise LedgerError("Unexpected owner ledger signer") + if ((state["revision"] == 0 and state["previous"] is not None) + or (state["revision"] > 0 and not _hex(state["previous"], 64))): + raise LedgerError("Invalid owner ledger chain") + checkpoint = _cp(state["manifest"], self.vault_id) + if checkpoint.key_epoch != state["key_epoch"]: + raise LedgerError("Ledger epoch disagrees with signed manifest") + devices = state["devices"] + used = state["used_request_ids"] + if not isinstance(devices, dict) or len(devices) > MAX_DEVICES: + raise LedgerError("Too many registered devices") + if not isinstance(used, list) or len(used) > MAX_REQUESTS: + raise LedgerError("Too many used enrollment requests") + if not all(_hex(x, 32) for x in used) or len(set(used)) != len(used): + raise LedgerError("Invalid duplicate enrollment nonce") + for device_id, details in devices.items(): + if (not _hex(device_id, 32) or not isinstance(details, dict) + or set(details) != {"status", "epoch"} + or details["status"] not in ("active", "needs_repair", "revoked") + or type(details["epoch"]) is not int + or details["epoch"] < 1 + or details["epoch"] > state["key_epoch"]): + raise LedgerError("Invalid registered device") + + def _signed(self, state: dict[str, Any], signer: Ed25519PrivateKey) -> bytes: + if (not isinstance(signer, Ed25519PrivateKey) + or not hmac.compare_digest(public_key_bytes(signer), self.owner_public)): + raise LedgerError("Authenticated owner signing authority required") + self._validate_state(state) + body = _json(state) + signature = signer.sign(body) + document = _json({ + "state": state, "signature": base64.b64encode(signature).decode("ascii"), + }) + if len(document) > MAX_SIGNED_BYTES: + raise LedgerError("Signed ledger exceeds size budget") + return document + + def _checked(self, db: sqlite3.Connection) -> tuple[dict[str, Any], str]: + row = db.execute("SELECT document FROM state WHERE vault_id = ?", (self.vault_id,)).fetchone() + anchor = self._read_anchor() + if row is None or anchor is None: + raise LedgerError("Missing ledger or trusted anchor: explicit recovery required") + document = bytes(row[0]) + digest = hashlib.sha256(document).hexdigest() + record = _parse(document) + if not isinstance(record, dict) or set(record) != _RECORD_FIELDS: + raise LedgerError("Invalid signed owner ledger document") + state = record["state"] + self._validate_state(state) + try: + signature = base64.b64decode(record["signature"], validate=True) + if len(signature) != 64: + raise ValueError("wrong signature length") + Ed25519PublicKey.from_public_bytes(self.owner_public).verify( + signature, _json(state), + ) + except (ValueError, InvalidSignature, TypeError) as exc: + raise LedgerError("Owner ledger signature does not verify") from exc + if anchor != { + "vault_id": self.vault_id, "revision": state["revision"], + "digest": digest, + }: + raise LedgerError("SQLite/Keychain high-water mismatch: frozen until recovery") + if not hmac.compare_digest(self.keys.load_pinned_owner(self.vault_id), self.owner_public): + raise LedgerError("Trusted owner pin mismatch") + return state, digest + + def bootstrap(self, owner_signer: Ed25519PrivateKey, signed_genesis: bytes) -> None: + """Initialize from a locally authenticated signed genesis only once.""" + if not isinstance(owner_signer, Ed25519PrivateKey) or not hmac.compare_digest( + public_key_bytes(owner_signer), self.owner_public, + ): + raise LedgerError("Authenticated owner required for bootstrap") + genesis = verify_manifest(signed_genesis, self.owner_public) + if (genesis.vault_id != self.vault_id or genesis.revision != 0 + or genesis.key_epoch != 1): + raise LedgerError("Invalid initial manifest") + # Only the previously created local Keychain master secret can initialize. + key = self.keys.load_epoch_key(self.vault_id, 1) + self.keys.pin_authenticated_owner(self.vault_id, self.owner_public) + state = { + "format": FORMAT, "version": VERSION, "vault_id": self.vault_id, + "revision": 0, "previous": None, + "owner_public": base64.b64encode(self.owner_public).decode("ascii"), + "key_epoch": 1, "key_sha256": hashlib.sha256(key).hexdigest(), + "manifest": asdict(genesis), "devices": {}, "used_request_ids": [], + } + document = self._signed(state, owner_signer) + digest = hashlib.sha256(document).hexdigest() + db = self._connect() + try: + db.execute("BEGIN IMMEDIATE") + if (db.execute("SELECT 1 FROM state WHERE vault_id = ?", + (self.vault_id,)).fetchone() or self._read_anchor() is not None): + raise LedgerError("Ledger is already initialized or ambiguous") + db.execute("INSERT INTO state (vault_id, document) VALUES (?, ?)", + (self.vault_id, document)) + db.commit() + self._write_anchor(0, digest) + except BaseException: + if db.in_transaction: + db.rollback() + raise + finally: + db.close() + + def read(self) -> dict[str, Any]: + """Authenticate all state against owner's pin and separate Keychain anchor.""" + db = self._connect() + try: + db.execute("BEGIN IMMEDIATE") + state, _ = self._checked(db) + db.commit() + return state + except BaseException: + if db.in_transaction: + db.rollback() + raise + finally: + db.close() + + def _persist( + self, db: sqlite3.Connection, old: dict[str, Any], + old_digest: str, new: dict[str, Any], + signer: Ed25519PrivateKey, + ) -> None: + if not db.in_transaction: + raise LedgerError("Ledger must be locked before advancing") + new["revision"] = old["revision"] + 1 + new["previous"] = old_digest + doc = self._signed(new, signer) + digest = hashlib.sha256(doc).hexdigest() + result = db.execute( + "UPDATE state SET document = ? WHERE vault_id = ? AND document = ?", + (doc, self.vault_id, db.execute( + "SELECT document FROM state WHERE vault_id = ?", (self.vault_id,), + ).fetchone()[0]), + ) + if result.rowcount != 1: + raise LedgerError("Concurrent owner ledger update refused") + # COMMIT is durable before attempting the separate Keychain anchor. + # A crash/failure after this point leaves ledger frozen, NEVER silently + # succeeding or rolling back to an older trusted head. + db.commit() + self._write_anchor(new["revision"], digest) + + def authorize_and_record( + self, + request: bytes, + signer: Ed25519PrivateKey, + *, + manually_compared_code: str, + explicit_approval: bool, + now: int | None = None, + ) -> bytes: + """Issue one read-only grant and durably consume request before return.""" + db = self._connect() + try: + db.execute("BEGIN IMMEDIATE") + old, digest = self._checked(db) + if len(old["used_request_ids"]) >= MAX_REQUESTS or len(old["devices"]) >= MAX_DEVICES: + raise LedgerError("Owner device/nonce registry capacity reached") + checkpoint = _cp(old["manifest"], self.vault_id) + key = self.keys.load_epoch_key(self.vault_id, old["key_epoch"]) + if hashlib.sha256(key).hexdigest() != old["key_sha256"]: + raise LedgerError("Local epoch key does not match trusted state") + # The signing/approval owner is the canonical pairing proof. + grant = authorize_readonly_device( + request, signer, key, checkpoint, + manually_compared_code=manually_compared_code, + explicit_approval=explicit_approval, now=now, + ) + doc = _parse(grant) + item = doc["grant"] + if item["vault_id"] != self.vault_id: + raise LedgerError("Attempted enrollment into another vault") + request_id, device_id = item["request_id"], item["device_id"] + if not _hex(request_id, 32) or not _hex(device_id, 32): + raise LedgerError("Invalid enrollment identifiers") + if request_id in old["used_request_ids"] or device_id in old["devices"]: + raise LedgerError("Repeated enrollment request or device") + new = json.loads(_json(old)) + new["used_request_ids"].append(request_id) + new["devices"][device_id] = {"status": "active", "epoch": old["key_epoch"]} + self._persist(db, old, digest, new, signer) + return grant + except BaseException: + if db.in_transaction: + db.rollback() + raise + finally: + db.close() + + def revoke_and_rotate( + self, device_id: str, signer: Ed25519PrivateKey, + next_signed_manifest: bytes, + ) -> bytes: + """Revoke and create a NEW independent epoch key in Keychain first. + + Remaining devices require explicit fresh grants for the new epoch. + This does not remotely erase their previously decrypted ciphertext. + Returns the fresh key to the local owner only after ledger+anchor proof. + """ + if not _hex(device_id, 32): + raise LedgerError("Invalid revoked device identity") + db = self._connect() + try: + db.execute("BEGIN IMMEDIATE") + old, digest = self._checked(db) + entry = old["devices"].get(device_id) + if entry is None or entry["status"] == "revoked": + raise LedgerError("Device is not currently enrolled") + current = _cp(old["manifest"], self.vault_id) + advanced = verify_manifest( + next_signed_manifest, self.owner_public, current, + ) + if (advanced.revision != current.revision + 1 + or advanced.key_epoch != current.key_epoch + 1): + raise LedgerError("Revocation requires a signed new manifest epoch") + # Keychain write precedes owner-ledger commit; an unexpected crash + # can strand an unused epoch secret but must not lose the new epoch. + fresh = secrets.token_bytes(32) + self.keys.create_epoch_key(self.vault_id, advanced.key_epoch, fresh) + new = json.loads(_json(old)) + new["key_epoch"] = advanced.key_epoch + new["key_sha256"] = hashlib.sha256(fresh).hexdigest() + new["manifest"] = asdict(advanced) + for ident, details in new["devices"].items(): + if ident == device_id: + details["status"] = "revoked" + elif details["status"] == "active": + details["status"] = "needs_repair" + self._persist(db, old, digest, new, signer) + return fresh + except BaseException: + if db.in_transaction: + db.rollback() + raise + finally: + db.close() diff --git a/experiments/secure_sync/test_owner_ledger.py b/experiments/secure_sync/test_owner_ledger.py new file mode 100644 index 00000000..f26d9a96 --- /dev/null +++ b/experiments/secure_sync/test_owner_ledger.py @@ -0,0 +1,279 @@ +"""Adversarial offline durability/rotation tests, synthetic secrets only. + +A fake Keychain permits deterministic crash tests. It does not qualify +packaged-app Keychain, secure user recovery or a physical second Mac. +""" +from __future__ import annotations + +import base64 +import json +import os +import sqlite3 +import tempfile +import unittest +from pathlib import Path + +from device_pairing import ( + PairingError, comparison_code, create_device_request, receive_readonly_device, +) +from owner_ledger import LedgerError, OwnerLedger +from secure_sync import SecureSyncError, open_snapshot, seal_snapshot, transcript_snapshot +from vault_keychain import KeychainError, MacKeychainVaultKeys, SERVICE +from vault_manifest import ( + new_manifest, new_vault_id, object_reference, public_key_bytes, sign_manifest, + verify_manifest, +) + +NOW = 1795000000 + + +class FakeKeychain: + def __init__(self): + self.data = {} + self.fail_anchor = False + self.fail_epoch = False + + def get_password(self, service, username): + return self.data.get((service, username)) + + def set_password(self, service, username, value): + if self.fail_anchor and username.endswith(":ledger-anchor"): + raise OSError("Synthetic Keychain anchor outage") + if self.fail_epoch and ":epoch:" in username: + raise OSError("Synthetic Keychain epoch storage outage") + self.data[(service, username)] = value + + +class OfflineLedgerTests(unittest.TestCase): + def setUp(self) -> None: + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.path = Path(self.tmp.name) / "owner.db" + self.backend = FakeKeychain() + self.keys = MacKeychainVaultKeys(_test_backend=self.backend) + self.vault = new_vault_id() + self.master = self.keys.create(self.vault) + self.signer = self.keys.create_owner_signer(self.vault) + self.pub = public_key_bytes(self.signer) + self.genesis = sign_manifest( + new_manifest(vault_id=self.vault, revision=0, previous=None), + self.signer, + ) + self.cp = verify_manifest(self.genesis, self.pub) + self.ledger = OwnerLedger(self.path, self.vault, self.pub, self.keys) + self.ledger.bootstrap(self.signer, self.genesis) + + def _new_ledger(self): + # Separate process-like object, same disk and Keychain backend. + return OwnerLedger( + self.path, self.vault, self.pub, + MacKeychainVaultKeys(_test_backend=self.backend), + ) + + def _approve(self, pending=None): + pending = pending or create_device_request(self.vault, now=NOW) + grant = self.ledger.authorize_and_record( + pending.request, self.signer, + manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + return pending, grant + + def _advance(self): + return sign_manifest(new_manifest( + vault_id=self.vault, revision=self.cp.revision + 1, + previous=self.cp.digest, key_epoch=self.cp.key_epoch + 1, + ), self.signer) + + def test_bootstrap_persists_only_public_signed_state_with_private_mode(self): + state = self._new_ledger().read() + self.assertEqual(state["revision"], 0) + self.assertEqual(state["key_epoch"], 1) + self.assertEqual(state["devices"], {}) + self.assertEqual(self.path.stat().st_mode & 0o777, 0o600) + raw = self.path.read_bytes() + self.assertNotIn(self.master, raw) + self.assertNotIn(self.signer.private_bytes_raw(), raw) + + def test_replay_rejected_across_owner_restarts(self): + pending, grant = self._approve() + state = self._new_ledger().read() + self.assertIn(json.loads(pending.request)["request_id"], state["used_request_ids"]) + self.assertEqual(state["revision"], 1) + with self.assertRaises(LedgerError): + self._new_ledger().authorize_and_record( + pending.request, self.signer, + manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + self.assertEqual(self._new_ledger().read()["revision"], 1) + accepted = receive_readonly_device( + pending, grant, independently_authenticated_owner=self.pub, now=NOW, + ) + self.assertEqual(accepted.vault_key, self.master) + + def test_duplicate_concurrent_style_instances_do_not_reissue(self): + left, right = self._new_ledger(), self._new_ledger() + pending = create_device_request(self.vault, now=NOW) + code = comparison_code(pending.request, now=NOW) + left.authorize_and_record( + pending.request, self.signer, manually_compared_code=code, + explicit_approval=True, now=NOW, + ) + with self.assertRaises(LedgerError): + right.authorize_and_record( + pending.request, self.signer, manually_compared_code=code, + explicit_approval=True, now=NOW, + ) + + def test_no_permission_from_human_bypass_or_ownering_impersonator(self): + pending = create_device_request(self.vault, now=NOW) + for permitted, code in ((False, comparison_code(pending.request, now=NOW)), (True, "00000000")): + with self.assertRaises(PairingError): + self.ledger.authorize_and_record( + pending.request, self.signer, manually_compared_code=code, + explicit_approval=permitted, now=NOW, + ) + self.assertEqual(self.ledger.read()["revision"], 0) + # Missing or changed pinned identity blocks all operations. + self.backend.data[(SERVICE, self.vault + ":owner-pin")] = base64.b64encode(b"x" * 32).decode() + with self.assertRaises(LedgerError): + self.ledger.read() + + def test_keychain_anchor_stops_signed_database_rollback(self): + with sqlite3.connect(self.path) as db: + previous = db.execute( + "SELECT document FROM state WHERE vault_id=?", (self.vault,), + ).fetchone()[0] + self._approve() + with sqlite3.connect(self.path) as db: + db.execute("UPDATE state SET document = ? WHERE vault_id=?", + (previous, self.vault)) + with self.assertRaisesRegex(LedgerError, "high-water mismatch"): + self._new_ledger().read() + + def test_external_database_tampering_fails_even_with_anchor(self): + self._approve() + with sqlite3.connect(self.path) as db: + document = json.loads(db.execute( + "SELECT document FROM state WHERE vault_id=?", (self.vault,), + ).fetchone()[0]) + document["state"]["devices"]["f" * 32] = {"status": "active", "epoch": 1} + db.execute("UPDATE state SET document=? WHERE vault_id=?", + (json.dumps(document).encode(), self.vault)) + with self.assertRaises(LedgerError): + self._new_ledger().read() + + def test_missing_anchor_is_never_silently_recreated(self): + self.backend.data.pop((SERVICE, self.vault + ":ledger-anchor")) + with self.assertRaisesRegex(LedgerError, "Missing ledger or trusted anchor"): + self._new_ledger().read() + with self.assertRaises(LedgerError): + self._new_ledger().bootstrap(self.signer, self.genesis) + + def test_keychain_failure_after_sqlite_commit_freezes_ledger(self): + self.backend.fail_anchor = True + pending = create_device_request(self.vault, now=NOW) + with self.assertRaises(KeychainError): + self.ledger.authorize_and_record( + pending.request, self.signer, + manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + self.backend.fail_anchor = False + with self.assertRaisesRegex(LedgerError, "high-water mismatch"): + self._new_ledger().read() + # No automatic repair from the later SQLite state. + with self.assertRaises(LedgerError): + self._new_ledger().authorize_and_record( + pending.request, self.signer, + manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + + def test_keychain_failure_before_epoch_commit_keeps_prior_state(self): + pending, _ = self._approve() + self.backend.fail_epoch = True + with self.assertRaises(KeychainError): + self.ledger.revoke_and_rotate( + json.loads(pending.request)["device_id"], self.signer, self._advance(), + ) + self.backend.fail_epoch = False + state = self._new_ledger().read() + self.assertEqual(state["key_epoch"], 1) + self.assertEqual(state["devices"][json.loads(pending.request)["device_id"]]["status"], "active") + + def test_revocation_rotates_to_independent_key_and_signed_epoch(self): + removed, removed_grant = self._approve() + survivor, survivor_grant = self._approve() + revoked_id = json.loads(removed.request)["device_id"] + surviving_id = json.loads(survivor.request)["device_id"] + old_recipient = receive_readonly_device( + removed, removed_grant, independently_authenticated_owner=self.pub, now=NOW, + ) + new_key = self.ledger.revoke_and_rotate(revoked_id, self.signer, self._advance()) + new_state = self._new_ledger().read() + self.assertEqual(new_state["key_epoch"], 2) + self.assertEqual(new_state["devices"][revoked_id]["status"], "revoked") + self.assertEqual(new_state["devices"][surviving_id]["status"], "needs_repair") + self.assertNotEqual(new_key, self.master) + self.assertEqual(self.keys.load_epoch_key(self.vault, 2), new_key) + future_snapshot = transcript_snapshot({"id": "post-revocation", "text": "future content"}) + blob = seal_snapshot(future_snapshot, new_key) + self.assertEqual(open_snapshot(blob, new_key), future_snapshot) + with self.assertRaises(SecureSyncError): + open_snapshot(blob, old_recipient.vault_key) + # The pre-rotation grant is now below an authenticated epoch checkpoint. + next_cp = verify_manifest(self._advance(), self.pub, self.cp) + with self.assertRaises(PairingError): + receive_readonly_device( + survivor, survivor_grant, independently_authenticated_owner=self.pub, + minimum_checkpoint=next_cp, now=NOW, + ) + + def test_post_rotation_new_pairing_uses_fresh_epoch_not_previous(self): + revoked, _ = self._approve() + self.ledger.revoke_and_rotate( + json.loads(revoked.request)["device_id"], self.signer, self._advance(), + ) + pending, grant = self._approve() + restored = receive_readonly_device( + pending, grant, independently_authenticated_owner=self.pub, now=NOW, + ) + self.assertEqual(restored.checkpoint.key_epoch, 2) + self.assertEqual(restored.vault_key, self.keys.load_epoch_key(self.vault, 2)) + self.assertNotEqual(restored.vault_key, self.master) + + def test_unsigned_or_skipped_manifest_epoch_cannot_revoke(self): + pending, _ = self._approve() + ident = json.loads(pending.request)["device_id"] + bad = sign_manifest(new_manifest( + vault_id=self.vault, revision=1, previous=self.cp.digest, key_epoch=1, + ), self.signer) + with self.assertRaises(LedgerError): + self.ledger.revoke_and_rotate(ident, self.signer, bad) + with self.assertRaises(LedgerError): + self.ledger.revoke_and_rotate("f" * 32, self.signer, self._advance()) + self.assertEqual(self.ledger.read()["key_epoch"], 1) + + def test_duplicate_revoke_does_not_rotate_again(self): + pending, _ = self._approve() + ident = json.loads(pending.request)["device_id"] + self.ledger.revoke_and_rotate(ident, self.signer, self._advance()) + with self.assertRaises(LedgerError): + self._new_ledger().revoke_and_rotate(ident, self.signer, self._advance()) + self.assertEqual(self._new_ledger().read()["key_epoch"], 2) + + def test_permissions_and_symlink_are_not_accepted(self): + os.chmod(self.path, 0o644) + with self.assertRaises(LedgerError): + self._new_ledger() + os.chmod(self.path, 0o600) + link = Path(self.tmp.name) / "owner-link.db" + link.symlink_to(self.path) + with self.assertRaises(LedgerError): + OwnerLedger(link, self.vault, self.pub, self.keys) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/secure_sync/vault_keychain.py b/experiments/secure_sync/vault_keychain.py index 6d1c04ff..f57c2ee6 100644 --- a/experiments/secure_sync/vault_keychain.py +++ b/experiments/secure_sync/vault_keychain.py @@ -160,3 +160,38 @@ def accept_signed_head(self, vault_id: str, document: bytes) -> TrustedCheckpoin if self.load_checkpoint(vault_id) != accepted: raise KeychainError("Checkpoint readback mismatch") return accepted + + def load_pinned_owner(self, vault_id: str) -> bytes: + """Authenticated owner pin, never silently accepted from remote data.""" + _validate_id(vault_id) + return self._load_secret(vault_id + ":owner-pin") + + def load_epoch_key(self, vault_id: str, epoch: int) -> bytes: + """Read an explicit independent epoch key. No derivation from old key.""" + _validate_id(vault_id) + if type(epoch) is not int or epoch < 1: + raise KeychainError("Invalid key epoch") + if epoch == 1: + return self.load(vault_id) + return self._load_secret(vault_id + f":epoch:{epoch}") + + def create_epoch_key(self, vault_id: str, epoch: int, secret: bytes) -> None: + """Fail on duplicate; caller owns process-wide SQLite serialization.""" + _validate_id(vault_id) + if type(epoch) is not int or epoch < 2 or not isinstance(secret, bytes) or len(secret) != 32: + raise KeychainError("Invalid new epoch secret") + self._create_secret(vault_id + f":epoch:{epoch}", secret) + if not secrets.compare_digest(self.load_epoch_key(vault_id, epoch), secret): + raise KeychainError("Epoch secret readback mismatch") + + def read_ledger_anchor(self, vault_id: str) -> str | None: + """Opaque small trusted anchor, parsed and checked by owner_ledger.""" + _validate_id(vault_id) + return self._get(vault_id + ":ledger-anchor") + + def write_ledger_anchor(self, vault_id: str, serialized: str) -> None: + """No file fallback; ambiguity on failed write freezes ledger reads.""" + _validate_id(vault_id) + if not isinstance(serialized, str) or len(serialized) > 256: + raise KeychainError("Invalid ledger anchor") + self._set(vault_id + ":ledger-anchor", serialized) From 5cd4d7896dd834af89a3acc07d779c5647d07913 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 12:25:53 +0100 Subject: [PATCH 16/24] docs(sync): keep active security plan bounded, remove stale duplicate checkpoint history --- docs/workstreams/secure-sync-google-drive.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 2de332ba..ecf999ee 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -50,11 +50,11 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model | SYNC-5 | Integrated Settings/Meeting status, complete privacy copy, accessible UX and correct cleanup | BLOCKED on SYNC-4 | Automated E2E FULL_MEDIA; WKWebView/Keychain target Mac; security/recovery audit | | SYNC-6 | Consider mobile companion/read-write editing **only after** the above is verified | BLOCKED | Product evidence and conflict-management design | -### Offline proof extension (2026-11-19) +### Security prototype boundary -- Isolated `vault_manifest.py`: Ed25519 owner-signed chain, opaque ciphertext references, contiguous revisions/epochs, pinned owner, fork and replay detection against a trusted checkpoint. A fresh device cannot prove remote freshness from Drive alone. -- Isolated `vault_keychain.py`: fail-closed macOS Keychain-only prototype storing independent AES vault and **software** Ed25519 signing secrets, authenticated owner pin and checkpoint. Not hardware Secure Enclave. Synthetic unit tests cover restart, tampering, bad signer, key replacement/corruption, failures and replay. -- Missing: genuine recovery materials, cross-process CAS, authenticated pairing, revocation/rotation, second-device trust anchor and verified backup. No OAuth, sync, migration, upload, local eviction, app integration or production cryptographic dependencies yet. +- `vault_manifest.py`: Ed25519 owner-signed head, contiguous epochs, checkpoint and encrypted-object digest verification. A new Mac cannot infer freshness from Drive. +- `vault_keychain.py`: local-only Keychain experiment for vault/owner identity and trusted checkpoints; not Secure Enclave or product integration. +- `recovery_capsule.py`, `device_pairing.py`, `owner_ledger.py`: separate recovery material, X25519 read-only grants, SQLite serialized/signed registry with a Keychain high-water anchor, fresh independent future-epoch keys on revocation. All synthetic/offline; pairing UX, crash recovery, independent restore and provider freshness still unproven. ### Validation — 2026-11-19/20 From d923719a41161b4537e380a407e58c5907c7aae3 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 12:26:53 +0100 Subject: [PATCH 17/24] docs(sync): remove redundant Keychain history to meet bounded plan budget --- docs/workstreams/secure-sync-google-drive.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index ecf999ee..58790bec 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -56,12 +56,10 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - `vault_keychain.py`: local-only Keychain experiment for vault/owner identity and trusted checkpoints; not Secure Enclave or product integration. - `recovery_capsule.py`, `device_pairing.py`, `owner_ledger.py`: separate recovery material, X25519 read-only grants, SQLite serialized/signed registry with a Keychain high-water anchor, fresh independent future-epoch keys on revocation. All synthetic/offline; pairing UX, crash recovery, independent restore and provider freshness still unproven. -### Validation — 2026-11-19/20 +### Physical Keychain proof and Mac evidence -- Exact source `b8dfea6474eee488b2a99e754941aab91fb17648`: [self-hosted Mac run 44552089974](https://github.com/daniele21/local-runner-infra/actions/runs/44552089974) `local-ci/mac=success`; **987 Python tests PASS; 17 crypto tests PASS; browser FULL_MEDIA PASS**. `KEYCHAIN_REAL_ENVIRONMENT=NOT_RUN` is intentional in non-interactive CI. -- Earlier attempts to access Keychain from a background runner failed `errSecInteractionNotAllowed (-25308)`, even with login Keychain unlocked. The same local synthetic `keyring` smoke passed interactively in Terminal, but without a supplied exact Git SHA; separate from bundle proof. -- **Packaged ad-hoc GUI Keychain gate PASS (user-supplied terminal evidence, test run 2026-11-19):** source `b8dfea6474eee488b2a99e754941aab91fb17648`, finalized artifact manifest `dist/artifacts/macos-arm64-local-real-environment-app/local-20261119T161450Z-f0de04/build-manifest.json`. `scripts/probe_packaged_keychain.py --build` reported `bundle_id=com.closedroom.app`, `signing=ad-hoc`, `status=pass`, `independent_child=true`, `cleanup=true`, `installed_app_modified=false`, scope `packaged-GUI-Terminal-Keychain-only`. The script validates finalized artifact provenance/signature and executes the Security.framework probe from the frozen app binary. Evidence is supplied by the operator, not independently downloaded from the Mac. -- **Gate qualified only for ad-hoc packaged diagnostic.** No Developer ID signing/notarization or installed-app workflow, no production vault key lifecycle, authenticated pairing, recovery, revocation, Google OAuth, Drive integration, upload or remote restoration has been proven. +- [Mac #44552089974](https://github.com/daniele21/local-runner-infra/actions/runs/44552089974): 987 app tests, 17 security tests and browser FULL_MEDIA PASS on `b8dfea64`. Headless Keychain deliberately NOT_RUN (`-25308`). +- **GUI-user ad-hoc packaged probe PASS** (operator log, exact `b8dfea6474eee488b2a99e754941aab91fb17648`, local artifact `local-20261119T161450Z-f0de04`): same signed binary's second-process read, cleanup and no installed-app modification. Not Developer ID/notarized or installed product functionality; no pairing or Drive proof. ### Current checkpoint From 846f7034af8d4424d0fe8871dd72488c3ef6cd53 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 12:32:30 +0100 Subject: [PATCH 18/24] docs(sync): capture exact Mac PASS for durable owner ledger and revocation tests --- docs/workstreams/secure-sync-google-drive.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 58790bec..dca575aa 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -65,5 +65,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Source branch from `dev`; draft PR #225. The Keychain experiment and packaged-app synthetic security smoke are **implemented and qualified at the scope above**; product sync is still OFF. No GCS/Drive transmission or real user meeting data transferred. - SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. -- SYNC-2 next offline candidate: `owner_ledger.py` uses SQLite FULL + `BEGIN IMMEDIATE` to serialize a signed public device registry, persisted enrollment nonces, and separate Keychain high-water digest. Failure between SQLite commit and Keychain update **freezes** vault; no auto reconciliation. Signed manifest key_epoch advances on revocation, fresh **independent** epoch secret stored in Keychain before commit; survivors require new grant, revoked device retains old read access. New synthetic regression suite `test_owner_ledger.py`; exact Mac run evidence pending. +- SYNC-2 P0 offline candidate **tested**: [Mac #44727751442](https://github.com/daniele21/local-runner-infra/actions/runs/44727751442) exact `d923719a`: **987 app tests PASS, 45 isolated security tests PASS (14 new), FULL_MEDIA PASS**, `local-ci/mac=success`. `owner_ledger.py`: signed SQLite registry + durable nonce consumption, Keychain high-water anchor and fail-closed split-commit; fresh independent future key stored before signed epoch rotation, revoked device cannot decrypt newer data. Fake-Keychain/canonical-path tests, not production. - Still SYNC-2 ACTIVE: recovery from frozen split-commit (no silent fix), out-of-band checkpoint freshness, owner public-key bootstrap, recovery-code update after rotation, persistent recipient-side trust state, fully authenticated two-screen GUI, real second Mac test, secure SDK/model lifecycle integration. No Drive/OAuth, production Keychain integration, user data sync or release claims. From a1a962c613e786b3393cd841bf9a09b1e940de00 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 16:25:45 +0100 Subject: [PATCH 19/24] spike(sync): stage Keychain intent and require authenticated forward-only ledger crash recovery --- docs/workstreams/secure-sync-google-drive.md | 3 +- experiments/secure_sync/README.md | 21 +- experiments/secure_sync/owner_ledger.py | 152 ++++++++++++- experiments/secure_sync/test_owner_ledger.py | 219 +++++++++++++++++++ experiments/secure_sync/vault_keychain.py | 18 ++ 5 files changed, 398 insertions(+), 15 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index dca575aa..37eb7248 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -66,4 +66,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Source branch from `dev`; draft PR #225. The Keychain experiment and packaged-app synthetic security smoke are **implemented and qualified at the scope above**; product sync is still OFF. No GCS/Drive transmission or real user meeting data transferred. - SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. - SYNC-2 P0 offline candidate **tested**: [Mac #44727751442](https://github.com/daniele21/local-runner-infra/actions/runs/44727751442) exact `d923719a`: **987 app tests PASS, 45 isolated security tests PASS (14 new), FULL_MEDIA PASS**, `local-ci/mac=success`. `owner_ledger.py`: signed SQLite registry + durable nonce consumption, Keychain high-water anchor and fail-closed split-commit; fresh independent future key stored before signed epoch rotation, revoked device cannot decrypt newer data. Fake-Keychain/canonical-path tests, not production. -- Still SYNC-2 ACTIVE: recovery from frozen split-commit (no silent fix), out-of-band checkpoint freshness, owner public-key bootstrap, recovery-code update after rotation, persistent recipient-side trust state, fully authenticated two-screen GUI, real second Mac test, secure SDK/model lifecycle integration. No Drive/OAuth, production Keychain integration, user data sync or release claims. +- SYNC-2 next iteration candidate: staged Keychain intent before each SQLite change; explicit, authenticated, exact one-step **forward** repair after split-commit, rejecting ambiguous old DB and missing/forged pending proof. Regression tests for replay, revocation and crashes. Exact Mac result pending. +- Still ACTIVE: ambiguous pre-commit recovery and initial bootstrap, independent checkpoint freshness, owner bootstrap and recovery-code rotation, recipient-side durable trust, real UI/two-Mac proof and production Keychain lifecycle. No Drive/OAuth, user data sync or release claim. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index bbd6f0c0..50a5f0d3 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -115,8 +115,17 @@ signed registry document, schema, and exact Keychain high-water anchor. `needs_repair`. They require fresh authenticated grants. A revoked device may retain old ciphertext/plaintext; there is no remote erase. - Keychain write failure before SQL commit leaves old epoch current (possible - orphan secret); failure after SQL commit before the high-water write freezes - the vault. Crash recovery and cleanup need a separate manual protocol. + orphan secret). Each new SQLite update is now preceded by an **exact forward + intent in Keychain** binding the trusted old anchor to the new signed record. + Every unresolved intent freezes normal reads, including ambiguous attempts + where SQLite still equals the old anchor (possible attacker rollback). + `recover_prepared_transition(..., expected_new_digest=..., explicit_confirmation=True)` + is **manual and forward-only**: it authenticates the owner signer, pinned + owner and SQLite signature, compares the independent Keychain intent and + prior/current high-water, validates the new epoch key, and completes only the + exact one-step signed successor. Missing/tampered intent, old DB, wrong key + and owner mismatch never auto-heal. App UX and recovery of ambiguous or + orphaned state still require separate design. - The persistent ledger has no secret material and uses an **experimental** Keychain adapter / fake backend in unit tests. No installation into the production app, Developer ID signature, independent trusted head, actual @@ -125,3 +134,11 @@ signed registry document, schema, and exact Keychain high-water anchor. Run the isolated `test_owner_ledger.py` suite via the existing `unittest discover -s experiments/secure_sync` Mac CI selector. + +The prepared Keychain record is **not** a user-held off-device recovery +proof, does not ensure monotonic Keychain state under OS backup restore, and +does not establish global/provider freshness. A bool/API digest argument +cannot establish a genuine human approval or independently archived receipt: +the app must introduce a reviewed confirmation boundary before enabling it. +Crash during initial genesis bootstrap is still fail-closed and requires +independent recovery; no automatic reset/repair was added. diff --git a/experiments/secure_sync/owner_ledger.py b/experiments/secure_sync/owner_ledger.py index f766932e..bf5cb2b6 100644 --- a/experiments/secure_sync/owner_ledger.py +++ b/experiments/secure_sync/owner_ledger.py @@ -5,9 +5,10 @@ and installed ClosedRoom are not touched. SQLite transactions serialize writers using ONE canonical local database path. -Keychain and SQLite cannot commit atomically. Any mid-commit disagreement -intentionally freezes the ledger until a separately authenticated recovery -workflow is designed. Never automatically repair by trusting either copy. +Keychain and SQLite cannot commit atomically. A Keychain-held prepared digest +must precede each SQLite update; an interrupted exact signed forward step can +be explicitly completed by the owner, while ambiguity/rollback fails closed. +This does not establish remote freshness or provide a production recovery UI. """ from __future__ import annotations @@ -234,11 +235,50 @@ def _signed(self, state: dict[str, Any], signer: Ed25519PrivateKey) -> bytes: raise LedgerError("Signed ledger exceeds size budget") return document - def _checked(self, db: sqlite3.Connection) -> tuple[dict[str, Any], str]: + def _read_prepare(self) -> dict[str, Any] | None: + """Trusted in-Keychain intent, independent from the mutable SQLite row.""" + raw = self.keys.read_ledger_prepare(self.vault_id) + if raw is None: + return None + if not isinstance(raw, str) or len(raw) > 512: + raise LedgerError("Corrupt Keychain prepared transition") + try: + prepared = _parse(raw.encode("ascii")) + except UnicodeEncodeError as exc: + raise LedgerError("Invalid Keychain prepared transition") from exc + if (not isinstance(prepared, dict) + or set(prepared) != {"vault_id", "from_revision", "from_digest", + "to_revision", "to_digest"} + or prepared["vault_id"] != self.vault_id + or type(prepared["from_revision"]) is not int + or prepared["from_revision"] < 0 + or type(prepared["to_revision"]) is not int + or prepared["to_revision"] != prepared["from_revision"] + 1 + or not _hex(prepared["from_digest"], 64) + or not _hex(prepared["to_digest"], 64) + or prepared["from_digest"] == prepared["to_digest"]): + raise LedgerError("Corrupt Keychain prepared transition") + return prepared + + def _stage_prepare( + self, from_revision: int, from_digest: str, + to_revision: int, to_digest: str, + ) -> None: + prepared = { + "vault_id": self.vault_id, + "from_revision": from_revision, "from_digest": from_digest, + "to_revision": to_revision, "to_digest": to_digest, + } + serialized = _json(prepared).decode("ascii") + self.keys.write_ledger_prepare(self.vault_id, serialized) + if self._read_prepare() != prepared: + raise LedgerError("Prepared transition Keychain readback mismatch") + + def _verified_record(self, db: sqlite3.Connection) -> tuple[dict[str, Any], str]: + """Verify signature and pinned owner, without trusting SQLite freshness.""" row = db.execute("SELECT document FROM state WHERE vault_id = ?", (self.vault_id,)).fetchone() - anchor = self._read_anchor() - if row is None or anchor is None: - raise LedgerError("Missing ledger or trusted anchor: explicit recovery required") + if row is None: + raise LedgerError("Missing signed owner ledger: explicit recovery required") document = bytes(row[0]) digest = hashlib.sha256(document).hexdigest() record = _parse(document) @@ -255,15 +295,97 @@ def _checked(self, db: sqlite3.Connection) -> tuple[dict[str, Any], str]: ) except (ValueError, InvalidSignature, TypeError) as exc: raise LedgerError("Owner ledger signature does not verify") from exc + if not hmac.compare_digest( + self.keys.load_pinned_owner(self.vault_id), self.owner_public, + ): + raise LedgerError("Trusted owner pin mismatch") + return state, digest + + def _checked(self, db: sqlite3.Connection) -> tuple[dict[str, Any], str]: + state, digest = self._verified_record(db) + anchor = self._read_anchor() + if anchor is None: + raise LedgerError("Missing ledger or trusted anchor: explicit recovery required") if anchor != { "vault_id": self.vault_id, "revision": state["revision"], "digest": digest, }: raise LedgerError("SQLite/Keychain high-water mismatch: frozen until recovery") - if not hmac.compare_digest(self.keys.load_pinned_owner(self.vault_id), self.owner_public): - raise LedgerError("Trusted owner pin mismatch") + # A prepared write may have stopped before SQLite COMMIT, after COMMIT, + # or during Keychain acknowledgement. Even a DB equal to the old anchor + # is ambiguous: it may have been rolled back after a real commit. + if self._read_prepare() is not None: + raise LedgerError("Unresolved Keychain prepared transition: explicit recovery required") return state, digest + def recover_prepared_transition( + self, owner_signer: Ed25519PrivateKey, *, + expected_new_digest: str, explicit_confirmation: bool, + ) -> str: + """Explicit local forward repair, NEVER trust or roll back SQLite alone. + + A prepared transition written to Keychain *before* SQLite COMMIT binds + the old high-water anchor to the exact signed successor document. + The operator must independently confirm which candidate was intended. + No prepared record => no repair. A DB still at the old anchor could be + either uncommitted OR a malicious post-commit rollback: refuse both. + """ + if (type(explicit_confirmation) is not bool or not explicit_confirmation + or not _hex(expected_new_digest, 64) + or not isinstance(owner_signer, Ed25519PrivateKey) + or not hmac.compare_digest( + public_key_bytes(owner_signer), self.owner_public, + )): + raise LedgerError("Explicit authenticated owner recovery required") + db = self._connect() + try: + db.execute("BEGIN IMMEDIATE") + state, digest = self._verified_record(db) + anchor = self._read_anchor() + prepared = self._read_prepare() + if anchor is None or prepared is None: + raise LedgerError("No independently Keychain-prepared transition") + if not hmac.compare_digest(prepared["to_digest"], expected_new_digest): + raise LedgerError("Wrong independently confirmed successor digest") + before = { + "vault_id": self.vault_id, + "revision": prepared["from_revision"], + "digest": prepared["from_digest"], + } + after = { + "vault_id": self.vault_id, + "revision": prepared["to_revision"], + "digest": prepared["to_digest"], + } + if not (state["revision"] == after["revision"] + and hmac.compare_digest(digest, after["digest"]) + and state["previous"] == before["digest"]): + raise LedgerError("Prepared successor unavailable or rolled back: recovery refused") + # Detect missing, changed or unrelated secrets before asserting the + # new epoch. The Keychain is the separate trust/secret owner. + key = self.keys.load_epoch_key(self.vault_id, state["key_epoch"]) + if not hmac.compare_digest( + hashlib.sha256(key).hexdigest(), state["key_sha256"], + ): + raise LedgerError("Trusted epoch key does not match signed successor") + if anchor == before: + self._write_anchor(after["revision"], after["digest"]) + elif anchor != after: + raise LedgerError("Keychain high-water is not a prepared predecessor/successor") + # If clearing the pending mark fails, all future ordinary reads + # remain frozen until a subsequent explicit recovery invocation. + self.keys.clear_ledger_prepare(self.vault_id) + if self._read_prepare() is not None: + raise LedgerError("Keychain preparation cleanup failed") + db.commit() + return "recovered" + except BaseException: + if db.in_transaction: + db.rollback() + raise + finally: + db.close() + def bootstrap(self, owner_signer: Ed25519PrivateKey, signed_genesis: bytes) -> None: """Initialize from a locally authenticated signed genesis only once.""" if not isinstance(owner_signer, Ed25519PrivateKey) or not hmac.compare_digest( @@ -329,6 +451,10 @@ def _persist( new["previous"] = old_digest doc = self._signed(new, signer) digest = hashlib.sha256(doc).hexdigest() + # The independent Keychain preparation MUST precede SQLite COMMIT. + # On a crash, only this exact signed successor is eligible for explicit + # forward recovery. A rolled-back DB or missing intent remains blocked. + self._stage_prepare(old["revision"], old_digest, new["revision"], digest) result = db.execute( "UPDATE state SET document = ? WHERE vault_id = ? AND document = ?", (doc, self.vault_id, db.execute( @@ -337,11 +463,13 @@ def _persist( ) if result.rowcount != 1: raise LedgerError("Concurrent owner ledger update refused") - # COMMIT is durable before attempting the separate Keychain anchor. - # A crash/failure after this point leaves ledger frozen, NEVER silently - # succeeding or rolling back to an older trusted head. db.commit() self._write_anchor(new["revision"], digest) + # A failure here leaves the ledger frozen despite anchor == SQLite, + # until the owner explicitly proves and finishes the preparation. + self.keys.clear_ledger_prepare(self.vault_id) + if self._read_prepare() is not None: + raise LedgerError("Unresolved Keychain prepared transition") def authorize_and_record( self, diff --git a/experiments/secure_sync/test_owner_ledger.py b/experiments/secure_sync/test_owner_ledger.py index f26d9a96..8f8a80bd 100644 --- a/experiments/secure_sync/test_owner_ledger.py +++ b/experiments/secure_sync/test_owner_ledger.py @@ -275,5 +275,224 @@ def test_permissions_and_symlink_are_not_accepted(self): OwnerLedger(link, self.vault, self.pub, self.keys) + def _document_digest(self): + import hashlib + with sqlite3.connect(self.path) as db: + document = db.execute( + "SELECT document FROM state WHERE vault_id=?", (self.vault,), + ).fetchone()[0] + return hashlib.sha256(document).hexdigest() + + def _interrupt_after_sql_commit(self): + self.backend.fail_anchor = True + pending = create_device_request(self.vault, now=NOW) + try: + with self.assertRaises(KeychainError): + self.ledger.authorize_and_record( + pending.request, self.signer, + manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + finally: + self.backend.fail_anchor = False + return pending, self._document_digest() + + def test_exact_prepared_forward_step_recovers_only_with_owner_confirmation(self): + pending, successor_digest = self._interrupt_after_sql_commit() + self.assertIsNotNone(self.keys.read_ledger_prepare(self.vault)) + with self.assertRaises(LedgerError): + self._new_ledger().read() + self.assertEqual(self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest=successor_digest, + explicit_confirmation=True, + ), "recovered") + self.assertIsNone(self.keys.read_ledger_prepare(self.vault)) + state = self._new_ledger().read() + self.assertEqual(state["revision"], 1) + self.assertIn(json.loads(pending.request)["request_id"], state["used_request_ids"]) + with self.assertRaises(LedgerError): + self._new_ledger().authorize_and_record( + pending.request, self.signer, + manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + self.assertEqual(self._new_ledger().read()["revision"], 1) + + def test_recovery_refuses_wrong_digest_absent_consent_and_wrong_signer(self): + from vault_manifest import generate_owner_signing_key + _, digest = self._interrupt_after_sql_commit() + for signer, expected, consent in ( + (self.signer, digest, False), + (self.signer, "a" * 64, True), + (generate_owner_signing_key(), digest, True), + ): + with self.subTest(consent=consent, expected=expected), self.assertRaises(LedgerError): + self._new_ledger().recover_prepared_transition( + signer, expected_new_digest=expected, + explicit_confirmation=consent, + ) + with self.assertRaises(LedgerError): + self._new_ledger().read() + + def test_recovery_refuses_if_keychain_preparation_is_missing(self): + _, digest = self._interrupt_after_sql_commit() + self.backend.data.pop((SERVICE, self.vault + ":ledger-prepare")) + with self.assertRaisesRegex(LedgerError, "No independently Keychain-prepared"): + self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest=digest, + explicit_confirmation=True, + ) + with self.assertRaises(LedgerError): + self._new_ledger().read() + + def test_recovery_does_not_accept_rolled_back_old_database(self): + with sqlite3.connect(self.path) as db: + old_document = db.execute( + "SELECT document FROM state WHERE vault_id=?", (self.vault,), + ).fetchone()[0] + _, digest = self._interrupt_after_sql_commit() + # DB may have committed and THEN been restored from backup. As long + # as Keychain preparation remains, old == anchor cannot be assumed safe. + with sqlite3.connect(self.path) as db: + db.execute("UPDATE state SET document=? WHERE vault_id=?", + (old_document, self.vault)) + with self.assertRaisesRegex(LedgerError, "Unresolved Keychain prepared"): + self._new_ledger().read() + with self.assertRaisesRegex(LedgerError, "rolled back"): + self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest=digest, + explicit_confirmation=True, + ) + + def test_recovery_refuses_prepared_but_uncommitted_sqlite_state(self): + old_digest = self._document_digest() + self.ledger._stage_prepare(0, old_digest, 1, "b" * 64) + with self.assertRaises(LedgerError): + self._new_ledger().read() + with self.assertRaisesRegex(LedgerError, "rolled back"): + self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest="b" * 64, + explicit_confirmation=True, + ) + + def test_recovery_refuses_signed_alternate_successor_document(self): + _, digest = self._interrupt_after_sql_commit() + with sqlite3.connect(self.path) as db: + document = json.loads(db.execute( + "SELECT document FROM state WHERE vault_id=?", (self.vault,), + ).fetchone()[0]) + state = document["state"] + state["devices"]["c" * 32] = {"status": "active", "epoch": 1} + forged_signed = self.ledger._signed(state, self.signer) + db.execute("UPDATE state SET document=? WHERE vault_id=?", + (forged_signed, self.vault)) + with self.assertRaisesRegex(LedgerError, "rolled back"): + self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest=digest, + explicit_confirmation=True, + ) + + def test_recovery_refuses_wrong_or_missing_epoch_secret(self): + _, digest = self._interrupt_after_sql_commit() + self.backend.data[(SERVICE, self.vault + ":master")] = base64.b64encode( + b"z" * 32, + ).decode() + with self.assertRaisesRegex(LedgerError, "epoch key"): + self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest=digest, + explicit_confirmation=True, + ) + with self.assertRaises(LedgerError): + self._new_ledger().read() + + def test_missing_preparation_cannot_invoke_recovery_on_healthy_ledger(self): + with self.assertRaisesRegex(LedgerError, "No independently Keychain-prepared"): + self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest="d" * 64, + explicit_confirmation=True, + ) + self.assertEqual(self.ledger.read()["revision"], 0) + + def test_corrupt_preparation_is_not_ignored_or_repaired(self): + self.backend.data[(SERVICE, self.vault + ":ledger-prepare")] = '{"from_revision":0}' + with self.assertRaisesRegex(LedgerError, "Corrupt Keychain prepared"): + self._new_ledger().read() + with self.assertRaises(LedgerError): + self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest="e" * 64, + explicit_confirmation=True, + ) + + def test_epoch_rotation_split_commit_can_recover_with_independent_secret(self): + pending, _ = self._approve() + self.backend.fail_anchor = True + try: + with self.assertRaises(KeychainError): + self.ledger.revoke_and_rotate( + json.loads(pending.request)["device_id"], + self.signer, self._advance(), + ) + finally: + self.backend.fail_anchor = False + digest = self._document_digest() + with self.assertRaises(LedgerError): + self._new_ledger().read() + self.assertEqual( + self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest=digest, + explicit_confirmation=True, + ), "recovered", + ) + self.assertEqual(self._new_ledger().read()["key_epoch"], 2) + self.assertEqual( + self._new_ledger().read()["devices"][json.loads(pending.request)["device_id"]]["status"], + "revoked", + ) + self.assertNotEqual(self.keys.load_epoch_key(self.vault, 2), self.master) + + def test_failed_cleanup_after_anchor_acceptance_requires_explicit_completion(self): + pending = create_device_request(self.vault, now=NOW) + original_clear = self.keys.clear_ledger_prepare + def fail_clear(vault_id): + raise KeychainError("Synthetic post-anchor cleanup failed") + self.keys.clear_ledger_prepare = fail_clear + try: + with self.assertRaises(KeychainError): + self.ledger.authorize_and_record( + pending.request, self.signer, + manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + finally: + self.keys.clear_ledger_prepare = original_clear + digest = self._document_digest() + with self.assertRaisesRegex(LedgerError, "Unresolved Keychain prepared"): + self._new_ledger().read() + self.assertEqual(self._new_ledger().recover_prepared_transition( + self.signer, expected_new_digest=digest, + explicit_confirmation=True, + ), "recovered") + self.assertEqual(self._new_ledger().read()["revision"], 1) + + def test_prepared_transition_write_failure_before_commit_keeps_old_record(self): + old_digest = self._document_digest() + original = self.keys.write_ledger_prepare + def fail_prepare(vault_id, serialized): + raise KeychainError("Synthetic prepare write failure") + self.keys.write_ledger_prepare = fail_prepare + try: + pending = create_device_request(self.vault, now=NOW) + with self.assertRaises(KeychainError): + self.ledger.authorize_and_record( + pending.request, self.signer, + manually_compared_code=comparison_code(pending.request, now=NOW), + explicit_approval=True, now=NOW, + ) + finally: + self.keys.write_ledger_prepare = original + self.assertEqual(self._document_digest(), old_digest) + self.assertEqual(self._new_ledger().read()["revision"], 0) + + if __name__ == "__main__": unittest.main() diff --git a/experiments/secure_sync/vault_keychain.py b/experiments/secure_sync/vault_keychain.py index f57c2ee6..a11b7c14 100644 --- a/experiments/secure_sync/vault_keychain.py +++ b/experiments/secure_sync/vault_keychain.py @@ -195,3 +195,21 @@ def write_ledger_anchor(self, vault_id: str, serialized: str) -> None: if not isinstance(serialized, str) or len(serialized) > 256: raise KeychainError("Invalid ledger anchor") self._set(vault_id + ":ledger-anchor", serialized) + + def read_ledger_prepare(self, vault_id: str) -> str | None: + """Keychain-owned prepared ledger digest; never sourced from SQLite.""" + _validate_id(vault_id) + value = self._get(vault_id + ":ledger-prepare") + return None if value == "" else value + + def write_ledger_prepare(self, vault_id: str, serialized: str) -> None: + """Durably stage the exact forward transition before SQLite commit.""" + _validate_id(vault_id) + if not isinstance(serialized, str) or not 0 < len(serialized) <= 512: + raise KeychainError("Invalid ledger preparation") + self._set(vault_id + ":ledger-prepare", serialized) + + def clear_ledger_prepare(self, vault_id: str) -> None: + """Explicitly clear only after the high-water anchor is verified.""" + _validate_id(vault_id) + self._set(vault_id + ":ledger-prepare", "") From d659874fc79571aa83b26cabb34ba4ba6107dde9 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 16:31:12 +0100 Subject: [PATCH 20/24] docs(sync): record exact Mac evidence for authenticated forward-only ledger crash recovery --- docs/workstreams/secure-sync-google-drive.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 37eb7248..47a93144 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -66,5 +66,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - Source branch from `dev`; draft PR #225. The Keychain experiment and packaged-app synthetic security smoke are **implemented and qualified at the scope above**; product sync is still OFF. No GCS/Drive transmission or real user meeting data transferred. - SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. - SYNC-2 P0 offline candidate **tested**: [Mac #44727751442](https://github.com/daniele21/local-runner-infra/actions/runs/44727751442) exact `d923719a`: **987 app tests PASS, 45 isolated security tests PASS (14 new), FULL_MEDIA PASS**, `local-ci/mac=success`. `owner_ledger.py`: signed SQLite registry + durable nonce consumption, Keychain high-water anchor and fail-closed split-commit; fresh independent future key stored before signed epoch rotation, revoked device cannot decrypt newer data. Fake-Keychain/canonical-path tests, not production. -- SYNC-2 next iteration candidate: staged Keychain intent before each SQLite change; explicit, authenticated, exact one-step **forward** repair after split-commit, rejecting ambiguous old DB and missing/forged pending proof. Regression tests for replay, revocation and crashes. Exact Mac result pending. -- Still ACTIVE: ambiguous pre-commit recovery and initial bootstrap, independent checkpoint freshness, owner bootstrap and recovery-code rotation, recipient-side durable trust, real UI/two-Mac proof and production Keychain lifecycle. No Drive/OAuth, user data sync or release claim. +- SYNC-2 local forward-crash recovery **PASS**: [Mac #44763250585](https://github.com/daniele21/local-runner-infra/actions/runs/44763250585), source `a1a962c6`: **987 app tests, 57 security tests (12 new), browser FULL_MEDIA PASS**, `local-ci/mac=success`. Keychain prepared-intent precedes SQLite COMMIT; signed successor and actual epoch key must match. Only explicit owner-confirmed forward completion; old/rolled-back DB, missing/forged intent, unsigned/alternate state fail closed. +- Still ACTIVE: ambiguous pre-commit or genesis failure must remain frozen pending independent recovery; OS Keychain rollback protection, owner/recovery-code rotation, recipient trust and two-screen UI, real two-Mac restore, signed-app production Keychain, provider freshness. No Drive/OAuth, user data sync or release claim. From 4da41fcc667addf41cc5638a02119aea75402925 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 17:21:49 +0100 Subject: [PATCH 21/24] spike(sync): verify native macOS Keychain update and cleanup in signed bundle --- docs/workstreams/secure-sync-google-drive.md | 3 +- experiments/secure_sync/README.md | 18 +++ scripts/probe_packaged_keychain.py | 29 ++++ .../bundled_module_dispatch.py | 1 + src/local_asr_server/macos_keychain_native.py | 111 ++++++++++++++- src/local_asr_server/macos_keychain_probe.py | 117 ++++++++++++++-- test/test_secure_sync_packaged_keychain.py | 131 +++++++++++++++++- 7 files changed, 394 insertions(+), 16 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 47a93144..8a2e2056 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -67,4 +67,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. - SYNC-2 P0 offline candidate **tested**: [Mac #44727751442](https://github.com/daniele21/local-runner-infra/actions/runs/44727751442) exact `d923719a`: **987 app tests PASS, 45 isolated security tests PASS (14 new), FULL_MEDIA PASS**, `local-ci/mac=success`. `owner_ledger.py`: signed SQLite registry + durable nonce consumption, Keychain high-water anchor and fail-closed split-commit; fresh independent future key stored before signed epoch rotation, revoked device cannot decrypt newer data. Fake-Keychain/canonical-path tests, not production. - SYNC-2 local forward-crash recovery **PASS**: [Mac #44763250585](https://github.com/daniele21/local-runner-infra/actions/runs/44763250585), source `a1a962c6`: **987 app tests, 57 security tests (12 new), browser FULL_MEDIA PASS**, `local-ci/mac=success`. Keychain prepared-intent precedes SQLite COMMIT; signed successor and actual epoch key must match. Only explicit owner-confirmed forward completion; old/rolled-back DB, missing/forged intent, unsigned/alternate state fail closed. -- Still ACTIVE: ambiguous pre-commit or genesis failure must remain frozen pending independent recovery; OS Keychain rollback protection, owner/recovery-code rotation, recipient trust and two-screen UI, real two-Mac restore, signed-app production Keychain, provider freshness. No Drive/OAuth, user data sync or release claim. +- Native-app Keychain bridge candidate: isolated `NativeVaultProbeBackend` with device-only `Security.framework` create/update/read/clear/delete and signed-binary second-process proof; packaged GUI execution pending on exact candidate. No production user keys. +- Still ACTIVE: ambiguous pre-commit/genesis recovery, OS Keychain rollback, owner/recovery rotation, recipient trust/two-screen UI, real two-Mac restore, actual product consent/integration and provider freshness. No Drive/OAuth/user-data sync. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index 50a5f0d3..eb7db727 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -142,3 +142,21 @@ cannot establish a genuine human approval or independently archived receipt: the app must introduce a reviewed confirmation boundary before enabling it. Crash during initial genesis bootstrap is still fail-closed and requires independent recovery; no automatic reset/repair was added. + +## Native bundle-backed vault probe (not user vault storage) + +The actual frozen macOS executable has a second diagnostic command, +`secure-sync-native-vault-smoke`, based on `NativeVaultProbeBackend` in +`src/local_asr_server/macos_keychain_native.py`. It uses a distinct fixed +`com.closedroom.app.secure-sync-vault-probe.v1` service and bounded synthetic +account names only. SecItemAdd creates a local device-only, unlocked-login +Keychain record; SecItemUpdate modifies an existing record; a same-signed +second process authenticates a challenge with the new key; a temporary +prepared-intent record is cleared; cleanup is verified. Normal app startup +and all meeting data remain untouched. Failures never fall back to files. + +`scripts/probe_packaged_keychain.py --build` now checks both the previous +single-secret path and this new update/clear/readback path, on an exact-SHA +signed test artifact. This does NOT prove the experimental `keyring` vault +is wired to the product, nor Keychain rollback resistance, durable recovery, +production consent, Developer ID/notarization or a second Mac. diff --git a/scripts/probe_packaged_keychain.py b/scripts/probe_packaged_keychain.py index 28f6d848..3e984215 100644 --- a/scripts/probe_packaged_keychain.py +++ b/scripts/probe_packaged_keychain.py @@ -110,6 +110,32 @@ def main() -> int: } if answer != expected: raise RuntimeError("Invalid bundle Keychain evidence") + # The second command exercises the new experimental native provider: + # create, atomic item update, zero-length preparation, signed-binary + # child read and cleanup. Still only synthetic identifiers and secrets. + vault_proc = subprocess.run( + [str(executable), "secure-sync-native-vault-smoke"], + capture_output=True, text=True, timeout=45, + ) + if vault_proc.returncode != 0: + raise RuntimeError( + "Packaged native-vault Keychain diagnostic failed; " + "use a logged-in macOS GUI session, not a headless runner." + ) + try: + vault_answer = json.loads(vault_proc.stdout.strip()) + except (json.JSONDecodeError, ValueError) as exc: + raise RuntimeError("Native-vault diagnostic returned invalid evidence") from exc + if vault_answer != { + "schema": "closedroom.native-vault-probe/v1", + "status": "pass", + "independent_child": True, + "updated_item": True, + "empty_preparation": True, + "cleanup": True, + "synthetic_only": True, + }: + raise RuntimeError("Native-vault diagnostic evidence mismatched") print(json.dumps({ "status": "pass", "source_revision": revision, @@ -119,6 +145,9 @@ def main() -> int: "independent_child": True, "cleanup": True, "installed_app_modified": False, + "native_vault_probe": True, + "updated_item": True, + "empty_preparation": True, }, sort_keys=True)) return 0 diff --git a/src/local_asr_server/bundled_module_dispatch.py b/src/local_asr_server/bundled_module_dispatch.py index 4e146070..f03e7930 100644 --- a/src/local_asr_server/bundled_module_dispatch.py +++ b/src/local_asr_server/bundled_module_dispatch.py @@ -86,6 +86,7 @@ def dispatch_bundled_module(argv: Sequence[str] | None = None) -> bool: # Offline diagnostics from the actual frozen app binary. No Cocoa/server. if len(arguments) >= 2 and arguments[1] in ( "secure-sync-keychain-smoke", "secure-sync-keychain-smoke-child", + "secure-sync-native-vault-smoke", "secure-sync-native-vault-smoke-child", ): from local_asr_server.macos_keychain_probe import dispatch_keychain_probe return dispatch_keychain_probe(arguments) diff --git a/src/local_asr_server/macos_keychain_native.py b/src/local_asr_server/macos_keychain_native.py index 3a2a0e89..18ebb529 100644 --- a/src/local_asr_server/macos_keychain_native.py +++ b/src/local_asr_server/macos_keychain_native.py @@ -12,6 +12,9 @@ from typing import Iterator SERVICE = "com.closedroom.app.secure-sync-probe.v1" +# Isolated experimental backend. Never stores user vault keys. +VAULT_PROBE_SERVICE = "com.closedroom.app.secure-sync-vault-probe.v1" +MAX_PROBE_PASSWORD_BYTES = 4096 ITEM_NOT_FOUND = -25300 DUPLICATE_ITEM = -25299 SUCCESS = 0 @@ -33,7 +36,10 @@ def _account_ok(account: str) -> bool: class _SecurityAPI: """Low-level macOS Keychain bindings. All created CoreFoundation refs released.""" - def __init__(self) -> None: + def __init__(self, *, service: str = SERVICE) -> None: + if service not in (SERVICE, VAULT_PROBE_SERVICE): + raise NativeKeychainError("Unapproved Keychain service") + self.service = service if sys.platform != "darwin": raise NativeKeychainError("macOS Security.framework is required") cf = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation") @@ -62,12 +68,15 @@ def __init__(self) -> None: sec.SecItemCopyMatching.restype = ctypes.c_int32 sec.SecItemDelete.argtypes = (ptr,) sec.SecItemDelete.restype = ctypes.c_int32 + sec.SecItemUpdate.argtypes = (ptr, ptr) + sec.SecItemUpdate.restype = ctypes.c_int32 self.cf, self.sec = cf, sec self._const = { k: ptr.in_dll(sec, k).value for k in ("kSecClass", "kSecClassGenericPassword", "kSecAttrService", "kSecAttrAccount", "kSecValueData", "kSecReturnData", - "kSecMatchLimit", "kSecMatchLimitOne") + "kSecMatchLimit", "kSecMatchLimitOne", + "kSecAttrAccessible", "kSecAttrAccessibleWhenUnlockedThisDeviceOnly") } self._true = ptr.in_dll(cf, "kCFBooleanTrue").value @@ -81,7 +90,7 @@ def _query(self, account: str, data: bytes | None = None, *, if not q: raise NativeKeychainError("Could not create Keychain query") created.append(q) - service = cf.CFStringCreateWithCString(None, SERVICE.encode("utf-8"), _UTF8) + service = cf.CFStringCreateWithCString(None, self.service.encode("utf-8"), _UTF8) acct = cf.CFStringCreateWithCString(None, account.encode("ascii"), _UTF8) if not service or not acct: if service: @@ -138,10 +147,38 @@ def get(self, account: str) -> bytes | None: def add(self, account: str, secret: bytes) -> None: with self._query(account, data=secret) as query: + # Per-device, unlocked-login-only data. No sync or backup migration. + if self.service == VAULT_PROBE_SERVICE: + self.cf.CFDictionarySetValue( + query, self._const["kSecAttrAccessible"], + self._const["kSecAttrAccessibleWhenUnlockedThisDeviceOnly"], + ) status = self.sec.SecItemAdd(query, None) if status != SUCCESS: raise NativeKeychainError(f"Keychain creation failed (OSStatus {status})") + def update(self, account: str, secret: bytes) -> None: + """Update only an existing Keychain item; never silently create.""" + with self._query(account) as query: + # SecItemUpdate accepts only attributes to change. + attrs = self.cf.CFDictionaryCreateMutable(None, 0, None, None) + if not attrs: + raise NativeKeychainError("Unable to allocate Keychain update") + try: + source = ctypes.create_string_buffer(secret) + blob = self.cf.CFDataCreate(None, source, len(secret)) + if not blob: + raise NativeKeychainError("Unable to encode Keychain update") + try: + self.cf.CFDictionarySetValue(attrs, self._const["kSecValueData"], blob) + status = self.sec.SecItemUpdate(query, attrs) + finally: + self.cf.CFRelease(blob) + finally: + self.cf.CFRelease(attrs) + if status != SUCCESS: + raise NativeKeychainError(f"Keychain update failed (OSStatus {status})") + def delete(self, account: str) -> None: with self._query(account) as query: status = self.sec.SecItemDelete(query) @@ -173,3 +210,71 @@ def delete(self, account: str) -> None: if not _account_ok(account): raise NativeKeychainError("Invalid Keychain account") self._api.delete(account) + + +def _vault_probe_account(account: str) -> bool: + """Allow only explicit synthetic hex IDs and a bounded known field suffix.""" + if not isinstance(account, str) or ":" not in account: + return False + vault_id, suffix = account.split(":", 1) + if not _account_ok(vault_id): + return False + if suffix in ("master", "owner-signing", "owner-pin", "checkpoint", + "ledger-anchor", "ledger-prepare"): + return True + if suffix.startswith("epoch:"): + value = suffix[6:] + return bool(value and value.isascii() and value.isdecimal() + and str(int(value)) == value and 2 <= int(value) <= 999999) + return False + + +class NativeVaultProbeBackend: + """Test-only Keychain provider matching the isolated vault backend protocol. + + This does NOT authorize a vault, store real user keys or initialize sync. + Only fixed VAULT_PROBE_SERVICE is accessible; no plaintext/file fallback. + """ + + def __init__(self, *, _test_api: object | None = None) -> None: + self._api = _SecurityAPI(service=VAULT_PROBE_SERVICE) if _test_api is None else _test_api + + @staticmethod + def _check(service: str, account: str) -> None: + if service != VAULT_PROBE_SERVICE or not _vault_probe_account(account): + raise NativeKeychainError("Unapproved native vault probe account") + + def get_password(self, service: str, account: str) -> str | None: + self._check(service, account) + raw = self._api.get(account) + if raw is None: + return None + if not isinstance(raw, bytes) or len(raw) > MAX_PROBE_PASSWORD_BYTES: + raise NativeKeychainError("Invalid Keychain probe data") + try: + return raw.decode("utf-8") + except UnicodeDecodeError as exc: + raise NativeKeychainError("Invalid Keychain probe encoding") from exc + + def set_password(self, service: str, account: str, password: str) -> None: + self._check(service, account) + if not isinstance(password, str): + raise NativeKeychainError("Invalid probe input") + raw = password.encode("utf-8") + if len(raw) > MAX_PROBE_PASSWORD_BYTES: + raise NativeKeychainError("Probe input too long") + # The Keychain update is atomic per record, not a cross-record CAS. + # No claim is made about multi-record vault state consistency. + old = self._api.get(account) + if old is None: + self._api.add(account, raw) + else: + self._api.update(account, raw) + if self._api.get(account) != raw: + raise NativeKeychainError("Keychain probe readback failed") + + def delete_password(self, service: str, account: str) -> None: + self._check(service, account) + self._api.delete(account) + if self._api.get(account) is not None: + raise NativeKeychainError("Keychain probe deletion unverified") diff --git a/src/local_asr_server/macos_keychain_probe.py b/src/local_asr_server/macos_keychain_probe.py index 98980c58..60f554eb 100644 --- a/src/local_asr_server/macos_keychain_probe.py +++ b/src/local_asr_server/macos_keychain_probe.py @@ -5,6 +5,7 @@ """ from __future__ import annotations +import base64 import hashlib import hmac import json @@ -12,10 +13,14 @@ import subprocess import sys -from local_asr_server.macos_keychain_native import MacKeychain, NativeKeychainError +from local_asr_server.macos_keychain_native import ( + MacKeychain, NativeKeychainError, NativeVaultProbeBackend, VAULT_PROBE_SERVICE, +) COMMAND = "secure-sync-keychain-smoke" CHILD_COMMAND = "secure-sync-keychain-smoke-child" +VAULT_COMMAND = "secure-sync-native-vault-smoke" +VAULT_CHILD_COMMAND = "secure-sync-native-vault-smoke-child" def _require_bundle() -> None: @@ -93,14 +98,106 @@ def run_synthetic_keychain_smoke() -> int: return 0 +def _vault_child(account: str, challenge_hex: str) -> int: + _require_bundle() + if (len(challenge_hex) != 64 + or any(ch not in "0123456789abcdef" for ch in challenge_hex)): + raise NativeKeychainError("Invalid synthetic challenge") + backend = NativeVaultProbeBackend() + stored = backend.get_password(VAULT_PROBE_SERVICE, account) + if stored is None: + raise NativeKeychainError("Native vault probe inaccessible from child") + try: + key = base64.b64decode(stored, validate=True) + except Exception as exc: + raise NativeKeychainError("Corrupt native vault probe secret") from exc + if len(key) != 32: + raise NativeKeychainError("Incorrect native vault probe key length") + print(hmac.digest(key, bytes.fromhex(challenge_hex), hashlib.sha256).hex()) + return 0 + + +def run_native_vault_backend_smoke() -> int: + """Run a no-meeting-data set/update/read/clear/delete roundtrip as app.""" + _require_bundle() + vault_id = secrets.token_hex(16) + account = vault_id + ":master" + prepare_account = vault_id + ":ledger-prepare" + backend = NativeVaultProbeBackend() + created: list[str] = [] + error: BaseException | None = None + cleaned = False + try: + if (backend.get_password(VAULT_PROBE_SERVICE, account) is not None + or backend.get_password(VAULT_PROBE_SERVICE, prepare_account) is not None): + raise NativeKeychainError("Random native vault probe identity collision") + old = secrets.token_bytes(32) + latest = secrets.token_bytes(32) + backend.set_password(VAULT_PROBE_SERVICE, account, base64.b64encode(old).decode("ascii")) + created.append(account) + backend.set_password(VAULT_PROBE_SERVICE, account, base64.b64encode(latest).decode("ascii")) + if backend.get_password(VAULT_PROBE_SERVICE, account) != base64.b64encode(latest).decode("ascii"): + raise NativeKeychainError("Native vault overwrite not readable") + backend.set_password(VAULT_PROBE_SERVICE, prepare_account, "pending") + created.append(prepare_account) + backend.set_password(VAULT_PROBE_SERVICE, prepare_account, "") + if backend.get_password(VAULT_PROBE_SERVICE, prepare_account) != "": + raise NativeKeychainError("Native vault preparation clear failed") + challenge = secrets.token_bytes(32) + proc = subprocess.run( + [sys.executable, VAULT_CHILD_COMMAND, account, challenge.hex()], + capture_output=True, text=True, timeout=25, check=False, + ) + if proc.returncode != 0: + raise NativeKeychainError("Second packaged process cannot access updated secret") + try: + answer = bytes.fromhex(proc.stdout.strip()) + except ValueError as exc: + raise NativeKeychainError("Invalid native vault second-process proof") from exc + if not hmac.compare_digest(answer, hmac.digest(latest, challenge, hashlib.sha256)): + raise NativeKeychainError("Native vault second-process key mismatch") + except BaseException as exc: + error = exc + finally: + try: + for item in reversed(created): + backend.delete_password(VAULT_PROBE_SERVICE, item) + cleaned = ( + backend.get_password(VAULT_PROBE_SERVICE, account) is None + and backend.get_password(VAULT_PROBE_SERVICE, prepare_account) is None + ) + except Exception: + cleaned = False + if not cleaned: + raise NativeKeychainError("Native vault probe cleanup could not be verified") from error + if error is not None: + raise NativeKeychainError("Native vault Keychain probe failed") from error + print(json.dumps({ + "schema": "closedroom.native-vault-probe/v1", + "status": "pass", + "independent_child": True, + "updated_item": True, + "empty_preparation": True, + "cleanup": True, + "synthetic_only": True, + }, sort_keys=True)) + return 0 + + def dispatch_keychain_probe(argv: list[str]) -> bool: """Recognize only diagnostic commands; reject malformed invocations.""" - if len(argv) > 1 and argv[1] in (COMMAND, CHILD_COMMAND): - if argv[1] == COMMAND and len(argv) == 2: - run_synthetic_keychain_smoke() - elif argv[1] == CHILD_COMMAND and len(argv) == 4: - _child(argv[2], argv[3]) - else: - raise SystemExit("Invalid packaged Keychain diagnostic arguments") - return True - return False + if len(argv) < 2 or argv[1] not in ( + COMMAND, CHILD_COMMAND, VAULT_COMMAND, VAULT_CHILD_COMMAND, + ): + return False + if len(argv) == 2 and argv[1] == COMMAND: + run_synthetic_keychain_smoke() + elif len(argv) == 4 and argv[1] == CHILD_COMMAND: + _child(argv[2], argv[3]) + elif len(argv) == 2 and argv[1] == VAULT_COMMAND: + run_native_vault_backend_smoke() + elif len(argv) == 4 and argv[1] == VAULT_CHILD_COMMAND: + _vault_child(argv[2], argv[3]) + else: + raise SystemExit("Invalid packaged Keychain diagnostic arguments") + return True diff --git a/test/test_secure_sync_packaged_keychain.py b/test/test_secure_sync_packaged_keychain.py index adc0b5a9..84c9259b 100644 --- a/test/test_secure_sync_packaged_keychain.py +++ b/test/test_secure_sync_packaged_keychain.py @@ -11,10 +11,13 @@ from local_asr_server.bundled_module_dispatch import dispatch_bundled_module from local_asr_server.macos_keychain_native import ( - MacKeychain, NativeKeychainError, _SecurityAPI, + MacKeychain, NativeKeychainError, NativeVaultProbeBackend, + VAULT_PROBE_SERVICE, _SecurityAPI, ) from local_asr_server.macos_keychain_probe import ( - CHILD_COMMAND, COMMAND, dispatch_keychain_probe, run_synthetic_keychain_smoke, + CHILD_COMMAND, COMMAND, VAULT_COMMAND, VAULT_CHILD_COMMAND, + dispatch_keychain_probe, run_synthetic_keychain_smoke, + run_native_vault_backend_smoke, ) @@ -37,6 +40,11 @@ def add(self, account: str, secret: bytes) -> None: raise NativeKeychainError("synthetic duplicate") self.data[account] = secret + def update(self, account: str, secret: bytes) -> None: + if self.fail_write or account not in self.data: + raise NativeKeychainError("synthetic update error") + self.data[account] = secret + def delete(self, account: str) -> None: self.deleted.append(account) self.data.pop(account, None) @@ -98,6 +106,121 @@ def test_background_ci_cannot_claim_gui_keychain_success(self) -> None: ) +class NativeVaultProbeBackendTests(unittest.TestCase): + def test_create_update_read_clear_and_delete(self) -> None: + api = FakeSecurity() + store = NativeVaultProbeBackend(_test_api=api) + account = "a" * 32 + ":ledger-prepare" + self.assertIsNone(store.get_password(VAULT_PROBE_SERVICE, account)) + store.set_password(VAULT_PROBE_SERVICE, account, "first") + store.set_password(VAULT_PROBE_SERVICE, account, "next") + self.assertEqual(store.get_password(VAULT_PROBE_SERVICE, account), "next") + store.set_password(VAULT_PROBE_SERVICE, account, "") + self.assertEqual(store.get_password(VAULT_PROBE_SERVICE, account), "") + store.delete_password(VAULT_PROBE_SERVICE, account) + self.assertIsNone(store.get_password(VAULT_PROBE_SERVICE, account)) + + def test_service_account_and_size_restrictions(self) -> None: + store = NativeVaultProbeBackend(_test_api=FakeSecurity()) + for name in ("a" * 32, "../vault:master", "A" * 32 + ":master", + "a" * 32 + ":unknown", "a" * 32 + ":epoch:01", + "a" * 32 + ":epoch:1", "a" * 32 + ":epoch:1000000"): + with self.subTest(name=name), self.assertRaises(NativeKeychainError): + store.set_password(VAULT_PROBE_SERVICE, name, "x") + with self.assertRaises(NativeKeychainError): + store.set_password("com.closedroom.app.secure-sync.v1", + "a" * 32 + ":master", "x") + with self.assertRaises(NativeKeychainError): + store.set_password(VAULT_PROBE_SERVICE, "a" * 32 + ":master", "x" * 5000) + store.set_password(VAULT_PROBE_SERVICE, "a" * 32 + ":epoch:2", "ok") + self.assertEqual(store.get_password(VAULT_PROBE_SERVICE, + "a" * 32 + ":epoch:2"), "ok") + + def test_native_failure_corruption_and_nonmac_no_fallback(self) -> None: + api = FakeSecurity() + store = NativeVaultProbeBackend(_test_api=api) + account = "b" * 32 + ":master" + api.fail_write = True + with self.assertRaises(NativeKeychainError): + store.set_password(VAULT_PROBE_SERVICE, account, "new") + api.fail_write = False + api.data[account] = b"\xff" + with self.assertRaises(NativeKeychainError): + store.get_password(VAULT_PROBE_SERVICE, account) + api.data[account] = b"valid" + api.fail_write = True + with self.assertRaises(NativeKeychainError): + store.set_password(VAULT_PROBE_SERVICE, account, "new") + self.assertEqual(api.data[account], b"valid") + with patch("local_asr_server.macos_keychain_native.sys.platform", "linux"): + with self.assertRaises(NativeKeychainError): + NativeVaultProbeBackend() + + def test_second_process_updated_secret_and_probe_cleanup(self) -> None: + api = FakeSecurity() + backend = NativeVaultProbeBackend(_test_api=api) + vault_id = "a" * 32 + challenge = b"z" * 32 + original = b"a" * 32 + replacement = b"b" * 32 + + def fake_child(args: list[str], **_: object): + self.assertEqual(args[1:3], [VAULT_CHILD_COMMAND, vault_id + ":master"]) + self.assertEqual(bytes.fromhex(args[3]), challenge) + stored = backend.get_password(VAULT_PROBE_SERVICE, vault_id + ":master") + proof = hmac.digest(base64.b64decode(stored), challenge, hashlib.sha256).hex() + return type("Child", (), {"returncode": 0, "stdout": proof})() + + import base64 + stdout = io.StringIO() + with ( + patch("local_asr_server.macos_keychain_probe._require_bundle"), + patch("local_asr_server.macos_keychain_probe.NativeVaultProbeBackend", + return_value=backend), + patch("local_asr_server.macos_keychain_probe.secrets.token_hex", + return_value=vault_id), + patch("local_asr_server.macos_keychain_probe.secrets.token_bytes", + side_effect=[original, replacement, challenge]), + patch("local_asr_server.macos_keychain_probe.subprocess.run", + side_effect=fake_child), + contextlib.redirect_stdout(stdout), + ): + self.assertEqual(run_native_vault_backend_smoke(), 0) + self.assertEqual(json.loads(stdout.getvalue())["updated_item"], True) + self.assertEqual(api.data, {}) + self.assertEqual(set(api.deleted), { + vault_id + ":master", vault_id + ":ledger-prepare", + }) + + def test_failed_child_probe_deletes_only_created_records(self) -> None: + api = FakeSecurity() + backend = NativeVaultProbeBackend(_test_api=api) + vault_id = "b" * 32 + with ( + patch("local_asr_server.macos_keychain_probe._require_bundle"), + patch("local_asr_server.macos_keychain_probe.NativeVaultProbeBackend", + return_value=backend), + patch("local_asr_server.macos_keychain_probe.secrets.token_hex", + return_value=vault_id), + patch("local_asr_server.macos_keychain_probe.subprocess.run", + return_value=type("Child", (), {"returncode": 2, "stdout": ""})()), + ): + with self.assertRaises(NativeKeychainError): + run_native_vault_backend_smoke() + self.assertEqual(api.data, {}) + api.data[vault_id + ":master"] = b"preexisting" + with ( + patch("local_asr_server.macos_keychain_probe._require_bundle"), + patch("local_asr_server.macos_keychain_probe.NativeVaultProbeBackend", + return_value=backend), + patch("local_asr_server.macos_keychain_probe.secrets.token_hex", + return_value=vault_id), + ): + with self.assertRaises(NativeKeychainError): + run_native_vault_backend_smoke() + self.assertEqual(api.data[vault_id + ":master"], b"preexisting") + + class SignedBundleDiagnosticTests(unittest.TestCase): def test_normal_app_and_unrelated_commands_are_not_intercepted(self) -> None: self.assertFalse(dispatch_keychain_probe(["ClosedRoom"])) @@ -112,6 +235,10 @@ def test_diagnostic_is_bundle_only_and_arguments_strict(self) -> None: dispatch_bundled_module(["ClosedRoom", COMMAND, "extraneous"]) with self.assertRaises(SystemExit): dispatch_bundled_module(["ClosedRoom", CHILD_COMMAND, "wrong"]) + with self.assertRaises(SystemExit): + dispatch_bundled_module(["ClosedRoom", VAULT_COMMAND, "extraneous"]) + with self.assertRaises(SystemExit): + dispatch_bundled_module(["ClosedRoom", VAULT_CHILD_COMMAND, "wrong"]) def test_packaged_parent_second_process_challenge_and_cleanup(self) -> None: api = FakeSecurity() From cc9d6e97e58192f6179d950d5fc32c3c5803ca3f Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 17:27:18 +0100 Subject: [PATCH 22/24] docs(sync): record exact Mac validation of native Keychain probe backend and outstanding GUI gate --- docs/workstreams/secure-sync-google-drive.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index 8a2e2056..b8ca4152 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -67,5 +67,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. - SYNC-2 P0 offline candidate **tested**: [Mac #44727751442](https://github.com/daniele21/local-runner-infra/actions/runs/44727751442) exact `d923719a`: **987 app tests PASS, 45 isolated security tests PASS (14 new), FULL_MEDIA PASS**, `local-ci/mac=success`. `owner_ledger.py`: signed SQLite registry + durable nonce consumption, Keychain high-water anchor and fail-closed split-commit; fresh independent future key stored before signed epoch rotation, revoked device cannot decrypt newer data. Fake-Keychain/canonical-path tests, not production. - SYNC-2 local forward-crash recovery **PASS**: [Mac #44763250585](https://github.com/daniele21/local-runner-infra/actions/runs/44763250585), source `a1a962c6`: **987 app tests, 57 security tests (12 new), browser FULL_MEDIA PASS**, `local-ci/mac=success`. Keychain prepared-intent precedes SQLite COMMIT; signed successor and actual epoch key must match. Only explicit owner-confirmed forward completion; old/rolled-back DB, missing/forged intent, unsigned/alternate state fail closed. -- Native-app Keychain bridge candidate: isolated `NativeVaultProbeBackend` with device-only `Security.framework` create/update/read/clear/delete and signed-binary second-process proof; packaged GUI execution pending on exact candidate. No production user keys. +- Native Keychain test backend **code PASS**: [Mac #44772706674](https://github.com/daniele21/local-runner-infra/actions/runs/44772706674), source `4da41fcc`: **992 app tests (5 new), 57 offline security tests, FULL_MEDIA PASS**. Isolated `NativeVaultProbeBackend` supports `Security.framework` item create/update/read/clear/delete and second-binary-process proof with synthetic data. **New packaged GUI execution NOT_RUN**; no production vault provisioning or user keys. - Still ACTIVE: ambiguous pre-commit/genesis recovery, OS Keychain rollback, owner/recovery rotation, recipient trust/two-screen UI, real two-Mac restore, actual product consent/integration and provider freshness. No Drive/OAuth/user-data sync. From e90e952707867ddb376ac54e2819dbbaa7fbb712 Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 18:30:08 +0100 Subject: [PATCH 23/24] fix(sync): select macOS Data Protection Keychain for device-only native probe --- docs/workstreams/secure-sync-google-drive.md | 2 +- experiments/secure_sync/README.md | 18 ++++++ scripts/probe_packaged_keychain.py | 16 ++++- src/local_asr_server/macos_keychain_native.py | 17 +++++- src/local_asr_server/macos_keychain_probe.py | 30 ++++++---- test/test_secure_sync_packaged_keychain.py | 58 +++++++++++++++++++ 6 files changed, 125 insertions(+), 16 deletions(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index b8ca4152..b97a5dc8 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -67,5 +67,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. - SYNC-2 P0 offline candidate **tested**: [Mac #44727751442](https://github.com/daniele21/local-runner-infra/actions/runs/44727751442) exact `d923719a`: **987 app tests PASS, 45 isolated security tests PASS (14 new), FULL_MEDIA PASS**, `local-ci/mac=success`. `owner_ledger.py`: signed SQLite registry + durable nonce consumption, Keychain high-water anchor and fail-closed split-commit; fresh independent future key stored before signed epoch rotation, revoked device cannot decrypt newer data. Fake-Keychain/canonical-path tests, not production. - SYNC-2 local forward-crash recovery **PASS**: [Mac #44763250585](https://github.com/daniele21/local-runner-infra/actions/runs/44763250585), source `a1a962c6`: **987 app tests, 57 security tests (12 new), browser FULL_MEDIA PASS**, `local-ci/mac=success`. Keychain prepared-intent precedes SQLite COMMIT; signed successor and actual epoch key must match. Only explicit owner-confirmed forward completion; old/rolled-back DB, missing/forged intent, unsigned/alternate state fail closed. -- Native Keychain test backend **code PASS**: [Mac #44772706674](https://github.com/daniele21/local-runner-infra/actions/runs/44772706674), source `4da41fcc`: **992 app tests (5 new), 57 offline security tests, FULL_MEDIA PASS**. Isolated `NativeVaultProbeBackend` supports `Security.framework` item create/update/read/clear/delete and second-binary-process proof with synthetic data. **New packaged GUI execution NOT_RUN**; no production vault provisioning or user keys. +- Native Keychain regression: [Mac #44772706674](https://github.com/daniele21/local-runner-infra/actions/runs/44772706674) automated PASS at `4da41fcc`, but operator's 2026-11-20 packaged GUI run **FAIL** on the new native-vault probe (old basic probe did not fail). Missing macOS `kSecUseDataProtectionKeychain` on queries using `ThisDeviceOnly` is a specific candidate root cause per Apple docs. Fix adds data-protection qualifier for all isolated CRUD, preserves device-only/no-sync, exposes sanitized OSStatus; exact-head Mac and new GUI proof pending. - Still ACTIVE: ambiguous pre-commit/genesis recovery, OS Keychain rollback, owner/recovery rotation, recipient trust/two-screen UI, real two-Mac restore, actual product consent/integration and provider freshness. No Drive/OAuth/user-data sync. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md index eb7db727..08e2710e 100644 --- a/experiments/secure_sync/README.md +++ b/experiments/secure_sync/README.md @@ -160,3 +160,21 @@ single-secret path and this new update/clear/readback path, on an exact-SHA signed test artifact. This does NOT prove the experimental `keyring` vault is wired to the product, nor Keychain rollback resistance, durable recovery, production consent, Developer ID/notarization or a second Mac. + +### Data Protection Keychain compatibility (macOS) + +A real GUI-user ad-hoc signed packaged run on 2026-11-20 created the app +artifact but failed the **new** native-vault diagnostic; the basic prior +probe had already passed. The previous wrapper incorrectly recommended +the login session without surfacing the OSStatus, so root cause was not +diagnosed by that output alone. + +Apple requires `kSecUseDataProtectionKeychain=true` for any macOS +`kSecAttrAccessibleWhenUnlockedThisDeviceOnly` item. The native probe now +uses that flag for **all** create/read/update/delete queries under its +isolated synthetic service; never uses `kSecAttrSynchronizable` (iCloud), +never removes ThisDeviceOnly and never silently retries against the +legacy login Keychain. The driver reports only a bounded operation and +OSStatus on failure. Pending new exact-HEAD GUI Terminal verification; +ad-hoc signing/entitlements may still be insufficient, and this must be +treated as a separate real-environment gate rather than an automated PASS. diff --git a/scripts/probe_packaged_keychain.py b/scripts/probe_packaged_keychain.py index 3e984215..73e8d9e4 100644 --- a/scripts/probe_packaged_keychain.py +++ b/scripts/probe_packaged_keychain.py @@ -12,6 +12,7 @@ import os import platform import plistlib +import re import subprocess from pathlib import Path @@ -118,9 +119,20 @@ def main() -> int: capture_output=True, text=True, timeout=45, ) if vault_proc.returncode != 0: + # Never emit raw child stdout/stderr: secrets, paths or OS details + # may appear in unexpected tracebacks. Only allowlist an operation + # and a bounded OSStatus from the native Keychain exception. + matches = re.findall( + r"Keychain (creation|read|update|cleanup) failed " + r"\(OSStatus (-?\d{1,7})\)", + vault_proc.stderr[-20000:], + ) + operation, status = matches[-1] if matches else ("unknown", "unavailable") raise RuntimeError( - "Packaged native-vault Keychain diagnostic failed; " - "use a logged-in macOS GUI session, not a headless runner." + "Packaged native-vault Keychain diagnostic failed: " + f"phase={operation}, osstatus={status}, " + f"returncode={vault_proc.returncode}. " + "No fallback or permission change was attempted." ) try: vault_answer = json.loads(vault_proc.stdout.strip()) diff --git a/src/local_asr_server/macos_keychain_native.py b/src/local_asr_server/macos_keychain_native.py index 18ebb529..3af72f90 100644 --- a/src/local_asr_server/macos_keychain_native.py +++ b/src/local_asr_server/macos_keychain_native.py @@ -76,10 +76,24 @@ def __init__(self, *, service: str = SERVICE) -> None: for k in ("kSecClass", "kSecClassGenericPassword", "kSecAttrService", "kSecAttrAccount", "kSecValueData", "kSecReturnData", "kSecMatchLimit", "kSecMatchLimitOne", - "kSecAttrAccessible", "kSecAttrAccessibleWhenUnlockedThisDeviceOnly") + "kSecAttrAccessible", "kSecAttrAccessibleWhenUnlockedThisDeviceOnly", + "kSecUseDataProtectionKeychain") } self._true = ptr.in_dll(cf, "kCFBooleanTrue").value + def _configure_query(self, query: int) -> None: + """Select macOS Data Protection Keychain for every vault probe CRUD. + + kSecAttrAccessible* is defined for macOS only with + kSecUseDataProtectionKeychain=true (not iCloud sync). The SAME + qualifier is required for add, copy, update and delete. Never + retry against the legacy login Keychain if access is denied. + """ + if self.service == VAULT_PROBE_SERVICE: + self.cf.CFDictionarySetValue( + query, self._const["kSecUseDataProtectionKeychain"], self._true, + ) + @contextmanager def _query(self, account: str, data: bytes | None = None, *, read: bool = False) -> Iterator[int]: @@ -105,6 +119,7 @@ def _query(self, account: str, data: bytes | None = None, *, ("kSecAttrAccount", acct), ): cf.CFDictionarySetValue(q, self._const[key], value) + self._configure_query(q) if data is not None: # CFDataCreate copies bytes; the transient C buffer is never logged. source = ctypes.create_string_buffer(data) diff --git a/src/local_asr_server/macos_keychain_probe.py b/src/local_asr_server/macos_keychain_probe.py index 60f554eb..740b6281 100644 --- a/src/local_asr_server/macos_keychain_probe.py +++ b/src/local_asr_server/macos_keychain_probe.py @@ -124,22 +124,23 @@ def run_native_vault_backend_smoke() -> int: account = vault_id + ":master" prepare_account = vault_id + ":ledger-prepare" backend = NativeVaultProbeBackend() - created: list[str] = [] + cleanup_allowed = False error: BaseException | None = None cleaned = False try: if (backend.get_password(VAULT_PROBE_SERVICE, account) is not None or backend.get_password(VAULT_PROBE_SERVICE, prepare_account) is not None): raise NativeKeychainError("Random native vault probe identity collision") + # Own both randomly selected synthetic accounts from here onwards. + # Always attempt cleanup, including ambiguous failed add/readback. + cleanup_allowed = True old = secrets.token_bytes(32) latest = secrets.token_bytes(32) backend.set_password(VAULT_PROBE_SERVICE, account, base64.b64encode(old).decode("ascii")) - created.append(account) backend.set_password(VAULT_PROBE_SERVICE, account, base64.b64encode(latest).decode("ascii")) if backend.get_password(VAULT_PROBE_SERVICE, account) != base64.b64encode(latest).decode("ascii"): raise NativeKeychainError("Native vault overwrite not readable") backend.set_password(VAULT_PROBE_SERVICE, prepare_account, "pending") - created.append(prepare_account) backend.set_password(VAULT_PROBE_SERVICE, prepare_account, "") if backend.get_password(VAULT_PROBE_SERVICE, prepare_account) != "": raise NativeKeychainError("Native vault preparation clear failed") @@ -159,15 +160,20 @@ def run_native_vault_backend_smoke() -> int: except BaseException as exc: error = exc finally: - try: - for item in reversed(created): - backend.delete_password(VAULT_PROBE_SERVICE, item) - cleaned = ( - backend.get_password(VAULT_PROBE_SERVICE, account) is None - and backend.get_password(VAULT_PROBE_SERVICE, prepare_account) is None - ) - except Exception: - cleaned = False + if cleanup_allowed: + try: + # Cleanup even if write raised *after* creating the item. + # Do not touch an account if either preflight check collided. + for item in (prepare_account, account): + backend.delete_password(VAULT_PROBE_SERVICE, item) + cleaned = ( + backend.get_password(VAULT_PROBE_SERVICE, account) is None + and backend.get_password(VAULT_PROBE_SERVICE, prepare_account) is None + ) + except Exception: + cleaned = False + else: + cleaned = error is not None if not cleaned: raise NativeKeychainError("Native vault probe cleanup could not be verified") from error if error is not None: diff --git a/test/test_secure_sync_packaged_keychain.py b/test/test_secure_sync_packaged_keychain.py index 84c9259b..e753fb2f 100644 --- a/test/test_secure_sync_packaged_keychain.py +++ b/test/test_secure_sync_packaged_keychain.py @@ -26,6 +26,7 @@ def __init__(self) -> None: self.data: dict[str, bytes] = {} self.fail_read = False self.fail_write = False + self.fail_after_add = False self.deleted: list[str] = [] def get(self, account: str) -> bytes | None: @@ -39,6 +40,8 @@ def add(self, account: str, secret: bytes) -> None: if account in self.data: raise NativeKeychainError("synthetic duplicate") self.data[account] = secret + if self.fail_after_add: + raise NativeKeychainError("Synthetic post-add readback failure") def update(self, account: str, secret: bytes) -> None: if self.fail_write or account not in self.data: @@ -106,6 +109,44 @@ def test_background_ci_cannot_claim_gui_keychain_success(self) -> None: ) +class DataProtectionKeychainContractTests(unittest.TestCase): + def test_protected_probe_selects_data_protection_on_every_query(self) -> None: + """The qualifier is shared by get/add/update/delete via _query.""" + class FakeCF: + def __init__(self): + self.calls = [] + + def CFDictionarySetValue(self, query, key, value): + self.calls.append((query, key, value)) + + vault = _SecurityAPI.__new__(_SecurityAPI) + vault.service = VAULT_PROBE_SERVICE + vault.cf = FakeCF() + vault._const = {"kSecUseDataProtectionKeychain": "DPK"} + vault._true = True + vault._configure_query("test-query") + self.assertEqual(vault.cf.calls, [("test-query", "DPK", True)]) + + legacy = _SecurityAPI.__new__(_SecurityAPI) + legacy.service = "com.closedroom.app.secure-sync-probe.v1" + legacy.cf = FakeCF() + legacy._const = vault._const + legacy._true = True + legacy._configure_query("legacy-query") + self.assertEqual(legacy.cf.calls, []) + + def test_query_and_crud_share_protected_selector_with_no_fallback(self) -> None: + import inspect + from local_asr_server.macos_keychain_native import _SecurityAPI + source = inspect.getsource(_SecurityAPI) + self.assertIn('"kSecUseDataProtectionKeychain"', source) + self.assertIn('"kSecAttrAccessibleWhenUnlockedThisDeviceOnly"', source) + self.assertIn("self._configure_query(q)", source) + for operation in ("get", "add", "update", "delete"): + self.assertIn(f"def {operation}(", source) + self.assertNotIn("kSecAttrSynchronizable", source) + + class NativeVaultProbeBackendTests(unittest.TestCase): def test_create_update_read_clear_and_delete(self) -> None: api = FakeSecurity() @@ -192,6 +233,23 @@ def fake_child(args: list[str], **_: object): vault_id + ":master", vault_id + ":ledger-prepare", }) + def test_partial_add_failure_cleans_own_synthetic_item(self) -> None: + api = FakeSecurity() + api.fail_after_add = True + backend = NativeVaultProbeBackend(_test_api=api) + vault_id = "d" * 32 + with ( + patch("local_asr_server.macos_keychain_probe._require_bundle"), + patch("local_asr_server.macos_keychain_probe.NativeVaultProbeBackend", + return_value=backend), + patch("local_asr_server.macos_keychain_probe.secrets.token_hex", + return_value=vault_id), + ): + with self.assertRaises(NativeKeychainError): + run_native_vault_backend_smoke() + self.assertEqual(api.data, {}) + self.assertIn(vault_id + ":master", api.deleted) + def test_failed_child_probe_deletes_only_created_records(self) -> None: api = FakeSecurity() backend = NativeVaultProbeBackend(_test_api=api) From 519fd28013bafc8f081cbb77594a355c762715fd Mon Sep 17 00:00:00 2001 From: Daniele21 Date: Fri, 20 Nov 2026 18:35:18 +0100 Subject: [PATCH 24/24] docs(sync): record exact Mac PASS for protected native Keychain query fix; GUI gate pending --- docs/workstreams/secure-sync-google-drive.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/workstreams/secure-sync-google-drive.md b/docs/workstreams/secure-sync-google-drive.md index b97a5dc8..00f45d1e 100644 --- a/docs/workstreams/secure-sync-google-drive.md +++ b/docs/workstreams/secure-sync-google-drive.md @@ -67,5 +67,5 @@ Non-goals of first pilot: remotely transcribing, syncing audio/screenshots/model - SYNC-2 offline proof at `ca4549f4`: [Mac run 44709517507](https://github.com/daniele21/local-runner-infra/actions/runs/44709517507) **987 app tests PASS, 31 isolated security tests PASS, browser FULL_MEDIA PASS**, `local-ci/mac=success`. Random 256-bit recovery code + AES-GCM capsule of owner key/vault key/trusted checkpoint; 5-minute X25519 read-only grant signed by Ed25519 owner, independently pinned owner key and manual SAS UX required. All synthetic, no production sync or real two-Mac pairing. - SYNC-2 P0 offline candidate **tested**: [Mac #44727751442](https://github.com/daniele21/local-runner-infra/actions/runs/44727751442) exact `d923719a`: **987 app tests PASS, 45 isolated security tests PASS (14 new), FULL_MEDIA PASS**, `local-ci/mac=success`. `owner_ledger.py`: signed SQLite registry + durable nonce consumption, Keychain high-water anchor and fail-closed split-commit; fresh independent future key stored before signed epoch rotation, revoked device cannot decrypt newer data. Fake-Keychain/canonical-path tests, not production. - SYNC-2 local forward-crash recovery **PASS**: [Mac #44763250585](https://github.com/daniele21/local-runner-infra/actions/runs/44763250585), source `a1a962c6`: **987 app tests, 57 security tests (12 new), browser FULL_MEDIA PASS**, `local-ci/mac=success`. Keychain prepared-intent precedes SQLite COMMIT; signed successor and actual epoch key must match. Only explicit owner-confirmed forward completion; old/rolled-back DB, missing/forged intent, unsigned/alternate state fail closed. -- Native Keychain regression: [Mac #44772706674](https://github.com/daniele21/local-runner-infra/actions/runs/44772706674) automated PASS at `4da41fcc`, but operator's 2026-11-20 packaged GUI run **FAIL** on the new native-vault probe (old basic probe did not fail). Missing macOS `kSecUseDataProtectionKeychain` on queries using `ThisDeviceOnly` is a specific candidate root cause per Apple docs. Fix adds data-protection qualifier for all isolated CRUD, preserves device-only/no-sync, exposes sanitized OSStatus; exact-head Mac and new GUI proof pending. +- Native Keychain fix: user's 2026-11-20 GUI packaged run **FAIL** on new vault probe after successful artifact build. Likely root cause: missing `kSecUseDataProtectionKeychain` qualifier for macOS `ThisDeviceOnly` item. Patched in `e90e9527` for all native CRUD without fallback; [Mac #44783958239](https://github.com/daniele21/local-runner-infra/actions/runs/44783958239) **995 app tests PASS (3 new), 57 isolated security tests PASS, FULL_MEDIA PASS**, `local-ci/mac=success`. Sanitized OSStatus now available if rerun fails. **New exact-head GUI Keychain still PENDING**, not a verified fix on user's session. - Still ACTIVE: ambiguous pre-commit/genesis recovery, OS Keychain rollback, owner/recovery rotation, recipient trust/two-screen UI, real two-Mac restore, actual product consent/integration and provider freshness. No Drive/OAuth/user-data sync.