| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use axum::Router; |
| 11 | use axum::body::Body; |
| 12 | use axum::http::{Request, StatusCode}; |
| 13 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 14 | use hezarfen_backend::state::AppState; |
| 15 | use hezarfen_backend::{build_router, database}; |
| 16 | use serde_json::{Value, json}; |
| 17 | use tower::ServiceExt; |
| 18 | |
| 19 | |
| 20 | async fn app_with(rate_limit: RateLimitConfig) -> Router { |
| 21 | let tenants = database::init_test_tenants().await; |
| 22 | build_router(AppState { |
| 23 | db: tenants.control().clone(), |
| 24 | tenants, |
| 25 | files_path: tempfile::tempdir().expect("files dir").keep(), |
| 26 | cookie_secure: false, |
| 27 | rate_limit, |
| 28 | chatbot_limit: Default::default(), |
| 29 | rag_limit: Default::default(), |
| 30 | exam_presence: Default::default(), |
| 31 | board_hub: Default::default(), |
| 32 | ai: None, |
| 33 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 34 | }) |
| 35 | } |
| 36 | |
| 37 | |
| 38 | |
| 39 | async fn send_as( |
| 40 | app: &Router, |
| 41 | ip: &str, |
| 42 | method: &str, |
| 43 | uri: &str, |
| 44 | body: Option<Value>, |
| 45 | ) -> (StatusCode, Value, Option<u64>) { |
| 46 | let builder = Request::builder() |
| 47 | .method(method) |
| 48 | .uri(uri) |
| 49 | .header("x-forwarded-for", ip); |
| 50 | let request = match body { |
| 51 | Some(b) => builder |
| 52 | .header("content-type", "application/json") |
| 53 | .body(Body::from(b.to_string())) |
| 54 | .unwrap(), |
| 55 | None => builder.body(Body::empty()).unwrap(), |
| 56 | }; |
| 57 | |
| 58 | let response = app.clone().oneshot(request).await.unwrap(); |
| 59 | let status = response.status(); |
| 60 | let retry_after = response |
| 61 | .headers() |
| 62 | .get("retry-after") |
| 63 | .and_then(|v| v.to_str().ok()) |
| 64 | .and_then(|v| v.parse().ok()); |
| 65 | let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) |
| 66 | .await |
| 67 | .unwrap(); |
| 68 | let body = serde_json::from_slice(&bytes).unwrap_or(Value::Null); |
| 69 | (status, body, retry_after) |
| 70 | } |
| 71 | |
| 72 | fn bad_login() -> Option<Value> { |
| 73 | Some(json!({ "username": "ghost", "password": "wrong-pass" })) |
| 74 | } |
| 75 | |
| 76 | fn auth_only(per_minute: u32) -> RateLimitConfig { |
| 77 | RateLimitConfig { |
| 78 | auth_per_minute: per_minute, |
| 79 | api_per_minute: 0, |
| 80 | trust_proxy: true, |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | #[tokio::test] |
| 85 | async fn login_attempts_hit_the_auth_limit() { |
| 86 | let app = app_with(auth_only(3)).await; |
| 87 | |
| 88 | for i in 1..=3 { |
| 89 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 90 | assert_eq!( |
| 91 | status, |
| 92 | StatusCode::UNAUTHORIZED, |
| 93 | "attempt {i} still allowed" |
| 94 | ); |
| 95 | } |
| 96 | |
| 97 | let (status, body, retry_after) = |
| 98 | send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 99 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 100 | assert_eq!(body["error"], "too many requests"); |
| 101 | let secs = retry_after.expect("429 must carry Retry-After"); |
| 102 | assert!((1..=60).contains(&secs), "Retry-After {secs} out of range"); |
| 103 | } |
| 104 | |
| 105 | #[tokio::test] |
| 106 | async fn register_and_login_share_the_auth_bucket() { |
| 107 | let app = app_with(auth_only(2)).await; |
| 108 | let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "secret1" }); |
| 109 | |
| 110 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/register", Some(creds)).await; |
| 111 | assert_eq!(status, StatusCode::CREATED); |
| 112 | let (status, _, _) = send_as( |
| 113 | &app, |
| 114 | "1.1.1.1", |
| 115 | "POST", |
| 116 | "/auth/login", |
| 117 | Some(json!({ "username": "ada", "password": "secret1" })), |
| 118 | ) |
| 119 | .await; |
| 120 | assert_eq!(status, StatusCode::OK); |
| 121 | |
| 122 | |
| 123 | |
| 124 | let (status, _, _) = send_as( |
| 125 | &app, |
| 126 | "1.1.1.1", |
| 127 | "POST", |
| 128 | "/auth/login", |
| 129 | Some(json!({ "username": "ada", "password": "secret1" })), |
| 130 | ) |
| 131 | .await; |
| 132 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 133 | } |
| 134 | |
| 135 | #[tokio::test] |
| 136 | async fn clients_are_limited_independently() { |
| 137 | let app = app_with(auth_only(1)).await; |
| 138 | |
| 139 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 140 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 141 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 142 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "1.1.1.1 exhausted"); |
| 143 | |
| 144 | |
| 145 | let (status, _, _) = send_as(&app, "2.2.2.2", "POST", "/auth/login", bad_login()).await; |
| 146 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 147 | } |
| 148 | |
| 149 | #[tokio::test] |
| 150 | async fn auth_limit_spares_me_logout_and_the_rest_of_the_api() { |
| 151 | let app = app_with(auth_only(1)).await; |
| 152 | |
| 153 | |
| 154 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 155 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 156 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 157 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 158 | |
| 159 | |
| 160 | let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/auth/me", None).await; |
| 161 | assert_eq!(status, StatusCode::UNAUTHORIZED, "me is not rate limited"); |
| 162 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/logout", None).await; |
| 163 | assert_eq!(status, StatusCode::NO_CONTENT, "logout is not rate limited"); |
| 164 | let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; |
| 165 | assert_eq!(status, StatusCode::OK, "health is not rate limited"); |
| 166 | } |
| 167 | |
| 168 | #[tokio::test] |
| 169 | async fn api_limit_meters_every_route() { |
| 170 | let app = app_with(RateLimitConfig { |
| 171 | auth_per_minute: 0, |
| 172 | api_per_minute: 5, |
| 173 | trust_proxy: true, |
| 174 | }) |
| 175 | .await; |
| 176 | |
| 177 | for i in 1..=5 { |
| 178 | let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; |
| 179 | assert_eq!(status, StatusCode::OK, "request {i} still allowed"); |
| 180 | } |
| 181 | let (status, body, retry_after) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; |
| 182 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 183 | assert_eq!(body["error"], "too many requests"); |
| 184 | assert!(retry_after.is_some()); |
| 185 | } |
| 186 | |
| 187 | #[tokio::test] |
| 188 | async fn zero_disables_a_tier() { |
| 189 | let app = app_with(RateLimitConfig::unlimited()).await; |
| 190 | for _ in 0..20 { |
| 191 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 192 | assert_eq!(status, StatusCode::UNAUTHORIZED, "never 429 when disabled"); |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | #[tokio::test] |
| 197 | async fn forwarded_header_is_ignored_unless_proxy_is_trusted() { |
| 198 | let app = app_with(RateLimitConfig { |
| 199 | auth_per_minute: 2, |
| 200 | api_per_minute: 0, |
| 201 | trust_proxy: false, |
| 202 | }) |
| 203 | .await; |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | for (i, ip) in ["1.1.1.1", "2.2.2.2"].iter().enumerate() { |
| 209 | let (status, _, _) = send_as(&app, ip, "POST", "/auth/login", bad_login()).await; |
| 210 | assert_eq!(status, StatusCode::UNAUTHORIZED, "attempt {i} allowed"); |
| 211 | } |
| 212 | let (status, _, _) = send_as(&app, "3.3.3.3", "POST", "/auth/login", bad_login()).await; |
| 213 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 214 | } |
| 215 | |
| 216 | #[tokio::test] |
| 217 | async fn only_the_rightmost_forwarded_hop_counts() { |
| 218 | let app = app_with(auth_only(2)).await; |
| 219 | |
| 220 | |
| 221 | let (status, _, _) = |
| 222 | send_as(&app, "6.6.6.6, 9.9.9.9", "POST", "/auth/login", bad_login()).await; |
| 223 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 224 | let (status, _, _) = |
| 225 | send_as(&app, "7.7.7.7, 9.9.9.9", "POST", "/auth/login", bad_login()).await; |
| 226 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 227 | let (status, _, _) = |
| 228 | send_as(&app, "8.8.8.8, 9.9.9.9", "POST", "/auth/login", bad_login()).await; |
| 229 | assert_eq!( |
| 230 | status, |
| 231 | StatusCode::TOO_MANY_REQUESTS, |
| 232 | "forged left-hand entries must not evade the limit" |
| 233 | ); |
| 234 | } |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | #[tokio::test] |
| 241 | async fn only_the_last_forwarded_header_line_counts() { |
| 242 | let app = app_with(auth_only(2)).await; |
| 243 | |
| 244 | let attempt = |forged: &'static str| { |
| 245 | let app = app.clone(); |
| 246 | async move { |
| 247 | let request = Request::builder() |
| 248 | .method("POST") |
| 249 | .uri("/auth/login") |
| 250 | .header("x-forwarded-for", forged) |
| 251 | .header("x-forwarded-for", "9.9.9.9") |
| 252 | .header("content-type", "application/json") |
| 253 | .body(Body::from(bad_login().unwrap().to_string())) |
| 254 | .unwrap(); |
| 255 | app.oneshot(request).await.unwrap().status() |
| 256 | } |
| 257 | }; |
| 258 | |
| 259 | assert_eq!(attempt("1.1.1.1").await, StatusCode::UNAUTHORIZED); |
| 260 | assert_eq!(attempt("2.2.2.2").await, StatusCode::UNAUTHORIZED); |
| 261 | assert_eq!( |
| 262 | attempt("3.3.3.3").await, |
| 263 | StatusCode::TOO_MANY_REQUESTS, |
| 264 | "a forged first line must not mint a fresh bucket per attempt" |
| 265 | ); |
| 266 | } |
| 267 | |
| 268 | #[tokio::test] |
| 269 | async fn ipv6_clients_are_keyed_too() { |
| 270 | let app = app_with(auth_only(1)).await; |
| 271 | |
| 272 | let (status, _, _) = send_as(&app, "2001:db8::1", "POST", "/auth/login", bad_login()).await; |
| 273 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 274 | let (status, _, _) = send_as(&app, "2001:db8::1", "POST", "/auth/login", bad_login()).await; |
| 275 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 276 | |
| 277 | let (status, _, _) = send_as(&app, "2001:db8::2", "POST", "/auth/login", bad_login()).await; |
| 278 | assert_eq!( |
| 279 | status, |
| 280 | StatusCode::UNAUTHORIZED, |
| 281 | "distinct v6 client is fresh" |
| 282 | ); |
| 283 | } |
| 284 | |
| 285 | #[tokio::test] |
| 286 | async fn malformed_forwarded_entries_share_the_fallback_bucket() { |
| 287 | let app = app_with(auth_only(2)).await; |
| 288 | |
| 289 | |
| 290 | |
| 291 | for garbage in ["not-an-ip", "999.1.2.3"] { |
| 292 | let (status, _, _) = send_as(&app, garbage, "POST", "/auth/login", bad_login()).await; |
| 293 | assert_eq!(status, StatusCode::UNAUTHORIZED, "{garbage:?} allowed once"); |
| 294 | } |
| 295 | let (status, _, _) = send_as(&app, "also;garbage", "POST", "/auth/login", bad_login()).await; |
| 296 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 297 | } |
| 298 | |
| 299 | #[tokio::test] |
| 300 | async fn auth_denials_still_spend_the_api_budget() { |
| 301 | |
| 302 | |
| 303 | |
| 304 | let app = app_with(RateLimitConfig { |
| 305 | auth_per_minute: 1, |
| 306 | api_per_minute: 3, |
| 307 | trust_proxy: true, |
| 308 | }) |
| 309 | .await; |
| 310 | |
| 311 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 312 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 313 | for _ in 0..2 { |
| 314 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; |
| 315 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 316 | } |
| 317 | |
| 318 | |
| 319 | let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; |
| 320 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); |
| 321 | |
| 322 | |
| 323 | let (status, _, _) = send_as(&app, "2.2.2.2", "GET", "/health", None).await; |
| 324 | assert_eq!(status, StatusCode::OK); |
| 325 | } |
| 326 | |
| 327 | #[tokio::test] |
| 328 | async fn concurrent_bursts_never_over_admit() { |
| 329 | let app = app_with(RateLimitConfig { |
| 330 | auth_per_minute: 0, |
| 331 | api_per_minute: 5, |
| 332 | trust_proxy: true, |
| 333 | }) |
| 334 | .await; |
| 335 | |
| 336 | |
| 337 | |
| 338 | let mut set = tokio::task::JoinSet::new(); |
| 339 | for _ in 0..20 { |
| 340 | let app = app.clone(); |
| 341 | set.spawn(async move { send_as(&app, "1.1.1.1", "GET", "/health", None).await.0 }); |
| 342 | } |
| 343 | |
| 344 | let (mut ok, mut limited) = (0, 0); |
| 345 | while let Some(status) = set.join_next().await { |
| 346 | match status.unwrap() { |
| 347 | StatusCode::OK => ok += 1, |
| 348 | StatusCode::TOO_MANY_REQUESTS => limited += 1, |
| 349 | other => panic!("unexpected status {other}"), |
| 350 | } |
| 351 | } |
| 352 | assert_eq!((ok, limited), (5, 15)); |
| 353 | } |
| 354 | |
| 355 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | #[tokio::test] |
| 362 | async fn keyless_clients_share_one_budget_once_the_map_is_saturated() { |
| 363 | use hezarfen_backend::constant::{PURGE_AT, RATE_LIMIT_OVERFLOW_MAX}; |
| 364 | |
| 365 | |
| 366 | |
| 367 | let limiter = UserRateLimiter::per_user_minute(1); |
| 368 | for i in 0..PURGE_AT { |
| 369 | assert!(limiter.enforce_user(&format!("flood-{i}")).is_ok()); |
| 370 | } |
| 371 | assert!( |
| 372 | limiter.enforce_user("flood-0").is_err(), |
| 373 | "the map must be full of exhausted buckets" |
| 374 | ); |
| 375 | |
| 376 | |
| 377 | for i in 0..RATE_LIMIT_OVERFLOW_MAX { |
| 378 | assert!( |
| 379 | limiter.enforce_user(&format!("newcomer-{i}")).is_ok(), |
| 380 | "newcomer {i} is within the shared overflow budget" |
| 381 | ); |
| 382 | } |
| 383 | assert!( |
| 384 | limiter.enforce_user("newcomer-last").is_err(), |
| 385 | "past the shared budget a keyless client must be refused, not admitted" |
| 386 | ); |
| 387 | } |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | use hezarfen_backend::constant::{RATE_SYNC_INTERVAL_SECS, RATE_SYNC_TIMEOUT_SECS}; |
| 402 | use hezarfen_backend::database::Database; |
| 403 | use hezarfen_backend::rate_limit::UserRateLimiter; |
| 404 | use hezarfen_backend::tenant::Tenants; |
| 405 | use std::time::Duration; |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | |
| 411 | async fn shared_db() -> (Tenants, Database) { |
| 412 | let tenants = database::init_test_tenants().await; |
| 413 | let db = tenants.control().clone(); |
| 414 | tokio::time::pause(); |
| 415 | (tenants, db) |
| 416 | } |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | async fn sync_round() { |
| 423 | |
| 424 | |
| 425 | |
| 426 | tokio::task::yield_now().await; |
| 427 | tokio::time::advance(Duration::from_secs(RATE_SYNC_INTERVAL_SECS)).await; |
| 428 | tokio::time::resume(); |
| 429 | tokio::time::sleep(Duration::from_millis(2000)).await; |
| 430 | tokio::time::pause(); |
| 431 | } |
| 432 | |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | async fn read_shared_hits(db: &Database) -> Vec<i64> { |
| 438 | tokio::time::resume(); |
| 439 | let rows = sqlx::query_scalar::<_, i64>("SELECT hits FROM rate_limit") |
| 440 | .fetch_all(db) |
| 441 | .await |
| 442 | .expect("read shared counters"); |
| 443 | tokio::time::pause(); |
| 444 | rows |
| 445 | } |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | const PINNED_WINDOW: i64 = 60_000; |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | fn two_processes(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter) { |
| 460 | let (a, b) = ( |
| 461 | UserRateLimiter::per_user_minute(max), |
| 462 | UserRateLimiter::per_user_minute(max), |
| 463 | ); |
| 464 | a.share_pinned("test", db.clone(), PINNED_WINDOW); |
| 465 | b.share_pinned("test", db.clone(), PINNED_WINDOW); |
| 466 | (a, b) |
| 467 | } |
| 468 | |
| 469 | |
| 470 | fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize { |
| 471 | (0..tries) |
| 472 | .filter(|_| limiter.enforce_user(user).is_ok()) |
| 473 | .count() |
| 474 | } |
| 475 | |
| 476 | #[tokio::test] |
| 477 | async fn a_restarted_process_inherits_the_windows_spend() { |
| 478 | let (_tenants, db) = shared_db().await; |
| 479 | let (a, b) = two_processes(6, &db); |
| 480 | |
| 481 | |
| 482 | |
| 483 | let spent = admits(&a, "user:a", 6) + admits(&b, "user:a", 6); |
| 484 | assert_eq!(spent, 12, "each process starts on its own local budget"); |
| 485 | |
| 486 | |
| 487 | |
| 488 | sync_round().await; |
| 489 | sync_round().await; |
| 490 | assert_eq!( |
| 491 | admits(&a, "user:a", 6) + admits(&b, "user:a", 6), |
| 492 | 0, |
| 493 | "the shared budget is spent" |
| 494 | ); |
| 495 | |
| 496 | |
| 497 | let rows = read_shared_hits(&db).await; |
| 498 | assert_eq!(rows, vec![spent as i64]); |
| 499 | } |
| 500 | |
| 501 | #[tokio::test] |
| 502 | async fn a_process_that_never_admitted_still_learns_the_budget_is_gone() { |
| 503 | let (_tenants, db) = shared_db().await; |
| 504 | let (a, b) = two_processes(4, &db); |
| 505 | |
| 506 | |
| 507 | assert_eq!(admits(&b, "user:a", 1), 1); |
| 508 | assert_eq!(admits(&a, "user:a", 3), 3); |
| 509 | sync_round().await; |
| 510 | sync_round().await; |
| 511 | |
| 512 | assert_eq!( |
| 513 | admits(&b, "user:a", 3), |
| 514 | 0, |
| 515 | "the shared total, not b's own count, is the cap" |
| 516 | ); |
| 517 | |
| 518 | assert_eq!(admits(&b, "user:b", 4), 4); |
| 519 | } |
| 520 | |
| 521 | #[tokio::test] |
| 522 | async fn a_down_database_leaves_each_process_on_its_local_budget() { |
| 523 | let (_tenants, db) = shared_db().await; |
| 524 | let (a, b) = two_processes(3, &db); |
| 525 | |
| 526 | |
| 527 | |
| 528 | |
| 529 | tokio::time::resume(); |
| 530 | sqlx::query("ALTER TABLE rate_limit RENAME TO rate_limit_out") |
| 531 | .execute(&db) |
| 532 | .await |
| 533 | .expect("take the shared table away"); |
| 534 | tokio::time::pause(); |
| 535 | |
| 536 | |
| 537 | |
| 538 | for _ in 0..3 { |
| 539 | sync_round().await; |
| 540 | assert_eq!(admits(&a, "user:a", 1), 1); |
| 541 | assert_eq!(admits(&b, "user:a", 1), 1); |
| 542 | } |
| 543 | assert_eq!(admits(&a, "user:a", 1), 0, "the local budget still binds"); |
| 544 | assert_eq!(admits(&b, "user:a", 1), 0); |
| 545 | |
| 546 | |
| 547 | |
| 548 | tokio::time::resume(); |
| 549 | tokio::time::sleep(Duration::from_secs(RATE_SYNC_TIMEOUT_SECS + 1)).await; |
| 550 | tokio::time::pause(); |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | tokio::time::resume(); |
| 558 | sqlx::query("ALTER TABLE rate_limit_out RENAME TO rate_limit") |
| 559 | .execute(&db) |
| 560 | .await |
| 561 | .expect("give the shared table back"); |
| 562 | tokio::time::pause(); |
| 563 | let raced: i64 = read_shared_hits(&db).await.iter().sum(); |
| 564 | assert!(raced <= 6, "the deltas are folded once: {raced}"); |
| 565 | |
| 566 | |
| 567 | |
| 568 | |
| 569 | sync_round().await; |
| 570 | sync_round().await; |
| 571 | let rows = read_shared_hits(&db).await; |
| 572 | assert_eq!(rows.iter().sum::<i64>(), 6); |
| 573 | } |
| 574 | |
| 575 | |
| 576 | async fn spawn_server(rate_limit: RateLimitConfig) -> String { |
| 577 | let tenants = database::init_test_tenants().await; |
| 578 | let app = build_router(AppState { |
| 579 | db: tenants.control().clone(), |
| 580 | tenants, |
| 581 | files_path: tempfile::tempdir().expect("files dir").keep(), |
| 582 | cookie_secure: false, |
| 583 | rate_limit, |
| 584 | chatbot_limit: Default::default(), |
| 585 | rag_limit: Default::default(), |
| 586 | exam_presence: Default::default(), |
| 587 | board_hub: Default::default(), |
| 588 | ai: None, |
| 589 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 590 | }); |
| 591 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 592 | let addr = listener.local_addr().unwrap(); |
| 593 | tokio::spawn(async move { |
| 594 | axum::serve( |
| 595 | listener, |
| 596 | app.into_make_service_with_connect_info::<std::net::SocketAddr>(), |
| 597 | ) |
| 598 | .await |
| 599 | .unwrap(); |
| 600 | }); |
| 601 | format!("http://{addr}") |
| 602 | } |
| 603 | |
| 604 | #[tokio::test] |
| 605 | async fn real_connections_are_keyed_by_peer_address() { |
| 606 | let base = spawn_server(RateLimitConfig { |
| 607 | auth_per_minute: 2, |
| 608 | api_per_minute: 0, |
| 609 | trust_proxy: false, |
| 610 | }) |
| 611 | .await; |
| 612 | let client = reqwest::Client::new(); |
| 613 | |
| 614 | |
| 615 | |
| 616 | for spoof in ["1.1.1.1", "2.2.2.2"] { |
| 617 | let res = client |
| 618 | .post(format!("{base}/auth/login")) |
| 619 | .header("x-forwarded-for", spoof) |
| 620 | .json(&json!({ "username": "ghost", "password": "wrong-pass" })) |
| 621 | .send() |
| 622 | .await |
| 623 | .unwrap(); |
| 624 | assert_eq!(res.status(), StatusCode::UNAUTHORIZED); |
| 625 | } |
| 626 | |
| 627 | let res = client |
| 628 | .post(format!("{base}/auth/login")) |
| 629 | .header("x-forwarded-for", "3.3.3.3") |
| 630 | .json(&json!({ "username": "ghost", "password": "wrong-pass" })) |
| 631 | .send() |
| 632 | .await |
| 633 | .unwrap(); |
| 634 | assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS); |
| 635 | let retry_after = res |
| 636 | .headers() |
| 637 | .get("retry-after") |
| 638 | .and_then(|v| v.to_str().ok()) |
| 639 | .and_then(|v| v.parse::<u64>().ok()) |
| 640 | .expect("429 over real HTTP carries Retry-After"); |
| 641 | assert!((1..=60).contains(&retry_after)); |
| 642 | let body: Value = res.json().await.unwrap(); |
| 643 | assert_eq!(body["error"], "too many requests"); |
| 644 | } |
| 645 | |
| 646 | #[tokio::test] |
| 647 | async fn a_limit_of_fifty_admits_exactly_fifty_requests() { |
| 648 | |
| 649 | |
| 650 | let app = app_with(RateLimitConfig { |
| 651 | auth_per_minute: 0, |
| 652 | api_per_minute: 50, |
| 653 | trust_proxy: true, |
| 654 | }) |
| 655 | .await; |
| 656 | |
| 657 | for n in 1..=50 { |
| 658 | let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; |
| 659 | assert_eq!(status, StatusCode::OK, "request {n}/50 must pass"); |
| 660 | } |
| 661 | |
| 662 | let (status, body, retry_after) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; |
| 663 | assert_eq!( |
| 664 | status, |
| 665 | StatusCode::TOO_MANY_REQUESTS, |
| 666 | "request 51 must trip" |
| 667 | ); |
| 668 | assert_eq!(body["error"], "too many requests"); |
| 669 | assert!(retry_after.is_some_and(|s| (1..=60).contains(&s))); |
| 670 | |
| 671 | |
| 672 | |
| 673 | let (status, _, _) = send_as(&app, "2.2.2.2", "GET", "/health", None).await; |
| 674 | assert_eq!(status, StatusCode::OK); |
| 675 | } |
| 676 | |
| 677 | |
| 678 | |
| 679 | |
| 680 | |
| 681 | |
| 682 | |
| 683 | |
| 684 | |
| 685 | |
| 686 | |
| 687 | |
| 688 | |
| 689 | |
| 690 | |
| 691 | #[tokio::test] |
| 692 | async fn every_route_enforces_the_shipped_limit_plus_one() { |
| 693 | |
| 694 | const CENSUS_AUTH: u32 = 2; |
| 695 | const CENSUS_API: u32 = 2; |
| 696 | |
| 697 | let app = app_with(RateLimitConfig { |
| 698 | auth_per_minute: CENSUS_AUTH, |
| 699 | api_per_minute: CENSUS_API, |
| 700 | trust_proxy: true, |
| 701 | }) |
| 702 | .await; |
| 703 | |
| 704 | |
| 705 | |
| 706 | let (status, spec, _) = send_as(&app, "254.0.0.1", "GET", "/api-docs/openapi.json", None).await; |
| 707 | assert_eq!(status, StatusCode::OK); |
| 708 | let paths = spec["paths"].as_object().expect("openapi paths object"); |
| 709 | |
| 710 | let mut routes: Vec<(String, String)> = vec![ |
| 711 | ("GET".into(), "/".into()), |
| 712 | ("GET".into(), "/swagger".into()), |
| 713 | ]; |
| 714 | for (path, item) in paths { |
| 715 | |
| 716 | |
| 717 | let concrete = path.replace(['{', '}'], ""); |
| 718 | for method in item.as_object().expect("path item").keys() { |
| 719 | routes.push((method.to_uppercase(), concrete.clone())); |
| 720 | } |
| 721 | } |
| 722 | assert!( |
| 723 | routes.len() >= 25, |
| 724 | "suspiciously few routes ({}) — OpenAPI enumeration broke?", |
| 725 | routes.len() |
| 726 | ); |
| 727 | |
| 728 | for (i, (method, path)) in routes.iter().enumerate() { |
| 729 | |
| 730 | let ip = format!("203.0.{}.{}", i / 200, (i % 200) + 1); |
| 731 | |
| 732 | |
| 733 | |
| 734 | |
| 735 | let limit = if ["/auth/login", "/auth/register", "/builder/login"].contains(&path.as_str()) |
| 736 | { |
| 737 | CENSUS_AUTH |
| 738 | } else { |
| 739 | CENSUS_API |
| 740 | }; |
| 741 | |
| 742 | for n in 1..=limit { |
| 743 | let (status, _, _) = send_as(&app, &ip, method, path, None).await; |
| 744 | assert_ne!( |
| 745 | status, |
| 746 | StatusCode::TOO_MANY_REQUESTS, |
| 747 | "{method} {path}: request {n}/{limit} must not be limited" |
| 748 | ); |
| 749 | } |
| 750 | let (status, _, retry_after) = send_as(&app, &ip, method, path, None).await; |
| 751 | assert_eq!( |
| 752 | status, |
| 753 | StatusCode::TOO_MANY_REQUESTS, |
| 754 | "{method} {path}: request {}/{limit} must be limited", |
| 755 | limit + 1 |
| 756 | ); |
| 757 | assert!( |
| 758 | retry_after.is_some_and(|s| (1..=60).contains(&s)), |
| 759 | "{method} {path}: 429 must carry a sane Retry-After" |
| 760 | ); |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | #[tokio::test] |
| 772 | async fn a_rejection_is_counted_under_its_tier() { |
| 773 | use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; |
| 774 | use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; |
| 775 | |
| 776 | let exporter = InMemoryMetricExporter::default(); |
| 777 | let provider = SdkMeterProvider::builder() |
| 778 | .with_reader(PeriodicReader::builder(exporter.clone()).build()) |
| 779 | .build(); |
| 780 | opentelemetry::global::set_meter_provider(provider.clone()); |
| 781 | |
| 782 | let app = app_with(RateLimitConfig { |
| 783 | auth_per_minute: 0, |
| 784 | api_per_minute: 2, |
| 785 | trust_proxy: true, |
| 786 | }) |
| 787 | .await; |
| 788 | for _ in 0..2 { |
| 789 | let (status, _, _) = send_as(&app, "9.9.9.9", "GET", "/health", None).await; |
| 790 | assert_eq!(status, StatusCode::OK); |
| 791 | } |
| 792 | let (status, _, _) = send_as(&app, "9.9.9.9", "GET", "/health", None).await; |
| 793 | assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "the tier is spent"); |
| 794 | |
| 795 | provider.force_flush().expect("flush"); |
| 796 | let mut api_rejections = 0u64; |
| 797 | for rm in exporter.get_finished_metrics().expect("exported metrics") { |
| 798 | for scope in rm.scope_metrics() { |
| 799 | for metric in scope.metrics() { |
| 800 | if metric.name() != "rate_limit_rejections_total" { |
| 801 | continue; |
| 802 | } |
| 803 | let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else { |
| 804 | panic!("a counter must export as a u64 sum"); |
| 805 | }; |
| 806 | for point in sum.data_points() { |
| 807 | if point |
| 808 | .attributes() |
| 809 | .any(|kv| kv.key.as_str() == "tier" && kv.value.as_str() == "api") |
| 810 | { |
| 811 | api_rejections = api_rejections.max(point.value()); |
| 812 | } |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | } |
| 817 | assert!( |
| 818 | api_rejections >= 1, |
| 819 | "the 429 must show up on rate_limit_rejections_total{{tier=\"api\"}}" |
| 820 | ); |
| 821 | } |