mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-01 21:07:34 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42c375ce7d | ||
|
|
269fa62b15 | ||
|
|
3f35984667 | ||
|
|
28b69a241f | ||
|
|
dc4110a626 | ||
|
|
2856e1be98 | ||
|
|
5c42a2b994 | ||
|
|
1c6f0ad31e | ||
|
|
eda2da73fd |
No files matched your search
@@ -9,7 +9,7 @@ use service::Services;
|
|||||||
|
|
||||||
use crate::{Ruma, router::ClientIdentity};
|
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(
|
pub(crate) async fn discover_rendezvous_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<discover_rendezvous::msc4388::Request>,
|
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(
|
pub(crate) async fn create_rendezvous_session_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<create_rendezvous_session::msc4388::Request>,
|
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())
|
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(
|
pub(crate) async fn update_rendezvous_session_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<update_rendezvous_session::msc4388::Request>,
|
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(
|
pub(crate) async fn get_rendezvous_session_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
body: Ruma<get_rendezvous_session::msc4388::Request>,
|
body: Ruma<get_rendezvous_session::msc4388::Request>,
|
||||||
) -> Result<get_rendezvous_session::msc4388::Response> {
|
) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||||
if let Some(mode) = headers.get("Sec-Fetch-Mode")
|
let is_navigation_mode = headers
|
||||||
&& let Ok(mode) = mode.to_str()
|
.get_all("Sec-Fetch-Mode")
|
||||||
&& mode == "navigate"
|
.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(
|
return Err!(Request(Forbidden(
|
||||||
"Rendezvous sessions do not accept browser navigation requests."
|
"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)
|
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(
|
pub(crate) async fn delete_rendezvous_session_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<delete_rendezvous_session::msc4388::Request>,
|
body: Ruma<delete_rendezvous_session::msc4388::Request>,
|
||||||
|
|||||||
+17
-5
@@ -190,11 +190,23 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
|||||||
.ruma_route(&client::well_known_policy_server)
|
.ruma_route(&client::well_known_policy_server)
|
||||||
.ruma_route(&client::get_rtc_transports)
|
.ruma_route(&client::get_rtc_transports)
|
||||||
.ruma_route(&client::room_initial_sync_route)
|
.ruma_route(&client::room_initial_sync_route)
|
||||||
.ruma_route(&client::discover_rendezvous_route)
|
.merge(
|
||||||
.ruma_route(&client::create_rendezvous_session_route)
|
Router::new()
|
||||||
.ruma_route(&client::update_rendezvous_session_route)
|
.ruma_route(&client::discover_rendezvous_route)
|
||||||
.ruma_route(&client::get_rendezvous_session_route)
|
.ruma_route(&client::create_rendezvous_session_route)
|
||||||
.ruma_route(&client::delete_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)
|
.ruma_route(&client::get_authorization_server_metadata_route)
|
||||||
.merge(client::oauth::router(state))
|
.merge(client::oauth::router(state))
|
||||||
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
|
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
|
||||||
|
|||||||
+17
-3
@@ -11,7 +11,11 @@ use axum::{
|
|||||||
use conduwuit::{Error, Result, err, error};
|
use conduwuit::{Error, Result, err, error};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
CanonicalJsonObject,
|
CanonicalJsonObject,
|
||||||
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
|
api::{
|
||||||
|
IncomingRequest, IncomingRequestExt,
|
||||||
|
auth_scheme::AuthScheme,
|
||||||
|
error::{DeserializationError, FromHttpRequestError},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
@@ -114,8 +118,18 @@ where
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Deserialize the body
|
// Deserialize the body
|
||||||
let body = R::try_from_http_request(request, &borrowed_path)
|
let body_is_empty = body.is_empty();
|
||||||
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
|
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 })
|
Ok(Self { body, json_body, identity })
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-1
@@ -194,6 +194,10 @@ impl CheckAuth for AccessTokenOptional {
|
|||||||
authentication: Self::Output,
|
authentication: Self::Output,
|
||||||
query: AuthQueryParams,
|
query: AuthQueryParams,
|
||||||
) -> Result<Self::Identity> {
|
) -> 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 {
|
if let Some(authentication) = authentication {
|
||||||
check_access_token(
|
check_access_token(
|
||||||
services,
|
services,
|
||||||
@@ -278,6 +282,11 @@ impl CheckAuth for NoAccessToken {
|
|||||||
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
|
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 {
|
if let Some(authentication) = authentication {
|
||||||
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
|
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
|
||||||
OAuthClientScope::ApiFullAccess,
|
OAuthClientScope::ApiFullAccess,
|
||||||
@@ -285,7 +294,7 @@ impl CheckAuth for NoAccessToken {
|
|||||||
.await
|
.await
|
||||||
.map(Some)
|
.map(Some)
|
||||||
} else {
|
} else {
|
||||||
if R::RATE_LIMITED {
|
if R::RATE_LIMITED && !is_rendezvous_session {
|
||||||
check_unauthenticated_request_ratelimiting(services, request_ip)?;
|
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)
|
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<()> {
|
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
|
||||||
if services
|
if services
|
||||||
.config
|
.config
|
||||||
|
|||||||
@@ -171,13 +171,14 @@ impl Error {
|
|||||||
/// Returns the Matrix error code / error kind
|
/// Returns the Matrix error code / error kind
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn kind(&self) -> ErrorKind {
|
pub fn kind(&self) -> ErrorKind {
|
||||||
use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
|
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
|
||||||
|
|
||||||
match self {
|
match self {
|
||||||
| Self::Federation(_, error) | Self::Ruma(error) =>
|
| Self::Federation(_, error) | Self::Ruma(error) =>
|
||||||
response::ruma_error_kind(error).clone(),
|
response::ruma_error_kind(error).clone(),
|
||||||
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
||||||
| Self::FeatureDisabled(..) => Unrecognized,
|
| Self::FeatureDisabled(..) => Unrecognized,
|
||||||
|
| Self::Path(_) | Self::Query(_) => InvalidParam,
|
||||||
| _ => Unknown,
|
| _ => Unknown,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -194,6 +195,7 @@ impl Error {
|
|||||||
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
|
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
|
||||||
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||||
| Self::Conflict(_) => StatusCode::CONFLICT,
|
| Self::Conflict(_) => StatusCode::CONFLICT,
|
||||||
|
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
|
||||||
| Self::Io(error) => response::io_error_code(error.kind()),
|
| Self::Io(error) => response::io_error_code(error.kind()),
|
||||||
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
|
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
|
||||||
| _ => StatusCode::INTERNAL_SERVER_ERROR,
|
| _ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
|||||||
@@ -73,6 +73,9 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
|
|||||||
// 413
|
// 413
|
||||||
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
|
||||||
|
// 409
|
||||||
|
| ConcurrentWrite => StatusCode::CONFLICT,
|
||||||
|
|
||||||
// 404
|
// 404
|
||||||
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
|
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
|
||||||
|
|
||||||
|
|||||||
@@ -1,25 +1,38 @@
|
|||||||
use std::{
|
use std::{
|
||||||
|
net::IpAddr,
|
||||||
sync::Arc,
|
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 lru_cache::LruCache;
|
||||||
|
use nonzero_ext::nonzero;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedTransactionId,
|
OwnedTransactionId,
|
||||||
api::client::rendezvous::{
|
api::{
|
||||||
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
client::rendezvous::{
|
||||||
update_rendezvous_session,
|
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
||||||
|
update_rendezvous_session,
|
||||||
|
},
|
||||||
|
error::{ErrorKind, LimitExceededErrorData, RetryAfter},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub struct Service {
|
pub struct Service {
|
||||||
sessions: SyncMutex<LruCache<String, Session>>,
|
sessions: SyncMutex<LruCache<String, Session>>,
|
||||||
|
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||||
|
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Session {
|
struct Session {
|
||||||
data: String,
|
data: String,
|
||||||
created_at: SystemTime,
|
created_at: Instant,
|
||||||
last_sequence_token: String,
|
last_sequence_token: String,
|
||||||
transaction_sequences: LruCache<OwnedTransactionId, String>,
|
transaction_sequences: LruCache<OwnedTransactionId, String>,
|
||||||
}
|
}
|
||||||
@@ -27,20 +40,31 @@ struct Session {
|
|||||||
impl Session {
|
impl Session {
|
||||||
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
|
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 {
|
Self {
|
||||||
data,
|
data,
|
||||||
created_at: SystemTime::now(),
|
created_at: now,
|
||||||
last_sequence_token: sequence_token,
|
last_sequence_token: sequence_token,
|
||||||
transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES),
|
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 {
|
impl crate::Service for Service {
|
||||||
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
|
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||||
Ok(Arc::new(Self {
|
Ok(Arc::new(Self {
|
||||||
sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)),
|
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 {
|
impl Service {
|
||||||
|
const CREATE_RATELIMIT: Quota = Quota::per_minute(nonzero!(30_u32));
|
||||||
const MAX_DATA_SIZE_BYTES: usize = 4096;
|
const MAX_DATA_SIZE_BYTES: usize = 4096;
|
||||||
const MAX_SESSIONS: usize = 256;
|
const MAX_SESSIONS: usize = 256;
|
||||||
const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
|
const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
|
||||||
|
const SESSION_RATELIMIT: Quota = Quota::per_minute(nonzero!(300_u32));
|
||||||
const TOKEN_LENGTH: usize = 32;
|
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 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.
|
/// Lock and fetch an unexpired rendezvous session.
|
||||||
fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, 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
|
// We don't clear out expired sessions manually, the LRU cache will
|
||||||
// evict them over time
|
// evict them over time
|
||||||
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
|
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
|
||||||
sessions
|
sessions
|
||||||
.get_mut(id)
|
.get_mut(id)
|
||||||
.filter(|session| {
|
.filter(|session| !session.is_expired(now))
|
||||||
SystemTime::now()
|
|
||||||
.duration_since(session.created_at)
|
|
||||||
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
|
|
||||||
})
|
|
||||||
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
|
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
|
||||||
})
|
})
|
||||||
.map_err(at!(1))
|
.map_err(at!(1))
|
||||||
@@ -86,7 +149,7 @@ impl Service {
|
|||||||
|
|
||||||
self.sessions
|
self.sessions
|
||||||
.lock()
|
.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(
|
Ok(create_rendezvous_session::msc4388::Response::new(
|
||||||
id,
|
id,
|
||||||
@@ -103,6 +166,12 @@ impl Service {
|
|||||||
sequence_token: String,
|
sequence_token: String,
|
||||||
data: String,
|
data: String,
|
||||||
) -> Result<update_rendezvous_session::msc4388::Response> {
|
) -> 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)?;
|
let mut session = self.lock_session(id)?;
|
||||||
|
|
||||||
// If the provided transaction ID was used already, we have to return
|
// 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.
|
/// Look up a rendezvous session by ID.
|
||||||
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
|
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()
|
let session_time_remaining = session
|
||||||
.duration_since(session.created_at)
|
.time_remaining(now)
|
||||||
.unwrap_or(Duration::MAX);
|
.unwrap_or_else(|| Duration::from_millis(1));
|
||||||
|
|
||||||
let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age);
|
|
||||||
|
|
||||||
Ok(get_rendezvous_session::msc4388::Response::new(
|
Ok(get_rendezvous_session::msc4388::Response::new(
|
||||||
session.last_sequence_token.clone(),
|
session.last_sequence_token.clone(),
|
||||||
@@ -158,8 +226,12 @@ impl Service {
|
|||||||
id: &str,
|
id: &str,
|
||||||
) -> Result<delete_rendezvous_session::msc4388::Response> {
|
) -> Result<delete_rendezvous_session::msc4388::Response> {
|
||||||
let mut sessions = self.sessions.lock();
|
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())
|
Ok(delete_rendezvous_session::msc4388::Response::new())
|
||||||
} else {
|
} else {
|
||||||
Err!(Request(NotFound("Unknown session")))
|
Err!(Request(NotFound("Unknown session")))
|
||||||
|
|||||||
Reference in new issue
Block a user