mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-29 08:29:22 +00:00
Harden BLE mesh DoS defenses and preserve 6-hour gossip history across stale timeouts (#1888)
This commit is contained in:
14 files changed
+491
-98
No files matched your search
@@ -58,10 +58,12 @@ struct BLEFragmentAssemblyBuffer {
|
||||
case stored(header: BLEFragmentHeader, started: Bool)
|
||||
case complete(header: BLEFragmentHeader, reassembledData: Data, started: Bool)
|
||||
case oversized(header: BLEFragmentHeader, projectedSize: Int, limit: Int, started: Bool)
|
||||
case mismatched(header: BLEFragmentHeader, expectedTotal: Int, expectedOriginalType: UInt8)
|
||||
}
|
||||
|
||||
private struct Metadata {
|
||||
let total: Int
|
||||
let originalType: UInt8
|
||||
let timestamp: Date
|
||||
let isBroadcast: Bool
|
||||
var lastFragmentAt: Date
|
||||
@@ -101,10 +103,30 @@ struct BLEFragmentAssemblyBuffer {
|
||||
maxInFlightAssemblies: Int,
|
||||
now: Date = Date()
|
||||
) -> AppendResult {
|
||||
let started = startAssemblyIfNeeded(for: header, maxInFlightAssemblies: maxInFlightAssemblies, now: now)
|
||||
if let existingMetadata = metadataByKey[header.key] {
|
||||
guard header.total == existingMetadata.total,
|
||||
header.originalType == existingMetadata.originalType,
|
||||
header.isBroadcastFragment == existingMetadata.isBroadcast,
|
||||
header.index >= 0,
|
||||
header.index < existingMetadata.total else {
|
||||
// Reject conflicting header metadata without evicting the
|
||||
// in-flight assembly so a spoofed fragment cannot force early
|
||||
// completion or downgrade the assembly size limit.
|
||||
return .mismatched(
|
||||
header: header,
|
||||
expectedTotal: existingMetadata.total,
|
||||
expectedOriginalType: existingMetadata.originalType
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
let currentSize = metadataByKey[header.key]?.totalBytes ?? 0
|
||||
let limit = Self.assemblyLimit(for: header.originalType)
|
||||
let started = startAssemblyIfNeeded(for: header, maxInFlightAssemblies: maxInFlightAssemblies, now: now)
|
||||
guard let metadata = metadataByKey[header.key] else {
|
||||
return .stored(header: header, started: started)
|
||||
}
|
||||
|
||||
let currentSize = metadata.totalBytes
|
||||
let limit = Self.assemblyLimit(for: metadata.originalType)
|
||||
// A re-delivered index replaces what it held rather than adding to
|
||||
// it: fragments bypass dedup and sync re-serves held indexes, so a
|
||||
// duplicate near the cap must not tip a valid assembly over it.
|
||||
@@ -129,16 +151,17 @@ struct BLEFragmentAssemblyBuffer {
|
||||
}
|
||||
|
||||
guard let fragments = fragmentsByKey[header.key],
|
||||
fragments.count == header.total else {
|
||||
fragments.count == metadata.total else {
|
||||
return .stored(header: header, started: started)
|
||||
}
|
||||
|
||||
var reassembled = Data()
|
||||
reassembled.reserveCapacity(projectedSize)
|
||||
for index in 0..<header.total {
|
||||
if let fragment = fragments[index] {
|
||||
reassembled.append(fragment)
|
||||
for index in 0..<metadata.total {
|
||||
guard let fragment = fragments[index] else {
|
||||
return .stored(header: header, started: started)
|
||||
}
|
||||
reassembled.append(fragment)
|
||||
}
|
||||
|
||||
fragmentsByKey.removeValue(forKey: header.key)
|
||||
@@ -163,6 +186,7 @@ struct BLEFragmentAssemblyBuffer {
|
||||
fragmentsByKey[header.key] = [:]
|
||||
metadataByKey[header.key] = Metadata(
|
||||
total: header.total,
|
||||
originalType: header.originalType,
|
||||
timestamp: now,
|
||||
isBroadcast: header.isBroadcastFragment,
|
||||
lastFragmentAt: now
|
||||
|
||||
@@ -31,9 +31,10 @@ final class BLEFragmentHandler {
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
func handle(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
@discardableResult
|
||||
func handle(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
let env = environment
|
||||
guard let header = BLEFragmentHeader(packet: packet) else { return }
|
||||
guard let header = BLEFragmentHeader(packet: packet) else { return false }
|
||||
|
||||
// Sync replay legitimately hands us our own fragments back (the RSR
|
||||
// ttl=0 restore path): after a relaunch the fragment store starts
|
||||
@@ -45,9 +46,12 @@ final class BLEFragmentHandler {
|
||||
if header.isBroadcastFragment {
|
||||
env.trackPacketSeen(packet)
|
||||
}
|
||||
return
|
||||
return true
|
||||
}
|
||||
|
||||
// Keep broadcast sync tracking and mesh relay independent of local
|
||||
// first-wins storage rejection so an injected conflicting fragment
|
||||
// cannot suppress honest downstream copies or REQUEST_SYNC recovery.
|
||||
if header.isBroadcastFragment {
|
||||
env.trackPacketSeen(packet)
|
||||
}
|
||||
@@ -56,29 +60,35 @@ final class BLEFragmentHandler {
|
||||
|
||||
logFragmentAssemblyResult(assemblyResult)
|
||||
|
||||
guard case let .complete(completedHeader, reassembled, _) = assemblyResult else { return }
|
||||
switch assemblyResult {
|
||||
case .oversized, .mismatched, .stored:
|
||||
return true
|
||||
case let .complete(completedHeader, reassembled, _):
|
||||
// Decode the original packet bytes we reassembled, so flags/compression are preserved
|
||||
if var originalPacket = BinaryProtocol.decode(reassembled) {
|
||||
|
||||
// Decode the original packet bytes we reassembled, so flags/compression are preserved
|
||||
if var originalPacket = BinaryProtocol.decode(reassembled) {
|
||||
|
||||
// Reassembled packet validation. Both platforms' fragmenters copy
|
||||
// the inner type into every fragment, and the assembly was sized
|
||||
// for that claim, so a packet of any other type is forged.
|
||||
let innerSender = PeerID(hexData: originalPacket.senderID)
|
||||
if originalPacket.type != completedHeader.originalType {
|
||||
SecureLogger.warning(
|
||||
"🚫 Reassembled packet id=\(completedHeader.idLogString) is type \(originalPacket.type), fragments claimed \(completedHeader.originalType)",
|
||||
category: .security
|
||||
)
|
||||
} else if !env.isAcceptedIngressPayload(originalPacket, innerSender) {
|
||||
// Cleanup below
|
||||
// Reassembled packet validation. Both platforms' fragmenters copy
|
||||
// the inner type into every fragment, and the assembly was sized
|
||||
// for that claim, so a packet of any other type is forged.
|
||||
let innerSender = PeerID(hexData: originalPacket.senderID)
|
||||
if originalPacket.type != completedHeader.originalType {
|
||||
SecureLogger.warning(
|
||||
"🚫 Reassembled packet id=\(completedHeader.idLogString) is type \(originalPacket.type), fragments claimed \(completedHeader.originalType)",
|
||||
category: .security
|
||||
)
|
||||
return false
|
||||
} else if !env.isAcceptedIngressPayload(originalPacket, innerSender) {
|
||||
return false
|
||||
} else {
|
||||
SecureLogger.debug("✅ Reassembled packet id=\(completedHeader.idLogString) type=\(originalPacket.type) bytes=\(reassembled.count)", category: .session)
|
||||
originalPacket.ttl = 0
|
||||
env.processReassembledPacket(originalPacket, peerID)
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
SecureLogger.debug("✅ Reassembled packet id=\(completedHeader.idLogString) type=\(originalPacket.type) bytes=\(reassembled.count)", category: .session)
|
||||
originalPacket.ttl = 0
|
||||
env.processReassembledPacket(originalPacket, peerID)
|
||||
SecureLogger.error("❌ Failed to decode reassembled packet (type=\(completedHeader.originalType), total=\(completedHeader.total))", category: .session)
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
SecureLogger.error("❌ Failed to decode reassembled packet (type=\(completedHeader.originalType), total=\(completedHeader.total))", category: .session)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +114,12 @@ final class BLEFragmentHandler {
|
||||
"🚫 Fragment assembly exceeds size limit (\(projectedSize) bytes > \(limit)), evicting. Type=\(header.originalType) Index=\(header.index)/\(header.total)",
|
||||
category: .security
|
||||
)
|
||||
|
||||
case let .mismatched(header, expectedTotal, expectedOriginalType):
|
||||
SecureLogger.warning(
|
||||
"🚫 Dropping mismatched fragment for id=\(header.idLogString): got total=\(header.total) type=\(header.originalType), expected total=\(expectedTotal) type=\(expectedOriginalType)",
|
||||
category: .security
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ struct BLEInboundWriteAppendMetadata: Equatable {
|
||||
}
|
||||
|
||||
struct BLEInboundWriteBuffer {
|
||||
static let defaultMaxTrackedCentrals = 64
|
||||
|
||||
enum AppendResult {
|
||||
case decoded(packet: BitchatPacket, metadata: BLEInboundWriteAppendMetadata)
|
||||
case waiting(metadata: BLEInboundWriteAppendMetadata)
|
||||
@@ -21,19 +23,23 @@ struct BLEInboundWriteBuffer {
|
||||
}
|
||||
|
||||
private var buffersByCentralID: [String: Data] = [:]
|
||||
private var centralOrder: [String] = []
|
||||
|
||||
mutating func removeAll() {
|
||||
buffersByCentralID.removeAll()
|
||||
centralOrder.removeAll()
|
||||
}
|
||||
|
||||
mutating func remove(for centralID: String) {
|
||||
buffersByCentralID.removeValue(forKey: centralID)
|
||||
centralOrder.removeAll { $0 == centralID }
|
||||
}
|
||||
|
||||
mutating func append(
|
||||
chunks: [BLEInboundWriteChunk],
|
||||
for centralID: String,
|
||||
capBytes: Int
|
||||
capBytes: Int,
|
||||
maxTrackedCentrals: Int = BLEInboundWriteBuffer.defaultMaxTrackedCentrals
|
||||
) -> AppendResult {
|
||||
var combined = buffersByCentralID[centralID] ?? Data()
|
||||
var appendedBytes = 0
|
||||
@@ -42,7 +48,21 @@ struct BLEInboundWriteBuffer {
|
||||
|
||||
for chunk in chunks where !chunk.data.isEmpty {
|
||||
offsets.append(chunk.offset)
|
||||
let end = chunk.offset + chunk.data.count
|
||||
let (end, overflow) = chunk.offset.addingReportingOverflow(chunk.data.count)
|
||||
|
||||
guard chunk.offset >= 0, !overflow, end <= capBytes else {
|
||||
remove(for: centralID)
|
||||
let reportedAccumulated = (chunk.offset < 0 || overflow)
|
||||
? max(combined.count, capBytes + 1)
|
||||
: max(combined.count, end)
|
||||
let metadata = BLEInboundWriteAppendMetadata(
|
||||
accumulatedBytes: reportedAccumulated,
|
||||
appendedBytes: appendedBytes + chunk.data.count,
|
||||
offsets: offsets,
|
||||
packetType: combined.count >= 2 ? combined[1] : (chunk.offset == 0 && chunk.data.count >= 2 ? chunk.data[1] : nil)
|
||||
)
|
||||
return .oversized(metadata: metadata)
|
||||
}
|
||||
|
||||
if chunk.offset == combined.count {
|
||||
if combined.isEmpty {
|
||||
@@ -67,15 +87,23 @@ struct BLEInboundWriteBuffer {
|
||||
)
|
||||
|
||||
if Self.hasCompleteFrame(combined), let packet = BinaryProtocol.decode(combined) {
|
||||
buffersByCentralID.removeValue(forKey: centralID)
|
||||
remove(for: centralID)
|
||||
return .decoded(packet: packet, metadata: metadata)
|
||||
}
|
||||
|
||||
guard combined.count <= capBytes else {
|
||||
buffersByCentralID.removeValue(forKey: centralID)
|
||||
remove(for: centralID)
|
||||
return .oversized(metadata: metadata)
|
||||
}
|
||||
|
||||
if buffersByCentralID[centralID] == nil {
|
||||
let cap = max(1, maxTrackedCentrals)
|
||||
while buffersByCentralID.count >= cap, !centralOrder.isEmpty {
|
||||
let oldest = centralOrder.removeFirst()
|
||||
buffersByCentralID.removeValue(forKey: oldest)
|
||||
}
|
||||
centralOrder.append(centralID)
|
||||
}
|
||||
buffersByCentralID[centralID] = combined
|
||||
return .waiting(metadata: metadata)
|
||||
}
|
||||
|
||||
@@ -48,7 +48,8 @@ final class BLEPublicMessageHandler {
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
func handle(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
@discardableResult
|
||||
func handle(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
let env = environment
|
||||
let now = env.now()
|
||||
let messageDecision = BLEPublicMessagePolicy.evaluate(
|
||||
@@ -63,10 +64,10 @@ final class BLEPublicMessageHandler {
|
||||
case .accept(let acceptance):
|
||||
messagePolicy = acceptance
|
||||
case .reject(.selfEcho):
|
||||
return
|
||||
return false
|
||||
case .reject(.staleBroadcast(let ageSeconds)):
|
||||
SecureLogger.debug("⏰ Ignoring stale broadcast message from \(peerID.id.prefix(8))… (age: \(ageSeconds)s)", category: .session)
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
// Snapshot peers to avoid concurrent mutation while iterating during nickname collision checks.
|
||||
@@ -92,7 +93,7 @@ final class BLEPublicMessageHandler {
|
||||
let signedDisplayName = (isSelf || verifiedViaRegistry) ? nil : env.signedSenderDisplayName(packet, peerID)
|
||||
guard isSelf || verifiedViaRegistry || signedDisplayName != nil else {
|
||||
SecureLogger.warning("🚫 Dropping public message with missing/invalid signature for claimed sender \(peerID.id.prefix(8))…", category: .security)
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
// Authenticity is established; prefer the registry's collision-resolved
|
||||
@@ -105,7 +106,7 @@ final class BLEPublicMessageHandler {
|
||||
allowConnectedUnverified: false
|
||||
) ?? signedDisplayName else {
|
||||
SecureLogger.warning("🚫 Dropping public message from unknown peer \(peerID.id.prefix(8))…", category: .security)
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
if messagePolicy.shouldTrackForSync {
|
||||
@@ -119,12 +120,12 @@ final class BLEPublicMessageHandler {
|
||||
// so nothing larger than a v1 frame is delivered.
|
||||
guard packet.payload.count <= Self.maxDeliveredPayloadBytes else {
|
||||
SecureLogger.warning("🚫 Dropping \(packet.payload.count)-byte public message from \(peerID.id.prefix(8))…: larger than a v1 frame", category: .security)
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
guard let content = String(data: packet.payload, encoding: .utf8) else {
|
||||
SecureLogger.error("❌ Failed to decode message payload as UTF-8", category: .session)
|
||||
return
|
||||
return false
|
||||
}
|
||||
// Determine if we have a direct link to the sender
|
||||
let directLink = env.linkState(peerID)
|
||||
@@ -147,5 +148,6 @@ final class BLEPublicMessageHandler {
|
||||
)
|
||||
}
|
||||
env.deliverPublicMessage(peerID, senderNickname, content, ts, messageID)
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -5028,20 +5028,21 @@ extension BLEService {
|
||||
/// freshness or poison attribution. Only after that does the packet enter
|
||||
/// our own gossip store, so we never help spread a bundle we couldn't
|
||||
/// attribute.
|
||||
private func handlePrekeyBundle(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
@discardableResult
|
||||
private func handlePrekeyBundle(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
guard let bundle = PrekeyBundle.decode(packet.payload) else {
|
||||
SecureLogger.debug("🔑 Ignoring malformed prekey bundle from \(peerID.id.prefix(8))…", category: .security)
|
||||
return
|
||||
return false
|
||||
}
|
||||
// Our own bundle is tracked at send time; a copy echoing back adds nothing.
|
||||
guard bundle.noiseStaticPublicKey != noiseService.getStaticPublicKeyData() else { return }
|
||||
guard bundle.noiseStaticPublicKey != noiseService.getStaticPublicKeyData() else { return false }
|
||||
let owner = PeerID(publicKey: bundle.noiseStaticPublicKey)
|
||||
// The owner's genuine bundle (direct or relayed) always carries the
|
||||
// owner's senderID + outer signature; gossip resends preserve both. A
|
||||
// packet whose senderID isn't the owner can't be authenticated here.
|
||||
guard PeerID(hexData: packet.senderID) == owner else {
|
||||
SecureLogger.debug("🔑 Ignoring prekey bundle whose sender ≠ owner \(owner.id.prefix(8))…", category: .security)
|
||||
return
|
||||
return false
|
||||
}
|
||||
// Look up the announce-bound signing key and stash-if-unbound in ONE
|
||||
// barrier: the receive queue is concurrent, so this bundle can race
|
||||
@@ -5069,23 +5070,25 @@ extension BLEService {
|
||||
}
|
||||
guard let signingKey else {
|
||||
SecureLogger.debug("🔑 Deferring prekey bundle without a bound signing key (owner \(owner.id.prefix(8))…)", category: .security)
|
||||
return
|
||||
return false
|
||||
}
|
||||
ingestVerifiedPrekeyBundle(bundle, packet: packet, owner: owner, signingKey: signingKey)
|
||||
return ingestVerifiedPrekeyBundle(bundle, packet: packet, owner: owner, signingKey: signingKey)
|
||||
}
|
||||
|
||||
/// Verify a bundle's inner + outer signatures against the owner's bound
|
||||
/// signing key and, on success, cache it and let it enter our gossip store.
|
||||
private func ingestVerifiedPrekeyBundle(_ bundle: PrekeyBundle, packet: BitchatPacket, owner: PeerID, signingKey: Data) {
|
||||
@discardableResult
|
||||
private func ingestVerifiedPrekeyBundle(_ bundle: PrekeyBundle, packet: BitchatPacket, owner: PeerID, signingKey: Data) -> Bool {
|
||||
guard noiseService.verifyPrekeyBundleSignature(bundle, signingPublicKey: signingKey),
|
||||
noiseService.verifyPacketSignature(packet, publicKey: signingKey) else {
|
||||
SecureLogger.debug("🔑 Ignoring prekey bundle without verifiable signature (owner \(owner.id.prefix(8))…)", category: .security)
|
||||
return
|
||||
return false
|
||||
}
|
||||
if prekeyBundleStore.ingest(bundle) {
|
||||
SecureLogger.debug("🔑 Cached prekey bundle for \(owner.id.prefix(8))… (\(bundle.prekeys.count) prekeys)", category: .security)
|
||||
}
|
||||
gossipSyncManager?.onPublicPacketSeen(packet)
|
||||
return true
|
||||
}
|
||||
|
||||
/// Re-attempt any prekey bundle that arrived before this owner's announce
|
||||
@@ -5863,12 +5866,12 @@ extension BLEService {
|
||||
}
|
||||
}
|
||||
|
||||
private func handleFragment(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
private func handleFragment(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
if DispatchQueue.getSpecific(key: messageQueueKey) != nil {
|
||||
fragmentHandler.handle(packet, from: peerID)
|
||||
return fragmentHandler.handle(packet, from: peerID)
|
||||
} else {
|
||||
messageQueue.async { [weak self] in
|
||||
self?.fragmentHandler.handle(packet, from: peerID)
|
||||
return onEngine {
|
||||
fragmentHandler.handle(packet, from: peerID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6186,7 +6189,7 @@ extension BLEService {
|
||||
// Process by type
|
||||
switch context.messageType {
|
||||
case .announce:
|
||||
handleAnnounce(packet, from: senderID)
|
||||
guard handleAnnounce(packet, from: senderID) else { return }
|
||||
|
||||
case .announceV2:
|
||||
// Parsed and ignored on purpose. The wire format and derivations are
|
||||
@@ -6198,7 +6201,7 @@ extension BLEService {
|
||||
break
|
||||
|
||||
case .message:
|
||||
handleMessage(packet, from: senderID)
|
||||
guard handleMessage(packet, from: senderID) else { return }
|
||||
|
||||
case .requestSync:
|
||||
handleRequestSync(packet, from: senderID)
|
||||
@@ -6210,7 +6213,7 @@ extension BLEService {
|
||||
handleNoiseEncrypted(packet, from: senderID)
|
||||
|
||||
case .fragment:
|
||||
handleFragment(packet, from: senderID)
|
||||
guard handleFragment(packet, from: senderID) else { return }
|
||||
|
||||
case .fileTransfer:
|
||||
// Broadcast files that fail sender authentication must not spread
|
||||
@@ -6225,7 +6228,7 @@ extension BLEService {
|
||||
handleGroupMessage(packet, from: senderID)
|
||||
|
||||
case .prekeyBundle:
|
||||
handlePrekeyBundle(packet, from: senderID)
|
||||
guard handlePrekeyBundle(packet, from: senderID) else { return }
|
||||
|
||||
case .boardPost:
|
||||
// Invalid or deleted posts must not spread; skip the relay step.
|
||||
@@ -6253,6 +6256,9 @@ extension BLEService {
|
||||
guard handleLeave(packet, from: senderID) else { return }
|
||||
|
||||
case .none:
|
||||
// Unknown/future wire types stay relayable (subject to dedup,
|
||||
// TTL clamp, and PacketPayloadLimits's default cap) for
|
||||
// forward compatibility with newer iOS/Android clients.
|
||||
SecureLogger.warning("⚠️ Unknown message type: \(packet.type)", category: .session)
|
||||
}
|
||||
|
||||
@@ -6305,16 +6311,17 @@ extension BLEService {
|
||||
engineScheduler.schedule(after: Double(decision.delayMs) / 1_000, execute: work)
|
||||
}
|
||||
|
||||
private func handleAnnounce(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
let result = announceHandler.handle(packet, from: peerID)
|
||||
private func handleAnnounce(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
guard let result = announceHandler.handle(packet, from: peerID),
|
||||
result.isVerified else {
|
||||
return false
|
||||
}
|
||||
|
||||
// A capability bit in the public announce is only a discovery hint.
|
||||
// Start authentication promptly for a directly connected candidate,
|
||||
// but never pin or pre-queue private bytes until encrypted 0x21 state
|
||||
// arrives from the completed Noise session.
|
||||
if let result,
|
||||
result.isVerified,
|
||||
result.isDirectAnnounce,
|
||||
if result.isDirectAnnounce,
|
||||
result.announcement.capabilities?.contains(.privateMedia) == true,
|
||||
privateMediaSendPolicy(to: result.peerID) == .awaitingCapabilityProof,
|
||||
!noiseService.hasSession(with: result.peerID) {
|
||||
@@ -6323,30 +6330,24 @@ extension BLEService {
|
||||
|
||||
// A verified announce is the moment a signing key becomes bound to this
|
||||
// owner's noise key: retry any prekey bundle that raced ahead of it.
|
||||
if let result, result.isVerified {
|
||||
drainPendingPrekeyBundles(for: result.peerID)
|
||||
}
|
||||
drainPendingPrekeyBundles(for: result.peerID)
|
||||
|
||||
// A verified direct announce proves the sender owns the link it came
|
||||
// in on: heal any stale binding left by a peer-ID rotation, and
|
||||
// consolidate duplicate same-role connections onto that link.
|
||||
if let result, result.isVerified, result.isDirectAnnounce {
|
||||
if result.isDirectAnnounce {
|
||||
rebindLinkAfterVerifiedDirectAnnounce(packet, to: result.peerID)
|
||||
retireRedundantPeripheralLinks(packet, to: result.peerID)
|
||||
}
|
||||
|
||||
// Bridge courier watch: a verified announce may add a peer whose
|
||||
// relay-parked drops we should start watching for.
|
||||
if let result, result.isVerified {
|
||||
onVerifiedPeerAnnounce?(result.peerID)
|
||||
}
|
||||
onVerifiedPeerAnnounce?(result.peerID)
|
||||
|
||||
// Courier work: an announce is the moment we learn a peer's Noise
|
||||
// static key, so check whether we're carrying mail addressed to them
|
||||
// (or spray-able mail they could carry). Verified announces only.
|
||||
guard !courierStore.isEmpty,
|
||||
let result,
|
||||
result.isVerified else { return }
|
||||
guard !courierStore.isEmpty else { return true }
|
||||
let noiseKey = result.announcement.noisePublicKey
|
||||
let authenticatedIngress = result.isDirectAnnounce
|
||||
&& canDeliverSecurely(to: result.peerID)
|
||||
@@ -6373,6 +6374,7 @@ extension BLEService {
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// When a peer relaunches it rotates its ephemeral peer ID, but an
|
||||
@@ -6855,7 +6857,7 @@ extension BLEService {
|
||||
|
||||
// Mention parsing moved to ChatViewModel
|
||||
|
||||
private func handleMessage(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
private func handleMessage(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
publicMessageHandler.handle(packet, from: peerID)
|
||||
}
|
||||
|
||||
@@ -7312,7 +7314,7 @@ extension BLEService {
|
||||
}
|
||||
for removedPeer in changes.removedPeers {
|
||||
SecureLogger.debug("🗑️ Removing stale peer after reachability window: \(removedPeer.peerID.id.prefix(8))… (\(removedPeer.nickname))", category: .session)
|
||||
gossipSyncManager?.removeAnnouncementForPeer(removedPeer.peerID)
|
||||
gossipSyncManager?.expireStaleAnnouncementForPeer(removedPeer.peerID)
|
||||
}
|
||||
|
||||
// Update UI if there were direct disconnections or offline removals
|
||||
|
||||
@@ -30,6 +30,9 @@ struct GroupMember: Codable, Equatable {
|
||||
/// in the keychain (see `GroupStore`).
|
||||
struct BitchatGroup: Codable, Equatable {
|
||||
static let maxMembers = 16
|
||||
static let maxGroups = 64
|
||||
static let maxNameLength = 40
|
||||
static let maxNameUTF8Bytes = 160
|
||||
static let groupIDLength = 16
|
||||
static let keyLength = 32
|
||||
|
||||
|
||||
@@ -76,16 +76,27 @@ final class GroupStore: ObservableObject {
|
||||
}
|
||||
|
||||
/// Inserts or replaces a group and its current key. Rejects rosters over
|
||||
/// the hard cap, groups whose creator is missing from the roster, and any
|
||||
/// change to the creator (fingerprint or signing key) of a group already
|
||||
/// held, so no caller can hand a known groupID to a different creator.
|
||||
/// the hard cap, groups whose creator is missing from the roster, new
|
||||
/// groups beyond the store cap, and any change to the creator (fingerprint
|
||||
/// or signing key) of a group already held, so no caller can hand a known
|
||||
/// groupID to a different creator.
|
||||
@discardableResult
|
||||
func upsert(_ group: BitchatGroup, key: Data) -> Bool {
|
||||
guard key.count == BitchatGroup.keyLength,
|
||||
Self.isWellFormed(group) else { return false }
|
||||
if let existing = self.group(withID: group.groupID), !existing.hasSameCreator(as: group) {
|
||||
let existingIndex = groups.firstIndex(where: { $0.groupID == group.groupID })
|
||||
if let existingIndex {
|
||||
let existing = groups[existingIndex]
|
||||
if !existing.hasSameCreator(as: group) {
|
||||
SecureLogger.warning(
|
||||
"Refusing group state: creator \(group.creatorFingerprint.prefix(8))… does not match stored creator \(existing.creatorFingerprint.prefix(8))…",
|
||||
category: .security
|
||||
)
|
||||
return false
|
||||
}
|
||||
} else if groups.count >= BitchatGroup.maxGroups {
|
||||
SecureLogger.warning(
|
||||
"Refusing group state: creator \(group.creatorFingerprint.prefix(8))… does not match stored creator \(existing.creatorFingerprint.prefix(8))…",
|
||||
"Refusing new group \(group.groupID.hexEncodedString().prefix(8))…: group store at cap (\(BitchatGroup.maxGroups))",
|
||||
category: .security
|
||||
)
|
||||
return false
|
||||
@@ -95,8 +106,8 @@ final class GroupStore: ObservableObject {
|
||||
return false
|
||||
}
|
||||
keyCache[group.groupID] = key
|
||||
if let index = groups.firstIndex(where: { $0.groupID == group.groupID }) {
|
||||
groups[index] = group
|
||||
if let existingIndex {
|
||||
groups[existingIndex] = group
|
||||
} else {
|
||||
groups.append(group)
|
||||
}
|
||||
@@ -158,9 +169,14 @@ final class GroupStore: ObservableObject {
|
||||
}
|
||||
|
||||
/// Structural invariants every stored group satisfies: a well-sized ID,
|
||||
/// a non-empty roster within the cap, and the creator in that roster.
|
||||
/// a non-empty bounded name, a non-empty roster within the cap, and the
|
||||
/// creator in that roster.
|
||||
private static func isWellFormed(_ group: BitchatGroup) -> Bool {
|
||||
group.groupID.count == BitchatGroup.groupIDLength
|
||||
let trimmedName = group.name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return group.groupID.count == BitchatGroup.groupIDLength
|
||||
&& !trimmedName.isEmpty
|
||||
&& trimmedName.count <= BitchatGroup.maxNameLength
|
||||
&& group.name.utf8.count <= BitchatGroup.maxNameUTF8Bytes
|
||||
&& !group.members.isEmpty
|
||||
&& group.members.count <= BitchatGroup.maxMembers
|
||||
&& group.creator != nil
|
||||
|
||||
@@ -305,7 +305,7 @@ final class GossipSyncManager {
|
||||
guard isPacketFresh(packet, nowMs: nowMs) else { return }
|
||||
guard isAnnouncementFresh(packet, nowMs: nowMs) else {
|
||||
let sender = PeerID(hexData: packet.senderID)
|
||||
removeState(for: sender)
|
||||
expireStalePresence(for: sender)
|
||||
return
|
||||
}
|
||||
let sender = PeerID(hexData: packet.senderID)
|
||||
@@ -788,17 +788,26 @@ final class GossipSyncManager {
|
||||
}
|
||||
guard !stalePeerIDs.isEmpty else { return }
|
||||
for peerKey in stalePeerIDs {
|
||||
removeState(for: peerKey)
|
||||
expireStalePresence(for: peerKey)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit removal hook for LEAVE/stale peer
|
||||
// Explicit removal hook for LEAVE or identity rotation
|
||||
func removeAnnouncementForPeer(_ peerID: PeerID) {
|
||||
queue.async { [weak self] in
|
||||
self?.removeState(for: peerID)
|
||||
}
|
||||
}
|
||||
|
||||
/// Passive reachability timeout: expire live presence and transient
|
||||
/// fragments without wiping 6-hour public messages or 15-minute
|
||||
/// group/file history, which age out on their own TTLs.
|
||||
func expireStaleAnnouncementForPeer(_ peerID: PeerID) {
|
||||
queue.async { [weak self] in
|
||||
self?.expireStalePresence(for: peerID)
|
||||
}
|
||||
}
|
||||
|
||||
/// Block-time hygiene: drop the carried public messages from a blocked
|
||||
/// sender and persist immediately, so nothing of theirs can resurface as
|
||||
/// an archived echo on the next launch. Narrower than `removeState(for:)`
|
||||
@@ -836,6 +845,11 @@ final class GossipSyncManager {
|
||||
}
|
||||
}
|
||||
|
||||
private func expireStalePresence(for peerID: PeerID) {
|
||||
_ = latestAnnouncementByPeer.removeValue(forKey: peerID)
|
||||
fragments.remove { PeerID(hexData: $0.senderID) == peerID }
|
||||
}
|
||||
|
||||
private func removeState(for peerID: PeerID) {
|
||||
// Deliberately keeps the peer's prekey bundle: bundles exist to reach
|
||||
// owners who left the mesh, and they age out on their own schedule.
|
||||
|
||||
@@ -151,8 +151,6 @@ extension ChatViewModel: ChatGroupContext {
|
||||
final class ChatGroupCoordinator {
|
||||
private unowned let context: any ChatGroupContext
|
||||
|
||||
private static let maxGroupNameLength = 40
|
||||
|
||||
init(context: any ChatGroupContext) {
|
||||
self.context = context
|
||||
}
|
||||
@@ -164,7 +162,8 @@ final class ChatGroupCoordinator {
|
||||
guard !name.isEmpty else {
|
||||
return .error(message: String(localized: "system.group.usage_create", comment: "Usage hint for /group create"))
|
||||
}
|
||||
guard name.count <= Self.maxGroupNameLength else {
|
||||
guard name.count <= BitchatGroup.maxNameLength,
|
||||
name.utf8.count <= BitchatGroup.maxNameUTF8Bytes else {
|
||||
return .error(message: String(localized: "system.group.name_too_long", comment: "Error when a group name exceeds the length cap"))
|
||||
}
|
||||
|
||||
@@ -552,6 +551,17 @@ private extension ChatGroupCoordinator {
|
||||
SecureLogger.warning("Dropping group state from non-creator \(peerID.id.prefix(8))…", category: .security)
|
||||
return
|
||||
}
|
||||
guard !context.isFingerprintBlocked(senderFingerprint) else {
|
||||
SecureLogger.warning("Dropping group state from blocked sender \(senderFingerprint.prefix(8))…", category: .security)
|
||||
return
|
||||
}
|
||||
let trimmedName = state.name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmedName.isEmpty,
|
||||
trimmedName.count <= BitchatGroup.maxNameLength,
|
||||
state.name.utf8.count <= BitchatGroup.maxNameUTF8Bytes else {
|
||||
SecureLogger.warning("Dropping group state with invalid name length (\(state.name.count) chars, \(state.name.utf8.count) bytes) from \(peerID.id.prefix(8))…", category: .security)
|
||||
return
|
||||
}
|
||||
guard state.verifyCreatorSignature() else {
|
||||
SecureLogger.warning("Dropping group state with invalid creator signature", category: .security)
|
||||
return
|
||||
@@ -603,8 +613,10 @@ private extension ChatGroupCoordinator {
|
||||
}
|
||||
|
||||
let isNewMembership = existing == nil
|
||||
guard context.groupStore.upsert(state.asGroup, key: state.key) else {
|
||||
SecureLogger.error("Failed to store group state for \(state.name)", category: .session)
|
||||
var sanitizedGroup = state.asGroup
|
||||
sanitizedGroup.name = trimmedName
|
||||
guard context.groupStore.upsert(sanitizedGroup, key: state.key) else {
|
||||
SecureLogger.error("Failed to store group state for \(trimmedName)", category: .session)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -615,14 +627,14 @@ private extension ChatGroupCoordinator {
|
||||
let notice = String(
|
||||
format: String(localized: "system.group.joined", comment: "System message when added to a group; placeholders are the group name and the inviter"),
|
||||
locale: .current,
|
||||
state.name,
|
||||
trimmedName,
|
||||
inviter
|
||||
)
|
||||
context.addSystemMessage(notice)
|
||||
context.markPrivateChatUnread(state.asGroup.peerID)
|
||||
context.notifyPrivateMessage(from: inviter, message: notice, peerID: state.asGroup.peerID)
|
||||
context.markPrivateChatUnread(sanitizedGroup.peerID)
|
||||
context.notifyPrivateMessage(from: inviter, message: notice, peerID: sanitizedGroup.peerID)
|
||||
} else if isInvite == false, let existing, state.epoch > existing.epoch {
|
||||
SecureLogger.info("Group '\(state.name)' rotated to epoch \(state.epoch)", category: .session)
|
||||
SecureLogger.info("Group '\(trimmedName)' rotated to epoch \(state.epoch)", category: .session)
|
||||
}
|
||||
context.notifyUIChanged()
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ private final class MockChatGroupContext: ChatGroupContext {
|
||||
|
||||
// Peers: the fingerprint each Noise session authenticated.
|
||||
var fingerprintsByPeerID: [PeerID: String] = [:]
|
||||
var blockedFingerprints: Set<String> = []
|
||||
|
||||
func getPeerIDForNickname(_ nickname: String) -> PeerID? { nil }
|
||||
func isPeerConnected(_ peerID: PeerID) -> Bool { false }
|
||||
@@ -46,7 +47,7 @@ private final class MockChatGroupContext: ChatGroupContext {
|
||||
func meshFingerprint(for peerID: PeerID) -> String? { fingerprintsByPeerID[peerID] }
|
||||
func cryptoIdentity(for peerID: PeerID) -> (fingerprint: String, signingKey: Data)? { nil }
|
||||
func connectedPeerID(forFingerprint fingerprint: String) -> PeerID? { nil }
|
||||
func isFingerprintBlocked(_ fingerprint: String) -> Bool { false }
|
||||
func isFingerprintBlocked(_ fingerprint: String) -> Bool { blockedFingerprints.contains(fingerprint) }
|
||||
|
||||
// Transport (outbound state is not exercised by these tests)
|
||||
func sendGroupInvitePayload(_ payload: Data, to peerID: PeerID) {}
|
||||
@@ -299,4 +300,41 @@ struct ChatGroupCoordinatorContextTests {
|
||||
coordinator.handleGroupKeyUpdatePayload(from: creator.peerID, payload: staleRemoval)
|
||||
expectUnchanged(context, joined: joined)
|
||||
}
|
||||
|
||||
@Test
|
||||
func blockedCreatorInviteIsDropped() throws {
|
||||
let context = MockChatGroupContext(identity: me)
|
||||
let coordinator = ChatGroupCoordinator(context: context)
|
||||
context.fingerprintsByPeerID[creator.peerID] = creator.fingerprint
|
||||
context.blockedFingerprints.insert(creator.fingerprint)
|
||||
|
||||
let invite = try creatorState(epoch: 1, members: [creator.member, me.member], key: groupKey)
|
||||
coordinator.handleGroupInvitePayload(from: creator.peerID, payload: invite)
|
||||
|
||||
#expect(context.groupStore.groups.isEmpty)
|
||||
#expect(context.systemMessages.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func oversizedOrEmptyGroupNameInviteIsDropped() throws {
|
||||
let context = MockChatGroupContext(identity: me)
|
||||
let coordinator = ChatGroupCoordinator(context: context)
|
||||
context.fingerprintsByPeerID[creator.peerID] = creator.fingerprint
|
||||
|
||||
for badName in [" ", String(repeating: "x", count: BitchatGroup.maxNameLength + 1)] {
|
||||
let group = BitchatGroup(
|
||||
groupID: groupID,
|
||||
name: badName,
|
||||
epoch: 1,
|
||||
members: [creator.member, me.member],
|
||||
creatorFingerprint: creator.fingerprint
|
||||
)
|
||||
let payload = try #require(GroupStatePayload.makeSigned(group: group, key: groupKey, sign: creator.sign))
|
||||
let encoded = try #require(payload.encode())
|
||||
coordinator.handleGroupInvitePayload(from: creator.peerID, payload: encoded)
|
||||
}
|
||||
|
||||
#expect(context.groupStore.groups.isEmpty)
|
||||
#expect(context.systemMessages.isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -84,10 +84,16 @@ struct GossipSyncManagerTests {
|
||||
#expect(manager._hasAnnouncement(for: PeerID(str: peerHex)))
|
||||
#expect(manager._messageCount(for: PeerID(str: peerHex)) == 1)
|
||||
|
||||
// Run cleanup past the timeout
|
||||
// Run cleanup past the stale peer timeout: presence expires, but
|
||||
// carried public messages survive until maxMessageAgeSeconds (6h).
|
||||
let future = Date().addingTimeInterval(config.stalePeerTimeoutSeconds + 1)
|
||||
manager._performMaintenanceSynchronously(now: future)
|
||||
#expect(manager._hasAnnouncement(for: PeerID(str: peerHex)) == false)
|
||||
#expect(manager._messageCount(for: PeerID(str: peerHex)) == 1)
|
||||
|
||||
// Explicit LEAVE removal still drops carried messages for the peer.
|
||||
manager.removeAnnouncementForPeer(PeerID(str: peerHex))
|
||||
manager._performMaintenanceSynchronously(now: future)
|
||||
#expect(manager._messageCount(for: PeerID(str: peerHex)) == 0)
|
||||
}
|
||||
|
||||
@@ -169,7 +175,8 @@ struct GossipSyncManagerTests {
|
||||
manager._performMaintenanceSynchronously()
|
||||
|
||||
#expect(manager._hasAnnouncement(for: PeerID(str: peerHex)) == false)
|
||||
#expect(manager._messageCount(for: PeerID(str: peerHex)) == 0)
|
||||
// A stale announce must not wipe fresh public messages within maxMessageAgeSeconds.
|
||||
#expect(manager._messageCount(for: PeerID(str: peerHex)) == 1)
|
||||
}
|
||||
|
||||
@Test func maintenanceEmitsTypedSyncRequests() throws {
|
||||
|
||||
@@ -437,4 +437,62 @@ struct BLEFragmentAssemblyBufferTests {
|
||||
ttl: 3
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func mismatchedTotalOrOriginalTypeIsRejectedWithoutEvictingAssembly() throws {
|
||||
var buffer = BLEFragmentAssemblyBuffer()
|
||||
let original = makePacket(payload: makePayload(count: 256))
|
||||
let fragmentID = Data(repeating: 0x0B, count: 8)
|
||||
let packets = try makeFragments(for: original, chunkSize: 128, fragmentID: fragmentID)
|
||||
let headers = try packets.map { try #require(BLEFragmentHeader(packet: $0)) }
|
||||
#expect(headers.count >= 2)
|
||||
|
||||
// Start a legitimate multi-fragment assembly with fragment 0.
|
||||
if case let .stored(_, started) = buffer.append(headers[0], maxInFlightAssemblies: 8) {
|
||||
#expect(started)
|
||||
} else {
|
||||
Issue.record("Expected first fragment to start assembly")
|
||||
}
|
||||
|
||||
// Spoofed fragment with total = 1 must NOT trigger premature completion or evict.
|
||||
let spoofedTotal = try #require(BLEFragmentHeader(packet: makeFragmentPacket(
|
||||
fragmentID: fragmentID,
|
||||
index: 0,
|
||||
total: 1,
|
||||
originalType: original.type,
|
||||
fragmentData: Data([0xFF])
|
||||
)))
|
||||
if case let .mismatched(_, expectedTotal, expectedType) = buffer.append(spoofedTotal, maxInFlightAssemblies: 8) {
|
||||
#expect(expectedTotal == headers.count)
|
||||
#expect(expectedType == original.type)
|
||||
} else {
|
||||
Issue.record("Expected mismatched total fragment to be rejected")
|
||||
}
|
||||
|
||||
// Spoofed fragment claiming a different originalType must NOT downgrade limit or evict.
|
||||
let spoofedType = try #require(BLEFragmentHeader(packet: makeFragmentPacket(
|
||||
fragmentID: fragmentID,
|
||||
index: 1,
|
||||
total: headers.count,
|
||||
originalType: MessageType.announce.rawValue,
|
||||
fragmentData: Data([0xEE])
|
||||
)))
|
||||
if case let .mismatched(_, expectedTotal, expectedType) = buffer.append(spoofedType, maxInFlightAssemblies: 8) {
|
||||
#expect(expectedTotal == headers.count)
|
||||
#expect(expectedType == original.type)
|
||||
} else {
|
||||
Issue.record("Expected mismatched originalType fragment to be rejected")
|
||||
}
|
||||
|
||||
// Remaining legitimate fragments still complete the original packet intact.
|
||||
var finalResult: BLEFragmentAssemblyBuffer.AppendResult?
|
||||
for header in headers.dropFirst() {
|
||||
finalResult = buffer.append(header, maxInFlightAssemblies: 8)
|
||||
}
|
||||
if case let .complete(_, reassembled, _) = finalResult {
|
||||
#expect(BinaryProtocol.decode(reassembled)?.payload == original.payload)
|
||||
} else {
|
||||
Issue.record("Expected original assembly to survive mismatched fragments and complete")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -169,6 +169,99 @@ struct BLEInboundWriteBufferTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func extremeOrNegativeOffsetRejectsWithoutAllocating() {
|
||||
var buffer = BLEInboundWriteBuffer()
|
||||
|
||||
let hugeOffsetResult = buffer.append(
|
||||
chunks: [BLEInboundWriteChunk(offset: 1_000_000_000, data: Data([0x01, 0x02]))],
|
||||
for: "attacker-huge",
|
||||
capBytes: 1024
|
||||
)
|
||||
if case .oversized = hugeOffsetResult {
|
||||
// Rejected immediately before allocating zero-fill padding.
|
||||
} else {
|
||||
Issue.record("Expected huge offset to be rejected as oversized")
|
||||
}
|
||||
|
||||
let overflowResult = buffer.append(
|
||||
chunks: [BLEInboundWriteChunk(offset: Int.max - 1, data: Data([0x01, 0x02, 0x03]))],
|
||||
for: "attacker-overflow",
|
||||
capBytes: 1024
|
||||
)
|
||||
if case .oversized = overflowResult {
|
||||
// Expected overflow guard.
|
||||
} else {
|
||||
Issue.record("Expected overflowing offset+length to be rejected")
|
||||
}
|
||||
|
||||
let negativeResult = buffer.append(
|
||||
chunks: [BLEInboundWriteChunk(offset: -4, data: Data([0x01]))],
|
||||
for: "attacker-neg",
|
||||
capBytes: 1024
|
||||
)
|
||||
if case .oversized = negativeResult {
|
||||
// Expected negative offset guard.
|
||||
} else {
|
||||
Issue.record("Expected negative offset to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func removeForCentralAndMaxTrackedCentralsBoundState() throws {
|
||||
var buffer = BLEInboundWriteBuffer()
|
||||
let packet = makePacket()
|
||||
let frame = try #require(packet.toBinaryData(padding: false))
|
||||
let splitIndex = max(1, frame.count / 2)
|
||||
|
||||
_ = buffer.append(
|
||||
chunks: [BLEInboundWriteChunk(offset: 0, data: frame.prefix(splitIndex))],
|
||||
for: "central-a",
|
||||
capBytes: 1024,
|
||||
maxTrackedCentrals: 2
|
||||
)
|
||||
_ = buffer.append(
|
||||
chunks: [BLEInboundWriteChunk(offset: 0, data: frame.prefix(splitIndex))],
|
||||
for: "central-b",
|
||||
capBytes: 1024,
|
||||
maxTrackedCentrals: 2
|
||||
)
|
||||
// Third central evicts oldest ("central-a").
|
||||
_ = buffer.append(
|
||||
chunks: [BLEInboundWriteChunk(offset: 0, data: frame.prefix(splitIndex))],
|
||||
for: "central-c",
|
||||
capBytes: 1024,
|
||||
maxTrackedCentrals: 2
|
||||
)
|
||||
|
||||
// Removing central-b explicitly drops its partial buffer.
|
||||
buffer.remove(for: "central-b")
|
||||
|
||||
let aSecondHalf = buffer.append(
|
||||
chunks: [BLEInboundWriteChunk(offset: splitIndex, data: frame.suffix(from: splitIndex))],
|
||||
for: "central-a",
|
||||
capBytes: 1024,
|
||||
maxTrackedCentrals: 2
|
||||
)
|
||||
if case .waiting = aSecondHalf {
|
||||
// Expected: central-a was evicted by cap.
|
||||
} else {
|
||||
Issue.record("Expected evicted central-a partial buffer to be gone")
|
||||
}
|
||||
|
||||
let bSecondHalf = buffer.append(
|
||||
chunks: [BLEInboundWriteChunk(offset: splitIndex, data: frame.suffix(from: splitIndex))],
|
||||
for: "central-b",
|
||||
capBytes: 1024,
|
||||
maxTrackedCentrals: 2
|
||||
)
|
||||
if case .waiting = bSecondHalf {
|
||||
// Expected: central-b was removed explicitly.
|
||||
} else {
|
||||
Issue.record("Expected explicitly removed central-b partial buffer to be gone")
|
||||
}
|
||||
}
|
||||
|
||||
private func makePacket(timestamp: UInt64 = 0x0102030405) -> BitchatPacket {
|
||||
BitchatPacket(
|
||||
type: MessageType.message.rawValue,
|
||||
|
||||
@@ -267,4 +267,84 @@ struct GroupStoreTests {
|
||||
#expect(store.groups.isEmpty)
|
||||
#expect(store.key(forGroupID: group.groupID) == nil)
|
||||
}
|
||||
|
||||
@Test func upsertRejectsEmptyAndOversizedGroupNames() {
|
||||
let keychain = MockKeychain()
|
||||
let store = GroupStore(keychain: keychain, persistsToDisk: false)
|
||||
let creator = makeMember(seed: 0xD1)
|
||||
let key = Data(repeating: 0x77, count: BitchatGroup.keyLength)
|
||||
|
||||
let emptyName = BitchatGroup(
|
||||
groupID: Data(repeating: 0x01, count: BitchatGroup.groupIDLength),
|
||||
name: " ",
|
||||
epoch: 1,
|
||||
members: [creator],
|
||||
creatorFingerprint: creator.fingerprint
|
||||
)
|
||||
#expect(!store.upsert(emptyName, key: key))
|
||||
|
||||
let hugeName = BitchatGroup(
|
||||
groupID: Data(repeating: 0x02, count: BitchatGroup.groupIDLength),
|
||||
name: String(repeating: "a", count: BitchatGroup.maxNameLength + 1),
|
||||
epoch: 1,
|
||||
members: [creator],
|
||||
creatorFingerprint: creator.fingerprint
|
||||
)
|
||||
#expect(!store.upsert(hugeName, key: key))
|
||||
|
||||
// Whitespace-padded or combining-mark-bloated names pass `.count` but
|
||||
// must still be rejected by the UTF-8 byte ceiling.
|
||||
let paddedName = BitchatGroup(
|
||||
groupID: Data(repeating: 0x03, count: BitchatGroup.groupIDLength),
|
||||
name: "x" + String(repeating: " ", count: BitchatGroup.maxNameUTF8Bytes + 1),
|
||||
epoch: 1,
|
||||
members: [creator],
|
||||
creatorFingerprint: creator.fingerprint
|
||||
)
|
||||
#expect(!store.upsert(paddedName, key: key))
|
||||
|
||||
let combiningMarkName = BitchatGroup(
|
||||
groupID: Data(repeating: 0x04, count: BitchatGroup.groupIDLength),
|
||||
name: "e" + String(repeating: "\u{0301}", count: BitchatGroup.maxNameUTF8Bytes),
|
||||
epoch: 1,
|
||||
members: [creator],
|
||||
creatorFingerprint: creator.fingerprint
|
||||
)
|
||||
#expect(!store.upsert(combiningMarkName, key: key))
|
||||
#expect(store.groups.isEmpty)
|
||||
}
|
||||
|
||||
@Test func upsertEnforcesMaxGroupsCapWithoutLeakingKeychainEntry() throws {
|
||||
let keychain = MockKeychain()
|
||||
let store = GroupStore(keychain: keychain, persistsToDisk: false)
|
||||
let creator = makeMember(seed: 0xD2)
|
||||
let key = Data(repeating: 0x88, count: BitchatGroup.keyLength)
|
||||
|
||||
for i in 0..<BitchatGroup.maxGroups {
|
||||
var id = Data(repeating: 0x00, count: BitchatGroup.groupIDLength)
|
||||
id[0] = UInt8(i & 0xFF)
|
||||
id[1] = UInt8((i >> 8) & 0xFF)
|
||||
let group = BitchatGroup(
|
||||
groupID: id,
|
||||
name: "group-\(i)",
|
||||
epoch: 1,
|
||||
members: [creator],
|
||||
creatorFingerprint: creator.fingerprint
|
||||
)
|
||||
#expect(store.upsert(group, key: key))
|
||||
}
|
||||
#expect(store.groups.count == BitchatGroup.maxGroups)
|
||||
|
||||
let overflowID = Data(repeating: 0xFF, count: BitchatGroup.groupIDLength)
|
||||
let overflowGroup = BitchatGroup(
|
||||
groupID: overflowID,
|
||||
name: "overflow",
|
||||
epoch: 1,
|
||||
members: [creator],
|
||||
creatorFingerprint: creator.fingerprint
|
||||
)
|
||||
#expect(!store.upsert(overflowGroup, key: key))
|
||||
#expect(store.groups.count == BitchatGroup.maxGroups)
|
||||
#expect(store.key(forGroupID: overflowID) == nil)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user