fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! Rate limits per client, as the PHP package's `RateLimit` middleware sets them: each client's
//! tier allows a number of requests per window (guests use the `guest` tier, by IP address), and
//! responses carry `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`. Over the limit,
//! a request gets a 429 `rate_limited` with `Retry-After`.
//!
//! The windows are fixed, as Laravel's `RateLimiter` keeps them: the first request starts a
//! window, and its count resets when the window ends. Counts live in the default cache store, so
//! every server must share it, such as the `database` or `redis` store.

use std::time::Duration;

use laravel::axum::http::{HeaderName, HeaderValue};
use laravel::cache::Repository;
use laravel::http::Response;
use sha2::{Digest, Sha256};

use crate::auth::ApiClient;
use crate::errors::{ApiError, ApiErrorCode};
use crate::{Config, time};

/// One tier's limit: `limit` requests per `per_seconds`, or `None` for no limit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tier {
    pub limit: Option<u64>,
    pub per_seconds: u64,
}

impl Tier {
    /// `limit` requests per `per_seconds` seconds.
    #[must_use]
    pub const fn new(limit: u64, per_seconds: u64) -> Self {
        Self {
            limit: Some(limit),
            per_seconds,
        }
    }

    /// No limit, such as for internal services.
    #[must_use]
    pub const fn unlimited() -> Self {
        Self {
            limit: None,
            per_seconds: 60,
        }
    }
}

/// A request that counted against a limit, for its response's headers.
pub(crate) struct Counted {
    key: String,
    limit: u64,
}

/// The client's tier, or `default` when it has none or names one that is not configured, so a
/// mistyped tier never locks its owner out. Guests use `guest`, falling back to `default`.
fn tier<'a>(config: &'a Config, client: Option<&ApiClient>) -> Option<&'a Tier> {
    let tiers = &config.rate_limit.tiers;
    let named = match client {
        None => Some("guest"),
        Some(client) => client.rate_limit_tier.as_deref(),
    };
    named
        .and_then(|name| tiers.iter().find(|(known, _)| known == name))
        .or_else(|| tiers.iter().find(|(known, _)| known == "default"))
        .map(|(_, tier)| tier)
}

/// Counts the request against its client's limit. `Err` is the 429 for a request over it. A
/// cache store that fails lets the request through, without headers.
pub(crate) async fn hit(
    config: &Config,
    client: Option<&ApiClient>,
    ip: &str,
) -> Result<Option<Counted>, Box<ApiError>> {
    if !config.rate_limit.enabled {
        return Ok(None);
    }
    let Some(&Tier {
        limit: Some(limit),
        per_seconds,
    }) = tier(config, client)
    else {
        return Ok(None);
    };
    let Ok(store) = laravel::cache::manager().default_store() else {
        return Ok(None);
    };
    let who = client.map_or_else(
        || format!("ip:{ip}"),
        |client| format!("client:{}", client.id),
    );
    let key = format!(
        "fusion-stack:rate-limit:{}",
        Sha256::digest(who.as_bytes())
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>()
    );

    if too_many_attempts(&store, &key, limit).await {
        let retry_after = available_in(&store, &key).await.max(1);
        let mut error = ApiError::new(
            ApiErrorCode::RateLimited,
            format!(
                "This client is limited to {limit} requests per {per_seconds} seconds. Retry in {retry_after} seconds."
            ),
        )
        .meta("limit", limit)
        .meta("retry_after", retry_after);
        for (name, value) in headers(limit, 0, retry_after) {
            error = error.header(name, value);
        }
        return Err(Box::new(
            error.header("Retry-After", retry_after.to_string()),
        ));
    }

    // Laravel's RateLimiter::hit: the timer starts the window, and the count lives as long.
    let decay = Duration::from_secs(per_seconds);
    let _ = store
        .add(&timer(&key), time::now() + to_i64(per_seconds), decay)
        .await;
    let added = store.add(&key, 0_i64, decay).await.unwrap_or(false);
    let hits = store.increment(&key, 1).await.ok().flatten();
    if !added && hits == Some(1) {
        let _ = store.put(&key, 1_i64, decay).await;
    }
    Ok(Some(Counted { key, limit }))
}

/// Adds the `RateLimit-*` headers to the response of a request that counted.
pub(crate) async fn add_headers(counted: Option<Counted>, response: Response) -> Response {
    let Some(Counted { key, limit }) = counted else {
        return response;
    };
    let Ok(store) = laravel::cache::manager().default_store() else {
        return response;
    };
    let attempts = attempts(&store, &key).await;
    let reset = available_in(&store, &key).await;
    let mut http = response.into_http();
    for (name, value) in headers(limit, limit.saturating_sub(attempts), reset) {
        if let Ok(value) = HeaderValue::try_from(value) {
            http.headers_mut()
                .append(HeaderName::from_static(name), value);
        }
    }
    Response::from_http(http)
}

fn headers(limit: u64, remaining: u64, reset: u64) -> [(&'static str, String); 3] {
    [
        ("ratelimit-limit", limit.to_string()),
        ("ratelimit-remaining", remaining.to_string()),
        ("ratelimit-reset", reset.to_string()),
    ]
}

fn timer(key: &str) -> String {
    format!("{key}:timer")
}

fn to_i64(value: u64) -> i64 {
    i64::try_from(value).unwrap_or(i64::MAX)
}

async fn attempts(store: &Repository, key: &str) -> u64 {
    store
        .get::<i64>(key)
        .await
        .ok()
        .flatten()
        .and_then(|attempts| u64::try_from(attempts).ok())
        .unwrap_or(0)
}

async fn too_many_attempts(store: &Repository, key: &str, limit: u64) -> bool {
    if attempts(store, key).await < limit {
        return false;
    }
    if store.has(&timer(key)).await.unwrap_or(false) {
        return true;
    }
    // The window ended: start again, as RateLimiter::resetAttempts does.
    let _ = store.forget(key).await;
    false
}

async fn available_in(store: &Repository, key: &str) -> u64 {
    let ends = store.get::<i64>(&timer(key)).await.ok().flatten();
    ends.map_or(0, |ends| u64::try_from(ends - time::now()).unwrap_or(0))
}

#[cfg(test)]
mod tests {
    use super::{Tier, tier};
    use crate::Config;
    use crate::auth::ApiClient;

    #[test]
    fn unknown_tiers_fall_back_to_default() {
        let config = Config::new().rate_limit_tier("sandbox", Tier::new(3, 60));
        let limit = |client: Option<&ApiClient>| tier(&config, client).and_then(|tier| tier.limit);
        assert_eq!(limit(None), Some(60));
        assert_eq!(limit(Some(&ApiClient::new("a"))), Some(300));
        let sandbox = ApiClient::new("b").rate_limit_tier(Some("sandbox"));
        assert_eq!(limit(Some(&sandbox)), Some(3));
        let typo = ApiClient::new("c").rate_limit_tier(Some("sandbx"));
        assert_eq!(limit(Some(&typo)), Some(300));
    }

    #[test]
    fn guests_fall_back_to_default_without_a_guest_tier() {
        let config = Config::new().rate_limit_tier("guest", None);
        assert_eq!(tier(&config, None).and_then(|tier| tier.limit), Some(300));
    }
}