use std::{fmt, sync::Arc};
use axum::http::{HeaderName, Request};
use sha2::{Digest, Sha256};
use crate::{
http::{RequestContext, to_lower_hex},
observability::{MetricRecorder, RecordingFailures},
};
use super::RateLimitStore;
use super::{
memory::TokenBucketRateLimiter,
model::{MAX_RATE_LIMIT_HEADER_VALUE_BYTES, RateLimitConfig},
};
#[derive(Clone)]
#[non_exhaustive]
pub struct RateLimitRuntime {
config: RateLimitConfig,
store: Arc<dyn RateLimitStore>,
key_source: RateLimitKeySource,
metrics: Option<Arc<dyn MetricRecorder>>,
pub(super) recording_failures: RecordingFailures,
}
impl fmt::Debug for RateLimitRuntime {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RateLimitRuntime")
.field("config", &self.config)
.field("key_source", &self.key_source)
.finish_non_exhaustive()
}
}
impl RateLimitRuntime {
#[must_use]
pub fn new(
config: RateLimitConfig,
key_source: RateLimitKeySource,
store: Arc<dyn RateLimitStore>,
) -> Self {
Self {
config,
store,
key_source,
metrics: None,
recording_failures: RecordingFailures::default(),
}
}
#[must_use]
pub fn in_memory(config: RateLimitConfig, key_source: RateLimitKeySource) -> Self {
Self::new(
config,
key_source,
Arc::new(TokenBucketRateLimiter::new(config)),
)
}
#[must_use]
pub fn from_limiter(
limiter: Arc<TokenBucketRateLimiter<String>>,
key_source: RateLimitKeySource,
) -> Self {
Self::new(limiter.config(), key_source, limiter)
}
#[must_use]
pub fn with_metrics(mut self, metrics: Option<Arc<dyn MetricRecorder>>) -> Self {
self.metrics = metrics;
self
}
#[must_use]
pub const fn config(&self) -> RateLimitConfig {
self.config
}
#[must_use]
pub fn store(&self) -> &Arc<dyn RateLimitStore> {
&self.store
}
#[must_use]
pub const fn key_source(&self) -> &RateLimitKeySource {
&self.key_source
}
#[must_use]
pub fn metrics(&self) -> Option<&Arc<dyn MetricRecorder>> {
self.metrics.as_ref()
}
#[must_use]
pub fn failed_recordings(&self) -> u64 {
self.recording_failures.count()
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RateLimitKeySource {
ClientIp,
Principal,
Tenant,
TrustedHeader(HeaderName),
Fixed(String),
}
impl fmt::Debug for RateLimitKeySource {
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(header) => formatter
.debug_tuple("TrustedHeader")
.field(header)
.finish(),
Self::Fixed(_) => formatter.debug_tuple("Fixed").field(&"[REDACTED]").finish(),
}
}
}
impl RateLimitKeySource {
#[must_use]
pub const fn trusted_header_from_upstream(name: HeaderName) -> Self {
Self::TrustedHeader(name)
}
#[must_use]
pub fn key_for<B>(&self, request: &Request<B>) -> Option<String> {
match self {
Self::ClientIp => request
.extensions()
.get::<RequestContext>()
.and_then(RequestContext::client_ip)
.map(ToOwned::to_owned),
Self::Principal => request
.extensions()
.get::<RequestContext>()
.and_then(RequestContext::principal)
.map(hash_principal_rate_limit_key),
Self::Tenant => request
.extensions()
.get::<RequestContext>()
.and_then(RequestContext::principal)
.and_then(crate::auth::Principal::tenant_id)
.map(|tenant| {
let mut hasher = Sha256::new();
hasher.update(b"footing-rate-limit-tenant-v1\0");
hash_rate_limit_part(&mut hasher, tenant.as_bytes());
format!("tenant:{}", to_lower_hex(&hasher.finalize()))
}),
Self::TrustedHeader(header) => {
let mut values = request.headers().get_all(header).iter();
let value = values.next()?.to_str().ok()?.trim();
if values.next().is_some()
|| value.is_empty()
|| value.len() > MAX_RATE_LIMIT_HEADER_VALUE_BYTES
{
return None;
}
Some(hash_header_rate_limit_key(header, value))
}
Self::Fixed(value) => Some(value.clone()),
}
}
}
fn hash_principal_rate_limit_key(principal: &crate::auth::Principal) -> String {
let mut hasher = Sha256::new();
hasher.update(b"footing-rate-limit-principal-v1\0");
match principal.tenant_id() {
Some(tenant) => {
hasher.update([1]);
hash_rate_limit_part(&mut hasher, tenant.as_bytes());
}
None => hasher.update([0]),
}
hash_rate_limit_part(
&mut hasher,
match principal.kind() {
crate::auth::PrincipalKind::User => b"user",
crate::auth::PrincipalKind::Client => b"client",
crate::auth::PrincipalKind::ServiceAccount => b"service_account",
},
);
hash_rate_limit_part(&mut hasher, principal.id().as_bytes());
format!("principal:{}", to_lower_hex(&hasher.finalize()))
}
fn hash_header_rate_limit_key(name: &HeaderName, value: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(b"footing-rate-limit-header-v1\0");
hash_rate_limit_part(&mut hasher, name.as_str().as_bytes());
hash_rate_limit_part(&mut hasher, value.as_bytes());
format!("header:{}", to_lower_hex(&hasher.finalize()))
}
fn hash_rate_limit_part(hasher: &mut Sha256, value: &[u8]) {
hasher.update(u64::try_from(value.len()).unwrap_or(u64::MAX).to_be_bytes());
hasher.update(value);
}