mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-24 22:45:19 +00:00
A broad audit surfaced ten critical/high issues across the crypto, transport, identity, and panic-wipe layers. This fixes all ten. Critical: - Nostr DMs were unauthenticated. The NIP-17 seal was signed with a throwaway ephemeral key and the receiver never verified it, so anyone who knows a recipient's npub could forge messages (and delivery/read receipts) into an existing trusted conversation. The seal is now signed with the sender's real identity key, and the receiver verifies the seal signature and that seal.pubkey == rumor.pubkey. NOTE: this is a breaking wire-protocol change (see PR). - Public BLE messages trusted registry membership instead of the packet signature. Since senderID is attacker-controlled, any verified peer could be impersonated in public chat. A valid signature from the claimed sender is now required before any registry identity is used. - Unverified announces still persisted the announced identity, letting a replayed noisePublicKey overwrite a victim's stored signing key and nickname. persistIdentity is now gated on verification. High: - Noise decrypt trapped on a 16-19 byte ciphertext (negative prefix length after nonce extraction) — a remote crash. Now validated. - Identity-cache debounce save used Timer.scheduledTimer on a GCD queue with no run loop, so it never fired; block/verify/favorite changes only persisted on explicit forceSave. Replaced with a DispatchSourceTimer on the queue; forceSave is now serialized. - Identity-cache key load couldn't tell "missing" from a transient keychain failure and would regenerate (deleting) the key, orphaning the cache. Now uses getIdentityKeyWithResult and falls back to a session-only ephemeral key without clobbering the persisted key/cache. - BLE receive-dedup key lacked a payload digest, so post-handshake flushes (queued msgs + delivery/read acks in the same ms) were dropped as duplicates. Digest added, matching the ingress registry. - Maintenance timer was created only in init and never recreated after a panic stop/start, silently degrading the mesh until app restart. Now recreated in startServices. - Panic wipe left persisted location state (selected channel, teleport set, bookmarks) and cached per-geohash Nostr private keys behind. Both are now cleared. - Panic spawned an orphan NostrRelayManager instead of reusing .shared, splitting relay state from every other component. Now reuses .shared. Tests updated to assert the fixed behavior (announce no longer persists unverified identities; public messages require a signature; receive dedup ID includes the payload digest). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
109 lines
4.0 KiB
Swift
109 lines
4.0 KiB
Swift
import BitFoundation
|
|
import Foundation
|
|
import Testing
|
|
@testable import bitchat
|
|
|
|
@Suite("BLE receive pipeline tests")
|
|
struct BLEReceivePipelineTests {
|
|
@Test("context includes sender, type-scoped message ID, and logging policy")
|
|
func contextBuildsTypeScopedMessageID() {
|
|
let sender = PeerID(str: "1122334455667788")
|
|
let local = PeerID(str: "8877665544332211")
|
|
let packet = makePacket(type: .message, sender: sender, timestamp: 1234)
|
|
|
|
let context = BLEReceivePipeline.context(for: packet, localPeerID: local)
|
|
|
|
#expect(context.senderID == sender)
|
|
// The message ID includes a payload digest so distinct packets sharing a
|
|
// sender/timestamp(ms)/type are not collapsed as duplicates.
|
|
let digest = packet.payload.sha256Hash().prefix(4).hexEncodedString()
|
|
#expect(context.messageID == "\(sender)-1234-\(MessageType.message.rawValue)-\(digest)")
|
|
#expect(context.messageType == .message)
|
|
#expect(context.shouldDeduplicate)
|
|
#expect(context.logsHandlingDetails)
|
|
}
|
|
|
|
@Test("fragments and self sync replays bypass global deduplication")
|
|
func contextBypassesDeduplicationForFragmentsAndSelfSyncReplay() {
|
|
let local = PeerID(str: "1122334455667788")
|
|
let remote = PeerID(str: "8877665544332211")
|
|
|
|
let fragment = BLEReceivePipeline.context(
|
|
for: makePacket(type: .fragment, sender: remote),
|
|
localPeerID: local
|
|
)
|
|
let selfReplay = BLEReceivePipeline.context(
|
|
for: makePacket(type: .message, sender: local, ttl: 0),
|
|
localPeerID: local
|
|
)
|
|
|
|
#expect(!fragment.shouldDeduplicate)
|
|
#expect(!selfReplay.shouldDeduplicate)
|
|
}
|
|
|
|
@Test("dense duplicate traffic cancels pending relays but sparse traffic does not")
|
|
func duplicateRelayCancellationUsesGraphDensity() {
|
|
#expect(!BLEReceivePipeline.shouldCancelScheduledRelayForDuplicate(connectedPeerCount: 2))
|
|
#expect(BLEReceivePipeline.shouldCancelScheduledRelayForDuplicate(connectedPeerCount: 3))
|
|
}
|
|
|
|
@Test("relay decision maps packet context and suppresses local recipient traffic")
|
|
func relayDecisionSuppressesLocalRecipientTraffic() {
|
|
let sender = PeerID(str: "1122334455667788")
|
|
let local = PeerID(str: "8877665544332211")
|
|
let packet = makePacket(
|
|
type: .noiseEncrypted,
|
|
sender: sender,
|
|
recipient: local,
|
|
ttl: 7
|
|
)
|
|
|
|
let decision = BLEReceivePipeline.relayDecision(
|
|
for: packet,
|
|
senderID: sender,
|
|
localPeerID: local,
|
|
degree: 3,
|
|
highDegreeThreshold: TransportConfig.bleHighDegreeThreshold
|
|
)
|
|
|
|
#expect(!decision.shouldRelay)
|
|
}
|
|
|
|
@Test("recent traffic tracker prunes by count and time window")
|
|
func recentTrafficTrackerPrunesByCountAndWindow() {
|
|
var tracker = BLERecentTrafficTracker()
|
|
let now = Date(timeIntervalSince1970: 1_000)
|
|
|
|
tracker.recordPacket(at: now.addingTimeInterval(-TransportConfig.bleRecentPacketWindowSeconds - 1))
|
|
#expect(!tracker.hasTraffic(within: TransportConfig.bleRecentPacketWindowSeconds, now: now))
|
|
|
|
for index in 0...TransportConfig.bleRecentPacketWindowMaxCount {
|
|
tracker.recordPacket(at: now.addingTimeInterval(Double(index) * 0.001))
|
|
}
|
|
|
|
#expect(tracker.count == TransportConfig.bleRecentPacketWindowMaxCount)
|
|
#expect(tracker.hasTraffic(within: 1.0, now: now.addingTimeInterval(0.1)))
|
|
|
|
tracker.removeAll()
|
|
#expect(tracker.count == 0)
|
|
}
|
|
|
|
private func makePacket(
|
|
type: MessageType,
|
|
sender: PeerID,
|
|
recipient: PeerID? = nil,
|
|
timestamp: UInt64 = 1,
|
|
ttl: UInt8 = 7
|
|
) -> BitchatPacket {
|
|
BitchatPacket(
|
|
type: type.rawValue,
|
|
senderID: Data(hexString: sender.id) ?? Data(),
|
|
recipientID: recipient.flatMap { Data(hexString: $0.id) },
|
|
timestamp: timestamp,
|
|
payload: Data([0x01, 0x02]),
|
|
signature: nil,
|
|
ttl: ttl
|
|
)
|
|
}
|
|
}
|