use std::{fmt, time::Duration};
use axum::http::HeaderName;
use serde::{Deserialize, Serialize};
use crate::{
config::{ConfigIssues, ConfigValidationError},
http::{RateLimitConfig, RateLimitKeySource},
};
use super::super::{error::HttpLayerError, policy::HttpRateLimitConfig};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct HttpRateLimitSettings {
#[serde(default)]
pub enabled: bool,
#[serde(default = "default_rate_limit_capacity")]
pub capacity: u32,
#[serde(default = "default_rate_limit_refill_tokens")]
pub refill_tokens: u32,
#[serde(
default = "default_rate_limit_refill_interval",
with = "crate::config::human_duration"
)]
pub refill_interval: Duration,
#[serde(default)]
pub key_source: RateLimitKeySourceSettings,
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
#[non_exhaustive]
pub enum RateLimitKeySourceSettings {
#[default]
ClientIp,
PrincipalId,
RequestId,
Header(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::PrincipalId => formatter.write_str("PrincipalId"),
Self::RequestId => formatter.write_str("RequestId"),
Self::Header(name) => formatter.debug_tuple("Header").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]
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>, 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<(), ConfigValidationError> {
let mut issues = ConfigIssues::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::RequestId => Ok(Self::RequestId),
RateLimitKeySourceSettings::Header(value) => {
Ok(Self::Header(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 ConfigIssues,
path: impl AsRef<str>,
value: &RateLimitKeySourceSettings,
) {
let path = path.as_ref();
match value {
RateLimitKeySourceSettings::ClientIp
| RateLimitKeySourceSettings::PrincipalId
| RateLimitKeySourceSettings::RequestId => {}
RateLimitKeySourceSettings::Header(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",
);
}
}
}