From 338304902f3f82975df4a8569a03bfd5b9e85d1b Mon Sep 17 00:00:00 2001 From: Jozef Koval Date: Wed, 30 Sep 2026 17:29:14 +0200 Subject: [PATCH] Keep parked Noise payloads when the proof watchdog fires with no session The capability-proof watchdog drains the peer's parked Noise payloads whenever the timeout-restore deferral is off, whether or not a session exists. The drain encrypts under the current session and never re-queues, so with the handshake still in flight past the 5 s deadline every encryption fails: media with a transfer ID gets a visible rejection, and a delivery ack, read receipt, verify, vouch or group payload is dropped with a log line. No attacker is needed. Sending a photo to a private-media peer with no session arms the watchdog and starts a handshake; anything parked behind that handshake is lost if it outlives 5 s, which is ordinary over a multi-hop mesh. noteNoiseSessionCleared re-arms the watchdog as a session goes away, so a slow reconnect with a pending media decision takes the same path. Of the drain's four production callers the watchdog was the only one without a session precondition; the timeout-restore case was already held back by deferredOutbound. It now drains only under an established session and otherwise leaves the payloads for the drain that runs when the session authenticates. The policy resolution is unchanged. proofTimeoutBeforeHandshakeLeavesParkedAckForTheSession drives it through the public path -- resolvePrivateMediaSendPolicy, then sendDeliveryAck -- and forces the watchdog as the neighbouring proof-timeout tests do. Without the guard it fails on its last expectation: the parked count goes from 1 to 0. It needs one DEBUG-only count hook, because _test_privateMediaTransferState only sees payloads that carry a transfer ID. Encryption fails closed throughout; nothing is sent unencrypted. The drain's error path still drops what it cannot encrypt; whether it should re-queue payloads without a transfer ID is left for review rather than changed here. Full SwiftPM suite green: 2068 tests in 222 suites. --- .../Services/BLE/BLENoiseSessionQueues.swift | 6 +++ bitchat/Services/BLE/BLEService.swift | 15 ++++++- .../EndToEnd/PrivateMediaEndToEndTests.swift | 44 +++++++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/bitchat/Services/BLE/BLENoiseSessionQueues.swift b/bitchat/Services/BLE/BLENoiseSessionQueues.swift index 301e6bce..fc0f8923 100644 --- a/bitchat/Services/BLE/BLENoiseSessionQueues.swift +++ b/bitchat/Services/BLE/BLENoiseSessionQueues.swift @@ -59,6 +59,12 @@ struct BLENoiseSessionQueues { } } + #if DEBUG + func typedPayloadCount(for peerID: PeerID) -> Int { + typedPayloadsByPeerID[peerID]?.count ?? 0 + } + #endif + @discardableResult mutating func removeTypedPayload(transferId: String) -> Bool { for peerID in Array(typedPayloadsByPeerID.keys) { diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index edd630e9..1e3a0a4f 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -1333,7 +1333,12 @@ final class BLEService: NSObject { ) guard expiration.expired else { return } let policy = privateMediaSendPolicy(to: peerID) - if !expiration.deferredOutbound { + // The drain encrypts under the current session and never re-queues. + // With the handshake still in flight past this deadline, every + // encryption would fail and each parked ack, receipt or payload would + // be dropped; leave them for the handshake-completion drain instead. + if !expiration.deferredOutbound, + noiseService.hasEstablishedSession(with: peerID) { sendPendingNoisePayloadsAfterHandshake(for: peerID) } completePrivateMediaPolicyResolution(expiration.completions, with: policy) @@ -3318,6 +3323,14 @@ extension BLEService { ) } + /// Typed payloads parked for `peerID` behind a handshake, with or + /// without a transfer ID (acks and receipts carry none). + func _test_pendingTypedPayloadCount(for peerID: PeerID) -> Int { + onEngine { + pendingNoiseSessionQueues.typedPayloadCount(for: peerID) + } + } + func _test_privateMediaAdmissionEntryCount() -> Int { privateMediaTransferAdmissions.count } diff --git a/bitchatTests/EndToEnd/PrivateMediaEndToEndTests.swift b/bitchatTests/EndToEnd/PrivateMediaEndToEndTests.swift index 30f071f5..54de4a23 100644 --- a/bitchatTests/EndToEnd/PrivateMediaEndToEndTests.swift +++ b/bitchatTests/EndToEnd/PrivateMediaEndToEndTests.swift @@ -862,6 +862,50 @@ struct PrivateMediaEndToEndTests { bob._test_onOutboundPacket = nil } + @Test + func proofTimeoutBeforeHandshakeLeavesParkedAckForTheSession() async throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("private-media-proof-timeout-parked-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let alice = makeService(baseDirectory: root.appendingPathComponent("alice", isDirectory: true)) + let bob = makeService(baseDirectory: root.appendingPathComponent("bob", isDirectory: true)) + alice._test_seedConnectedPeer( + bob.myPeerID, + nickname: "Bob", + capabilities: .privateMedia, + noisePublicKey: bob.noiseStaticPublicKeyData() + ) + + // No session yet: resolving the media policy arms the 5 s proof + // watchdog and starts a handshake, which on a multi-hop mesh can + // take longer than that. + let recorder = PrivateMediaPolicyRecorder() + alice.resolvePrivateMediaSendPolicy(to: bob.myPeerID) { recorder.record($0) } + let registered = await TestHelpers.waitUntil( + { alice._test_hasPendingPrivateMediaPolicyResolution(for: bob.myPeerID) }, + timeout: TestConstants.longTimeout + ) + #expect(registered) + #expect(!alice.canDeliverSecurely(to: bob.myPeerID)) + + // An ack owed to Bob parks behind that same handshake. + alice.sendDeliveryAck(for: "earlier-message-from-bob", to: bob.myPeerID) + await alice._test_drainNoiseMessagePipeline() + #expect(alice._test_pendingTypedPayloadCount(for: bob.myPeerID) == 1) + + alice._test_forcePrivateMediaProofTimeout(for: bob.myPeerID) + let resolved = await TestHelpers.waitUntil( + { recorder.snapshot() == .legacyRequiresConsent }, + timeout: TestConstants.longTimeout + ) + #expect(resolved) + + // The watchdog settles the media policy. It must not consume the ack: + // with no session the ack cannot be encrypted, and a drained payload + // is never re-queued, so it would be lost for good. + #expect(alice._test_pendingTypedPayloadCount(for: bob.myPeerID) == 1) + } + @Test func authenticatedFingerprintMismatchCannotPoisonCapabilityPin() async throws { let root = FileManager.default.temporaryDirectory