| 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, try_app_context}, |
| 22 | router::{Body, HeaderMap, Response, StatusCode, header::RETRY_AFTER, headers}, |
| 23 | }; |
| 24 | |
| 25 | use crate::application::AppConfig; |
| 26 | use crate::infrastructure::metrics::{Limiter, metrics}; |
| 27 | |
| 28 | |
| 29 | const WINDOW: Duration = Duration::from_secs(60); |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | const PER_CLIENT: u32 = 10; |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | const GLOBAL: u32 = 60; |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | const MAX_KEYS: usize = 4096; |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | const GIT_PER_CLIENT: u32 = 60; |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | const GIT_GLOBAL: u32 = 600; |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | #[derive(Debug)] |
| 87 | pub struct GitAuthLimiter(RateLimiter); |
| 88 | |
| 89 | impl Default for GitAuthLimiter { |
| 90 | fn default() -> Self { |
| 91 | Self(RateLimiter::new( |
| 92 | WINDOW, |
| 93 | GIT_PER_CLIENT, |
| 94 | GIT_GLOBAL, |
| 95 | MAX_KEYS, |
| 96 | )) |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | pub fn git_auth_throttled(cx: &Cx) -> Option<Duration> { |
| 106 | match app_context::<GitAuthLimiter>(cx).0.check(&client_key(cx)) { |
| 107 | Decision::Allowed => None, |
| 108 | Decision::Throttled(retry_after) => { |
| 109 | eprintln!("steid: rate limited a git authentication attempt"); |
| 110 | metrics().record_rate_limited(Limiter::GitAuth); |
| 111 | Some(retry_after) |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | const ARCHIVE_PER_CLIENT: u32 = 10; |
| 123 | |
| 124 | |
| 125 | |
| 126 | const ARCHIVE_GLOBAL: u32 = 60; |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | #[derive(Debug)] |
| 132 | pub struct ArchiveLimiter(RateLimiter); |
| 133 | |
| 134 | impl Default for ArchiveLimiter { |
| 135 | fn default() -> Self { |
| 136 | Self(RateLimiter::new( |
| 137 | WINDOW, |
| 138 | ARCHIVE_PER_CLIENT, |
| 139 | ARCHIVE_GLOBAL, |
| 140 | MAX_KEYS, |
| 141 | )) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | pub fn archive_throttled(cx: &Cx) -> Option<Duration> { |
| 149 | match app_context::<ArchiveLimiter>(cx).0.check(&client_key(cx)) { |
| 150 | Decision::Allowed => None, |
| 151 | Decision::Throttled(retry_after) => { |
| 152 | eprintln!("steid: rate limited an archive download"); |
| 153 | metrics().record_rate_limited(Limiter::Archive); |
| 154 | Some(retry_after) |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | const SEARCH_PER_CLIENT: u32 = 20; |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | const SEARCH_GLOBAL: u32 = 120; |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | #[derive(Debug)] |
| 187 | pub struct SearchLimiter(RateLimiter); |
| 188 | |
| 189 | impl Default for SearchLimiter { |
| 190 | fn default() -> Self { |
| 191 | Self(RateLimiter::new( |
| 192 | WINDOW, |
| 193 | SEARCH_PER_CLIENT, |
| 194 | SEARCH_GLOBAL, |
| 195 | MAX_KEYS, |
| 196 | )) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | pub fn search_throttled(cx: &Cx) -> Option<Duration> { |
| 206 | match app_context::<SearchLimiter>(cx).0.check(&client_key(cx)) { |
| 207 | Decision::Allowed => None, |
| 208 | Decision::Throttled(retry_after) => { |
| 209 | eprintln!("steid: rate limited a code search"); |
| 210 | metrics().record_rate_limited(Limiter::Search); |
| 211 | Some(retry_after) |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | const INSTANCE_PER_CLIENT: u32 = 60; |
| 225 | |
| 226 | |
| 227 | |
| 228 | const INSTANCE_GLOBAL: u32 = 600; |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | #[derive(Debug)] |
| 238 | pub struct InstanceLimiter(RateLimiter); |
| 239 | |
| 240 | impl Default for InstanceLimiter { |
| 241 | fn default() -> Self { |
| 242 | Self(RateLimiter::new( |
| 243 | WINDOW, |
| 244 | INSTANCE_PER_CLIENT, |
| 245 | INSTANCE_GLOBAL, |
| 246 | MAX_KEYS, |
| 247 | )) |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | |
| 252 | |
| 253 | pub fn instance_throttled(cx: &Cx) -> Option<Response> { |
| 254 | match app_context::<InstanceLimiter>(cx).0.check(&client_key(cx)) { |
| 255 | Decision::Allowed => None, |
| 256 | Decision::Throttled(retry_after) => { |
| 257 | eprintln!("steid: rate limited an instance poll"); |
| 258 | Some(too_many_requests(retry_after)) |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | const METRICS_PER_CLIENT: u32 = 30; |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | const METRICS_GLOBAL: u32 = 300; |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | #[derive(Debug)] |
| 291 | pub struct MetricsLimiter(RateLimiter); |
| 292 | |
| 293 | impl Default for MetricsLimiter { |
| 294 | fn default() -> Self { |
| 295 | Self(RateLimiter::new( |
| 296 | WINDOW, |
| 297 | METRICS_PER_CLIENT, |
| 298 | METRICS_GLOBAL, |
| 299 | MAX_KEYS, |
| 300 | )) |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | pub fn metrics_throttled(cx: &Cx) -> Option<Response> { |
| 309 | match app_context::<MetricsLimiter>(cx).0.check(&client_key(cx)) { |
| 310 | Decision::Allowed => None, |
| 311 | Decision::Throttled(retry_after) => { |
| 312 | |
| 313 | |
| 314 | eprintln!("steid: rate limited an unauthorized /metrics request"); |
| 315 | metrics().record_rate_limited(Limiter::Metrics); |
| 316 | Some(too_many_requests(retry_after)) |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | |
| 322 | const BACKUP_WINDOW: Duration = Duration::from_secs(3_600); |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | const BACKUP_PER_CLIENT: u32 = 2; |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | const BACKUP_GLOBAL: u32 = 8; |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | #[derive(Debug)] |
| 349 | pub struct BackupLimiter(RateLimiter); |
| 350 | |
| 351 | impl Default for BackupLimiter { |
| 352 | fn default() -> Self { |
| 353 | Self(RateLimiter::new( |
| 354 | BACKUP_WINDOW, |
| 355 | BACKUP_PER_CLIENT, |
| 356 | BACKUP_GLOBAL, |
| 357 | MAX_KEYS, |
| 358 | )) |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | pub fn backup_throttled(cx: &Cx) -> Option<Duration> { |
| 366 | match app_context::<BackupLimiter>(cx).0.check(&client_key(cx)) { |
| 367 | Decision::Allowed => None, |
| 368 | Decision::Throttled(retry_after) => { |
| 369 | eprintln!("steid: rate limited a backup download"); |
| 370 | Some(retry_after) |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | const RESET_PER_CLIENT: u32 = 30; |
| 389 | |
| 390 | |
| 391 | |
| 392 | const RESET_GLOBAL: u32 = 120; |
| 393 | |
| 394 | |
| 395 | #[derive(Debug)] |
| 396 | pub struct ResetLimiter(RateLimiter); |
| 397 | |
| 398 | impl Default for ResetLimiter { |
| 399 | fn default() -> Self { |
| 400 | Self(RateLimiter::new( |
| 401 | WINDOW, |
| 402 | RESET_PER_CLIENT, |
| 403 | RESET_GLOBAL, |
| 404 | MAX_KEYS, |
| 405 | )) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | |
| 410 | |
| 411 | pub fn reset_throttled(cx: &Cx) -> Option<Response> { |
| 412 | match app_context::<ResetLimiter>(cx).0.check(&client_key(cx)) { |
| 413 | Decision::Allowed => None, |
| 414 | Decision::Throttled(retry_after) => { |
| 415 | eprintln!("steid: rate limited a password reset attempt"); |
| 416 | Some(too_many_requests(retry_after)) |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | |
| 422 | #[derive(Debug)] |
| 423 | pub struct RateLimiter { |
| 424 | window: Duration, |
| 425 | per_client: u32, |
| 426 | global: u32, |
| 427 | max_keys: usize, |
| 428 | state: Mutex<State>, |
| 429 | } |
| 430 | |
| 431 | #[derive(Debug)] |
| 432 | struct State { |
| 433 | clients: HashMap<Box<str>, Window>, |
| 434 | global: Window, |
| 435 | } |
| 436 | |
| 437 | |
| 438 | #[derive(Debug, Clone, Copy)] |
| 439 | struct Window { |
| 440 | opened: Instant, |
| 441 | hits: u32, |
| 442 | } |
| 443 | |
| 444 | impl Window { |
| 445 | fn new(now: Instant) -> Self { |
| 446 | Self { |
| 447 | opened: now, |
| 448 | hits: 0, |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | |
| 453 | fn record(&mut self, now: Instant, window: Duration) -> u32 { |
| 454 | if now.duration_since(self.opened) >= window { |
| 455 | *self = Self::new(now); |
| 456 | } |
| 457 | |
| 458 | self.hits = self.hits.saturating_add(1); |
| 459 | self.hits |
| 460 | } |
| 461 | |
| 462 | fn expired(&self, now: Instant, window: Duration) -> bool { |
| 463 | now.duration_since(self.opened) >= window |
| 464 | } |
| 465 | |
| 466 | fn remaining(&self, now: Instant, window: Duration) -> Duration { |
| 467 | window.saturating_sub(now.duration_since(self.opened)) |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | |
| 472 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 473 | pub enum Decision { |
| 474 | Allowed, |
| 475 | |
| 476 | Throttled(Duration), |
| 477 | } |
| 478 | |
| 479 | impl Default for RateLimiter { |
| 480 | fn default() -> Self { |
| 481 | Self::new(WINDOW, PER_CLIENT, GLOBAL, MAX_KEYS) |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | impl RateLimiter { |
| 486 | |
| 487 | |
| 488 | #[must_use] |
| 489 | pub fn new(window: Duration, per_client: u32, global: u32, max_keys: usize) -> Self { |
| 490 | Self { |
| 491 | window, |
| 492 | per_client, |
| 493 | global, |
| 494 | max_keys, |
| 495 | state: Mutex::new(State { |
| 496 | clients: HashMap::new(), |
| 497 | global: Window::new(Instant::now()), |
| 498 | }), |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | |
| 503 | pub fn check(&self, key: &str) -> Decision { |
| 504 | self.check_at(key, Instant::now()) |
| 505 | } |
| 506 | |
| 507 | |
| 508 | fn check_at(&self, key: &str, now: Instant) -> Decision { |
| 509 | let mut state = self.state.lock().unwrap_or_else(|poisoned| { |
| 510 | |
| 511 | |
| 512 | self.state.clear_poison(); |
| 513 | poisoned.into_inner() |
| 514 | }); |
| 515 | |
| 516 | |
| 517 | |
| 518 | let global_hits = state.global.record(now, self.window); |
| 519 | if global_hits > self.global { |
| 520 | return Decision::Throttled(state.global.remaining(now, self.window)); |
| 521 | } |
| 522 | |
| 523 | if !state.clients.contains_key(key) && state.clients.len() >= self.max_keys { |
| 524 | let window = self.window; |
| 525 | state.clients.retain(|_, entry| !entry.expired(now, window)); |
| 526 | |
| 527 | if state.clients.len() >= self.max_keys { |
| 528 | |
| 529 | |
| 530 | return Decision::Allowed; |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | let entry = state |
| 535 | .clients |
| 536 | .entry(key.into()) |
| 537 | .or_insert_with(|| Window::new(now)); |
| 538 | |
| 539 | if entry.record(now, self.window) > self.per_client { |
| 540 | return Decision::Throttled(entry.remaining(now, self.window)); |
| 541 | } |
| 542 | |
| 543 | Decision::Allowed |
| 544 | } |
| 545 | |
| 546 | |
| 547 | #[must_use] |
| 548 | pub fn tracked_keys(&self) -> usize { |
| 549 | self.state.lock().map_or(0, |state| state.clients.len()) |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | pub fn throttled(cx: &Cx) -> Option<Response> { |
| 558 | match app_context::<RateLimiter>(cx).check(&client_key(cx)) { |
| 559 | Decision::Allowed => None, |
| 560 | Decision::Throttled(retry_after) => { |
| 561 | eprintln!("steid: rate limited an auth attempt"); |
| 562 | metrics().record_rate_limited(Limiter::Auth); |
| 563 | Some(too_many_requests(retry_after)) |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | |
| 569 | |
| 570 | fn too_many_requests(retry_after: Duration) -> Response { |
| 571 | let seconds = retry_after.as_secs().max(1); |
| 572 | |
| 573 | let mut response = Response::new(Body::from("too many attempts, try again shortly\n")); |
| 574 | *response.status_mut() = StatusCode::TOO_MANY_REQUESTS; |
| 575 | response.headers_mut().insert(RETRY_AFTER, seconds.into()); |
| 576 | |
| 577 | response |
| 578 | } |
| 579 | |
| 580 | |
| 581 | |
| 582 | |
| 583 | |
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | |
| 589 | |
| 590 | |
| 591 | |
| 592 | |
| 593 | |
| 594 | |
| 595 | |
| 596 | |
| 597 | |
| 598 | |
| 599 | |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 604 | |
| 605 | |
| 606 | fn client_key(cx: &Cx) -> String { |
| 607 | |
| 608 | |
| 609 | |
| 610 | let trusted = try_app_context::<AppConfig>(cx).is_some_and(|config| config.trusted_proxy); |
| 611 | |
| 612 | key_from(trusted, headers(cx)) |
| 613 | } |
| 614 | |
| 615 | |
| 616 | |
| 617 | fn key_from(trusted_proxy: bool, headers: &HeaderMap) -> String { |
| 618 | if !trusted_proxy { |
| 619 | return SHARED_KEY.to_owned(); |
| 620 | } |
| 621 | |
| 622 | let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok()); |
| 623 | |
| 624 | let forwarded = value("x-forwarded-for") |
| 625 | .and_then(|list| list.rsplit(',').next()) |
| 626 | .and_then(address); |
| 627 | |
| 628 | forwarded |
| 629 | .or_else(|| value("x-real-ip").and_then(address)) |
| 630 | |
| 631 | |
| 632 | |
| 633 | .unwrap_or_else(|| SHARED_KEY.to_owned()) |
| 634 | } |
| 635 | |
| 636 | |
| 637 | const SHARED_KEY: &str = "direct"; |
| 638 | |
| 639 | |
| 640 | |
| 641 | fn address(raw: &str) -> Option<String> { |
| 642 | |
| 643 | const MAX: usize = 64; |
| 644 | |
| 645 | let candidate = raw.trim(); |
| 646 | |
| 647 | let plausible = !candidate.is_empty() |
| 648 | && candidate.len() <= MAX |
| 649 | && candidate |
| 650 | .chars() |
| 651 | .all(|c| c.is_ascii_hexdigit() || matches!(c, '.' | ':' | '%' | '[' | ']')); |
| 652 | |
| 653 | plausible.then(|| candidate.to_owned()) |
| 654 | } |
| 655 | |
| 656 | #[cfg(test)] |
| 657 | mod tests { |
| 658 | use super::*; |
| 659 | |
| 660 | fn limiter() -> RateLimiter { |
| 661 | RateLimiter::new(Duration::from_secs(60), 3, 100, 16) |
| 662 | } |
| 663 | |
| 664 | #[test] |
| 665 | fn allows_attempts_up_to_the_limit() { |
| 666 | let limiter = limiter(); |
| 667 | let now = Instant::now(); |
| 668 | |
| 669 | for _ in 0..3 { |
| 670 | assert_eq!(limiter.check_at("a", now), Decision::Allowed); |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | #[test] |
| 675 | fn refuses_the_attempt_after_the_limit() { |
| 676 | let limiter = limiter(); |
| 677 | let now = Instant::now(); |
| 678 | |
| 679 | for _ in 0..3 { |
| 680 | limiter.check_at("a", now); |
| 681 | } |
| 682 | |
| 683 | assert!(matches!(limiter.check_at("a", now), Decision::Throttled(_))); |
| 684 | } |
| 685 | |
| 686 | #[test] |
| 687 | fn reports_how_long_until_the_window_rolls() { |
| 688 | let limiter = limiter(); |
| 689 | let now = Instant::now(); |
| 690 | |
| 691 | for _ in 0..4 { |
| 692 | limiter.check_at("a", now); |
| 693 | } |
| 694 | |
| 695 | let Decision::Throttled(retry_after) = limiter.check_at("a", now + Duration::from_secs(20)) |
| 696 | else { |
| 697 | panic!("the key is over its limit"); |
| 698 | }; |
| 699 | |
| 700 | assert_eq!(retry_after, Duration::from_secs(40)); |
| 701 | } |
| 702 | |
| 703 | #[test] |
| 704 | fn recovers_once_the_window_has_passed() { |
| 705 | let limiter = limiter(); |
| 706 | let now = Instant::now(); |
| 707 | |
| 708 | for _ in 0..4 { |
| 709 | limiter.check_at("a", now); |
| 710 | } |
| 711 | |
| 712 | assert_eq!( |
| 713 | limiter.check_at("a", now + Duration::from_secs(60)), |
| 714 | Decision::Allowed |
| 715 | ); |
| 716 | } |
| 717 | |
| 718 | #[test] |
| 719 | fn keys_are_independent() { |
| 720 | let limiter = limiter(); |
| 721 | let now = Instant::now(); |
| 722 | |
| 723 | for _ in 0..4 { |
| 724 | limiter.check_at("a", now); |
| 725 | } |
| 726 | |
| 727 | assert_eq!(limiter.check_at("b", now), Decision::Allowed); |
| 728 | } |
| 729 | |
| 730 | #[test] |
| 731 | fn the_global_window_catches_a_caller_rotating_keys() { |
| 732 | let limiter = RateLimiter::new(Duration::from_secs(60), 3, 5, 16); |
| 733 | let now = Instant::now(); |
| 734 | |
| 735 | for index in 0..5 { |
| 736 | assert_eq!( |
| 737 | limiter.check_at(&format!("k{index}"), now), |
| 738 | Decision::Allowed |
| 739 | ); |
| 740 | } |
| 741 | |
| 742 | assert!(matches!( |
| 743 | limiter.check_at("k5", now), |
| 744 | Decision::Throttled(_) |
| 745 | )); |
| 746 | } |
| 747 | |
| 748 | #[test] |
| 749 | fn the_map_does_not_grow_past_its_cap() { |
| 750 | let limiter = RateLimiter::new(Duration::from_secs(60), 3, u32::MAX, 16); |
| 751 | let now = Instant::now(); |
| 752 | |
| 753 | for index in 0..5_000 { |
| 754 | limiter.check_at(&format!("k{index}"), now); |
| 755 | } |
| 756 | |
| 757 | assert!(limiter.tracked_keys() <= 16); |
| 758 | } |
| 759 | |
| 760 | #[test] |
| 761 | fn expired_entries_are_swept_to_make_room() { |
| 762 | let limiter = RateLimiter::new(Duration::from_secs(60), 3, u32::MAX, 16); |
| 763 | let now = Instant::now(); |
| 764 | |
| 765 | for index in 0..16 { |
| 766 | limiter.check_at(&format!("old{index}"), now); |
| 767 | } |
| 768 | |
| 769 | |
| 770 | |
| 771 | let later = now + Duration::from_secs(61); |
| 772 | for _ in 0..4 { |
| 773 | limiter.check_at("new", later); |
| 774 | } |
| 775 | |
| 776 | assert!(matches!( |
| 777 | limiter.check_at("new", later), |
| 778 | Decision::Throttled(_) |
| 779 | )); |
| 780 | assert!(limiter.tracked_keys() <= 16); |
| 781 | } |
| 782 | |
| 783 | #[test] |
| 784 | fn a_key_beyond_the_cap_is_still_covered_by_the_global_window() { |
| 785 | let limiter = RateLimiter::new(Duration::from_secs(60), 3, 20, 2); |
| 786 | let now = Instant::now(); |
| 787 | |
| 788 | for index in 0..20 { |
| 789 | limiter.check_at(&format!("k{index}"), now); |
| 790 | } |
| 791 | |
| 792 | assert!(matches!( |
| 793 | limiter.check_at("k20", now), |
| 794 | Decision::Throttled(_) |
| 795 | )); |
| 796 | } |
| 797 | |
| 798 | |
| 799 | fn forwarded(pairs: &[(&str, &str)]) -> HeaderMap { |
| 800 | let mut headers = HeaderMap::new(); |
| 801 | for (name, value) in pairs { |
| 802 | headers.insert( |
| 803 | topcoat::router::HeaderName::from_bytes(name.as_bytes()).expect("valid name"), |
| 804 | value.parse().expect("valid value"), |
| 805 | ); |
| 806 | } |
| 807 | headers |
| 808 | } |
| 809 | |
| 810 | #[test] |
| 811 | fn an_untrusted_proxy_keys_everyone_together() { |
| 812 | |
| 813 | |
| 814 | assert_eq!( |
| 815 | key_from(false, &forwarded(&[("x-forwarded-for", "203.0.113.7")])), |
| 816 | SHARED_KEY |
| 817 | ); |
| 818 | assert_eq!( |
| 819 | key_from(false, &forwarded(&[("x-forwarded-for", "198.51.100.9")])), |
| 820 | SHARED_KEY |
| 821 | ); |
| 822 | assert_eq!( |
| 823 | key_from(false, &forwarded(&[("x-real-ip", "203.0.113.7")])), |
| 824 | SHARED_KEY |
| 825 | ); |
| 826 | } |
| 827 | |
| 828 | #[test] |
| 829 | fn a_trusted_proxy_keys_on_the_rightmost_forwarded_entry() { |
| 830 | |
| 831 | |
| 832 | assert_eq!( |
| 833 | key_from( |
| 834 | true, |
| 835 | &forwarded(&[("x-forwarded-for", "1.2.3.4, 203.0.113.7")]) |
| 836 | ), |
| 837 | "203.0.113.7" |
| 838 | ); |
| 839 | assert_eq!( |
| 840 | key_from(true, &forwarded(&[("x-real-ip", "203.0.113.7")])), |
| 841 | "203.0.113.7" |
| 842 | ); |
| 843 | assert_eq!(key_from(true, &forwarded(&[])), SHARED_KEY); |
| 844 | } |
| 845 | |
| 846 | #[test] |
| 847 | fn a_trusted_proxy_that_forwards_rubbish_falls_back_to_the_shared_key() { |
| 848 | assert_eq!( |
| 849 | key_from(true, &forwarded(&[("x-forwarded-for", "not an address")])), |
| 850 | SHARED_KEY |
| 851 | ); |
| 852 | } |
| 853 | |
| 854 | #[test] |
| 855 | fn an_address_is_accepted() { |
| 856 | assert_eq!(address(" 203.0.113.7 "), Some("203.0.113.7".to_owned())); |
| 857 | assert_eq!(address("2001:db8::1"), Some("2001:db8::1".to_owned())); |
| 858 | } |
| 859 | |
| 860 | #[test] |
| 861 | fn a_hostile_header_value_is_rejected() { |
| 862 | assert_eq!(address(""), None); |
| 863 | assert_eq!(address("not an address"), None); |
| 864 | assert_eq!(address(&"9".repeat(65)), None); |
| 865 | } |
| 866 | |
| 867 | #[test] |
| 868 | fn the_archive_limiter_allows_ten_downloads_a_minute_then_refuses() { |
| 869 | let limiter = ArchiveLimiter::default(); |
| 870 | for _ in 0..ARCHIVE_PER_CLIENT { |
| 871 | assert!(matches!(limiter.0.check("a"), Decision::Allowed)); |
| 872 | } |
| 873 | assert!(matches!(limiter.0.check("a"), Decision::Throttled(_))); |
| 874 | |
| 875 | assert!(matches!(limiter.0.check("b"), Decision::Allowed)); |
| 876 | } |
| 877 | |
| 878 | #[test] |
| 879 | fn the_instance_poll_gets_a_budget_a_provisioner_can_live_inside() { |
| 880 | |
| 881 | |
| 882 | |
| 883 | const { assert!(INSTANCE_PER_CLIENT >= 60) }; |
| 884 | |
| 885 | let limiter = InstanceLimiter::default(); |
| 886 | let now = Instant::now(); |
| 887 | |
| 888 | for _ in 0..INSTANCE_PER_CLIENT { |
| 889 | assert_eq!(limiter.0.check_at("a", now), Decision::Allowed); |
| 890 | } |
| 891 | |
| 892 | assert!(matches!( |
| 893 | limiter.0.check_at("a", now), |
| 894 | Decision::Throttled(_) |
| 895 | )); |
| 896 | } |
| 897 | |
| 898 | #[test] |
| 899 | fn the_metrics_limiter_bounds_token_guessing_without_touching_the_sign_in_budget() { |
| 900 | const { assert!(METRICS_PER_CLIENT > PER_CLIENT) }; |
| 901 | |
| 902 | let limiter = MetricsLimiter::default(); |
| 903 | let now = Instant::now(); |
| 904 | |
| 905 | for _ in 0..METRICS_PER_CLIENT { |
| 906 | assert_eq!(limiter.0.check_at("a", now), Decision::Allowed); |
| 907 | } |
| 908 | |
| 909 | assert!(matches!( |
| 910 | limiter.0.check_at("a", now), |
| 911 | Decision::Throttled(_) |
| 912 | )); |
| 913 | assert_eq!( |
| 914 | limiter.0.check_at("b", now), |
| 915 | Decision::Allowed, |
| 916 | "another client has its own budget" |
| 917 | ); |
| 918 | } |
| 919 | |
| 920 | #[test] |
| 921 | fn the_backup_limiter_allows_two_an_hour_then_refuses() { |
| 922 | let limiter = BackupLimiter::default(); |
| 923 | let now = Instant::now(); |
| 924 | |
| 925 | for _ in 0..BACKUP_PER_CLIENT { |
| 926 | assert_eq!(limiter.0.check_at("a", now), Decision::Allowed); |
| 927 | } |
| 928 | assert!(matches!( |
| 929 | limiter.0.check_at("a", now), |
| 930 | Decision::Throttled(_) |
| 931 | )); |
| 932 | |
| 933 | |
| 934 | |
| 935 | assert!(matches!( |
| 936 | limiter.0.check_at("a", now + Duration::from_secs(3_500)), |
| 937 | Decision::Throttled(_) |
| 938 | )); |
| 939 | assert_eq!( |
| 940 | limiter.0.check_at("a", now + Duration::from_secs(3_600)), |
| 941 | Decision::Allowed |
| 942 | ); |
| 943 | } |
| 944 | |
| 945 | #[test] |
| 946 | fn the_git_transport_gets_a_budget_a_clone_can_live_inside() { |
| 947 | |
| 948 | |
| 949 | |
| 950 | const { assert!(GIT_PER_CLIENT > PER_CLIENT * 4) }; |
| 951 | |
| 952 | let limiter = GitAuthLimiter::default(); |
| 953 | let now = Instant::now(); |
| 954 | |
| 955 | for _ in 0..GIT_PER_CLIENT { |
| 956 | assert_eq!(limiter.0.check_at("a", now), Decision::Allowed); |
| 957 | } |
| 958 | |
| 959 | assert!(matches!( |
| 960 | limiter.0.check_at("a", now), |
| 961 | Decision::Throttled(_) |
| 962 | )); |
| 963 | assert_eq!( |
| 964 | limiter.0.check_at("b", now), |
| 965 | Decision::Allowed, |
| 966 | "another client has its own budget" |
| 967 | ); |
| 968 | } |
| 969 | |
| 970 | #[test] |
| 971 | fn the_reset_page_gets_a_budget_a_person_can_reload_inside() { |
| 972 | |
| 973 | |
| 974 | |
| 975 | let limiter = ResetLimiter::default().0; |
| 976 | |
| 977 | for _ in 0..30 { |
| 978 | assert!(matches!(limiter.check("a"), Decision::Allowed)); |
| 979 | } |
| 980 | assert!(matches!(limiter.check("a"), Decision::Throttled(_))); |
| 981 | assert!( |
| 982 | matches!(limiter.check("b"), Decision::Allowed), |
| 983 | "another client has its own budget" |
| 984 | ); |
| 985 | |
| 986 | |
| 987 | assert!(matches!( |
| 988 | RateLimiter::default().check("a"), |
| 989 | Decision::Allowed |
| 990 | )); |
| 991 | } |
| 992 | |
| 993 | #[test] |
| 994 | fn the_search_limiter_allows_twenty_searches_a_minute_then_refuses() { |
| 995 | |
| 996 | |
| 997 | let limiter = SearchLimiter::default().0; |
| 998 | |
| 999 | for _ in 0..SEARCH_PER_CLIENT { |
| 1000 | assert!(matches!(limiter.check("a"), Decision::Allowed)); |
| 1001 | } |
| 1002 | assert!(matches!(limiter.check("a"), Decision::Throttled(_))); |
| 1003 | assert!( |
| 1004 | matches!(limiter.check("b"), Decision::Allowed), |
| 1005 | "another client has its own budget" |
| 1006 | ); |
| 1007 | } |
| 1008 | |
| 1009 | #[test] |
| 1010 | fn searching_never_spends_the_sign_in_allowance() { |
| 1011 | |
| 1012 | |
| 1013 | let searches = SearchLimiter::default().0; |
| 1014 | |
| 1015 | for _ in 0..SEARCH_GLOBAL { |
| 1016 | let _ = searches.check("a"); |
| 1017 | } |
| 1018 | |
| 1019 | assert!(matches!( |
| 1020 | RateLimiter::default().check("a"), |
| 1021 | Decision::Allowed |
| 1022 | )); |
| 1023 | assert!(matches!( |
| 1024 | ArchiveLimiter::default().0.check("a"), |
| 1025 | Decision::Allowed |
| 1026 | )); |
| 1027 | } |
| 1028 | |
| 1029 | #[test] |
| 1030 | fn the_search_global_window_backstops_a_forged_client_key() { |
| 1031 | |
| 1032 | |
| 1033 | let limiter = SearchLimiter::default().0; |
| 1034 | |
| 1035 | for key in 0..SEARCH_GLOBAL { |
| 1036 | assert!(matches!(limiter.check(&key.to_string()), Decision::Allowed)); |
| 1037 | } |
| 1038 | assert!(matches!(limiter.check("fresh"), Decision::Throttled(_))); |
| 1039 | } |
| 1040 | } |