Skip to main content

seiva_http/
rate_limit.rs

1//! A fixed-window, per-client request rate limiter (OWASP API4).
2//!
3//! OWASP API Security **API4 (Unrestricted Resource Consumption)** asks that a
4//! service bound how much work a single caller can demand. The body-size limit
5//! in [`router`](crate::router) bounds one request; this bounds the *rate* of
6//! requests from one client.
7//!
8//! The design follows the framework's "inject the clock" rule (as
9//! [`seiva_webhooks`](https://docs.rs) does for its replay window): a
10//! [`RateLimiter`] holds a [`Clock`] port, so a test advances time deterministically
11//! instead of sleeping. The algorithm is a fixed window — simple, allocation-light,
12//! and good enough as a first line of defence; a deployment that needs a smoother
13//! token bucket puts a dedicated edge in front.
14//!
15//! The client key is the peer IP from
16//! [`ConnectInfo<SocketAddr>`](axum::extract::ConnectInfo), which the server
17//! runtime installs (see `seiva-server`). A request without that extension (a
18//! non-networked test harness driving the router directly) shares a single
19//! fallback bucket, so the limiter is still exercised but never panics.
20//!
21//! **Behind a reverse proxy**, the peer IP is the proxy's, so every client would
22//! collapse into one bucket. A deployment that terminates TLS at a *single*
23//! trusted edge sets [`RateLimiter::trusting_forwarded_for`] (wired from
24//! [`HttpSecurity`](crate::HttpSecurity)); the limiter then keys on the rightmost
25//! `X-Forwarded-For` entry — the address that trusted proxy observed, which a
26//! client cannot spoof (it can only prepend entries to its left). Deeper proxy
27//! chains need a dedicated edge, per the token-bucket note above.
28//!
29//! The client key carries a **tenant dimension** (OWASP API4, multi-tenant
30//! isolation): an authenticated caller is keyed by `(tenant, peer IP)`, so two
31//! tenants sharing a source IP (a corporate NAT, a mobile carrier, a cloud egress)
32//! get **separate budgets** — one tenant exhausting its rate can no longer `429`
33//! another from the same address. An anonymous caller is keyed by peer IP alone.
34//!
35//! The per-client table is **bounded**: a flood of distinct keys (the very thing
36//! API4 guards against) must not let the limiter itself exhaust memory. At
37//! [`MAX_TRACKED_CLIENTS`] entries the table first drops every window that has
38//! fully elapsed; if it is still full of live counters it **evicts the oldest
39//! window** to make room for the new key. It does *not* fail open (which would let
40//! a flood switch the limiter off globally — a bypass of the very control) nor
41//! reject the fresh client (which would turn the flood into a `429` DoS for
42//! everyone): memory stays capped while the limit keeps applying.
43
44use std::collections::HashMap;
45use std::net::{IpAddr, Ipv4Addr, SocketAddr};
46use std::sync::{Arc, Mutex};
47use std::time::{Duration, SystemTime};
48
49use axum::extract::{ConnectInfo, Request, State};
50use axum::http::{HeaderMap, HeaderValue};
51use axum::middleware::Next;
52use axum::response::{IntoResponse, Response};
53use seiva_identity::Principal;
54use seiva_ports::Clock;
55
56use crate::problem::{Problem, ProblemResponse};
57use crate::request_id::RequestIdExt;
58
59/// How many requests a single client may make per window.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub struct RateLimit {
62    /// The maximum number of requests permitted within one [`window`](Self::window).
63    pub max_requests: u32,
64    /// The length of the fixed window.
65    pub window: Duration,
66}
67
68impl RateLimit {
69    /// A generous default for a general-purpose JSON API: 300 requests per
70    /// minute per client. High enough not to trip a normal UI, low enough to
71    /// blunt a single abusive caller; a deployment tunes it from config.
72    pub const DEFAULT_MAX_REQUESTS: u32 = 300;
73    /// The default window length (60 seconds).
74    pub const DEFAULT_WINDOW: Duration = Duration::from_secs(60);
75}
76
77impl Default for RateLimit {
78    fn default() -> Self {
79        Self {
80            max_requests: Self::DEFAULT_MAX_REQUESTS,
81            window: Self::DEFAULT_WINDOW,
82        }
83    }
84}
85
86/// A [`Clock`] reading the real wall clock. The production default; tests inject
87/// a controllable clock instead.
88#[derive(Debug, Default, Clone, Copy)]
89struct SystemClock;
90
91impl Clock for SystemClock {
92    fn now(&self) -> SystemTime {
93        SystemTime::now()
94    }
95}
96
97/// The identity a request is rate-limited under. An authenticated caller is
98/// scoped by its tenant **and** peer IP, so tenants behind one shared address keep
99/// independent budgets (multi-tenant API4 isolation); an unauthenticated caller is
100/// scoped by peer IP alone.
101#[derive(Debug, Clone, PartialEq, Eq, Hash)]
102enum ClientKey {
103    /// Authenticated caller: `(tenant, peer IP)`.
104    Tenant { tenant: String, ip: IpAddr },
105    /// Unauthenticated (or untenanted) caller: peer IP only.
106    Ip(IpAddr),
107}
108
109impl From<IpAddr> for ClientKey {
110    fn from(ip: IpAddr) -> Self {
111        ClientKey::Ip(ip)
112    }
113}
114
115impl std::fmt::Display for ClientKey {
116    /// The stable string the distributed store keys on. The `t:`/`ip:` prefixes
117    /// keep a tenant named like an IP from colliding with an IP bucket.
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        match self {
120            ClientKey::Tenant { tenant, ip } => write!(f, "t:{tenant}:{ip}"),
121            ClientKey::Ip(ip) => write!(f, "ip:{ip}"),
122        }
123    }
124}
125
126/// One client's fixed-window counter.
127#[derive(Debug, Clone, Copy)]
128struct Window {
129    start: SystemTime,
130    count: u32,
131}
132
133/// The ceiling on distinct client keys the limiter tracks at once. Reaching it
134/// triggers a sweep of elapsed windows; it bounds the table so the limiter cannot
135/// be turned into a memory-exhaustion vector by a flood of distinct source IPs.
136/// ~100k small entries is a few MiB.
137pub const MAX_TRACKED_CLIENTS: usize = 100_000;
138
139/// A shareable fixed-window rate limiter. Cloning shares the same underlying
140/// counters and clock, so the middleware layer and its state stay one limiter.
141///
142/// The counters live under a single `Mutex`. Sharding the lock was tried and
143/// measured (panel finding E5, `benchmarks/hot-path`): under 64 concurrent
144/// distinct-client requests across the full HTTP stack it showed **no** gain —
145/// the critical section (one `HashMap` probe) is too short to contend, and a
146/// per-request shard hash only added cost. A deployment that genuinely needs
147/// cross-replica rate limiting at scale uses the distributed store
148/// (`rate_limit_with_store`, ADR 0015), not a sharded in-process lock.
149#[derive(Clone)]
150pub struct RateLimiter {
151    limit: RateLimit,
152    clock: Arc<dyn Clock>,
153    windows: Arc<Mutex<HashMap<ClientKey, Window>>>,
154    trust_forwarded_for: bool,
155}
156
157impl RateLimiter {
158    /// A limiter over the real wall clock.
159    #[must_use]
160    pub fn new(limit: RateLimit) -> Self {
161        Self::with_clock(limit, Arc::new(SystemClock))
162    }
163
164    /// A limiter over an injected [`Clock`], for deterministic tests.
165    #[must_use]
166    pub fn with_clock(limit: RateLimit, clock: Arc<dyn Clock>) -> Self {
167        Self {
168            limit,
169            clock,
170            windows: Arc::new(Mutex::new(HashMap::new())),
171            trust_forwarded_for: false,
172        }
173    }
174
175    /// Keys on the rightmost `X-Forwarded-For` entry instead of the raw peer IP.
176    ///
177    /// Enable this **only** when the service sits behind a single trusted reverse
178    /// proxy that sets `X-Forwarded-For`: the rightmost entry is the address that
179    /// proxy observed and a client cannot forge it. Left off (the default), the
180    /// limiter keys on the TCP peer — correct for a directly exposed service, but
181    /// collapsing every client into one bucket behind a proxy.
182    #[must_use]
183    pub fn trusting_forwarded_for(mut self, trust: bool) -> Self {
184        self.trust_forwarded_for = trust;
185        self
186    }
187
188    /// Records a request from `key` and reports whether it is permitted.
189    ///
190    /// Returns `Ok(())` when within the window's budget. When the budget is
191    /// exhausted it returns `Err(retry_after)`, the time until the current
192    /// window rolls over, without incrementing (so a flood does not keep
193    /// pushing the reset further out).
194    fn check(&self, key: ClientKey) -> Result<(), Duration> {
195        let now = self.clock.now();
196        let mut windows = self.windows.lock().unwrap_or_else(|e| e.into_inner());
197
198        // Bound the table: a flood of distinct keys must not grow it without end.
199        if windows.len() >= MAX_TRACKED_CLIENTS && !windows.contains_key(&key) {
200            // Drop every window that has fully elapsed — it carries no live
201            // budget, so forgetting it only resets an otherwise-idle key.
202            windows.retain(|_, w| {
203                now.duration_since(w.start).unwrap_or(Duration::ZERO) < self.limit.window
204            });
205            // Still full of *live* counters: evict the oldest window (closest to
206            // rolling over anyway) to make room for the new key. Not fail-open
207            // (which switches the whole limiter off under a flood — a bypass of the
208            // control) and not a blanket reject (which turns the flood into a `429`
209            // DoS for fresh clients); memory stays capped while the limit keeps
210            // applying to every key, new ones included.
211            if windows.len() >= MAX_TRACKED_CLIENTS && !windows.contains_key(&key) {
212                if let Some(oldest) = windows
213                    .iter()
214                    .min_by_key(|(_, w)| w.start)
215                    .map(|(k, _)| k.clone())
216                {
217                    windows.remove(&oldest);
218                }
219            }
220        }
221
222        let window = windows.entry(key).or_insert(Window {
223            start: now,
224            count: 0,
225        });
226
227        // A clock moving backwards (duration_since errors) is treated as "still
228        // in the window": never grants extra budget from a time glitch.
229        let elapsed = now.duration_since(window.start).unwrap_or(Duration::ZERO);
230        if elapsed >= self.limit.window {
231            // The window rolled over: start a fresh one counting this request.
232            window.start = now;
233            window.count = 1;
234            return Ok(());
235        }
236
237        if window.count < self.limit.max_requests {
238            window.count += 1;
239            Ok(())
240        } else {
241            Err(self.limit.window - elapsed)
242        }
243    }
244}
245
246/// The fallback key for a request with no [`ConnectInfo`] (a direct, non-networked
247/// test harness). All such requests share this bucket.
248const UNKNOWN_PEER: IpAddr = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
249
250/// Whether `path` is exempt from rate limiting — the framework's health probes
251/// (`/health/live`, `/health/ready`), which a load balancer polls constantly and
252/// must never be throttled out of service.
253fn is_rate_limit_exempt(path: &str) -> bool {
254    path == "/health/live" || path == "/health/ready"
255}
256
257/// The rightmost parseable `X-Forwarded-For` entry — the address the single
258/// trusted reverse proxy in front observed. A client can prepend forged entries
259/// to the left of the header, but not past the value the trusted proxy appends,
260/// so taking the rightmost resists spoofing. `None` if the header is absent,
261/// unreadable, or holds no parseable address.
262fn forwarded_client_ip(headers: &HeaderMap) -> Option<IpAddr> {
263    headers
264        .get("x-forwarded-for")?
265        .to_str()
266        .ok()?
267        .rsplit(',')
268        .find_map(|entry| entry.trim().parse::<IpAddr>().ok())
269}
270
271/// The key a request is rate-limited under. The peer IP is the trusted forwarded
272/// client IP when `trust_forwarded_for` is set and present, else the TCP peer IP,
273/// else the shared [`UNKNOWN_PEER`] fallback. When the request carries an
274/// authenticated tenant (the `authn` layer runs outside the limiter and installs
275/// the [`Principal`]), the key is scoped by `(tenant, IP)` so tenants sharing an
276/// address keep separate budgets; otherwise it is the IP alone.
277fn client_key(request: &Request, trust_forwarded_for: bool) -> ClientKey {
278    let ip = if trust_forwarded_for {
279        forwarded_client_ip(request.headers())
280    } else {
281        None
282    }
283    .or_else(|| {
284        request
285            .extensions()
286            .get::<ConnectInfo<SocketAddr>>()
287            .map(|ci| ci.0.ip())
288    })
289    .unwrap_or(UNKNOWN_PEER);
290
291    match request
292        .extensions()
293        .get::<Arc<Principal>>()
294        .and_then(|p| p.tenant.clone())
295    {
296        Some(tenant) => ClientKey::Tenant { tenant, ip },
297        None => ClientKey::Ip(ip),
298    }
299}
300
301/// Middleware enforcing a [`RateLimiter`] keyed by client IP.
302///
303/// On an exhausted budget it returns a `429` [`Problem`] carrying a `Retry-After`
304/// header (whole seconds, rounded up). Mount it with
305/// [`axum::middleware::from_fn_with_state`]`(limiter, rate_limit)`.
306pub async fn rate_limit(
307    State(limiter): State<RateLimiter>,
308    request: Request,
309    next: Next,
310) -> Response {
311    // Operational health probes are exempt (§8): a load balancer or orchestrator
312    // polls `/health/*` constantly, and many clients can share one source IP
313    // (a NAT, the proxy itself). Counting probes against a client budget would
314    // let that traffic trip a `429` and get the instance marked unhealthy — a
315    // restart storm. The probes carry no business effect, so they skip the limiter.
316    if is_rate_limit_exempt(request.uri().path()) {
317        return next.run(request).await;
318    }
319
320    let key = client_key(&request, limiter.trust_forwarded_for);
321
322    match limiter.check(key) {
323        Ok(()) => next.run(request).await,
324        Err(retry_after) => {
325            let request_id = request.extensions().request_id();
326            rate_limited_response(retry_after, request.uri().path(), request_id)
327        }
328    }
329}
330
331/// The `429` problem response carrying a `Retry-After` header (whole seconds,
332/// rounded up) — shared by the in-process and the distributed limiters.
333fn rate_limited_response(
334    retry_after: Duration,
335    path: &str,
336    request_id: Option<String>,
337) -> Response {
338    let seconds = retry_after.as_secs() + u64::from(retry_after.subsec_nanos() > 0);
339    let mut response = ProblemResponse(
340        Problem::too_many_requests("request rate limit exceeded")
341            .with_instance(path.to_owned())
342            .with_request_id_opt(request_id),
343    )
344    .into_response();
345    if let Ok(value) = HeaderValue::from_str(&seconds.to_string()) {
346        response.headers_mut().insert("retry-after", value);
347    }
348    response
349}
350
351/// What [`rate_limit_with_store`] does when the shared store itself **errors**
352/// (e.g. a Redis outage) — distinct from the store *returning* a decision.
353///
354/// This is a call-site choice (the [`RateLimitStore`](seiva_ports::RateLimitStore)
355/// port documents the default as fail-open); pick [`FailClosed`](Self::FailClosed)
356/// for a deployment where losing the ceiling is worse than shedding load.
357#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
358pub enum StoreErrorPolicy {
359    /// Serve the request when the store errors. Abuse-dampening must not drop
360    /// legitimate traffic on a limiter outage — the historical default and the
361    /// port's documented contract. The trade-off: while the store is down, every
362    /// replica has lost its ceiling at once, so an auth/OTP endpoint runs
363    /// unthrottled. The fail-open path is logged at **ERROR** (alertable), never
364    /// hidden at WARN, so an operator sees the window it is exercised in.
365    #[default]
366    FailOpen,
367    /// Refuse with `503 Service Unavailable` while the store is unavailable, so
368    /// the ceiling is never silently lifted. Correct for a service that fronts
369    /// authentication/OTP and would rather shed load than brute-force-expose it.
370    FailClosed,
371}
372
373/// A **distributed** rate limiter: the same window + proxy-trust policy as the
374/// in-process [`RateLimiter`], but the budget lives in a shared
375/// [`RateLimitStore`](seiva_ports::RateLimitStore) (e.g. Redis) so it holds
376/// across replicas (ADR 0015). Build one and mount [`rate_limit_with_store`].
377#[derive(Clone)]
378pub struct DistributedRateLimit {
379    store: std::sync::Arc<dyn seiva_ports::RateLimitStore>,
380    limit: RateLimit,
381    trust_forwarded_for: bool,
382    on_store_error: StoreErrorPolicy,
383}
384
385impl DistributedRateLimit {
386    /// A distributed limiter over `store`, enforcing `limit` per client.
387    ///
388    /// On a store error it defaults to [`StoreErrorPolicy::FailOpen`]; call
389    /// [`on_store_error`](Self::on_store_error) to shed load instead.
390    #[must_use]
391    pub fn new(store: std::sync::Arc<dyn seiva_ports::RateLimitStore>, limit: RateLimit) -> Self {
392        Self {
393            store,
394            limit,
395            trust_forwarded_for: false,
396            on_store_error: StoreErrorPolicy::default(),
397        }
398    }
399
400    /// Keys on the rightmost `X-Forwarded-For` entry (single trusted edge only),
401    /// exactly as [`RateLimiter::trusting_forwarded_for`].
402    #[must_use]
403    pub fn trusting_forwarded_for(mut self, trust: bool) -> Self {
404        self.trust_forwarded_for = trust;
405        self
406    }
407
408    /// What to do when the shared store errors (default
409    /// [`StoreErrorPolicy::FailOpen`]).
410    #[must_use]
411    pub fn on_store_error(mut self, policy: StoreErrorPolicy) -> Self {
412        self.on_store_error = policy;
413        self
414    }
415}
416
417/// Middleware enforcing a [`DistributedRateLimit`]. Health probes are exempt (as
418/// in [`rate_limit`]). The store check is atomic in the backend; if the store
419/// errors (a transient outage) the request is permitted — rate limiting is
420/// abuse-dampening, so a limiter outage must not drop legitimate traffic.
421pub async fn rate_limit_with_store(
422    State(cfg): State<DistributedRateLimit>,
423    request: Request,
424    next: Next,
425) -> Response {
426    if is_rate_limit_exempt(request.uri().path()) {
427        return next.run(request).await;
428    }
429    let key = client_key(&request, cfg.trust_forwarded_for).to_string();
430    match cfg
431        .store
432        .check(&key, cfg.limit.max_requests, cfg.limit.window)
433        .await
434    {
435        Ok(seiva_ports::RateLimitDecision::Permitted) => next.run(request).await,
436        Ok(seiva_ports::RateLimitDecision::Limited { retry_after }) => {
437            let request_id = request.extensions().request_id();
438            rate_limited_response(retry_after, request.uri().path(), request_id)
439        }
440        Err(error) => match cfg.on_store_error {
441            StoreErrorPolicy::FailOpen => {
442                // ERROR, not WARN: during the outage every replica has lost its
443                // ceiling at once, so this is the alertable window an operator
444                // must see — not a routine condition to bury.
445                tracing::error!(
446                    target: "seiva::rate_limit", %error, policy = "fail_open",
447                    "rate-limit store unavailable; serving UNTHROTTLED across all replicas",
448                );
449                next.run(request).await
450            }
451            StoreErrorPolicy::FailClosed => {
452                tracing::error!(
453                    target: "seiva::rate_limit", %error, policy = "fail_closed",
454                    "rate-limit store unavailable; shedding load (503)",
455                );
456                let request_id = request.extensions().request_id();
457                store_unavailable_response(request.uri().path(), request_id)
458            }
459        },
460        // A future decision kind this middleware does not yet understand. It is
461        // not a store error, so it follows the same configured policy rather than
462        // silently serving: fail-open serves (forward-compatible), fail-closed
463        // sheds (never lift the ceiling on something we cannot interpret).
464        Ok(other) => match cfg.on_store_error {
465            StoreErrorPolicy::FailOpen => {
466                tracing::warn!(target: "seiva::rate_limit", ?other, "unhandled rate-limit decision; serving");
467                next.run(request).await
468            }
469            StoreErrorPolicy::FailClosed => {
470                tracing::warn!(target: "seiva::rate_limit", ?other, "unhandled rate-limit decision; shedding (503)");
471                let request_id = request.extensions().request_id();
472                store_unavailable_response(request.uri().path(), request_id)
473            }
474        },
475    }
476}
477
478/// The `503` a request gets when the shared rate-limit store is unavailable and
479/// the configured policy is [`StoreErrorPolicy::FailClosed`]. Carries a short
480/// `Retry-After` so a load balancer backs off while the store recovers.
481fn store_unavailable_response(path: &str, request_id: Option<String>) -> Response {
482    let mut response = ProblemResponse(
483        Problem::new(
484            axum::http::StatusCode::SERVICE_UNAVAILABLE,
485            "rate limiter unavailable",
486        )
487        .with_detail("the shared rate-limit store is unavailable; retry shortly")
488        .with_instance(path.to_owned())
489        .with_request_id_opt(request_id),
490    )
491    .into_response();
492    response
493        .headers_mut()
494        .insert("retry-after", HeaderValue::from_static("1"));
495    response
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use axum::body::Body;
502    use axum::http::{Request as HttpRequest, StatusCode};
503    use axum::middleware::from_fn_with_state;
504    use axum::routing::get;
505    use axum::Router;
506    use seiva_testing::FixedClock;
507    use tower::ServiceExt; // for `oneshot`
508
509    fn app(limiter: RateLimiter) -> Router {
510        Router::new()
511            .route("/", get(|| async { "ok" }))
512            .layer(from_fn_with_state(limiter, rate_limit))
513    }
514
515    async fn hit(app: &Router) -> StatusCode {
516        app.clone()
517            .oneshot(HttpRequest::builder().uri("/").body(Body::empty()).unwrap())
518            .await
519            .unwrap()
520            .status()
521    }
522
523    #[tokio::test]
524    async fn allows_up_to_the_limit_then_429s() {
525        let clock = Arc::new(FixedClock::at_unix_secs(0));
526        let limiter = RateLimiter::with_clock(
527            RateLimit {
528                max_requests: 3,
529                window: Duration::from_secs(60),
530            },
531            clock.clone(),
532        );
533        let app = app(limiter);
534
535        // Three requests inside the window are permitted...
536        assert_eq!(hit(&app).await, StatusCode::OK);
537        assert_eq!(hit(&app).await, StatusCode::OK);
538        assert_eq!(hit(&app).await, StatusCode::OK);
539        // ...the fourth is refused.
540        assert_eq!(hit(&app).await, StatusCode::TOO_MANY_REQUESTS);
541    }
542
543    #[tokio::test]
544    async fn store_backed_limiter_permits_up_to_the_limit_then_429s_and_exempts_health() {
545        use seiva_testing::InMemoryRateLimitStore;
546        let store = std::sync::Arc::new(InMemoryRateLimitStore::new());
547        let cfg = DistributedRateLimit::new(
548            store,
549            RateLimit {
550                max_requests: 2,
551                window: Duration::from_secs(60),
552            },
553        );
554        let app = Router::new()
555            .route("/", get(|| async { "ok" }))
556            .route("/health/ready", get(|| async { "ready" }))
557            .layer(from_fn_with_state(cfg, rate_limit_with_store));
558
559        let hit = |path: &'static str| {
560            let app = app.clone();
561            async move {
562                app.oneshot(
563                    HttpRequest::builder()
564                        .uri(path)
565                        .body(Body::empty())
566                        .unwrap(),
567                )
568                .await
569                .unwrap()
570                .status()
571            }
572        };
573
574        // Two permitted, the third over budget.
575        assert_eq!(hit("/").await, StatusCode::OK);
576        assert_eq!(hit("/").await, StatusCode::OK);
577        assert_eq!(hit("/").await, StatusCode::TOO_MANY_REQUESTS);
578        // Health stays exempt even when the business budget is spent.
579        assert_eq!(hit("/health/ready").await, StatusCode::OK);
580        assert_eq!(hit("/health/ready").await, StatusCode::OK);
581    }
582
583    #[tokio::test]
584    async fn health_probes_are_exempt_from_the_limit() {
585        let clock = Arc::new(FixedClock::at_unix_secs(0));
586        let limiter = RateLimiter::with_clock(
587            RateLimit {
588                max_requests: 1,
589                window: Duration::from_secs(60),
590            },
591            clock.clone(),
592        );
593        let app = Router::new()
594            .route("/", get(|| async { "ok" }))
595            .route("/health/live", get(|| async { "live" }))
596            .route("/health/ready", get(|| async { "ready" }))
597            .layer(from_fn_with_state(limiter, rate_limit));
598
599        let probe = |path: &'static str| {
600            let app = app.clone();
601            async move {
602                app.oneshot(
603                    HttpRequest::builder()
604                        .uri(path)
605                        .body(Body::empty())
606                        .unwrap(),
607                )
608                .await
609                .unwrap()
610                .status()
611            }
612        };
613
614        // Hammer the probes well past the budget of 1 — never throttled.
615        for _ in 0..5 {
616            assert_eq!(probe("/health/live").await, StatusCode::OK);
617            assert_eq!(probe("/health/ready").await, StatusCode::OK);
618        }
619        // A business route still consumes and exhausts the same small budget.
620        assert_eq!(probe("/").await, StatusCode::OK);
621        assert_eq!(probe("/").await, StatusCode::TOO_MANY_REQUESTS);
622    }
623
624    #[tokio::test]
625    async fn window_rollover_restores_budget() {
626        let clock = Arc::new(FixedClock::at_unix_secs(0));
627        let limiter = RateLimiter::with_clock(
628            RateLimit {
629                max_requests: 1,
630                window: Duration::from_secs(60),
631            },
632            clock.clone(),
633        );
634        let app = app(limiter);
635
636        assert_eq!(hit(&app).await, StatusCode::OK);
637        assert_eq!(hit(&app).await, StatusCode::TOO_MANY_REQUESTS);
638
639        // Advancing past the window resets the budget.
640        clock.advance(Duration::from_secs(61));
641        assert_eq!(hit(&app).await, StatusCode::OK);
642    }
643
644    #[tokio::test]
645    async fn too_many_requests_carries_retry_after() {
646        let clock = Arc::new(FixedClock::at_unix_secs(0));
647        let limiter = RateLimiter::with_clock(
648            RateLimit {
649                max_requests: 1,
650                window: Duration::from_secs(30),
651            },
652            clock.clone(),
653        );
654        let app = app(limiter);
655
656        assert_eq!(hit(&app).await, StatusCode::OK);
657        let res = app
658            .oneshot(HttpRequest::builder().uri("/").body(Body::empty()).unwrap())
659            .await
660            .unwrap();
661        assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
662        let retry_after: u64 = res.headers()["retry-after"]
663            .to_str()
664            .unwrap()
665            .parse()
666            .unwrap();
667        assert!(retry_after > 0 && retry_after <= 30);
668    }
669
670    #[test]
671    fn forwarded_client_ip_takes_the_rightmost_parseable_entry() {
672        let mut headers = HeaderMap::new();
673        // A client prepends a forged entry; the trusted proxy appends the real
674        // one on the right — that is the one we must key on.
675        headers.insert(
676            "x-forwarded-for",
677            HeaderValue::from_static("9.9.9.9, 203.0.113.7"),
678        );
679        assert_eq!(
680            forwarded_client_ip(&headers),
681            Some("203.0.113.7".parse().unwrap())
682        );
683
684        assert_eq!(forwarded_client_ip(&HeaderMap::new()), None);
685    }
686
687    #[test]
688    fn trusted_forwarded_for_keys_each_client_independently() {
689        let clock = Arc::new(FixedClock::at_unix_secs(0));
690        let limiter = RateLimiter::with_clock(
691            RateLimit {
692                max_requests: 1,
693                window: Duration::from_secs(60),
694            },
695            clock.clone(),
696        )
697        .trusting_forwarded_for(true);
698
699        let a: IpAddr = "203.0.113.1".parse().unwrap();
700        let b: IpAddr = "203.0.113.2".parse().unwrap();
701
702        // One client exhausting its budget does not touch another's — the bug a
703        // single shared (proxy-IP) bucket would cause.
704        assert!(limiter.check(a.into()).is_ok());
705        assert!(limiter.check(a.into()).is_err());
706        assert!(limiter.check(b.into()).is_ok());
707    }
708
709    #[test]
710    fn tenants_sharing_an_ip_get_independent_budgets() {
711        let clock = Arc::new(FixedClock::at_unix_secs(0));
712        let limiter = RateLimiter::with_clock(
713            RateLimit {
714                max_requests: 1,
715                window: Duration::from_secs(60),
716            },
717            clock.clone(),
718        );
719        let ip: IpAddr = "203.0.113.9".parse().unwrap();
720        let acme = ClientKey::Tenant {
721            tenant: "acme".to_owned(),
722            ip,
723        };
724        let globex = ClientKey::Tenant {
725            tenant: "globex".to_owned(),
726            ip,
727        };
728
729        // Same source IP, different tenants: `acme` spending its budget must not
730        // `429` `globex` (the noisy-neighbour bug a per-IP-only key would cause).
731        assert!(limiter.check(acme.clone()).is_ok());
732        assert!(limiter.check(acme).is_err());
733        assert!(limiter.check(globex).is_ok());
734    }
735
736    #[test]
737    fn a_saturated_table_evicts_the_oldest_rather_than_failing_open() {
738        let clock = Arc::new(FixedClock::at_unix_secs(0));
739        let limiter = RateLimiter::with_clock(
740            RateLimit {
741                max_requests: 1,
742                window: Duration::from_secs(3600),
743            },
744            clock.clone(),
745        );
746        // Fill the table with live counters (none elapsed within the long window).
747        for i in 0..(MAX_TRACKED_CLIENTS as u64) {
748            let ip = IpAddr::from([(i >> 24) as u8, (i >> 16) as u8, (i >> 8) as u8, i as u8]);
749            assert!(limiter.check(ip.into()).is_ok());
750        }
751        // A brand-new key under saturation is still tracked (not waved through): it
752        // consumes its single-request budget and the next hit is refused, proving
753        // the limiter did not fail open.
754        let fresh: IpAddr = "198.51.100.1".parse().unwrap();
755        assert!(limiter.check(fresh.into()).is_ok());
756        assert!(limiter.check(fresh.into()).is_err());
757        // And the table stayed bounded.
758        assert!(limiter.windows.lock().unwrap().len() <= MAX_TRACKED_CLIENTS);
759    }
760
761    #[test]
762    fn the_client_table_is_bounded_under_a_flood_of_distinct_keys() {
763        let clock = Arc::new(FixedClock::at_unix_secs(0));
764        let limiter = RateLimiter::with_clock(RateLimit::default(), clock.clone());
765
766        // Far more distinct keys than the cap, all within one window, must not
767        // grow the table past the ceiling: the limiter cannot be the API4 vector
768        // it defends against.
769        for i in 0..(MAX_TRACKED_CLIENTS as u64 + 5_000) {
770            let octets = (i >> 24) as u8;
771            let ip = IpAddr::from([octets, (i >> 16) as u8, (i >> 8) as u8, i as u8]);
772            let _ = limiter.check(ip.into());
773        }
774        let tracked = limiter.windows.lock().unwrap().len();
775        assert!(
776            tracked <= MAX_TRACKED_CLIENTS,
777            "table must stay bounded, got {tracked}"
778        );
779    }
780
781    /// A `RateLimitStore` that always errors — stands in for a Redis outage.
782    struct FailingStore;
783    #[async_trait::async_trait]
784    impl seiva_ports::RateLimitStore for FailingStore {
785        async fn check(
786            &self,
787            _key: &str,
788            _limit: u32,
789            _window: Duration,
790        ) -> seiva_ports::PortResult<seiva_ports::RateLimitDecision> {
791            Err("rate-limit store unreachable".into())
792        }
793    }
794
795    fn store_app(cfg: DistributedRateLimit) -> Router {
796        Router::new()
797            .route("/", get(|| async { "ok" }))
798            .layer(from_fn_with_state(cfg, rate_limit_with_store))
799    }
800
801    async fn status_of(app: &Router) -> Response {
802        app.clone()
803            .oneshot(HttpRequest::builder().uri("/").body(Body::empty()).unwrap())
804            .await
805            .unwrap()
806    }
807
808    #[tokio::test]
809    async fn store_error_fails_open_by_default() {
810        // RL-FAILOPEN-1: the historical contract — a limiter outage must not drop
811        // legitimate traffic. Default policy, so the request is still served.
812        let cfg = DistributedRateLimit::new(
813            Arc::new(FailingStore),
814            RateLimit {
815                max_requests: 1,
816                window: Duration::from_secs(60),
817            },
818        );
819        assert_eq!(status_of(&store_app(cfg)).await.status(), StatusCode::OK);
820    }
821
822    #[tokio::test]
823    async fn store_error_fails_closed_with_503_when_configured() {
824        // RL-FAILOPEN-1: a deployment fronting auth/OTP opts into shedding load so
825        // the brute-force ceiling is never silently lifted during a Redis outage.
826        let cfg = DistributedRateLimit::new(
827            Arc::new(FailingStore),
828            RateLimit {
829                max_requests: 1,
830                window: Duration::from_secs(60),
831            },
832        )
833        .on_store_error(StoreErrorPolicy::FailClosed);
834
835        let res = status_of(&store_app(cfg)).await;
836        assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);
837        assert_eq!(
838            res.headers()
839                .get("retry-after")
840                .and_then(|v| v.to_str().ok()),
841            Some("1"),
842            "a shed 503 must tell the load balancer when to retry"
843        );
844    }
845}