footing 0.5.5

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

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

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

use crate::{
    http::{RequestContext, to_lower_hex},
    observability::{MetricRecorder, RecordingFailures},
};

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

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

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.
    ///
    /// If the store is bound to one policy (as [`TokenBucketRateLimiter`] is),
    /// `config` must match that policy. A mismatch fails closed during checks.
    /// The store owns its clock, including when backed by a shared database.
    #[must_use]
    pub fn new(
        config: RateLimitConfig,
        key_source: RateLimitKeySource,
        store: Arc<dyn RateLimitStore>,
    ) -> Self {
        Self {
            config,
            store,
            key_source,
            metrics: None,
            recording_failures: RecordingFailures::default(),
        }
    }

    /// Creates a runtime backed by the bounded in-memory store.
    /// Each call creates independent balances; clones share the same store.
    #[must_use]
    pub fn in_memory(config: RateLimitConfig, key_source: RateLimitKeySource) -> Self {
        Self::new(
            config,
            key_source,
            Arc::new(TokenBucketRateLimiter::new(config)),
        )
    }

    #[must_use]
    /// Uses an existing limiter, including its clock and current balances.
    pub fn from_limiter(
        limiter: Arc<TokenBucketRateLimiter<String>>,
        key_source: RateLimitKeySource,
    ) -> Self {
        Self::new(limiter.config(), key_source, limiter)
    }

    #[must_use]
    /// Configures decision and store-error metrics.
    /// Failed store checks are counted separately with `stage=check` and a stable
    /// `error_code`; missing keys and ordinary denials are not store failures.
    /// Backend messages and bucket keys are never metric labels. Failed metric
    /// writes increment [`Self::failed_recordings`].
    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 metrics.
    pub fn metrics(&self) -> Option<&Arc<dyn MetricRecorder>> {
        self.metrics.as_ref()
    }

    /// Returns failed metric writes across clones of this runtime.
    #[must_use]
    pub fn failed_recordings(&self) -> u64 {
        self.recording_failures.count()
    }
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Enumerates the supported rate limit key source values.
pub enum RateLimitKeySource {
    /// Indicates client IP.
    ClientIp,
    /// Uses the verified principal's tenant, kind, and identifier.
    Principal,
    /// Shares one bucket among all verified principals belonging to a tenant.
    ///
    /// Users, clients and service accounts in the same tenant share the quota.
    /// A missing principal or tenant fails closed; client headers do not supply
    /// this identity. Like `Principal`, this requires the stack's authentication hook.
    Tenant,
    /// A custom header that a trusted upstream strips and overwrites.
    /// The caller must ensure the upstream removes client-supplied values.
    TrustedHeader(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::Principal => formatter.write_str("Principal"),
            Self::Tenant => formatter.write_str("Tenant"),
            Self::TrustedHeader(header) => formatter
                .debug_tuple("TrustedHeader")
                .field(header)
                .finish(),
            Self::Fixed(_) => formatter.debug_tuple("Fixed").field(&"[REDACTED]").finish(),
        }
    }
}

impl RateLimitKeySource {
    #[must_use]
    /// Uses a custom header that is stripped and overwritten upstream.
    /// The caller must ensure the upstream removes all client-supplied values.
    pub const fn trusted_header_from_upstream(name: HeaderName) -> Self {
        Self::TrustedHeader(name)
    }

    #[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::Principal => request
                .extensions()
                .get::<RequestContext>()
                .and_then(RequestContext::principal)
                .map(hash_principal_rate_limit_key),
            Self::Tenant => request
                .extensions()
                .get::<RequestContext>()
                .and_then(RequestContext::principal)
                .and_then(crate::auth::Principal::tenant_id)
                .map(|tenant| {
                    let mut hasher = Sha256::new();
                    hasher.update(b"footing-rate-limit-tenant-v1\0");
                    hash_rate_limit_part(&mut hasher, tenant.as_bytes());
                    format!("tenant:{}", to_lower_hex(&hasher.finalize()))
                }),
            Self::TrustedHeader(header) => {
                let mut values = request.headers().get_all(header).iter();
                let value = values.next()?.to_str().ok()?.trim();
                if values.next().is_some()
                    || value.is_empty()
                    || value.len() > MAX_RATE_LIMIT_HEADER_VALUE_BYTES
                {
                    return None;
                }
                Some(hash_header_rate_limit_key(header, value))
            }
            Self::Fixed(value) => Some(value.clone()),
        }
    }
}

fn hash_principal_rate_limit_key(principal: &crate::auth::Principal) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"footing-rate-limit-principal-v1\0");
    match principal.tenant_id() {
        Some(tenant) => {
            hasher.update([1]);
            hash_rate_limit_part(&mut hasher, tenant.as_bytes());
        }
        None => hasher.update([0]),
    }
    hash_rate_limit_part(
        &mut hasher,
        match principal.kind() {
            crate::auth::PrincipalKind::User => b"user",
            crate::auth::PrincipalKind::Client => b"client",
            crate::auth::PrincipalKind::ServiceAccount => b"service_account",
        },
    );
    hash_rate_limit_part(&mut hasher, principal.id().as_bytes());
    format!("principal:{}", to_lower_hex(&hasher.finalize()))
}

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);
}