1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//! Keyed sliding-window rate limiter (WEFT-148).
//!
//! Used for DoS protection on:
//! - [`crate::cluster::ClusterMembership::add_peer`] — per source
//! - [`crate::governance::GovernanceEngine::evaluate`] — per principal
//!
//! Thresholds are fully configurable via [`RateLimitConfig`]. A limit of
//! `0` disables enforcement (always allow).
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// Configuration for a keyed rate limiter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RateLimitConfig {
/// Maximum events allowed per key within [`Self::window`].
///
/// `0` means unlimited (rate limiting disabled).
pub max_per_window: u32,
/// Sliding window length.
pub window: Duration,
}
impl RateLimitConfig {
/// Disabled rate limiting (always allow).
pub const fn unlimited() -> Self {
Self {
max_per_window: 0,
window: Duration::from_secs(0),
}
}
/// `max` events per key per minute.
pub const fn per_minute(max: u32) -> Self {
Self {
max_per_window: max,
window: Duration::from_secs(60),
}
}
/// `max` events per key per second.
pub const fn per_second(max: u32) -> Self {
Self {
max_per_window: max,
window: Duration::from_secs(1),
}
}
/// Whether this config enforces a limit.
pub const fn is_enabled(&self) -> bool {
self.max_per_window > 0
}
}
/// Default peer-add limit: 1 addition per source per 100 ms
/// (preserves the pre-WEFT-148 aggressiveness, but keyed per source).
pub const DEFAULT_PEER_ADD_RATE: RateLimitConfig = RateLimitConfig {
max_per_window: 1,
window: Duration::from_millis(100),
};
/// Default governance-evaluation limit: 256 evaluations per principal
/// per second. High enough for normal agent tool loops; low enough to
/// stop a flood from a single principal.
pub const DEFAULT_GOVERNANCE_EVAL_RATE: RateLimitConfig = RateLimitConfig {
max_per_window: 256,
window: Duration::from_secs(1),
};
/// Thread-safe sliding-window rate limiter keyed by an arbitrary string
/// (source address, principal / agent id, etc.).
pub struct KeyedRateLimiter {
config: Mutex<RateLimitConfig>,
/// Per-key timestamps of recent allowed events (oldest first).
windows: Mutex<HashMap<String, Vec<Instant>>>,
}
impl KeyedRateLimiter {
/// Create a limiter with the given config.
pub fn new(config: RateLimitConfig) -> Self {
Self {
config: Mutex::new(config),
windows: Mutex::new(HashMap::new()),
}
}
/// Create an unlimited (always-allow) limiter.
pub fn unlimited() -> Self {
Self::new(RateLimitConfig::unlimited())
}
/// Current configuration snapshot.
pub fn config(&self) -> RateLimitConfig {
*self
.config
.lock()
.unwrap_or_else(|e| e.into_inner())
}
/// Replace the configuration at runtime.
///
/// Does not clear existing windows; the next `check` uses the new
/// thresholds against remaining timestamps.
pub fn set_config(&self, config: RateLimitConfig) {
*self
.config
.lock()
.unwrap_or_else(|e| e.into_inner()) = config;
}
/// Check whether an event for `key` is allowed.
///
/// On allow, records the event. On deny, does not record (so a
/// denied flood does not permanently fill the window).
///
/// Returns `true` if allowed, `false` if rate-limited.
pub fn check(&self, key: &str) -> bool {
let config = self.config();
if !config.is_enabled() {
return true;
}
let now = Instant::now();
let mut map = match self.windows.lock() {
Ok(g) => g,
// Fail open on poisoned lock — DoS protection must not become
// a hard-fault denial of service itself.
Err(_) => return true,
};
let entry = map.entry(key.to_owned()).or_default();
entry.retain(|ts| now.duration_since(*ts) < config.window);
if entry.len() >= config.max_per_window as usize {
return false;
}
entry.push(now);
true
}
/// Number of tracked keys (for tests / metrics).
pub fn tracked_keys(&self) -> usize {
self.windows
.lock()
.map(|m| m.len())
.unwrap_or(0)
}
/// Clear all recorded windows (tests / admin reset).
pub fn reset(&self) {
if let Ok(mut m) = self.windows.lock() {
m.clear();
}
}
}
impl Default for KeyedRateLimiter {
fn default() -> Self {
Self::new(RateLimitConfig::per_minute(60))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unlimited_always_allows() {
let lim = KeyedRateLimiter::unlimited();
for _ in 0..100 {
assert!(lim.check("any"));
}
}
#[test]
fn blocks_after_quota() {
let lim = KeyedRateLimiter::new(RateLimitConfig {
max_per_window: 3,
window: Duration::from_secs(60),
});
assert!(lim.check("a"));
assert!(lim.check("a"));
assert!(lim.check("a"));
assert!(!lim.check("a"));
}
#[test]
fn separate_keys_independent() {
let lim = KeyedRateLimiter::new(RateLimitConfig {
max_per_window: 1,
window: Duration::from_secs(60),
});
assert!(lim.check("source-1"));
assert!(!lim.check("source-1"));
assert!(lim.check("source-2"));
}
#[test]
fn set_config_disables() {
let lim = KeyedRateLimiter::new(RateLimitConfig {
max_per_window: 1,
window: Duration::from_secs(60),
});
assert!(lim.check("x"));
assert!(!lim.check("x"));
lim.set_config(RateLimitConfig::unlimited());
assert!(lim.check("x"));
}
#[test]
fn default_constants_enabled() {
assert!(DEFAULT_PEER_ADD_RATE.is_enabled());
assert!(DEFAULT_GOVERNANCE_EVAL_RATE.is_enabled());
assert_eq!(DEFAULT_PEER_ADD_RATE.max_per_window, 1);
assert_eq!(DEFAULT_GOVERNANCE_EVAL_RATE.max_per_window, 256);
}
}