mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-29 08:29:22 +00:00
replay fix/noise-rate-limiter-unbounded-peer-maps onto current main (#1670)
History rewrite left this branch with no merge-base, so stale peer windows are pruned on the current sliding-window limiter.
This commit is contained in:
1 parent
202e13cddf
commit
22451ca64c
3 files changed
+178
-5
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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..<peerCount {
|
||||
XCTAssertTrue(limiter.allowHandshake(from: makePeerID(index + 1)))
|
||||
}
|
||||
XCTAssertEqual(limiter.trackedHandshakePeerCount, peerCount)
|
||||
|
||||
// Past the one-minute handshake window, none of them is still relevant.
|
||||
clock.advance(NoiseSecurityConstants.handshakeRateLimitWindow + 1)
|
||||
XCTAssertTrue(limiter.allowHandshake(from: makePeerID(200)))
|
||||
|
||||
XCTAssertEqual(
|
||||
limiter.trackedHandshakePeerCount,
|
||||
1,
|
||||
"departed peers must not be retained once their handshake window has passed"
|
||||
)
|
||||
}
|
||||
|
||||
func test_messageMap_doesNotRetainPeersPastTheirWindow() {
|
||||
let clock = TestClock(Date(timeIntervalSince1970: 20_000))
|
||||
let limiter = NoiseRateLimiter(now: { clock.now })
|
||||
|
||||
let peerCount = 10
|
||||
for index in 0..<peerCount {
|
||||
XCTAssertTrue(limiter.allowMessage(from: makePeerID(index + 1)))
|
||||
}
|
||||
XCTAssertEqual(limiter.trackedMessagePeerCount, peerCount)
|
||||
|
||||
clock.advance(NoiseSecurityConstants.messageRateLimitWindow + 1)
|
||||
XCTAssertTrue(limiter.allowMessage(from: makePeerID(200)))
|
||||
|
||||
XCTAssertEqual(
|
||||
limiter.trackedMessagePeerCount,
|
||||
1,
|
||||
"departed peers must not be retained once their message window has passed"
|
||||
)
|
||||
}
|
||||
|
||||
func test_pruningUsesEachMapsWindow() {
|
||||
let clock = TestClock(Date(timeIntervalSince1970: 25_000))
|
||||
let limiter = NoiseRateLimiter(now: { clock.now })
|
||||
let peerID = makePeerID(1)
|
||||
XCTAssertTrue(limiter.allowHandshake(from: peerID))
|
||||
XCTAssertTrue(limiter.allowMessage(from: peerID))
|
||||
|
||||
clock.advance(NoiseSecurityConstants.messageRateLimitWindow)
|
||||
XCTAssertTrue(limiter.allowHandshake(from: makePeerID(2)))
|
||||
XCTAssertEqual(limiter.trackedMessagePeerCount, 0)
|
||||
XCTAssertEqual(limiter.trackedHandshakePeerCount, 2)
|
||||
|
||||
clock.advance(NoiseSecurityConstants.handshakeRateLimitWindow)
|
||||
XCTAssertTrue(limiter.allowMessage(from: peerID))
|
||||
XCTAssertEqual(limiter.trackedHandshakePeerCount, 0)
|
||||
XCTAssertEqual(limiter.trackedMessagePeerCount, 1)
|
||||
}
|
||||
|
||||
func test_pruningKeepsAPeerStillInsideItsWindow() {
|
||||
// The counterpart: pruning must not discard a peer whose budget is still
|
||||
// being enforced, or the limit becomes trivially bypassable by waiting.
|
||||
let clock = TestClock(Date(timeIntervalSince1970: 30_000))
|
||||
let limiter = NoiseRateLimiter(now: { clock.now })
|
||||
let peerID = makePeerID(7)
|
||||
|
||||
for _ in 0..<NoiseSecurityConstants.maxHandshakesPerMinute {
|
||||
XCTAssertTrue(limiter.allowHandshake(from: peerID))
|
||||
}
|
||||
XCTAssertFalse(limiter.allowHandshake(from: peerID))
|
||||
|
||||
// Well past the prune interval, but well inside the one-minute window.
|
||||
clock.advance(5)
|
||||
XCTAssertFalse(
|
||||
limiter.allowHandshake(from: peerID),
|
||||
"a peer still inside its window must stay rate limited across a prune"
|
||||
)
|
||||
XCTAssertEqual(limiter.trackedHandshakePeerCount, 1)
|
||||
}
|
||||
|
||||
func test_pruneRecoversAfterBackwardClockStep() {
|
||||
let clock = TestClock(Date(timeIntervalSince1970: 40_000))
|
||||
let limiter = NoiseRateLimiter(now: { clock.now })
|
||||
|
||||
// Plant lastPrune ahead of wall time.
|
||||
XCTAssertTrue(limiter.allowHandshake(from: makePeerID(1)))
|
||||
clock.advance(-100) // now = 39_900; lastPrune = 40_000
|
||||
|
||||
let peerCount = 20
|
||||
for index in 0..<peerCount {
|
||||
XCTAssertTrue(limiter.allowHandshake(from: makePeerID(index + 10)))
|
||||
}
|
||||
|
||||
// Expire that cohort while lastPrune is still in the future without
|
||||
// the fix (elapsed stays negative). With the fix, prune runs and the
|
||||
// aged cohort is reclaimed.
|
||||
clock.advance(NoiseSecurityConstants.handshakeRateLimitWindow + 1) // now = 39_961
|
||||
XCTAssertTrue(limiter.allowHandshake(from: makePeerID(200)))
|
||||
|
||||
XCTAssertLessThanOrEqual(
|
||||
limiter.trackedHandshakePeerCount,
|
||||
2,
|
||||
"a backwards clock step must not latch pruning off"
|
||||
)
|
||||
XCTAssertGreaterThanOrEqual(limiter.trackedHandshakePeerCount, 1)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user