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::HttpMiddlewareError, policy::HttpRateLimitConfig};
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct HttpRateLimitSettings {
pub enabled: bool,
pub capacity: u32,
pub refill_tokens: u32,
#[serde(with = "crate::settings::human_duration")]
pub refill_interval: Duration,
#[cfg_attr(feature = "tier", tier(secret))]
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]
pub enum RateLimitKeySourceSettings {
#[default]
ClientIp,
Principal,
TrustedHeader(String),
Fixed(String),
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 {
#[must_use]
pub const fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
#[must_use]
pub const fn with_capacity(mut self, capacity: u32) -> Self {
self.capacity = capacity;
self
}
#[must_use]
pub const fn with_refill_tokens(mut self, refill_tokens: u32) -> Self {
self.refill_tokens = refill_tokens;
self
}
#[must_use]
pub const fn with_refill_interval(mut self, refill_interval: Duration) -> Self {
self.refill_interval = refill_interval;
self
}
#[must_use]
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,
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",
);
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(format!("{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()))
}
}
}
}