footing 0.1.6

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

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

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for HTTP rate limit.
pub struct HttpRateLimitSettings {
    #[serde(default)]
    /// Whether request rate limiting is enabled.
    pub enabled: bool,
    #[serde(default = "default_rate_limit_capacity")]
    /// Maximum tokens held by each rate-limit bucket.
    pub capacity: u32,
    #[serde(default = "default_rate_limit_refill_tokens")]
    /// Tokens restored during each refill interval.
    pub refill_tokens: u32,
    #[serde(
        default = "default_rate_limit_refill_interval",
        with = "crate::settings::human_duration"
    )]
    /// Time between token refills.
    pub refill_interval: Duration,
    #[serde(default)]
    #[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,
    /// Indicates principal identifier.
    PrincipalId,
    /// A custom header stripped and overwritten by a trusted upstream.
    TrustedHeader(String),
    /// Indicates fixed.
    Fixed(String),
}

impl fmt::Debug for RateLimitKeySourceSettings {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ClientIp => formatter.write_str("ClientIp"),
            Self::PrincipalId => formatter.write_str("PrincipalId"),
            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: default_rate_limit_capacity(),
            refill_tokens: default_rate_limit_refill_tokens(),
            refill_interval: default_rate_limit_refill_interval(),
            key_source: RateLimitKeySourceSettings::ClientIp,
        }
    }
}

impl HttpRateLimitSettings {
    #[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 config(
        &self,
    ) -> Result<Option<HttpRateLimitConfig>, HttpLayerError> {
        if !self.enabled {
            return Ok(None);
        }
        let config = RateLimitConfig::new(self.capacity, self.refill_tokens, self.refill_interval)?;
        Ok(Some(HttpRateLimitConfig::new(
            config,
            RateLimitKeySource::try_from(&self.key_source)?,
        )))
    }

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        if self.enabled {
            issues.require(
                self.capacity > 0,
                format!("{path}.capacity"),
                "must be greater than zero when rate limit is enabled",
            );
            issues.require(
                self.refill_tokens > 0,
                format!("{path}.refill_tokens"),
                "must be greater than zero when rate limit is enabled",
            );
            issues.require(
                !self.refill_interval.is_zero(),
                format!("{path}.refill_interval"),
                "must be greater than zero when rate limit is enabled",
            );
            validate_rate_limit_key_source_setting(
                &mut issues,
                format!("{path}.key_source"),
                &self.key_source,
            );
        }
        issues.into_result()
    }
}

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

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

fn default_rate_limit_capacity() -> u32 {
    100
}

fn default_rate_limit_refill_tokens() -> u32 {
    100
}

fn default_rate_limit_refill_interval() -> Duration {
    Duration::from_secs(60)
}

fn validate_rate_limit_key_source_setting(
    issues: &mut SettingsIssues,
    path: impl AsRef<str>,
    value: &RateLimitKeySourceSettings,
) {
    let path = path.as_ref();
    match value {
        RateLimitKeySourceSettings::ClientIp | RateLimitKeySourceSettings::PrincipalId => {}
        RateLimitKeySourceSettings::TrustedHeader(value) => {
            issues.require(
                HeaderName::try_from(value.trim()).is_ok(),
                format!("{path}.value"),
                "must be a valid HTTP header name",
            );
        }
        RateLimitKeySourceSettings::Fixed(value) => {
            issues.require(
                !value.trim().is_empty(),
                format!("{path}.value"),
                "must not be empty",
            );
        }
    }
}