Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -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" : {
Expand All @@ -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%%" : {

},
Expand Down Expand Up @@ -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..." : {

Expand Down Expand Up @@ -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" : {

Expand Down
4 changes: 4 additions & 0 deletions SnapSafe.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -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 */; };
Expand Down Expand Up @@ -388,6 +389,7 @@
C0FFEE00000000000000022C /* ImportProblem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImportProblem.swift; sourceTree = "<group>"; };
C0FFEE000000000000000226 /* SecurityWipeSteps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecurityWipeSteps.swift; sourceTree = "<group>"; };
C0FFEE000000000000000224 /* SecurityResetOrderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecurityResetOrderTests.swift; sourceTree = "<group>"; };
C0FFEE0000000000000002A0 /* WipeSpy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WipeSpy.swift; sourceTree = "<group>"; };
C0FFEE000000000000000210 /* VideoPlaybackPreferencesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoPlaybackPreferencesTests.swift; sourceTree = "<group>"; };
C0FFEE000000000000000212 /* VideoPlaybackPreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoPlaybackPreferences.swift; sourceTree = "<group>"; };
C0FFEE000000000000000214 /* ImportMediaFilesUseCaseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImportMediaFilesUseCaseTests.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -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 */,
Expand Down Expand Up @@ -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 */,
Expand Down
3 changes: 2 additions & 1 deletion SnapSafe/Data/AppDependencyInjection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ extension Container {
imageRepository: self.secureImageRepository(),
pinRepository: self.pinRepository(),
encryptionScheme: self.encryptionScheme(),
authorizePinUseCase: self.authorizedPinUseCase()
authorizePinUseCase: self.authorizedPinUseCase(),
securityResetUseCase: self.securityResetUseCase()
) }
}

Expand Down
34 changes: 30 additions & 4 deletions SnapSafe/Data/UseCases/SecurityResetUseCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ final class SecurityResetUseCase: @unchecked Sendable {
}

private let steps: SecurityWipeSteps
private let lock = NSLock()
private var inFlight: Task<Void, Never>?

init(
authManager: AuthorizationRepository,
Expand All @@ -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<Void, Never> {
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()
}
}
26 changes: 20 additions & 6 deletions SnapSafe/Data/UseCases/VerifyPinUseCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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)
}

Expand Down
34 changes: 13 additions & 21 deletions SnapSafe/Screens/PinVerification/PINVerificationViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 = ""
}
}

Expand Down
21 changes: 21 additions & 0 deletions SnapSafeTests/SecurityResetOrderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
3 changes: 2 additions & 1 deletion SnapSafeTests/VerifyPinUseCaseAttemptTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Loading
Loading