mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-29 08:29:22 +00:00
Merge 9ffd473884 into 04995f68e4
This commit is contained in:
23 files changed
+1342
-116
No files matched your search
@@ -724,7 +724,7 @@ final class BLEService: NSObject {
|
||||
func suspendForPanicReset() {
|
||||
setPanicSuspended(true)
|
||||
noisePacketHandler.resetForPanic()
|
||||
gossipSyncManager?.stop()
|
||||
gossipSyncManager?.stopForPanic()
|
||||
gossipSyncManager = nil
|
||||
// Stop the radio and drain CoreBluetooth's delegate queue first. A
|
||||
// callback may already have passed its initial suspension check; the
|
||||
@@ -760,7 +760,7 @@ final class BLEService: NSObject {
|
||||
currentNickname: String,
|
||||
restartServices: Bool = true
|
||||
) {
|
||||
gossipSyncManager?.stop()
|
||||
gossipSyncManager?.stopForPanic()
|
||||
gossipSyncManager = nil
|
||||
// Discard deferred pre-panic ciphertext behind any in-flight receive
|
||||
// handlers so none can repopulate the handler's bounded queue.
|
||||
@@ -769,6 +769,7 @@ final class BLEService: NSObject {
|
||||
}
|
||||
onEngine {
|
||||
pendingNoiseSessionQueues.removeAll()
|
||||
pendingPrekeyBundles.removeAll()
|
||||
}
|
||||
|
||||
let panicReset = onEngine {
|
||||
@@ -2929,12 +2930,9 @@ final class BLEService: NSObject {
|
||||
|
||||
// MARK: - GossipSyncManager Delegate
|
||||
extension BLEService: GossipSyncManager.Delegate {
|
||||
// Gossip calls arrive on the manager's own serial queue; sends read
|
||||
// the engine-owned bindings, so they enter an engine slot. The sync
|
||||
// hop is safe: mesh.sync sits above the engine in the sync order —
|
||||
// production engine code only ever queue.async's into the manager
|
||||
// (the queue.sync helpers are DEBUG test entry points that run on
|
||||
// test threads), so no reverse edge exists.
|
||||
// Gossip delegate calls synchronously enter the engine. Engine callers
|
||||
// must enqueue manager work asynchronously to avoid reversing that order.
|
||||
// Keep the synchronous panic-retirement drain outside the engine queue.
|
||||
func sendPacket(_ packet: BitchatPacket) {
|
||||
onEngine {
|
||||
broadcastPacket(packet)
|
||||
|
||||
@@ -91,14 +91,24 @@ final class BoardStore {
|
||||
private var posts: [StoredPost] = []
|
||||
private var tombstones: [StoredTombstone] = []
|
||||
private let queue = DispatchQueue(label: "chat.bitchat.board.store")
|
||||
private let fileURL: URL?
|
||||
private var fileURL: URL?
|
||||
private let resolveDefaultFileURL: () -> URL?
|
||||
private let persistsToDisk: Bool
|
||||
private let now: () -> Date
|
||||
|
||||
/// - Parameter fileURL: Overrides the on-disk location (tests). Ignored
|
||||
/// when `persistsToDisk` is false.
|
||||
init(persistsToDisk: Bool = true, fileURL: URL? = nil, now: @escaping () -> Date = Date.init) {
|
||||
init(
|
||||
persistsToDisk: Bool = true,
|
||||
fileURL: URL? = nil,
|
||||
now: @escaping () -> Date = Date.init,
|
||||
resolveDefaultFileURL: (() -> URL?)? = nil
|
||||
) {
|
||||
self.now = now
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -147,18 +157,19 @@ final class BoardStore {
|
||||
// MARK: - Maintenance
|
||||
|
||||
/// Panic wipe: drop all board data from memory and disk.
|
||||
func wipe() {
|
||||
queue.sync {
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
let removed = queue.sync {
|
||||
posts.removeAll()
|
||||
tombstones.removeAll()
|
||||
if let fileURL {
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
}
|
||||
let removed = !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)
|
||||
publishSnapshotLocked()
|
||||
return removed
|
||||
}
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.didWipe.send()
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
// MARK: - Internals (call only on `queue`)
|
||||
|
||||
@@ -121,7 +121,9 @@ final class CourierStore {
|
||||
|
||||
private var envelopes: [StoredEnvelope] = []
|
||||
private let queue = DispatchQueue(label: "chat.bitchat.courier.store")
|
||||
private let fileURL: URL?
|
||||
private var fileURL: URL?
|
||||
private let resolveDefaultFileURL: () -> URL?
|
||||
private let persistsToDisk: Bool
|
||||
private let now: () -> Date
|
||||
private let readData: (URL) throws -> Data
|
||||
/// A protected file can be present but unreadable during an iOS
|
||||
@@ -139,10 +141,14 @@ final class CourierStore {
|
||||
persistsToDisk: Bool = true,
|
||||
fileURL: URL? = nil,
|
||||
now: @escaping () -> Date = Date.init,
|
||||
readData: @escaping (URL) throws -> Data = { try Data(contentsOf: $0) }
|
||||
readData: @escaping (URL) throws -> Data = { try Data(contentsOf: $0) },
|
||||
resolveDefaultFileURL: (() -> URL?)? = nil
|
||||
) {
|
||||
self.now = now
|
||||
self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil
|
||||
let resolver = resolveDefaultFileURL ?? Self.defaultFileURL
|
||||
self.resolveDefaultFileURL = resolver
|
||||
self.persistsToDisk = persistsToDisk
|
||||
self.fileURL = persistsToDisk ? (fileURL ?? resolver()) : nil
|
||||
self.readData = readData
|
||||
loadFromDisk()
|
||||
#if os(iOS)
|
||||
@@ -416,15 +422,16 @@ final class CourierStore {
|
||||
// MARK: - Maintenance
|
||||
|
||||
/// Panic wipe: drop all carried mail from memory and disk.
|
||||
func wipe() {
|
||||
queue.sync {
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
let removed = queue.sync {
|
||||
envelopes.removeAll()
|
||||
diskLoadDeferred = false
|
||||
if let fileURL {
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
}
|
||||
let removed = !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)
|
||||
publishCountLocked()
|
||||
return removed
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
/// Retries a protected-data read and merges any envelopes accepted while
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -202,7 +202,8 @@ final class BridgeCourierService: ObservableObject {
|
||||
}
|
||||
|
||||
/// Panic wipe: forget queued drops and the persisted dedup record.
|
||||
func wipe() {
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
cancelActivePublishes()
|
||||
rejectedDropKeys = ExpiringIDSet(
|
||||
capacity: Limits.maxTrackedIDs,
|
||||
@@ -210,7 +211,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
)
|
||||
publishedDropKeys = ExpiringIDSet(capacity: Limits.maxTrackedIDs, lifetime: CourierEnvelope.maxLifetimeSeconds)
|
||||
seenDropEventIDs = ExpiringIDSet(capacity: Limits.maxTrackedIDs, lifetime: CourierEnvelope.maxLifetimeSeconds)
|
||||
dedupStore.wipe()
|
||||
return dedupStore.wipe()
|
||||
}
|
||||
|
||||
// MARK: - Sender role
|
||||
|
||||
@@ -78,12 +78,21 @@ final class BridgeDropDedupStore {
|
||||
var seenDropEventIDs: [String: Date]
|
||||
}
|
||||
|
||||
private let fileURL: URL?
|
||||
private var fileURL: URL?
|
||||
private let resolveDefaultFileURL: () -> URL?
|
||||
private let persistsToDisk: Bool
|
||||
|
||||
/// - Parameter fileURL: Overrides the on-disk location (tests). Ignored
|
||||
/// when `persistsToDisk` is false.
|
||||
init(persistsToDisk: Bool = true, fileURL: URL? = nil) {
|
||||
self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil
|
||||
init(
|
||||
persistsToDisk: Bool = true,
|
||||
fileURL: URL? = nil,
|
||||
resolveDefaultFileURL: (() -> URL?)? = nil
|
||||
) {
|
||||
let resolver = resolveDefaultFileURL ?? Self.defaultFileURL
|
||||
self.resolveDefaultFileURL = resolver
|
||||
self.persistsToDisk = persistsToDisk
|
||||
self.fileURL = persistsToDisk ? (fileURL ?? resolver()) : nil
|
||||
}
|
||||
|
||||
func load() -> Snapshot {
|
||||
@@ -118,9 +127,9 @@ final class BridgeDropDedupStore {
|
||||
}
|
||||
|
||||
/// Panic wipe: forget which drops we published or handled.
|
||||
func wipe() {
|
||||
guard let fileURL else { return }
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
return !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)
|
||||
}
|
||||
|
||||
private static func defaultFileURL() -> URL? {
|
||||
|
||||
@@ -22,13 +22,23 @@ final class GroupStore: ObservableObject {
|
||||
@Published private(set) var groups: [BitchatGroup] = []
|
||||
|
||||
private let keychain: KeychainManagerProtocol
|
||||
private let fileURL: URL?
|
||||
private var fileURL: URL?
|
||||
private let resolveDefaultFileURL: () -> URL?
|
||||
private let persistsToDisk: Bool
|
||||
|
||||
/// - Parameter fileURL: Overrides the on-disk location (tests). Ignored
|
||||
/// when `persistsToDisk` is false.
|
||||
init(keychain: KeychainManagerProtocol, persistsToDisk: Bool = true, fileURL: URL? = nil) {
|
||||
init(
|
||||
keychain: KeychainManagerProtocol,
|
||||
persistsToDisk: Bool = true,
|
||||
fileURL: URL? = nil,
|
||||
resolveDefaultFileURL: (() -> URL?)? = nil
|
||||
) {
|
||||
self.keychain = keychain
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -130,14 +140,13 @@ final class GroupStore: ObservableObject {
|
||||
/// Panic wipe: drop all group keys and metadata from memory and disk.
|
||||
/// (The panic flow also nukes the whole keychain; deleting per-group keys
|
||||
/// here keeps the store safe to wipe on its own.)
|
||||
func wipe() {
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
for group in groups {
|
||||
_ = keychain.deleteIdentityKey(forKey: Self.keychainKey(for: group.groupID))
|
||||
}
|
||||
groups.removeAll()
|
||||
if let fileURL {
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
}
|
||||
return !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)
|
||||
}
|
||||
|
||||
// MARK: - Internals
|
||||
|
||||
@@ -313,12 +313,13 @@ final class MessageDeduplicationService {
|
||||
|
||||
/// Clears all caches. This is the wipe/panic path: the persisted
|
||||
/// private-envelope record goes with everything else.
|
||||
func clearAll() {
|
||||
@discardableResult
|
||||
func clearAll() -> Bool {
|
||||
contentCache.clear()
|
||||
nostrEventCache.clear()
|
||||
nostrAckCache.clear()
|
||||
pendingPersistIDs.removeAll()
|
||||
nostrEventStore?.wipe()
|
||||
return nostrEventStore?.wipe() ?? true
|
||||
}
|
||||
|
||||
/// Clears only the in-memory Nostr caches (events and ACKs). Runs on
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -21,13 +21,22 @@ import Foundation
|
||||
/// file must also load during a locked-background restoration relaunch.
|
||||
/// Wiped on panic via the dedup service's clear paths.
|
||||
final class NostrProcessedEventStore {
|
||||
private let fileURL: URL?
|
||||
private var fileURL: URL?
|
||||
private let resolveDefaultFileURL: () -> URL?
|
||||
// All file access is serialized here: appends are read-modify-write, and
|
||||
// overlapping debounced flushes would otherwise race and drop IDs.
|
||||
private let ioQueue = DispatchQueue(label: "chat.bitchat.nostr-processed-events", qos: .utility)
|
||||
private let ioQueue: DispatchQueue
|
||||
|
||||
init(fileURL: URL? = nil) {
|
||||
self.fileURL = fileURL ?? Self.defaultFileURL()
|
||||
/// The I/O queue must be serial to preserve append and wipe ordering.
|
||||
init(
|
||||
fileURL: URL? = nil,
|
||||
ioQueue: DispatchQueue = DispatchQueue(label: "chat.bitchat.nostr-processed-events", qos: .utility),
|
||||
resolveDefaultFileURL: (() -> URL?)? = nil
|
||||
) {
|
||||
let resolver = resolveDefaultFileURL ?? Self.defaultFileURL
|
||||
self.resolveDefaultFileURL = resolver
|
||||
self.fileURL = fileURL ?? resolver()
|
||||
self.ioQueue = ioQueue
|
||||
}
|
||||
|
||||
/// Processed event IDs, oldest first (insertion order).
|
||||
@@ -55,11 +64,9 @@ final class NostrProcessedEventStore {
|
||||
}
|
||||
}
|
||||
|
||||
func wipe() {
|
||||
ioQueue.async { [self] in
|
||||
guard let fileURL else { return }
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
}
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
ioQueue.sync { PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL) }
|
||||
}
|
||||
|
||||
private func loadLocked() -> [String] {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//
|
||||
// PanicFileDeletion.swift
|
||||
// bitchat
|
||||
//
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
// For more information, see <https://unlicense.org>
|
||||
//
|
||||
|
||||
import BitLogger
|
||||
import Foundation
|
||||
|
||||
/// Missing files succeed; unresolved persistent locations and removal errors fail.
|
||||
enum PanicFileDeletion {
|
||||
static func remove(_ fileURL: inout URL?, resolvingWith resolve: () -> URL?) -> Bool {
|
||||
// Retry a failed lookup and retain the recovered location for later persistence.
|
||||
if fileURL == nil { fileURL = resolve() }
|
||||
return remove(fileURL)
|
||||
}
|
||||
|
||||
static func remove(_ fileURL: URL?) -> Bool {
|
||||
guard let fileURL else { return false }
|
||||
do {
|
||||
try FileManager.default.removeItem(at: fileURL)
|
||||
return true
|
||||
} catch let error as NSError {
|
||||
if error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError {
|
||||
return true
|
||||
}
|
||||
SecureLogger.error("Panic metadata deletion failed: \(error)", category: .security)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//
|
||||
// PanicMetadataWipeOperations.swift
|
||||
// bitchat
|
||||
//
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
// For more information, see <https://unlicense.org>
|
||||
//
|
||||
|
||||
/// Metadata cleanup dependencies for the panic transaction.
|
||||
struct PanicMetadataWipeOperations {
|
||||
var wipeCourier: () -> Bool
|
||||
var wipeBridge: () -> Bool
|
||||
var wipeGossip: () -> Bool
|
||||
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 required persistent cleanup succeeded.
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
queue.sync {
|
||||
bundles.removeAll()
|
||||
if let fileURL {
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
}
|
||||
return !persistsToDisk || PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,10 +18,13 @@ import Foundation
|
||||
/// range — so file protection (no additional sealing) is the right at-rest
|
||||
/// posture. Wiped on panic.
|
||||
final class GossipMessageArchive {
|
||||
private let fileURL: URL?
|
||||
private var fileURL: URL?
|
||||
private let resolveDefaultFileURL: () -> URL?
|
||||
|
||||
init(fileURL: URL? = nil) {
|
||||
self.fileURL = fileURL ?? Self.defaultFileURL()
|
||||
init(fileURL: URL? = nil, resolveDefaultFileURL: (() -> URL?)? = nil) {
|
||||
let resolver = resolveDefaultFileURL ?? Self.defaultFileURL
|
||||
self.resolveDefaultFileURL = resolver
|
||||
self.fileURL = fileURL ?? resolver()
|
||||
}
|
||||
|
||||
/// Raw binary packets, decoded and freshness-filtered by the caller.
|
||||
@@ -56,14 +59,15 @@ final class GossipMessageArchive {
|
||||
}
|
||||
}
|
||||
|
||||
func wipe() {
|
||||
guard let fileURL else { return }
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
@discardableResult
|
||||
func wipe() -> Bool {
|
||||
return PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL)
|
||||
}
|
||||
|
||||
/// Panic-wipe hook for callers that don't hold the live instance.
|
||||
static func wipeDefault() {
|
||||
GossipMessageArchive().wipe()
|
||||
@discardableResult
|
||||
static func wipeDefault(resolveDefaultFileURL: (() -> URL?)? = nil) -> Bool {
|
||||
GossipMessageArchive(resolveDefaultFileURL: resolveDefaultFileURL).wipe()
|
||||
}
|
||||
|
||||
private static func defaultFileURL() -> URL? {
|
||||
|
||||
@@ -135,6 +135,7 @@ final class GossipSyncManager {
|
||||
// sender while the owner is away.
|
||||
private var latestPrekeyBundleByPeer: [PeerID: (id: String, packet: BitchatPacket)] = [:]
|
||||
private var archiveDirty = false
|
||||
private var stoppedForPanic = false
|
||||
|
||||
// Timer
|
||||
private var periodicTimer: DispatchSourceTimer?
|
||||
@@ -199,6 +200,15 @@ final class GossipSyncManager {
|
||||
periodicTimer?.cancel(); periodicTimer = nil
|
||||
}
|
||||
|
||||
/// Retire this owner after its earlier persistence finishes. The caller
|
||||
/// removes the archive after this returns, while transport admission is closed.
|
||||
func stopForPanic() {
|
||||
stop()
|
||||
queue.sync {
|
||||
stoppedForPanic = true
|
||||
}
|
||||
}
|
||||
|
||||
func scheduleInitialSyncToPeer(_ peerID: PeerID, delaySeconds: TimeInterval = 5.0) {
|
||||
queue.asyncAfter(deadline: .now() + delaySeconds) { [weak self] in
|
||||
guard let self = self else { return }
|
||||
@@ -685,6 +695,7 @@ final class GossipSyncManager {
|
||||
}
|
||||
|
||||
private func persistArchiveIfDirty() {
|
||||
guard !stoppedForPanic else { return }
|
||||
guard archiveDirty, let archive else { return }
|
||||
archiveDirty = false
|
||||
let packets = messages.allPackets(isFresh: isPacketFresh)
|
||||
|
||||
@@ -329,6 +329,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
var nostrRelayManager: NostrRelayManager?
|
||||
private let userDefaults = UserDefaults.standard
|
||||
let keychain: KeychainManagerProtocol
|
||||
private let panicMetadataWipeOperations: PanicMetadataWipeOperations?
|
||||
private let panicRecoveryOperations: PanicRecoveryOperations
|
||||
private let panicNetworkLifecycle: PanicNetworkLifecycle
|
||||
private var isPanicResetting = false
|
||||
@@ -1163,6 +1164,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
sfMetrics: StoreAndForwardMetrics? = nil,
|
||||
panicMediaWipe: (() throws -> Void)? = nil,
|
||||
panicRecoveryOperations: PanicRecoveryOperations? = nil,
|
||||
panicMetadataWipeOperations: PanicMetadataWipeOperations? = nil,
|
||||
panicNetworkLifecycle: PanicNetworkLifecycle = .noop
|
||||
) {
|
||||
let conversations = conversations ?? ConversationStore()
|
||||
@@ -1178,6 +1180,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
)
|
||||
|
||||
self.keychain = keychain
|
||||
self.panicMetadataWipeOperations = panicMetadataWipeOperations
|
||||
self.panicRecoveryOperations = panicRecoveryOperations
|
||||
?? .ephemeral(wipeMedia: panicMediaWipe ?? {})
|
||||
self.panicNetworkLifecycle = panicNetworkLifecycle
|
||||
@@ -1636,10 +1639,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
// Drop courier mail carried for third parties (memory and disk),
|
||||
// our own queued outbox, the carried public history, and the
|
||||
// counters describing all of it
|
||||
CourierStore.shared.wipe()
|
||||
BridgeCourierService.shared.wipe()
|
||||
messageRouter.wipeOutbox()
|
||||
GossipMessageArchive.wipeDefault()
|
||||
var metadataWipeCompleted = (panicMetadataWipeOperations?.wipeCourier() ?? CourierStore.shared.wipe())
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeBridge() ?? BridgeCourierService.shared.wipe()) && metadataWipeCompleted
|
||||
metadataWipeCompleted = messageRouter.wipeOutbox() && metadataWipeCompleted
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeGossip() ?? GossipMessageArchive.wipeDefault()) && metadataWipeCompleted
|
||||
StoreAndForwardMetrics.shared.reset()
|
||||
|
||||
// Ambient-liveliness bookkeeping: sampled nearby-chat previews, the
|
||||
@@ -1654,14 +1657,14 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
NostrRelaySettings.reset()
|
||||
|
||||
// Drop private group keys and rosters (keychain + disk)
|
||||
groupStore.wipe()
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeGroups() ?? groupStore.wipe()) && metadataWipeCompleted
|
||||
// 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.
|
||||
BoardStore.shared.wipe()
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeBoard() ?? BoardStore.shared.wipe()) && metadataWipeCompleted
|
||||
|
||||
// Drop any share-extension handoff staged in the app group. The normal
|
||||
// panic path clears this through AppChromeModel.onPanicWipe, but the
|
||||
@@ -1697,7 +1700,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
|
||||
// Clear read receipt tracking
|
||||
sentReadReceipts.removeAll()
|
||||
deduplicationService.clearAll()
|
||||
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeEvents() ?? deduplicationService.clearAll()) && metadataWipeCompleted
|
||||
|
||||
// IMPORTANT: Clear Nostr-related state
|
||||
// Drop relay subscriptions, handlers, pending sends, and replay state.
|
||||
@@ -1731,7 +1734,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
let panicCompleted: Bool
|
||||
do {
|
||||
try panicRecoveryOperations.wipeMedia(recoveryIntent)
|
||||
if keychainWipeCompleted {
|
||||
if keychainWipeCompleted && metadataWipeCompleted {
|
||||
try panicRecoveryOperations.complete()
|
||||
panicCompleted = true
|
||||
SecureLogger.info(
|
||||
|
||||
@@ -19,7 +19,9 @@ import BitFoundation
|
||||
// MARK: - Test Helpers
|
||||
|
||||
@MainActor
|
||||
private func makeTestableViewModel() -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
private func makeTestableViewModel(
|
||||
locationManager: LocationChannelManager = .shared
|
||||
) -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
let keychain = MockKeychain()
|
||||
let keychainHelper = MockKeychainHelper()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychainHelper)
|
||||
@@ -30,7 +32,8 @@ private func makeTestableViewModel() -> (viewModel: ChatViewModel, transport: Mo
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
identityManager: identityManager,
|
||||
transport: transport
|
||||
transport: transport,
|
||||
locationManager: locationManager
|
||||
)
|
||||
|
||||
return (viewModel, transport)
|
||||
@@ -273,16 +276,21 @@ struct ChatViewModelNostrExtensionTests {
|
||||
func subscribeNostrEvent_addsToTimeline_ifMatchesGeohash() async throws {
|
||||
let geohash = "u4pruydq"
|
||||
let channel = ChannelID.location(GeohashChannel(level: .city, geohash: geohash))
|
||||
let suiteName = "NostrTimeline.\(UUID().uuidString)"
|
||||
let storage = try #require(UserDefaults(suiteName: suiteName))
|
||||
defer { storage.removePersistentDomain(forName: suiteName) }
|
||||
let locationManager = LocationChannelManager(storage: storage)
|
||||
let (viewModel, _) = makeTestableViewModel(locationManager: locationManager)
|
||||
|
||||
LocationChannelManager.shared.select(channel)
|
||||
defer { LocationChannelManager.shared.select(.mesh) }
|
||||
// Channel selection is asynchronous. This fixture owns its manager,
|
||||
// so parallel tests cannot change the channel before event delivery.
|
||||
locationManager.select(channel)
|
||||
let channelReady = await TestHelpers.waitUntil({
|
||||
locationManager.selectedChannel == channel && viewModel.activeChannel == channel
|
||||
&& viewModel.currentGeohash == geohash
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
try #require(channelReady, "The location-channel fixture must settle before delivering an event")
|
||||
|
||||
_ = await TestHelpers.waitUntil({ LocationChannelManager.shared.selectedChannel == channel }, timeout: TestConstants.settleTimeout)
|
||||
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
|
||||
_ = await TestHelpers.waitUntil({ viewModel.activeChannel == channel }, timeout: TestConstants.settleTimeout)
|
||||
|
||||
let signer = try NostrIdentity.generate()
|
||||
let event = NostrEvent(
|
||||
pubkey: signer.publicKeyHex,
|
||||
@@ -293,27 +301,13 @@ struct ChatViewModelNostrExtensionTests {
|
||||
)
|
||||
let signed = try event.sign(with: signer.schnorrSigningKey())
|
||||
viewModel.handleNostrEvent(signed)
|
||||
|
||||
|
||||
let didAppend = await TestHelpers.waitUntil({
|
||||
viewModel.publicMessagePipeline.flushIfNeeded()
|
||||
if viewModel.messages.contains(where: { $0.content == "Hello Geo" }) { return true }
|
||||
// LocationChannelManager is a process-wide singleton: a suite
|
||||
// running in parallel (e.g. CommandProcessorTests) can flip the
|
||||
// selected channel mid-test, which reroutes or drops the event
|
||||
// permanently — no amount of waiting recovers it. Re-assert the
|
||||
// channel and redeliver on each poll: every channel switch clears
|
||||
// the processed-event set and the store dedups by message ID, so
|
||||
// redelivery is idempotent and interference heals on the next
|
||||
// poll while a genuine failure still times out.
|
||||
if LocationChannelManager.shared.selectedChannel != channel {
|
||||
LocationChannelManager.shared.select(channel)
|
||||
}
|
||||
if viewModel.activeChannel == channel {
|
||||
viewModel.handleNostrEvent(signed)
|
||||
}
|
||||
return false
|
||||
return viewModel.messages.contains { $0.id == signed.id && $0.content == "Hello Geo" }
|
||||
}, timeout: TestConstants.settleTimeout)
|
||||
#expect(didAppend)
|
||||
#expect(viewModel.conversations.conversationIDs(forMessageID: signed.id) == [.geohash(geohash)])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
|
||||
@@ -20,7 +20,9 @@ private func makeTestableViewModel(
|
||||
panicMediaWipe: (() throws -> Void)? = nil,
|
||||
panicRecoveryOperations: PanicRecoveryOperations? = nil,
|
||||
panicNetworkLifecycle: PanicNetworkLifecycle = .noop,
|
||||
locationManager: LocationChannelManager = .shared
|
||||
panicMetadataWipeOperations: PanicMetadataWipeOperations? = nil,
|
||||
locationManager: LocationChannelManager = .shared,
|
||||
outboxStore: MessageOutboxStore? = nil
|
||||
) -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
let keychain = injectedKeychain ?? MockKeychain()
|
||||
let keychainHelper = MockKeychainHelper()
|
||||
@@ -34,8 +36,10 @@ private func makeTestableViewModel(
|
||||
identityManager: identityManager,
|
||||
transport: transport,
|
||||
locationManager: locationManager,
|
||||
outboxStore: outboxStore,
|
||||
panicMediaWipe: panicMediaWipe,
|
||||
panicRecoveryOperations: panicRecoveryOperations,
|
||||
panicMetadataWipeOperations: panicMetadataWipeOperations,
|
||||
panicNetworkLifecycle: panicNetworkLifecycle
|
||||
)
|
||||
|
||||
@@ -2150,6 +2154,227 @@ struct ChatViewModelPrivateMediaDeletionTests {
|
||||
|
||||
struct ChatViewModelPanicTests {
|
||||
|
||||
@Test(arguments: 0...6) @MainActor
|
||||
func metadataFailureAttemptsRemainingCleanupAndRetryCommits(_ failedStore: Int) {
|
||||
let names = ["courier", "bridge", "gossip", "groups", "board", "events"]
|
||||
var attempts: [String] = []
|
||||
var denyDeletion = true
|
||||
var pending = false
|
||||
var commits = 0
|
||||
var mediaAttempts = 0
|
||||
var restarts = 0
|
||||
func wipe(_ index: Int) -> Bool {
|
||||
attempts.append(names[index])
|
||||
return !denyDeletion || (failedStore != index && failedStore != 6)
|
||||
}
|
||||
let metadata = PanicMetadataWipeOperations(
|
||||
wipeCourier: { wipe(0) },
|
||||
wipeBridge: { wipe(1) },
|
||||
wipeGossip: { wipe(2) },
|
||||
wipeGroups: { wipe(3) },
|
||||
wipeBoard: { wipe(4) },
|
||||
wipeEvents: { wipe(5) },
|
||||
wipePrekeys: { true }
|
||||
)
|
||||
let recovery = PanicRecoveryOperations(
|
||||
isPending: { pending },
|
||||
begin: {
|
||||
pending = true
|
||||
return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
|
||||
},
|
||||
wipeMedia: { _ in mediaAttempts += 1 },
|
||||
complete: { commits += 1; pending = false }
|
||||
)
|
||||
let keychain = MockKeychain()
|
||||
let (viewModel, transport) = makeTestableViewModel(
|
||||
keychain: keychain,
|
||||
panicRecoveryOperations: recovery,
|
||||
panicNetworkLifecycle: PanicNetworkLifecycle(stop: {}, restart: { restarts += 1 }),
|
||||
panicMetadataWipeOperations: metadata
|
||||
)
|
||||
let starts = transport.startServicesCallCount
|
||||
|
||||
#expect(!viewModel.panicClearAllData(), "A denied metadata store must keep panic incomplete")
|
||||
#expect(attempts == names, "A denied store must not skip the later metadata stores")
|
||||
#expect(keychain.deleteAllCallCount == 1)
|
||||
#expect(mediaAttempts == 1, "Metadata failure must not skip media cleanup")
|
||||
#expect(pending)
|
||||
#expect(commits == 0)
|
||||
#expect(restarts == 0)
|
||||
#expect(transport.startServicesCallCount == starts)
|
||||
#expect(!viewModel.networkActivationAllowed)
|
||||
|
||||
denyDeletion = false
|
||||
attempts.removeAll()
|
||||
#expect(viewModel.panicClearAllData())
|
||||
#expect(attempts == names, "Retry must attempt the full metadata cleanup again")
|
||||
#expect(keychain.deleteAllCallCount == 2)
|
||||
#expect(mediaAttempts == 2)
|
||||
#expect(!pending)
|
||||
#expect(commits == 1)
|
||||
#expect(restarts == 1)
|
||||
#expect(transport.startServicesCallCount == starts + 1)
|
||||
#expect(viewModel.networkActivationAllowed)
|
||||
}
|
||||
|
||||
@Test(arguments: 0..<6) @MainActor
|
||||
func unresolvedMetadataLocationKeepsPanicPendingUntilRetry(_ failedStore: Int) throws {
|
||||
let names = ["courier", "bridge", "gossip", "groups", "board", "events"]
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let files = names.map { root.appendingPathComponent("\($0).json") }
|
||||
let sibling = root.appendingPathComponent("keep.txt")
|
||||
let bytes = Data("SYNTHETIC_UNRESOLVED_METADATA".utf8)
|
||||
let siblingBytes = Data("KEEP".utf8)
|
||||
var denyLookup = true
|
||||
var lookups = Array(repeating: 0, count: names.count)
|
||||
func resolve(_ index: Int) -> URL? {
|
||||
lookups[index] += 1
|
||||
return denyLookup && index == failedStore ? nil : files[index]
|
||||
}
|
||||
let keychain = MockKeychain()
|
||||
let courier = CourierStore(resolveDefaultFileURL: { resolve(0) })
|
||||
let bridge = BridgeDropDedupStore(resolveDefaultFileURL: { resolve(1) })
|
||||
let gossip = GossipMessageArchive(resolveDefaultFileURL: { resolve(2) })
|
||||
let groups = GroupStore(keychain: keychain, resolveDefaultFileURL: { resolve(3) })
|
||||
let board = BoardStore(resolveDefaultFileURL: { resolve(4) })
|
||||
let events = NostrProcessedEventStore(resolveDefaultFileURL: { resolve(5) })
|
||||
let bridgeService = BridgeCourierService(dedupStore: bridge)
|
||||
let deduplicationService = MessageDeduplicationService(nostrEventStore: events)
|
||||
let wipes: [() -> Bool] = [
|
||||
{ courier.wipe() }, { bridgeService.wipe() }, { gossip.wipe() },
|
||||
{ groups.wipe() }, { board.wipe() }, { deduplicationService.clearAll() }
|
||||
]
|
||||
// File removal does not depend on decoding; seed after constructing the stores.
|
||||
for file in files { try bytes.write(to: file) }
|
||||
try siblingBytes.write(to: sibling)
|
||||
var attempts: [String] = []
|
||||
func wipe(_ index: Int) -> Bool {
|
||||
attempts.append(names[index])
|
||||
return wipes[index]()
|
||||
}
|
||||
let metadata = PanicMetadataWipeOperations(
|
||||
wipeCourier: { wipe(0) }, wipeBridge: { wipe(1) },
|
||||
wipeGossip: { wipe(2) }, wipeGroups: { wipe(3) },
|
||||
wipeBoard: { wipe(4) }, wipeEvents: { wipe(5) },
|
||||
wipePrekeys: { true }
|
||||
)
|
||||
var pending = false
|
||||
var mediaAttempts = 0
|
||||
var completionOrder: [String] = []
|
||||
let recovery = PanicRecoveryOperations(
|
||||
isPending: { pending },
|
||||
begin: {
|
||||
pending = true
|
||||
return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
|
||||
},
|
||||
wipeMedia: { _ in mediaAttempts += 1 },
|
||||
complete: { completionOrder.append("complete"); pending = false }
|
||||
)
|
||||
let lifecycle = PanicNetworkLifecycle(stop: {}, restart: {
|
||||
#expect(!pending, "Recovery must complete before service restart")
|
||||
completionOrder.append("restart")
|
||||
})
|
||||
let (viewModel, transport) = makeTestableViewModel(
|
||||
keychain: keychain,
|
||||
panicRecoveryOperations: recovery,
|
||||
panicNetworkLifecycle: lifecycle,
|
||||
panicMetadataWipeOperations: metadata
|
||||
)
|
||||
let starts = transport.startServicesCallCount
|
||||
#expect(keychain.saveIdentityKey(Data("SYNTHETIC_KEY".utf8), forKey: "panic-url-resolution-test"))
|
||||
|
||||
#expect(!viewModel.panicClearAllData(), "An unresolved persistent location must keep panic incomplete")
|
||||
#expect(attempts == names, "A failed lookup must not skip other metadata stores")
|
||||
#expect(keychain.deleteAllCallCount == 1)
|
||||
#expect(keychain.getIdentityKey(forKey: "panic-url-resolution-test") == nil)
|
||||
#expect(mediaAttempts == 1)
|
||||
#expect(pending)
|
||||
#expect(completionOrder.isEmpty, "An unresolved store must not complete recovery or restart services")
|
||||
#expect(transport.startServicesCallCount == starts)
|
||||
#expect(!viewModel.networkActivationAllowed)
|
||||
#expect(try Data(contentsOf: files[failedStore]) == bytes)
|
||||
for index in names.indices where index != failedStore {
|
||||
#expect(!fm.fileExists(atPath: files[index].path), "Other metadata stores must still be deleted")
|
||||
}
|
||||
#expect(try Data(contentsOf: sibling) == siblingBytes)
|
||||
|
||||
let failedLookups = lookups[failedStore]
|
||||
denyLookup = false
|
||||
attempts.removeAll()
|
||||
#expect(viewModel.panicClearAllData(), "Retry must resolve the location and finish cleanup")
|
||||
#expect(lookups[failedStore] > failedLookups, "Retry must attempt the failed lookup again")
|
||||
#expect(attempts == names)
|
||||
#expect(keychain.deleteAllCallCount == 2)
|
||||
#expect(mediaAttempts == 2)
|
||||
#expect(!pending)
|
||||
#expect(completionOrder == ["complete", "restart"])
|
||||
#expect(transport.startServicesCallCount == starts + 1)
|
||||
#expect(viewModel.networkActivationAllowed)
|
||||
for file in files { #expect(!fm.fileExists(atPath: file.path)) }
|
||||
#expect(try Data(contentsOf: sibling) == siblingBytes)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func metadataFailureDuringBootstrapKeepsIntentForRetry() {
|
||||
let names = ["courier", "bridge", "gossip", "groups", "board", "events"]
|
||||
var attempts: [String] = []
|
||||
var denyBoardDeletion = true
|
||||
var pending = true
|
||||
var commits = 0
|
||||
var mediaAttempts = 0
|
||||
var restarts = 0
|
||||
func wipe(_ index: Int) -> Bool {
|
||||
attempts.append(names[index])
|
||||
return index != 4 || !denyBoardDeletion
|
||||
}
|
||||
let metadata = PanicMetadataWipeOperations(
|
||||
wipeCourier: { wipe(0) }, wipeBridge: { wipe(1) },
|
||||
wipeGossip: { wipe(2) }, wipeGroups: { wipe(3) },
|
||||
wipeBoard: { wipe(4) }, wipeEvents: { wipe(5) },
|
||||
wipePrekeys: { true }
|
||||
)
|
||||
let recovery = PanicRecoveryOperations(
|
||||
isPending: { pending },
|
||||
begin: {
|
||||
pending = true
|
||||
return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
|
||||
},
|
||||
wipeMedia: { _ in mediaAttempts += 1 },
|
||||
complete: { commits += 1; pending = false }
|
||||
)
|
||||
let keychain = MockKeychain()
|
||||
let (viewModel, transport) = makeTestableViewModel(
|
||||
keychain: keychain,
|
||||
panicRecoveryOperations: recovery,
|
||||
panicNetworkLifecycle: PanicNetworkLifecycle(stop: {}, restart: { restarts += 1 }),
|
||||
panicMetadataWipeOperations: metadata
|
||||
)
|
||||
|
||||
#expect(attempts == names, "Bootstrap recovery must attempt each metadata operation")
|
||||
#expect(keychain.deleteAllCallCount == 1)
|
||||
#expect(mediaAttempts == 1)
|
||||
#expect(pending)
|
||||
#expect(commits == 0)
|
||||
#expect(restarts == 0)
|
||||
#expect(transport.startServicesCallCount == 0)
|
||||
#expect(!viewModel.networkActivationAllowed)
|
||||
|
||||
denyBoardDeletion = false
|
||||
attempts.removeAll()
|
||||
#expect(viewModel.panicClearAllData())
|
||||
#expect(attempts == names)
|
||||
#expect(keychain.deleteAllCallCount == 2)
|
||||
#expect(mediaAttempts == 2)
|
||||
#expect(!pending)
|
||||
#expect(commits == 1)
|
||||
#expect(restarts == 1)
|
||||
#expect(transport.startServicesCallCount == 1)
|
||||
#expect(viewModel.networkActivationAllowed)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func panicClearAllData_finishesMediaWipeBeforeReturning() {
|
||||
var wipeFinished = false
|
||||
@@ -2411,3 +2636,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)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import Foundation
|
||||
import BitFoundation
|
||||
import XCTest
|
||||
@testable import bitchat
|
||||
|
||||
final class PanicMetadataCompletionTests: XCTestCase {
|
||||
// Dispatch workers own the synchronous store calls. The lock protects the
|
||||
// observation shared with the asynchronous XCTest method.
|
||||
private final class Fixture: @unchecked Sendable {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
let queue = DispatchQueue(label: "test.processed-events.panic")
|
||||
let release = DispatchSemaphore(value: 0)
|
||||
private let lock = NSLock()
|
||||
private var released = false
|
||||
var file: URL { root.appendingPathComponent("events.json") }
|
||||
lazy var store = NostrProcessedEventStore(fileURL: file, ioQueue: queue)
|
||||
lazy var archive = GossipMessageArchive(fileURL: root.appendingPathComponent("gossip.json"))
|
||||
lazy var gossip = GossipSyncManager(
|
||||
myPeerID: PeerID(str: "0102030405060708"),
|
||||
requestSyncManager: RequestSyncManager(),
|
||||
archive: archive
|
||||
)
|
||||
|
||||
func openQueue() {
|
||||
lock.lock()
|
||||
released = true
|
||||
lock.unlock()
|
||||
release.signal()
|
||||
}
|
||||
|
||||
var queueWasReleased: Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return released
|
||||
}
|
||||
}
|
||||
|
||||
func testProcessedEventWipeWaitsForEarlierAppendAndAllowsFreshPersistence() async {
|
||||
let fixture = Fixture()
|
||||
let held = expectation(description: "serial file queue held after seed")
|
||||
let entered = expectation(description: "worker about to wipe queued append")
|
||||
let returnedEarly = expectation(description: "wipe returned while file queue held")
|
||||
returnedEarly.isInverted = true
|
||||
let completed = expectation(description: "wipe and fresh persistence completed")
|
||||
defer { fixture.openQueue() }
|
||||
|
||||
DispatchQueue.global().async {
|
||||
fixture.store.append(["synthetic-seed"], cap: 10)
|
||||
XCTAssertEqual(fixture.store.load(), ["synthetic-seed"])
|
||||
fixture.queue.async {
|
||||
held.fulfill()
|
||||
fixture.release.wait()
|
||||
}
|
||||
}
|
||||
await fulfillment(of: [held], timeout: TestConstants.settleTimeout)
|
||||
|
||||
DispatchQueue.global().async {
|
||||
fixture.store.append(["synthetic-pre-panic"], cap: 10)
|
||||
entered.fulfill()
|
||||
let wiped = fixture.store.wipe()
|
||||
if !fixture.queueWasReleased { returnedEarly.fulfill() }
|
||||
XCTAssertTrue(wiped)
|
||||
XCTAssertTrue(fixture.queueWasReleased, "Processed-event wipe must finish deletion before returning")
|
||||
// Inspect before a load or another queue fence could hide an early return.
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.file.path),
|
||||
"Processed-event wipe must finish deletion before returning")
|
||||
fixture.store.append(["synthetic-fresh"], cap: 10)
|
||||
XCTAssertEqual(fixture.store.load(), ["synthetic-fresh"])
|
||||
let reopened = NostrProcessedEventStore(fileURL: fixture.file)
|
||||
XCTAssertEqual(reopened.load(), ["synthetic-fresh"])
|
||||
try? FileManager.default.removeItem(at: fixture.root)
|
||||
completed.fulfill()
|
||||
}
|
||||
await fulfillment(of: [entered], timeout: TestConstants.settleTimeout)
|
||||
// This bounded observation is scheduling evidence; the intended removal
|
||||
// control must reach the early-return assertion to establish sensitivity.
|
||||
await fulfillment(of: [returnedEarly], timeout: TestConstants.negativeWaitWindow)
|
||||
fixture.openQueue()
|
||||
await fulfillment(of: [completed], timeout: TestConstants.settleTimeout)
|
||||
}
|
||||
|
||||
func testGossipPanicRetirementDrainsQueuedPersistenceBeforeArchiveDeletion() async {
|
||||
let fixture = Fixture()
|
||||
let held = expectation(description: "gossip queue held by packet collection")
|
||||
let entered = expectation(description: "worker about to retire gossip owner")
|
||||
let returnedEarly = expectation(description: "retirement returned while gossip queue held")
|
||||
returnedEarly.isInverted = true
|
||||
let completed = expectation(description: "retirement and archive deletion completed")
|
||||
defer { fixture.openQueue() }
|
||||
|
||||
DispatchQueue.global().async {
|
||||
fixture.gossip.collectPublicMessagePackets { _ in
|
||||
held.fulfill()
|
||||
fixture.release.wait()
|
||||
}
|
||||
}
|
||||
await fulfillment(of: [held], timeout: TestConstants.settleTimeout)
|
||||
DispatchQueue.global().async {
|
||||
let sender = PeerID(str: "1122334455667788")
|
||||
let packet = BitchatPacket(
|
||||
type: MessageType.message.rawValue,
|
||||
senderID: Data([0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]),
|
||||
recipientID: nil,
|
||||
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
|
||||
payload: Data("SYNTHETIC_QUEUED_GOSSIP".utf8), signature: nil, ttl: 1
|
||||
)
|
||||
fixture.gossip.onPublicPacketSeen(packet)
|
||||
fixture.gossip.persistNow()
|
||||
entered.fulfill()
|
||||
fixture.gossip.stopForPanic()
|
||||
XCTAssertTrue(fixture.queueWasReleased, "Gossip retirement must wait for queued persistence")
|
||||
if !fixture.queueWasReleased { returnedEarly.fulfill() }
|
||||
XCTAssertEqual(fixture.archive.load().count, 1,
|
||||
"The queued pre-panic packet must reach persistence before retirement returns")
|
||||
XCTAssertTrue(fixture.archive.wipe())
|
||||
let latePacket = BitchatPacket(
|
||||
type: packet.type, senderID: packet.senderID, recipientID: nil,
|
||||
timestamp: packet.timestamp,
|
||||
payload: Data("SYNTHETIC_RETIRED_OWNER_CALLBACK".utf8), signature: nil, ttl: 1
|
||||
)
|
||||
fixture.gossip.onPublicPacketSeen(latePacket)
|
||||
fixture.gossip.persistNow()
|
||||
XCTAssertEqual(fixture.gossip._messageCount(for: sender), 2)
|
||||
XCTAssertTrue(fixture.archive.load().isEmpty,
|
||||
"The retired owner must not recreate its deleted archive")
|
||||
fixture.gossip.stop()
|
||||
try? FileManager.default.removeItem(at: fixture.root)
|
||||
completed.fulfill()
|
||||
}
|
||||
await fulfillment(of: [entered], timeout: TestConstants.settleTimeout)
|
||||
await fulfillment(of: [returnedEarly], timeout: TestConstants.negativeWaitWindow)
|
||||
fixture.openQueue()
|
||||
await fulfillment(of: [completed], timeout: TestConstants.settleTimeout)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import Testing
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#endif
|
||||
@testable import bitchat
|
||||
|
||||
@Suite(.serialized)
|
||||
@MainActor
|
||||
struct PanicMetadataStoreTests {
|
||||
enum Store: CaseIterable { case groups, board, courier, gossip, bridge, events }
|
||||
|
||||
@Test(arguments: Store.allCases)
|
||||
func deletionFailureIsReportedAndRetryPreservesSibling(_ store: Store) throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { _ = chmod(root.path, 0o700); try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("metadata.json")
|
||||
let sibling = root.appendingPathComponent("keep.txt")
|
||||
let wipe: () -> Bool
|
||||
switch store {
|
||||
case .groups:
|
||||
let owner = GroupStore(keychain: MockKeychain(), fileURL: file)
|
||||
wipe = { owner.wipe() }
|
||||
case .board:
|
||||
let owner = BoardStore(fileURL: file)
|
||||
wipe = { owner.wipe() }
|
||||
case .courier:
|
||||
let owner = CourierStore(fileURL: file)
|
||||
wipe = { owner.wipe() }
|
||||
case .gossip:
|
||||
let owner = GossipMessageArchive(fileURL: file)
|
||||
wipe = { owner.wipe() }
|
||||
case .bridge:
|
||||
let owner = BridgeDropDedupStore(fileURL: file)
|
||||
wipe = { owner.wipe() }
|
||||
case .events:
|
||||
let owner = NostrProcessedEventStore(fileURL: file)
|
||||
wipe = { owner.wipe() }
|
||||
}
|
||||
// Deletion is independent of record decoding; producer/reload coverage is separate.
|
||||
let bytes = Data("SYNTHETIC_METADATA_DELETE_UNIT_FIXTURE".utf8)
|
||||
try bytes.write(to: file)
|
||||
try Data("KEEP".utf8).write(to: sibling)
|
||||
#expect(chmod(root.path, 0o500) == 0)
|
||||
#expect(!wipe(), "A denied metadata deletion must be reported")
|
||||
#expect(try Data(contentsOf: file) == bytes)
|
||||
#expect(chmod(root.path, 0o700) == 0)
|
||||
#expect(wipe(), "Metadata deletion must succeed after access is restored")
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
#expect(fm.fileExists(atPath: sibling.path), "Unrelated metadata sibling must survive")
|
||||
if fm.fileExists(atPath: sibling.path) {
|
||||
#expect(try Data(contentsOf: sibling) == Data("KEEP".utf8))
|
||||
}
|
||||
#expect(wipe(), "An absent metadata file must be harmless")
|
||||
}
|
||||
|
||||
private func makeWipe(
|
||||
_ store: Store,
|
||||
fileURL: URL? = nil,
|
||||
persistsToDisk: Bool = true,
|
||||
resolve: @escaping () -> URL?
|
||||
) -> () -> Bool {
|
||||
switch store {
|
||||
case .groups:
|
||||
let owner = GroupStore(keychain: MockKeychain(), persistsToDisk: persistsToDisk,
|
||||
fileURL: fileURL, resolveDefaultFileURL: resolve)
|
||||
return { owner.wipe() }
|
||||
case .board:
|
||||
let owner = BoardStore(persistsToDisk: persistsToDisk, fileURL: fileURL,
|
||||
resolveDefaultFileURL: resolve)
|
||||
return { owner.wipe() }
|
||||
case .courier:
|
||||
let owner = CourierStore(persistsToDisk: persistsToDisk, fileURL: fileURL,
|
||||
resolveDefaultFileURL: resolve)
|
||||
return { owner.wipe() }
|
||||
case .gossip:
|
||||
let owner = GossipMessageArchive(fileURL: fileURL, resolveDefaultFileURL: resolve)
|
||||
return { owner.wipe() }
|
||||
case .bridge:
|
||||
let owner = BridgeDropDedupStore(persistsToDisk: persistsToDisk, fileURL: fileURL,
|
||||
resolveDefaultFileURL: resolve)
|
||||
return { owner.wipe() }
|
||||
case .events:
|
||||
let owner = NostrProcessedEventStore(fileURL: fileURL, resolveDefaultFileURL: resolve)
|
||||
return { owner.wipe() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test(arguments: Store.allCases)
|
||||
func unresolvedLocationFailsAndSameOwnerRetries(_ store: Store) throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("metadata.json")
|
||||
let sibling = root.appendingPathComponent("keep.txt")
|
||||
let bytes = Data("SYNTHETIC_UNRESOLVED_METADATA".utf8)
|
||||
try bytes.write(to: file)
|
||||
try Data("KEEP".utf8).write(to: sibling)
|
||||
var resolvedURL: URL?
|
||||
var lookups = 0
|
||||
let wipe = makeWipe(store) { lookups += 1; return resolvedURL }
|
||||
#expect(!wipe(), "An unresolved persistent location must not count as deleted")
|
||||
#expect(try Data(contentsOf: file) == bytes)
|
||||
let failedLookups = lookups
|
||||
resolvedURL = file
|
||||
#expect(wipe(), "The same store must retry a failed location lookup")
|
||||
#expect(lookups > failedLookups)
|
||||
#expect(!fm.fileExists(atPath: file.path), "Recovered lookup must delete the retained metadata")
|
||||
#expect(try Data(contentsOf: sibling) == Data("KEEP".utf8))
|
||||
let recoveredLookups = lookups
|
||||
resolvedURL = nil
|
||||
#expect(wipe(), "A recovered, now absent location must remain harmless")
|
||||
#expect(lookups == recoveredLookups, "A recovered location must be retained")
|
||||
}
|
||||
|
||||
@Test(arguments: Store.allCases)
|
||||
func explicitLocationBypassesDefaultLookup(_ store: Store) throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("metadata.json")
|
||||
var lookups = 0
|
||||
let wipe = makeWipe(store, fileURL: file) { lookups += 1; return nil }
|
||||
try Data("SYNTHETIC_EXPLICIT_METADATA".utf8).write(to: file)
|
||||
#expect(wipe())
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
#expect(wipe(), "An explicitly located missing file must be harmless")
|
||||
#expect(lookups == 0, "Explicit locations must bypass default lookup")
|
||||
}
|
||||
|
||||
@Test(arguments: [Store.groups, .board, .courier, .bridge])
|
||||
func memoryOnlyStoreNeitherResolvesNorDeletes(_ store: Store) throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("keep.json")
|
||||
let bytes = Data("SYNTHETIC_UNOWNED_FILE".utf8)
|
||||
try bytes.write(to: file)
|
||||
var lookups = 0
|
||||
let wipe = makeWipe(store, fileURL: file, persistsToDisk: false) { lookups += 1; return file }
|
||||
#expect(wipe(), "An intentionally memory-only store has no persistent cleanup")
|
||||
#expect(fm.fileExists(atPath: file.path), "Memory-only cleanup must preserve supplied files")
|
||||
if fm.fileExists(atPath: file.path) { #expect(try Data(contentsOf: file) == bytes) }
|
||||
let wipeWithoutOverride = makeWipe(store, persistsToDisk: false) { lookups += 1; return file }
|
||||
#expect(wipeWithoutOverride())
|
||||
#expect(lookups == 0, "Memory-only stores must not resolve a persistent location")
|
||||
#expect(fm.fileExists(atPath: file.path))
|
||||
if fm.fileExists(atPath: file.path) { #expect(try Data(contentsOf: file) == bytes) }
|
||||
}
|
||||
|
||||
@Test
|
||||
func defaultGossipWipeReportsUnresolvedLocationAndRetries() throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("archive.json")
|
||||
let sibling = root.appendingPathComponent("keep.txt")
|
||||
let bytes = Data("SYNTHETIC_DEFAULT_ARCHIVE".utf8)
|
||||
try bytes.write(to: file)
|
||||
try Data("KEEP".utf8).write(to: sibling)
|
||||
#expect(!GossipMessageArchive.wipeDefault(resolveDefaultFileURL: { nil }),
|
||||
"Default archive cleanup must report failed lookup")
|
||||
#expect(try Data(contentsOf: file) == bytes)
|
||||
#expect(GossipMessageArchive.wipeDefault(resolveDefaultFileURL: { file }))
|
||||
#expect(!fm.fileExists(atPath: file.path))
|
||||
#expect(try Data(contentsOf: sibling) == Data("KEEP".utf8))
|
||||
#expect(GossipMessageArchive.wipeDefault(resolveDefaultFileURL: { file }))
|
||||
}
|
||||
|
||||
@Test(arguments: Store.allCases)
|
||||
func recoveredLocationSupportsSameOwnerPersistence(_ store: Store) throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("metadata.json")
|
||||
var resolvedURL: URL?
|
||||
let resolve = { resolvedURL }
|
||||
let wipe: () -> Bool
|
||||
let saveAndReload: () throws -> Void
|
||||
let now = Date(timeIntervalSince1970: 1_750_000_000)
|
||||
switch store {
|
||||
case .groups:
|
||||
let keychain = MockKeychain()
|
||||
let owner = GroupStore(keychain: keychain, resolveDefaultFileURL: resolve)
|
||||
wipe = { owner.wipe() }
|
||||
saveAndReload = {
|
||||
let member = GroupMember(fingerprint: Data(repeating: 1, count: 32).hexEncodedString(),
|
||||
signingKey: Data(repeating: 2, count: 32), nickname: "synthetic")
|
||||
let group = try #require(owner.createGroup(named: "synthetic", creator: member))
|
||||
let reloaded = GroupStore(keychain: keychain, fileURL: file)
|
||||
#expect(reloaded.group(withID: group.groupID) == group)
|
||||
}
|
||||
case .board:
|
||||
let owner = BoardStore(now: { now }, resolveDefaultFileURL: resolve)
|
||||
wipe = { owner.wipe() }
|
||||
saveAndReload = {
|
||||
let author = Curve25519.Signing.PrivateKey()
|
||||
let postID = Data(repeating: 3, count: 16)
|
||||
let created = UInt64(now.timeIntervalSince1970 * 1000)
|
||||
let expires = created + 3_600_000
|
||||
let key = author.publicKey.rawRepresentation
|
||||
let signingBytes = BoardPostPacket.signingBytes(
|
||||
postID: postID, geohash: "9q8yy", content: "synthetic", authorSigningKey: key,
|
||||
authorNickname: "synthetic", createdAt: created, expiresAt: expires, flags: 0)
|
||||
let post = BoardPostPacket(
|
||||
postID: postID, geohash: "9q8yy", content: "synthetic", authorSigningKey: key,
|
||||
authorNickname: "synthetic", createdAt: created, expiresAt: expires, flags: 0,
|
||||
signature: try author.signature(for: signingBytes))
|
||||
let wire = BoardWire.post(post)
|
||||
let packet = BitchatPacket(type: MessageType.boardPost.rawValue,
|
||||
senderID: Data(repeating: 4, count: 8), recipientID: nil,
|
||||
timestamp: created, payload: wire.encode(), signature: nil, ttl: 1)
|
||||
#expect(owner.ingest(wire, packet: packet) == .accepted)
|
||||
let reloaded = BoardStore(fileURL: file, now: { now })
|
||||
#expect(reloaded.posts(forGeohash: "9q8yy").map(\.postID) == [postID])
|
||||
}
|
||||
case .courier:
|
||||
let owner = CourierStore(now: { now }, resolveDefaultFileURL: resolve)
|
||||
wipe = { owner.wipe() }
|
||||
saveAndReload = {
|
||||
let recipient = Data(repeating: 5, count: 32)
|
||||
let envelope = CourierEnvelope(
|
||||
recipientTag: CourierEnvelope.recipientTag(
|
||||
noiseStaticKey: recipient, epochDay: CourierEnvelope.epochDay(for: now)),
|
||||
expiry: UInt64((now.timeIntervalSince1970 + 3600) * 1000),
|
||||
ciphertext: Data(repeating: 6, count: 96))
|
||||
#expect(owner.deposit(envelope, from: Data(repeating: 7, count: 32)))
|
||||
let reloaded = CourierStore(fileURL: file, now: { now })
|
||||
#expect(reloaded.takeEnvelopes(for: recipient) == [envelope])
|
||||
}
|
||||
case .gossip:
|
||||
let owner = GossipMessageArchive(resolveDefaultFileURL: resolve)
|
||||
wipe = { owner.wipe() }
|
||||
saveAndReload = {
|
||||
let packet = BitchatPacket(type: MessageType.message.rawValue,
|
||||
senderID: Data(repeating: 8, count: 8), recipientID: nil,
|
||||
timestamp: UInt64(now.timeIntervalSince1970 * 1000),
|
||||
payload: Data("SYNTHETIC_PUBLIC_PACKET".utf8), signature: nil, ttl: 1)
|
||||
let encoded = try #require(packet.toBinaryData(padding: false))
|
||||
owner.save([encoded])
|
||||
#expect(GossipMessageArchive(fileURL: file).load() == [encoded])
|
||||
}
|
||||
case .bridge:
|
||||
let owner = BridgeDropDedupStore(resolveDefaultFileURL: resolve)
|
||||
wipe = { owner.wipe() }
|
||||
saveAndReload = {
|
||||
owner.save(BridgeDropDedupStore.Snapshot(
|
||||
publishedDropKeys: ["synthetic-drop": now], seenDropEventIDs: ["synthetic-event": now]))
|
||||
let reloaded = BridgeDropDedupStore(fileURL: file).load()
|
||||
#expect(reloaded.publishedDropKeys == ["synthetic-drop": now])
|
||||
#expect(reloaded.seenDropEventIDs == ["synthetic-event": now])
|
||||
}
|
||||
case .events:
|
||||
let owner = NostrProcessedEventStore(resolveDefaultFileURL: resolve)
|
||||
wipe = { owner.wipe() }
|
||||
saveAndReload = {
|
||||
let eventID = String(repeating: "a", count: 64)
|
||||
owner.append([eventID], cap: 10)
|
||||
// load fences the serial append before a fresh owner reads the file.
|
||||
#expect(owner.load() == [eventID])
|
||||
#expect(NostrProcessedEventStore(fileURL: file).load() == [eventID])
|
||||
}
|
||||
}
|
||||
#expect(!wipe())
|
||||
resolvedURL = file
|
||||
#expect(wipe())
|
||||
resolvedURL = nil
|
||||
try saveAndReload()
|
||||
}
|
||||
|
||||
@Test(arguments: [false, true])
|
||||
func panicRetirementPreventsPersistenceAndOrdinaryStopPreservesIt(_ retire: Bool) throws {
|
||||
let fm = FileManager.default
|
||||
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: root) }
|
||||
let file = root.appendingPathComponent("archive.json")
|
||||
let archive = GossipMessageArchive(fileURL: file)
|
||||
let sender = PeerID(str: "1122334455667788")
|
||||
let packet = BitchatPacket(type: MessageType.message.rawValue,
|
||||
senderID: Data([0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]),
|
||||
recipientID: nil,
|
||||
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
|
||||
payload: Data("SYNTHETIC_PUBLIC_PACKET".utf8), signature: nil, ttl: 1)
|
||||
let encoded = try #require(packet.toBinaryData(padding: false))
|
||||
archive.save([encoded])
|
||||
let manager = GossipSyncManager(myPeerID: sender, requestSyncManager: RequestSyncManager(), archive: archive)
|
||||
#expect(manager._messageCount(for: sender) == 1)
|
||||
if retire { manager.stopForPanic() } else { manager.stop(); manager.start() }
|
||||
defer { manager.stop() }
|
||||
#expect(archive.wipe())
|
||||
manager.persistNow()
|
||||
_ = manager._messageCount(for: sender)
|
||||
#expect(fm.fileExists(atPath: file.path) == !retire,
|
||||
"A retired owner must not save; ordinary stop/start must retain persistence")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user