use std::{num::NonZeroUsize, time::Duration};
use crate::http::{
IdempotencyConfig, IdempotencyRequestPolicy, RateLimitConfig, RateLimitKeySource,
RateLimitRequestPolicy,
};
use axum::{
extract::MatchedPath,
http::{
HeaderName, HeaderValue, Method, Request,
header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE},
},
};
use super::{error::HttpLayerError, 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,
Permissive,
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 {
pub(super) fn new(allowed_origins: impl IntoIterator<Item = HeaderValue>) -> Self {
Self {
allowed_origins: allowed_origins.into_iter().collect(),
allowed_methods: vec![
Method::GET,
Method::POST,
Method::PUT,
Method::PATCH,
Method::DELETE,
],
allowed_headers: default_cors_allowed_headers(),
exposed_headers: default_cors_exposed_headers(),
allow_credentials: false,
max_age: Some(Duration::from_secs(10 * 60)),
}
}
pub(super) fn from_origin_strs(
origins: impl IntoIterator<Item = impl AsRef<str>>,
) -> Result<Self, axum::http::header::InvalidHeaderValue> {
let origins = origins
.into_iter()
.map(|origin| HeaderValue::from_str(origin.as_ref().trim()))
.collect::<Result<Vec<_>, _>>()?;
Ok(Self::new(origins))
}
pub(super) fn allow_methods(mut self, methods: impl IntoIterator<Item = Method>) -> Self {
self.allowed_methods = methods.into_iter().collect();
self
}
pub(super) fn allow_headers(mut self, headers: impl IntoIterator<Item = HeaderName>) -> Self {
self.allowed_headers = headers.into_iter().collect();
self
}
pub(super) fn expose_headers(mut self, headers: impl IntoIterator<Item = HeaderName>) -> Self {
self.exposed_headers = headers.into_iter().collect();
self
}
pub(super) const fn allow_credentials(mut self, allow_credentials: bool) -> Self {
self.allow_credentials = allow_credentials;
self
}
pub(super) const fn max_age(mut self, max_age: Option<Duration>) -> Self {
self.max_age = max_age;
self
}
#[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
}
pub(super) fn validate(&self) -> Result<(), HttpLayerError> {
if self.allowed_origins.is_empty()
|| self
.allowed_origins
.iter()
.any(|origin| origin.as_bytes().is_empty())
{
return Err(HttpLayerError::CorsAllowedOriginsEmpty);
}
if self
.allowed_origins
.iter()
.any(|origin| origin.as_bytes() == b"*")
{
return Err(if self.allow_credentials {
HttpLayerError::CorsWildcardOriginWithCredentials
} else {
HttpLayerError::CorsWildcardOriginRestricted
});
}
Ok(())
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct HttpLayerConfig {
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) request_body_limit: Option<NonZeroUsize>,
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: RateLimitConfig,
pub(super) key_source: RateLimitKeySource,
}
impl HttpRateLimitConfig {
#[must_use]
pub const fn new(limiter: RateLimitConfig, key_source: RateLimitKeySource) -> Self {
Self {
limiter,
key_source,
}
}
#[must_use]
pub const fn limiter(&self) -> RateLimitConfig {
self.limiter
}
#[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, HttpLayerError> {
NonZeroUsize::new(value)
.map(Self::Bytes)
.ok_or(HttpLayerError::InvalidRequestBodyLimit)
}
pub fn from_optional(value: Option<usize>) -> Result<Self, HttpLayerError> {
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: Vec<HttpRouteRule>,
}
impl Default for HttpRequestPolicy {
fn default() -> Self {
Self {
default_rate_limit: RateLimitRequestPolicy::Enabled,
default_idempotency: IdempotencyRequestPolicy::HeaderOptional,
default_request_body_limit: RequestBodyLimitPolicy::Disabled,
rules: Vec::new(),
}
}
}
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: Vec::new(),
}
}
#[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 {
self.rules.push(rule);
self
}
#[must_use]
pub fn with_rules(mut self, rules: impl IntoIterator<Item = HttpRouteRule>) -> Self {
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))
}
#[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 {
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_limit_overrides(&self) -> bool {
!matches!(
self.default_request_body_limit,
RequestBodyLimitPolicy::Disabled
) || self
.rules
.iter()
.any(|rule| rule.request_body_limit.is_some())
}
pub(super) fn request_body_limit_for<B>(
&self,
request: &Request<B>,
fallback: RequestBodyLimitPolicy,
) -> RequestBodyLimitPolicy {
let mut policy = match self.default_request_body_limit {
RequestBodyLimitPolicy::Disabled => fallback,
configured => configured,
};
for rule in &self.rules {
if rule.matches(request)
&& let Some(configured) = rule.request_body_limit
{
policy = configured;
}
}
policy
}
}
#[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, HttpLayerError> {
RouteMatcher::exact(path).map(Self::new)
}
pub fn prefix(prefix: impl Into<String>) -> Result<Self, HttpLayerError> {
RouteMatcher::prefix(prefix).map(Self::new)
}
pub fn raw_prefix(prefix: impl Into<String>) -> Result<Self, HttpLayerError> {
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<B>(&self, request: &Request<B>) -> bool {
self.matches_route(request.method(), request_path(request))
}
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, HttpLayerError> {
Self::path(RouteMatcherKind::Exact, path)
}
pub fn prefix(path: impl Into<String>) -> Result<Self, HttpLayerError> {
Self::path(RouteMatcherKind::Prefix, path)
}
pub fn raw_prefix(path: impl Into<String>) -> Result<Self, HttpLayerError> {
Self::path(RouteMatcherKind::RawPrefix, path)
}
fn path(
constructor: impl FnOnce(String) -> RouteMatcherKind,
path: impl Into<String>,
) -> Result<Self, HttpLayerError> {
let path = path.into();
if !path.starts_with('/') {
return Err(HttpLayerError::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())
}
fn default_cors_allowed_headers() -> Vec<HeaderName> {
vec![
ACCEPT,
AUTHORIZATION,
CONTENT_TYPE,
HeaderName::from_static("x-request-id"),
HeaderName::from_static("traceparent"),
]
}
fn default_cors_exposed_headers() -> Vec<HeaderName> {
vec![HeaderName::from_static("x-request-id")]
}