Compare commits

...
7 changed files with 180 additions and 40 deletions

No files matched your search

+23 -9
View File
@@ -9,7 +9,7 @@ use service::Services;
use crate::{Ruma, router::ClientIdentity};
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous`
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous`
pub(crate) async fn discover_rendezvous_route(
State(services): State<crate::State>,
body: Ruma<discover_rendezvous::msc4388::Request>,
@@ -20,7 +20,7 @@ pub(crate) async fn discover_rendezvous_route(
)))
}
/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/`
/// `POST /_matrix/client/unstable/io.element.msc4388/rendezvous`
pub(crate) async fn create_rendezvous_session_route(
State(services): State<crate::State>,
body: Ruma<create_rendezvous_session::msc4388::Request>,
@@ -32,7 +32,7 @@ pub(crate) async fn create_rendezvous_session_route(
services.rendezvous.create_session(body.data.clone())
}
/// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}`
/// `PUT /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}/{txn_id}`
pub(crate) async fn update_rendezvous_session_route(
State(services): State<crate::State>,
body: Ruma<update_rendezvous_session::msc4388::Request>,
@@ -45,16 +45,30 @@ pub(crate) async fn update_rendezvous_session_route(
)
}
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
pub(crate) async fn get_rendezvous_session_route(
State(services): State<crate::State>,
headers: HeaderMap,
body: Ruma<get_rendezvous_session::msc4388::Request>,
) -> Result<get_rendezvous_session::msc4388::Response> {
if let Some(mode) = headers.get("Sec-Fetch-Mode")
&& let Ok(mode) = mode.to_str()
&& mode == "navigate"
{
let is_navigation_mode = headers
.get_all("Sec-Fetch-Mode")
.iter()
.filter_map(|v| v.to_str().ok())
.any(|mode| {
mode.eq_ignore_ascii_case("navigate") || mode.eq_ignore_ascii_case("nested-navigate")
});
let is_navigation_dest = headers
.get_all("Sec-Fetch-Dest")
.iter()
.filter_map(|v| v.to_str().ok())
.any(|dest| {
matches!(
dest.to_ascii_lowercase().as_str(),
"document" | "iframe" | "frame" | "object" | "embed" | "fencedframe"
)
});
if is_navigation_mode || is_navigation_dest {
return Err!(Request(Forbidden(
"Rendezvous sessions do not accept browser navigation requests."
)));
@@ -63,7 +77,7 @@ pub(crate) async fn get_rendezvous_session_route(
services.rendezvous.get_session(&body.id)
}
/// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
/// `DELETE /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
pub(crate) async fn delete_rendezvous_session_route(
State(services): State<crate::State>,
body: Ruma<delete_rendezvous_session::msc4388::Request>,
+17 -5
View File
@@ -190,11 +190,23 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::well_known_policy_server)
.ruma_route(&client::get_rtc_transports)
.ruma_route(&client::room_initial_sync_route)
.ruma_route(&client::discover_rendezvous_route)
.ruma_route(&client::create_rendezvous_session_route)
.ruma_route(&client::update_rendezvous_session_route)
.ruma_route(&client::get_rendezvous_session_route)
.ruma_route(&client::delete_rendezvous_session_route)
.merge(
Router::new()
.ruma_route(&client::discover_rendezvous_route)
.ruma_route(&client::create_rendezvous_session_route)
.ruma_route(&client::update_rendezvous_session_route)
.ruma_route(&client::get_rendezvous_session_route)
.ruma_route(&client::delete_rendezvous_session_route)
.layer(axum::middleware::map_response(
async |mut response: axum::response::Response| {
response.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_static("no-store"),
);
response
},
)),
)
.ruma_route(&client::get_authorization_server_metadata_route)
.merge(client::oauth::router(state))
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
+17 -3
View File
@@ -11,7 +11,11 @@ use axum::{
use conduwuit::{Error, Result, err, error};
use ruma::{
CanonicalJsonObject,
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
api::{
IncomingRequest, IncomingRequestExt,
auth_scheme::AuthScheme,
error::{DeserializationError, FromHttpRequestError},
},
};
use serde::Deserialize;
@@ -114,8 +118,18 @@ where
.await?;
// Deserialize the body
let body = R::try_from_http_request(request, &borrowed_path)
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
let body_is_empty = body.is_empty();
let body = R::try_from_http_request(request, &borrowed_path).map_err(|e| match e {
| FromHttpRequestError::Deserialization(DeserializationError::Json(ref json_err))
if body_is_empty || json_err.is_syntax() || json_err.is_eof() =>
err!(Request(NotJson(debug_warn!("{e}")))),
| FromHttpRequestError::Deserialization(DeserializationError::Utf8(_)) =>
err!(Request(NotJson(debug_warn!("{e}")))),
| FromHttpRequestError::Deserialization(
DeserializationError::Ident(_) | DeserializationError::Query(_),
) => err!(Request(InvalidParam(debug_warn!("{e}")))),
| _ => err!(Request(BadJson(debug_warn!("{e}")))),
})?;
Ok(Self { body, json_body, identity })
}
+24 -1
View File
@@ -194,6 +194,10 @@ impl CheckAuth for AccessTokenOptional {
authentication: Self::Output,
query: AuthQueryParams,
) -> Result<Self::Identity> {
if R::RATE_LIMITED && is_rendezvous_create_route(TypeId::of::<R>()) {
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::<R>());
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::<R>(), &[
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<Regi
Ok(appservice_info)
}
fn is_rendezvous_create_route(route: TypeId) -> bool {
route == TypeId::of::<client::rendezvous::discover_rendezvous::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::create_rendezvous_session::msc4388::Request>()
}
fn is_rendezvous_session_route(route: TypeId) -> bool {
route == TypeId::of::<client::rendezvous::get_rendezvous_session::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::update_rendezvous_session::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::delete_rendezvous_session::msc4388::Request>()
}
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
if services
.config
+3 -1
View File
@@ -171,13 +171,14 @@ impl Error {
/// Returns the Matrix error code / error kind
#[inline]
pub fn kind(&self) -> ErrorKind {
use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
match self {
| Self::Federation(_, error) | Self::Ruma(error) =>
response::ruma_error_kind(error).clone(),
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
| Self::FeatureDisabled(..) => Unrecognized,
| Self::Path(_) | Self::Query(_) => InvalidParam,
| _ => Unknown,
}
}
@@ -194,6 +195,7 @@ impl Error {
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
| Self::Conflict(_) => StatusCode::CONFLICT,
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
| Self::Io(error) => response::io_error_code(error.kind()),
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
| _ => StatusCode::INTERNAL_SERVER_ERROR,
+3
View File
@@ -73,6 +73,9 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
// 413
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
// 409
| ConcurrentWrite => StatusCode::CONFLICT,
// 404
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
+93 -21
View File
@@ -1,25 +1,38 @@
use std::{
net::IpAddr,
sync::Arc,
time::{Duration, SystemTime},
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<LruCache<String, Session>>,
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
}
struct Session {
data: String,
created_at: SystemTime,
created_at: Instant,
last_sequence_token: String,
transaction_sequences: LruCache<OwnedTransactionId, String>,
}
@@ -27,20 +40,31 @@ struct Session {
impl Session {
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
fn new(data: String, sequence_token: String) -> Self {
fn new(data: String, sequence_token: String, now: Instant) -> Self {
Self {
data,
created_at: SystemTime::now(),
created_at: now,
last_sequence_token: sequence_token,
transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES),
}
}
fn time_remaining(&self, now: Instant) -> Option<Duration> {
let age = now.saturating_duration_since(self.created_at);
(age < Service::SESSION_MAX_AGE)
.then(|| Service::SESSION_MAX_AGE.saturating_sub(age))
.filter(|remaining| !remaining.is_zero())
}
fn is_expired(&self, now: Instant) -> bool { self.time_remaining(now).is_none() }
}
impl crate::Service for Service {
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
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),
}))
}
@@ -48,25 +72,64 @@ 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<IpAddr>,
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 {
!id.is_empty()
&& id.len() <= 255
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~'))
}
/// Lock and fetch an unexpired rendezvous session.
fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, Session>> {
self.lock_session_at(id, Instant::now())
}
fn lock_session_at(
&self,
id: &str,
now: Instant,
) -> Result<SyncMappedMutexGuard<'_, Session>> {
// We don't clear out expired sessions manually, the LRU cache will
// evict them over time
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
sessions
.get_mut(id)
.filter(|session| {
SystemTime::now()
.duration_since(session.created_at)
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
})
.filter(|session| !session.is_expired(now))
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
})
.map_err(at!(1))
@@ -86,7 +149,7 @@ impl Service {
self.sessions
.lock()
.insert(id.clone(), Session::new(data, sequence_token.clone()));
.insert(id.clone(), Session::new(data, sequence_token.clone(), Instant::now()));
Ok(create_rendezvous_session::msc4388::Response::new(
id,
@@ -103,6 +166,12 @@ impl Service {
sequence_token: String,
data: String,
) -> Result<update_rendezvous_session::msc4388::Response> {
if !Self::is_valid_opaque_id(transaction.as_str()) {
return Err!(Request(InvalidParam(
"Transaction ID does not comply with the opaque identifier grammar"
)));
}
let mut session = self.lock_session(id)?;
// If the provided transaction ID was used already, we have to return
@@ -137,13 +206,12 @@ impl Service {
/// Look up a rendezvous session by ID.
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
let session = self.lock_session(id)?;
let now = Instant::now();
let session = self.lock_session_at(id, now)?;
let session_age = SystemTime::now()
.duration_since(session.created_at)
.unwrap_or(Duration::MAX);
let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age);
let session_time_remaining = session
.time_remaining(now)
.unwrap_or_else(|| Duration::from_millis(1));
Ok(get_rendezvous_session::msc4388::Response::new(
session.last_sequence_token.clone(),
@@ -158,8 +226,12 @@ impl Service {
id: &str,
) -> Result<delete_rendezvous_session::msc4388::Response> {
let mut sessions = self.sessions.lock();
let now = Instant::now();
if sessions.remove(id).is_some() {
if sessions
.remove(id)
.is_some_and(|session| !session.is_expired(now))
{
Ok(delete_rendezvous_session::msc4388::Response::new())
} else {
Err!(Request(NotFound("Unknown session")))