footing 0.6.1

Feature-gated foundations for Rust backend services
Documentation
use std::{fmt, time::Duration};

use axum::http::HeaderName;
use serde::{Deserialize, Serialize};

use crate::{
    http::{RateLimitConfig, RateLimitKeySource},
    settings::{SettingsIssues, SettingsValidationError, field_path},
};

use super::super::{error::HttpMiddlewareError, policy::HttpRateLimitConfig};

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for HTTP rate limit.
pub struct HttpRateLimitSettings {
    /// Whether request rate limiting is enabled.
    pub enabled: bool,
    /// Maximum tokens held by each rate-limit bucket.
    pub capacity: u32,
    /// Tokens restored during each refill interval.
    pub refill_tokens: u32,
    #[serde(with = "crate::settings::human_duration")]
    /// Time between token refills.
    pub refill_interval: Duration,
    #[cfg_attr(feature = "tier", tier(secret))]
    /// Request attribute used to select a rate-limit bucket.
    pub key_source: RateLimitKeySourceSettings,
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
#[non_exhaustive]
/// Serializable settings for rate limit key source.
pub enum RateLimitKeySourceSettings {
    #[default]
    /// Indicates client IP.
    ClientIp,
    /// Uses the verified principal’s tenant, kind, and identifier.
    Principal,
    /// A custom header stripped and overwritten by a trusted upstream.
    TrustedHeader(String),
    /// Indicates fixed.
    Fixed(String),
    /// Shares a quota across verified users, clients and service accounts in one tenant.
    /// Requires an authentication hook and a principal with a tenant identifier.
    ///
    /// ```
    /// use footing::http::{HttpRateLimitSettings, RateLimitKeySourceSettings};
    ///
    /// let settings = HttpRateLimitSettings::default()
    ///     .with_enabled(true)
    ///     .with_key_source(RateLimitKeySourceSettings::Tenant);
    /// ```
    Tenant,
}

impl fmt::Debug for RateLimitKeySourceSettings {
    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(name) => {
                formatter.debug_tuple("TrustedHeader").field(name).finish()
            }
            Self::Fixed(_) => formatter.debug_tuple("Fixed").field(&"[REDACTED]").finish(),
        }
    }
}

impl Default for HttpRateLimitSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            capacity: 100,
            refill_tokens: 100,
            refill_interval: Duration::from_secs(60),
            key_source: RateLimitKeySourceSettings::ClientIp,
        }
    }
}

impl HttpRateLimitSettings {
    /// Validates settings beneath `http.rate_limit`.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("http.rate_limit")
    }

    /// Validates settings using their location in the application configuration.
    ///
    /// `path` prefixes every reported field. An empty path reports fields at the
    /// document root; the supplied path is otherwise used unchanged.
    pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        self.build_at(path).map(|_| ())
    }

    #[must_use]
    /// Configures enabled and returns the updated value.
    pub const fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    #[must_use]
    /// Configures capacity and returns the updated value.
    pub const fn with_capacity(mut self, capacity: u32) -> Self {
        self.capacity = capacity;
        self
    }

    #[must_use]
    /// Configures refill tokens and returns the updated value.
    pub const fn with_refill_tokens(mut self, refill_tokens: u32) -> Self {
        self.refill_tokens = refill_tokens;
        self
    }

    #[must_use]
    /// Configures refill interval and returns the updated value.
    pub const fn with_refill_interval(mut self, refill_interval: Duration) -> Self {
        self.refill_interval = refill_interval;
        self
    }

    #[must_use]
    /// Configures key source and returns the updated value.
    pub fn with_key_source(mut self, key_source: RateLimitKeySourceSettings) -> Self {
        self.key_source = key_source;
        self
    }

    pub(in crate::http::layers) fn build_at(
        &self,
        path: &str,
    ) -> Result<Option<HttpRateLimitConfig>, SettingsValidationError> {
        if !self.enabled {
            return Ok(None);
        }
        let mut issues = SettingsIssues::new();
        issues.require(
            self.capacity > 0,
            field_path(path, "capacity"),
            "must be greater than zero when rate limit is enabled",
        );
        issues.require(
            self.refill_tokens > 0,
            field_path(path, "refill_tokens"),
            "must be greater than zero when rate limit is enabled",
        );
        issues.require(
            !self.refill_interval.is_zero(),
            field_path(path, "refill_interval"),
            "must be greater than zero when rate limit is enabled",
        );
        let key_source = RateLimitKeySource::try_from(&self.key_source).map_err(|error| {
            let message = match error {
                HttpMiddlewareError::InvalidHeaderName { .. } => "must be a valid HTTP header name",
                _ => "must not be empty",
            };
            SettingsValidationError::single(field_path(path, "key_source.value"), message)
        });
        if let Err(error) = &key_source {
            issues.extend(error.clone());
        }
        issues.into_result()?;
        let config = RateLimitConfig::new(self.capacity, self.refill_tokens, self.refill_interval)
            .map_err(|error| SettingsValidationError::single(path, error.to_string()))?;
        Ok(Some(HttpRateLimitConfig::new(config, key_source?)))
    }
}

impl TryFrom<&RateLimitKeySourceSettings> for RateLimitKeySource {
    type Error = HttpMiddlewareError;

    fn try_from(value: &RateLimitKeySourceSettings) -> Result<Self, Self::Error> {
        match value {
            RateLimitKeySourceSettings::ClientIp => Ok(Self::ClientIp),
            RateLimitKeySourceSettings::Principal => Ok(Self::Principal),
            RateLimitKeySourceSettings::Tenant => Ok(Self::Tenant),
            RateLimitKeySourceSettings::TrustedHeader(value) => Ok(
                Self::trusted_header_from_upstream(HeaderName::try_from(value.trim()).map_err(
                    |source| HttpMiddlewareError::InvalidHeaderName {
                        field: "rate_limit.key_source",
                        source,
                    },
                )?),
            ),
            RateLimitKeySourceSettings::Fixed(value) => {
                let value = value.trim();
                if value.is_empty() {
                    return Err(HttpMiddlewareError::InvalidRateLimitKeySource {
                        field: "rate_limit.key_source",
                    });
                }
                Ok(Self::Fixed(value.to_owned()))
            }
        }
    }
}