footing 0.1.2

Feature-gated foundations for Rust backend services
Documentation
//! Rate-limit runtime dependencies and request-key extraction.

use std::{fmt, sync::Arc, time::Instant};

use async_trait::async_trait;
use axum::http::{HeaderName, Request};
use sha2::{Digest, Sha256};

use crate::{
    clock::{SharedClock, system_clock},
    http::RequestContext,
    observability::MetricRecorder,
};

use super::memory::RateLimitStore;
use super::{
    memory::{MemoryRateLimitStore, TokenBucketRateLimiter},
    model::{
        MAX_RATE_LIMIT_HEADER_VALUE_BYTES, RateLimitConfig, RateLimitDecision, RateLimitError,
    },
};

#[derive(Clone)]
#[non_exhaustive]
/// Represents rate limit runtime.
pub struct RateLimitRuntime {
    config: RateLimitConfig,
    store: Arc<dyn RateLimitStore>,
    key_source: RateLimitKeySource,
    clock: SharedClock,
    metrics: Option<Arc<dyn MetricRecorder>>,
}

impl fmt::Debug for RateLimitRuntime {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RateLimitRuntime")
            .field("config", &self.config)
            .field("key_source", &self.key_source)
            .finish_non_exhaustive()
    }
}

impl RateLimitRuntime {
    /// Creates a runtime backed by a caller-provided store.
    #[must_use]
    pub fn new(
        config: RateLimitConfig,
        key_source: RateLimitKeySource,
        store: Arc<dyn RateLimitStore>,
    ) -> Self {
        Self {
            config,
            store,
            key_source,
            clock: system_clock(),
            metrics: None,
        }
    }

    /// Creates a runtime backed by the bounded in-memory store.
    #[must_use]
    pub fn in_memory(config: RateLimitConfig, key_source: RateLimitKeySource) -> Self {
        Self::new(
            config,
            key_source,
            Arc::new(MemoryRateLimitStore::new(config)),
        )
    }

    #[must_use]
    /// Creates a value from limiter.
    pub fn from_limiter(
        limiter: Arc<TokenBucketRateLimiter<String>>,
        key_source: RateLimitKeySource,
    ) -> Self {
        Self {
            config: limiter.config(),
            store: Arc::new(TokenBucketRateLimiterStore { limiter }),
            key_source,
            clock: system_clock(),
            metrics: None,
        }
    }

    #[must_use]
    /// Configures clock and returns the updated value.
    pub fn with_clock(mut self, clock: SharedClock) -> Self {
        self.clock = clock;
        self
    }

    #[must_use]
    /// Configures metrics and returns the updated value.
    pub fn with_metrics(mut self, metrics: Option<Arc<dyn MetricRecorder>>) -> Self {
        self.metrics = metrics;
        self
    }

    #[must_use]
    /// Returns the config.
    pub const fn config(&self) -> RateLimitConfig {
        self.config
    }

    #[must_use]
    /// Returns the store.
    pub fn store(&self) -> &Arc<dyn RateLimitStore> {
        &self.store
    }

    #[must_use]
    /// Returns the key source.
    pub const fn key_source(&self) -> &RateLimitKeySource {
        &self.key_source
    }

    #[must_use]
    /// Returns the clock.
    pub fn clock(&self) -> &SharedClock {
        &self.clock
    }

    #[must_use]
    /// Returns the metrics.
    pub fn metrics(&self) -> Option<&Arc<dyn MetricRecorder>> {
        self.metrics.as_ref()
    }
}

#[derive(Debug)]
struct TokenBucketRateLimiterStore {
    limiter: Arc<TokenBucketRateLimiter<String>>,
}

#[async_trait]
impl RateLimitStore for TokenBucketRateLimiterStore {
    async fn check(
        &self,
        key: String,
        config: RateLimitConfig,
        now: Instant,
    ) -> Result<RateLimitDecision, RateLimitError> {
        self.limiter.check_at_with_config(key, config, now)
    }

    async fn prune_idle(&self, older_than: Instant) -> Result<usize, RateLimitError> {
        self.limiter.prune_idle(older_than)
    }
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Enumerates the supported rate limit key source values.
pub enum RateLimitKeySource {
    /// Indicates client IP.
    ClientIp,
    /// Indicates principal identifier.
    PrincipalId,
    /// Indicates request identifier.
    RequestId,
    /// Indicates header.
    Header(HeaderName),
    /// Indicates fixed.
    Fixed(String),
}

impl fmt::Debug for RateLimitKeySource {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ClientIp => formatter.write_str("ClientIp"),
            Self::PrincipalId => formatter.write_str("PrincipalId"),
            Self::RequestId => formatter.write_str("RequestId"),
            Self::Header(name) => formatter.debug_tuple("Header").field(name).finish(),
            Self::Fixed(_) => formatter.debug_tuple("Fixed").field(&"[REDACTED]").finish(),
        }
    }
}

impl RateLimitKeySource {
    #[must_use]
    /// Returns the key for.
    pub fn key_for<B>(&self, request: &Request<B>) -> Option<String> {
        match self {
            Self::ClientIp => request
                .extensions()
                .get::<RequestContext>()
                .and_then(RequestContext::client_ip)
                .map(ToOwned::to_owned),
            Self::PrincipalId => request
                .extensions()
                .get::<RequestContext>()
                .and_then(RequestContext::principal)
                .map(|principal| principal.id().to_owned()),
            Self::RequestId => request
                .extensions()
                .get::<RequestContext>()
                .map(|context| context.request_id().to_string()),
            Self::Header(name) => request
                .headers()
                .get(name)
                .and_then(|value| value.to_str().ok())
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .filter(|value| value.len() <= MAX_RATE_LIMIT_HEADER_VALUE_BYTES)
                .map(|value| hash_header_rate_limit_key(name, value)),
            Self::Fixed(value) => Some(value.clone()),
        }
    }
}

fn hash_header_rate_limit_key(name: &HeaderName, value: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"footing-rate-limit-header-v1\0");
    hash_rate_limit_part(&mut hasher, name.as_str().as_bytes());
    hash_rate_limit_part(&mut hasher, value.as_bytes());
    format!("header:{}", to_lower_hex(&hasher.finalize()))
}

fn hash_rate_limit_part(hasher: &mut Sha256, value: &[u8]) {
    hasher.update(u64::try_from(value.len()).unwrap_or(u64::MAX).to_be_bytes());
    hasher.update(value);
}

fn to_lower_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";

    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(char::from(HEX[usize::from(byte >> 4)]));
        output.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    output
}