diff --git a/Localizable.xcstrings b/Localizable.xcstrings index 8f95e63..afc37f5 100644 --- a/Localizable.xcstrings +++ b/Localizable.xcstrings @@ -22,6 +22,10 @@ } } }, + "%lld could not be imported." : { + "comment" : "Part of the Files import result message: how many selected files failed to import.", + "isCommentAutoGenerated" : true + }, "%lld of %lld" : { "localizations" : { "en" : { @@ -32,6 +36,10 @@ } } }, + "%lld skipped (only photos and videos are supported)." : { + "comment" : "A sentence that explains that some files were skipped because they were not photos or videos.", + "isCommentAutoGenerated" : true + }, "%lld%%" : { }, @@ -275,6 +283,10 @@ }, "Import" : { + }, + "Imported ^[%lld item](inflect: true)." : { + "comment" : "A message about the result of a Files import. The string interpolations use the number of items imported, skipped, and failed, formatted as counts.", + "isCommentAutoGenerated" : true }, "Importing photos..." : { @@ -575,6 +587,10 @@ }, "The camera app that minds its own business." : { + }, + "The selected files could not be opened." : { + "comment" : "An error message shown when the user tries to import files, but the file picker fails to open them.", + "isCommentAutoGenerated" : true }, "Theme" : { diff --git a/SnapSafe.xcodeproj/project.pbxproj b/SnapSafe.xcodeproj/project.pbxproj index 7102d1f..606c647 100644 --- a/SnapSafe.xcodeproj/project.pbxproj +++ b/SnapSafe.xcodeproj/project.pbxproj @@ -183,6 +183,7 @@ C0FFEE00000000000000022D /* ImportProblem.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0FFEE00000000000000022C /* ImportProblem.swift */; }; C0FFEE000000000000000227 /* SecurityWipeSteps.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0FFEE000000000000000226 /* SecurityWipeSteps.swift */; }; C0FFEE000000000000000225 /* SecurityResetOrderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0FFEE000000000000000224 /* SecurityResetOrderTests.swift */; }; + C0FFEE0000000000000002A1 /* WipeSpy.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0FFEE0000000000000002A0 /* WipeSpy.swift */; }; C0FFEE000000000000000211 /* VideoPlaybackPreferencesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0FFEE000000000000000210 /* VideoPlaybackPreferencesTests.swift */; }; C0FFEE000000000000000213 /* VideoPlaybackPreferences.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0FFEE000000000000000212 /* VideoPlaybackPreferences.swift */; }; C0FFEE000000000000000215 /* ImportMediaFilesUseCaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0FFEE000000000000000214 /* ImportMediaFilesUseCaseTests.swift */; }; @@ -388,6 +389,7 @@ C0FFEE00000000000000022C /* ImportProblem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImportProblem.swift; sourceTree = ""; }; C0FFEE000000000000000226 /* SecurityWipeSteps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecurityWipeSteps.swift; sourceTree = ""; }; C0FFEE000000000000000224 /* SecurityResetOrderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecurityResetOrderTests.swift; sourceTree = ""; }; + C0FFEE0000000000000002A0 /* WipeSpy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WipeSpy.swift; sourceTree = ""; }; C0FFEE000000000000000210 /* VideoPlaybackPreferencesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoPlaybackPreferencesTests.swift; sourceTree = ""; }; C0FFEE000000000000000212 /* VideoPlaybackPreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoPlaybackPreferences.swift; sourceTree = ""; }; C0FFEE000000000000000214 /* ImportMediaFilesUseCaseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImportMediaFilesUseCaseTests.swift; sourceTree = ""; }; @@ -850,6 +852,7 @@ 66A404D62E694A450054FFE7 /* PinRepositoryTest.swift */, C0FFEE000000000000000200 /* PinStrengthCheckUseCaseTests.swift */, C0FFEE000000000000000224 /* SecurityResetOrderTests.swift */, + C0FFEE0000000000000002A0 /* WipeSpy.swift */, C0FFEE000000000000000210 /* VideoPlaybackPreferencesTests.swift */, C0FFEE000000000000000214 /* ImportMediaFilesUseCaseTests.swift */, C0FFEE000000000000000220 /* PinKeyboardPolicyTests.swift */, @@ -1209,6 +1212,7 @@ 66A404D72E694A450054FFE7 /* PinRepositoryTest.swift in Sources */, C0FFEE000000000000000201 /* PinStrengthCheckUseCaseTests.swift in Sources */, C0FFEE000000000000000225 /* SecurityResetOrderTests.swift in Sources */, + C0FFEE0000000000000002A1 /* WipeSpy.swift in Sources */, C0FFEE000000000000000211 /* VideoPlaybackPreferencesTests.swift in Sources */, C0FFEE000000000000000215 /* ImportMediaFilesUseCaseTests.swift in Sources */, C0FFEE000000000000000221 /* PinKeyboardPolicyTests.swift in Sources */, diff --git a/SnapSafe/Data/AppDependencyInjection.swift b/SnapSafe/Data/AppDependencyInjection.swift index d8cbbf6..aa05bb7 100644 --- a/SnapSafe/Data/AppDependencyInjection.swift +++ b/SnapSafe/Data/AppDependencyInjection.swift @@ -82,7 +82,8 @@ extension Container { imageRepository: self.secureImageRepository(), pinRepository: self.pinRepository(), encryptionScheme: self.encryptionScheme(), - authorizePinUseCase: self.authorizedPinUseCase() + authorizePinUseCase: self.authorizedPinUseCase(), + securityResetUseCase: self.securityResetUseCase() ) } } diff --git a/SnapSafe/Data/UseCases/SecurityResetUseCase.swift b/SnapSafe/Data/UseCases/SecurityResetUseCase.swift index 9f656cf..492211d 100644 --- a/SnapSafe/Data/UseCases/SecurityResetUseCase.swift +++ b/SnapSafe/Data/UseCases/SecurityResetUseCase.swift @@ -34,6 +34,8 @@ final class SecurityResetUseCase: @unchecked Sendable { } private let steps: SecurityWipeSteps + private let lock = NSLock() + private var inFlight: Task? init( authManager: AuthorizationRepository, @@ -58,9 +60,33 @@ final class SecurityResetUseCase: @unchecked Sendable { /// because they are the state a later launch would use to notice an /// unfinished wipe. func reset() async { - await steps.destroyKeys() - await steps.deleteMedia() - await steps.eraseSettings() - Logger.security.info("Security Reset Complete!") + await startReset().value + } + + /// Starts the wipe without waiting for it, and returns the running task. + /// Only one wipe runs at a time: while one is in flight, further calls join + /// it instead of starting a second. A refused PIN attempt at the limit, a + /// second wipe request and the settings button can therefore all ask for a + /// wipe without the stages ever running concurrently. + @discardableResult + func startReset() -> Task { + lock.lock() + defer { lock.unlock() } + if let inFlight { return inFlight } + let task = Task { [steps] in + await steps.destroyKeys() + await steps.deleteMedia() + await steps.eraseSettings() + Logger.security.info("Security Reset Complete!") + self.finishReset() + } + inFlight = task + return task + } + + private func finishReset() { + lock.lock() + inFlight = nil + lock.unlock() } } diff --git a/SnapSafe/Data/UseCases/VerifyPinUseCase.swift b/SnapSafe/Data/UseCases/VerifyPinUseCase.swift index 0a043c2..f3f99ce 100644 --- a/SnapSafe/Data/UseCases/VerifyPinUseCase.swift +++ b/SnapSafe/Data/UseCases/VerifyPinUseCase.swift @@ -20,6 +20,9 @@ enum PinVerificationResult: Sendable { /// attempt count from the repository (the single writer), so the caller /// never re-derives or re-writes it from stale local state (M1). case invalidPin(failedAttempts: Int) + /// The failed-attempt budget is spent. The wipe has been started (or is + /// already running) by the use case; the caller only reflects the state. + case lockedOut case failure(Error) } @@ -29,19 +32,22 @@ final class VerifyPinUseCase: @unchecked Sendable { private let pinRepository: PinRepository private let encryptionScheme: EncryptionScheme private let authorizePinUseCase: AuthorizePinUseCase + private let securityResetUseCase: SecurityResetUseCase init( authRepository: AuthorizationRepository, imageRepository: SecureImageRepository, pinRepository: PinRepository, encryptionScheme: EncryptionScheme, - authorizePinUseCase: AuthorizePinUseCase + authorizePinUseCase: AuthorizePinUseCase, + securityResetUseCase: SecurityResetUseCase ) { self.authRepo = authRepository self.imageRepo = imageRepository self.pinRepository = pinRepository self.encryptionScheme = encryptionScheme self.authorizePinUseCase = authorizePinUseCase + self.securityResetUseCase = securityResetUseCase } /// Verifies a PIN and handles poison pill activation if detected. @@ -56,17 +62,18 @@ final class VerifyPinUseCase: @unchecked Sendable { // counter (level-triggered), not only from the UI's reaction to the // attempt that crossed the limit. Once the limit is reached a wipe is // due or running, and a correct guess in that window must neither - // unlock nor reset the counter that says the wipe is due. Reporting the - // count makes the caller (re)trigger the wipe, which also finishes one - // that was interrupted. Nothing is evaluated: not the poison pill, not - // the PIN. + // unlock nor reset the counter that says the wipe is due. The wipe is + // (re)started here, which also finishes one that was interrupted; a wipe + // already in flight is joined, not duplicated. Nothing is evaluated: not + // the poison pill, not the PIN. let persistedAttempts = await authRepo.getFailedAttempts() let limit = await AuthorizationRepository.MAX_FAILED_ATTEMPTS if persistedAttempts >= limit { Logger.security.critical("PIN verification refused: failed-attempt limit already reached", metadata: [ "attemptCount": .stringConvertible(persistedAttempts) ]) - return .invalidPin(failedAttempts: persistedAttempts) + securityResetUseCase.startReset() + return .lockedOut } // Count this attempt before evaluating the PIN, and wait until the count @@ -109,6 +116,13 @@ final class VerifyPinUseCase: @unchecked Sendable { // The attempt was already counted above. Return that authoritative // count so the caller never writes it a second time (M1). Logger.security.warning("PIN verification failed - invalid PIN provided") + if attemptNumber >= limit { + Logger.security.critical("Maximum failed PIN attempts reached, starting security reset", metadata: [ + "attemptCount": .stringConvertible(attemptNumber) + ]) + securityResetUseCase.startReset() + return .lockedOut + } return .invalidPin(failedAttempts: attemptNumber) } diff --git a/SnapSafe/Screens/PinVerification/PINVerificationViewModel.swift b/SnapSafe/Screens/PinVerification/PINVerificationViewModel.swift index 5d0542f..3d8cf64 100644 --- a/SnapSafe/Screens/PinVerification/PINVerificationViewModel.swift +++ b/SnapSafe/Screens/PinVerification/PINVerificationViewModel.swift @@ -36,9 +36,6 @@ final class PINVerificationViewModel: ObservableObject { @Injected(\.verifyPinUseCase) private var verifyPinUseCase: VerifyPinUseCase - @Injected(\.securityResetUseCase) - private var securityResetUseCase: SecurityResetUseCase - @Injected(\.settingsDataSource) private var settings: SettingsDataSource @@ -171,26 +168,21 @@ final class PINVerificationViewModel: ObservableObject { "maxAttempts": .stringConvertible(AuthorizationRepository.MAX_FAILED_ATTEMPTS) ]) - // Check if we've reached the maximum failed attempts - if failedAttempts >= AuthorizationRepository.MAX_FAILED_ATTEMPTS { - Logger.security.critical("Maximum failed PIN attempts reached, triggering security reset", metadata: [ - "attemptCount": .stringConvertible(failedAttempts) - ]) - - // Trigger security reset - Task { - await securityResetUseCase.reset() - } - } else { - Logger.security.info("Failed PIN verification", metadata: [ - "attemptCount": .stringConvertible(failedAttempts) - ]) + Logger.security.info("Failed PIN verification", metadata: [ + "attemptCount": .stringConvertible(failedAttempts) + ]) - // Refresh backoff state after the failed attempt. - Task { - await updateBackoffTime() - } + // Refresh backoff state after the failed attempt. + Task { + await updateBackoffTime() } + + case .lockedOut: + // The use case has already started the wipe. Show the same error as + // any other wrong PIN and reflect the spent budget. + showError = true + failedAttempts = AuthorizationRepository.MAX_FAILED_ATTEMPTS + pin = "" } } diff --git a/SnapSafeTests/SecurityResetOrderTests.swift b/SnapSafeTests/SecurityResetOrderTests.swift index 5146853..d5c5aaf 100644 --- a/SnapSafeTests/SecurityResetOrderTests.swift +++ b/SnapSafeTests/SecurityResetOrderTests.swift @@ -56,4 +56,25 @@ final class SecurityResetOrderTests: XCTestCase { let events = await recorder.events XCTAssertEqual(events, ["keys", "media", "settings"]) } + + func testConcurrentResetsRunTheStagesOnce() async { + let spy = WipeSpy(held: true) + let useCase = spy.useCase + let first = useCase.startReset() + await spy.waitUntilStarted() + let second = useCase.startReset() + spy.release() + await first.value + await second.value + XCTAssertEqual(spy.started, 1, "stages ran \(spy.started) times for two overlapping resets, expected 1") + XCTAssertEqual(spy.peakConcurrency, 1, "peak concurrent wipes was \(spy.peakConcurrency), expected 1") + } + + func testResetCanRunAgainAfterTheFirstFinished() async { + let spy = WipeSpy() + let useCase = spy.useCase + await useCase.reset() + await useCase.reset() + XCTAssertEqual(spy.started, 2, "two sequential resets ran the stages \(spy.started) times, expected 2") + } } diff --git a/SnapSafeTests/VerifyPinUseCaseAttemptTests.swift b/SnapSafeTests/VerifyPinUseCaseAttemptTests.swift index 44387ca..946c69e 100644 --- a/SnapSafeTests/VerifyPinUseCaseAttemptTests.swift +++ b/SnapSafeTests/VerifyPinUseCaseAttemptTests.swift @@ -39,7 +39,8 @@ final class VerifyPinUseCaseAttemptTests: XCTestCase { imageRepository: imageRepo, pinRepository: pinRepo, encryptionScheme: scheme, - authorizePinUseCase: AuthorizePinUseCase(authRepository: authRepo, pinRepository: pinRepo) + authorizePinUseCase: AuthorizePinUseCase(authRepository: authRepo, pinRepository: pinRepo), + securityResetUseCase: WipeSpy().useCase ) return (sut, authRepo) } diff --git a/SnapSafeTests/VerifyPinUseCaseTests.swift b/SnapSafeTests/VerifyPinUseCaseTests.swift index d5594aa..69e7e19 100644 --- a/SnapSafeTests/VerifyPinUseCaseTests.swift +++ b/SnapSafeTests/VerifyPinUseCaseTests.swift @@ -85,7 +85,8 @@ final class VerifyPinUseCaseTests: XCTestCase { imageRepository: imageRepo, pinRepository: pinRepo, encryptionScheme: throwingScheme, - authorizePinUseCase: authorizePinUseCase + authorizePinUseCase: authorizePinUseCase, + securityResetUseCase: WipeSpy().useCase ) let result = await sut.verifyPin(pin) @@ -93,7 +94,7 @@ final class VerifyPinUseCaseTests: XCTestCase { switch result { case .failure(let error): XCTAssertEqual(error as? TestError, .transient) - case .success, .invalidPin: + case .success, .invalidPin, .lockedOut: XCTFail("Expected .failure(.transient), got \(result)") } } @@ -108,6 +109,7 @@ final class VerifyPinUseCaseTests: XCTestCase { let pinRepo: MockPinRepository let settings: MockSettingsDataSource let scheme: MockEncryptionScheme + let wipe: WipeSpy } private func makeCorrectPinUseCase( @@ -150,14 +152,16 @@ final class VerifyPinUseCaseTests: XCTestCase { thumbnailCache: ThumbnailCache(), encryptionScheme: passthrough ) + let wipe = WipeSpy() let sut = VerifyPinUseCase( authRepository: authRepo, imageRepository: imageRepo, pinRepository: pinRepo, encryptionScheme: customScheme ?? scheme, - authorizePinUseCase: AuthorizePinUseCase(authRepository: authRepo, pinRepository: pinRepo) + authorizePinUseCase: AuthorizePinUseCase(authRepository: authRepo, pinRepository: pinRepo), + securityResetUseCase: wipe.useCase ) - return Harness(sut: sut, authRepo: authRepo, pinRepo: pinRepo, settings: settings, scheme: scheme) + return Harness(sut: sut, authRepo: authRepo, pinRepo: pinRepo, settings: settings, scheme: scheme, wipe: wipe) } private func currentlyAuthorized(_ authRepo: AuthorizationRepository) -> Bool? { @@ -228,10 +232,9 @@ final class VerifyPinUseCaseTests: XCTestCase { let result = await harness.sut.verifyPin("1234") - guard case .invalidPin(let failedAttempts) = result else { - return XCTFail("Expected .invalidPin, got \(result)") - } - XCTAssertEqual(failedAttempts, limit, "must report the limit so the caller (re)triggers the wipe") + guard case .lockedOut = result else { return XCTFail("Expected .lockedOut, got \(result)") } + await harness.wipe.waitUntilStarted() + XCTAssertEqual(harness.wipe.started, 1, "wipe started \(harness.wipe.started) times, expected exactly once") XCTAssertEqual(currentlyAuthorized(harness.authRepo), false) verify(harness.pinRepo).verifySecurityPin(.any).called(.never) verify(harness.pinRepo).hasPoisonPillPin().called(.never) @@ -246,10 +249,7 @@ final class VerifyPinUseCaseTests: XCTestCase { let result = await harness.sut.verifyPin("1234") - guard case .invalidPin(let failedAttempts) = result else { - return XCTFail("Expected .invalidPin, got \(result)") - } - XCTAssertEqual(failedAttempts, over) + guard case .lockedOut = result else { return XCTFail("Expected .lockedOut, got \(result)") } verify(harness.pinRepo).verifySecurityPin(.any).called(.never) } @@ -264,6 +264,53 @@ final class VerifyPinUseCaseTests: XCTestCase { guard case .success = result else { return XCTFail("Expected .success, got \(result)") } XCTAssertEqual(currentlyAuthorized(harness.authRepo), true) + XCTAssertEqual(harness.wipe.started, 0, "a correct PIN below the limit started \(harness.wipe.started) wipes") + } + + func test_verifyPin_wrongPinThatSpendsTheBudget_startsTheWipeOnce_andReportsLockedOut() async throws { + let limit = AuthorizationRepository.MAX_FAILED_ATTEMPTS + // The stored PIN is "1234"; the guess "0000" is wrong and is the last allowed attempt. + let harness = makeCorrectPinUseCase(pin: "1234", derivationThrows: false, persistedFailedAttempts: limit - 1) + given(harness.pinRepo).verifySecurityPin(.value("0000")).willReturn(false) + + let result = await harness.sut.verifyPin("0000") + + guard case .lockedOut = result else { return XCTFail("Expected .lockedOut, got \(result)") } + await harness.wipe.waitUntilStarted() + XCTAssertEqual(harness.wipe.started, 1, "wipe started \(harness.wipe.started) times, expected exactly once") + } + + func test_verifyPin_wrongPinBelowTheLimit_doesNotStartAWipe() async throws { + let harness = makeCorrectPinUseCase(pin: "1234", derivationThrows: false, persistedFailedAttempts: 0) + given(harness.pinRepo).verifySecurityPin(.value("0000")).willReturn(false) + + let result = await harness.sut.verifyPin("0000") + + guard case .invalidPin = result else { return XCTFail("Expected .invalidPin, got \(result)") } + XCTAssertEqual(harness.wipe.started, 0, "a wrong PIN below the limit started \(harness.wipe.started) wipes") + } + + func test_verifyPin_refusedAttemptWhileAWipeIsRunning_doesNotStartASecondWipe() async throws { + let limit = AuthorizationRepository.MAX_FAILED_ATTEMPTS + let harness = makeCorrectPinUseCase(pin: "1234", derivationThrows: false, persistedFailedAttempts: limit) + let held = WipeSpy(held: true) + let sut = VerifyPinUseCase( + authRepository: harness.authRepo, + imageRepository: SecureImageRepository(thumbnailCache: ThumbnailCache(), encryptionScheme: PassThroughEncryptionScheme()), + pinRepository: harness.pinRepo, + encryptionScheme: harness.scheme, + authorizePinUseCase: AuthorizePinUseCase(authRepository: harness.authRepo, pinRepository: harness.pinRepo), + securityResetUseCase: held.useCase + ) + + _ = await sut.verifyPin("1234") + await held.waitUntilStarted() + _ = await sut.verifyPin("1234") + _ = await sut.verifyPin("1234") + held.release() + + XCTAssertEqual(held.started, 1, "wipe started \(held.started) times while one was in flight, expected 1") + XCTAssertEqual(held.peakConcurrency, 1, "peak concurrent wipes was \(held.peakConcurrency), expected 1") } func test_verifyPin_onInvalidPin_incrementsCounterExactlyOnce_andReturnsNewCount() async throws { @@ -302,7 +349,8 @@ final class VerifyPinUseCaseTests: XCTestCase { imageRepository: imageRepo, pinRepository: pinRepo, encryptionScheme: passthrough, - authorizePinUseCase: authorizePinUseCase + authorizePinUseCase: authorizePinUseCase, + securityResetUseCase: WipeSpy().useCase ) let result = await sut.verifyPin(pin) @@ -363,7 +411,8 @@ final class VerifyPinUseCaseTests: XCTestCase { imageRepository: imageRepo, pinRepository: pinRepo, encryptionScheme: scheme, - authorizePinUseCase: authorizePinUseCase + authorizePinUseCase: authorizePinUseCase, + securityResetUseCase: WipeSpy().useCase ) _ = await sut.verifyPin(pin) @@ -404,7 +453,8 @@ final class VerifyPinUseCaseTests: XCTestCase { imageRepository: imageManager, pinRepository: pinRepository, encryptionScheme: PassThroughEncryptionScheme(), - authorizePinUseCase: authorizePinUseCase + authorizePinUseCase: authorizePinUseCase, + securityResetUseCase: WipeSpy().useCase ) XCTAssertNotNil(verifyPinUseCase) diff --git a/SnapSafeTests/WipeSpy.swift b/SnapSafeTests/WipeSpy.swift new file mode 100644 index 0000000..6bc5eed --- /dev/null +++ b/SnapSafeTests/WipeSpy.swift @@ -0,0 +1,68 @@ +// +// WipeSpy.swift +// SnapSafeTests +// + +import Foundation +@testable import SnapSafe + +/// Counts how often each wipe stage ran, and optionally holds the wipe open so a +/// test can ask for a second wipe while the first is still in flight. +final class WipeSpy: @unchecked Sendable { + private let lock = NSLock() + private var runs = 0 + private var concurrent = 0 + private var peak = 0 + private let gate: AsyncStream? + private var gateContinuation: AsyncStream.Continuation? + + init(held: Bool = false) { + if held { + var continuation: AsyncStream.Continuation? + gate = AsyncStream { continuation = $0 } + gateContinuation = continuation + } else { + gate = nil + } + } + + /// Number of wipes that have started their first stage. + var started: Int { lock.lock(); defer { lock.unlock() }; return runs } + /// Highest number of wipes that were ever running at the same moment. + var peakConcurrency: Int { lock.lock(); defer { lock.unlock() }; return peak } + + /// Lets a held wipe proceed. + func release() { gateContinuation?.yield(); gateContinuation?.finish() } + + var useCase: SecurityResetUseCase { + SecurityResetUseCase(steps: SecurityWipeSteps( + destroyKeys: { [self] in + begin() + if let gate { for await _ in gate { break } } + }, + deleteMedia: {}, + eraseSettings: { [self] in end() } + )) + } + + private func begin() { + lock.lock() + runs += 1 + concurrent += 1 + peak = max(peak, concurrent) + lock.unlock() + } + + private func end() { + lock.lock() + concurrent -= 1 + lock.unlock() + } +} + +extension WipeSpy { + /// Waits until a wipe has begun its first stage. + func waitUntilStarted() async { + while started == 0 { try? await Task.sleep(for: .milliseconds(5)) } + } +} diff --git a/docs/tla/FINDINGS.md b/docs/tla/FINDINGS.md index 2ace8e8..334681d 100644 --- a/docs/tla/FINDINGS.md +++ b/docs/tla/FINDINGS.md @@ -26,7 +26,7 @@ Each of these is modelled. Reverting one in the Swift (and in the model) makes a after that, so a transient failure later does not burn an attempt. (`LockoutBudget`, `NoUnlockAfterBudget`) 2. **`verifyPin` refuses to evaluate anything once the persisted counter is at the limit**, and - reports the count so the view model (re-)starts the wipe. This also finishes a wipe that was + starts the wipe itself (`SecurityResetUseCase.startReset`, which joins a wipe already running) and returns `.lockedOut`. A wrong PIN that spends the budget does the same. This also finishes a wipe that was interrupted, and stops a correct PIN entered while a wipe is queued from unlocking or resetting the counter. (`WipeCompleteness`, `NoUnlockAfterBudget`) 3. **The wipe destroys key material first and erases the PIN record and counter last** @@ -49,7 +49,7 @@ Each of these is modelled. Reverting one in the Swift (and in the model) makes a - **Two concurrent verification flows** violate several properties: a pill flow that started before a wipe finishes can write a PIN record after it, and one flow's success can reset the counter under - another flow's wipe. Run `FLOWS='{f1, f2}' docs/tla/check.sh` to see them. Allowing multiple + another flow's wipe. The model assumes one flow; to see them, set `FLOWS='{f1, f2}'` in `check.sh`. Allowing multiple windows, or calling `verifyPin` from a second code path, requires fixing these first. - **Backoff is not covered.** Time is not modelled. Backoff is enforced only in `PINVerificationViewModel` (the unlock button is disabled while it runs), not inside `verifyPin`. diff --git a/docs/tla/README.md b/docs/tla/README.md index ba7d152..3875ade 100644 --- a/docs/tla/README.md +++ b/docs/tla/README.md @@ -32,7 +32,6 @@ Settings, as environment variables: |---|---|---| | `MAXATTEMPTS` | `2` | lockout threshold (the app uses 10; the structure of every result is the same for any value) | | `MAXCRASHES` | `1` | how many process kills TLC may inject (`0` disables kills) | -| `FLOWS` | `{f1}` | concurrent verification flows. The app is full-screen only (`UIRequiresFullScreen`), so one PIN screen exists at a time. `'{f1, f2}'` models two windows | | `TLA_JAR` | `~/.local/share/tla2tools/tla2tools.jar` | location of the checker | ## Reading the output @@ -52,13 +51,12 @@ Every step name is one `await`-separated step of the Swift code: | Step | Swift | |---|---| -| `Start` | `VerifyPinUseCase.verifyPin` reads the persisted counter, refuses at the limit, otherwise counts this attempt durably before evaluating anything | +| `Start` | `VerifyPinUseCase.verifyPin` reads the persisted counter, starts the wipe and refuses at the limit, otherwise counts this attempt durably before evaluating anything | | `PillCheck`, `PillDek`, `PillPhotos`, `PillPin` | poison-pill detection and activation: read the stored pill record, delete the real key, delete the real photos, then make the pill PIN the active PIN | -| `Auth` | `AuthorizePinUseCase`: compare the PIN with the stored record | +| `Auth` | `AuthorizePinUseCase`: compare the PIN with the stored record; a rejected PIN at the limit starts the wipe | | `Authz` | `authorizeSession()` | | `Reset` | `resetFailedAttempts()` | | `Derive` | `deriveAndCacheKey` (may fail transiently) | -| `UI` | the view model starts the wipe if the count it got back is at the limit | | `WipeStep` | one of the four steps of `SecurityResetUseCase.reset()` | | `Lock` | the session is locked (backgrounding or timeout) | | `Crash` | the process dies at an arbitrary instant; disk survives, memory and in-flight work do not | @@ -82,8 +80,8 @@ The final state lists the variables. `consec` and `won` and `lucky` and `wipeTri One flow, `MaxAttempts = 2`, one process kill: **every property holds.** The same holds with two process kills, with `MaxAttempts = 3`, and with kills disabled. -With `FLOWS='{f1, f2}'` several properties are violated. That configuration needs two concurrent -verification flows, which the app prevents (see "Limits"). +The model assumes exactly one verification flow at a time, because the app is single-window (see +"Limits"). `FINDINGS.md` explains the design decisions the properties depend on, and the known limits. @@ -103,7 +101,7 @@ about the Swift code. - The attacker is not a separate process. TLC picks every input at every step, which covers an attacker who can type anything and kill the app at any moment. -- Two concurrent flows break several properties: a pill flow that started before a wipe finishes can +- The model assumes one flow. Two concurrent flows (`FLOWS='{f1, f2}'` in `check.sh`) break several properties: a pill flow that started before a wipe finishes can write a PIN record after it, and one flow's success can reset the counter under another flow's wipe. The app prevents this by being single-window (`UIRequiresFullScreen = YES` and `UIApplicationSupportsMultipleScenes = NO`), and `SingleWindowGuardTests` fails if either changes. diff --git a/docs/tla/SnapSafeAuth.tla b/docs/tla/SnapSafeAuth.tla index e6ef43b..1398080 100644 --- a/docs/tla/SnapSafeAuth.tla +++ b/docs/tla/SnapSafeAuth.tla @@ -35,7 +35,7 @@ EXTENDS Integers, Sequences, TLC CONSTANTS MaxAttempts, \* lockout threshold (AuthorizationRepository.MAX_FAILED_ATTEMPTS) - Flows, \* concurrent verification flows, e.g. two iPad scenes + Flows, \* concurrent verification flows, the app guarantees exactly one (single-window) MaxCrashes \* how many process kills the checker may inject VARIABLES @@ -68,7 +68,7 @@ NoWipe == -1 Inputs == {"real", "pill", "bad"} PCs == {"idle", "pillCheck", "pillDek", "pillPhotos", "pillPin", - "auth", "authz", "reset", "derive", "ui"} + "auth", "authz", "reset", "derive"} TypeOK == /\ stored \in {"real", "pill", "none"} @@ -102,7 +102,7 @@ Goto(f, p) == fs' = [fs EXCEPT ![f].pc = p] (***************************************************************************) (* Unlock flow, one action per `await`-separated step of verifyPin. *) -(* Each flow is one PINVerificationViewModel. One flow per scene/window. *) +(* Each flow is one PINVerificationViewModel calling verifyPin. One flow per scene/window. *) (***************************************************************************) \* The user (or attacker) submits an input. The VM's isLoading flag only @@ -112,16 +112,20 @@ Start(f, i) == /\ stored # "none" /\ ~authorized \* the PIN screen is only shown while locked /\ IF failed >= MaxAttempts - \* verifyPin reads the persisted counter first and refuses to evaluate - \* at the limit; the view model then (re-)triggers the wipe. - THEN fs' = [fs EXCEPT ![f].pc = "ui", ![f].inp = i, - ![f].ret = failed, ![f].res = "none"] + \* verifyPin reads the persisted counter first and, at the limit, + \* evaluates nothing: it starts the wipe itself (or joins one that is + \* already running) and returns .lockedOut. No await in between. + THEN /\ fs' = [fs EXCEPT ![f].pc = "idle", ![f].inp = i, + ![f].ret = failed, ![f].res = "none"] + /\ wipe' = IF wipe = NoWipe THEN 0 ELSE wipe + /\ wipeTriggered' = (wipeTriggered \/ wipe = NoWipe) \* Otherwise the attempt is counted and persisted FIRST, then the PIN \* is evaluated. A correct PIN consumes the reservation (Reset). - ELSE fs' = [fs EXCEPT ![f].pc = "pillCheck", ![f].inp = i, - ![f].ret = failed + 1, ![f].res = "none"] + ELSE /\ fs' = [fs EXCEPT ![f].pc = "pillCheck", ![f].inp = i, + ![f].ret = failed + 1, ![f].res = "none"] + /\ UNCHANGED <> /\ failed' = IF failed >= MaxAttempts THEN failed ELSE failed + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> \* hasPoisonPillPin() && verifyPoisonPillPin(pin), then \* pinRepository.preparePoisonPillActivation(): reads the stored pill record, @@ -155,14 +159,20 @@ PillPin(f) == /\ Goto(f, "auth") /\ UNCHANGED <> -\* authorizePin: compare the input with whatever PIN is stored right now. +\* authorizePin: compare the input with whatever PIN is stored right now. A +\* rejected PIN whose reserved count is at the limit starts the wipe in the +\* same step (verifyPin calls SecurityResetUseCase.startReset, which joins a +\* wipe that is already running) and returns .lockedOut. Auth(f) == /\ fs[f].pc = "auth" /\ LET ok == stored # "none" /\ fs[f].inp = stored + startWipe == ~ok /\ fs[f].ret >= MaxAttempts /\ wipe = NoWipe IN /\ fs' = [fs EXCEPT ![f].res = IF ok THEN "ok" ELSE "reject", - ![f].pc = IF ok THEN "authz" ELSE "ui"] + ![f].pc = IF ok THEN "authz" ELSE "idle"] /\ consec' = IF ok \/ stored = "none" THEN consec ELSE consec + 1 - /\ UNCHANGED <> + /\ wipe' = IF startWipe THEN 0 ELSE wipe + /\ wipeTriggered' = (wipeTriggered \/ startWipe) + /\ UNCHANGED <> \* authorizePin: authRepository.authorizeSession(). The session is marked \* authorized BEFORE the key is derived. @@ -194,17 +204,6 @@ Derive(f) == /\ authorized' = FALSE /\ UNCHANGED <> -\* PINVerificationViewModel: `if failedAttempts >= MAX { Task { reset() } }` -\* This is EDGE-triggered off the value this flow got back, not off storage. -UI(f) == - /\ fs[f].pc = "ui" - /\ Goto(f, "idle") - \* Judged from the count this flow got back, which may be stale by now. - /\ IF fs[f].ret >= MaxAttempts /\ wipe = NoWipe - THEN wipe' = 0 /\ wipeTriggered' = TRUE - ELSE UNCHANGED <> - /\ UNCHANGED <> - (***************************************************************************) (* SecurityResetUseCase.reset(): four separate awaited steps. *) (* Order: HW keys, DEKs, photos, then settings (PIN record + counter), so *) @@ -252,7 +251,7 @@ Next == \/ \E f \in Flows, i \in Inputs : Start(f, i) \/ \E f \in Flows : \/ PillCheck(f) \/ PillDek(f) \/ PillPhotos(f) \/ PillPin(f) - \/ Auth(f) \/ Authz(f) \/ Reset(f) \/ Derive(f) \/ UI(f) + \/ Auth(f) \/ Authz(f) \/ Reset(f) \/ Derive(f) \/ WipeStep \/ Lock \/ Crash diff --git a/docs/tla/check.sh b/docs/tla/check.sh index 6e9ff63..7b05d9c 100755 --- a/docs/tla/check.sh +++ b/docs/tla/check.sh @@ -15,8 +15,6 @@ # TLA_JAR path to tla2tools.jar (default ~/.local/share/tla2tools/tla2tools.jar) # MAXATTEMPTS lockout threshold (default 2; the app uses 10) # MAXCRASHES process kills TLC may inject (default 1; 0 disables kills) -# FLOWS concurrent verification flows (default '{f1}': the app is full-screen only, -# so one PIN screen exists at a time; '{f1, f2}' models two windows) # # Needs Java 17+ and tla2tools.jar. See README.md. set -euo pipefail @@ -40,8 +38,9 @@ promise() { PROPS=("$@") [[ ${#PROPS[@]} -eq 0 ]] && PROPS=("${ALL_PROPS[@]}") -FLOWS="${FLOWS:-}" -[[ -z "$FLOWS" ]] && FLOWS='{f1}' +# The app is single-window (UIRequiresFullScreen, no multiple scenes), so exactly one +# PIN-verification flow exists at a time. This is an assumption of the model, not a setting. +FLOWS='{f1}' MAXATTEMPTS="${MAXATTEMPTS:-2}" MAXCRASHES="${MAXCRASHES:-1}" JAR="${TLA_JAR:-$HOME/.local/share/tla2tools/tla2tools.jar}"