forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

rate_limit.rs821 lines, 31.7 KiBHistoryRawDownload
1//! Router-level rate limiting tests. Each test builds the app with a
2//! deliberately tight [`RateLimitConfig`] and, with `trust_proxy` on, poses as
3//! different clients via the `X-Forwarded-For` header — `oneshot` requests
4//! carry no real peer address, so the header path is also the only way to
5//! separate callers here. The final tests instead boot a real TCP server to
6//! exercise the peer-address (`ConnectInfo`) keying exactly as production runs
7//! it. Window-arithmetic and header-parsing edge cases live as unit tests in
8//! `src/rate_limit.rs` under paused tokio time.
9
10use axum::Router;
11use axum::body::Body;
12use axum::http::{Request, StatusCode};
13use hezarfen_backend::rate_limit::RateLimitConfig;
14use hezarfen_backend::state::AppState;
15use hezarfen_backend::{build_router, database};
16use serde_json::{Value, json};
17use tower::ServiceExt;
18
19/// App with the given limits, backed by a fresh per-test Postgres deployment.
20async 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/// Send one request posing as client `ip` (via `X-Forwarded-For`). Returns the
38/// status, the parsed body, and the `Retry-After` header if present.
39async 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
72fn bad_login() -> Option<Value> {
73 Some(json!({ "username": "ghost", "password": "wrong-pass" }))
74}
75
76fn 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]
85async 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]
106async 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 // Two credential requests spent the whole budget; the third is metered
123 // regardless of whether it would have succeeded.
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]
136async 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 // A different client is untouched by 1.1.1.1's exhausted bucket.
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]
150async fn auth_limit_spares_me_logout_and_the_rest_of_the_api() {
151 let app = app_with(auth_only(1)).await;
152
153 // Exhaust the credential budget.
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 // Same client: session probing, logout, and plain API stay reachable.
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]
169async 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]
188async 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]
197async 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 // Without TRUST_PROXY, spoofed X-Forwarded-For must not mint fresh
206 // buckets: all three land on the shared fallback address and the third
207 // request trips the limit despite claiming three different clients.
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]
217async fn only_the_rightmost_forwarded_hop_counts() {
218 let app = app_with(auth_only(2)).await;
219
220 // Different left (client-forgeable) entries, same rightmost hop: one bucket.
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/// A proxy that appends its hop as a *separate* `X-Forwarded-For` line leaves
237/// the client's forged line first. Billing that first line would mint a bucket
238/// per attempt and the credential tier would never fire, so the last line —
239/// the only one the client cannot write — is what keys the request.
240#[tokio::test]
241async 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]
269async 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]
286async fn malformed_forwarded_entries_share_the_fallback_bucket() {
287 let app = app_with(auth_only(2)).await;
288
289 // Unparseable entries cannot mint per-garbage buckets — they all collapse
290 // onto the fallback address, so the third request trips the shared limit.
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]
300async fn auth_denials_still_spend_the_api_budget() {
301 // Both tiers on: the catch-all api tier is the outer layer, so it meters
302 // raw request volume — including credential attempts the inner auth tier
303 // goes on to reject.
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); // api 1/3, auth 1/1
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); // auth tier; api 2/3 then 3/3
316 }
317
318 // The api budget is gone even though only one login reached a handler.
319 let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await;
320 assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
321
322 // Per-IP, not global: another client is unaffected.
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]
328async 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 // 20 requests race one 5-token bucket; the mutex must admit exactly 5,
337 // no matter how the tasks interleave.
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/// A saturated bucket map must not be a bypass. Fill it to `PURGE_AT` with
356/// exhausted buckets — nothing lapsed, nothing evictable — and every further
357/// *new* key gets no bucket of its own. It is still metered: all of them share
358/// one aggregate budget, `RATE_LIMIT_OVERFLOW_MAX` per window, and past that
359/// they are refused. Admitting them unmetered would let an attacker buy
360/// unlimited throughput from fresh keys after paying to fill the map once.
361#[tokio::test]
362async fn keyless_clients_share_one_budget_once_the_map_is_saturated() {
363 use hezarfen_backend::constant::{PURGE_AT, RATE_LIMIT_OVERFLOW_MAX};
364
365 // One request per key exhausts it, so the map fills with buckets that can
366 // neither be swept (same window) nor evicted (all at their limit).
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 // Distinct newcomers, none of which can get into the map.
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// --- the window outlives the process ------------------------------------
390//
391// Two `UserRateLimiter`s over one control database stand in for the process
392// before and after a restart: two separate sets of in-memory buckets sharing
393// only the `rate_limit` table, which is what stops a restart mid-window from
394// handing every client a fresh budget. Time is paused, so a round of the sync
395// task is driven by advancing past `RATE_SYNC_INTERVAL_SECS` — and because the
396// task blocks on the database (not on time) mid-round, the short sleep
397// afterwards cannot resolve until the round has finished. Assertions stay on
398// admissions and on the rows the fold wrote: which limiter's statement lands
399// first cannot matter, a round is one atomic statement per limiter.
400
401use hezarfen_backend::constant::{RATE_SYNC_INTERVAL_SECS, RATE_SYNC_TIMEOUT_SECS};
402use hezarfen_backend::database::Database;
403use hezarfen_backend::rate_limit::UserRateLimiter;
404use hezarfen_backend::tenant::Tenants;
405use std::time::Duration;
406
407/// A fresh per-test deployment — the trio shares its **control** database,
408/// where the `rate_limit` table lives — with the clock frozen only afterwards:
409/// every pool dials on the real clock, since a paused clock never fires a
410/// connect deadline and a stalled dial would hang the test.
411async 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/// Let the sync task run one round: fire its timer, then hand it *real* time
419/// to finish in. The real time is not optional — a round waits on the database,
420/// and a paused clock auto-advances straight past a virtual sleep while it
421/// does, so the assertions would race the round they are about.
422async fn sync_round() {
423 // Let a freshly spawned task reach its `sleep` first: `advance` moves the
424 // clock *before* it yields, so a timer registered after it is registered
425 // against the new now and would sit out the whole round.
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/// The `rate_limit` rows, read in a resumed window: a pool statement run
434/// directly under the paused clock cannot dial — auto-advance fires the
435/// connect deadline the instant the runtime idles — so every direct
436/// statement here hands the clock back first.
437async 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/// One fixed wall window for every round below. The sync task reads the real
448/// clock, so without this the tests here assert about "the" shared row while a
449/// minute boundary landing between two limiters' rounds would give them a row
450/// each — a run that passes because of when it ran, which is the same
451/// accidental clock dependency that hid the epoch-roll double-charge from this
452/// suite. Rolling *between* windows is covered by the unit tests, which drive
453/// `sync_once`'s epoch directly.
454const PINNED_WINDOW: i64 = 60_000;
455
456/// Two limiters of one tier, sharing `db` and one wall window — the process
457/// before a restart and the process after, which is the only way one deployment
458/// runs two sets of buckets over one `rate_limit` row.
459fn 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/// How many of `tries` requests a limiter admits for `user`.
470fn 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]
477async 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 // Each spends freely until its first sync — the accepted one-interval
482 // overshoot, and the whole reason the shared row exists at all.
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 // Two rounds: each limiter's fold is its own statement, so the process
487 // that landed first only learns the other's spend on the next tick.
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 // And the shared row agrees with what was actually admitted.
497 let rows = read_shared_hits(&db).await;
498 assert_eq!(rows, vec![spent as i64]);
499}
500
501#[tokio::test]
502async 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 // b spends one request, so it has a bucket to sync; a spends the rest.
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 // Other users are untouched by a spent bucket.
518 assert_eq!(admits(&b, "user:b", 4), 4);
519}
520
521#[tokio::test]
522async 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 // The shared store goes down: the fold's table is taken away — the one
527 // statement a round needs fails outright — and comes back without either
528 // limiter being restarted.
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 // Nothing is shared while the database is down — and nothing stalls: both
537 // limiters keep serving their own budgets at full speed.
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 // Drain in-flight folds that started while the table was gone. Restoring
547 // earlier lets a parked query land and the empty-row assert is load luck.
548 tokio::time::resume();
549 tokio::time::sleep(Duration::from_secs(RATE_SYNC_TIMEOUT_SECS + 1)).await;
550 tokio::time::pause();
551
552 // The table comes back. A fold parked inside its statement lands the
553 // moment it does — real I/O the virtual clock cannot order, which is why
554 // this asserts the arithmetic and not the timing: a round that raced the
555 // outage never folds the same deltas twice, and the deltas the outage
556 // could not report are still sitting in the buckets to be carried.
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 // Recovery needs no restart. Two rounds, because each limiter's fold is
567 // its own statement: the shared row ends at everything both processes
568 // admitted while the table was gone — three each, the local budget.
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/// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`.
576async 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]
605async 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 // Every request arrives from 127.0.0.1. Spoofed X-Forwarded-For values
615 // must not matter with TRUST_PROXY off: one peer, one bucket.
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]
647async fn a_limit_of_fifty_admits_exactly_fifty_requests() {
648 // Production-scale boundary through the whole HTTP stack: all 50 budgeted
649 // requests answer 200, the 51st answers 429 — no off-by-one at real sizes.
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 // The 51st being rejected spent nothing extra: a fresh client still has
672 // its own full budget.
673 let (status, _, _) = send_as(&app, "2.2.2.2", "GET", "/health", None).await;
674 assert_eq!(status, StatusCode::OK);
675}
676
677/// Every route is behind a limiter: request `limit` passes, request
678/// `limit + 1` answers 429. The route list is pulled from the app's own
679/// OpenAPI document, so an endpoint added tomorrow is covered automatically;
680/// `/` and the Swagger mount don't appear there and are appended by hand.
681///
682/// The census uses a small budget. The shipped API tier is 30_000 a minute;
683/// hammering that once per route would be millions of requests. Production-scale
684/// exactness lives in the in-memory boundary test. This one proves the wiring:
685/// credential routes hit the auth tier, everything else the api tier.
686///
687/// Each (method, path) pair poses as its own client IP, giving it a fresh
688/// bucket. Requests carry no body — extractors reject them long after the
689/// limiter has counted, which is exactly what makes hammering the credential
690/// endpoints cheap (no argon2 runs for a body-less request).
691#[tokio::test]
692async fn every_route_enforces_the_shipped_limit_plus_one() {
693 // Small on purpose. See the comment above.
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 // Enumerate routes from the spec (fetched under a reserved IP so the
705 // fetch itself doesn't spend any route's budget).
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 // "/notes/{id}" -> "/notes/id": a well-formed URL whose dummy segment
716 // fails lookup in the handler, long after the limiter counted it.
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 // One unique client per route (203.0.x.x is TEST-NET-3).
730 let ip = format!("203.0.{}.{}", i / 200, (i % 200) + 1);
731 // The strict tier owns the credential endpoints — the school's two and
732 // the vendor's own login, which has a budget of its own so a school's
733 // brute-forcer cannot spend it; everything else runs into the catch-all
734 // api tier.
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/// A refusal is not only a status: an operator watching a tier needs the
765/// count. Installs a real meter provider, drives the api tier to its `429` and
766/// reads the counter back out of an in-memory exporter.
767///
768/// It shares the process with the rest of this binary, so the assertion is "at
769/// least one, tagged api" rather than an exact total — another test refusing
770/// concurrently is data on the same series.
771#[tokio::test]
772async 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}