mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-26 21:25:22 +00:00
Make panic wipe deterministic and device-bound (#1431)
* Make panic wipe deterministic and device-bound * Scope install markers to iOS * Harden panic recovery and service shutdown * Invalidate queued BLE ingress during panic * Harden panic keychain and media cleanup --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: jack <jack@deck.local>
This commit is contained in:
@@ -370,6 +370,132 @@ struct BLEFileTransferHandlerTests {
|
||||
#expect(!FileManager.default.fileExists(atPath: evictable.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicWipeDeletesEveryManagedMediaFileAndRecreatesEmptyDirectories() throws {
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("panic-media-wipe-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: base)
|
||||
let subdirectories = [
|
||||
"voicenotes/incoming",
|
||||
"voicenotes/outgoing",
|
||||
"images/incoming",
|
||||
"images/outgoing",
|
||||
"files/incoming",
|
||||
"files/outgoing"
|
||||
]
|
||||
|
||||
for subdirectory in subdirectories {
|
||||
let directory = base
|
||||
.appendingPathComponent("files", isDirectory: true)
|
||||
.appendingPathComponent(subdirectory, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
try Data("secret".utf8).write(to: directory.appendingPathComponent("artifact.bin"))
|
||||
}
|
||||
let unmanaged = base.appendingPathComponent("files/legacy/secret.bin")
|
||||
try FileManager.default.createDirectory(at: unmanaged.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try Data("legacy".utf8).write(to: unmanaged)
|
||||
|
||||
try store.panicWipe()
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: unmanaged.path))
|
||||
for subdirectory in subdirectories {
|
||||
let directory = base
|
||||
.appendingPathComponent("files", isDirectory: true)
|
||||
.appendingPathComponent(subdirectory, isDirectory: true)
|
||||
var isDirectory: ObjCBool = false
|
||||
#expect(FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory))
|
||||
#expect(isDirectory.boolValue)
|
||||
#expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicWipeAttemptsDeletionWhenMarkerPersistenceFails() throws {
|
||||
enum MarkerFailure: Error { case unavailable }
|
||||
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"panic-marker-failure-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let secret = base
|
||||
.appendingPathComponent("files/images/outgoing", isDirectory: true)
|
||||
.appendingPathComponent("secret.jpg")
|
||||
try FileManager.default.createDirectory(
|
||||
at: secret.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
try Data("secret".utf8).write(to: secret)
|
||||
let store = BLEIncomingFileStore(
|
||||
baseDirectory: base,
|
||||
panicMarkerWriter: { _, _ in throw MarkerFailure.unavailable }
|
||||
)
|
||||
|
||||
do {
|
||||
try store.panicWipe(hasDurablePendingMarker: false)
|
||||
Issue.record("Expected the missing durable marker to fail closed")
|
||||
} catch {
|
||||
// The marker error is reported only after the deletion attempt.
|
||||
}
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: secret.path))
|
||||
#expect(
|
||||
FileManager.default.fileExists(
|
||||
atPath: secret.deletingLastPathComponent().path
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func externalMarkerAllowsDeletionToCommitWhenFileMarkerFails() throws {
|
||||
enum MarkerFailure: Error { case unavailable }
|
||||
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"panic-external-marker-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let secret = base
|
||||
.appendingPathComponent("files/voicenotes/incoming", isDirectory: true)
|
||||
.appendingPathComponent("secret.m4a")
|
||||
try FileManager.default.createDirectory(
|
||||
at: secret.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
try Data("secret".utf8).write(to: secret)
|
||||
let store = BLEIncomingFileStore(
|
||||
baseDirectory: base,
|
||||
panicMarkerWriter: { _, _ in throw MarkerFailure.unavailable }
|
||||
)
|
||||
|
||||
try store.panicWipe(hasDurablePendingMarker: true)
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: secret.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicRecoveryMarkerPersistsUntilExplicitCommit() throws {
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"panic-recovery-marker-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: base)
|
||||
|
||||
try store.markPanicRecoveryPending()
|
||||
#expect(try store.isPanicRecoveryPending())
|
||||
try store.panicWipe(hasDurablePendingMarker: true)
|
||||
#expect(try store.isPanicRecoveryPending())
|
||||
|
||||
try store.completePanicRecovery()
|
||||
|
||||
#expect(try !store.isPanicRecoveryPending())
|
||||
}
|
||||
|
||||
private func expectNoSideEffects(_ recorder: Recorder) {
|
||||
#expect(recorder.signedNameQueries.isEmpty)
|
||||
#expect(recorder.trackedPackets.isEmpty)
|
||||
|
||||
@@ -76,6 +76,7 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
burstMaxDelay: 0
|
||||
)
|
||||
|
||||
service.start()
|
||||
service.performHeartbeat()
|
||||
|
||||
let sentAllAllowedChannels = await waitUntil { sentGeohashes.count == 3 }
|
||||
@@ -83,7 +84,7 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
XCTAssertEqual(Set(sentGeohashes), Set(["9q", "9q8y", "9q8yy"]))
|
||||
XCTAssertEqual(Set(lookedUpGeohashes), Set(["9q", "9q8y", "9q8yy"]))
|
||||
XCTAssertEqual(sleptNanoseconds.count, 3)
|
||||
XCTAssertEqual(scheduler.intervals, [17])
|
||||
XCTAssertEqual(scheduler.intervals, [17, 17])
|
||||
}
|
||||
|
||||
func test_performHeartbeat_skipsBroadcastWhenTorIsNotReady() async {
|
||||
@@ -97,11 +98,12 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
loopMaxInterval: 21
|
||||
)
|
||||
|
||||
service.start()
|
||||
service.performHeartbeat()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
|
||||
XCTAssertEqual(sendCount, 0)
|
||||
XCTAssertEqual(scheduler.intervals, [21])
|
||||
XCTAssertEqual(scheduler.intervals, [21, 21])
|
||||
}
|
||||
|
||||
func test_performHeartbeat_skipsBroadcastWhenAppIsBackgrounded() async {
|
||||
@@ -115,11 +117,45 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
loopMaxInterval: 22
|
||||
)
|
||||
|
||||
service.start()
|
||||
service.performHeartbeat()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
|
||||
XCTAssertEqual(sendCount, 0)
|
||||
XCTAssertEqual(scheduler.intervals, [22])
|
||||
XCTAssertEqual(scheduler.intervals, [22, 22])
|
||||
}
|
||||
|
||||
func test_stopForPanic_cancelsTimerAndSuppressesDelayedBroadcast() async throws {
|
||||
let identity = try NostrIdentity.generate()
|
||||
let scheduler = MockGeohashPresenceScheduler()
|
||||
var sleeperContinuation: CheckedContinuation<Void, Never>?
|
||||
var sendCount = 0
|
||||
let service = makeService(
|
||||
scheduler: scheduler,
|
||||
deriveIdentity: { _ in identity },
|
||||
relaySender: { _, _ in sendCount += 1 },
|
||||
sleeper: { _ in
|
||||
await withCheckedContinuation { continuation in
|
||||
sleeperContinuation = continuation
|
||||
}
|
||||
},
|
||||
burstMinDelay: 1,
|
||||
burstMaxDelay: 1
|
||||
)
|
||||
|
||||
service.start()
|
||||
service.performHeartbeat()
|
||||
let delayStarted = await waitUntil {
|
||||
sleeperContinuation != nil
|
||||
}
|
||||
XCTAssertTrue(delayStarted)
|
||||
|
||||
service.stopForPanic()
|
||||
sleeperContinuation?.resume()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
|
||||
XCTAssertEqual(sendCount, 0)
|
||||
XCTAssertEqual(scheduler.timers.first?.invalidateCallCount, 1)
|
||||
}
|
||||
|
||||
func test_broadcastPresence_skipsSendWhenNoRelaysAreAvailable() async throws {
|
||||
|
||||
@@ -91,6 +91,53 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
XCTAssertGreaterThanOrEqual(context.relayController.connectCallCount, 1)
|
||||
}
|
||||
|
||||
func test_stopForPanic_synchronouslyStopsAndIgnoresPublisherUpdates() async {
|
||||
let context = makeService(permission: .authorized, favorites: [])
|
||||
|
||||
context.service.start()
|
||||
context.service.stopForPanic()
|
||||
let connectCountAfterStop = context.relayController.connectCallCount
|
||||
let startCountAfterStop = context.torController.startIfNeededCallCount
|
||||
|
||||
context.favoritesSubject.send([Data([0x01])])
|
||||
context.reachability.set(false)
|
||||
context.reachability.set(true)
|
||||
try? await Task.sleep(nanoseconds: 30_000_000)
|
||||
|
||||
XCTAssertFalse(context.service.activationAllowed)
|
||||
XCTAssertEqual(context.reachability.stopCallCount, 1)
|
||||
XCTAssertEqual(context.torController.autoStartAllowedValues.last, false)
|
||||
XCTAssertEqual(context.proxyController.proxyModes.last, false)
|
||||
XCTAssertGreaterThanOrEqual(
|
||||
context.torController.shutdownCompletelyCallCount,
|
||||
1
|
||||
)
|
||||
XCTAssertGreaterThanOrEqual(
|
||||
context.relayController.disconnectCallCount,
|
||||
1
|
||||
)
|
||||
XCTAssertEqual(
|
||||
context.relayController.connectCallCount,
|
||||
connectCountAfterStop
|
||||
)
|
||||
XCTAssertEqual(
|
||||
context.torController.startIfNeededCallCount,
|
||||
startCountAfterStop
|
||||
)
|
||||
}
|
||||
|
||||
func test_start_afterPanicStop_reestablishesSubscriptions() {
|
||||
let context = makeService(permission: .authorized, favorites: [])
|
||||
|
||||
context.service.start()
|
||||
context.service.stopForPanic()
|
||||
context.service.start()
|
||||
|
||||
XCTAssertTrue(context.service.activationAllowed)
|
||||
XCTAssertEqual(context.reachability.startCallCount, 2)
|
||||
XCTAssertEqual(context.relayController.connectCallCount, 2)
|
||||
}
|
||||
|
||||
private func makeService(
|
||||
permission: LocationChannelManager.PermissionState,
|
||||
favorites: Set<Data>
|
||||
@@ -104,6 +151,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
let torController = MockNetworkActivationTorController()
|
||||
let relayController = MockNetworkActivationRelayController()
|
||||
let proxyController = MockNetworkActivationProxyController()
|
||||
let reachability = MockNetworkActivationReachability()
|
||||
let notificationCenter = NotificationCenter()
|
||||
let service = NetworkActivationService(
|
||||
storage: storage,
|
||||
@@ -111,7 +159,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
mutualFavoritesPublisher: favoritesSubject.eraseToAnyPublisher(),
|
||||
permissionProvider: { permissionSubject.value },
|
||||
mutualFavoritesProvider: { favoritesSubject.value },
|
||||
reachabilityMonitor: AlwaysReachableMonitor(),
|
||||
reachabilityMonitor: reachability,
|
||||
torController: torController,
|
||||
relayController: relayController,
|
||||
proxyController: proxyController,
|
||||
@@ -121,6 +169,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
service: service,
|
||||
storage: storage,
|
||||
favoritesSubject: favoritesSubject,
|
||||
reachability: reachability,
|
||||
torController: torController,
|
||||
relayController: relayController,
|
||||
proxyController: proxyController,
|
||||
@@ -148,12 +197,38 @@ private struct NetworkActivationTestContext {
|
||||
let service: NetworkActivationService
|
||||
let storage: UserDefaults
|
||||
let favoritesSubject: CurrentValueSubject<Set<Data>, Never>
|
||||
let reachability: MockNetworkActivationReachability
|
||||
let torController: MockNetworkActivationTorController
|
||||
let relayController: MockNetworkActivationRelayController
|
||||
let proxyController: MockNetworkActivationProxyController
|
||||
let notificationCenter: NotificationCenter
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class MockNetworkActivationReachability:
|
||||
NetworkReachabilityMonitoring {
|
||||
private let subject = CurrentValueSubject<Bool, Never>(true)
|
||||
private(set) var startCallCount = 0
|
||||
private(set) var stopCallCount = 0
|
||||
|
||||
var isReachable: Bool { subject.value }
|
||||
var reachabilityPublisher: AnyPublisher<Bool, Never> {
|
||||
subject.removeDuplicates().dropFirst().eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
func start() {
|
||||
startCallCount += 1
|
||||
}
|
||||
|
||||
func stop() {
|
||||
stopCallCount += 1
|
||||
}
|
||||
|
||||
func set(_ reachable: Bool) {
|
||||
subject.send(reachable)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class MockNetworkActivationTorController: NetworkActivationTorControlling {
|
||||
private(set) var autoStartAllowedValues: [Bool] = []
|
||||
|
||||
@@ -213,6 +213,7 @@ private final class ControllableReachabilityMonitor: NetworkReachabilityMonitori
|
||||
subject.removeDuplicates().dropFirst().eraseToAnyPublisher()
|
||||
}
|
||||
func start() { startCalled = true }
|
||||
func stop() { startCalled = false }
|
||||
func set(_ reachable: Bool) { subject.send(reachable) }
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user