diff --git a/bitchat/Services/BLE/BLEFragmentCeilingPolicy.swift b/bitchat/Services/BLE/BLEFragmentCeilingPolicy.swift new file mode 100644 index 00000000..1d3ae256 --- /dev/null +++ b/bitchat/Services/BLE/BLEFragmentCeilingPolicy.swift @@ -0,0 +1,76 @@ +import BitFoundation +import Foundation + +/// Decides how many BLE fragments one outbound packet may be split into for a +/// particular recipient. +/// +/// Before an explicit ceiling existed on the wire, this was inferred from the +/// packet type: a directed `fileTransfer` was assumed to be the raw migration +/// fallback aimed at current Android (256 fragments), and anything else was +/// assumed to be aimed at a client with a reassembler as large as our own. +/// That proxy holds only while "implements the encrypted `0x20` path" and "has +/// a large reassembler" are the same population. A client that adopts `0x20` +/// with a smaller buffer breaks it in the silent direction: we would send +/// fragments the peer drops, and the transfer fails with no local signal. +/// +/// An authenticated peer that advertised `maxReassemblyFragments` has stated +/// its own limit inside the Noise session, so that number is used instead of +/// the proxy — in both directions. A peer asking for less than 256 is the case +/// the proxy gets dangerously wrong; a peer asking for more has told us the +/// migration cap does not apply to it. +/// +/// Deliberately free of BLE, Combine and app-model imports: the whole decision +/// is inputs to outputs, and every branch below is exercised directly in +/// `BLEFragmentCeilingPolicyTests`. +enum BLEFragmentCeilingPolicy { + /// Why a particular ceiling was chosen. Carried so the caller can log and + /// explain a rejection, and so tests assert the reasoning rather than just + /// the number — two sources can agree on a value by coincidence. + enum Source: Equatable { + /// The recipient advertised its own limit in authenticated peer state. + case negotiated + /// No advertisement; the recipient is assumed to be a released client + /// on the directed raw-file migration path. + case migrationFallbackProxy + /// No advertisement and no reason to assume a small reassembler. + case localCeiling + } + + struct Decision: Equatable { + let maxFragments: Int + let source: Source + + func admits(fragmentCount: Int) -> Bool { + fragmentCount <= maxFragments + } + } + + /// We never originate a transfer larger than we would be willing to + /// reassemble ourselves. A peer advertising a ceiling above our own is not + /// treated as an invitation to exceed it: the symmetric bound keeps one + /// side's configuration change from silently raising the other side's + /// memory exposure, and nothing today needs more. + static func decide( + packetType: UInt8, + isDirectedToPeer: Bool, + negotiatedCeiling: UInt16?, + localCeiling: Int = BLEFragmentAssemblyBuffer.maxReassemblyFragments, + migrationFallbackCeiling: Int = BLEOutboundFragmentPlanner.privateMediaV1MaxFragments + ) -> Decision { + if let negotiatedCeiling, negotiatedCeiling > 0 { + return Decision( + maxFragments: min(Int(negotiatedCeiling), localCeiling), + source: .negotiated + ) + } + + if isDirectedToPeer, packetType == MessageType.fileTransfer.rawValue { + return Decision( + maxFragments: min(migrationFallbackCeiling, localCeiling), + source: .migrationFallbackProxy + ) + } + + return Decision(maxFragments: localCeiling, source: .localCeiling) + } +} diff --git a/bitchatTests/Services/BLEFragmentCeilingPolicyTests.swift b/bitchatTests/Services/BLEFragmentCeilingPolicyTests.swift new file mode 100644 index 00000000..385e0239 --- /dev/null +++ b/bitchatTests/Services/BLEFragmentCeilingPolicyTests.swift @@ -0,0 +1,163 @@ +import BitFoundation +import Foundation +import Testing + +@testable import bitchat + +struct BLEFragmentCeilingPolicyTests { + private let fileTransfer = MessageType.fileTransfer.rawValue + private let noiseEncrypted = MessageType.noiseEncrypted.rawValue + + // MARK: - The proxy, unchanged where nothing was negotiated + + @Test + func directedFileTransferWithoutAnAdvertisementKeepsTheMigrationCap() { + let decision = BLEFragmentCeilingPolicy.decide( + packetType: fileTransfer, + isDirectedToPeer: true, + negotiatedCeiling: nil + ) + + #expect(decision.source == .migrationFallbackProxy) + #expect(decision.maxFragments == BLEOutboundFragmentPlanner.privateMediaV1MaxFragments) + #expect(decision.admits(fragmentCount: 256)) + #expect(!decision.admits(fragmentCount: 257)) + } + + @Test + func encryptedMediaWithoutAnAdvertisementKeepsTheFullLocalCeiling() { + let decision = BLEFragmentCeilingPolicy.decide( + packetType: noiseEncrypted, + isDirectedToPeer: true, + negotiatedCeiling: nil + ) + + #expect(decision.source == .localCeiling) + #expect(decision.maxFragments == BLEFragmentAssemblyBuffer.maxReassemblyFragments) + // The regression the 256 cap caused for iOS→iOS photos in the + // ~120–512 KiB range: those plans must still be admitted. + #expect(decision.admits(fragmentCount: 900)) + } + + @Test + func broadcastFileTransferIsNotTreatedAsTheDirectedMigrationPath() { + let decision = BLEFragmentCeilingPolicy.decide( + packetType: fileTransfer, + isDirectedToPeer: false, + negotiatedCeiling: nil + ) + + #expect(decision.source == .localCeiling) + #expect(decision.maxFragments == BLEFragmentAssemblyBuffer.maxReassemblyFragments) + } + + // MARK: - An advertisement replaces the proxy + + @Test + func anAdvertisedCeilingBelowTheMigrationCapIsHonoured() { + // The case the type proxy gets wrong in the silent direction: a client + // on the encrypted path whose reassembler is smaller than ours. Without + // the advertisement we would happily plan 900 fragments it will drop. + let decision = BLEFragmentCeilingPolicy.decide( + packetType: noiseEncrypted, + isDirectedToPeer: true, + negotiatedCeiling: 128 + ) + + #expect(decision.source == .negotiated) + #expect(decision.maxFragments == 128) + #expect(decision.admits(fragmentCount: 128)) + #expect(!decision.admits(fragmentCount: 129)) + } + + @Test + func anAdvertisedCeilingAboveTheMigrationCapLiftsItForThatPeer() { + // A peer that speaks 0x21 has told us the deployed-Android assumption + // behind the 256 cap does not describe it. + let decision = BLEFragmentCeilingPolicy.decide( + packetType: fileTransfer, + isDirectedToPeer: true, + negotiatedCeiling: 1024 + ) + + #expect(decision.source == .negotiated) + #expect(decision.maxFragments == 1024) + #expect(decision.admits(fragmentCount: 1024)) + } + + @Test + func anAdvertisedCeilingIsClampedToWhatWeWouldReassembleOurselves() { + let local = BLEFragmentAssemblyBuffer.maxReassemblyFragments + let decision = BLEFragmentCeilingPolicy.decide( + packetType: noiseEncrypted, + isDirectedToPeer: true, + negotiatedCeiling: UInt16.max + ) + + #expect(decision.source == .negotiated) + #expect(decision.maxFragments == local) + #expect(!decision.admits(fragmentCount: local + 1)) + } + + @Test + func aZeroAdvertisementFallsBackRatherThanBlockingEveryTransfer() { + // The decoder rejects a zero on the wire, so this can only arrive from + // a future caller passing one through. Treat it as absent: refusing + // every fragment to that peer would be a worse failure than the proxy. + let decision = BLEFragmentCeilingPolicy.decide( + packetType: fileTransfer, + isDirectedToPeer: true, + negotiatedCeiling: 0 + ) + + #expect(decision.source == .migrationFallbackProxy) + #expect(decision.maxFragments == BLEOutboundFragmentPlanner.privateMediaV1MaxFragments) + } + + // MARK: - Invariants across the whole input space + + @Test + func noDecisionEverExceedsTheLocalCeiling() { + let local = BLEFragmentAssemblyBuffer.maxReassemblyFragments + let ceilings: [UInt16?] = [nil, 1, 255, 256, 257, 9_999, 10_000, 10_001, UInt16.max] + let types: [UInt8] = [ + fileTransfer, + noiseEncrypted, + MessageType.message.rawValue, + MessageType.announce.rawValue, + ] + + for ceiling in ceilings { + for type in types { + for directed in [true, false] { + let decision = BLEFragmentCeilingPolicy.decide( + packetType: type, + isDirectedToPeer: directed, + negotiatedCeiling: ceiling + ) + #expect(decision.maxFragments >= 1) + #expect(decision.maxFragments <= local) + } + } + } + } + + @Test + func advertisingOurOwnCeilingRoundTripsThroughTheWireField() throws { + // The advertised number has to fit the 2-byte TLV, or we would ship a + // truncated ceiling that reads as a much smaller buffer. + let local = BLEFragmentAssemblyBuffer.maxReassemblyFragments + #expect(local > 0) + #expect(local <= Int(UInt16.max)) + + let packet = AuthenticatedPeerStatePacket( + capabilities: [.privateMedia], + signingPublicKey: Data(repeating: 0x11, count: 32), + maxReassemblyFragments: UInt16(local) + ) + let encoded = try #require(packet.encode()) + let decoded = try #require(AuthenticatedPeerStatePacket.decode(from: encoded)) + let advertised = try #require(decoded.maxReassemblyFragments) + #expect(Int(advertised) == local) + } +}