-
-
Notifications
You must be signed in to change notification settings - Fork 210
fix(settings): preserve provider API keys until Keychain write succeeds #433
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
postoso
wants to merge
1
commit into
altic-dev:main
Choose a base branch
from
postoso:fix/keychain-migration-dataloss
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+279
−24
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
210 changes: 210 additions & 0 deletions
210
Tests/FluidDictationIntegrationTests/ProviderAPIKeyMigrationTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,210 @@ | ||
| @testable import FluidVoice_Debug | ||
| import Foundation | ||
| import XCTest | ||
|
|
||
| /// Regression coverage for the provider-API-key migrations in `SettingsStore`. | ||
| /// Both migrations must persist the replacement before destroying the legacy source, | ||
| /// so a failed Keychain write can never silently lose a user's API key. | ||
| final class ProviderAPIKeyMigrationTests: XCTestCase { | ||
| private let savedProvidersKey = "SavedProviders" | ||
| private let providerAPIKeysKey = "ProviderAPIKeys" | ||
| private let providerAPIKeyIdentifiersKey = "ProviderAPIKeyIdentifiers" | ||
|
|
||
| // MARK: - scrubSavedProviderAPIKeys | ||
|
|
||
| func testScrubPreservesAPIKeyWhenKeychainStoreFailsForThatProvider() throws { | ||
| try self.withRestoredProviderState { defaults in | ||
| let keychain = MockProviderKeychain() | ||
| keychain.failingProviderIDs = ["custom:failing-provider"] | ||
| SettingsStore.shared.setKeychainForTesting(keychain) | ||
|
|
||
| let succeeding = SettingsStore.SavedProvider( | ||
| id: "custom:ok-provider", | ||
| name: "OK Provider", | ||
| baseURL: "https://ok.example", | ||
| apiKey: "sk-ok", | ||
| models: [] | ||
| ) | ||
| let failing = SettingsStore.SavedProvider( | ||
| id: "custom:failing-provider", | ||
| name: "Failing Provider", | ||
| baseURL: "https://fail.example", | ||
| apiKey: "sk-keep-me", | ||
| models: [] | ||
| ) | ||
| defaults.set(try JSONEncoder().encode([succeeding, failing]), forKey: self.savedProvidersKey) | ||
|
|
||
| SettingsStore.shared.scrubSavedProviderAPIKeysForTesting() | ||
|
|
||
| let data = try XCTUnwrap(defaults.data(forKey: self.savedProvidersKey)) | ||
| let result = try JSONDecoder().decode([SettingsStore.SavedProvider].self, from: data) | ||
| let failingResult = try XCTUnwrap(result.first { $0.id == "custom:failing-provider" }) | ||
| let okResult = try XCTUnwrap(result.first { $0.id == "custom:ok-provider" }) | ||
|
|
||
| XCTAssertEqual( | ||
| failingResult.apiKey, | ||
| "sk-keep-me", | ||
| "A provider whose Keychain write failed must keep its plaintext key, not lose it." | ||
| ) | ||
| XCTAssertEqual(okResult.apiKey, "", "A successfully migrated provider should be blanked in defaults.") | ||
| XCTAssertEqual(keychain.consolidatedKeys["custom:ok-provider"], "sk-ok") | ||
| } | ||
| } | ||
|
|
||
| func testScrubMigratesAndBlanksKeyWhenKeychainStoreSucceeds() throws { | ||
| try self.withRestoredProviderState { defaults in | ||
| let keychain = MockProviderKeychain() | ||
| SettingsStore.shared.setKeychainForTesting(keychain) | ||
|
|
||
| let provider = SettingsStore.SavedProvider( | ||
| id: "custom:provider", | ||
| name: "Provider", | ||
| baseURL: "https://provider.example", | ||
| apiKey: "sk-secret", | ||
| models: [] | ||
| ) | ||
| defaults.set(try JSONEncoder().encode([provider]), forKey: self.savedProvidersKey) | ||
|
|
||
| SettingsStore.shared.scrubSavedProviderAPIKeysForTesting() | ||
|
|
||
| let data = try XCTUnwrap(defaults.data(forKey: self.savedProvidersKey)) | ||
| let result = try JSONDecoder().decode([SettingsStore.SavedProvider].self, from: data) | ||
| XCTAssertEqual(result.first?.apiKey, "", "Key should be blanked in defaults once stored in the Keychain.") | ||
| XCTAssertEqual(keychain.consolidatedKeys["custom:provider"], "sk-secret") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - migrateProviderAPIKeysIfNeeded | ||
|
|
||
| func testMigrateKeepsLegacySourcesWhenConsolidatedSaveFails() throws { | ||
| try self.withRestoredProviderState { defaults in | ||
| let keychain = MockProviderKeychain() | ||
| keychain.legacyEntries = ["anthropic": "legacy-keychain-secret"] | ||
| keychain.shouldThrowOnWrite = true | ||
| SettingsStore.shared.setKeychainForTesting(keychain) | ||
|
|
||
| defaults.set(["openai": "legacy-defaults-secret"], forKey: self.providerAPIKeysKey) | ||
|
|
||
| SettingsStore.shared.migrateProviderAPIKeysForTesting() | ||
|
|
||
| let legacyDefaults = try XCTUnwrap(defaults.dictionary(forKey: self.providerAPIKeysKey) as? [String: String]) | ||
| XCTAssertEqual( | ||
| legacyDefaults["openai"], | ||
| "legacy-defaults-secret", | ||
| "Legacy UserDefaults keys must survive when the consolidated save fails." | ||
| ) | ||
| XCTAssertTrue( | ||
| keychain.removedLegacyProviderIDs.isEmpty, | ||
| "Legacy Keychain entries must not be removed when the consolidated save fails." | ||
| ) | ||
| XCTAssertEqual( | ||
| keychain.legacyEntries["anthropic"], | ||
| "legacy-keychain-secret", | ||
| "Legacy Keychain values must survive when the consolidated save fails." | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| func testMigrateRemovesLegacySourcesWhenConsolidatedSaveSucceeds() throws { | ||
| try self.withRestoredProviderState { defaults in | ||
| let keychain = MockProviderKeychain() | ||
| keychain.legacyEntries = ["anthropic": "legacy-keychain-secret"] | ||
| SettingsStore.shared.setKeychainForTesting(keychain) | ||
|
|
||
| defaults.set(["openai": "legacy-defaults-secret"], forKey: self.providerAPIKeysKey) | ||
|
|
||
| SettingsStore.shared.migrateProviderAPIKeysForTesting() | ||
|
|
||
| XCTAssertNil( | ||
| defaults.dictionary(forKey: self.providerAPIKeysKey), | ||
| "Legacy UserDefaults keys should be removed once the consolidated save succeeds." | ||
| ) | ||
| XCTAssertEqual(keychain.consolidatedKeys["openai"], "legacy-defaults-secret") | ||
| XCTAssertEqual(keychain.consolidatedKeys["anthropic"], "legacy-keychain-secret") | ||
| XCTAssertEqual( | ||
| keychain.removedLegacyProviderIDs, | ||
| [["anthropic"]], | ||
| "Legacy Keychain entries should be removed once the consolidated save succeeds." | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Helpers | ||
|
|
||
| /// Snapshots the provider-related UserDefaults keys and the injected Keychain, runs `body` | ||
| /// against the shared store, then restores both. Mirrors `HotkeyShortcutTests`, which also | ||
| /// exercises `SettingsStore.shared` against `UserDefaults.standard`. | ||
| private func withRestoredProviderState(_ body: (UserDefaults) throws -> Void) throws { | ||
| let defaults = UserDefaults.standard | ||
| let keys = [self.savedProvidersKey, self.providerAPIKeysKey, self.providerAPIKeyIdentifiersKey] | ||
| var snapshot: [String: Any] = [:] | ||
| for key in keys { | ||
| if let value = defaults.object(forKey: key) { | ||
| snapshot[key] = value | ||
| } | ||
| } | ||
|
|
||
| defer { | ||
| for key in keys { | ||
| if let previous = snapshot[key] { | ||
| defaults.set(previous, forKey: key) | ||
| } else { | ||
| defaults.removeObject(forKey: key) | ||
| } | ||
| } | ||
| SettingsStore.shared.setKeychainForTesting(KeychainService.shared) | ||
| } | ||
|
|
||
| for key in keys { | ||
| defaults.removeObject(forKey: key) | ||
| } | ||
|
|
||
| try body(defaults) | ||
| } | ||
| } | ||
|
|
||
| private final class MockProviderKeychain: ProviderKeychain { | ||
| enum Failure: Error { | ||
| case write | ||
| } | ||
|
|
||
| var consolidatedKeys: [String: String] | ||
| var legacyEntries: [String: String] | ||
| var failingProviderIDs: Set<String> = [] | ||
| var shouldThrowOnWrite = false | ||
| private(set) var removedLegacyProviderIDs: [[String]] = [] | ||
|
|
||
| init(consolidatedKeys: [String: String] = [:], legacyEntries: [String: String] = [:]) { | ||
| self.consolidatedKeys = consolidatedKeys | ||
| self.legacyEntries = legacyEntries | ||
| } | ||
|
|
||
| func storeKey(_ key: String, for providerID: String) throws { | ||
| if self.shouldThrowOnWrite || self.failingProviderIDs.contains(providerID) { | ||
| throw Failure.write | ||
| } | ||
| self.consolidatedKeys[providerID] = key | ||
| } | ||
|
|
||
| func storeAllKeys(_ values: [String: String]) throws { | ||
| if self.shouldThrowOnWrite { | ||
| throw Failure.write | ||
| } | ||
| self.consolidatedKeys = values | ||
| } | ||
|
|
||
| func fetchAllKeys() throws -> [String: String] { | ||
| self.consolidatedKeys | ||
| } | ||
|
|
||
| func legacyProviderEntries() throws -> [String: String] { | ||
| self.legacyEntries | ||
| } | ||
|
|
||
| func removeLegacyEntries(providerIDs: [String]) throws { | ||
| self.removedLegacyProviderIDs.append(providerIDs) | ||
| for providerID in providerIDs { | ||
| self.legacyEntries.removeValue(forKey: providerID) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a legacy Keychain item cannot be deleted,
KeychainService.saveStoredKeys()throws fromremoveLegacyEntries()afterSecItemAdd/SecItemUpdatehas already persisted the consolidated key. Because this new blanking now only runs ifstoreKeyreturns normally, that cleanup-only failure path leaves the provider API key inSavedProvidersplaintext on every launch even though the replacement Keychain write succeeded; the migration should distinguish write failure from post-write cleanup failure or avoid surfacing cleanup failure as a failed store.Useful? React with 👍 / 👎.