Include metadata cleanup in panic wipe completion

The affected metadata stores did not report file-removal failures to the
panic controller. Processed-event cleanup could return before its queued
deletion finished.

- Include deletion results from the six metadata stores in panic completion.
- Keep recovery pending and services suspended after a required deletion
  fails, while continuing the remaining cleanup attempts.
- Wait for queued processed-event work and deletion before returning.
- Finish queued gossip saves before deleting the archive, and prevent
  further saves from the retired manager.
- Add regression tests for failure, retry, missing files, preserving
  unrelated files and cleanup completion.
This commit is contained in:
heyaim 2026-10-30 15:33:42 -05:00
parent 04995f68e4
commit c97cb0c2f9
16 changed files with 451 additions and 47 deletions

View File

@ -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.
@ -2929,12 +2929,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)

View File

@ -147,18 +147,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 = PanicFileDeletion.remove(fileURL)
publishSnapshotLocked()
return removed
}
DispatchQueue.main.async { [weak self] in
self?.didWipe.send()
}
return removed
}
// MARK: - Internals (call only on `queue`)

View File

@ -416,15 +416,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 = PanicFileDeletion.remove(fileURL)
publishCountLocked()
return removed
}
return removed
}
/// Retries a protected-data read and merges any envelopes accepted while

View File

@ -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

View File

@ -118,9 +118,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 PanicFileDeletion.remove(fileURL)
}
private static func defaultFileURL() -> URL? {

View File

@ -130,14 +130,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 PanicFileDeletion.remove(fileURL)
}
// MARK: - Internals

View File

@ -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

View File

@ -24,10 +24,15 @@ final class NostrProcessedEventStore {
private let fileURL: 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) {
/// 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)
) {
self.fileURL = fileURL ?? Self.defaultFileURL()
self.ioQueue = ioQueue
}
/// Processed event IDs, oldest first (insertion order).
@ -55,11 +60,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) }
}
private func loadLocked() -> [String] {

View File

@ -0,0 +1,27 @@
//
// 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 backing files are already erased; other removal errors keep panic pending.
enum PanicFileDeletion {
static func remove(_ fileURL: URL?) -> Bool {
guard let fileURL else { return true }
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
}
}
}

View File

@ -0,0 +1,17 @@
//
// 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
}

View File

@ -56,13 +56,14 @@ final class GossipMessageArchive {
}
}
func wipe() {
guard let fileURL else { return }
try? FileManager.default.removeItem(at: fileURL)
@discardableResult
func wipe() -> Bool {
return PanicFileDeletion.remove(fileURL)
}
/// Panic-wipe hook for callers that don't hold the live instance.
static func wipeDefault() {
@discardableResult
static func wipeDefault() -> Bool {
GossipMessageArchive().wipe()
}

View File

@ -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)

View File

@ -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()
var metadataWipeCompleted = (panicMetadataWipeOperations?.wipeCourier() ?? CourierStore.shared.wipe())
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeBridge() ?? BridgeCourierService.shared.wipe()) && metadataWipeCompleted
messageRouter.wipeOutbox()
GossipMessageArchive.wipeDefault()
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()
// 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(

View File

@ -20,6 +20,7 @@ private func makeTestableViewModel(
panicMediaWipe: (() throws -> Void)? = nil,
panicRecoveryOperations: PanicRecoveryOperations? = nil,
panicNetworkLifecycle: PanicNetworkLifecycle = .noop,
panicMetadataWipeOperations: PanicMetadataWipeOperations? = nil,
locationManager: LocationChannelManager = .shared
) -> (viewModel: ChatViewModel, transport: MockTransport) {
let keychain = injectedKeychain ?? MockKeychain()
@ -36,6 +37,7 @@ private func makeTestableViewModel(
locationManager: locationManager,
panicMediaWipe: panicMediaWipe,
panicRecoveryOperations: panicRecoveryOperations,
panicMetadataWipeOperations: panicMetadataWipeOperations,
panicNetworkLifecycle: panicNetworkLifecycle
)
@ -2150,6 +2152,125 @@ 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) }
)
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 @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) }
)
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

View File

@ -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)
}
}

View File

@ -0,0 +1,86 @@
import BitFoundation
import Foundation
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")
}
@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")
}
}