diff --git a/.github/ci/local-test.sh b/.github/ci/local-test.sh index e03cc2d1..fa93f4ac 100644 --- a/.github/ci/local-test.sh +++ b/.github/ci/local-test.sh @@ -28,6 +28,18 @@ 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 +# 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/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 new file mode 100644 index 00000000..00f45d1e --- /dev/null +++ b/docs/workstreams/secure-sync-google-drive.md @@ -0,0 +1,71 @@ +# 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: 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 + +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, 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 | +| SYNC-6 | Consider mobile companion/read-write editing **only after** the above is verified | BLOCKED | Product evidence and conflict-management design | + +### Security prototype boundary + +- `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. + +### Physical Keychain proof and Mac evidence + +- [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 + +- 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 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 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. diff --git a/experiments/secure_sync/README.md b/experiments/secure_sync/README.md new file mode 100644 index 00000000..08e2710e --- /dev/null +++ b/experiments/secure_sync/README.md @@ -0,0 +1,180 @@ +# Secure sync crypto proof — NOT production sync + +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: + +```sh +uv run --no-project --with cryptography --with keyring -- python -m unittest discover -s experiments/secure_sync -p 'test_*.py' -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 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. + +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. 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 +``` + +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. + +## 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. + +## 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). 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 + 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. + +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. + +## 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. + +### 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/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/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()) diff --git a/experiments/secure_sync/owner_ledger.py b/experiments/secure_sync/owner_ledger.py new file mode 100644 index 00000000..bf5cb2b6 --- /dev/null +++ b/experiments/secure_sync/owner_ledger.py @@ -0,0 +1,567 @@ +"""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. 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 + +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 _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() + 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) + 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 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") + # 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( + 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() + # 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( + "SELECT document FROM state WHERE vault_id = ?", (self.vault_id,), + ).fetchone()[0]), + ) + if result.rowcount != 1: + raise LedgerError("Concurrent owner ledger update refused") + 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, + 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/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/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_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() diff --git a/experiments/secure_sync/test_owner_ledger.py b/experiments/secure_sync/test_owner_ledger.py new file mode 100644 index 00000000..8f8a80bd --- /dev/null +++ b/experiments/secure_sync/test_owner_ledger.py @@ -0,0 +1,498 @@ +"""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) + + + 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/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() 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..a11b7c14 --- /dev/null +++ b/experiments/secure_sync/vault_keychain.py @@ -0,0 +1,215 @@ +"""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 + + 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) + + 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", "") 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") diff --git a/scripts/probe_packaged_keychain.py b/scripts/probe_packaged_keychain.py new file mode 100644 index 00000000..73e8d9e4 --- /dev/null +++ b/scripts/probe_packaged_keychain.py @@ -0,0 +1,168 @@ +#!/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 re +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") + # 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: + # 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: " + 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()) + 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, + "signing": signing, + "bundle_id": "com.closedroom.app", + "scope": "packaged-GUI-Terminal-Keychain-only", + "independent_child": True, + "cleanup": True, + "installed_app_modified": False, + "native_vault_probe": True, + "updated_item": True, + "empty_preparation": True, + }, 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..f03e7930 100644 --- a/src/local_asr_server/bundled_module_dispatch.py +++ b/src/local_asr_server/bundled_module_dispatch.py @@ -83,6 +83,13 @@ 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", + "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) 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..3af72f90 --- /dev/null +++ b/src/local_asr_server/macos_keychain_native.py @@ -0,0 +1,295 @@ +"""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" +# 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 +_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, *, 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") + 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 + 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", + "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]: + 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, self.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) + 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) + 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: + # 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) + 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) + + +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 new file mode 100644 index 00000000..740b6281 --- /dev/null +++ b/src/local_asr_server/macos_keychain_probe.py @@ -0,0 +1,209 @@ +"""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 base64 +import hashlib +import hmac +import json +import secrets +import subprocess +import sys + +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: + 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 _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() + 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")) + 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") + 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: + 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: + 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) < 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 new file mode 100644 index 00000000..e753fb2f --- /dev/null +++ b/test/test_secure_sync_packaged_keychain.py @@ -0,0 +1,364 @@ +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, NativeVaultProbeBackend, + VAULT_PROBE_SERVICE, _SecurityAPI, +) +from local_asr_server.macos_keychain_probe import ( + CHILD_COMMAND, COMMAND, VAULT_COMMAND, VAULT_CHILD_COMMAND, + dispatch_keychain_probe, run_synthetic_keychain_smoke, + run_native_vault_backend_smoke, +) + + +class FakeSecurity: + 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: + 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 + 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: + raise NativeKeychainError("synthetic update error") + 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() + + 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 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() + 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_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) + 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"])) + 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"]) + 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() + 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()