279 lines
9.8 KiB
Rust
279 lines
9.8 KiB
Rust
//! Request limiting for the unauthenticated and expensive endpoints.
|
|
//!
|
|
//! Limits are per *source*, so one noisy client cannot use up the budget of
|
|
//! the others. The source is the TCP peer. `X-Forwarded-For` is honoured only
|
|
//! when the peer is a configured trusted proxy (`TESSERA_TRUSTED_PROXIES`),
|
|
//! walking the header right to left past trusted hops. IPv6 sources are keyed by
|
|
//! their /64. State is in memory and per hub process: it resets on restart and
|
|
//! is not shared between replicas.
|
|
use axum::http::HeaderMap;
|
|
use governor::{
|
|
clock::DefaultClock, state::keyed::DefaultKeyedStateStore, state::InMemoryState,
|
|
state::NotKeyed, Quota, RateLimiter,
|
|
};
|
|
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
|
|
use std::num::NonZeroU32;
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
use std::sync::Arc;
|
|
use tokio::sync::Semaphore;
|
|
|
|
type Keyed = RateLimiter<IpAddr, DefaultKeyedStateStore<IpAddr>, DefaultClock>;
|
|
type Direct = RateLimiter<NotKeyed, InMemoryState, DefaultClock>;
|
|
|
|
pub struct LimitConfig {
|
|
pub login_source: Quota,
|
|
/// Ceiling for the single emergency account across all sources. Deliberately
|
|
/// looser than the per-source quota: a tight account lock would let anyone
|
|
/// lock the break-glass operator out.
|
|
pub login_account: Quota,
|
|
pub claim_source: Quota,
|
|
pub claim_global: Quota,
|
|
pub oidc_login_source: Quota,
|
|
pub oidc_callback_source: Quota,
|
|
pub argon2_concurrency: usize,
|
|
}
|
|
|
|
fn per_minute(rate: u32, burst: u32) -> Quota {
|
|
Quota::per_minute(NonZeroU32::new(rate).unwrap()).allow_burst(NonZeroU32::new(burst).unwrap())
|
|
}
|
|
|
|
impl Default for LimitConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
login_source: per_minute(10, 5),
|
|
login_account: per_minute(60, 30),
|
|
claim_source: per_minute(10, 5),
|
|
claim_global: per_minute(120, 60),
|
|
oidc_login_source: per_minute(30, 15),
|
|
oidc_callback_source: per_minute(60, 30),
|
|
argon2_concurrency: 2,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct Limits {
|
|
login_source: Keyed,
|
|
login_account: Direct,
|
|
claim_source: Keyed,
|
|
claim_global: Direct,
|
|
oidc_login_source: Keyed,
|
|
oidc_callback_source: Keyed,
|
|
audit_denial: Keyed,
|
|
admin_token_failure: Keyed,
|
|
pub argon2: Arc<Semaphore>,
|
|
trusted_proxies: Vec<IpAddr>,
|
|
calls: AtomicU64,
|
|
}
|
|
|
|
impl Limits {
|
|
pub fn new(config: LimitConfig, trusted_proxies: Vec<IpAddr>) -> Self {
|
|
Self {
|
|
login_source: RateLimiter::keyed(config.login_source),
|
|
login_account: RateLimiter::direct(config.login_account),
|
|
claim_source: RateLimiter::keyed(config.claim_source),
|
|
claim_global: RateLimiter::direct(config.claim_global),
|
|
oidc_login_source: RateLimiter::keyed(config.oidc_login_source),
|
|
oidc_callback_source: RateLimiter::keyed(config.oidc_callback_source),
|
|
// one audit row per source per minute, so a flood cannot fill the audit table
|
|
audit_denial: RateLimiter::keyed(per_minute(1, 1)),
|
|
admin_token_failure: RateLimiter::keyed(per_minute(10, 5)),
|
|
argon2: Arc::new(Semaphore::new(config.argon2_concurrency)),
|
|
trusted_proxies,
|
|
calls: AtomicU64::new(0),
|
|
}
|
|
}
|
|
|
|
pub fn from_env() -> anyhow::Result<Self> {
|
|
let mut proxies = Vec::new();
|
|
if let Ok(list) = std::env::var("TESSERA_TRUSTED_PROXIES") {
|
|
for item in list.split(',').map(str::trim).filter(|s| !s.is_empty()) {
|
|
proxies.push(
|
|
item.parse::<IpAddr>().map_err(|_| {
|
|
anyhow::anyhow!("TESSERA_TRUSTED_PROXIES: invalid IP {item}")
|
|
})?,
|
|
);
|
|
}
|
|
}
|
|
Ok(Self::new(LimitConfig::default(), proxies))
|
|
}
|
|
|
|
/// The rate-limit key for a request. `None` peer (should not happen) maps to
|
|
/// one strict shared bucket instead of bypassing limits.
|
|
pub fn source(&self, peer: Option<SocketAddr>, headers: &HeaderMap) -> IpAddr {
|
|
let Some(peer) = peer else {
|
|
return IpAddr::V6(Ipv6Addr::UNSPECIFIED);
|
|
};
|
|
let mut client = peer.ip();
|
|
if self.trusted_proxies.contains(&client) {
|
|
let forwarded: Vec<&str> = headers
|
|
.get_all("x-forwarded-for")
|
|
.iter()
|
|
.filter_map(|v| v.to_str().ok())
|
|
.flat_map(|line| line.split(','))
|
|
.map(str::trim)
|
|
.collect();
|
|
for hop in forwarded.iter().rev() {
|
|
match hop.parse::<IpAddr>() {
|
|
Ok(ip) if self.trusted_proxies.contains(&ip) => continue,
|
|
Ok(ip) => {
|
|
client = ip;
|
|
break;
|
|
}
|
|
Err(_) => break, // malformed: stay on the proxy's own address
|
|
}
|
|
}
|
|
}
|
|
normalize(client)
|
|
}
|
|
|
|
fn maintain(&self) {
|
|
if self.calls.fetch_add(1, Ordering::Relaxed) % 512 == 511 {
|
|
self.login_source.retain_recent();
|
|
self.claim_source.retain_recent();
|
|
self.oidc_login_source.retain_recent();
|
|
self.oidc_callback_source.retain_recent();
|
|
self.audit_denial.retain_recent();
|
|
self.admin_token_failure.retain_recent();
|
|
}
|
|
}
|
|
|
|
pub fn login_allowed(&self, source: IpAddr) -> bool {
|
|
self.maintain();
|
|
self.login_source.check_key(&source).is_ok() && self.login_account.check().is_ok()
|
|
}
|
|
|
|
pub fn claim_allowed(&self, source: IpAddr) -> bool {
|
|
self.maintain();
|
|
self.claim_source.check_key(&source).is_ok() && self.claim_global.check().is_ok()
|
|
}
|
|
|
|
pub fn oidc_login_allowed(&self, source: IpAddr) -> bool {
|
|
self.maintain();
|
|
self.oidc_login_source.check_key(&source).is_ok()
|
|
}
|
|
|
|
pub fn oidc_callback_allowed(&self, source: IpAddr) -> bool {
|
|
self.maintain();
|
|
self.oidc_callback_source.check_key(&source).is_ok()
|
|
}
|
|
|
|
/// Counts one wrong admin token from `source`; false once that source has used up its budget.
|
|
pub fn admin_token_failure(&self, source: IpAddr) -> bool {
|
|
self.maintain();
|
|
self.admin_token_failure.check_key(&source).is_ok()
|
|
}
|
|
|
|
/// True at most once a minute per source: use it to decide whether a denial is audited.
|
|
pub fn audit_denial(&self, source: IpAddr) -> bool {
|
|
self.audit_denial.check_key(&source).is_ok()
|
|
}
|
|
}
|
|
|
|
/// IPv4-mapped IPv6 becomes IPv4; other IPv6 addresses collapse to their /64.
|
|
fn normalize(ip: IpAddr) -> IpAddr {
|
|
match ip {
|
|
IpAddr::V4(_) => ip,
|
|
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
|
|
Some(v4) => IpAddr::V4(v4),
|
|
None => {
|
|
let mut octets = v6.octets();
|
|
octets[8..].fill(0);
|
|
IpAddr::V6(Ipv6Addr::from(octets))
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use axum::http::HeaderValue;
|
|
|
|
fn peer(ip: &str) -> Option<SocketAddr> {
|
|
Some(SocketAddr::new(ip.parse().unwrap(), 4000))
|
|
}
|
|
|
|
fn headers(xff: &str) -> HeaderMap {
|
|
let mut h = HeaderMap::new();
|
|
h.insert("x-forwarded-for", HeaderValue::from_str(xff).unwrap());
|
|
h
|
|
}
|
|
|
|
fn limits(proxies: &[&str]) -> Limits {
|
|
Limits::new(
|
|
LimitConfig::default(),
|
|
proxies.iter().map(|p| p.parse().unwrap()).collect(),
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn one_source_cannot_use_up_another_sources_login_budget() {
|
|
let l = limits(&[]);
|
|
let a = l.source(peer("203.0.113.1"), &HeaderMap::new());
|
|
let b = l.source(peer("203.0.113.2"), &HeaderMap::new());
|
|
let mut allowed = 0;
|
|
for _ in 0..50 {
|
|
allowed += l.login_allowed(a) as u32;
|
|
}
|
|
assert_eq!(allowed, 5, "burst of 5, then refused");
|
|
assert!(l.login_allowed(b), "an unrelated source is unaffected");
|
|
}
|
|
|
|
#[test]
|
|
fn forwarded_for_is_ignored_unless_the_peer_is_a_trusted_proxy() {
|
|
let l = limits(&["10.0.0.1"]);
|
|
let spoof = headers("198.51.100.9");
|
|
assert_eq!(
|
|
l.source(peer("203.0.113.7"), &spoof),
|
|
"203.0.113.7".parse::<IpAddr>().unwrap(),
|
|
"untrusted peer cannot choose its key"
|
|
);
|
|
assert_eq!(
|
|
l.source(peer("10.0.0.1"), &spoof),
|
|
"198.51.100.9".parse::<IpAddr>().unwrap()
|
|
);
|
|
// client-supplied prefix is ignored: walk right to left, skipping trusted hops
|
|
let chain = headers("1.1.1.1, 198.51.100.9, 10.0.0.1");
|
|
assert_eq!(
|
|
l.source(peer("10.0.0.1"), &chain),
|
|
"198.51.100.9".parse::<IpAddr>().unwrap()
|
|
);
|
|
// junk or missing header falls back to the proxy itself
|
|
assert_eq!(
|
|
l.source(peer("10.0.0.1"), &headers("not-an-ip")),
|
|
"10.0.0.1".parse::<IpAddr>().unwrap()
|
|
);
|
|
assert_eq!(
|
|
l.source(peer("10.0.0.1"), &HeaderMap::new()),
|
|
"10.0.0.1".parse::<IpAddr>().unwrap()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn ipv6_sources_share_a_budget_per_64_and_mapped_v4_is_v4() {
|
|
let l = limits(&[]);
|
|
let a = l.source(peer("2001:db8:1:2::1"), &HeaderMap::new());
|
|
let b = l.source(peer("2001:db8:1:2:ffff::9"), &HeaderMap::new());
|
|
let c = l.source(peer("2001:db8:1:3::1"), &HeaderMap::new());
|
|
assert_eq!(a, b);
|
|
assert_ne!(a, c);
|
|
assert_eq!(
|
|
l.source(peer("::ffff:192.0.2.5"), &HeaderMap::new()),
|
|
"192.0.2.5".parse::<IpAddr>().unwrap()
|
|
);
|
|
assert_eq!(
|
|
l.source(None, &HeaderMap::new()),
|
|
IpAddr::V6(Ipv6Addr::UNSPECIFIED)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn denials_are_audited_at_most_once_a_minute_per_source() {
|
|
let l = limits(&[]);
|
|
let a: IpAddr = "203.0.113.1".parse().unwrap();
|
|
assert!(l.audit_denial(a));
|
|
assert!(!l.audit_denial(a));
|
|
assert!(l.audit_denial("203.0.113.2".parse().unwrap()));
|
|
}
|
|
}
|