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),
}
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::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 config(
&self,
) -> Result<Option<HttpRateLimitConfig>, HttpMiddlewareError> {
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 = HttpMiddlewareError;
fn try_from(value: &RateLimitKeySourceSettings) -> Result<Self, Self::Error> {
match value {
RateLimitKeySourceSettings::ClientIp => Ok(Self::ClientIp),
RateLimitKeySourceSettings::Principal => Ok(Self::Principal),
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()))
}
}
}
}
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::Principal => {}
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",
);
}
}
}