|
| 1 | +use axum::{ |
| 2 | + extract::{ConnectInfo, FromRequestParts}, |
| 3 | + http::{request::Parts, StatusCode}, |
| 4 | +}; |
| 5 | +use chrono::{DateTime, Duration, Utc}; |
| 6 | +use std::{ |
| 7 | + collections::{HashMap, VecDeque}, |
| 8 | + net::{IpAddr, SocketAddr}, |
| 9 | +}; |
| 10 | + |
| 11 | +/// How often do we allow the same ip in the time frame |
| 12 | +const IP_LIMIT: usize = 100; |
| 13 | +const IP_WINDOW: Duration = Duration::seconds(10 * 60); // 10 minutes |
| 14 | + |
| 15 | +/// How often do we allow the same email to be registered in the time frame |
| 16 | +const EMAIL_LIMIT: usize = 30; |
| 17 | +const EMAIL_WINDOW: Duration = Duration::seconds(24 * 3600); // 1 day |
| 18 | + |
| 19 | +/// How often do we allow the same npub in the time frame |
| 20 | +const NPUB_LIMIT: usize = 100; |
| 21 | +const NPUB_WINDOW: Duration = Duration::seconds(10 * 60); // 10 minutes |
| 22 | + |
| 23 | +const MAX_IDLE: Duration = Duration::seconds(24 * 3600); // remove after 24h idle |
| 24 | +const PRUNE_INTERVAL: Duration = Duration::seconds(10 * 60); // check every 10 minutes |
| 25 | + |
| 26 | +#[derive(Debug)] |
| 27 | +struct SlidingWindow { |
| 28 | + hits: VecDeque<DateTime<Utc>>, |
| 29 | + window: Duration, |
| 30 | + limit: usize, |
| 31 | + last_seen: DateTime<Utc>, |
| 32 | +} |
| 33 | + |
| 34 | +impl SlidingWindow { |
| 35 | + fn new(limit: usize, window: Duration) -> Self { |
| 36 | + Self { |
| 37 | + hits: VecDeque::with_capacity(limit), |
| 38 | + window, |
| 39 | + limit, |
| 40 | + last_seen: Utc::now(), |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + fn allow(&mut self, now: DateTime<Utc>) -> bool { |
| 45 | + // Remove expired hits |
| 46 | + while let Some(&ts) = self.hits.front() { |
| 47 | + if now - ts > self.window { |
| 48 | + self.hits.pop_front(); |
| 49 | + } else { |
| 50 | + break; |
| 51 | + } |
| 52 | + } |
| 53 | + self.last_seen = now; |
| 54 | + |
| 55 | + if self.hits.len() < self.limit { |
| 56 | + self.hits.push_back(now); |
| 57 | + true |
| 58 | + } else { |
| 59 | + false |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +#[derive(Debug)] |
| 65 | +pub struct RateLimiter { |
| 66 | + by_ip: HashMap<String, SlidingWindow>, |
| 67 | + by_email: HashMap<String, SlidingWindow>, |
| 68 | + by_npub_sender: HashMap<String, SlidingWindow>, |
| 69 | + by_npub_receiver: HashMap<String, SlidingWindow>, |
| 70 | + last_prune: DateTime<Utc>, |
| 71 | +} |
| 72 | + |
| 73 | +impl RateLimiter { |
| 74 | + pub fn new() -> Self { |
| 75 | + Self { |
| 76 | + by_ip: HashMap::new(), |
| 77 | + by_email: HashMap::new(), |
| 78 | + by_npub_sender: HashMap::new(), |
| 79 | + by_npub_receiver: HashMap::new(), |
| 80 | + last_prune: Utc::now(), |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + /// Check if the request is allowed |
| 85 | + /// There is always an IP, but not always an email, or npub - everything that's set has to be allowed |
| 86 | + /// The values are expected to be validated before getting in here |
| 87 | + pub fn check( |
| 88 | + &mut self, |
| 89 | + ip: &str, |
| 90 | + email: Option<&str>, |
| 91 | + npub_sender: Option<&str>, |
| 92 | + npub_receiver: Option<&str>, |
| 93 | + ) -> bool { |
| 94 | + let now = Utc::now(); |
| 95 | + self.prune_if_needed(now); |
| 96 | + |
| 97 | + let ip_ok = self |
| 98 | + .by_ip |
| 99 | + .entry(ip.to_string()) |
| 100 | + .or_insert_with(|| SlidingWindow::new(IP_LIMIT, IP_WINDOW)) |
| 101 | + .allow(now); |
| 102 | + |
| 103 | + let email_ok = if let Some(email) = email { |
| 104 | + let key = email.to_lowercase(); |
| 105 | + self.by_email |
| 106 | + .entry(key) |
| 107 | + .or_insert_with(|| SlidingWindow::new(EMAIL_LIMIT, EMAIL_WINDOW)) |
| 108 | + .allow(now) |
| 109 | + } else { |
| 110 | + true // no email provided -> skip check |
| 111 | + }; |
| 112 | + |
| 113 | + let npub_sender_ok = if let Some(npub) = npub_sender { |
| 114 | + self.by_npub_sender |
| 115 | + .entry(npub.to_string()) |
| 116 | + .or_insert_with(|| SlidingWindow::new(NPUB_LIMIT, NPUB_WINDOW)) |
| 117 | + .allow(now) |
| 118 | + } else { |
| 119 | + true // no sender npub provided -> skip check |
| 120 | + }; |
| 121 | + |
| 122 | + let npub_receiver_ok = if let Some(npub) = npub_receiver { |
| 123 | + self.by_npub_receiver |
| 124 | + .entry(npub.to_string()) |
| 125 | + .or_insert_with(|| SlidingWindow::new(NPUB_LIMIT, NPUB_WINDOW)) |
| 126 | + .allow(now) |
| 127 | + } else { |
| 128 | + true // no received npub provided -> skip check |
| 129 | + }; |
| 130 | + |
| 131 | + ip_ok && email_ok && npub_sender_ok && npub_receiver_ok |
| 132 | + } |
| 133 | + |
| 134 | + /// Every PRUNE_INTERVAL, remove outdated entries |
| 135 | + fn prune_if_needed(&mut self, now: DateTime<Utc>) { |
| 136 | + if now - self.last_prune < PRUNE_INTERVAL { |
| 137 | + return; |
| 138 | + } |
| 139 | + |
| 140 | + self.last_prune = now; |
| 141 | + |
| 142 | + // only keep recent entries |
| 143 | + self.by_ip.retain(|_, win| now - win.last_seen <= MAX_IDLE); |
| 144 | + self.by_email |
| 145 | + .retain(|_, win| now - win.last_seen <= MAX_IDLE); |
| 146 | + self.by_npub_sender |
| 147 | + .retain(|_, win| now - win.last_seen <= MAX_IDLE); |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +pub struct RealIp(pub IpAddr); |
| 152 | + |
| 153 | +impl<S> FromRequestParts<S> for RealIp |
| 154 | +where |
| 155 | + S: Send + Sync, |
| 156 | +{ |
| 157 | + type Rejection = (StatusCode, &'static str); |
| 158 | + |
| 159 | + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { |
| 160 | + // Check X-FORWARDED-FOR header and take the first value for gcp as per |
| 161 | + // https://cloud.google.com/functions/docs/reference/headers#x-forwarded-for |
| 162 | + if let Some(forwarded) = parts.headers.get("x-forwarded-for") |
| 163 | + && let Ok(s) = forwarded.to_str() |
| 164 | + && let Some(ip_str) = s.split(',').next() |
| 165 | + && let Ok(ip) = ip_str.trim().parse() |
| 166 | + { |
| 167 | + return Ok(RealIp(ip)); |
| 168 | + } |
| 169 | + |
| 170 | + // Fallback to socket addr for local dev |
| 171 | + if let Some(addr) = parts.extensions.get::<ConnectInfo<SocketAddr>>() { |
| 172 | + return Ok(RealIp(addr.ip())); |
| 173 | + } |
| 174 | + |
| 175 | + Err((StatusCode::BAD_REQUEST, "No request IP")) |
| 176 | + } |
| 177 | +} |
0 commit comments