mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-22 08:17:28 +00:00
Keep panic wipe pending when prekey or outbox cleanup fails
Prekey and outbox cleanup failures now keep panic recovery pending. Unresolved file locations are retried on a later cleanup attempt, and recovered paths support future saves. Panic identity reset clears prekey packets waiting for peer verification. Other cleanup steps still run after a failure, with existing keychain failure reporting and outbox recovery protections preserved.
This commit is contained in:
parent
749f90653f
commit
e3c9aff101
@ -769,6 +769,7 @@ final class BLEService: NSObject {
|
||||
}
|
||||
onEngine {
|
||||
pendingNoiseSessionQueues.removeAll()
|
||||
pendingPrekeyBundles.removeAll()
|
||||
}
|
||||
|
||||
let panicReset = onEngine {
|
||||
|
||||
@ -91,7 +91,8 @@ final class MessageOutboxStore {
|
||||
let unseenDurable: Snapshot
|
||||
}
|
||||
|
||||
private let fileURL: URL?
|
||||
private var fileURL: URL?
|
||||
private let resolveDefaultFileURL: () -> URL?
|
||||
private let keychain: KeychainManagerProtocol
|
||||
private let readData: (URL) throws -> Data
|
||||
private let writeData: (Data, URL, Data.WritingOptions) throws -> Void
|
||||
@ -149,10 +150,13 @@ final class MessageOutboxStore {
|
||||
writeData: @escaping (Data, URL, Data.WritingOptions) throws -> Void = {
|
||||
try $0.write(to: $1, options: $2)
|
||||
},
|
||||
beforeRecoveryNotification: @escaping () -> Void = {}
|
||||
beforeRecoveryNotification: @escaping () -> Void = {},
|
||||
resolveDefaultFileURL: (() -> URL?)? = nil
|
||||
) {
|
||||
self.keychain = keychain
|
||||
self.fileURL = fileURL ?? Self.defaultFileURL()
|
||||
let resolver = resolveDefaultFileURL ?? Self.defaultFileURL
|
||||
self.resolveDefaultFileURL = resolver
|
||||
self.fileURL = fileURL ?? resolver()
|
||||
self.readData = readData
|
||||
self.writeData = writeData
|
||||
self.beforeRecoveryNotification = beforeRecoveryNotification
|
||||
@ -593,8 +597,9 @@ final class MessageOutboxStore {
|
||||
return recovered?.snapshot
|
||||
}
|
||||
|
||||
/// Panic wipe: drop the queued mail and the key that could ever read it.
|
||||
func wipe() {
|
||||
/// Clears queued mail and attempts key removal; returns the file-cleanup result.
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
lock.lock()
|
||||
diskState = .loaded
|
||||
cachedSnapshot = [:]
|
||||
@ -608,11 +613,10 @@ final class MessageOutboxStore {
|
||||
recoveryRouterSnapshot = [:]
|
||||
unreportedRecoveredSnapshot = nil
|
||||
lifecycleGeneration &+= 1
|
||||
if let fileURL {
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
}
|
||||
let removed = PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)
|
||||
keychain.delete(key: Self.keychainKey, service: Self.keychainService)
|
||||
lock.unlock()
|
||||
return removed
|
||||
}
|
||||
|
||||
// MARK: - Internals
|
||||
|
||||
@ -550,11 +550,12 @@ final class MessageRouter {
|
||||
retryBridgeCourierDeposits()
|
||||
}
|
||||
|
||||
/// Panic wipe: forget queued mail on disk and in memory.
|
||||
func wipeOutbox() {
|
||||
/// Clears queued mail and reports persistent cleanup when a store is configured.
|
||||
@discardableResult
|
||||
func wipeOutbox() -> Bool {
|
||||
outbox.removeAll()
|
||||
secureTransmissions.removeAll()
|
||||
outboxStore?.wipe()
|
||||
return outboxStore?.wipe() ?? true
|
||||
}
|
||||
|
||||
/// Returns true only when the receipt was handed to a reachable transport.
|
||||
|
||||
@ -14,4 +14,5 @@ struct PanicMetadataWipeOperations {
|
||||
var wipeGroups: () -> Bool
|
||||
var wipeBoard: () -> Bool
|
||||
var wipeEvents: () -> Bool
|
||||
var wipePrekeys: () -> Bool = { PrekeyBundleStore.shared.wipe() }
|
||||
}
|
||||
|
||||
@ -50,7 +50,9 @@ final class PrekeyBundleStore {
|
||||
|
||||
private var bundles: [Data: StoredBundle] = [:]
|
||||
private let queue = DispatchQueue(label: "chat.bitchat.prekeys.bundles")
|
||||
private let fileURL: URL?
|
||||
private var fileURL: URL?
|
||||
private let resolveDefaultFileURL: () -> URL?
|
||||
private let persistsToDisk: Bool
|
||||
private let maxPeers: Int
|
||||
private let now: () -> Date
|
||||
|
||||
@ -60,11 +62,15 @@ final class PrekeyBundleStore {
|
||||
persistsToDisk: Bool = true,
|
||||
fileURL: URL? = nil,
|
||||
maxPeers: Int = Limits.maxPeers,
|
||||
now: @escaping () -> Date = Date.init
|
||||
now: @escaping () -> Date = Date.init,
|
||||
resolveDefaultFileURL: (() -> URL?)? = nil
|
||||
) {
|
||||
self.now = now
|
||||
self.maxPeers = maxPeers
|
||||
self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil
|
||||
let resolver = resolveDefaultFileURL ?? Self.defaultFileURL
|
||||
self.resolveDefaultFileURL = resolver
|
||||
self.persistsToDisk = persistsToDisk
|
||||
self.fileURL = persistsToDisk ? (fileURL ?? resolver()) : nil
|
||||
loadFromDisk()
|
||||
}
|
||||
|
||||
@ -143,13 +149,12 @@ final class PrekeyBundleStore {
|
||||
|
||||
// MARK: - Maintenance
|
||||
|
||||
/// Panic wipe: drop all cached bundles from memory and disk.
|
||||
func wipe() {
|
||||
/// Clears cached bundles; returns whether the persistent file was removed or absent.
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
queue.sync {
|
||||
bundles.removeAll()
|
||||
if let fileURL {
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
}
|
||||
return !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1641,7 +1641,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
// counters describing all of it
|
||||
var metadataWipeCompleted = (panicMetadataWipeOperations?.wipeCourier() ?? CourierStore.shared.wipe())
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeBridge() ?? BridgeCourierService.shared.wipe()) && metadataWipeCompleted
|
||||
messageRouter.wipeOutbox()
|
||||
metadataWipeCompleted = messageRouter.wipeOutbox() && metadataWipeCompleted
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeGossip() ?? GossipMessageArchive.wipeDefault()) && metadataWipeCompleted
|
||||
StoreAndForwardMetrics.shared.reset()
|
||||
|
||||
@ -1661,7 +1661,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
// Drop cached peers' prekey bundles (who we could write to is
|
||||
// metadata too). Our own prekey privates are keychain-backed and go
|
||||
// with deleteAllKeychainData above plus the identity reset below.
|
||||
PrekeyBundleStore.shared.wipe()
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipePrekeys() ?? PrekeyBundleStore.shared.wipe()) && metadataWipeCompleted
|
||||
// Drop bulletin-board posts and tombstones (memory and disk); board
|
||||
// posts are signed with our identity key and persist for days.
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeBoard() ?? BoardStore.shared.wipe()) && metadataWipeCompleted
|
||||
|
||||
@ -21,7 +21,8 @@ private func makeTestableViewModel(
|
||||
panicRecoveryOperations: PanicRecoveryOperations? = nil,
|
||||
panicNetworkLifecycle: PanicNetworkLifecycle = .noop,
|
||||
panicMetadataWipeOperations: PanicMetadataWipeOperations? = nil,
|
||||
locationManager: LocationChannelManager = .shared
|
||||
locationManager: LocationChannelManager = .shared,
|
||||
outboxStore: MessageOutboxStore? = nil
|
||||
) -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
let keychain = injectedKeychain ?? MockKeychain()
|
||||
let keychainHelper = MockKeychainHelper()
|
||||
@ -35,6 +36,7 @@ private func makeTestableViewModel(
|
||||
identityManager: identityManager,
|
||||
transport: transport,
|
||||
locationManager: locationManager,
|
||||
outboxStore: outboxStore,
|
||||
panicMediaWipe: panicMediaWipe,
|
||||
panicRecoveryOperations: panicRecoveryOperations,
|
||||
panicMetadataWipeOperations: panicMetadataWipeOperations,
|
||||
@ -2631,3 +2633,180 @@ struct ChatViewModelLifecycleTests {
|
||||
#expect(transport.startServicesCallCount == 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Suite(.serialized)
|
||||
struct PrekeyPanicCompletionTests {
|
||||
@Test(arguments: [false, true], [false, true]) @MainActor
|
||||
func failedPrekeyCleanupRetainsRecoveryUntilRetry(_ unresolved: Bool, _ bootstrap: Bool) throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
let directory = root.appendingPathComponent("prekeys")
|
||||
try fm.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let file = directory.appendingPathComponent("bundles.json")
|
||||
let sibling = directory.appendingPathComponent("keep")
|
||||
let oldPeer = Data(repeating: 0x71, count: 32)
|
||||
let seed = PrekeyBundleStore(fileURL: file)
|
||||
#expect(seed.ingest(PrekeyBundle(
|
||||
noiseStaticPublicKey: oldPeer,
|
||||
prekeys: [.init(id: 1, publicKey: Data(repeating: 0x72, count: 32))],
|
||||
generatedAt: UInt64(Date().timeIntervalSince1970 * 1000),
|
||||
signature: Data(repeating: 0, count: 64)
|
||||
)))
|
||||
let bytes = try Data(contentsOf: file)
|
||||
var denied = true
|
||||
defer {
|
||||
try? fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path)
|
||||
try? fm.removeItem(at: root)
|
||||
}
|
||||
let store = PrekeyBundleStore(resolveDefaultFileURL: { unresolved && denied ? nil : file })
|
||||
try bytes.write(to: file)
|
||||
try Data("KEEP".utf8).write(to: sibling)
|
||||
if !unresolved { try fm.setAttributes([.posixPermissions: 0o500], ofItemAtPath: directory.path) }
|
||||
var attempts: [String] = []
|
||||
func cleaned(_ name: String) -> Bool { attempts.append(name); return true }
|
||||
let operations = PanicMetadataWipeOperations(
|
||||
wipeCourier: { cleaned("courier") }, wipeBridge: { cleaned("bridge") },
|
||||
wipeGossip: { cleaned("gossip") }, wipeGroups: { cleaned("groups") },
|
||||
wipeBoard: { cleaned("board") }, wipeEvents: { cleaned("events") },
|
||||
wipePrekeys: { attempts.append("prekeys"); return store.wipe() }
|
||||
)
|
||||
var pending = bootstrap
|
||||
var completion: [String] = []
|
||||
var media = 0
|
||||
let recovery = PanicRecoveryOperations(isPending: { pending }, begin: {
|
||||
pending = true
|
||||
return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
|
||||
}, wipeMedia: { _ in media += 1 }, complete: {
|
||||
pending = false; completion.append("complete")
|
||||
})
|
||||
let keychain = MockKeychain()
|
||||
let (viewModel, transport) = makeTestableViewModel(
|
||||
keychain: keychain, panicRecoveryOperations: recovery,
|
||||
panicNetworkLifecycle: .init(stop: {}, restart: {
|
||||
#expect(!pending)
|
||||
completion.append("restart")
|
||||
}), panicMetadataWipeOperations: operations
|
||||
)
|
||||
let starts = bootstrap ? 0 : transport.startServicesCallCount
|
||||
if !bootstrap {
|
||||
#expect(!viewModel.panicClearAllData(), "Prekey removal failure must keep panic incomplete")
|
||||
}
|
||||
#expect(attempts == ["courier", "bridge", "gossip", "groups", "prekeys", "board", "events"])
|
||||
#expect(keychain.deleteAllCallCount == 1 && media == 1)
|
||||
#expect(!store.hasUsableBundle(for: oldPeer))
|
||||
#expect(pending && completion.isEmpty)
|
||||
#expect(!viewModel.networkActivationAllowed)
|
||||
#expect(transport.startServicesCallCount == starts)
|
||||
#expect(try Data(contentsOf: file) == bytes)
|
||||
denied = false
|
||||
try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path)
|
||||
attempts.removeAll()
|
||||
#expect(viewModel.panicClearAllData())
|
||||
#expect(attempts == ["courier", "bridge", "gossip", "groups", "prekeys", "board", "events"])
|
||||
#expect(keychain.deleteAllCallCount == 2 && media == 2)
|
||||
#expect(!pending && completion == ["complete", "restart"])
|
||||
#expect(viewModel.networkActivationAllowed)
|
||||
#expect(transport.startServicesCallCount == starts + 1)
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
#expect(try Data(contentsOf: sibling) == Data("KEEP".utf8))
|
||||
#expect(viewModel.panicClearAllData(), "Repeated absent prekey file cleanup must succeed")
|
||||
let freshPeer = Data(repeating: 0x73, count: 32)
|
||||
#expect(store.ingest(PrekeyBundle(
|
||||
noiseStaticPublicKey: freshPeer,
|
||||
prekeys: [.init(id: 1, publicKey: Data(repeating: 0x74, count: 32))],
|
||||
generatedAt: UInt64(Date().timeIntervalSince1970 * 1000),
|
||||
signature: Data(repeating: 0, count: 64)
|
||||
)))
|
||||
let reopened = PrekeyBundleStore(fileURL: file)
|
||||
#expect(reopened.hasUsableBundle(for: freshPeer),
|
||||
"The recovered prekey location must support future persistence after controller recovery")
|
||||
#expect(!reopened.hasUsableBundle(for: oldPeer))
|
||||
}
|
||||
}
|
||||
|
||||
@Suite(.serialized)
|
||||
struct OutboxPanicCompletionTests {
|
||||
@Test(arguments: [false, true], [false, true]) @MainActor
|
||||
func failedOutboxCleanupRetainsRecoveryUntilRetry(_ unresolved: Bool, _ bootstrap: Bool) throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
let directory = root.appendingPathComponent("outbox")
|
||||
try fm.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let file = directory.appendingPathComponent("outbox.sealed")
|
||||
let sibling = directory.appendingPathComponent("keep")
|
||||
let keychain = MockKeychain()
|
||||
let oldPeer = PeerID(str: "0000000000000071")
|
||||
MessageOutboxStore(keychain: keychain, fileURL: file).save([
|
||||
oldPeer: [.init(content: "SYNTHETIC_OLD_OUTBOX", nickname: "synthetic",
|
||||
messageID: "synthetic-before-recovery", timestamp: Date())]
|
||||
])
|
||||
let bytes = try Data(contentsOf: file)
|
||||
var denied = true
|
||||
defer {
|
||||
try? fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path)
|
||||
try? fm.removeItem(at: root)
|
||||
}
|
||||
let store = MessageOutboxStore(keychain: keychain, resolveDefaultFileURL: { unresolved && denied ? nil : file })
|
||||
try bytes.write(to: file)
|
||||
try Data("KEEP".utf8).write(to: sibling)
|
||||
if !unresolved { try fm.setAttributes([.posixPermissions: 0o500], ofItemAtPath: directory.path) }
|
||||
var attempts: [String] = []
|
||||
func cleaned(_ name: String) -> Bool { attempts.append(name); return true }
|
||||
let operations = PanicMetadataWipeOperations(
|
||||
wipeCourier: { cleaned("courier") }, wipeBridge: { cleaned("bridge") },
|
||||
wipeGossip: { cleaned("gossip") }, wipeGroups: { cleaned("groups") },
|
||||
wipeBoard: { cleaned("board") }, wipeEvents: { cleaned("events") },
|
||||
wipePrekeys: { cleaned("prekeys") }
|
||||
)
|
||||
var pending = bootstrap
|
||||
var completion: [String] = []
|
||||
var media = 0
|
||||
let recovery = PanicRecoveryOperations(isPending: { pending }, begin: {
|
||||
pending = true
|
||||
return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
|
||||
}, wipeMedia: { _ in media += 1 }, complete: {
|
||||
pending = false; completion.append("complete")
|
||||
})
|
||||
let (viewModel, transport) = makeTestableViewModel(
|
||||
keychain: keychain, panicRecoveryOperations: recovery,
|
||||
panicNetworkLifecycle: .init(stop: {}, restart: {
|
||||
#expect(!pending)
|
||||
completion.append("restart")
|
||||
}), panicMetadataWipeOperations: operations, outboxStore: store
|
||||
)
|
||||
let starts = bootstrap ? 0 : transport.startServicesCallCount
|
||||
if !bootstrap {
|
||||
#expect(!viewModel.panicClearAllData(), "Outbox removal failure must keep panic incomplete")
|
||||
}
|
||||
#expect(attempts == ["courier", "bridge", "gossip", "groups", "prekeys", "board", "events"])
|
||||
#expect(keychain.deleteAllCallCount == 1 && media == 1)
|
||||
#expect(store.load().isEmpty)
|
||||
#expect(keychain.load(key: "outbox-encryption-key", service: "chat.bitchat.outbox") == nil)
|
||||
#expect(pending && completion.isEmpty)
|
||||
#expect(!viewModel.networkActivationAllowed)
|
||||
#expect(transport.startServicesCallCount == starts)
|
||||
#expect(try Data(contentsOf: file) == bytes)
|
||||
denied = false
|
||||
try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path)
|
||||
attempts.removeAll()
|
||||
#expect(viewModel.panicClearAllData())
|
||||
#expect(attempts == ["courier", "bridge", "gossip", "groups", "prekeys", "board", "events"])
|
||||
#expect(keychain.deleteAllCallCount == 2 && media == 2)
|
||||
#expect(!pending && completion == ["complete", "restart"])
|
||||
#expect(viewModel.networkActivationAllowed)
|
||||
#expect(transport.startServicesCallCount == starts + 1)
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
#expect(try Data(contentsOf: sibling) == Data("KEEP".utf8))
|
||||
#expect(viewModel.panicClearAllData(), "Repeated absent outbox file cleanup must succeed")
|
||||
let freshPeer = PeerID(str: "0000000000000073")
|
||||
viewModel.messageRouter.sendPrivate(
|
||||
"SYNTHETIC_FRESH_OUTBOX", to: freshPeer,
|
||||
recipientNickname: "synthetic", messageID: "synthetic-after-recovery"
|
||||
)
|
||||
let fresh = MessageOutboxStore(keychain: keychain, fileURL: file).load()
|
||||
#expect(fresh[oldPeer] == nil)
|
||||
#expect(fresh[freshPeer]?.map(\.messageID) == ["synthetic-after-recovery"],
|
||||
"The router must persist fresh mail after controller recovery")
|
||||
}
|
||||
}
|
||||
|
||||
@ -401,4 +401,83 @@ struct PrekeyEndToEndTests {
|
||||
#expect(!cached)
|
||||
#expect(!alice._test_hasGossipPrekeyBundle(for: bob.myPeerID))
|
||||
}
|
||||
@Test(arguments: [false, true]) @MainActor
|
||||
func panicDropsUnboundPrekeyPacketsButAcceptsFreshBundles(_ performPanic: Bool) async throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent("deferred-prekey-\(UUID().uuidString)")
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let keychain = MockKeychain()
|
||||
let bridge = NostrIdentityBridge(keychain: MockKeychainHelper())
|
||||
let identity = MockIdentityManager(keychain)
|
||||
let alice = BLEService(
|
||||
keychain: keychain, idBridge: bridge, identityManager: identity,
|
||||
initializeBluetoothManagers: false,
|
||||
incomingFileStore: BLEIncomingFileStore(baseDirectory: root.appendingPathComponent("media"))
|
||||
)
|
||||
alice.courierStore = CourierStore(persistsToDisk: false)
|
||||
let file = root.appendingPathComponent("prekeys/bundles.json")
|
||||
alice.prekeyBundleStore = PrekeyBundleStore(fileURL: file)
|
||||
let bob = makeService()
|
||||
defer { alice.stopServices(); bob.stopServices() }
|
||||
let tap = PacketTap()
|
||||
bob._test_onOutboundPacket = tap.record
|
||||
let captured = try await captureAnnounceAndBundle(from: bob, tap: tap)
|
||||
let peerKey = bob.noiseStaticPublicKeyData()
|
||||
let metadata = PanicMetadataWipeOperations(
|
||||
wipeCourier: { true }, wipeBridge: { true }, wipeGossip: { true },
|
||||
wipeGroups: { true }, wipeBoard: { true }, wipeEvents: { true },
|
||||
wipePrekeys: { alice.prekeyBundleStore.wipe() }
|
||||
)
|
||||
let recovery = PanicRecoveryOperations(isPending: { false }, begin: {
|
||||
PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
|
||||
}, wipeMedia: { _ in }, complete: {})
|
||||
let viewModel = ChatViewModel(
|
||||
keychain: keychain, idBridge: bridge, identityManager: identity, transport: alice,
|
||||
panicRecoveryOperations: recovery, panicMetadataWipeOperations: metadata,
|
||||
panicNetworkLifecycle: .noop
|
||||
)
|
||||
// The production receive handler runs, without a preseeded owner binding.
|
||||
alice._test_handlePacket(captured.bundle, fromPeerID: bob.myPeerID, preseedPeer: false)
|
||||
await fencePrekeyProbe(alice)
|
||||
#expect(!alice.prekeyBundleStore.hasUsableBundle(for: peerKey))
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
if performPanic {
|
||||
#expect(viewModel.panicClearAllData(restartServices: false))
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
}
|
||||
alice._test_handlePacket(captured.announce, fromPeerID: bob.myPeerID, preseedPeer: false)
|
||||
await fencePrekeyProbe(alice)
|
||||
#expect(alice.prekeyBundleStore.hasUsableBundle(for: peerKey) == !performPanic,
|
||||
"Panic must discard a pre-panic unbound bundle before a later announce can drain it")
|
||||
#expect(PrekeyBundleStore(fileURL: file).hasUsableBundle(for: peerKey) == !performPanic,
|
||||
"A later announce alone must not persist a pre-panic deferred bundle")
|
||||
if performPanic {
|
||||
let fresh = bob.signPacketForBroadcast(BitchatPacket(
|
||||
type: captured.bundle.type, senderID: captured.bundle.senderID,
|
||||
recipientID: nil, timestamp: captured.bundle.timestamp + 1,
|
||||
payload: captured.bundle.payload, signature: nil, ttl: captured.bundle.ttl
|
||||
))
|
||||
#expect(fresh.signature != nil)
|
||||
alice._test_handlePacket(fresh, fromPeerID: bob.myPeerID, preseedPeer: false)
|
||||
await fencePrekeyProbe(alice)
|
||||
#expect(PrekeyBundleStore(fileURL: file).hasUsableBundle(for: peerKey),
|
||||
"A fresh post-panic bundle must remain persistable")
|
||||
}
|
||||
}
|
||||
|
||||
private final class PrekeyProbeService: @unchecked Sendable {
|
||||
let service: BLEService
|
||||
init(_ service: BLEService) { self.service = service }
|
||||
}
|
||||
|
||||
private func fencePrekeyProbe(_ service: BLEService) async {
|
||||
let box = PrekeyProbeService(service)
|
||||
await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global().async {
|
||||
box.service._test_fenceEngine()
|
||||
continuation.resume()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -118,6 +118,113 @@ struct PrekeyBundleStoreTests {
|
||||
#expect(store.hasUsableBundle(for: keys[2]))
|
||||
}
|
||||
|
||||
private func panicBundle(noiseKey: Data, generatedAt: UInt64) -> PrekeyBundle {
|
||||
PrekeyBundle(
|
||||
noiseStaticPublicKey: noiseKey,
|
||||
prekeys: [.init(id: 1, publicKey: Data(repeating: 0x41, count: 32))],
|
||||
generatedAt: generatedAt,
|
||||
signature: Data(count: PrekeyBundle.signatureLength)
|
||||
)
|
||||
}
|
||||
|
||||
@Test func deniedPanicDeletionClearsMemoryAndRetriesWithoutRemovingSibling() throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent("prekey-panic-\(UUID().uuidString)")
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer {
|
||||
try? fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path)
|
||||
try? fm.removeItem(at: root)
|
||||
}
|
||||
let file = root.appendingPathComponent("bundles.json")
|
||||
let sibling = root.appendingPathComponent("keep.txt")
|
||||
let siblingBytes = Data("SYNTHETIC_UNRELATED_FILE".utf8)
|
||||
try siblingBytes.write(to: sibling)
|
||||
let current = Date(timeIntervalSince1970: 1_800_000_000)
|
||||
let noiseKey = Data(repeating: 0xD1, count: 32)
|
||||
let store = PrekeyBundleStore(fileURL: file, now: { current })
|
||||
#expect(store.ingest(panicBundle(noiseKey: noiseKey, generatedAt: 1_800_000_000_000)))
|
||||
let original = try Data(contentsOf: file)
|
||||
#expect(PrekeyBundleStore(fileURL: file, now: { current }).hasUsableBundle(for: noiseKey))
|
||||
|
||||
try fm.setAttributes([.posixPermissions: 0o500], ofItemAtPath: root.path)
|
||||
#expect(!store.wipe(), "Denied prekey file removal must be reported")
|
||||
#expect(!store.hasUsableBundle(for: noiseKey), "Prekey memory must clear even when file removal fails")
|
||||
#expect(store.assignPrekey(messageID: "synthetic-after-wipe", recipientNoiseKey: noiseKey) == nil)
|
||||
#expect(try Data(contentsOf: file) == original)
|
||||
#expect(PrekeyBundleStore(fileURL: file, now: { current }).hasUsableBundle(for: noiseKey))
|
||||
#expect(try Data(contentsOf: sibling) == siblingBytes)
|
||||
|
||||
try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path)
|
||||
#expect(store.wipe(), "Prekey deletion must succeed after access is restored")
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
#expect(store.wipe(), "An absent prekey file must count as successful cleanup")
|
||||
#expect(try Data(contentsOf: sibling) == siblingBytes)
|
||||
}
|
||||
|
||||
@Test func unresolvedPanicLocationRetriesAndRetainsRecoveredPersistenceLocation() throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent("prekey-location-\(UUID().uuidString)")
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("bundles.json")
|
||||
let current = Date(timeIntervalSince1970: 1_800_000_000)
|
||||
let oldKey = Data(repeating: 0xD2, count: 32)
|
||||
let freshKey = Data(repeating: 0xD3, count: 32)
|
||||
let seed = PrekeyBundleStore(fileURL: file, now: { current })
|
||||
#expect(seed.ingest(panicBundle(noiseKey: oldKey, generatedAt: 1_800_000_000_000)))
|
||||
let original = try Data(contentsOf: file)
|
||||
var available = false
|
||||
var lookups = 0
|
||||
let store = PrekeyBundleStore(now: { current }, resolveDefaultFileURL: {
|
||||
lookups += 1
|
||||
return available ? file : nil
|
||||
})
|
||||
#expect(lookups == 1)
|
||||
#expect(store.ingest(panicBundle(noiseKey: oldKey, generatedAt: 1_800_000_000_000)))
|
||||
#expect(!store.wipe(), "An unresolved persistent prekey location must fail cleanup")
|
||||
#expect(lookups == 2, "Panic must retry the unresolved prekey location")
|
||||
#expect(!store.hasUsableBundle(for: oldKey))
|
||||
#expect(try Data(contentsOf: file) == original)
|
||||
|
||||
available = true
|
||||
#expect(store.wipe(), "A later panic attempt must resolve and remove the prekey file")
|
||||
#expect(lookups == 3)
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
available = false
|
||||
#expect(store.ingest(panicBundle(noiseKey: freshKey, generatedAt: 1_800_000_000_000)))
|
||||
#expect(lookups == 3)
|
||||
let reopened = PrekeyBundleStore(fileURL: file, now: { current })
|
||||
#expect(reopened.hasUsableBundle(for: freshKey), "Fresh bundles must persist at the recovered location")
|
||||
#expect(!reopened.hasUsableBundle(for: oldKey))
|
||||
#expect(store.wipe())
|
||||
#expect(lookups == 3, "The recovered prekey location must remain cached")
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
}
|
||||
|
||||
@Test func memoryOnlyPanicIgnoresOverrideAndDefaultResolver() throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent("prekey-memory-\(UUID().uuidString)")
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let override = root.appendingPathComponent("override.json")
|
||||
let resolved = root.appendingPathComponent("resolved.json")
|
||||
let sentinel = Data("SYNTHETIC_UNRELATED_FILE".utf8)
|
||||
try sentinel.write(to: override)
|
||||
try sentinel.write(to: resolved)
|
||||
var lookups = 0
|
||||
let current = Date(timeIntervalSince1970: 1_800_000_000)
|
||||
let noiseKey = Data(repeating: 0xD4, count: 32)
|
||||
let store = PrekeyBundleStore(persistsToDisk: false, fileURL: override, now: { current },
|
||||
resolveDefaultFileURL: { lookups += 1; return resolved })
|
||||
#expect(store.ingest(panicBundle(noiseKey: noiseKey, generatedAt: 1_800_000_000_000)))
|
||||
#expect(store.hasUsableBundle(for: noiseKey))
|
||||
#expect(store.wipe(), "Intentional memory-only prekeys need no disk cleanup")
|
||||
#expect(!store.hasUsableBundle(for: noiseKey))
|
||||
#expect(store.wipe())
|
||||
#expect(lookups == 0, "Memory-only prekeys must not resolve a disk location")
|
||||
#expect(try Data(contentsOf: override) == sentinel)
|
||||
#expect(try Data(contentsOf: resolved) == sentinel)
|
||||
}
|
||||
|
||||
@Test func persistsAcrossInstancesAndWipes() throws {
|
||||
let dir = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("prekey-bundle-store-tests-\(UUID().uuidString)", isDirectory: true)
|
||||
@ -133,7 +240,7 @@ struct PrekeyBundleStoreTests {
|
||||
let second = PrekeyBundleStore(fileURL: fileURL)
|
||||
#expect(second.assignPrekey(messageID: "m2", recipientNoiseKey: noiseKey)?.id == 2)
|
||||
|
||||
second.wipe()
|
||||
#expect(second.wipe())
|
||||
#expect(!FileManager.default.fileExists(atPath: fileURL.path))
|
||||
let third = PrekeyBundleStore(fileURL: fileURL)
|
||||
#expect(!third.hasUsableBundle(for: noiseKey))
|
||||
|
||||
@ -243,6 +243,85 @@ struct MessageOutboxStoreTests {
|
||||
#expect(relaunched[otherPeer]?.map(\.messageID) == ["shared-id"])
|
||||
}
|
||||
|
||||
@Test func deniedPanicDeletionRetainsCiphertextButClearsMemoryAndMockedKey() throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent("outbox-panic-\(UUID().uuidString)")
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer {
|
||||
try? fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path)
|
||||
try? fm.removeItem(at: root)
|
||||
}
|
||||
let file = root.appendingPathComponent("outbox.sealed")
|
||||
let sibling = root.appendingPathComponent("keep.txt")
|
||||
let siblingBytes = Data("SYNTHETIC_UNRELATED_FILE".utf8)
|
||||
try siblingBytes.write(to: sibling)
|
||||
let keychain = MockKeychain()
|
||||
let peerID = PeerID(str: "0000000000000001")
|
||||
let store = MessageOutboxStore(keychain: keychain, fileURL: file)
|
||||
store.save([peerID: [makeMessage("synthetic-before-panic")]])
|
||||
#expect(store.load()[peerID]?.map(\.messageID) == ["synthetic-before-panic"])
|
||||
#expect(keychain.load(key: "outbox-encryption-key", service: "chat.bitchat.outbox") != nil)
|
||||
let ciphertext = try Data(contentsOf: file)
|
||||
|
||||
try fm.setAttributes([.posixPermissions: 0o500], ofItemAtPath: root.path)
|
||||
#expect(!store.wipe(), "Denied outbox byte deletion must be reported")
|
||||
#expect(store.load().isEmpty, "Outbox memory must clear despite failed byte deletion")
|
||||
#expect(keychain.load(key: "outbox-encryption-key", service: "chat.bitchat.outbox") == nil,
|
||||
"Failed byte deletion must still attempt mocked key deletion")
|
||||
#expect(try Data(contentsOf: file) == ciphertext)
|
||||
let reopened = MessageOutboxStore(keychain: keychain, fileURL: file)
|
||||
#expect(reopened.load().isEmpty, "The retained ciphertext must not recover messages without its mocked key")
|
||||
#expect(try Data(contentsOf: file) == ciphertext)
|
||||
#expect(try Data(contentsOf: sibling) == siblingBytes)
|
||||
|
||||
try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path)
|
||||
#expect(store.wipe(), "Outbox byte deletion must succeed after access is restored")
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
#expect(store.wipe(), "An absent outbox file must count as successful cleanup")
|
||||
#expect(try Data(contentsOf: sibling) == siblingBytes)
|
||||
store.save([peerID: [makeMessage("synthetic-after-panic")]])
|
||||
let fresh = MessageOutboxStore(keychain: keychain, fileURL: file).load()
|
||||
#expect(fresh[peerID]?.map(\.messageID) == ["synthetic-after-panic"])
|
||||
}
|
||||
|
||||
@Test func unresolvedPanicLocationRetriesAndRetainsRecoveredOutboxLocation() throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent("outbox-location-\(UUID().uuidString)")
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("outbox.sealed")
|
||||
let keychain = MockKeychain()
|
||||
let peerID = PeerID(str: "0000000000000001")
|
||||
MessageOutboxStore(keychain: keychain, fileURL: file)
|
||||
.save([peerID: [makeMessage("synthetic-before-panic")]])
|
||||
let ciphertext = try Data(contentsOf: file)
|
||||
var available = false
|
||||
var lookups = 0
|
||||
let store = MessageOutboxStore(keychain: keychain, resolveDefaultFileURL: {
|
||||
lookups += 1
|
||||
return available ? file : nil
|
||||
})
|
||||
#expect(lookups == 1)
|
||||
#expect(!store.wipe(), "An unresolved outbox location must fail panic cleanup")
|
||||
#expect(lookups == 2, "Panic must retry an unresolved outbox location")
|
||||
#expect(store.load().isEmpty)
|
||||
#expect(try Data(contentsOf: file) == ciphertext)
|
||||
#expect(keychain.load(key: "outbox-encryption-key", service: "chat.bitchat.outbox") == nil)
|
||||
|
||||
available = true
|
||||
#expect(store.wipe(), "A later panic attempt must resolve and remove the outbox file")
|
||||
#expect(lookups == 3)
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
available = false
|
||||
store.save([peerID: [makeMessage("synthetic-after-panic")]])
|
||||
#expect(lookups == 3)
|
||||
let reopened = MessageOutboxStore(keychain: keychain, fileURL: file).load()
|
||||
#expect(reopened[peerID]?.map(\.messageID) == ["synthetic-after-panic"],
|
||||
"Fresh outbox messages must persist at the recovered location")
|
||||
#expect(store.wipe())
|
||||
#expect(lookups == 3, "The recovered outbox location must remain cached")
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
}
|
||||
|
||||
@Test func wipeRemovesFileAndKey() {
|
||||
let fileURL = makeTempURL()
|
||||
let keychain = MockKeychain()
|
||||
@ -250,8 +329,10 @@ struct MessageOutboxStoreTests {
|
||||
store.save([PeerID(str: "0000000000000001"): [makeMessage("m1")]])
|
||||
#expect(FileManager.default.fileExists(atPath: fileURL.path))
|
||||
|
||||
store.wipe()
|
||||
#expect(keychain.load(key: "outbox-encryption-key", service: "chat.bitchat.outbox") != nil)
|
||||
#expect(store.wipe())
|
||||
#expect(!FileManager.default.fileExists(atPath: fileURL.path))
|
||||
#expect(keychain.load(key: "outbox-encryption-key", service: "chat.bitchat.outbox") == nil)
|
||||
#expect(store.load().isEmpty)
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user