use std::{fmt, sync::Arc};
use axum::http::{HeaderName, Request};
use sha2::{Digest, Sha256};
use crate::{
clock::{SharedClock, system_clock},
http::{RequestContext, to_lower_hex},
observability::MetricRecorder,
};
use super::memory::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,
clock: SharedClock,
metrics: Option<Arc<dyn MetricRecorder>>,
}
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,
clock: system_clock(),
metrics: None,
}
}
#[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_clock(mut self, clock: SharedClock) -> Self {
self.clock = clock;
self
}
#[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 clock(&self) -> &SharedClock {
&self.clock
}
#[must_use]
pub fn metrics(&self) -> Option<&Arc<dyn MetricRecorder>> {
self.metrics.as_ref()
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RateLimitKeySource {
ClientIp,
Principal,
TrustedHeader(TrustedRateLimitHeader),
Fixed(String),
}
#[derive(Clone, PartialEq, Eq)]
pub struct TrustedRateLimitHeader(HeaderName);
impl TrustedRateLimitHeader {
#[must_use]
pub const fn from_trusted_upstream(name: HeaderName) -> Self {
Self(name)
}
#[must_use]
pub const fn name(&self) -> &HeaderName {
&self.0
}
}
impl fmt::Debug for TrustedRateLimitHeader {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_tuple("TrustedRateLimitHeader")
.field(&self.0)
.finish()
}
}
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::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(TrustedRateLimitHeader::from_trusted_upstream(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::TrustedHeader(header) => request
.headers()
.get(header.name())
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
.filter(|value| value.len() <= MAX_RATE_LIMIT_HEADER_VALUE_BYTES)
.map(|value| hash_header_rate_limit_key(header.name(), 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);
}