Skip to main content

ledger_engine/
guard.rs

1//! Request limits per client, like Clio's DOS guard.
2//!
3//! Each client (IP address) has, per sweep interval, a budget of weighted
4//! requests and of response bytes, and a cap on connections open at once
5//! (HTTP requests in progress and WebSocket sessions). Past either budget, or
6//! at the connection cap, the client gets `slowDown` until the next sweep: over
7//! HTTP as status 503 with the error in the body, as Clio does, over
8//! WebSocket as an error response. Whitelisted addresses are not counted.
9//!
10//! Behind a proxy every request comes from the proxy's address. Only for a
11//! peer listed as a trusted proxy is the client taken from the request: from
12//! `CF-Connecting-IP` (Cloudflare), else the last `for=` of `Forwarded` (as
13//! Clio), else the first address of `X-Forwarded-For`. From anyone else these
14//! headers are ignored, so a client can't pose as another.
15//!
16//! Off unless configured: with no budgets set nothing is counted.
17
18use std::collections::HashMap;
19use std::net::IpAddr;
20use std::sync::Mutex;
21use std::time::Duration;
22
23use axum::http::HeaderMap;
24use serde_json::{Map, Value};
25
26/// Limits; `None` means no limit of that kind.
27#[derive(Debug, Clone, Default)]
28pub struct GuardConfig {
29    /// Weighted requests per client per sweep.
30    pub max_requests: Option<u64>,
31    /// Response bytes per client per sweep.
32    pub max_bytes: Option<u64>,
33    /// Connections per client open at once.
34    pub max_connections: Option<u32>,
35    /// Milliseconds of handling that count as one more request against
36    /// `max_requests`, so that a request that reads much cold history costs
37    /// more than one that is answered from the cache.
38    pub work_ms: Option<u64>,
39    pub sweep: Duration,
40    /// Addresses and networks that are never limited.
41    pub whitelist: Vec<Net>,
42    /// Peers whose forwarding headers name the real client.
43    pub trusted_proxies: Vec<Net>,
44}
45
46impl GuardConfig {
47    pub fn enabled(&self) -> bool {
48        self.max_requests.is_some() || self.max_bytes.is_some() || self.max_connections.is_some()
49    }
50}
51
52/// An address or a network in CIDR notation.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Net {
55    addr: IpAddr,
56    bits: u8,
57}
58
59impl std::str::FromStr for Net {
60    type Err = String;
61
62    fn from_str(s: &str) -> Result<Net, String> {
63        let (a, bits) = match s.split_once('/') {
64            Some((a, b)) => (a, Some(b)),
65            None => (s, None),
66        };
67        let addr: IpAddr = a
68            .trim()
69            .parse()
70            .map_err(|_| format!("not an address: {s}"))?;
71        let max = if addr.is_ipv4() { 32 } else { 128 };
72        let bits = match bits {
73            Some(b) => b
74                .trim()
75                .parse::<u8>()
76                .ok()
77                .filter(|b| *b <= max)
78                .ok_or_else(|| format!("bad prefix length: {s}"))?,
79            None => max,
80        };
81        Ok(Net { addr, bits })
82    }
83}
84
85impl Net {
86    pub fn contains(&self, ip: IpAddr) -> bool {
87        let ip = canonical(ip);
88        match (self.addr, ip) {
89            (IpAddr::V4(n), IpAddr::V4(a)) => prefix(
90                u128::from(u32::from(n)) << 96,
91                u128::from(u32::from(a)) << 96,
92                self.bits,
93            ),
94            (IpAddr::V6(n), IpAddr::V6(a)) => prefix(u128::from(n), u128::from(a), self.bits),
95            _ => false,
96        }
97    }
98}
99
100fn prefix(n: u128, a: u128, bits: u8) -> bool {
101    if bits == 0 {
102        return true;
103    }
104    let mask = u128::MAX << (128 - u32::from(bits));
105    n & mask == a & mask
106}
107
108/// An IPv4 address seen as IPv6 (`::ffff:a.b.c.d`) is the IPv4 address.
109fn canonical(ip: IpAddr) -> IpAddr {
110    match ip {
111        IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4),
112        v4 => v4,
113    }
114}
115
116/// How much a request counts against the budget: reads that walk many objects
117/// or build proofs count more.
118pub fn weight(method: &str, params: &Map<String, Value>) -> u64 {
119    let flag = |k: &str| params.get(k).and_then(Value::as_bool).unwrap_or(false);
120    match method {
121        "proof_ledger" | "proof_tx" | "proof_entry" => 10,
122        "ledger_data" => 5,
123        "ledger" if flag("transactions") && flag("expand") => 5,
124        "account_tx" | "nft_history" | "book_changes" | "nfts_by_issuer" => 2,
125        // The work falls on a node, which doesn't limit us.
126        _ if crate::forward::forwarded(method, params) => 3,
127        _ => 1,
128    }
129}
130
131#[derive(Debug, Default, Clone, Copy)]
132struct Usage {
133    requests: u64,
134    bytes: u64,
135    connections: u32,
136}
137
138#[derive(Debug, Default)]
139pub struct Guard {
140    config: GuardConfig,
141    usage: Mutex<HashMap<IpAddr, Usage>>,
142}
143
144/// An open connection; closing it gives the slot back.
145#[derive(Debug)]
146pub struct Connection<'a> {
147    guard: &'a Guard,
148    ip: Option<IpAddr>,
149}
150
151impl Drop for Connection<'_> {
152    fn drop(&mut self) {
153        if let Some(ip) = self.ip {
154            let mut u = self.guard.lock();
155            if let Some(e) = u.get_mut(&ip) {
156                e.connections = e.connections.saturating_sub(1);
157            }
158        }
159    }
160}
161
162impl Guard {
163    pub fn new(config: GuardConfig) -> Guard {
164        Guard {
165            config,
166            usage: Mutex::default(),
167        }
168    }
169
170    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<IpAddr, Usage>> {
171        self.usage.lock().unwrap_or_else(|p| p.into_inner())
172    }
173
174    fn counted(&self, ip: IpAddr) -> bool {
175        self.config.enabled() && !self.config.whitelist.iter().any(|n| n.contains(ip))
176    }
177
178    /// The client behind a connection from `peer`.
179    pub fn client(&self, peer: IpAddr, headers: &HeaderMap) -> IpAddr {
180        let peer = canonical(peer);
181        if !self.config.trusted_proxies.iter().any(|n| n.contains(peer)) {
182            return peer;
183        }
184        forwarded_client(headers).map_or(peer, canonical)
185    }
186
187    fn within(&self, u: &Usage) -> bool {
188        self.config.max_requests.is_none_or(|m| u.requests <= m)
189            && self.config.max_bytes.is_none_or(|m| u.bytes <= m)
190    }
191
192    /// Opens a connection for `ip`; `None` if the client is at its cap or
193    /// over budget.
194    pub fn connect(&self, ip: IpAddr) -> Option<Connection<'_>> {
195        if !self.counted(ip) {
196            return Some(Connection {
197                guard: self,
198                ip: None,
199            });
200        }
201        let mut all = self.lock();
202        let u = all.entry(ip).or_default();
203        if !self.within(u)
204            || self
205                .config
206                .max_connections
207                .is_some_and(|m| u.connections >= m)
208        {
209            return None;
210        }
211        u.connections += 1;
212        Some(Connection {
213            guard: self,
214            ip: Some(ip),
215        })
216    }
217
218    /// Counts a request; `false` if the client is over budget with it.
219    pub fn request(&self, ip: IpAddr, weight: u64) -> bool {
220        if !self.counted(ip) {
221            return true;
222        }
223        let mut all = self.lock();
224        let u = all.entry(ip).or_default();
225        if !self.within(u) {
226            return false;
227        }
228        u.requests += weight;
229        self.within(u)
230    }
231
232    /// Counts the time a request of `ip` took to handle against its request
233    /// budget: one more request per `work_ms`. The next request over budget
234    /// gets `slowDown`.
235    pub fn worked(&self, ip: IpAddr, spent: Duration) {
236        let Some(per) = self.config.work_ms.filter(|m| *m > 0) else {
237            return;
238        };
239        let extra = spent.as_millis() as u64 / per;
240        if extra > 0 && self.counted(ip) {
241            self.lock().entry(ip).or_default().requests += extra;
242        }
243    }
244
245    /// Counts the bytes of a response sent to `ip`.
246    pub fn sent(&self, ip: IpAddr, bytes: usize) {
247        if self.counted(ip) {
248            self.lock().entry(ip).or_default().bytes += bytes as u64;
249        }
250    }
251
252    /// Starts a new interval: budgets are full again, open connections stay.
253    pub fn sweep(&self) {
254        let mut all = self.lock();
255        all.retain(|_, u| u.connections > 0);
256        for u in all.values_mut() {
257            u.requests = 0;
258            u.bytes = 0;
259        }
260    }
261
262    pub fn sweep_every(&self) -> Option<Duration> {
263        self.config.enabled().then_some(self.config.sweep)
264    }
265}
266
267/// The client a proxy names in its headers.
268fn forwarded_client(headers: &HeaderMap) -> Option<IpAddr> {
269    let text = |name: &str| headers.get(name).and_then(|v| v.to_str().ok());
270    if let Some(ip) = text("cf-connecting-ip").and_then(|v| v.trim().parse().ok()) {
271        return Some(ip);
272    }
273    if let Some(v) = text("forwarded") {
274        let lower = v.to_ascii_lowercase();
275        if let Some(at) = lower.rfind("for=") {
276            let rest = &v[at + 4..];
277            let end = rest.find([';', ',']).unwrap_or(rest.len());
278            if let Some(ip) = parse_node(&rest[..end]) {
279                return Some(ip);
280            }
281        }
282    }
283    text("x-forwarded-for")
284        .and_then(|v| v.split(',').next())
285        .and_then(|v| v.trim().parse().ok())
286}
287
288/// A `Forwarded` node: `192.0.2.4`, `"192.0.2.4:80"`, `"[2001:db8::1]:80"`.
289fn parse_node(s: &str) -> Option<IpAddr> {
290    let s = s.trim().trim_matches('"');
291    if let Some(rest) = s.strip_prefix('[') {
292        return rest.split(']').next()?.parse().ok();
293    }
294    s.parse()
295        .ok()
296        .or_else(|| s.rsplit_once(':').and_then(|(a, _)| a.parse().ok()))
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302
303    fn ip(s: &str) -> IpAddr {
304        s.parse().unwrap()
305    }
306
307    fn guard(c: GuardConfig) -> Guard {
308        Guard::new(GuardConfig {
309            sweep: Duration::from_secs(1),
310            ..c
311        })
312    }
313
314    #[test]
315    fn networks() {
316        let n: Net = "10.1.0.0/16".parse().unwrap();
317        assert!(n.contains(ip("10.1.200.3")));
318        assert!(!n.contains(ip("10.2.0.1")));
319        assert!(n.contains(ip("::ffff:10.1.0.9")));
320        let one: Net = "2001:db8::1".parse().unwrap();
321        assert!(one.contains(ip("2001:db8::1")) && !one.contains(ip("2001:db8::2")));
322        assert!("10.0.0.0/33".parse::<Net>().is_err());
323        assert!("0.0.0.0/0".parse::<Net>().unwrap().contains(ip("8.8.8.8")));
324    }
325
326    #[test]
327    fn handling_time_counts_against_the_budget() {
328        let g = guard(GuardConfig {
329            max_requests: Some(10),
330            work_ms: Some(50),
331            whitelist: vec!["127.0.0.1".parse().unwrap()],
332            ..GuardConfig::default()
333        });
334        let a = ip("192.0.2.1");
335        assert!(g.request(a, 1));
336        // Under one unit of work costs nothing more.
337        g.worked(a, Duration::from_millis(49));
338        assert!(g.request(a, 1));
339        // 400 ms is 8 more: 2 + 8 = 10, at the limit; the next one is over.
340        g.worked(a, Duration::from_millis(400));
341        assert!(!g.request(a, 1));
342        g.worked(ip("127.0.0.1"), Duration::from_secs(60));
343        assert!(g.request(ip("127.0.0.1"), 1));
344        g.sweep();
345        assert!(g.request(a, 1));
346        // Without work_ms time is not counted.
347        let off = guard(GuardConfig {
348            max_requests: Some(2),
349            ..GuardConfig::default()
350        });
351        off.worked(a, Duration::from_secs(60));
352        assert!(off.request(a, 2));
353    }
354
355    #[test]
356    fn budgets_reset_on_sweep_and_whitelist_is_free() {
357        let g = guard(GuardConfig {
358            max_requests: Some(3),
359            whitelist: vec!["127.0.0.1".parse().unwrap()],
360            ..GuardConfig::default()
361        });
362        let a = ip("192.0.2.1");
363        assert!(g.request(a, 2));
364        assert!(g.request(a, 1));
365        assert!(!g.request(a, 1));
366        assert!(!g.request(a, 1));
367        assert!(g.request(ip("192.0.2.2"), 1));
368        for _ in 0..100 {
369            assert!(g.request(ip("127.0.0.1"), 10));
370        }
371        g.sweep();
372        assert!(g.request(a, 3));
373        let bytes = guard(GuardConfig {
374            max_bytes: Some(100),
375            ..GuardConfig::default()
376        });
377        bytes.sent(a, 101);
378        assert!(!bytes.request(a, 1));
379    }
380
381    #[test]
382    fn connections_are_capped_and_given_back() {
383        let g = guard(GuardConfig {
384            max_connections: Some(2),
385            ..GuardConfig::default()
386        });
387        let a = ip("192.0.2.1");
388        let c1 = g.connect(a).unwrap();
389        let _c2 = g.connect(a).unwrap();
390        assert!(g.connect(a).is_none());
391        drop(c1);
392        g.sweep();
393        assert!(g.connect(a).is_some());
394        let off = guard(GuardConfig::default());
395        let _held: Vec<_> = (0..10).map(|_| off.connect(a).unwrap()).collect();
396    }
397
398    #[test]
399    fn forwarding_headers_count_only_from_trusted_proxies() {
400        let g = guard(GuardConfig {
401            max_requests: Some(1),
402            trusted_proxies: vec!["127.0.0.1".parse().unwrap()],
403            ..GuardConfig::default()
404        });
405        let mut h = HeaderMap::new();
406        h.insert("x-forwarded-for", "203.0.113.7, 10.0.0.1".parse().unwrap());
407        assert_eq!(g.client(ip("127.0.0.1"), &h), ip("203.0.113.7"));
408        assert_eq!(g.client(ip("198.51.100.1"), &h), ip("198.51.100.1"));
409        h.insert(
410            "forwarded",
411            "for=192.0.2.60;proto=http, for=\"[2001:db8::7]:4711\""
412                .parse()
413                .unwrap(),
414        );
415        assert_eq!(g.client(ip("127.0.0.1"), &h), ip("2001:db8::7"));
416        h.insert("cf-connecting-ip", "198.51.100.9".parse().unwrap());
417        assert_eq!(g.client(ip("::ffff:127.0.0.1"), &h), ip("198.51.100.9"));
418    }
419
420    #[test]
421    fn heavy_requests_weigh_more() {
422        let p = |v: Value| v.as_object().cloned().unwrap();
423        assert_eq!(weight("server_info", &Map::new()), 1);
424        assert_eq!(
425            weight("ledger", &p(serde_json::json!({"transactions": true}))),
426            1
427        );
428        assert_eq!(
429            weight(
430                "ledger",
431                &p(serde_json::json!({"transactions": true, "expand": true}))
432            ),
433            5
434        );
435        assert_eq!(weight("proof_tx", &Map::new()), 10);
436        assert_eq!(weight("fee", &Map::new()), 3);
437    }
438}