diff --git a/src/api/router/auth.rs b/src/api/router/auth.rs index 0569ebfbf..7d5fd803f 100644 --- a/src/api/router/auth.rs +++ b/src/api/router/auth.rs @@ -194,6 +194,10 @@ impl CheckAuth for AccessTokenOptional { authentication: Self::Output, query: AuthQueryParams, ) -> Result { + if R::RATE_LIMITED && is_rendezvous_create_route(TypeId::of::()) { + services.rendezvous.check_create_ratelimit(request_ip)?; + } + if let Some(authentication) = authentication { check_access_token( services, @@ -278,6 +282,11 @@ impl CheckAuth for NoAccessToken { err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err)))) })?; + let is_rendezvous_session = is_rendezvous_session_route(TypeId::of::()); + if R::RATE_LIMITED && is_rendezvous_session { + services.rendezvous.check_session_ratelimit(request_ip)?; + } + if let Some(authentication) = authentication { check_access_token(services, &authentication, query, TypeId::of::(), &[ OAuthClientScope::ApiFullAccess, @@ -285,7 +294,7 @@ impl CheckAuth for NoAccessToken { .await .map(Some) } else { - if R::RATE_LIMITED { + if R::RATE_LIMITED && !is_rendezvous_session { check_unauthenticated_request_ratelimiting(services, request_ip)?; } @@ -433,6 +442,20 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result bool { + route == TypeId::of::() + || route + == TypeId::of::() +} + +fn is_rendezvous_session_route(route: TypeId) -> bool { + route == TypeId::of::() + || route + == TypeId::of::() + || route + == TypeId::of::() +} + fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> { if services .config diff --git a/src/service/rendezvous/mod.rs b/src/service/rendezvous/mod.rs index 65b78925e..184178a8c 100644 --- a/src/service/rendezvous/mod.rs +++ b/src/service/rendezvous/mod.rs @@ -1,20 +1,33 @@ use std::{ + net::IpAddr, sync::Arc, time::{Duration, Instant}, }; -use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils}; +use conduwuit::{ + Err, Error, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils, +}; +use governor::{ + DefaultKeyedRateLimiter, Quota, RateLimiter, + clock::{Clock, DefaultClock}, +}; use lru_cache::LruCache; +use nonzero_ext::nonzero; use ruma::{ OwnedTransactionId, - api::client::rendezvous::{ - create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session, - update_rendezvous_session, + api::{ + client::rendezvous::{ + create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session, + update_rendezvous_session, + }, + error::{ErrorKind, LimitExceededErrorData, RetryAfter}, }, }; pub struct Service { sessions: SyncMutex>, + create_ratelimiter: DefaultKeyedRateLimiter, + session_ratelimiter: DefaultKeyedRateLimiter, } struct Session { @@ -50,6 +63,8 @@ impl crate::Service for Service { fn build(_: crate::Args<'_>) -> Result> { Ok(Arc::new(Self { sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)), + create_ratelimiter: RateLimiter::keyed(Self::CREATE_RATELIMIT), + session_ratelimiter: RateLimiter::keyed(Self::SESSION_RATELIMIT), })) } @@ -57,11 +72,38 @@ impl crate::Service for Service { } impl Service { + const CREATE_RATELIMIT: Quota = Quota::per_minute(nonzero!(30_u32)); const MAX_DATA_SIZE_BYTES: usize = 4096; const MAX_SESSIONS: usize = 256; const SESSION_MAX_AGE: Duration = Duration::from_secs(300); + const SESSION_RATELIMIT: Quota = Quota::per_minute(nonzero!(300_u32)); const TOKEN_LENGTH: usize = 32; + pub fn check_create_ratelimit(&self, ip: IpAddr) -> Result<()> { + Self::check_ratelimiter(&self.create_ratelimiter, ip) + } + + pub fn check_session_ratelimit(&self, ip: IpAddr) -> Result<()> { + Self::check_ratelimiter(&self.session_ratelimiter, ip) + } + + fn check_ratelimiter( + ratelimiter: &DefaultKeyedRateLimiter, + ip: IpAddr, + ) -> Result<()> { + if let Err(not_until) = ratelimiter.check_key(&ip) { + let wait_time = not_until.wait_time_from(DefaultClock::default().now()); + let mut data = LimitExceededErrorData::new(); + data.retry_after = Some(RetryAfter::Delay(wait_time)); + return Err(Error::BadRequest( + ErrorKind::LimitExceeded(data), + "Rate limit exceeded.", + )); + } + + Ok(()) + } + fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) } fn is_valid_opaque_id(id: &str) -> bool {