mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-27 16:45:21 +00:00
* Deflake two iOS-sim CI tests with unbounded timing assumptions Both failed on main-adjacent CI runs during this session's PRs. Neither was a product bug; both asserted things about real time that a loaded runner is under no obligation to honour. **NetworkReachabilityGateTests: a wall-clock upper bound.** test_monitor_duplicateUpdatesDoNotPostponeOfflineCommit slept 500ms for real, then asserted total elapsed time was under 1.4s to prove a duplicate mid-window had not restarted the 1.0s debounce. One CI run took 3.75s. No wall-clock bound can separate "deadline preserved" from "runner is slow", because Task.sleep and the asyncAfter flush are both real time and neither is bounded above. The deadline property was already covered deterministically one level down: test_debounce_duplicateObservationsPreservePendingDeadline drives ReachabilityDebounce with injected timestamps and checks pendingRemaining directly. So the monitor test now asserts only what needs a real monitor — that a duplicate still yields exactly one committed false through the debounce — with an injected clock for the arithmetic and a generous liveness budget. Renamed to say what it actually checks. No coverage lost, and it runs in 0.14s instead of ~3.8s because the real sleep is gone. **NoiseEncryptionServiceTests: injected timeouts that also arm during setup.** #1483 diagnosed and fixed exactly this in the quarantine-restore test, but two sibling tests kept the shape. Their injected ordinaryResponderHandshakeTimeout (0.04 and 0.06) also arms during the establishSessions setup handshake, where bob is the responder — so a preempted runner fires it mid-setup, tears down the half-open responder, and message 3 gets answered as a fresh initiation. The CI failure named setup's own `#expect(finalMessage == nil)` seeing a 96-byte message 2, which is precisely the signature #1483 recorded. Raised both to 1.0s, matching #1483's remedy: the scenarios still need the responder timeout to fire, and it still does, just with room for setup to complete first. Thin 1-second waitUntil budgets in the file now use the shared TestConstants.longTimeout; every one of them backs a positive assertion, so waitUntil still returns the moment the condition holds and nothing gets slower in the passing case. No assertion weakened in either file. Verified 3x sequentially and 3x with all 18 cores saturated. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Raise two more starvation-prone test deadlines Both surfaced on the CI runs for this PR and #1487, both in tests neither PR touches, both the same shape as the two already fixed here: a deadline sized for the work rather than for a runner executing many suites at once. VoiceNotePlaybackControllerTests waited 5s for a @MainActor Task that playback schedules for the session acquire and its failure path. When that Task is not scheduled in time the helper reports *two* failures — the wait, and the `!isPlaying` the un-run failure path has not reset yet — which reads like a playback bug rather than a starved scheduler. That is exactly what CI showed. GeoRelayDirectoryTests waited 10s for work the directory runs in Task.detached(priority: .utility); utility priority competes with every other suite. The retry-scheduling case timed out at exactly 10.06s with the retry never scheduled, reading like a missing retry rather than a starved background task. Raised to 30s each with the reasoning recorded at the helper. Both helpers return as soon as their condition holds, so nothing slows down when tests pass — only the genuine-failure case takes longer to report. Verified 3x with all cores saturated: both suites clean. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Make the flake class unrepeatable, not just fixed Raising four deadlines fixed the four tests that happened to fire. The class was still there: fourteen separate waitUntil helpers, most defaulting to 1.0s, plus wait call sites with literal budgets. The fifth instance would have landed the same way, on someone else's unrelated PR. The rule, now written down in TestConstants.settleTimeout: **a wait deadline is not a latency budget.** It exists so a genuine hang eventually fails the suite, so size it for the worst-case scheduler, never for how long the operation should take. Waits return as soon as their condition holds, so a generous deadline is free in the passing case and only extends genuine failures. - Every wait helper now defaults to TestConstants.settleTimeout (30s), and the literal wait call sites below the floor were converted too — sixteen sites across ten files. - TestTimingHygieneTests enforces it by scanning the test sources: wait defaults and wait call sites must be at least minimumSettleTimeout, and no test may assert an upper bound on elapsed wall-clock time (the assertion that started this, which cannot separate correct behaviour from a slow machine). - Both rules waive per line with "test-timing-ok: <reason>", accepted on the line or in the comment block above it so the reason has room to be a sentence. One legitimate use so far: a NEGATIVE wait in NoiseCoverageTests asserting a promotion has *not* completed within 50ms, where a long deadline would only make the suite slow while still passing. Injected production timeouts are deliberately not matched — the Noise handshake timeouts are the behaviour under test, and short values are correct there. Verified the guard actually fails: a canary file with both banned shapes was flagged with file and line, and the suite went green again once it was removed. Full suite passes with all 18 cores saturated. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Close the guard's blind spot: named short timeouts A fifth flake landed on CI while the first guard was in review — GossipSyncBoardTests timing out at 1.03s — and the guard did not catch it, because the deadline was `TestConstants.shortTimeout` rather than a literal. A literals-only scan cannot see a short value behind a symbol, which is the more common way it is written: 81 wait sites used shortTimeout (1s) or defaultTimeout (5s), every one of them below the floor. Rather than guess which of those were safe to raise, all 81 were converted and the suite timed. Runtime went 15s -> 72s, which located the genuine negative waits precisely: ten tests that assert something does *not* happen and therefore always run their deadline out. Measurement instead of a heuristic, since a mis-guess in either direction is invisible — too short reintroduces the flake, too long silently costs a minute a run. Those 28 sites now use `TestConstants.negativeWaitWindow`, a named constant whose doc explains the inverted reasoning: for a negative wait, starvation can only make the assertion *more* likely to hold, so short is correct, and the name states the polarity instead of leaving a bare literal that reads like the mistake. Suite is back to 15.3s. The guard now also rejects `timeout: TestConstants.shortTimeout` and `defaultTimeout`, while accepting `negativeWaitWindow` by name. Re-verified with a canary carrying every banned shape — literal default, both named constants, and an elapsed-time upper bound. All four were flagged with file and line; the suite went green again on removal. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Delete shortTimeout now that nothing may use it The hygiene guard bans `TestConstants.shortTimeout` at every wait site and the last users were converted, so Periphery correctly flagged the constant itself as dead and failed CI. Remove it from both TestConstants copies; the banned-name entry stays so the symbol cannot quietly return. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
405 lines
17 KiB
Swift
405 lines
17 KiB
Swift
//
|
|
// PrekeyEndToEndTests.swift
|
|
// bitchat
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
import Testing
|
|
import Foundation
|
|
import CoreBluetooth
|
|
import BitFoundation
|
|
@testable import bitchat
|
|
|
|
/// Forward-secret courier flow through real BLEService instances: Bob gossips
|
|
/// a signed prekey bundle, Alice verifies and caches it, seals to a one-time
|
|
/// prekey instead of Bob's static key, Carol carries the opaque envelope, and
|
|
/// Bob opens it with the matching prekey private.
|
|
struct PrekeyEndToEndTests {
|
|
|
|
// MARK: - Helpers
|
|
|
|
private final class PacketTap {
|
|
private let lock = NSLock()
|
|
private var packets: [BitchatPacket] = []
|
|
|
|
func record(_ packet: BitchatPacket) {
|
|
lock.lock(); packets.append(packet); lock.unlock()
|
|
}
|
|
|
|
func first(ofType type: MessageType) -> BitchatPacket? {
|
|
lock.lock(); defer { lock.unlock() }
|
|
return packets.first { $0.type == type.rawValue }
|
|
}
|
|
}
|
|
|
|
private final class NoiseCaptureDelegate: BitchatDelegate {
|
|
private let lock = NSLock()
|
|
private var payloads: [(peerID: PeerID, type: NoisePayloadType, payload: Data)] = []
|
|
|
|
func didReceiveNoisePayload(from peerID: PeerID, type: NoisePayloadType, payload: Data, timestamp: Date) {
|
|
lock.lock(); payloads.append((peerID, type, payload)); lock.unlock()
|
|
}
|
|
|
|
func snapshot() -> [(peerID: PeerID, type: NoisePayloadType, payload: Data)] {
|
|
lock.lock(); defer { lock.unlock() }
|
|
return payloads
|
|
}
|
|
|
|
// Unused BitchatDelegate requirements.
|
|
func didReceiveMessage(_ message: BitchatMessage) {}
|
|
func didConnectToPeer(_ peerID: PeerID) {}
|
|
func didDisconnectFromPeer(_ peerID: PeerID) {}
|
|
func didUpdatePeerList(_ peers: [PeerID]) {}
|
|
func didUpdateBluetoothState(_ state: CBManagerState) {}
|
|
func didReceivePublicMessage(from peerID: PeerID, nickname: String, content: String, timestamp: Date, messageID: String?) {}
|
|
}
|
|
|
|
private func makeService() -> BLEService {
|
|
let keychain = MockKeychain()
|
|
let service = BLEService(
|
|
keychain: keychain,
|
|
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
|
|
identityManager: MockIdentityManager(keychain),
|
|
initializeBluetoothManagers: false
|
|
)
|
|
service.courierStore = CourierStore(persistsToDisk: false)
|
|
service.prekeyBundleStore = PrekeyBundleStore(persistsToDisk: false)
|
|
return service
|
|
}
|
|
|
|
private func preseedConnectedPeer(_ peer: BLEService, in service: BLEService) {
|
|
let packet = BitchatPacket(
|
|
type: MessageType.message.rawValue,
|
|
senderID: Data(hexString: peer.myPeerID.id) ?? Data(),
|
|
recipientID: nil,
|
|
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
|
|
payload: Data("ping".utf8),
|
|
signature: nil,
|
|
ttl: 1
|
|
)
|
|
service._test_handlePacket(packet, fromPeerID: peer.myPeerID)
|
|
}
|
|
|
|
/// Broadcast announce + prekey bundle from `peer` and return both packets.
|
|
private func captureAnnounceAndBundle(from peer: BLEService, tap: PacketTap) async throws -> (announce: BitchatPacket, bundle: BitchatPacket) {
|
|
peer.sendBroadcastAnnounce()
|
|
let published = await TestHelpers.waitUntil(
|
|
{ tap.first(ofType: .announce) != nil && tap.first(ofType: .prekeyBundle) != nil },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(published)
|
|
return (
|
|
announce: try #require(tap.first(ofType: .announce)),
|
|
bundle: try #require(tap.first(ofType: .prekeyBundle))
|
|
)
|
|
}
|
|
|
|
// MARK: - Tests
|
|
|
|
@Test func prekeySealedMailTravelsViaCourierAndOpens() async throws {
|
|
let alice = makeService()
|
|
let carol = makeService()
|
|
let bob = makeService()
|
|
carol.courierDepositPolicy = { _, _ in .favorite }
|
|
|
|
let bobDelegate = NoiseCaptureDelegate()
|
|
bob.delegate = bobDelegate
|
|
|
|
let aliceOut = PacketTap()
|
|
alice._test_onOutboundPacket = aliceOut.record
|
|
let carolOut = PacketTap()
|
|
carol._test_onOutboundPacket = carolOut.record
|
|
let bobOut = PacketTap()
|
|
bob._test_onOutboundPacket = bobOut.record
|
|
|
|
preseedConnectedPeer(carol, in: alice)
|
|
|
|
// 1. While Bob is still around, Alice hears his verified announce
|
|
// (binding his signing key) and his gossiped prekey bundle.
|
|
let (announce, bundlePacket) = try await captureAnnounceAndBundle(from: bob, tap: bobOut)
|
|
alice._test_handlePacket(announce, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
alice._test_handlePacket(bundlePacket, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
let cached = await TestHelpers.waitUntil(
|
|
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(cached)
|
|
|
|
// 2. Bob goes dark; Alice seals for him and deposits with Carol.
|
|
// The envelope must be v2: sealed to a one-time prekey.
|
|
#expect(alice.sendCourierMessage(
|
|
"burn after reading",
|
|
messageID: "prekey-msg-1",
|
|
recipientNoiseKey: bob.noiseStaticPublicKeyData(),
|
|
via: [carol.myPeerID]
|
|
))
|
|
let deposited = await TestHelpers.waitUntil(
|
|
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(deposited)
|
|
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
|
|
let sealedEnvelope = try #require(CourierEnvelope.decode(depositPacket.payload))
|
|
#expect(sealedEnvelope.prekeyID != nil)
|
|
|
|
// 3. Carol carries it (opaque, prekey or not).
|
|
carol._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, signingPublicKey: alice.noiseSigningPublicKeyData())
|
|
let carried = await TestHelpers.waitUntil(
|
|
{ !carol.courierStore.isEmpty },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(carried)
|
|
|
|
// 4. Bob resurfaces near Carol → handover, and the v2 discriminator
|
|
// survives the store round-trip.
|
|
bob.sendBroadcastAnnounce()
|
|
let reannounced = await TestHelpers.waitUntil(
|
|
{ bobOut.first(ofType: .announce) != nil },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(reannounced)
|
|
let handoverTrigger = try #require(bobOut.first(ofType: .announce))
|
|
carol._test_handlePacket(handoverTrigger, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
let handedOver = await TestHelpers.waitUntil(
|
|
{ carolOut.first(ofType: .courierEnvelope) != nil },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(handedOver)
|
|
let handoverPacket = try #require(carolOut.first(ofType: .courierEnvelope))
|
|
let handedEnvelope = try #require(CourierEnvelope.decode(handoverPacket.payload))
|
|
#expect(handedEnvelope.prekeyID == sealedEnvelope.prekeyID)
|
|
|
|
// 5. Bob opens it with the matching one-time prekey private and sees
|
|
// Alice as the authenticated sender.
|
|
bob._test_handlePacket(handoverPacket, fromPeerID: carol.myPeerID)
|
|
let received = await TestHelpers.waitUntil(
|
|
{ !bobDelegate.snapshot().isEmpty },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(received)
|
|
|
|
let delivered = try #require(bobDelegate.snapshot().first)
|
|
#expect(delivered.type == .privateMessage)
|
|
#expect(delivered.peerID == PeerID(hexData: alice.noiseStaticPublicKeyData()))
|
|
let message = try #require(PrivateMessagePacket.decode(from: delivered.payload))
|
|
#expect(message.messageID == "prekey-msg-1")
|
|
#expect(message.content == "burn after reading")
|
|
|
|
// 6. Redelivery tolerance: the same envelope arriving via another
|
|
// packet (spray-and-wait) still decrypts inside the prekey grace
|
|
// window (asserted at the crypto layer in NoisePrekeyTests), but
|
|
// the duplicate is absorbed before delivery — the receiver dedups
|
|
// on the inner message ID, so redundant courier copies never
|
|
// re-deliver (or re-ack) the same message.
|
|
let redelivery = BitchatPacket(
|
|
type: MessageType.courierEnvelope.rawValue,
|
|
senderID: Data(hexString: carol.myPeerID.id) ?? Data(),
|
|
recipientID: handoverPacket.recipientID,
|
|
timestamp: handoverPacket.timestamp + 1,
|
|
payload: handoverPacket.payload,
|
|
signature: nil,
|
|
ttl: 1
|
|
)
|
|
bob._test_handlePacket(redelivery, fromPeerID: carol.myPeerID)
|
|
let redelivered = await TestHelpers.waitUntil(
|
|
{ bobDelegate.snapshot().count == 2 },
|
|
timeout: TestConstants.negativeWaitWindow
|
|
)
|
|
#expect(!redelivered)
|
|
#expect(bobDelegate.snapshot().count == 1)
|
|
}
|
|
|
|
@Test func withoutBundleSealingFallsBackToStatic() async throws {
|
|
let alice = makeService()
|
|
let bob = makeService()
|
|
|
|
let bobDelegate = NoiseCaptureDelegate()
|
|
bob.delegate = bobDelegate
|
|
let aliceOut = PacketTap()
|
|
alice._test_onOutboundPacket = aliceOut.record
|
|
|
|
// Bob is a connected "courier" who happens to be the recipient: the
|
|
// envelope reaches him directly and the recipient tag matches.
|
|
preseedConnectedPeer(bob, in: alice)
|
|
|
|
// Alice never saw a bundle for Bob → v1 static-sealed envelope.
|
|
#expect(alice.sendCourierMessage(
|
|
"plain static seal",
|
|
messageID: "static-msg-1",
|
|
recipientNoiseKey: bob.noiseStaticPublicKeyData(),
|
|
via: [bob.myPeerID]
|
|
))
|
|
let deposited = await TestHelpers.waitUntil(
|
|
{ aliceOut.first(ofType: .courierEnvelope) != nil },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(deposited)
|
|
let depositPacket = try #require(aliceOut.first(ofType: .courierEnvelope))
|
|
let envelope = try #require(CourierEnvelope.decode(depositPacket.payload))
|
|
#expect(envelope.prekeyID == nil)
|
|
|
|
// Bob opens the v1 envelope exactly as before the prekey change.
|
|
// (No preseed: Alice is absent from Bob's mesh, so the sender should
|
|
// resolve to her full noise-key ID like the courier case.)
|
|
bob._test_handlePacket(depositPacket, fromPeerID: alice.myPeerID, preseedPeer: false)
|
|
let received = await TestHelpers.waitUntil(
|
|
{ !bobDelegate.snapshot().isEmpty },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(received)
|
|
let delivered = try #require(bobDelegate.snapshot().first)
|
|
#expect(delivered.peerID == PeerID(hexData: alice.noiseStaticPublicKeyData()))
|
|
let message = try #require(PrivateMessagePacket.decode(from: delivered.payload))
|
|
#expect(message.content == "plain static seal")
|
|
}
|
|
|
|
@Test func unverifiableBundleIsIgnored() async throws {
|
|
let alice = makeService()
|
|
let bob = makeService()
|
|
|
|
let bobOut = PacketTap()
|
|
bob._test_onOutboundPacket = bobOut.record
|
|
|
|
// Alice receives Bob's bundle but never saw a verified announce, so
|
|
// no signing key is bound to his noise key: the bundle must not be
|
|
// cached or enter Alice's gossip store.
|
|
let (_, bundlePacket) = try await captureAnnounceAndBundle(from: bob, tap: bobOut)
|
|
alice._test_handlePacket(bundlePacket, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
let cached = await TestHelpers.waitUntil(
|
|
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
|
timeout: TestConstants.negativeWaitWindow
|
|
)
|
|
#expect(!cached)
|
|
}
|
|
|
|
@Test func forgedBundleSignatureIsRejected() async throws {
|
|
let alice = makeService()
|
|
let bob = makeService()
|
|
|
|
let bobOut = PacketTap()
|
|
bob._test_onOutboundPacket = bobOut.record
|
|
|
|
let (announce, bundlePacket) = try await captureAnnounceAndBundle(from: bob, tap: bobOut)
|
|
alice._test_handlePacket(announce, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
// Mallory tampers with the gossiped bundle in flight.
|
|
let bundle = try #require(PrekeyBundle.decode(bundlePacket.payload))
|
|
var forgedSignature = bundle.signature
|
|
forgedSignature[0] ^= 0x01
|
|
let forged = PrekeyBundle(
|
|
noiseStaticPublicKey: bundle.noiseStaticPublicKey,
|
|
prekeys: bundle.prekeys,
|
|
generatedAt: bundle.generatedAt,
|
|
signature: forgedSignature
|
|
)
|
|
let forgedPacket = BitchatPacket(
|
|
type: MessageType.prekeyBundle.rawValue,
|
|
senderID: bundlePacket.senderID,
|
|
recipientID: nil,
|
|
timestamp: bundlePacket.timestamp,
|
|
payload: try #require(forged.encode()),
|
|
signature: bundlePacket.signature,
|
|
ttl: bundlePacket.ttl
|
|
)
|
|
alice._test_handlePacket(forgedPacket, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
let cached = await TestHelpers.waitUntil(
|
|
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
|
timeout: TestConstants.negativeWaitWindow
|
|
)
|
|
#expect(!cached)
|
|
}
|
|
|
|
@Test func verifiedBundleEntersGossipStore() async throws {
|
|
let alice = makeService()
|
|
let bob = makeService()
|
|
|
|
let bobOut = PacketTap()
|
|
bob._test_onOutboundPacket = bobOut.record
|
|
|
|
let (announce, bundlePacket) = try await captureAnnounceAndBundle(from: bob, tap: bobOut)
|
|
alice._test_handlePacket(announce, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
alice._test_handlePacket(bundlePacket, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
let cached = await TestHelpers.waitUntil(
|
|
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
|
timeout: TestConstants.settleTimeout
|
|
)
|
|
#expect(cached)
|
|
// The verified bundle now participates in Alice's sync rounds.
|
|
#expect(alice._test_hasGossipPrekeyBundle(for: bob.myPeerID))
|
|
}
|
|
|
|
@Test func spoofedSenderPrekeyBundleIsRejected() async throws {
|
|
let alice = makeService()
|
|
let bob = makeService()
|
|
|
|
let bobOut = PacketTap()
|
|
bob._test_onOutboundPacket = bobOut.record
|
|
|
|
let (announce, bundlePacket) = try await captureAnnounceAndBundle(from: bob, tap: bobOut)
|
|
alice._test_handlePacket(announce, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
// A relay re-broadcasts Bob's genuine bundle under a fabricated sender
|
|
// ID (the DoS that would multiply cache/gossip entries and exhaust the
|
|
// per-owner cap). Attribution is by the bundle's own key and the outer
|
|
// signature is bound to Bob's sender ID, so the spoof is dropped — no
|
|
// cache entry, and no gossip entry under either the fake or real ID.
|
|
let fakeSender = Data((0..<8).map { _ in UInt8.random(in: 0...255) })
|
|
let spoofed = BitchatPacket(
|
|
type: MessageType.prekeyBundle.rawValue,
|
|
senderID: fakeSender,
|
|
recipientID: nil,
|
|
timestamp: bundlePacket.timestamp + 5_000,
|
|
payload: bundlePacket.payload,
|
|
signature: bundlePacket.signature,
|
|
ttl: bundlePacket.ttl
|
|
)
|
|
alice._test_handlePacket(spoofed, fromPeerID: PeerID(hexData: fakeSender), preseedPeer: false)
|
|
|
|
let cached = await TestHelpers.waitUntil(
|
|
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
|
timeout: TestConstants.negativeWaitWindow
|
|
)
|
|
#expect(!cached)
|
|
#expect(!alice._test_hasGossipPrekeyBundle(for: bob.myPeerID))
|
|
#expect(!alice._test_hasGossipPrekeyBundle(for: PeerID(hexData: fakeSender)))
|
|
}
|
|
|
|
@Test func replayedPrekeyBundleWithFreshTimestampIsRejected() async throws {
|
|
let alice = makeService()
|
|
let bob = makeService()
|
|
|
|
let bobOut = PacketTap()
|
|
bob._test_onOutboundPacket = bobOut.record
|
|
|
|
let (announce, bundlePacket) = try await captureAnnounceAndBundle(from: bob, tap: bobOut)
|
|
alice._test_handlePacket(announce, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
// Rewriting the outer timestamp (to defeat the freshness window)
|
|
// invalidates the packet signature, which covers senderID + timestamp.
|
|
let replay = BitchatPacket(
|
|
type: MessageType.prekeyBundle.rawValue,
|
|
senderID: bundlePacket.senderID,
|
|
recipientID: nil,
|
|
timestamp: bundlePacket.timestamp + 5_000,
|
|
payload: bundlePacket.payload,
|
|
signature: bundlePacket.signature,
|
|
ttl: bundlePacket.ttl
|
|
)
|
|
alice._test_handlePacket(replay, fromPeerID: bob.myPeerID, preseedPeer: false)
|
|
|
|
let cached = await TestHelpers.waitUntil(
|
|
{ alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData()) },
|
|
timeout: TestConstants.negativeWaitWindow
|
|
)
|
|
#expect(!cached)
|
|
#expect(!alice._test_hasGossipPrekeyBundle(for: bob.myPeerID))
|
|
}
|
|
}
|