Skip to main content

fusion_stack/
rate_limit.rs

1//! Rate limits per client, as the PHP package's `RateLimit` middleware sets them: each client's
2//! tier allows a number of requests per window (guests use the `guest` tier, by IP address), and
3//! responses carry `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`. Over the limit,
4//! a request gets a 429 `rate_limited` with `Retry-After`.
5//!
6//! The windows are fixed, as Laravel's `RateLimiter` keeps them: the first request starts a
7//! window, and its count resets when the window ends. Counts live in the default cache store, so
8//! every server must share it, such as the `database` or `redis` store.
9
10use std::time::Duration;
11
12use laravel::axum::http::{HeaderName, HeaderValue};
13use laravel::cache::Repository;
14use laravel::http::Response;
15use sha2::{Digest, Sha256};
16
17use crate::auth::ApiClient;
18use crate::errors::{ApiError, ApiErrorCode};
19use crate::{Config, time};
20
21/// One tier's limit: `limit` requests per `per_seconds`, or `None` for no limit.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Tier {
24    pub limit: Option<u64>,
25    pub per_seconds: u64,
26}
27
28impl Tier {
29    /// `limit` requests per `per_seconds` seconds.
30    #[must_use]
31    pub const fn new(limit: u64, per_seconds: u64) -> Self {
32        Self {
33            limit: Some(limit),
34            per_seconds,
35        }
36    }
37
38    /// No limit, such as for internal services.
39    #[must_use]
40    pub const fn unlimited() -> Self {
41        Self {
42            limit: None,
43            per_seconds: 60,
44        }
45    }
46}
47
48/// A request that counted against a limit, for its response's headers.
49pub(crate) struct Counted {
50    key: String,
51    limit: u64,
52}
53
54/// The client's tier, or `default` when it has none or names one that is not configured, so a
55/// mistyped tier never locks its owner out. Guests use `guest`, falling back to `default`.
56fn tier<'a>(config: &'a Config, client: Option<&ApiClient>) -> Option<&'a Tier> {
57    let tiers = &config.rate_limit.tiers;
58    let named = match client {
59        None => Some("guest"),
60        Some(client) => client.rate_limit_tier.as_deref(),
61    };
62    named
63        .and_then(|name| tiers.iter().find(|(known, _)| known == name))
64        .or_else(|| tiers.iter().find(|(known, _)| known == "default"))
65        .map(|(_, tier)| tier)
66}
67
68/// Counts the request against its client's limit. `Err` is the 429 for a request over it. A
69/// cache store that fails lets the request through, without headers.
70pub(crate) async fn hit(
71    config: &Config,
72    client: Option<&ApiClient>,
73    ip: &str,
74) -> Result<Option<Counted>, Box<ApiError>> {
75    if !config.rate_limit.enabled {
76        return Ok(None);
77    }
78    let Some(&Tier {
79        limit: Some(limit),
80        per_seconds,
81    }) = tier(config, client)
82    else {
83        return Ok(None);
84    };
85    let Ok(store) = laravel::cache::manager().default_store() else {
86        return Ok(None);
87    };
88    let who = client.map_or_else(
89        || format!("ip:{ip}"),
90        |client| format!("client:{}", client.id),
91    );
92    let key = format!(
93        "fusion-stack:rate-limit:{}",
94        Sha256::digest(who.as_bytes())
95            .iter()
96            .map(|byte| format!("{byte:02x}"))
97            .collect::<String>()
98    );
99
100    if too_many_attempts(&store, &key, limit).await {
101        let retry_after = available_in(&store, &key).await.max(1);
102        let mut error = ApiError::new(
103            ApiErrorCode::RateLimited,
104            format!(
105                "This client is limited to {limit} requests per {per_seconds} seconds. Retry in {retry_after} seconds."
106            ),
107        )
108        .meta("limit", limit)
109        .meta("retry_after", retry_after);
110        for (name, value) in headers(limit, 0, retry_after) {
111            error = error.header(name, value);
112        }
113        return Err(Box::new(
114            error.header("Retry-After", retry_after.to_string()),
115        ));
116    }
117
118    // Laravel's RateLimiter::hit: the timer starts the window, and the count lives as long.
119    let decay = Duration::from_secs(per_seconds);
120    let _ = store
121        .add(&timer(&key), time::now() + to_i64(per_seconds), decay)
122        .await;
123    let added = store.add(&key, 0_i64, decay).await.unwrap_or(false);
124    let hits = store.increment(&key, 1).await.ok().flatten();
125    if !added && hits == Some(1) {
126        let _ = store.put(&key, 1_i64, decay).await;
127    }
128    Ok(Some(Counted { key, limit }))
129}
130
131/// Adds the `RateLimit-*` headers to the response of a request that counted.
132pub(crate) async fn add_headers(counted: Option<Counted>, response: Response) -> Response {
133    let Some(Counted { key, limit }) = counted else {
134        return response;
135    };
136    let Ok(store) = laravel::cache::manager().default_store() else {
137        return response;
138    };
139    let attempts = attempts(&store, &key).await;
140    let reset = available_in(&store, &key).await;
141    let mut http = response.into_http();
142    for (name, value) in headers(limit, limit.saturating_sub(attempts), reset) {
143        if let Ok(value) = HeaderValue::try_from(value) {
144            http.headers_mut()
145                .append(HeaderName::from_static(name), value);
146        }
147    }
148    Response::from_http(http)
149}
150
151fn headers(limit: u64, remaining: u64, reset: u64) -> [(&'static str, String); 3] {
152    [
153        ("ratelimit-limit", limit.to_string()),
154        ("ratelimit-remaining", remaining.to_string()),
155        ("ratelimit-reset", reset.to_string()),
156    ]
157}
158
159fn timer(key: &str) -> String {
160    format!("{key}:timer")
161}
162
163fn to_i64(value: u64) -> i64 {
164    i64::try_from(value).unwrap_or(i64::MAX)
165}
166
167async fn attempts(store: &Repository, key: &str) -> u64 {
168    store
169        .get::<i64>(key)
170        .await
171        .ok()
172        .flatten()
173        .and_then(|attempts| u64::try_from(attempts).ok())
174        .unwrap_or(0)
175}
176
177async fn too_many_attempts(store: &Repository, key: &str, limit: u64) -> bool {
178    if attempts(store, key).await < limit {
179        return false;
180    }
181    if store.has(&timer(key)).await.unwrap_or(false) {
182        return true;
183    }
184    // The window ended: start again, as RateLimiter::resetAttempts does.
185    let _ = store.forget(key).await;
186    false
187}
188
189async fn available_in(store: &Repository, key: &str) -> u64 {
190    let ends = store.get::<i64>(&timer(key)).await.ok().flatten();
191    ends.map_or(0, |ends| u64::try_from(ends - time::now()).unwrap_or(0))
192}
193
194#[cfg(test)]
195mod tests {
196    use super::{Tier, tier};
197    use crate::Config;
198    use crate::auth::ApiClient;
199
200    #[test]
201    fn unknown_tiers_fall_back_to_default() {
202        let config = Config::new().rate_limit_tier("sandbox", Tier::new(3, 60));
203        let limit = |client: Option<&ApiClient>| tier(&config, client).and_then(|tier| tier.limit);
204        assert_eq!(limit(None), Some(60));
205        assert_eq!(limit(Some(&ApiClient::new("a"))), Some(300));
206        let sandbox = ApiClient::new("b").rate_limit_tier(Some("sandbox"));
207        assert_eq!(limit(Some(&sandbox)), Some(3));
208        let typo = ApiClient::new("c").rate_limit_tier(Some("sandbx"));
209        assert_eq!(limit(Some(&typo)), Some(300));
210    }
211
212    #[test]
213    fn guests_fall_back_to_default_without_a_guest_tier() {
214        let config = Config::new().rate_limit_tier("guest", None);
215        assert_eq!(tier(&config, None).and_then(|tier| tier.limit), Some(300));
216    }
217}