diff --git a/bitchat/Noise/NoiseRateLimiter.swift b/bitchat/Noise/NoiseRateLimiter.swift index db10e960..a8c9a874 100644 --- a/bitchat/Noise/NoiseRateLimiter.swift +++ b/bitchat/Noise/NoiseRateLimiter.swift @@ -17,13 +17,13 @@ final class NoiseRateLimiter { mutating func allow( peerID: PeerID, + now: Date, window: TimeInterval, globalLimit: Int, perPeerLimit: Int, label: String, unit: String ) -> Bool { - let now = Date() let cutoff = now.addingTimeInterval(-window) global = global.filter { $0 > cutoff } @@ -44,6 +44,18 @@ final class NoiseRateLimiter { return true } + /// Drops peers whose timestamps have all aged out of their window. + /// A peer that never comes back otherwise keeps its entry for the + /// lifetime of the process. + mutating func prune(now: Date, window: TimeInterval) { + let cutoff = now.addingTimeInterval(-window) + global = global.filter { $0 > cutoff } + byPeer = byPeer.compactMapValues { timestamps in + let recent = timestamps.filter { $0 > cutoff } + return recent.isEmpty ? nil : recent + } + } + mutating func removeAll() { global.removeAll() byPeer.removeAll() @@ -53,12 +65,37 @@ final class NoiseRateLimiter { private var handshakes = SlidingWindow() private var messages = SlidingWindow() private let lock = NSLock() + private var lastPrune: Date = .distantPast + + /// Sweeping every peer on every admission would put an O(peers) walk on the + /// message path. Once a second is frequent enough to keep both maps to + /// peers seen inside their own windows. + private static let pruneInterval: TimeInterval = 1 + + /// Clock seam. Injected so time-dependent retention can be tested without + /// threading `now` through every call site. + private let now: () -> Date + + init(now: @escaping () -> Date = Date.init) { + self.now = now + } + + var trackedHandshakePeerCount: Int { + lock.withLock { handshakes.byPeer.count } + } + + var trackedMessagePeerCount: Int { + lock.withLock { messages.byPeer.count } + } func allowHandshake(from peerID: PeerID) -> Bool { lock.withLock { - handshakes.allow( + let now = self.now() + pruneStalePeersLocked(now: now) + return handshakes.allow( peerID: peerID, - window: 60, + now: now, + window: NoiseSecurityConstants.handshakeRateLimitWindow, globalLimit: NoiseSecurityConstants.maxGlobalHandshakesPerMinute, perPeerLimit: NoiseSecurityConstants.maxHandshakesPerMinute, label: "handshake", @@ -69,9 +106,12 @@ final class NoiseRateLimiter { func allowMessage(from peerID: PeerID) -> Bool { lock.withLock { - messages.allow( + let now = self.now() + pruneStalePeersLocked(now: now) + return messages.allow( peerID: peerID, - window: 1, + now: now, + window: NoiseSecurityConstants.messageRateLimitWindow, globalLimit: NoiseSecurityConstants.maxGlobalMessagesPerSecond, perPeerLimit: NoiseSecurityConstants.maxMessagesPerSecond, label: "message", @@ -80,6 +120,17 @@ final class NoiseRateLimiter { } } + /// Must be called with the lock held. + private func pruneStalePeersLocked(now: Date) { + let elapsed = now.timeIntervalSince(lastPrune) + // A backwards clock step parks lastPrune in the future; without the + // `elapsed < 0` arm pruning would stop until wall time catches up. + guard elapsed >= Self.pruneInterval || elapsed < 0 else { return } + lastPrune = now + handshakes.prune(now: now, window: NoiseSecurityConstants.handshakeRateLimitWindow) + messages.prune(now: now, window: NoiseSecurityConstants.messageRateLimitWindow) + } + func reset(for peerID: PeerID) { lock.withLock { handshakes.byPeer.removeValue(forKey: peerID) diff --git a/bitchat/Noise/NoiseSecurityConstants.swift b/bitchat/Noise/NoiseSecurityConstants.swift index c6372211..fe0dc7d1 100644 --- a/bitchat/Noise/NoiseSecurityConstants.swift +++ b/bitchat/Noise/NoiseSecurityConstants.swift @@ -68,6 +68,8 @@ enum NoiseSecurityConstants { static let maxMessagesPerSession: UInt64 = 1_000_000_000 // 1 billion messages // Rate limiting + static let handshakeRateLimitWindow: TimeInterval = 60 + static let messageRateLimitWindow: TimeInterval = 1 static let maxHandshakesPerMinute = 10 static let maxMessagesPerSecond = 100 diff --git a/bitchatTests/Noise/NoiseRateLimiterTests.swift b/bitchatTests/Noise/NoiseRateLimiterTests.swift index 623fe22e..38ed0292 100644 --- a/bitchatTests/Noise/NoiseRateLimiterTests.swift +++ b/bitchatTests/Noise/NoiseRateLimiterTests.swift @@ -67,4 +67,124 @@ final class NoiseRateLimiterTests: XCTestCase { private func makePeerID(_ value: Int) -> PeerID { PeerID(str: String(format: "%016x", value)) } + + // MARK: - Peer-map retention + + /// Drives the limiter's clock so window expiry is observable. + private final class TestClock: @unchecked Sendable { + private let lock = NSLock() + private var _now: Date + init(_ start: Date) { _now = start } + var now: Date { lock.withLock { _now } } + func advance(_ seconds: TimeInterval) { lock.withLock { _now += seconds } } + } + + func test_handshakeMap_doesNotRetainPeersPastTheirWindow() { + let clock = TestClock(Date(timeIntervalSince1970: 10_000)) + let limiter = NoiseRateLimiter(now: { clock.now }) + + // A burst of one-shot peers, each handshaking once and never returning. + // Stay inside the global per-minute budget so every one is admitted. + let peerCount = 20 + for index in 0..