Compare commits

..
19 changed files with 176 additions and 213 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
Network issues while refreshing an access token will no longer cause OAuth-compatible clients to be forcibly logged out. Contributed by @ginger.
-1
View File
@@ -1 +0,0 @@
Continuwuity will now request the `profile` OIDC scope from identity providers by default to improve compatibility with identity providers that require it to access users' profile claims, as recommended by the OIDC specification. Contributed by @ginger.
-1
View File
@@ -1 +0,0 @@
Attempting to start a UIAA session on a homeserver with UIAA disabled will now return `403 M_UNAUTHORIZED` instead of `404 M_UNSUPPORTED`. Contributed by @ginger.
+2 -4
View File
@@ -2582,12 +2582,10 @@
# Additional scopes Continuwuity should request from the IDP. This may be
# necessary to access certain claims. Continuwuity always requests the
# `openid` scope, regardless of the contents of this option,
# and will also request the `profile` scope by default if this option is
# not set.
# `openid` scope.
#
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES
#additional_scopes = ["profile"]
#additional_scopes = []
# Additional trusted audiences that Continuwuity will accept in the `aud`
# claim of the OIDC token returned by the IDP. If your identity
-1
View File
@@ -26,7 +26,6 @@
LD_LIBRARY_PATH = lib.makeLibraryPath (
[
pkgs.stdenv.cc.cc.lib
pkgs.llvmPackages.libclang.lib
]
++ lib.optionals pkgs.stdenv.hostPlatform.isLinux [
pkgs.liburing
+9 -23
View File
@@ -9,7 +9,7 @@ use service::Services;
use crate::{Ruma, router::ClientIdentity};
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous`
/// `GET /_matrix/client/msc4388/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/unstable/io.element.msc4388/rendezvous`
/// `POST /_matrix/client/msc4388/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/unstable/io.element.msc4388/rendezvous/{id}/{txn_id}`
/// `PUT /_matrix/client/msc4388/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,30 +45,16 @@ pub(crate) async fn update_rendezvous_session_route(
)
}
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
/// `GET /_matrix/client/msc4388/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> {
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 {
if let Some(mode) = headers.get("Sec-Fetch-Mode")
&& let Ok(mode) = mode.to_str()
&& mode == "navigate"
{
return Err!(Request(Forbidden(
"Rendezvous sessions do not accept browser navigation requests."
)));
@@ -77,7 +63,7 @@ pub(crate) async fn get_rendezvous_session_route(
services.rendezvous.get_session(&body.id)
}
/// `DELETE /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
/// `DELETE /_matrix/client/msc4388/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>,
+5 -17
View File
@@ -190,23 +190,11 @@ 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)
.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::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)
.ruma_route(&client::get_authorization_server_metadata_route)
.merge(client::oauth::router(state))
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
+3 -17
View File
@@ -11,11 +11,7 @@ use axum::{
use conduwuit::{Error, Result, err, error};
use ruma::{
CanonicalJsonObject,
api::{
IncomingRequest, IncomingRequestExt,
auth_scheme::AuthScheme,
error::{DeserializationError, FromHttpRequestError},
},
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
};
use serde::Deserialize;
@@ -118,18 +114,8 @@ where
.await?;
// Deserialize the body
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}")))),
})?;
let body = R::try_from_http_request(request, &borrowed_path)
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
Ok(Self { body, json_body, identity })
}
+23 -30
View File
@@ -194,10 +194,6 @@ 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,
@@ -282,11 +278,6 @@ 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,
@@ -294,7 +285,7 @@ impl CheckAuth for NoAccessToken {
.await
.map(Some)
} else {
if R::RATE_LIMITED && !is_rendezvous_session {
if R::RATE_LIMITED {
check_unauthenticated_request_ratelimiting(services, request_ip)?;
}
@@ -328,6 +319,19 @@ async fn check_access_token(
));
}
let session_info = services
.oauth
.get_session_info_for_device(&sender_user, &sender_device)
.await;
if let Some(session_info) = &session_info {
services.oauth.clear_previous_refresh_token(
&sender_user,
&sender_device,
session_info,
);
}
// Locked users can only use /logout and /logout/all
if services
.users
@@ -342,12 +346,6 @@ async fn check_access_token(
}
}
let session_info = services
.oauth
.get_session_info_for_device(&sender_user, &sender_device)
.await
.map(Box::new);
// Make sure the user has the right scopes to use the route
let mut user_scopes = if let Some(session_info) = &session_info {
session_info.scopes()
@@ -425,6 +423,15 @@ async fn check_access_token(
sender_device,
appservice_info: Box::new(appservice_info),
})
} else if services.users.is_previous_token(token).await {
// Return a soft-logout for previous tokens. This is necessary
// to make token refreshing idempotent.
Err(Error::Request(
ErrorKind::UnknownToken(assign!(UnknownTokenErrorData::new(), { soft_logout: true })),
"This token has expired".into(),
StatusCode::UNAUTHORIZED,
))
} else {
Err(Error::Request(
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
@@ -442,20 +449,6 @@ 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 -7
View File
@@ -2823,12 +2823,10 @@ pub struct OidcConfig {
/// Additional scopes Continuwuity should request from the IDP. This may be
/// necessary to access certain claims. Continuwuity always requests the
/// `openid` scope, regardless of the contents of this option,
/// and will also request the `profile` scope by default if this option is
/// not set.
/// `openid` scope.
///
/// default: ["profile"]
#[serde(default = "default_additional_scopes")]
/// default: []
#[serde(default)]
pub additional_scopes: Vec<Scope>,
/// Additional trusted audiences that Continuwuity will accept in the `aud`
@@ -3448,8 +3446,6 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
}
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
// NOTE: This must be declared *after* every config struct in this file. The
// example config generator writes sections in macro expansion order, and the
// `global` section truncates the file, so declaring this module any earlier
+1 -3
View File
@@ -171,14 +171,13 @@ impl Error {
/// Returns the Matrix error code / error kind
#[inline]
pub fn kind(&self) -> ErrorKind {
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
use ruma::api::error::ErrorKind::{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,
}
}
@@ -195,7 +194,6 @@ 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,9 +73,6 @@ 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,
+4
View File
@@ -407,6 +407,10 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "userdeviceid_token",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userdeviceid_previoustoken",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userdevicesessionid_uiaainfo",
..descriptor::RANDOM_SMALL
+77 -10
View File
@@ -1,5 +1,6 @@
use std::{
collections::{BTreeSet, HashMap},
fmt::Write,
sync::Arc,
time::{Duration, SystemTime},
};
@@ -55,7 +56,7 @@ struct Services {
config: Dep<config::Service>,
}
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SessionInfo {
pub client_id: String,
#[serde(deserialize_with = "client_metadata::btreeset_skip_err")]
@@ -64,6 +65,8 @@ pub struct SessionInfo {
temporary_scopes: BTreeSet<OAuthClientScope>,
#[serde(default)]
current_refresh_token: String,
#[serde(default)]
previous_refresh_token: Option<String>,
}
impl SessionInfo {
@@ -71,6 +74,15 @@ impl SessionInfo {
pub fn scopes(&self) -> BTreeSet<OAuthClientScope> {
self.scopes.union(&self.temporary_scopes).cloned().collect()
}
#[must_use]
pub fn scope_string(&self, device_id: &DeviceId) -> String {
let mut scopes = self.scopes().iter().join(" ");
let _ = write!(scopes, " urn:matrix:client:device:{device_id}");
scopes
}
}
#[derive(Debug, Deserialize, Serialize)]
@@ -246,6 +258,24 @@ impl Service {
.ok()
}
/// Clear a session's previous refresh token, if it has one.
pub fn clear_previous_refresh_token(
&self,
user_id: &UserId,
device_id: &DeviceId,
session_info: &SessionInfo,
) {
if session_info.previous_refresh_token.is_some() {
let mut session_info = session_info.clone();
session_info.previous_refresh_token = None;
self.db
.userdeviceid_oauthsessioninfo
.put((user_id, device_id), Json(session_info));
}
}
pub async fn request_authorization_code(
&self,
authorizing_user: OwnedUserId,
@@ -645,6 +675,7 @@ impl Service {
SessionInfo {
client_id: client_id.clone(),
current_refresh_token: Self::generate_token(),
previous_refresh_token: None,
scopes: requested_scopes.scopes,
temporary_scopes: BTreeSet::new(),
}
@@ -702,15 +733,53 @@ impl Service {
assert_eq!(&client_id, &session_info.client_id, "session info client id mismatch");
// TODO: this doesn't include the device ID "scope", do any clients rely
// on that?
let scope = session_info.scopes.iter().join(" ");
let new_refresh_token = Self::generate_token();
if refresh_token == session_info.current_refresh_token {
// The client is refreshing with their current refresh token.
// We need to generate a new refresh token and save this token as
// the previous one.
session_info
.current_refresh_token
.clone_from(&new_refresh_token);
// Remove the old previous token if it's set. This can only happen
// if the client decides to refresh twice in a row without using its
// new access token, since we'll also do this when the new access
// token is used for the first time.
if let Some(previous_refresh_token) = session_info.previous_refresh_token {
self.db
.refreshtoken_refreshtokeninfo
.remove(&previous_refresh_token);
}
session_info.previous_refresh_token = Some(refresh_token);
} else if Some(&refresh_token) == session_info.previous_refresh_token.as_ref() {
// The client is refreshing with their previous refresh token,
// probably because they didn't get the new one we made for them. We
// need to make a second new one, but we don't touch the existing
// previous one in case they don't get the second new one either.
// Wipe the current token, we're going to make a new one.
self.db
.refreshtoken_refreshtokeninfo
.remove(&session_info.current_refresh_token);
session_info
.current_refresh_token
.clone_from(&new_refresh_token);
} else {
// The client is trying to use a refresh token that isn't their
// current or previous one, but still has information in the
// database. This is definitely not a legal state, so we need to
// bail out.
panic!("refresh token is not current or previous for its session");
}
let scope = session_info.scope_string(&refresh_token_info.device_id);
let new_access_token = DeviceToken::new_random().with_max_age(Self::ACCESS_TOKEN_MAX_AGE);
let new_refresh_token = Self::generate_token();
session_info
.current_refresh_token
.clone_from(&new_refresh_token);
self.services
.users
@@ -729,8 +798,6 @@ impl Service {
Json(session_info),
);
self.db.refreshtoken_refreshtokeninfo.remove(&refresh_token);
drop(refresh_token);
self.db
.refreshtoken_refreshtokeninfo
.raw_put(&new_refresh_token, Json(refresh_token_info));
+21 -93
View File
@@ -1,38 +1,25 @@
use std::{
net::IpAddr,
sync::Arc,
time::{Duration, Instant},
time::{Duration, SystemTime},
};
use conduwuit::{
Err, Error, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils,
};
use governor::{
DefaultKeyedRateLimiter, Quota, RateLimiter,
clock::{Clock, DefaultClock},
};
use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils};
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,
},
error::{ErrorKind, LimitExceededErrorData, RetryAfter},
api::client::rendezvous::{
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
update_rendezvous_session,
},
};
pub struct Service {
sessions: SyncMutex<LruCache<String, Session>>,
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
}
struct Session {
data: String,
created_at: Instant,
created_at: SystemTime,
last_sequence_token: String,
transaction_sequences: LruCache<OwnedTransactionId, String>,
}
@@ -40,31 +27,20 @@ struct Session {
impl Session {
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
fn new(data: String, sequence_token: String, now: Instant) -> Self {
fn new(data: String, sequence_token: String) -> Self {
Self {
data,
created_at: now,
created_at: SystemTime::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),
}))
}
@@ -72,64 +48,25 @@ 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| !session.is_expired(now))
.filter(|session| {
SystemTime::now()
.duration_since(session.created_at)
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
})
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
})
.map_err(at!(1))
@@ -149,7 +86,7 @@ impl Service {
self.sessions
.lock()
.insert(id.clone(), Session::new(data, sequence_token.clone(), Instant::now()));
.insert(id.clone(), Session::new(data, sequence_token.clone()));
Ok(create_rendezvous_session::msc4388::Response::new(
id,
@@ -166,12 +103,6 @@ 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
@@ -206,12 +137,13 @@ impl Service {
/// Look up a rendezvous session by ID.
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
let now = Instant::now();
let session = self.lock_session_at(id, now)?;
let session = self.lock_session(id)?;
let session_time_remaining = session
.time_remaining(now)
.unwrap_or_else(|| Duration::from_millis(1));
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);
Ok(get_rendezvous_session::msc4388::Response::new(
session.last_sequence_token.clone(),
@@ -226,12 +158,8 @@ 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_and(|session| !session.is_expired(now))
{
if sessions.remove(id).is_some() {
Ok(delete_rendezvous_session::msc4388::Response::new())
} else {
Err!(Request(NotFound("Unknown session")))
+2 -2
View File
@@ -348,8 +348,8 @@ impl Service {
.compatibility_mode()
.uiaa_available()
{
return Err!(Request(Forbidden(
"User-interactive authentication is not available on this server."
return Err!(Request(Unrecognized(
"User-interactive authentication is unavailable on this server"
)));
}
+6
View File
@@ -632,6 +632,12 @@ impl super::Service {
}
}
// Discard this device's previous token entry if the current token
// isn't expired.
self.db
.userdeviceid_previoustoken
.del((&user_id, &device_id));
Some((user_id, device_id, AccessTokenStatus::Valid))
}
+17 -1
View File
@@ -184,8 +184,13 @@ impl super::Service {
// Remove old token
if let Ok(old_token) = self.db.userdeviceid_token.qry(&key).await {
self.db.token_userdeviceid.remove(&old_token);
self.db.userdeviceid_tokenexpires.remove(&old_token);
// It will be removed from userdeviceid_token by the insert later
// Save the previous token only if we don't already have one saved
// for this device.
if !self.db.userdeviceid_previoustoken.contains(&key).await {
self.db.userdeviceid_previoustoken.put_raw(key, &old_token);
}
}
// Assign token to user device combination
@@ -207,6 +212,17 @@ impl super::Service {
Ok(())
}
/// Returns whether the provided token was previously used by a device
/// before a token refresh, and therefore should cause a soft-logout.
pub async fn is_previous_token(&self, token: &str) -> bool {
self.db
.userdeviceid_previoustoken
.stream::<Ignore, String>()
.ignore_err()
.ready_any(|(_, previous_token)| previous_token == token)
.await
}
/// Pushes a new to-device event into a device's inbox.
pub async fn add_to_device_event(
&self,
+2
View File
@@ -83,6 +83,7 @@ struct Data {
userdeviceid_tokenexpires: Arc<Map>,
userdeviceid_metadata: Arc<Map>,
userdeviceid_token: Arc<Map>,
userdeviceid_previoustoken: Arc<Map>,
userfilterid_filter: Arc<Map>,
userid_avatarurl: Arc<Map>,
userid_deactivated: Arc<Map>,
@@ -134,6 +135,7 @@ impl crate::Service for Service {
remoteuserid_remoteuser: args.db["remoteuserid_remoteuser"].clone(),
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
userdeviceid_token: args.db["userdeviceid_token"].clone(),
userdeviceid_previoustoken: args.db["userdeviceid_previoustoken"].clone(),
userfilterid_filter: args.db["userfilterid_filter"].clone(),
userid_avatarurl: args.db["userid_avatarurl"].clone(),
userid_deactivated: args.db["userid_deactivated"].clone(),