From d99062b6f80954ce8892441b2157a052d66c3a5a Mon Sep 17 00:00:00 2001 From: LibraVault Date: Sun, 23 Aug 2026 17:01:26 +0000 Subject: [PATCH] =?UTF-8?q?feat(ios):=20core=20Cloud=20TTS=20foundation=20?= =?UTF-8?q?=E2=80=94=20Keychain=20store,=20consent,=20pure=20gate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR 1 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), issue #452. Mirrors Android's core:cloudtts foundation (#462), adapted where iOS's own conventions genuinely differ rather than ported literally. New Sources/Features/CloudTTS/: - CloudProviderId — the PRD's closed 5-vendor list (§3). - CloudCredentialFields — per-provider required-field sets (Amazon Polly's SigV4 needs 3 fields, Azure needs 2, the rest need 1 bearer key) — same reasoning as Android's identical Map credential shape, kept in sync by hand. - CloudApiKeyStore protocol + KeychainCloudApiKeyStore — one kSecClassGenericPassword item per provider, kSecAttrAccessibleWhen UnlockedThisDeviceOnly. Deliberately does NOT additionally wrap through HardwareKeyWrap/the Secure Enclave the way Android's RealCloudApiKeyStore wraps through HardwareKeyWrapFactory before writing to DataStore — that extra layer exists on Android because a DataStore file has no OS-level encryption-at-rest of its own; the Keychain already provides that here, and a BYOK vendor key isn't LibraVault's root of trust the way the vault master key is. - CloudVoicePreferences — consent/selected-provider/selected-voice-id, mirrors SupporterStatusPersistence's shape (not bolted onto UserPreferencesPersistence, whose existing keys use the opposite "true by default" polarity). - CloudTtsGate — pure function, not a class wrapping live StoreKitBillingManager/CloudVoicePreferences: StoreKitBillingManager needs a live SKTestSession to test for real (documented Xcode 26.5 CLI gap), so the actual AND logic lives in a function of two Bools instead, letting CloudTtsGateTests cover all four quadrants with no StoreKit dependency at all. - CloudTtsProvider protocol — shared shape for the 5 vendor adapters (next PR). Tests: CloudTtsGateTests (4-quadrant + explicit "subscription alone never opens the gate" regression guard), CloudVoicePreferencesTests, CloudCredentialFieldsTests, CloudApiKeyStoreTests (real Keychain round-trip — guarded with the same errSecMissingEntitlement XCTSkip pattern SecureEnclaveHardwareKeyWrapTests already uses for this CI job's CODE_SIGNING_ALLOWED=NO environment), FakeCloudApiKeyStore for downstream test targets (engine/UI PRs). No Xcode/macOS available in this environment — verified by careful manual review against this codebase's existing conventions (matched HardwareKeyWrap/SecureEnclaveHardwareKeyWrapFactory's Keychain query style, SupporterStatusPersistence's UserDefaults shape, and the skipIfKeychainKeyPersistenceUnavailable CI gotcha) rather than a local build; real verification is this PR's CI run (ios-app-build.yml). Closes nothing yet — first of 4 iOS PRs for #452. --- .../Features/CloudTTS/CloudApiKeyStore.swift | 43 ++++++ .../CloudTTS/CloudCredentialFields.swift | 43 ++++++ .../Features/CloudTTS/CloudProviderId.swift | 27 ++++ .../Features/CloudTTS/CloudTtsGate.swift | 24 ++++ .../Features/CloudTTS/CloudTtsProvider.swift | 58 ++++++++ .../CloudTTS/CloudVoicePreferences.swift | 61 +++++++++ .../CloudTTS/KeychainCloudApiKeyStore.swift | 105 +++++++++++++++ .../CloudTTS/CloudApiKeyStoreTests.swift | 124 ++++++++++++++++++ .../CloudTTS/CloudCredentialFieldsTests.swift | 37 ++++++ .../CloudTTS/CloudTtsGateTests.swift | 29 ++++ .../CloudTTS/CloudVoicePreferencesTests.swift | 58 ++++++++ .../CloudTTS/FakeCloudApiKeyStore.swift | 27 ++++ 12 files changed, 636 insertions(+) create mode 100644 ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudApiKeyStore.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudCredentialFields.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudProviderId.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudTtsGate.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudTtsProvider.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudVoicePreferences.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/KeychainCloudApiKeyStore.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudApiKeyStoreTests.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudCredentialFieldsTests.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudTtsGateTests.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudVoicePreferencesTests.swift create mode 100644 ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/FakeCloudApiKeyStore.swift diff --git a/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudApiKeyStore.swift b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudApiKeyStore.swift new file mode 100644 index 00000000..ee2cf3c8 --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudApiKeyStore.swift @@ -0,0 +1,43 @@ +import Foundation + +/// iOS counterpart to Android's `CloudApiKeyStore` interface (core/cloudtts/CloudApiKeyStore.kt) +/// — a protocol, not a direct Keychain call at every call site, for the same reason +/// `HardwareKeyWrap` is one (see that file's doc comment): fakeable in plain unit tests +/// without touching the real Keychain. Credentials are a `[CloudCredentialField: String]` +/// map, not a single `apiKey: String`, matching Android's identical shape (see +/// `CloudCredentialFields`'s doc comment for why). +protocol CloudApiKeyStore { + /// Overwrites any existing credentials for `provider`. Callers (see + /// `CloudApiKeyStoreError`) are expected to have already validated the credentials + /// against the real vendor API (PRD §6: "validated with a single cheap test call, + /// then stored") — this method itself does no validation, only storage. + func save(provider: CloudProviderId, credentials: [CloudCredentialField: String]) throws + + /// `nil` if nothing has been saved for `provider` yet. + func load(provider: CloudProviderId) -> [CloudCredentialField: String]? + + /// No-op if nothing was saved for `provider`. + func clear(provider: CloudProviderId) +} + +/// Errors `CloudApiKeyStore` conformers can throw. +enum CloudApiKeyStoreError: LocalizedError, Equatable { + /// `credentials`' keys didn't exactly match `CloudCredentialFields.requiredFields` + /// for the given provider — mirrors Android's `RealCloudApiKeyStore.saveCredentials` + /// `require()` check, catching a caller bug (a missing/extra field) before it's + /// silently stored in a shape a vendor adapter can't actually use. + case fieldMismatch(provider: CloudProviderId) + + /// A Keychain operation (`SecItemAdd`/`SecItemUpdate`/`SecItemDelete`) failed for a + /// reason other than "item not found." + case keychainError(status: OSStatus) + + var errorDescription: String? { + switch self { + case .fieldMismatch(let provider): + return "Credentials for \(provider.displayName) don't match its required fields" + case .keychainError(let status): + return "Keychain operation failed (OSStatus \(status))" + } + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudCredentialFields.swift b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudCredentialFields.swift new file mode 100644 index 00000000..47ba2bae --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudCredentialFields.swift @@ -0,0 +1,43 @@ +import Foundation + +/// Mirrors Android's `CloudCredentialFields` object (core/cloudtts/CloudApiKeyStore.kt) +/// field-by-field — kept in sync by hand, like `StoreKitBillingManager`'s product ids, +/// since Kotlin and Swift can't share a constant here. A single `apiKey: String` couldn't +/// express Amazon Polly's real (SigV4, multi-field) auth — same reasoning as Android's +/// identical `Map`-shaped credentials. +enum CloudCredentialField: String, Codable, CaseIterable, Hashable { + case apiKey + case region + case accessKeyID + case secretAccessKey + + var label: String { + switch self { + case .apiKey: return "API Key" + case .region: return "Region" + case .accessKeyID: return "Access Key ID" + case .secretAccessKey: return "Secret Access Key" + } + } +} + +enum CloudCredentialFields { + /// Which fields each vendor's real auth scheme actually needs. Mirrors Android's + /// `CloudCredentialFields.requiredFields` exactly: + /// - ElevenLabs (`xi-api-key` header), OpenAI, Google Cloud TTS (bearer header) — + /// a single API key. + /// - Azure AI Speech — API key plus a region (its host is region-scoped: + /// `{region}.tts.speech.microsoft.com`). + /// - Amazon Polly — SigV4 request signing needs an access key id, secret access + /// key, AND region; there's no single bearer token. + static func requiredFields(for provider: CloudProviderId) -> Set { + switch provider { + case .elevenLabs, .openAI, .googleCloudTTS: + return [.apiKey] + case .azureSpeech: + return [.apiKey, .region] + case .amazonPolly: + return [.accessKeyID, .secretAccessKey, .region] + } + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudProviderId.swift b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudProviderId.swift new file mode 100644 index 00000000..d704721f --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudProviderId.swift @@ -0,0 +1,27 @@ +import Foundation + +/// Mirrors Android's `CloudProviderId` (core/cloudtts/CloudProviderId.kt) — the PRD's +/// closed list of five vendor presets (docs/cloud-tts-premium-prd.md §3). `String`-backed +/// and `Codable` so it round-trips directly through `UserDefaults`/Keychain storage +/// (see `CloudVoicePreferences`/`KeychainCloudApiKeyStore`) without a separate raw-value +/// mapping layer. Raw values are camelCase (Swift convention), NOT the same strings as +/// Android's `CloudProviderId.name` (SCREAMING_SNAKE_CASE, e.g. `"GOOGLE_CLOUD_TTS"`) — +/// the two platforms never share persisted state, so there's no cross-platform format to +/// keep in sync here, unlike `StoreKitBillingManager`'s product ids. +enum CloudProviderId: String, CaseIterable, Codable { + case elevenLabs + case openAI + case googleCloudTTS + case azureSpeech + case amazonPolly + + var displayName: String { + switch self { + case .elevenLabs: return "ElevenLabs" + case .openAI: return "OpenAI" + case .googleCloudTTS: return "Google Cloud TTS" + case .azureSpeech: return "Azure AI Speech" + case .amazonPolly: return "Amazon Polly" + } + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudTtsGate.swift b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudTtsGate.swift new file mode 100644 index 00000000..9af7c79e --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudTtsGate.swift @@ -0,0 +1,24 @@ +import Foundation + +/// The four-quadrant gate (PRD §4): a real subscription AND explicit consent are BOTH +/// required before any cloud TTS call is allowed. A pure function taking two plain +/// `Bool`s, not a class wrapping live `StoreKitBillingManager`/`CloudVoicePreferences` +/// instances — `StoreKitBillingManager.isSubscribed` needs a live `SKTestSession`/ +/// `.storekit` config to exercise for real, a documented Xcode 26.5 `xcodebuild test` +/// CLI gap (see `StoreKitBillingManagerTests.skipIfStoreKitConfigUnavailableViaCLI`'s doc +/// comment). Extracting the actual AND logic into a function of two `Bool`s means +/// `CloudTtsGateTests` can exercise all four quadrants with neither a live StoreKit +/// session nor a real UserDefaults-backed `CloudVoicePreferences` — mirrors Android's +/// `CloudTtsGate` combining `SupportBillingClient.observeSubscriptionActive()` and +/// `TtsPreferences.consentFlow`, minus the `Flow`/reactive plumbing iOS doesn't need +/// here (both inputs are already synchronously readable: `isSubscribed` is a `@Published` +/// property already resolved by billing-manager init, `consentEnabled` is a plain +/// `UserDefaults` read). +enum CloudTtsGate { + /// Explicitly `isSubscribed`, NOT `isSupporter` — a one-time tip alone (no active + /// subscription) must never open this gate, matching the PRD-mandated distinction + /// `StoreKitBillingManager.isSubscribed`'s own doc comment draws from `isSupporter`. + static func canUseCloudTts(isSubscribed: Bool, consentEnabled: Bool) -> Bool { + isSubscribed && consentEnabled + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudTtsProvider.swift b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudTtsProvider.swift new file mode 100644 index 00000000..6be41db3 --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudTtsProvider.swift @@ -0,0 +1,58 @@ +import Foundation + +/// One HTTP call shape shared by all five vendor adapters (`Vendors/*Adapter.swift`) — +/// iOS counterpart to Android's `CloudTtsProvider` interface (core/cloudtts/CloudTtsProvider.kt). +/// A protocol, not a direct `URLSession` call at every call site, both for fakeability in +/// tests and so `CloudTtsEngine` can dispatch to whichever vendor is actually selected +/// without a hardcoded `switch` of its own — `RealCloudTtsProvider` (added in the +/// vendors PR) is the dispatcher; this is just the shared contract. +/// +/// Every conformer/caller MUST check `CloudTtsGate.canUseCloudTts` immediately before +/// calling either method below — this protocol has no way to enforce that itself, since +/// enforcing it here would require this protocol to depend on `StoreKitBillingManager`/ +/// `CloudVoicePreferences`, which would invert the dependency direction this feature is +/// built on (see the implementation plan's "Engine integration seam"). `CloudTtsEngine` +/// (added in the engine PR) is the actual enforcement point. +protocol CloudTtsProvider { + /// Synthesizes `text` as speech using `voiceID` and `credentials`, returning the raw + /// audio bytes. Format is vendor-specific (MP3 for most) — handled generically by + /// `AVAudioPlayer` on the `CloudTtsEngine` side, the same "don't care about the + /// container format, just play the bytes" approach Android's `MediaPlayer`-based + /// `CloudPlayback` takes. + func synthesize( + provider: CloudProviderId, + text: String, + voiceID: String, + credentials: [CloudCredentialField: String] + ) async throws -> Data + + /// A single cheap validation call (PRD §6: "validated with a single cheap test + /// call, then stored") — never persists anything itself. The caller only saves + /// credentials (via `CloudApiKeyStore`) once this succeeds. + func validateKey( + provider: CloudProviderId, + credentials: [CloudCredentialField: String] + ) async throws +} + +/// Errors this protocol's conformers throw — deliberately generic (not +/// per-vendor-specific HTTP status parsing) since callers only need to know "did it +/// work," not why, to decide whether to fall back to the on-device engine. Mirrors +/// Android's `CloudTtsProvider`'s `Result<...>` failure shape, adapted to Swift's +/// `throws` convention. +enum CloudTtsProviderError: LocalizedError, Equatable { + case missingCredentials(field: CloudCredentialField) + case httpError(statusCode: Int, body: String) + case invalidResponse + + var errorDescription: String? { + switch self { + case .missingCredentials(let field): + return "Missing required field: \(field.label)" + case .httpError(let statusCode, let body): + return "HTTP \(statusCode): \(body.prefix(200))" + case .invalidResponse: + return "Unexpected response from the TTS vendor" + } + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudVoicePreferences.swift b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudVoicePreferences.swift new file mode 100644 index 00000000..f785e7b8 --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/CloudVoicePreferences.swift @@ -0,0 +1,61 @@ +import Foundation + +/// Consent + selection state for Premium Cloud TTS Voices (PRD §4/§6). Mirrors +/// `SupporterStatusPersistence`'s exact shape (plain, non-`ObservableObject` struct, +/// injectable `UserDefaults` for test isolation, namespaced `"xyz.libravault.*"` keys) — +/// deliberately NOT bolted onto `UserPreferencesPersistence`, whose existing boolean +/// keys (e.g. `loadMiniPlayerAutoHideEnabled`) use `object(forKey:) as? Bool` specifically +/// to default to `true`/enabled when absent. Consent here needs the opposite default +/// (PRD §4: off until explicitly accepted), which `UserDefaults.bool(forKey:)`'s +/// absent-reads-false behavior already gives for free — reusing the wrong-polarity +/// pattern would risk a future refactor accidentally flipping the default. +struct CloudVoicePreferences { + private let defaults: UserDefaults + + private enum Key { + static let consentEnabled = "xyz.libravault.cloudtts.consentEnabled" + static let selectedProvider = "xyz.libravault.cloudtts.selectedProvider" + static let selectedVoiceID = "xyz.libravault.cloudtts.selectedVoiceID" + } + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + /// Absent key correctly reads as `false` via `bool(forKey:)` — a never-configured + /// install must default to consent OFF (PRD §4: "off by default — enabling it sends + /// text to a vendor's servers"), the same "do not silently opt in" reasoning as + /// Android's `CLOUD_VOICES_CONSENT_KEY` default. + func loadConsentEnabled() -> Bool { + defaults.bool(forKey: Key.consentEnabled) + } + + func save(consentEnabled: Bool) { + defaults.set(consentEnabled, forKey: Key.consentEnabled) + } + + func loadSelectedProvider() -> CloudProviderId? { + guard let raw = defaults.string(forKey: Key.selectedProvider) else { return nil } + return CloudProviderId(rawValue: raw) + } + + func save(selectedProvider: CloudProviderId?) { + defaults.set(selectedProvider?.rawValue, forKey: Key.selectedProvider) + } + + /// Scoped to Cloud TTS only — deliberately a SEPARATE key from + /// `UserPreferencesPersistence`'s TTS engine type, not shared the way Android's + /// `TtsPreferences.selectedVoiceFlow` is shared across all three engine types + /// there. iOS's on-device engines (`TTSEngineBridge`/`PocketTTSEngine`) don't have + /// a "selected voice id" concept of their own to collide with (see + /// `TTSEngineBridge.voice(for:)` — the system voice is auto-detected from text + /// language, never user-picked), so there's no equivalent stale-carryover risk to + /// guard against here the way `CloudVoicesSection`'s Android counterpart does. + func loadSelectedVoiceID() -> String? { + defaults.string(forKey: Key.selectedVoiceID) + } + + func save(selectedVoiceID: String?) { + defaults.set(selectedVoiceID, forKey: Key.selectedVoiceID) + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/KeychainCloudApiKeyStore.swift b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/KeychainCloudApiKeyStore.swift new file mode 100644 index 00000000..d85457e0 --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVault/Sources/Features/CloudTTS/KeychainCloudApiKeyStore.swift @@ -0,0 +1,105 @@ +import Foundation +import Security + +/// Real, Keychain-backed `CloudApiKeyStore`. One `kSecClassGenericPassword` item per +/// provider, keyed by `kSecAttrAccount` = the provider's raw value under a fixed +/// `kSecAttrService` — a different shape from `SecureEnclaveHardwareKeyWrapFactory`'s +/// `kSecClassKey` items (that class stores an actual EC keypair; this stores an +/// arbitrary opaque secret, which `kSecClassGenericPassword` is Apple's documented class +/// for). +/// +/// Deliberately does NOT additionally wrap the value through `HardwareKeyWrap`/the +/// Secure Enclave the way Android's `RealCloudApiKeyStore` wraps through +/// `HardwareKeyWrapFactory` before writing to DataStore — that extra layer exists on +/// Android because a DataStore file is plain app-private storage with no OS-level +/// encryption-at-rest of its own. The iOS Keychain already provides encryption-at-rest +/// itself (backed by the Secure Enclave-derived class keys, the same hierarchy +/// `SecureEnclaveHardwareKeyWrap` sits on top of for the vault master key), and +/// `kSecAttrAccessibleWhenUnlockedThisDeviceOnly` below is the standard, sufficient +/// pattern for a secret like a BYOK vendor API key — unlike the vault master key, this +/// isn't LibraVault's root of trust, so no extra ECIES wrapping layer is warranted here. +/// +/// Credentials are JSON-encoded as `[String: String]` (not `[CloudCredentialField: +/// String]` directly) before being handed to `JSONEncoder` — dictionaries keyed by a +/// custom `RawRepresentable` enum aren't guaranteed to encode as a JSON object across +/// Codable's synthesized behavior, so the field/value pairs are converted to plain +/// `String` keys first, matching a pattern already proven safe rather than relying on +/// an implementation detail. +final class KeychainCloudApiKeyStore: CloudApiKeyStore { + + private static let service = "xyz.libravault.cloudtts.apikey" + + func save(provider: CloudProviderId, credentials: [CloudCredentialField: String]) throws { + let requiredFields = CloudCredentialFields.requiredFields(for: provider) + guard Set(credentials.keys) == requiredFields else { + throw CloudApiKeyStoreError.fieldMismatch(provider: provider) + } + + let plainKeyed = Dictionary(uniqueKeysWithValues: credentials.map { ($0.key.rawValue, $0.value) }) + let data: Data + do { + data = try JSONEncoder().encode(plainKeyed) + } catch { + // JSONEncoder failing on a [String: String] would mean something is + // fundamentally broken about the runtime, not a real recoverable case — + // there's no vendor-specific reason this should ever throw, so it's + // surfaced as the same keychainError case with status 0 rather than adding + // a third error case nothing else in this type could ever produce. + throw CloudApiKeyStoreError.keychainError(status: 0) + } + + // Delete-then-add, not SecItemUpdate: mirrors + // SecureEnclaveHardwareKeyWrapFactory.createNew's "any existing item under this + // identity is replaced" contract — simpler than branching on whether an item + // already exists, and this is a cheap, infrequent (user-initiated) operation. + deleteItem(provider: provider) + + var query = keychainQuery(provider: provider) + query[kSecValueData as String] = data + query[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly + + let status = SecItemAdd(query as CFDictionary, nil) + guard status == errSecSuccess else { + throw CloudApiKeyStoreError.keychainError(status: status) + } + } + + func load(provider: CloudProviderId) -> [CloudCredentialField: String]? { + var query = keychainQuery(provider: provider) + query[kSecReturnData as String] = true + query[kSecMatchLimit as String] = kSecMatchLimitOne + + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + guard status == errSecSuccess, let data = item as? Data else { return nil } + + guard let plainKeyed = try? JSONDecoder().decode([String: String].self, from: data) else { + return nil + } + // A field name that no longer maps to a known CloudCredentialField (e.g. a + // stale Keychain item from a since-removed field) is dropped rather than + // failing the whole load — the caller's own required-fields check downstream + // (CloudTtsEngine/onValidateAndSaveCloudKey-equivalent) is what should reject a + // now-incomplete credential set, not this layer silently returning nil for an + // otherwise-readable item. + return Dictionary(uniqueKeysWithValues: plainKeyed.compactMap { key, value in + CloudCredentialField(rawValue: key).map { ($0, value) } + }) + } + + func clear(provider: CloudProviderId) { + deleteItem(provider: provider) + } + + private func deleteItem(provider: CloudProviderId) { + SecItemDelete(keychainQuery(provider: provider) as CFDictionary) + } + + private func keychainQuery(provider: CloudProviderId) -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.service, + kSecAttrAccount as String: provider.rawValue, + ] + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudApiKeyStoreTests.swift b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudApiKeyStoreTests.swift new file mode 100644 index 00000000..31ab2218 --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudApiKeyStoreTests.swift @@ -0,0 +1,124 @@ +import XCTest +import Security +@testable import LibraVault + +/// Tests for `KeychainCloudApiKeyStore` against the REAL Keychain — Simulator-safe, +/// unlike Secure Enclave key persistence (see `SecureEnclaveHardwareKeyWrapTests`'s doc +/// comment): `kSecClassGenericPassword` items don't need real hardware, only Keychain +/// availability. Still guarded the same way that file is, though: this repo's +/// `ios-app-build.yml` CI job runs `xcodebuild test` with `CODE_SIGNING_ALLOWED=NO`, +/// leaving the test bundle with zero entitlements — confirmed (2026-08-19, see that +/// file) to break `kSecClassKey` persistence with `errSecMissingEntitlement`, and +/// generic-password persistence is not guaranteed to be exempt from the same +/// restriction. `skipIfKeychainPersistenceUnavailable` below mirrors that file's own +/// skip helper so this suite degrades the same way instead of failing CI outright if +/// that turns out to be true here too. +final class CloudApiKeyStoreTests: XCTestCase { + + private var providersToClean: [CloudProviderId] = [] + + override func tearDown() { + let store = KeychainCloudApiKeyStore() + providersToClean.forEach { store.clear(provider: $0) } + providersToClean.removeAll() + super.tearDown() + } + + private func skipIfKeychainPersistenceUnavailable(_ error: Error) throws { + guard case CloudApiKeyStoreError.keychainError(let status) = error, status == errSecMissingEntitlement else { + return + } + throw XCTSkip("Keychain generic-password persistence unavailable (errSecMissingEntitlement) — this CI job runs with CODE_SIGNING_ALLOWED=NO; needs a signed build or real device") + } + + func testLoadReturnsNilWhenNothingSaved() { + let store = KeychainCloudApiKeyStore() + XCTAssertNil(store.load(provider: .elevenLabs)) + } + + func testSaveThenLoadRoundTripsSingleFieldCredentials() throws { + let store = KeychainCloudApiKeyStore() + providersToClean.append(.openAI) + do { + try store.save(provider: .openAI, credentials: [.apiKey: "sk-test-value"]) + } catch { + try skipIfKeychainPersistenceUnavailable(error) + throw error + } + XCTAssertEqual(store.load(provider: .openAI), [.apiKey: "sk-test-value"]) + } + + func testSaveThenLoadRoundTripsMultiFieldCredentials() throws { + let store = KeychainCloudApiKeyStore() + providersToClean.append(.amazonPolly) + let credentials: [CloudCredentialField: String] = [ + .accessKeyID: "AKIAEXAMPLE", + .secretAccessKey: "shh-its-a-secret", + .region: "us-east-1", + ] + do { + try store.save(provider: .amazonPolly, credentials: credentials) + } catch { + try skipIfKeychainPersistenceUnavailable(error) + throw error + } + XCTAssertEqual(store.load(provider: .amazonPolly), credentials) + } + + func testSaveRejectsCredentialsMissingARequiredField() { + let store = KeychainCloudApiKeyStore() + XCTAssertThrowsError(try store.save(provider: .azureSpeech, credentials: [.apiKey: "key-only-no-region"])) { error in + XCTAssertEqual(error as? CloudApiKeyStoreError, .fieldMismatch(provider: .azureSpeech)) + } + } + + func testSaveRejectsCredentialsWithAnExtraField() { + let store = KeychainCloudApiKeyStore() + let extra: [CloudCredentialField: String] = [.apiKey: "key", .region: "unexpected-for-this-provider"] + XCTAssertThrowsError(try store.save(provider: .openAI, credentials: extra)) { error in + XCTAssertEqual(error as? CloudApiKeyStoreError, .fieldMismatch(provider: .openAI)) + } + } + + func testSaveOverwritesAnyExistingCredentialsForTheSameProvider() throws { + let store = KeychainCloudApiKeyStore() + providersToClean.append(.googleCloudTTS) + do { + try store.save(provider: .googleCloudTTS, credentials: [.apiKey: "first-key"]) + try store.save(provider: .googleCloudTTS, credentials: [.apiKey: "second-key"]) + } catch { + try skipIfKeychainPersistenceUnavailable(error) + throw error + } + XCTAssertEqual(store.load(provider: .googleCloudTTS), [.apiKey: "second-key"]) + } + + func testClearRemovesCredentials() throws { + let store = KeychainCloudApiKeyStore() + do { + try store.save(provider: .elevenLabs, credentials: [.apiKey: "to-be-cleared"]) + } catch { + try skipIfKeychainPersistenceUnavailable(error) + throw error + } + store.clear(provider: .elevenLabs) + XCTAssertNil(store.load(provider: .elevenLabs)) + } + + /// A provider's stored credentials are independent of every other provider's — + /// regression guard against a keying bug (e.g. a shared/static Keychain query + /// missing `kSecAttrAccount`) that would make one provider's save clobber another's. + func testCredentialsForDifferentProvidersDoNotCollide() throws { + let store = KeychainCloudApiKeyStore() + providersToClean.append(contentsOf: [.elevenLabs, .openAI]) + do { + try store.save(provider: .elevenLabs, credentials: [.apiKey: "elevenlabs-key"]) + try store.save(provider: .openAI, credentials: [.apiKey: "openai-key"]) + } catch { + try skipIfKeychainPersistenceUnavailable(error) + throw error + } + XCTAssertEqual(store.load(provider: .elevenLabs), [.apiKey: "elevenlabs-key"]) + XCTAssertEqual(store.load(provider: .openAI), [.apiKey: "openai-key"]) + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudCredentialFieldsTests.swift b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudCredentialFieldsTests.swift new file mode 100644 index 00000000..4d6cc44b --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudCredentialFieldsTests.swift @@ -0,0 +1,37 @@ +import XCTest +@testable import LibraVault + +final class CloudCredentialFieldsTests: XCTestCase { + + func testElevenLabsRequiresOnlyApiKey() { + XCTAssertEqual(CloudCredentialFields.requiredFields(for: .elevenLabs), [.apiKey]) + } + + func testOpenAIRequiresOnlyApiKey() { + XCTAssertEqual(CloudCredentialFields.requiredFields(for: .openAI), [.apiKey]) + } + + func testGoogleCloudTTSRequiresOnlyApiKey() { + XCTAssertEqual(CloudCredentialFields.requiredFields(for: .googleCloudTTS), [.apiKey]) + } + + func testAzureSpeechRequiresApiKeyAndRegion() { + XCTAssertEqual(CloudCredentialFields.requiredFields(for: .azureSpeech), [.apiKey, .region]) + } + + /// The one vendor whose auth isn't a bearer/header key at all — SigV4 needs all + /// three. Regression guard against this silently regressing to a single `.apiKey` + /// the way a careless refactor of the `switch` in `requiredFields` could. + func testAmazonPollyRequiresAccessKeySecretAndRegion() { + XCTAssertEqual( + CloudCredentialFields.requiredFields(for: .amazonPolly), + [.accessKeyID, .secretAccessKey, .region] + ) + } + + func testEveryProviderDisplayNameIsNonEmpty() { + for provider in CloudProviderId.allCases { + XCTAssertFalse(provider.displayName.isEmpty, "\(provider) has an empty displayName") + } + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudTtsGateTests.swift b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudTtsGateTests.swift new file mode 100644 index 00000000..8e3dd089 --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudTtsGateTests.swift @@ -0,0 +1,29 @@ +import XCTest +@testable import LibraVault + +final class CloudTtsGateTests: XCTestCase { + + func testGateOpenOnlyWhenBothSubscribedAndConsented() { + XCTAssertTrue(CloudTtsGate.canUseCloudTts(isSubscribed: true, consentEnabled: true)) + } + + func testGateClosedWhenSubscribedButNotConsented() { + XCTAssertFalse(CloudTtsGate.canUseCloudTts(isSubscribed: true, consentEnabled: false)) + } + + func testGateClosedWhenConsentedButNotSubscribed() { + XCTAssertFalse(CloudTtsGate.canUseCloudTts(isSubscribed: false, consentEnabled: true)) + } + + func testGateClosedWhenNeitherSubscribedNorConsented() { + XCTAssertFalse(CloudTtsGate.canUseCloudTts(isSubscribed: false, consentEnabled: false)) + } + + /// Regression guard for the exact bug class this gate exists to prevent: buying the + /// subscription alone must never be sufficient on its own (PRD §4) — this is the + /// single most safety-critical assertion in this file even though it's implied by + /// the four cases above. + func testSubscriptionAloneNeverOpensTheGate() { + XCTAssertFalse(CloudTtsGate.canUseCloudTts(isSubscribed: true, consentEnabled: false)) + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudVoicePreferencesTests.swift b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudVoicePreferencesTests.swift new file mode 100644 index 00000000..c3236e17 --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/CloudVoicePreferencesTests.swift @@ -0,0 +1,58 @@ +import XCTest +@testable import LibraVault + +final class CloudVoicePreferencesTests: XCTestCase { + + private func makeIsolatedDefaults() -> UserDefaults { + let suiteName = "CloudVoicePreferencesTests.\(UUID().uuidString)" + return UserDefaults(suiteName: suiteName)! + } + + func testLoadConsentEnabledDefaultsToFalseWhenNothingSaved() { + let prefs = CloudVoicePreferences(defaults: makeIsolatedDefaults()) + XCTAssertFalse(prefs.loadConsentEnabled()) + } + + func testSaveThenLoadRoundTripsConsentEnabledTrue() { + let defaults = makeIsolatedDefaults() + CloudVoicePreferences(defaults: defaults).save(consentEnabled: true) + XCTAssertTrue(CloudVoicePreferences(defaults: defaults).loadConsentEnabled()) + } + + func testSaveThenLoadRoundTripsConsentEnabledFalse() { + let defaults = makeIsolatedDefaults() + CloudVoicePreferences(defaults: defaults).save(consentEnabled: true) + CloudVoicePreferences(defaults: defaults).save(consentEnabled: false) + XCTAssertFalse(CloudVoicePreferences(defaults: defaults).loadConsentEnabled()) + } + + func testLoadSelectedProviderDefaultsToNilWhenNothingSaved() { + let prefs = CloudVoicePreferences(defaults: makeIsolatedDefaults()) + XCTAssertNil(prefs.loadSelectedProvider()) + } + + func testSaveThenLoadRoundTripsSelectedProvider() { + let defaults = makeIsolatedDefaults() + CloudVoicePreferences(defaults: defaults).save(selectedProvider: .amazonPolly) + XCTAssertEqual(CloudVoicePreferences(defaults: defaults).loadSelectedProvider(), .amazonPolly) + } + + func testSaveNilSelectedProviderClearsIt() { + let defaults = makeIsolatedDefaults() + let prefs = CloudVoicePreferences(defaults: defaults) + prefs.save(selectedProvider: .openAI) + prefs.save(selectedProvider: nil) + XCTAssertNil(prefs.loadSelectedProvider()) + } + + func testLoadSelectedVoiceIDDefaultsToNilWhenNothingSaved() { + let prefs = CloudVoicePreferences(defaults: makeIsolatedDefaults()) + XCTAssertNil(prefs.loadSelectedVoiceID()) + } + + func testSaveThenLoadRoundTripsSelectedVoiceID() { + let defaults = makeIsolatedDefaults() + CloudVoicePreferences(defaults: defaults).save(selectedVoiceID: "alloy") + XCTAssertEqual(CloudVoicePreferences(defaults: defaults).loadSelectedVoiceID(), "alloy") + } +} diff --git a/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/FakeCloudApiKeyStore.swift b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/FakeCloudApiKeyStore.swift new file mode 100644 index 00000000..4439dbe8 --- /dev/null +++ b/ios/LibraVaultApp/LibraVault/LibraVaultTests/CloudTTS/FakeCloudApiKeyStore.swift @@ -0,0 +1,27 @@ +import Foundation +@testable import LibraVault + +/// Test-only in-memory `CloudApiKeyStore` — for tests exercising code that depends on +/// this protocol (Settings view models, `CloudTtsEngine`) without touching the real +/// Keychain. Mirrors Android's `FakeCloudApiKeyStore` testing double (implicit via MockK +/// in `SettingsViewModelTest`) and this codebase's own `FakeHardwareKeyWrapFactory` +/// pattern: behaves like the real thing for the properties tests care about (per-provider +/// storage, field-mismatch rejection) without any real system dependency. +final class FakeCloudApiKeyStore: CloudApiKeyStore { + private var storage: [CloudProviderId: [CloudCredentialField: String]] = [:] + + func save(provider: CloudProviderId, credentials: [CloudCredentialField: String]) throws { + guard Set(credentials.keys) == CloudCredentialFields.requiredFields(for: provider) else { + throw CloudApiKeyStoreError.fieldMismatch(provider: provider) + } + storage[provider] = credentials + } + + func load(provider: CloudProviderId) -> [CloudCredentialField: String]? { + storage[provider] + } + + func clear(provider: CloudProviderId) { + storage.removeValue(forKey: provider) + } +}