| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::{ |
| 15 | collections::HashMap, |
| 16 | sync::Mutex, |
| 17 | time::{Duration, Instant}, |
| 18 | }; |
| 19 | |
| 20 | use topcoat::{ |
| 21 | context::{Cx, app_context}, |
| 22 | router::{Body, Response, StatusCode, header::RETRY_AFTER, headers}, |
| 23 | }; |
| 24 | |
| 25 | |
| 26 | const WINDOW: Duration = Duration::from_secs(60); |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | const PER_CLIENT: u32 = 10; |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | const GLOBAL: u32 = 60; |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | const MAX_KEYS: usize = 4096; |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | const GIT_PER_CLIENT: u32 = 60; |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | const GIT_GLOBAL: u32 = 600; |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | #[derive(Debug)] |
| 84 | pub struct GitAuthLimiter(RateLimiter); |
| 85 | |
| 86 | impl Default for GitAuthLimiter { |
| 87 | fn default() -> Self { |
| 88 | Self(RateLimiter::new( |
| 89 | WINDOW, |
| 90 | GIT_PER_CLIENT, |
| 91 | GIT_GLOBAL, |
| 92 | MAX_KEYS, |
| 93 | )) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | pub fn git_auth_throttled(cx: &Cx) -> Option<Duration> { |
| 103 | match app_context::<GitAuthLimiter>(cx).0.check(&client_key(cx)) { |
| 104 | Decision::Allowed => None, |
| 105 | Decision::Throttled(retry_after) => { |
| 106 | eprintln!("steid: rate limited a git authentication attempt"); |
| 107 | Some(retry_after) |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | const ARCHIVE_PER_CLIENT: u32 = 10; |
| 119 | |
| 120 | |
| 121 | |
| 122 | const ARCHIVE_GLOBAL: u32 = 60; |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | #[derive(Debug)] |
| 128 | pub struct ArchiveLimiter(RateLimiter); |
| 129 | |
| 130 | impl Default for ArchiveLimiter { |
| 131 | fn default() -> Self { |
| 132 | Self(RateLimiter::new( |
| 133 | WINDOW, |
| 134 | ARCHIVE_PER_CLIENT, |
| 135 | ARCHIVE_GLOBAL, |
| 136 | MAX_KEYS, |
| 137 | )) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | pub fn archive_throttled(cx: &Cx) -> Option<Duration> { |
| 145 | match app_context::<ArchiveLimiter>(cx).0.check(&client_key(cx)) { |
| 146 | Decision::Allowed => None, |
| 147 | Decision::Throttled(retry_after) => { |
| 148 | eprintln!("steid: rate limited an archive download"); |
| 149 | Some(retry_after) |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | |
| 155 | #[derive(Debug)] |
| 156 | pub struct RateLimiter { |
| 157 | window: Duration, |
| 158 | per_client: u32, |
| 159 | global: u32, |
| 160 | max_keys: usize, |
| 161 | state: Mutex<State>, |
| 162 | } |
| 163 | |
| 164 | #[derive(Debug)] |
| 165 | struct State { |
| 166 | clients: HashMap<Box<str>, Window>, |
| 167 | global: Window, |
| 168 | } |
| 169 | |
| 170 | |
| 171 | #[derive(Debug, Clone, Copy)] |
| 172 | struct Window { |
| 173 | opened: Instant, |
| 174 | hits: u32, |
| 175 | } |
| 176 | |
| 177 | impl Window { |
| 178 | fn new(now: Instant) -> Self { |
| 179 | Self { |
| 180 | opened: now, |
| 181 | hits: 0, |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | |
| 186 | fn record(&mut self, now: Instant, window: Duration) -> u32 { |
| 187 | if now.duration_since(self.opened) >= window { |
| 188 | *self = Self::new(now); |
| 189 | } |
| 190 | |
| 191 | self.hits = self.hits.saturating_add(1); |
| 192 | self.hits |
| 193 | } |
| 194 | |
| 195 | fn expired(&self, now: Instant, window: Duration) -> bool { |
| 196 | now.duration_since(self.opened) >= window |
| 197 | } |
| 198 | |
| 199 | fn remaining(&self, now: Instant, window: Duration) -> Duration { |
| 200 | window.saturating_sub(now.duration_since(self.opened)) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | |
| 205 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 206 | pub enum Decision { |
| 207 | Allowed, |
| 208 | |
| 209 | Throttled(Duration), |
| 210 | } |
| 211 | |
| 212 | impl Default for RateLimiter { |
| 213 | fn default() -> Self { |
| 214 | Self::new(WINDOW, PER_CLIENT, GLOBAL, MAX_KEYS) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | impl RateLimiter { |
| 219 | |
| 220 | |
| 221 | #[must_use] |
| 222 | pub fn new(window: Duration, per_client: u32, global: u32, max_keys: usize) -> Self { |
| 223 | Self { |
| 224 | window, |
| 225 | per_client, |
| 226 | global, |
| 227 | max_keys, |
| 228 | state: Mutex::new(State { |
| 229 | clients: HashMap::new(), |
| 230 | global: Window::new(Instant::now()), |
| 231 | }), |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | |
| 236 | pub fn check(&self, key: &str) -> Decision { |
| 237 | self.check_at(key, Instant::now()) |
| 238 | } |
| 239 | |
| 240 | |
| 241 | fn check_at(&self, key: &str, now: Instant) -> Decision { |
| 242 | let mut state = self.state.lock().unwrap_or_else(|poisoned| { |
| 243 | |
| 244 | |
| 245 | self.state.clear_poison(); |
| 246 | poisoned.into_inner() |
| 247 | }); |
| 248 | |
| 249 | |
| 250 | |
| 251 | let global_hits = state.global.record(now, self.window); |
| 252 | if global_hits > self.global { |
| 253 | return Decision::Throttled(state.global.remaining(now, self.window)); |
| 254 | } |
| 255 | |
| 256 | if !state.clients.contains_key(key) && state.clients.len() >= self.max_keys { |
| 257 | let window = self.window; |
| 258 | state.clients.retain(|_, entry| !entry.expired(now, window)); |
| 259 | |
| 260 | if state.clients.len() >= self.max_keys { |
| 261 | |
| 262 | |
| 263 | return Decision::Allowed; |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | let entry = state |
| 268 | .clients |
| 269 | .entry(key.into()) |
| 270 | .or_insert_with(|| Window::new(now)); |
| 271 | |
| 272 | if entry.record(now, self.window) > self.per_client { |
| 273 | return Decision::Throttled(entry.remaining(now, self.window)); |
| 274 | } |
| 275 | |
| 276 | Decision::Allowed |
| 277 | } |
| 278 | |
| 279 | |
| 280 | #[must_use] |
| 281 | pub fn tracked_keys(&self) -> usize { |
| 282 | self.state.lock().map_or(0, |state| state.clients.len()) |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | pub fn throttled(cx: &Cx) -> Option<Response> { |
| 291 | match app_context::<RateLimiter>(cx).check(&client_key(cx)) { |
| 292 | Decision::Allowed => None, |
| 293 | Decision::Throttled(retry_after) => { |
| 294 | eprintln!("steid: rate limited an auth attempt"); |
| 295 | Some(too_many_requests(retry_after)) |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | |
| 301 | |
| 302 | fn too_many_requests(retry_after: Duration) -> Response { |
| 303 | let seconds = retry_after.as_secs().max(1); |
| 304 | |
| 305 | let mut response = Response::new(Body::from("too many attempts, try again shortly\n")); |
| 306 | *response.status_mut() = StatusCode::TOO_MANY_REQUESTS; |
| 307 | response.headers_mut().insert(RETRY_AFTER, seconds.into()); |
| 308 | |
| 309 | response |
| 310 | } |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | fn client_key(cx: &Cx) -> String { |
| 337 | let headers = headers(cx); |
| 338 | let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok()); |
| 339 | |
| 340 | let forwarded = value("x-forwarded-for") |
| 341 | .and_then(|list| list.rsplit(',').next()) |
| 342 | .and_then(address); |
| 343 | |
| 344 | forwarded |
| 345 | .or_else(|| value("x-real-ip").and_then(address)) |
| 346 | |
| 347 | |
| 348 | |
| 349 | .unwrap_or_else(|| "direct".to_owned()) |
| 350 | } |
| 351 | |
| 352 | |
| 353 | |
| 354 | fn address(raw: &str) -> Option<String> { |
| 355 | |
| 356 | const MAX: usize = 64; |
| 357 | |
| 358 | let candidate = raw.trim(); |
| 359 | |
| 360 | let plausible = !candidate.is_empty() |
| 361 | && candidate.len() <= MAX |
| 362 | && candidate |
| 363 | .chars() |
| 364 | .all(|c| c.is_ascii_hexdigit() || matches!(c, '.' | ':' | '%' | '[' | ']')); |
| 365 | |
| 366 | plausible.then(|| candidate.to_owned()) |
| 367 | } |
| 368 | |
| 369 | #[cfg(test)] |
| 370 | mod tests { |
| 371 | use super::*; |
| 372 | |
| 373 | fn limiter() -> RateLimiter { |
| 374 | RateLimiter::new(Duration::from_secs(60), 3, 100, 16) |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn allows_attempts_up_to_the_limit() { |
| 379 | let limiter = limiter(); |
| 380 | let now = Instant::now(); |
| 381 | |
| 382 | for _ in 0..3 { |
| 383 | assert_eq!(limiter.check_at("a", now), Decision::Allowed); |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | #[test] |
| 388 | fn refuses_the_attempt_after_the_limit() { |
| 389 | let limiter = limiter(); |
| 390 | let now = Instant::now(); |
| 391 | |
| 392 | for _ in 0..3 { |
| 393 | limiter.check_at("a", now); |
| 394 | } |
| 395 | |
| 396 | assert!(matches!(limiter.check_at("a", now), Decision::Throttled(_))); |
| 397 | } |
| 398 | |
| 399 | #[test] |
| 400 | fn reports_how_long_until_the_window_rolls() { |
| 401 | let limiter = limiter(); |
| 402 | let now = Instant::now(); |
| 403 | |
| 404 | for _ in 0..4 { |
| 405 | limiter.check_at("a", now); |
| 406 | } |
| 407 | |
| 408 | let Decision::Throttled(retry_after) = limiter.check_at("a", now + Duration::from_secs(20)) |
| 409 | else { |
| 410 | panic!("the key is over its limit"); |
| 411 | }; |
| 412 | |
| 413 | assert_eq!(retry_after, Duration::from_secs(40)); |
| 414 | } |
| 415 | |
| 416 | #[test] |
| 417 | fn recovers_once_the_window_has_passed() { |
| 418 | let limiter = limiter(); |
| 419 | let now = Instant::now(); |
| 420 | |
| 421 | for _ in 0..4 { |
| 422 | limiter.check_at("a", now); |
| 423 | } |
| 424 | |
| 425 | assert_eq!( |
| 426 | limiter.check_at("a", now + Duration::from_secs(60)), |
| 427 | Decision::Allowed |
| 428 | ); |
| 429 | } |
| 430 | |
| 431 | #[test] |
| 432 | fn keys_are_independent() { |
| 433 | let limiter = limiter(); |
| 434 | let now = Instant::now(); |
| 435 | |
| 436 | for _ in 0..4 { |
| 437 | limiter.check_at("a", now); |
| 438 | } |
| 439 | |
| 440 | assert_eq!(limiter.check_at("b", now), Decision::Allowed); |
| 441 | } |
| 442 | |
| 443 | #[test] |
| 444 | fn the_global_window_catches_a_caller_rotating_keys() { |
| 445 | let limiter = RateLimiter::new(Duration::from_secs(60), 3, 5, 16); |
| 446 | let now = Instant::now(); |
| 447 | |
| 448 | for index in 0..5 { |
| 449 | assert_eq!( |
| 450 | limiter.check_at(&format!("k{index}"), now), |
| 451 | Decision::Allowed |
| 452 | ); |
| 453 | } |
| 454 | |
| 455 | assert!(matches!( |
| 456 | limiter.check_at("k5", now), |
| 457 | Decision::Throttled(_) |
| 458 | )); |
| 459 | } |
| 460 | |
| 461 | #[test] |
| 462 | fn the_map_does_not_grow_past_its_cap() { |
| 463 | let limiter = RateLimiter::new(Duration::from_secs(60), 3, u32::MAX, 16); |
| 464 | let now = Instant::now(); |
| 465 | |
| 466 | for index in 0..5_000 { |
| 467 | limiter.check_at(&format!("k{index}"), now); |
| 468 | } |
| 469 | |
| 470 | assert!(limiter.tracked_keys() <= 16); |
| 471 | } |
| 472 | |
| 473 | #[test] |
| 474 | fn expired_entries_are_swept_to_make_room() { |
| 475 | let limiter = RateLimiter::new(Duration::from_secs(60), 3, u32::MAX, 16); |
| 476 | let now = Instant::now(); |
| 477 | |
| 478 | for index in 0..16 { |
| 479 | limiter.check_at(&format!("old{index}"), now); |
| 480 | } |
| 481 | |
| 482 | |
| 483 | |
| 484 | let later = now + Duration::from_secs(61); |
| 485 | for _ in 0..4 { |
| 486 | limiter.check_at("new", later); |
| 487 | } |
| 488 | |
| 489 | assert!(matches!( |
| 490 | limiter.check_at("new", later), |
| 491 | Decision::Throttled(_) |
| 492 | )); |
| 493 | assert!(limiter.tracked_keys() <= 16); |
| 494 | } |
| 495 | |
| 496 | #[test] |
| 497 | fn a_key_beyond_the_cap_is_still_covered_by_the_global_window() { |
| 498 | let limiter = RateLimiter::new(Duration::from_secs(60), 3, 20, 2); |
| 499 | let now = Instant::now(); |
| 500 | |
| 501 | for index in 0..20 { |
| 502 | limiter.check_at(&format!("k{index}"), now); |
| 503 | } |
| 504 | |
| 505 | assert!(matches!( |
| 506 | limiter.check_at("k20", now), |
| 507 | Decision::Throttled(_) |
| 508 | )); |
| 509 | } |
| 510 | |
| 511 | #[test] |
| 512 | fn an_address_is_accepted() { |
| 513 | assert_eq!(address(" 203.0.113.7 "), Some("203.0.113.7".to_owned())); |
| 514 | assert_eq!(address("2001:db8::1"), Some("2001:db8::1".to_owned())); |
| 515 | } |
| 516 | |
| 517 | #[test] |
| 518 | fn a_hostile_header_value_is_rejected() { |
| 519 | assert_eq!(address(""), None); |
| 520 | assert_eq!(address("not an address"), None); |
| 521 | assert_eq!(address(&"9".repeat(65)), None); |
| 522 | } |
| 523 | |
| 524 | #[test] |
| 525 | fn the_archive_limiter_allows_ten_downloads_a_minute_then_refuses() { |
| 526 | let limiter = ArchiveLimiter::default(); |
| 527 | for _ in 0..ARCHIVE_PER_CLIENT { |
| 528 | assert!(matches!(limiter.0.check("a"), Decision::Allowed)); |
| 529 | } |
| 530 | assert!(matches!(limiter.0.check("a"), Decision::Throttled(_))); |
| 531 | |
| 532 | assert!(matches!(limiter.0.check("b"), Decision::Allowed)); |
| 533 | } |
| 534 | |
| 535 | #[test] |
| 536 | fn the_git_transport_gets_a_budget_a_clone_can_live_inside() { |
| 537 | |
| 538 | |
| 539 | |
| 540 | const { assert!(GIT_PER_CLIENT > PER_CLIENT * 4) }; |
| 541 | |
| 542 | let limiter = GitAuthLimiter::default(); |
| 543 | let now = Instant::now(); |
| 544 | |
| 545 | for _ in 0..GIT_PER_CLIENT { |
| 546 | assert_eq!(limiter.0.check_at("a", now), Decision::Allowed); |
| 547 | } |
| 548 | |
| 549 | assert!(matches!( |
| 550 | limiter.0.check_at("a", now), |
| 551 | Decision::Throttled(_) |
| 552 | )); |
| 553 | assert_eq!( |
| 554 | limiter.0.check_at("b", now), |
| 555 | Decision::Allowed, |
| 556 | "another client has its own budget" |
| 557 | ); |
| 558 | } |
| 559 | } |