use std::{num::NonZeroUsize, sync::Arc, time::Duration};
use crate::http::{
IdempotencyConfig, IdempotencyRequestPolicy, RateLimitConfig, RateLimitKeySource,
RateLimitRequestPolicy,
};
use axum::{
extract::MatchedPath,
http::{HeaderName, HeaderValue, Method, Request},
};
use super::{error::HttpMiddlewareError, security::SecurityHeadersConfig};
use crate::http::trusted_proxy::ForwardedHeadersPolicy;
pub const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_HTTP_REQUEST_BODY_LIMIT: usize = 2 * 1024 * 1024;
pub const DEFAULT_HSTS_MAX_AGE: Duration = Duration::from_secs(31_536_000);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CorsPolicy {
Disabled,
AnyOrigin(CorsConfig),
Restricted(CorsConfig),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CorsConfig {
pub(super) allowed_origins: Vec<HeaderValue>,
pub(super) allowed_methods: Vec<Method>,
pub(super) allowed_headers: Vec<HeaderName>,
pub(super) exposed_headers: Vec<HeaderName>,
pub(super) allow_credentials: bool,
pub(super) max_age: Option<Duration>,
}
impl CorsConfig {
#[must_use]
pub fn allowed_origins(&self) -> &[HeaderValue] {
&self.allowed_origins
}
#[must_use]
pub fn allowed_methods(&self) -> &[Method] {
&self.allowed_methods
}
#[must_use]
pub fn allowed_headers(&self) -> &[HeaderName] {
&self.allowed_headers
}
#[must_use]
pub fn exposed_headers(&self) -> &[HeaderName] {
&self.exposed_headers
}
#[must_use]
pub const fn credentials_allowed(&self) -> bool {
self.allow_credentials
}
#[must_use]
pub const fn max_age_value(&self) -> Option<Duration> {
self.max_age
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct HttpMiddlewareConfig {
pub(super) request_context: bool,
pub(super) forwarded_headers: ForwardedHeadersPolicy,
pub(super) trace: bool,
pub(super) cors: CorsPolicy,
pub(super) security_headers: Option<SecurityHeadersConfig>,
pub(super) timeout: Option<Duration>,
pub(super) compression: bool,
pub(super) rate_limit: Option<HttpRateLimitConfig>,
pub(super) idempotency: Option<IdempotencyConfig>,
pub(super) request_policy: HttpRequestPolicy,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct HttpRateLimitConfig {
pub(super) limiter_config: RateLimitConfig,
pub(super) key_source: RateLimitKeySource,
}
impl HttpRateLimitConfig {
#[must_use]
pub const fn new(limiter_config: RateLimitConfig, key_source: RateLimitKeySource) -> Self {
Self {
limiter_config,
key_source,
}
}
#[must_use]
pub const fn limiter_config(&self) -> RateLimitConfig {
self.limiter_config
}
#[must_use]
pub const fn key_source(&self) -> &RateLimitKeySource {
&self.key_source
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RequestBodyLimitPolicy {
Disabled,
Bytes(NonZeroUsize),
}
impl RequestBodyLimitPolicy {
pub fn bytes(value: usize) -> Result<Self, HttpMiddlewareError> {
NonZeroUsize::new(value)
.map(Self::Bytes)
.ok_or(HttpMiddlewareError::InvalidRequestBodyLimit)
}
pub fn from_optional(value: Option<usize>) -> Result<Self, HttpMiddlewareError> {
match value {
Some(value) => Self::bytes(value),
None => Ok(Self::Disabled),
}
}
#[must_use]
pub const fn as_optional(self) -> Option<usize> {
match self {
Self::Disabled => None,
Self::Bytes(value) => Some(value.get()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HttpRequestPolicy {
default_rate_limit: RateLimitRequestPolicy,
default_idempotency: IdempotencyRequestPolicy,
default_request_body_limit: RequestBodyLimitPolicy,
rules: Arc<Vec<HttpRouteRule>>,
}
#[derive(Clone)]
struct ResolvedRequestPolicy {
source: HttpRequestPolicy,
method: Method,
path: String,
effective: EffectiveHttpRequestPolicy,
}
impl Default for HttpRequestPolicy {
fn default() -> Self {
Self {
default_rate_limit: RateLimitRequestPolicy::Enabled,
default_idempotency: IdempotencyRequestPolicy::HeaderOptional,
default_request_body_limit: RequestBodyLimitPolicy::Bytes(
const {
NonZeroUsize::new(DEFAULT_HTTP_REQUEST_BODY_LIMIT)
.expect("default body limit is nonzero")
},
),
rules: Arc::default(),
}
}
}
impl HttpRequestPolicy {
#[must_use]
pub fn disabled() -> Self {
Self {
default_rate_limit: RateLimitRequestPolicy::Disabled,
default_idempotency: IdempotencyRequestPolicy::Disabled,
default_request_body_limit: RequestBodyLimitPolicy::Disabled,
rules: Arc::default(),
}
}
#[must_use]
pub const fn with_default_rate_limit(mut self, policy: RateLimitRequestPolicy) -> Self {
self.default_rate_limit = policy;
self
}
#[must_use]
pub const fn with_default_idempotency(mut self, policy: IdempotencyRequestPolicy) -> Self {
self.default_idempotency = policy;
self
}
#[must_use]
pub const fn with_default_request_body_limit(mut self, policy: RequestBodyLimitPolicy) -> Self {
self.default_request_body_limit = policy;
self
}
#[must_use]
pub fn with_rule(mut self, rule: HttpRouteRule) -> Self {
Arc::make_mut(&mut self.rules).push(rule);
self
}
#[must_use]
pub fn with_rules(mut self, rules: impl IntoIterator<Item = HttpRouteRule>) -> Self {
Arc::make_mut(&mut self.rules).extend(rules);
self
}
#[must_use]
pub fn rules(&self) -> &[HttpRouteRule] {
&self.rules
}
#[must_use]
pub const fn default_rate_limit(&self) -> RateLimitRequestPolicy {
self.default_rate_limit
}
#[must_use]
pub const fn default_idempotency(&self) -> IdempotencyRequestPolicy {
self.default_idempotency
}
#[must_use]
pub const fn default_request_body_limit(&self) -> RequestBodyLimitPolicy {
self.default_request_body_limit
}
#[must_use]
pub fn policy_for<B>(&self, request: &Request<B>) -> EffectiveHttpRequestPolicy {
self.policy_for_route(request.method(), request_path(request))
}
pub(crate) fn resolve<B>(&self, request: &mut Request<B>) -> EffectiveHttpRequestPolicy {
if let Some(cached) = request.extensions().get::<ResolvedRequestPolicy>()
&& Arc::ptr_eq(&self.rules, &cached.source.rules)
&& self.default_rate_limit == cached.source.default_rate_limit
&& self.default_idempotency == cached.source.default_idempotency
&& self.default_request_body_limit == cached.source.default_request_body_limit
&& request.method() == cached.method
&& request_path(request) == cached.path
{
return cached.effective;
}
let effective = self.policy_for(request);
let cached = ResolvedRequestPolicy {
source: self.clone(),
method: request.method().clone(),
path: request_path(request).to_owned(),
effective,
};
request.extensions_mut().insert(cached);
effective
}
#[must_use]
pub fn policy_for_route(&self, method: &Method, path: &str) -> EffectiveHttpRequestPolicy {
let mut policy = EffectiveHttpRequestPolicy {
rate_limit: self.default_rate_limit,
idempotency: self.default_idempotency,
request_body_limit: self.default_request_body_limit,
};
for rule in self.rules.iter() {
if !rule.matches_route(method, path) {
continue;
}
if let Some(rate_limit) = rule.rate_limit {
policy.rate_limit = rate_limit;
}
if let Some(idempotency) = rule.idempotency {
policy.idempotency = idempotency;
}
if let Some(request_body_limit) = rule.request_body_limit {
policy.request_body_limit = request_body_limit;
}
}
policy
}
#[must_use]
pub fn has_request_body_limits(&self) -> bool {
!matches!(
self.default_request_body_limit,
RequestBodyLimitPolicy::Disabled
) || self.rules.iter().any(|rule| {
matches!(
rule.request_body_limit,
Some(RequestBodyLimitPolicy::Bytes(_))
)
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HttpRouteRule {
pub(super) matcher: RouteMatcher,
pub(super) methods: Vec<Method>,
pub(super) rate_limit: Option<RateLimitRequestPolicy>,
pub(super) idempotency: Option<IdempotencyRequestPolicy>,
pub(super) request_body_limit: Option<RequestBodyLimitPolicy>,
}
impl HttpRouteRule {
#[must_use]
pub fn any() -> Self {
Self::new(RouteMatcher::any())
}
pub fn exact(path: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
RouteMatcher::exact(path).map(Self::new)
}
pub fn prefix(prefix: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
RouteMatcher::prefix(prefix).map(Self::new)
}
pub fn raw_prefix(prefix: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
RouteMatcher::raw_prefix(prefix).map(Self::new)
}
#[must_use]
pub fn new(matcher: RouteMatcher) -> Self {
Self {
matcher,
methods: Vec::new(),
rate_limit: None,
idempotency: None,
request_body_limit: None,
}
}
#[must_use]
pub fn methods(mut self, methods: impl IntoIterator<Item = Method>) -> Self {
self.methods = methods.into_iter().collect();
self
}
#[must_use]
pub const fn rate_limit(mut self, policy: RateLimitRequestPolicy) -> Self {
self.rate_limit = Some(policy);
self
}
#[must_use]
pub const fn idempotency(mut self, policy: IdempotencyRequestPolicy) -> Self {
self.idempotency = Some(policy);
self
}
#[must_use]
pub const fn request_body_limit(mut self, policy: RequestBodyLimitPolicy) -> Self {
self.request_body_limit = Some(policy);
self
}
#[must_use]
pub const fn matcher(&self) -> &RouteMatcher {
&self.matcher
}
#[must_use]
pub fn methods_slice(&self) -> &[Method] {
&self.methods
}
fn matches_route(&self, method: &Method, path: &str) -> bool {
(self.methods.is_empty() || self.methods.iter().any(|expected| expected == method))
&& self.matcher.matches(path)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RouteMatcher(pub(super) RouteMatcherKind);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum RouteMatcherKind {
Any,
Exact(String),
Prefix(String),
RawPrefix(String),
}
impl RouteMatcher {
#[must_use]
pub const fn any() -> Self {
Self(RouteMatcherKind::Any)
}
pub fn exact(path: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
Self::path(RouteMatcherKind::Exact, path)
}
pub fn prefix(path: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
Self::path(RouteMatcherKind::Prefix, path)
}
pub fn raw_prefix(path: impl Into<String>) -> Result<Self, HttpMiddlewareError> {
Self::path(RouteMatcherKind::RawPrefix, path)
}
fn path(
constructor: impl FnOnce(String) -> RouteMatcherKind,
path: impl Into<String>,
) -> Result<Self, HttpMiddlewareError> {
let path = path.into();
if !crate::http::is_valid_route_path(&path) {
return Err(HttpMiddlewareError::InvalidRouteMatcher);
}
Ok(Self(constructor(path)))
}
#[must_use]
pub fn matches(&self, path: &str) -> bool {
match &self.0 {
RouteMatcherKind::Any => true,
RouteMatcherKind::Exact(expected) => path == expected,
RouteMatcherKind::Prefix(prefix) => path_matches_segment_prefix(path, prefix),
RouteMatcherKind::RawPrefix(prefix) => path.starts_with(prefix),
}
}
}
fn path_matches_segment_prefix(path: &str, prefix: &str) -> bool {
if path == prefix {
return true;
}
let Some(rest) = path.strip_prefix(prefix) else {
return false;
};
prefix.ends_with('/') || rest.starts_with('/')
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct EffectiveHttpRequestPolicy {
rate_limit: RateLimitRequestPolicy,
idempotency: IdempotencyRequestPolicy,
request_body_limit: RequestBodyLimitPolicy,
}
impl EffectiveHttpRequestPolicy {
#[must_use]
pub const fn rate_limit(self) -> RateLimitRequestPolicy {
self.rate_limit
}
#[must_use]
pub const fn idempotency(self) -> IdempotencyRequestPolicy {
self.idempotency
}
#[must_use]
pub const fn request_body_limit(self) -> RequestBodyLimitPolicy {
self.request_body_limit
}
}
fn request_path<B>(request: &Request<B>) -> &str {
request
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str)
.unwrap_or_else(|| request.uri().path())
}