Merge branch 'main' into nex/feat/notary-server

# Conflicts:
#	src/api/server/key.rs
#	src/service/server_keys/mod.rs
#	src/service/server_keys/request.rs
#	src/service/server_keys/verify.rs
This commit is contained in:
timedout committed 2026-11-23 14:18:38 +00:00
commit 98d78dfdf1
335 files changed
+9944 -6292

No files matched your search

+1 -3
View File
@@ -51,8 +51,6 @@ jemalloc_stats = [
release_max_log_level = [
"conduwuit-core/release_max_log_level",
"conduwuit-service/release_max_log_level",
"log/max_level_trace",
"log/release_max_level_info",
"tracing/max_level_trace",
"tracing/release_max_level_info",
]
@@ -80,7 +78,6 @@ http-body-util.workspace = true
hyper.workspace = true
itertools.workspace = true
lettre.workspace = true
log.workspace = true
rand.workspace = true
reqwest.workspace = true
ruma.workspace = true
@@ -90,6 +87,7 @@ serde.workspace = true
sha1.workspace = true
tokio.workspace = true
tracing.workspace = true
wildmatch.workspace = true
[lints]
workspace = true
-1
View File
@@ -135,7 +135,6 @@ pub(crate) async fn add_3pid_route(
let email = services
.threepid
.get_valid_session(&body.sid, &body.client_secret)
.await
.map_err(|message| err!(Request(ThreepidAuthFailed("{message}"))))?
.consume();
+7 -4
View File
@@ -117,10 +117,13 @@ async fn set_account_data(
data: &RawJsonValue,
) -> Result {
if event_type_s == "m.fully_read" {
return Err!(Request(BadJson(
"This endpoint cannot be used for marking a room as fully read (setting \
m.fully_read)"
)));
return Err!(Request(
BadJson(
"This endpoint cannot be used for marking a room as fully read (setting \
m.fully_read)"
),
METHOD_NOT_ALLOWED
));
}
let data: serde_json::Value = serde_json::from_str(data.get())
+2 -4
View File
@@ -20,8 +20,7 @@ pub(crate) async fn create_alias_route(
services
.rooms
.alias
.appservice_checks(&body.room_alias, body.identity.appservice_info())
.await?;
.appservice_checks(&body.room_alias, body.identity.appservice_info())?;
// this isn't apart of alias_checks or delete alias route because we should
// allow removing forbidden room aliases
@@ -69,8 +68,7 @@ pub(crate) async fn delete_alias_route(
services
.rooms
.alias
.appservice_checks(&body.room_alias, body.identity.appservice_info())
.await?;
.appservice_checks(&body.room_alias, body.identity.appservice_info())?;
services
.rooms
+12 -5
View File
@@ -1,7 +1,7 @@
use std::collections::{BTreeMap, BTreeSet};
use axum::extract::State;
use conduwuit::{Result, Server};
use conduwuit::{Result, Server, config::experiments::ToggledExperiment};
use ruma::{
RoomVersionId,
api::{
@@ -46,14 +46,18 @@ pub(crate) async fn get_capabilities_route(
capabilities.get_login_token =
GetLoginTokenCapability::new(services.server.config.login_via_existing_session);
capabilities.forget_forced_upon_leave.enabled = true;
capabilities.forget_forced_upon_leave.enabled =
services.server.config.forget_forced_upon_leave;
if services.users.is_admin(sender_user).await {
capabilities.account_moderation.lock = true;
capabilities.account_moderation.suspend = true;
capabilities.admin =
AdminCapability::new(BTreeSet::from_iter([OAuthClientScope::ServerAdministration]));
if services.config.experiments.msc4484.is_enabled() {
capabilities.admin = AdminCapability::new(BTreeSet::from_iter([
OAuthClientScope::ServerAdministration,
]));
}
}
capabilities.profile_fields = Some(
@@ -62,7 +66,10 @@ pub(crate) async fn get_capabilities_route(
capabilities.set(
"org.matrix.msc4174.webpush",
json!({ "enabled": true, "vapid": services.pusher.webpush_vapid_public_key() }),
json!({
"enabled": services.config.experiments.msc4174.is_enabled(),
"vapid": services.pusher.webpush_vapid_public_key()
}),
)?;
Ok(get_capabilities::v3::Response::new(capabilities))
+4 -4
View File
@@ -3,10 +3,10 @@ use conduwuit::{Err, Result, at};
use futures::StreamExt;
use ruma::{
api::client::dehydrated_device::{
delete_dehydrated_device::unstable as delete_dehydrated_device,
get_dehydrated_device::unstable as get_dehydrated_device,
get_events::unstable as get_events,
put_dehydrated_device::unstable as put_dehydrated_device,
delete_dehydrated_device::msc3814 as delete_dehydrated_device,
get_dehydrated_device::msc3814 as get_dehydrated_device,
get_events::msc3814 as get_events,
put_dehydrated_device::msc3814 as put_dehydrated_device,
},
assign,
};
+19 -5
View File
@@ -15,8 +15,7 @@ use ruma::{
OneTimeKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
api::{
client::keys::{
claim_keys, get_key_changes, get_keys, upload_keys,
upload_signatures::{self},
claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures,
upload_signing_keys,
},
federation,
@@ -523,7 +522,22 @@ where
for (server, response) in futures {
match response {
| Ok(response) => {
for (user, master_key) in response.master_keys {
let is_wanted = |user_id: &UserId| {
user_id.server_name() == server && device_keys_input.contains_key(user_id)
};
let filtered_master_keys = response
.master_keys
.into_iter()
.filter(|(user_id, _)| is_wanted(user_id));
let filtered_self_signing_keys = response
.self_signing_keys
.into_iter()
.filter(|(user_id, _)| is_wanted(user_id));
let filtered_device_keys = response
.device_keys
.into_iter()
.filter(|(user_id, _)| is_wanted(user_id));
for (user, master_key) in filtered_master_keys {
let (master_key_id, mut master_key) = parse_master_key(&user, &master_key)?;
if let Ok(our_master_key) = services
@@ -549,8 +563,8 @@ where
}
}
self_signing_keys.extend(response.self_signing_keys);
device_keys.extend(response.device_keys);
self_signing_keys.extend(filtered_self_signing_keys);
device_keys.extend(filtered_device_keys);
},
| Err(e) => {
failures.insert(server.to_string(), json!({ "error": e.to_string() }));
+5 -3
View File
@@ -2,7 +2,7 @@ use std::time::Duration;
use axum::extract::State;
use conduwuit::{
Err, Result, err,
Err, Result, debug, err,
utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize},
};
use conduwuit_core::error;
@@ -30,9 +30,9 @@ pub(crate) async fn get_media_config_route(
State(services): State<crate::State>,
_body: Ruma<get_media_config::v1::Request>,
) -> Result<get_media_config::v1::Response> {
Ok(get_media_config::v1::Response::new(ruma_from_usize(
Ok(get_media_config::v1::Response::new(Some(ruma_from_usize(
services.server.config.max_request_size,
)))
))))
}
/// # `POST /_matrix/media/v3/upload`
@@ -219,10 +219,12 @@ pub(crate) async fn get_media_preview_route(
)));
}
debug!("Fetching a URL preview for {url} on behalf of {sender_user}");
let preview = services
.media
.get_url_preview(&url)
.await
.inspect(|_| debug!(user=%sender_user, %url, "Finished fetching a URL preview"))
.map_err(|error| {
err!(Request(Unknown(
debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}")
-398
View File
@@ -1,398 +0,0 @@
#![allow(deprecated)]
use axum::extract::State;
use conduwuit::{
Err, Result, err,
utils::{content_disposition::make_content_disposition, math::ruma_from_usize},
};
use conduwuit_service::media::{CORP_CROSS_ORIGIN, Dim, FileMeta};
use reqwest::Url;
use ruma::{
api::client::media::{
create_content, get_content, get_content_as_filename, get_content_thumbnail,
get_media_config, get_media_preview,
},
assign,
};
use service::media::mxc::Mxc;
use crate::{Ruma, RumaResponse, client::create_content_route};
/// # `GET /_matrix/media/v3/config`
///
/// Returns max upload size.
pub(crate) async fn get_media_config_legacy_route(
State(services): State<crate::State>,
_body: Ruma<get_media_config::v3::Request>,
) -> Result<get_media_config::v3::Response> {
Ok(get_media_config::v3::Response::new(ruma_from_usize(
services.server.config.max_request_size,
)))
}
/// # `GET /_matrix/media/v1/config`
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// Returns max upload size.
pub(crate) async fn get_media_config_legacy_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_media_config::v3::Request>,
) -> Result<RumaResponse<get_media_config::v3::Response>> {
get_media_config_legacy_route(State(services), body)
.await
.map(RumaResponse)
}
/// # `GET /_matrix/media/v3/preview_url`
///
/// Returns URL preview.
pub(crate) async fn get_media_preview_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_media_preview::v3::Request>,
) -> Result<get_media_preview::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
let url = &body.url;
let url = Url::parse(&body.url).map_err(|e| {
err!(Request(InvalidParam(
debug_warn!(%sender_user, %url, "Requested URL is not valid: {e}")
)))
})?;
if !services.media.url_preview_allowed(&url) {
return Err!(Request(Forbidden(
debug_warn!(%sender_user, %url, "URL is not allowed to be previewed")
)));
}
let preview = services.media.get_url_preview(&url).await.map_err(|e| {
err!(Request(Unknown(
debug_error!(%sender_user, %url, "Failed to fetch a URL preview: {e}")
)))
})?;
serde_json::value::to_raw_value(&preview)
.map(get_media_preview::v3::Response::from_raw_value)
.map_err(|error| {
err!(Request(Unknown(
debug_error!(%sender_user, %url, "Failed to parse URL preview: {error}")
)))
})
}
/// # `GET /_matrix/media/v1/preview_url`
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// Returns URL preview.
pub(crate) async fn get_media_preview_legacy_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_media_preview::v3::Request>,
) -> Result<RumaResponse<get_media_preview::v3::Response>> {
get_media_preview_legacy_route(State(services), body)
.await
.map(RumaResponse)
}
/// # `POST /_matrix/media/v1/upload`
///
/// Permanently save media in the server.
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// - Some metadata will be saved in the database
/// - Media will be saved in the media/ directory
pub(crate) async fn create_content_legacy_route(
State(services): State<crate::State>,
body: Ruma<create_content::v3::Request>,
) -> Result<RumaResponse<create_content::v3::Response>> {
create_content_route(State(services), body)
.await
.map(RumaResponse)
}
/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}`
///
/// Load media from our server or over federation.
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub(crate) async fn get_content_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_content::v3::Request>,
) -> Result<get_content::v3::Response> {
let mxc = Mxc {
server_name: &body.server_name,
media_id: &body.media_id,
};
match services.media.get(&mxc).await? {
| Some(FileMeta {
content,
content_type,
content_disposition,
}) => {
let content_disposition = make_content_disposition(
content_disposition.as_ref(),
content_type.as_deref(),
None,
);
Ok(assign!(
get_content::v3::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
}
))
},
| _ =>
if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
let response = services
.media
.fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms)
.await
.map_err(|e| {
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}"))))
})?;
let content_disposition = make_content_disposition(
response.content_disposition.as_ref(),
response.content_type.as_deref(),
None,
);
Ok(assign!(
get_content::v3::Response::new(
response.file,
response.content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
}
))
} else {
Err!(Request(NotFound("Media not found.")))
},
}
}
/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}`
///
/// Load media from our server or over federation.
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub(crate) async fn get_content_legacy_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_content::v3::Request>,
) -> Result<RumaResponse<get_content::v3::Response>> {
get_content_legacy_route(State(services), body)
.await
.map(RumaResponse)
}
/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}/{fileName}`
///
/// Load media from our server or over federation, permitting desired filename.
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub(crate) async fn get_content_as_filename_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_content_as_filename::v3::Request>,
) -> Result<get_content_as_filename::v3::Response> {
let mxc = Mxc {
server_name: &body.server_name,
media_id: &body.media_id,
};
match services.media.get(&mxc).await? {
| Some(FileMeta {
content,
content_type,
content_disposition,
}) => {
let content_disposition = make_content_disposition(
content_disposition.as_ref(),
content_type.as_deref(),
Some(&body.filename),
);
Ok(assign!(get_content_as_filename::v3::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
}
))
},
| _ =>
if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
let response = services
.media
.fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms)
.await
.map_err(|e| {
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}"))))
})?;
let content_disposition = make_content_disposition(
response.content_disposition.as_ref(),
response.content_type.as_deref(),
None,
);
Ok(assign!(
get_content_as_filename::v3::Response::new(
response.file,
response.content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()),
}
))
} else {
Err!(Request(NotFound("Media not found.")))
},
}
}
/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}/{fileName}`
///
/// Load media from our server or over federation, permitting desired filename.
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub(crate) async fn get_content_as_filename_legacy_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_content_as_filename::v3::Request>,
) -> Result<RumaResponse<get_content_as_filename::v3::Response>> {
get_content_as_filename_legacy_route(State(services), body)
.await
.map(RumaResponse)
}
/// # `GET /_matrix/media/v3/thumbnail/{serverName}/{mediaId}`
///
/// Load media thumbnail from our server or over federation.
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub(crate) async fn get_content_thumbnail_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_content_thumbnail::v3::Request>,
) -> Result<get_content_thumbnail::v3::Response> {
let mxc = Mxc {
server_name: &body.server_name,
media_id: &body.media_id,
};
let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?;
match services.media.get_thumbnail(&mxc, &dim).await? {
| Some(FileMeta {
content,
content_type,
content_disposition,
}) => {
let content_disposition = make_content_disposition(
content_disposition.as_ref(),
content_type.as_deref(),
None,
);
Ok(assign!(
get_content_thumbnail::v3::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
}
))
},
| _ =>
if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
let response = services
.media
.fetch_remote_thumbnail_legacy(&body)
.await
.map_err(|e| {
err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}"))))
})?;
let content_disposition = make_content_disposition(
response.content_disposition.as_ref(),
response.content_type.as_deref(),
None,
);
Ok(assign!(
get_content_thumbnail::v3::Response::new(
response.file,
response.content_type.unwrap_or_default(),
content_disposition,
),
{
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
}
))
} else {
Err!(Request(NotFound("Media not found.")))
},
}
}
/// # `GET /_matrix/media/v1/thumbnail/{serverName}/{mediaId}`
///
/// Load media thumbnail from our server or over federation.
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub(crate) async fn get_content_thumbnail_legacy_legacy_route(
State(services): State<crate::State>,
body: Ruma<get_content_thumbnail::v3::Request>,
) -> Result<RumaResponse<get_content_thumbnail::v3::Response>> {
get_content_thumbnail_legacy_route(State(services), body)
.await
.map(RumaResponse)
}
+16 -20
View File
@@ -1,4 +1,4 @@
use std::{borrow::Borrow, collections::HashMap, iter::once, sync::Arc};
use std::{borrow::Borrow, collections::HashMap, sync::Arc};
use axum::extract::State;
use conduwuit::{
@@ -16,10 +16,7 @@ use futures::{FutureExt, StreamExt};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName,
OwnedUserId, RoomId, UserId,
api::{
client::knock::knock_room,
federation::{self},
},
api::{client::knock::knock_room, federation},
canonical_json::to_canonical_value,
events::{
StateEventType,
@@ -461,14 +458,13 @@ async fn knock_room_helper_local(
services
.rooms
.timeline
.append_pdu(
&parsed_knock_pdu,
knock_event,
once(parsed_knock_pdu.event_id.borrow()),
&state_lock,
room_id,
)
.progress_extremities(&parsed_knock_pdu)
.await?;
services
.rooms
.timeline
.append_pdu(&parsed_knock_pdu, knock_event, room_id)
.await;
Ok(())
}
@@ -587,7 +583,7 @@ async fn knock_room_helper_remote(
let mut state_map: HashMap<u64, OwnedEventId> = HashMap::new();
for event in state {
for mut event in state {
let Some(state_key) = event.get("state_key") else {
debug_warn!("send_knock stripped state event missing state_key: {event:?}");
continue;
@@ -614,6 +610,7 @@ async fn knock_room_helper_remote(
.get_or_create_shortstatekey(&event_type, &state_key)
.await;
event.insert("event_id".into(), CanonicalJsonValue::String(event_id.to_string()));
services.rooms.outlier.add_pdu_outlier(&event_id, &event);
state_map.insert(shortstatekey, event_id.clone());
}
@@ -662,14 +659,13 @@ async fn knock_room_helper_remote(
services
.rooms
.timeline
.append_pdu(
&parsed_knock_pdu,
knock_event,
once(parsed_knock_pdu.event_id.borrow()),
&state_lock,
room_id,
)
.progress_extremities(&parsed_knock_pdu)
.await?;
services
.rooms
.timeline
.append_pdu(&parsed_knock_pdu, knock_event, room_id)
.await;
info!("Setting final room state for new room");
// We set the room state after inserting the pdu, so that we never have a
+1 -4
View File
@@ -10,10 +10,7 @@ use conduwuit::{
use futures::{FutureExt, StreamExt, pin_mut};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedServerName, RoomId, UserId,
api::{
client::membership::leave_room,
federation::{self},
},
api::{client::membership::leave_room, federation},
events::{
StateEventType,
room::member::{MembershipState, RoomMemberEventContent},
+1 -1
View File
@@ -9,7 +9,7 @@ use conduwuit::{
use futures::{FutureExt, StreamExt, future::join};
use ruma::{
api::client::membership::{
get_member_events::{self},
get_member_events,
joined_members::{self, v3::RoomMember},
},
events::{
+39 -32
View File
@@ -1,6 +1,8 @@
use axum::extract::State;
use conduwuit::{
Err, Error, Result, at, debug_warn,
Err, Error, Result, at,
config::experiments::ToggledExperiment,
debug_warn,
matrix::{
event::{Event, Matches},
pdu::PduCount,
@@ -22,7 +24,7 @@ use conduwuit_service::{
};
use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture, pin_mut};
use ruma::{
RoomId, UserId,
EventId, RoomId, UserId,
api::{
Direction,
client::{filter::RoomEventFilter, message::get_message_events},
@@ -30,8 +32,9 @@ use ruma::{
},
assign,
events::{
AnyStateEvent, StateEventType,
AnyStateEvent, StateEventType, SyncEphemeralRoomEvent,
TimelineEventType::{self, *},
receipt::ReceiptEventContent,
},
serde::Raw,
};
@@ -209,36 +212,32 @@ pub(crate) async fn lazy_loading_witness<'a, I>(
where
I: Iterator<Item = &'a PdusIterItem> + Clone + Send,
{
let oldest = events
.clone()
.map(|(count, _)| count)
.copied()
.min()
.unwrap_or_else(PduCount::max);
let newest = events
.clone()
.map(|(count, _)| count)
.copied()
.max()
.unwrap_or_else(PduCount::max);
let chunk_event_ids: std::collections::HashSet<&EventId> =
events.clone().map(|(_, event)| event.event_id()).collect();
let receipts = services
.rooms
.read_receipt
.readreceipts_since(lazy_loading_context.room_id, Some(oldest.into_unsigned()));
.readreceipts_since(lazy_loading_context.room_id, None);
pin_mut!(receipts);
let receipt_users = receipts.ready_filter_map(|(user_id, _, raw)| {
let event =
serde_json::from_str::<SyncEphemeralRoomEvent<ReceiptEventContent>>(raw.json().get())
.ok()?;
event
.content
.keys()
.any(|id| chunk_event_ids.contains(&**id))
.then_some(user_id)
});
let witness: MemberSet = events
.stream()
.map(ref_at!(1))
.map(Event::sender)
.map(ToOwned::to_owned)
.chain(
receipts
.ready_take_while(|(_, c, _)| *c <= newest.into_unsigned())
.map(|(user_id, ..)| user_id),
)
.chain(receipt_users)
.collect()
.await;
@@ -318,21 +317,29 @@ where
if server_ignored {
// the sender's server is ignored, so ignore this event
return Err(Error::BadRequest(
ErrorKind::SenderIgnored(SenderIgnoredErrorData::new()),
"The sender's server is ignored by this server.",
));
return if services.config.experiments.msc4406.is_enabled() {
Err(Error::BadRequest(
ErrorKind::SenderIgnored(SenderIgnoredErrorData::new()),
"The sender's server is ignored by this server.",
))
} else {
Err!(Request(NotFound("This event's sender's homeserver is ignored by this server.")))
};
}
if user_ignored && !services.config.send_messages_from_ignored_users_to_client {
// the recipient of this PDU has the sender ignored, and we're not
// configured to send ignored messages to clients
return Err(Error::BadRequest(
ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender(
event.sender().to_owned(),
)),
"You have ignored this sender.",
));
return if services.config.experiments.msc4406.is_enabled() {
Err(Error::BadRequest(
ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender(
event.sender().to_owned(),
)),
"You have ignored this sender.",
))
} else {
Err!(Request(NotFound("You have ignored the sender of this event.")))
};
}
Ok(false)
+2 -2
View File
@@ -12,7 +12,6 @@ pub(super) mod directory;
pub(super) mod filter;
pub(super) mod keys;
pub(super) mod media;
pub(super) mod media_legacy;
pub(super) mod membership;
pub(super) mod message;
pub(super) mod mutual_rooms;
@@ -24,6 +23,7 @@ pub(super) mod push;
pub(super) mod read_marker;
pub(super) mod redact;
pub(super) mod relations;
pub(super) mod rendezvous;
pub(super) mod report;
pub(super) mod room;
pub(super) mod search;
@@ -57,7 +57,6 @@ pub(super) use directory::*;
pub(super) use filter::*;
pub(super) use keys::*;
pub(super) use media::*;
pub(super) use media_legacy::*;
pub(super) use membership::*;
pub use membership::{leave_all_rooms, leave_room, remote_leave_room};
pub(super) use message::*;
@@ -71,6 +70,7 @@ pub(super) use push::*;
pub(super) use read_marker::*;
pub(super) use redact::*;
pub(super) use relations::*;
pub(super) use rendezvous::*;
pub(super) use report::*;
pub(super) use room::*;
pub(super) use search::*;
+3 -3
View File
@@ -13,8 +13,8 @@ use crate::Ruma;
#[tracing::instrument(skip_all, name = "mutual_rooms", level = "info")]
pub(crate) async fn get_mutual_rooms_unstable_route(
State(services): State<crate::State>,
body: Ruma<get_mutual_rooms::unstable::Request>,
) -> Result<get_mutual_rooms::unstable::Response> {
body: Ruma<get_mutual_rooms::msc2666::Request>,
) -> Result<get_mutual_rooms::msc2666::Response> {
let sender_user = body.identity.expect_sender_user()?;
if sender_user == body.user_id {
@@ -28,7 +28,7 @@ pub(crate) async fn get_mutual_rooms_unstable_route(
.collect()
.await;
Ok(get_mutual_rooms::unstable::Response::new(mutual_rooms))
Ok(get_mutual_rooms::msc2666::Response::new(mutual_rooms))
}
/// # `GET /_matrix/client/v1/mutual_rooms`
+54 -38
View File
@@ -1,14 +1,14 @@
use std::collections::BTreeMap;
use axum::extract::State;
use conduwuit::{Err, PduCount, Result, err};
use conduwuit::{Err, Result, err};
use ruma::{
MilliSecondsSinceUnixEpoch,
api::client::{read_marker::set_read_marker, receipt::create_receipt},
events::{
RoomAccountDataEventType,
fully_read::{FullyReadEvent, FullyReadEventContent},
receipt::{Receipt, ReceiptEvent, ReceiptEventContent, ReceiptType},
receipt::{Receipt, ReceiptEvent, ReceiptEventContent, ReceiptThread, ReceiptType},
},
};
@@ -27,6 +27,15 @@ pub(crate) async fn set_read_marker_route(
) -> Result<set_read_marker::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
if !services
.rooms
.state_cache
.is_joined(sender_user, &body.room_id)
.await
{
return Err!(Request(Forbidden("You are not in this room.")));
}
if let Some(event) = &body.fully_read {
let fully_read_event = FullyReadEvent::new(FullyReadEventContent::new(event.to_owned()));
@@ -92,13 +101,8 @@ pub(crate) async fn set_read_marker_route(
.timeline
.get_pdu_count(event)
.await
.map_err(|_| err!(Request(NotFound("Event not found."))))?;
let PduCount::Normal(count) = count else {
return Err!(Request(InvalidParam(
"Event is a backfilled PDU and cannot be marked as read."
)));
};
.map_err(|_| err!(Request(NotFound("Event not found."))))?
.into_unsigned();
services
.rooms
@@ -122,11 +126,26 @@ pub(crate) async fn create_receipt_route(
) -> Result<create_receipt::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
if !services
.rooms
.state_cache
.is_joined(sender_user, &body.room_id)
.await
{
return Err!(Request(Forbidden("You are not in this room.")));
}
services
.users
.update_device_last_seen(sender_user, body.identity.sender_device(), client_ip)
.await;
if body.receipt_type == create_receipt::v3::ReceiptType::FullyRead
&& body.thread != ReceiptThread::Unthreaded
{
return Err!(Request(InvalidParam("thread_id cannot be specified for m.fully_read")));
}
if matches!(
&body.receipt_type,
create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate
@@ -159,44 +178,41 @@ pub(crate) async fn create_receipt_route(
)
.await?;
},
| create_receipt::v3::ReceiptType::Read => {
let receipt_content = [(
body.event_id.clone(),
BTreeMap::from_iter([(
ReceiptType::Read,
| create_receipt::v3::ReceiptType::Read =>
if services.config.allow_local_read_receipts
&& !services.users.is_suspended(sender_user).await?
{
let mut receipt = Receipt::new(MilliSecondsSinceUnixEpoch::now());
receipt.thread = body.thread.clone();
let receipt_content = [(
body.event_id.clone(),
BTreeMap::from_iter([(
sender_user.to_owned(),
Receipt::new(MilliSecondsSinceUnixEpoch::now()),
ReceiptType::Read,
BTreeMap::from_iter([(sender_user.to_owned(), receipt)]),
)]),
)]),
)];
)];
services
.rooms
.read_receipt
.readreceipt_update(
sender_user,
&body.room_id,
ReceiptEvent::new(
body.room_id.clone(),
ReceiptEventContent::from_iter(receipt_content),
),
)
.await;
},
services
.rooms
.read_receipt
.readreceipt_update(
sender_user,
&body.room_id,
ReceiptEvent::new(
body.room_id.clone(),
ReceiptEventContent::from_iter(receipt_content),
),
)
.await;
},
| create_receipt::v3::ReceiptType::ReadPrivate => {
let count = services
.rooms
.timeline
.get_pdu_count(&body.event_id)
.await
.map_err(|_| err!(Request(NotFound("Event not found."))))?;
let PduCount::Normal(count) = count else {
return Err!(Request(InvalidParam(
"Event is a backfilled PDU and cannot be marked as read."
)));
};
.map_err(|_| err!(Request(NotFound("Event not found."))))?
.into_unsigned();
services
.rooms
+46 -38
View File
@@ -2,7 +2,7 @@ use axum::extract::State;
use conduwuit::{
Err, Result, at, debug_warn, err,
matrix::{Event, event::RelationTypeEqual, pdu::PduCount},
utils::{IterStream, ReadyExt, result::FlatOk, stream::WidebandExt},
utils::{IterStream, result::FlatOk, stream::WidebandExt},
};
use conduwuit_service::Services;
use futures::StreamExt;
@@ -98,6 +98,10 @@ pub(crate) async fn get_relating_events_route(
.await
}
// Spec (v1.10) recommends a depth of at least 3
const RECURSION_DEPTH: u8 = 3;
const LEVELS_BELOW: u8 = RECURSION_DEPTH - 1;
#[allow(clippy::too_many_arguments)]
async fn paginate_relations_with_filter(
services: &Services,
@@ -147,28 +151,49 @@ async fn paginate_relations_with_filter(
.unwrap_or(30)
.min(100);
// Spec (v1.10) recommends depth of at least 3
let depth: u8 = if recurse { 3 } else { 1 };
let max_depth = if recurse { LEVELS_BELOW } else { 0 };
let events: Vec<_> = services
// One more than the limit, to know whether there's another page
let mut events = services
.rooms
.pdu_metadata
.get_relations(sender_user, room_id, target, start, limit, depth, dir)
.await
.get_relations(
sender_user,
room_id,
target,
start,
limit.saturating_add(1),
max_depth,
dir,
|pdu| {
filter_event_type
.as_ref()
.is_none_or(|kind| kind == pdu.kind())
&& filter_rel_type
.as_ref()
.is_none_or(|rel_type| rel_type.relation_type_equal(pdu))
},
)
.await;
let past_to = to.and_then(|to| {
events
.iter()
.position(|(count, _)| !to.is_after(*count, dir))
});
if let Some(past_to) = past_to {
events.truncate(past_to);
}
let has_more = past_to.is_none() && events.len() > limit;
events.truncate(limit);
let next_batch =
has_more.then(|| events.last().map_or(start, |(count, _)| *count).to_string());
let chunk: Vec<_> = events
.into_iter()
.filter(|(_, pdu)| {
filter_event_type
.as_ref()
.is_none_or(|kind| kind == pdu.kind())
})
.filter(|(_, pdu)| {
filter_rel_type
.as_ref()
.is_none_or(|rel_type| rel_type.relation_type_equal(pdu))
})
.stream()
.ready_take_while(|(count, _)| Some(*count) != to)
.take(limit)
.wide_filter_map(|item| visibility_filter(services, sender_user, item))
.wide_filter_map(|item| ignored_filter(services, item, sender_user))
.then(async |mut pdu| {
@@ -182,32 +207,15 @@ async fn paginate_relations_with_filter(
}
pdu
})
.collect()
.await;
// Determine if there are more events to fetch
let has_more = events.len() >= limit;
let next_batch = if has_more {
match dir {
| Direction::Forward => events.last(),
| Direction::Backward => events.first(),
}
.map(|(count, _)| count.to_string())
} else {
None
};
let chunk: Vec<_> = events
.into_iter()
.map(at!(1))
.map(Event::into_format)
.collect();
.collect()
.await;
Ok(assign!(get_relating_events::v1::Response::new(chunk), {
next_batch,
prev_batch: from.map(Into::into),
recursion_depth: recurse.then_some(depth.into()),
recursion_depth: recurse.then_some(RECURSION_DEPTH.into()),
}))
}
+76
View File
@@ -0,0 +1,76 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use http::HeaderMap;
use ruma::api::client::rendezvous::{
create_rendezvous_session, delete_rendezvous_session, discover_rendezvous,
get_rendezvous_session, update_rendezvous_session,
};
use service::Services;
use crate::{Ruma, router::ClientIdentity};
/// `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>,
) -> Result<discover_rendezvous::msc4388::Response> {
Ok(discover_rendezvous::msc4388::Response::new(rendezvous_available(
&services,
body.identity.as_ref(),
)))
}
/// `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>,
) -> Result<create_rendezvous_session::msc4388::Response> {
if !rendezvous_available(&services, body.identity.as_ref()) {
return Err!(Request(Forbidden("You are not authorized to create a rendezvous session")));
}
services.rendezvous.create_session(body.data.clone())
}
/// `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>,
) -> Result<update_rendezvous_session::msc4388::Response> {
services.rendezvous.update_session(
&body.id,
body.txn_id.clone(),
body.sequence_token.clone(),
body.data.clone(),
)
}
/// `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> {
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."
)));
}
services.rendezvous.get_session(&body.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>,
) -> Result<delete_rendezvous_session::msc4388::Response> {
services.rendezvous.delete_session(&body.id)
}
fn rendezvous_available(services: &Services, identity: Option<&ClientIdentity>) -> bool {
!services.config.require_auth_for_rendezvous || identity.is_some()
}
+30 -12
View File
@@ -1,18 +1,21 @@
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
sync::atomic::{AtomicU64, Ordering::SeqCst},
};
use axum::extract::State;
use conduwuit::{
Err, Error, Result, debug, debug_info, err, info,
matrix::{StateKey, pdu::PartialPdu},
trace,
utils::to_canonical_object,
utils::{self, to_canonical_object},
warn,
};
use conduwuit_service::{Services, appservice::RegistrationInfo};
use futures::FutureExt;
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, Int, MilliSecondsSinceUnixEpoch, OwnedRoomAliasId,
OwnedUserId, RoomAliasId, RoomId,
OwnedUserId, RoomAliasId, RoomId, UInt,
api::{
client::room::{
self,
@@ -46,6 +49,8 @@ use serde_json::value::to_raw_value;
use crate::{Ruma, client::invite_helper};
static LAST_CREATE_TS: AtomicU64 = AtomicU64::new(0);
// We use this to keep around extra data in the `creation_content`
// while still parsing and validating keys that we care about.
#[derive(Deserialize, Default)]
@@ -72,7 +77,7 @@ struct FullCreationContent {
/// - Send events listed in initial state
/// - Send events implied by `name` and `topic`
/// - Send invite events
#[allow(clippy::large_stack_frames)]
#[allow(clippy::large_unopt_stack_frames)]
#[allow(clippy::cognitive_complexity)]
pub(crate) async fn create_room_route(
State(services): State<crate::State>,
@@ -116,7 +121,10 @@ pub(crate) async fn create_room_route(
// ID exactly matches this, and abort if it doesn't. Otherwise, we use it
// as the room ID itself.
let expect_room_id = {
let body_ref = body.json_body.as_ref().unwrap();
let body_ref = body
.json_body
.as_ref()
.ok_or_else(|| err!(Request(BadJson("Invalid JSON body"))))?;
if let Some(CanonicalJsonValue::String(room_id)) = body_ref
.get("fi.mau.room_id")
.or_else(|| body_ref.get("room_id"))
@@ -297,7 +305,10 @@ pub(crate) async fn create_room_route(
// Allow requesters to override the `origin_server_ts` to customize room ids
// from v12 onwards
let custom_origin_server_ts = {
let body_ref = body.json_body.as_ref().unwrap();
let body_ref = body
.json_body
.as_ref()
.ok_or_else(|| err!(Request(BadJson("Invalid JSON body"))))?;
body_ref
.get("origin_server_ts")
.or_else(|| body_ref.get("fi.mau.origin_server_ts"))
@@ -307,6 +318,17 @@ pub(crate) async fn create_room_route(
.map(MilliSecondsSinceUnixEpoch)
};
// v12+ room IDs are the create event's hash, so give each create event a
// unique timestamp to avoid collisions.
let create_timestamp = custom_origin_server_ts.or_else(|| {
room_id.is_none().then(|| {
let now = utils::millis_since_unix_epoch();
let next = |last: u64| now.max(last.saturating_add(1));
let prev = LAST_CREATE_TS.update(SeqCst, SeqCst, next);
MilliSecondsSinceUnixEpoch(UInt::new_saturating(next(prev)))
})
});
let mut create_event_content = to_canonical_object(create_event_content)
.expect("should be able to serialize create event content");
@@ -322,7 +344,7 @@ pub(crate) async fn create_room_route(
event_type: TimelineEventType::RoomCreate,
content: to_raw_value(&create_event_content)?,
state_key: Some(StateKey::new()),
timestamp: custom_origin_server_ts,
timestamp: create_timestamp,
..Default::default()
},
sender_user,
@@ -758,11 +780,7 @@ async fn room_alias_check(
if !info.aliases.is_match(full_room_alias.as_str()) {
return Err!(Request(Exclusive("Room alias is not in namespace.")));
}
} else if services
.appservice
.is_exclusive_alias(&full_room_alias)
.await
{
} else if services.appservice.is_exclusive_alias(&full_room_alias) {
return Err!(Request(Exclusive("Room alias reserved by appservice.",)));
}
+89 -5
View File
@@ -1,14 +1,30 @@
use axum::extract::State;
use conduwuit::{Err, Event, Result, debug_warn, err};
use ruma::api::client::room::get_room_event;
use axum::extract::{Query, State};
use conduwuit::{
Err, Error, Event, PduEvent, Result, config::experiments::ToggledExperiment, debug_warn, err,
};
use futures::TryFutureExt;
use http::StatusCode;
use ruma::{
UserId,
api::{client::room::get_room_event, error::ErrorKind},
};
use serde::Deserialize;
use serde_json::json;
use crate::{Ruma, client::is_ignored_pdu};
#[derive(Deserialize)]
pub(crate) struct Msc2815Params {
#[serde(rename = "fi.mau.msc2815.include_unredacted_content", default)]
include_unredacted_content: Option<bool>,
}
/// # `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}`
///
/// Gets a single event.
pub(crate) async fn get_room_event_route(
State(ref services): State<crate::State>,
Query(params): Query<Msc2815Params>,
ref body: Ruma<get_room_event::v3::Request>,
) -> Result<get_room_event::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
@@ -24,7 +40,7 @@ pub(crate) async fn get_room_event_route(
services.rooms.state_accessor.is_world_readable(room_id)
);
if !joined && !world_readable {
return Err!(Request(NotFound("Event {} not found.", event_id)));
return Err!(Request(NotFound("Event {event_id} not found.")));
}
services
@@ -32,10 +48,15 @@ pub(crate) async fn get_room_event_route(
.timeline
.get_remote_pdu(room_id, event_id)
.await
.map_err(|_| err!(Request(NotFound("Event {} not found.", event_id))))?
.map_err(|_| err!(Request(NotFound("Event {event_id} not found."))))?
},
| Err(e) => return Err(e),
};
if !event.room_id_or_hash().eq(room_id) {
// Return not found instead of invalid param to avoid revealing the
// existence of events the user might not be allowed to know about.
return Err!(Request(NotFound("Event {event_id} not found.")));
}
// NOTE: checked after fetching, as visibility of an unknown event cannot
// be determined (user_can_see_event returns true for those).
@@ -49,6 +70,13 @@ pub(crate) async fn get_room_event_route(
return Err!(Request(Forbidden("You don't have permission to view this event.")));
}
if services.config.experiments.msc2815.is_enabled()
&& params.include_unredacted_content.unwrap_or(false)
&& event.is_redacted()
{
unredact(services, sender_user, &mut event).await?;
}
if let Err(e) = services
.rooms
.pdu_metadata
@@ -67,3 +95,59 @@ pub(crate) async fn get_room_event_route(
Ok(get_room_event::v3::Response::new(event.into_format()))
}
async fn unredact(services: &crate::State, sender_user: &UserId, event: &mut PduEvent) -> Result {
if !services.users.is_admin(sender_user).await {
let power_levels = services
.rooms
.state_accessor
.get_room_power_levels(&event.room_id_or_hash())
.await;
if power_levels.for_user(sender_user) < power_levels.redact {
return Err!(Request(Forbidden(
"You don't have permission to view redacted content in this room."
)));
}
}
let content = services
.rooms
.timeline
.get_pdu_id(event.event_id())
.and_then(async |pdu_id| {
services
.rooms
.timeline
.get_unredacted_content(&pdu_id)
.await
})
.await;
let Ok(content) = content else {
// CustomErrorKind has private fields; only serde can build one.
let keep_ms = services
.config
.experiments
.msc2815
.expect("msc2815 config is disabled but unredact() attempted to access it anyway")
.unredacted_content_max_age_secs
.saturating_mul(1000);
let kind = serde_json::from_value::<ErrorKind>(json!({
"errcode": "FI.MAU.MSC2815_UNREDACTED_CONTENT_DELETED",
"fi.mau.msc2815.content_keep_ms": keep_ms,
}))
.expect("errcode is a valid custom error kind");
return Err(Error::Request(
kind,
"The unredacted content of this event is not available.".into(),
StatusCode::NOT_FOUND,
));
};
event.content = content;
Ok(())
}
+1 -2
View File
@@ -94,8 +94,7 @@ pub(crate) async fn room_initial_sync_route(
.first()
.map(at!(0))
.as_ref()
.map(ToString::to_string)
.unwrap_or_default();
.map_or_default(ToString::to_string);
let start = events.last().map(at!(0)).as_ref().map(ToString::to_string);
let chunk = events
+4 -1
View File
@@ -2,11 +2,14 @@ mod aliases;
mod create;
mod event;
mod initial_sync;
mod stripped_state;
mod summary;
mod timestamp_to_event;
mod upgrade;
pub(crate) use self::{
aliases::get_room_aliases_route, create::create_room_route, event::get_room_event_route,
initial_sync::room_initial_sync_route, summary::get_room_summary,
initial_sync::room_initial_sync_route, stripped_state::get_stripped_state_route,
summary::get_room_summary, timestamp_to_event::get_event_by_timestamp_route,
upgrade::upgrade_room_route,
};
+71
View File
@@ -0,0 +1,71 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use ruma::{
api::client::state::get_stripped_state, assign, events::ALLOWED_STRIPPED_STATE_EVENTS,
};
use service::rooms::summary::{Accessibility, RoomStrippedState};
use crate::{Ruma, router::ClientIdentity};
/// # `POST /_matrix/client/unstable/org.continuwuity.msc4560.stripped_state/{room_id_or_alias}` ([MSC4560])
///
/// Returns a room's stripped state.
///
/// [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560
#[tracing::instrument(skip_all, name = "stripped_state", level = "info")]
pub(crate) async fn get_stripped_state_route(
State(services): State<crate::State>,
body: Ruma<get_stripped_state::msc4560::Request>,
) -> Result<get_stripped_state::msc4560::Response> {
let user_id = body.identity.as_ref().and_then(ClientIdentity::sender_user);
if body.via.len() > get_stripped_state::msc4560::MAX_VIAS {
return Err!(Request(TooLarge("Too many vias, please be less indecisive.")));
}
if let Some(forbidden_type) = body
.state
.iter()
.find(|event_type| !ALLOWED_STRIPPED_STATE_EVENTS.contains(event_type))
{
return Err!(Request(InvalidParam(
"Event type {forbidden_type} may not be requested as stripped state."
)));
}
let (room_id, _) = services
.rooms
.alias
.resolve_with_servers(&body.room_id_or_alias, Some(body.via.clone()))
.await?;
if services.rooms.metadata.is_banned(&room_id).await {
return Err!(Request(Forbidden("This room is banned on this homeserver.")));
}
match services
.rooms
.summary
.get_stripped_state_for_user(
user_id,
&room_id,
&body.via,
&body.state,
body.num_joined_members,
)
.await
{
| Accessibility::Accessible((
via,
RoomStrippedState { state, num_joined_members, .. },
)) => Ok(
assign!(get_stripped_state::msc4560::Response::new(via), { state, num_joined_members }),
),
| Accessibility::Inaccessible => {
Err!(Request(Forbidden("You may not request this room's stripped state.")))
},
| Accessibility::NotFound => {
Err!(Request(NotFound("This room does not exist.")))
},
}
}
+4 -7
View File
@@ -13,7 +13,7 @@ pub(crate) async fn get_room_summary(
State(services): State<crate::State>,
body: Ruma<get_summary::v1::Request>,
) -> Result<get_summary::v1::Response> {
let (room_id, servers) = services
let (room_id, _) = services
.rooms
.alias
.resolve_with_servers(&body.room_id_or_alias, Some(body.via.clone()))
@@ -27,12 +27,9 @@ pub(crate) async fn get_room_summary(
.rooms
.summary
.get_room_summary_for_user(
body.identity
.as_ref()
.map(ClientIdentity::expect_sender_user)
.transpose()?,
body.identity.as_ref().and_then(ClientIdentity::sender_user),
&room_id,
&servers,
&body.via,
)
.await?;
@@ -42,7 +39,7 @@ pub(crate) async fn get_room_summary(
Err!(Request(Forbidden("You may not preview this room."), FORBIDDEN))
},
| Accessibility::NotFound => {
Err!(Request(Forbidden("This room does not exist."), FORBIDDEN))
Err!(Request(NotFound("This room does not exist.")))
},
}
}
+61
View File
@@ -0,0 +1,61 @@
use axum::extract::State;
use conduwuit::{Err, Event, Result, utils::stream::TryIgnore};
use futures::{StreamExt, pin_mut};
use ruma::api::client::room::get_event_by_timestamp;
use crate::Ruma;
const MAX_CANDIDATES: usize = 20;
/// # `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event`
///
/// Gets the ID of the event closest to the given timestamp, in the direction
/// specified by `dir`.
pub(crate) async fn get_event_by_timestamp_route(
State(ref services): State<crate::State>,
body: Ruma<get_event_by_timestamp::v1::Request>,
) -> Result<get_event_by_timestamp::v1::Response> {
let sender_user = body.identity.expect_sender_user()?;
let room_id = &body.room_id;
if !services
.rooms
.state_accessor
.user_can_see_state_events(sender_user, room_id)
.await
{
return Err!(Request(Forbidden("You don't have permission to view this room.")));
}
if !services.rooms.timeline.timestamp_index_ready().await {
return Err!(FeatureDisabled("timestamp_to_event"));
}
let candidates = services
.rooms
.timeline
.pdus_by_timestamp(room_id, body.ts, body.dir)
.ignore_err()
.take(MAX_CANDIDATES);
pin_mut!(candidates);
while let Some((_, pdu)) = candidates.next().await {
if services
.rooms
.state_accessor
.user_can_see_event(sender_user, room_id, pdu.event_id())
.await
{
return Ok(get_event_by_timestamp::v1::Response::new(
pdu.event_id().to_owned(),
pdu.origin_server_ts(),
));
}
}
Err!(Request(NotFound(
"Unable to find event from {} in direction {:?}",
body.ts.get(),
body.dir
)))
}
+1 -6
View File
@@ -95,12 +95,7 @@ pub(crate) async fn send_message_event_route(
PartialPdu {
event_type: body.event_type.clone().into(),
content,
sticky: services
.config
.allow_sticky_events
.then_some(body.sticky_duration_ms)
.flatten()
.map(sticky::object),
sticky: body.sticky_duration_ms.map(sticky::object),
unsigned: Some(unsigned),
timestamp: if body.identity.is_appservice()
|| services.admin.user_is_admin(sender_user).await
+84 -61
View File
@@ -15,7 +15,7 @@ use conduwuit::{
},
warn,
};
use conduwuit_service::Services;
use conduwuit_service::{Services, rooms::read_receipt::pack_receipts};
use futures::{
FutureExt, StreamExt, TryFutureExt,
future::{OptionFuture, join, join3, join4, try_join, try_join3},
@@ -64,7 +64,7 @@ pub(super) async fn load_joined_room(
services: &Services,
sync_context: SyncContext<'_>,
ref room_id: OwnedRoomId,
) -> Result<(JoinedRoom, DeviceListUpdates)> {
) -> Result<JoinedRoom> {
/*
Building a sync response involves many steps which all depend on each other.
To parallelize the process as much as possible, each step is divided into its own function,
@@ -80,7 +80,6 @@ pub(super) async fn load_joined_room(
sticky,
summary,
notification_counts,
device_list_updates,
},
) = try_join3(
build_account_data(services, sync_context, room_id),
@@ -117,7 +116,7 @@ pub(super) async fn load_joined_room(
unread_thread_notifications: BTreeMap::new(),
});
Ok((joined_room, device_list_updates))
Ok(joined_room)
}
/// Collect changes to the syncing user's account data events.
@@ -243,9 +242,14 @@ async fn build_ephemeral(
let (receipt_events, typing_event, private_read_event) =
join3(receipt_events, typing_event, private_read_event).await;
let mut edus = receipt_events;
let mut all_receipts = receipt_events;
all_receipts.extend(private_read_event);
let mut edus = Vec::new();
if !all_receipts.is_empty() {
edus.push(pack_receipts(all_receipts.into_iter()).cast());
}
edus.extend(typing_event);
edus.extend(private_read_event);
Ok(assign!(Ephemeral::new(), { events: edus }))
}
@@ -258,7 +262,6 @@ struct StateAndTimeline {
sticky: Sticky,
summary: Option<RoomSummary>,
notification_counts: Option<UnreadNotificationsCount>,
device_list_updates: DeviceListUpdates,
}
async fn build_sticky_events(
@@ -268,10 +271,6 @@ async fn build_sticky_events(
timeline: &TimelinePdus,
joined_since_last_sync: bool,
) -> Sticky {
if !services.config.allow_sticky_events {
return Sticky::new();
}
let SyncContext {
syncing_user,
last_sync_end_count,
@@ -376,24 +375,14 @@ async fn build_state_and_timeline(
debug_warn!("timeline for newly joined room is empty");
}
let (summary, device_list_updates) = try_join(
build_room_summary(
services,
sync_context,
room_id,
shortstatehashes,
&timeline,
&state_events,
joined_since_last_sync,
),
build_device_list_updates(
services,
sync_context,
room_id,
shortstatehashes,
&state_events,
joined_since_last_sync,
),
let summary = build_room_summary(
services,
sync_context,
room_id,
shortstatehashes,
&timeline,
&state_events,
joined_since_last_sync,
)
.await?;
@@ -429,7 +418,6 @@ async fn build_state_and_timeline(
sticky,
summary,
notification_counts,
device_list_updates,
})
}
@@ -799,8 +787,7 @@ async fn build_room_summary(
Ok(Some(assign!(RoomSummary::new(), {
heroes: heroes
.map(|heroes| heroes.into_iter().collect())
.unwrap_or_default(),
.map_or_default(|heroes| heroes.into_iter().collect()),
joined_member_count: Some(ruma_from_u64(joined_member_count)),
invited_member_count: Some(ruma_from_u64(invited_member_count)),
})))
@@ -853,35 +840,34 @@ async fn build_heroes(
.await
}
/// Collect updates to users' device lists for E2EE.
#[tracing::instrument(level = "debug", skip_all)]
async fn build_device_list_updates(
/// Collect updates to users' device lists for E2EE in a joined room.
#[tracing::instrument(level = "debug", skip_all, fields(%room_id))]
pub(super) async fn load_device_list_updates(
services: &Services,
SyncContext {
sync_context: SyncContext<'_>,
room_id: &RoomId,
) -> Result<DeviceListUpdates> {
let SyncContext {
syncing_user,
last_sync_end_count,
current_count,
..
}: SyncContext<'_>,
room_id: &RoomId,
ShortStateHashes { current_shortstatehash, .. }: ShortStateHashes,
state_events: &Vec<PduEvent>,
joined_since_last_sync: bool,
) -> Result<DeviceListUpdates> {
let is_encrypted_room = services
.rooms
.state_accessor
.state_get(current_shortstatehash, &StateEventType::RoomEncryption, "")
.is_ok();
} = sync_context;
let mut device_list_updates = DeviceListUpdates::new();
// initial syncs don't include device updates, and rooms which aren't
// encrypted don't affect them, so return early in either of those cases
if last_sync_end_count.is_none() || !(is_encrypted_room.await) {
return Ok(DeviceListUpdates::new());
if last_sync_end_count.is_none()
|| !services
.rooms
.state_accessor
.is_encrypted_room(room_id)
.await
{
return Ok(device_list_updates);
}
let mut device_list_updates = DeviceListUpdates::new();
// add users with changed keys to the `changed` list
services
.users
@@ -892,19 +878,56 @@ async fn build_device_list_updates(
})
.await;
// add users who now share encrypted rooms to `changed` and
// users who no longer share encrypted rooms to `left`
for state_event in state_events {
if state_event.kind == RoomMember {
let Some(content): Option<RoomMemberEventContent> = state_event.get_content().ok()
let shortstatehashes = fetch_shortstatehashes(services, sync_context, room_id).await?;
let ShortStateHashes {
current_shortstatehash,
last_sync_end_shortstatehash,
} = shortstatehashes;
if check_joined_since_last_sync(services, shortstatehashes, sync_context).await? {
// the syncing user now shares an encrypted room with every member
services
.rooms
.state_cache
.room_members(room_id)
.ready_for_each(|user_id| {
device_list_updates.changed.insert(user_id);
})
.await;
} else if let Some(last_sync_end_shortstatehash) = last_sync_end_shortstatehash
&& last_sync_end_shortstatehash != current_shortstatehash
{
// add users who now share encrypted rooms to `changed` and
// users who no longer share encrypted rooms to `left`
let state_added = services
.rooms
.state_accessor
.state_added((last_sync_end_shortstatehash, current_shortstatehash))
.await?;
for (shortstatekey, _) in state_added {
let Ok((StateEventType::RoomMember, state_key)) = services
.rooms
.short
.get_statekey_from_short(shortstatekey)
.await
else {
continue;
};
let Some(user_id): Option<OwnedUserId> = state_event
.state_key
.as_ref()
.and_then(|key| key.parse().ok())
let Ok(user_id) = OwnedUserId::try_from(state_key.as_str()) else {
continue;
};
let Ok(content): Result<RoomMemberEventContent> = services
.rooms
.state_accessor
.state_get_content(
current_shortstatehash,
&StateEventType::RoomMember,
user_id.as_str(),
)
.await
else {
continue;
};
@@ -920,7 +943,7 @@ async fn build_device_list_updates(
| Leave if !shares_encrypted_room => {
device_list_updates.left.insert(user_id);
},
| Join if joined_since_last_sync || shares_encrypted_room => {
| Join if shares_encrypted_room => {
device_list_updates.changed.insert(user_id);
},
| _ => (),
+118 -22
View File
@@ -3,7 +3,6 @@ mod left;
mod state;
use std::{
cmp::{self},
collections::{BTreeMap, HashMap, HashSet},
time::Duration,
};
@@ -21,7 +20,7 @@ use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture};
use ruma::{
DeviceId, OwnedUserId, RoomId, UserId,
api::client::{
filter::FilterDefinition,
filter::{self, FilterDefinition, RoomFilter},
sync::sync_events::{
self, DeviceLists,
v3::{
@@ -39,13 +38,17 @@ use service::{
account_data::AnyRawAccountDataEvent,
rooms::lazy_loading::{self, MemberSet, Options as _},
};
use wildmatch::WildMatch;
use super::{load_timeline, share_encrypted_room};
use crate::{
Ruma,
client::{
is_ignored_invite,
sync::v3::{joined::load_joined_room, left::load_left_room},
sync::v3::{
joined::{load_device_list_updates, load_joined_room},
left::load_left_room,
},
},
client_ip::ClientIp,
};
@@ -201,9 +204,14 @@ pub(crate) async fn sync_events_route(
.update_device_last_seen(sender_user, Some(sender_device), client_ip)
.await;
let mut wake_receiver = services.sync.subscribe_to_wake(sender_user).await;
let mut wake_receiver = services.sync.subscribe_to_wake(sender_user);
let response = build_sync_events(&services, &body).await?;
if body.body.full_state
let timeout_duration = body.body.timeout.unwrap_or_default();
// If the timeout is zero, request has full_state=true, or there's
// meaningful data to return, do so immediately.
if timeout_duration.is_zero()
|| body.body.full_state
|| !(response.rooms.is_empty()
&& response.presence.is_empty()
&& response.account_data.is_empty()
@@ -213,11 +221,15 @@ pub(crate) async fn sync_events_route(
return Ok(response);
}
// Hang a few seconds so requests are not spammed
// Stop hanging if new info arrives
let default = Duration::from_secs(30);
let duration = cmp::min(body.body.timeout.unwrap_or(default), default);
_ = tokio::time::timeout(duration, wake_receiver.changed()).await;
// Otherwise, wait for a wake signal to rebuild changes. Cap timeout at 30
// seconds (this isn't specced, but a reasonable cap since most clients have
// a 30-second polling interval).
let duration = timeout_duration.min(Duration::from_secs(30));
let mut shutdown_signal = services.server.signal.subscribe();
tokio::select! {
_ = tokio::time::timeout(duration, wake_receiver.changed()) => {},
_ = shutdown_signal.recv() => return Err!(Request(Unknown("Server is shutting down"), SERVICE_UNAVAILABLE)),
};
// Retry returning data
build_sync_events(&services, &body).await
@@ -271,34 +283,47 @@ pub(crate) async fn build_sync_events(
.rooms
.state_cache
.rooms_joined(syncing_user)
.ready_filter(|room_id| room_selected(&filter.room, room_id))
.broad_filter_map(|room_id| async {
let joined_room = load_joined_room(services, context, room_id.clone()).await;
match joined_room {
| Ok((room, updates)) => Some((room_id, room, updates)),
| Ok(room) => Some((room_id, room)),
| Err(err) => {
error!(?err, %room_id, "error loading joined room");
None
},
}
})
.ready_fold(
(BTreeMap::new(), DeviceListUpdates::new()),
|(mut joined_rooms, mut all_updates), (room_id, joined_room, updates)| {
all_updates.merge(updates);
.ready_fold(BTreeMap::new(), |mut joined_rooms, (room_id, joined_room)| {
if !joined_room.is_empty() {
joined_rooms.insert(room_id, joined_room);
}
if !joined_room.is_empty() {
joined_rooms.insert(room_id, joined_room);
}
joined_rooms
});
(joined_rooms, all_updates)
},
);
// a filtered out room still contributes its device list updates
let device_list_updates = services
.rooms
.state_cache
.rooms_joined(syncing_user)
.broad_filter_map(|room_id| async move {
load_device_list_updates(services, context, &room_id)
.await
.inspect_err(|err| error!(?err, %room_id, "error loading device list updates"))
.ok()
})
.ready_fold(DeviceListUpdates::new(), |mut all_updates, updates| {
all_updates.merge(updates);
all_updates
});
let left_rooms = services
.rooms
.state_cache
.rooms_left(syncing_user)
.ready_filter(|(room_id, _)| room_selected(&filter.room, room_id))
.broad_filter_map(|(room_id, leave_pdu)| async {
let left_room = load_left_room(services, context, room_id.clone(), leave_pdu).await;
@@ -317,6 +342,7 @@ pub(crate) async fn build_sync_events(
.rooms
.state_cache
.rooms_invited(syncing_user)
.ready_filter(|(room_id, _)| room_selected(&filter.room, room_id))
.wide_filter_map(async |(room_id, invite_state)| {
if is_ignored_invite(services, syncing_user, &room_id).await {
None
@@ -347,6 +373,7 @@ pub(crate) async fn build_sync_events(
.rooms
.state_cache
.rooms_knocked(syncing_user)
.ready_filter(|(room_id, _)| room_selected(&filter.room, room_id))
.fold_default(|mut knocked_rooms: BTreeMap<_, _>, (room_id, knock_state)| async move {
let knock_count = services
.rooms
@@ -376,6 +403,13 @@ pub(crate) async fn build_sync_events(
.account_data
.changes_since(None, syncing_user, last_sync_end_count, Some(current_count))
.ready_filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Global))
.ready_filter(|event| {
event
.get_field::<String>("type")
.ok()
.flatten()
.is_some_and(|event_type| type_selected(&filter.account_data, &event_type))
})
.collect();
let to_device_events = services
@@ -404,7 +438,8 @@ pub(crate) async fn build_sync_events(
.list_unused_fallback_key_types(syncing_user, syncing_device);
let (
(joined_rooms, mut device_list_updates),
joined_rooms,
mut device_list_updates,
left_rooms,
invited_rooms,
knocked_rooms,
@@ -417,6 +452,7 @@ pub(crate) async fn build_sync_events(
) = async {
futures::join!(
joined_rooms,
device_list_updates,
left_rooms,
invited_rooms,
knocked_rooms,
@@ -465,6 +501,24 @@ pub(crate) async fn build_sync_events(
Ok(response)
}
fn room_selected(filter: &RoomFilter, room_id: &RoomId) -> bool {
!filter.not_rooms.iter().any(|not_room| not_room == room_id)
&& filter
.rooms
.as_ref()
.is_none_or(|rooms| rooms.iter().any(|room| room == room_id))
}
fn type_selected(filter: &filter::Filter, event_type: &str) -> bool {
let matches = |pattern: &String| WildMatch::new(pattern).matches(event_type);
!filter.not_types.iter().any(matches)
&& filter
.types
.as_ref()
.is_none_or(|types| types.iter().any(matches))
}
#[tracing::instrument(name = "presence", level = "debug", skip_all)]
async fn process_presence_updates(
services: &Services,
@@ -528,3 +582,45 @@ async fn prepare_lazily_loaded_members(
lazily_loaded_members
}
#[cfg(test)]
mod tests {
use ruma::{owned_room_id, room_id};
use super::*;
#[test]
fn rooms_filter_selects_rooms() {
let room_id = room_id!("!a:example.com");
let mut filter = RoomFilter::default();
assert!(room_selected(&filter, room_id));
filter.rooms = Some(Vec::new());
assert!(!room_selected(&filter, room_id));
filter.rooms = Some(vec![room_id.to_owned()]);
assert!(room_selected(&filter, room_id));
filter.not_rooms = vec![owned_room_id!("!a:example.com")];
assert!(!room_selected(&filter, room_id));
}
#[test]
fn types_filter_selects_account_data() {
let mut filter = filter::Filter::default();
assert!(type_selected(&filter, "m.direct"));
filter.types = Some(Vec::new());
assert!(!type_selected(&filter, "m.direct"));
filter.types = Some(vec!["m.direct".to_owned()]);
assert!(type_selected(&filter, "m.direct"));
filter.types = Some(vec!["m.*".to_owned()]);
assert!(type_selected(&filter, "m.direct"));
assert!(!type_selected(&filter, "im.ponies.user_emotes"));
filter.not_types = vec!["m.direct".to_owned()];
assert!(!type_selected(&filter, "m.direct"));
}
}
+128 -130
View File
@@ -24,7 +24,7 @@ use conduwuit::{
use conduwuit_service::{
Services,
rooms::read_receipt::pack_receipts,
sync::{SnakeConnectionsKey, into_snake_key},
sync::{SnakeConnectionsKey, StickyDelivered, into_snake_key},
};
use futures::{
FutureExt, StreamExt, TryFutureExt,
@@ -34,7 +34,7 @@ use futures::{
use ruma::{
DeviceId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, UInt, UserId,
api::client::sync::sync_events::{
self, DeviceLists, UnreadNotificationsCount, v5::request::ExtensionRoomConfig,
self, DeviceLists, UnreadNotificationsCount, msc4186::request::ExtensionRoomConfig,
},
assign,
directory::RoomTypeFilter,
@@ -63,7 +63,7 @@ use crate::{
client_ip::ClientIp,
};
type SyncInfo<'a> = (&'a UserId, &'a DeviceId, u64, &'a sync_events::v5::Request);
type SyncInfo<'a> = (&'a UserId, &'a DeviceId, u64, &'a sync_events::msc4186::Request);
type TodoRooms = BTreeMap<OwnedRoomId, (BTreeSet<TypeStateKey>, usize, u64)>;
type KnownRooms = BTreeMap<String, BTreeMap<OwnedRoomId, u64>>;
type KnownRoomUpdates = BTreeMap<String, BTreeSet<OwnedRoomId>>;
@@ -86,8 +86,9 @@ fn num_live_events<'a>(
}
struct SyncCollection {
response: sync_events::v5::Response,
response: sync_events::msc4186::Response,
known_room_updates: KnownRoomUpdates,
sticky_delivered: StickyDelivered,
}
/// `POST /_matrix/client/unstable/org.matrix.simplified_msc3575/sync`
@@ -103,8 +104,8 @@ struct SyncCollection {
pub(crate) async fn sync_events_v5_route(
State(ref services): State<crate::State>,
ClientIp(client_ip): ClientIp, // NOTE: Required for updating device metadata
body: Ruma<sync_events::v5::Request>,
) -> Result<sync_events::v5::Response> {
body: Ruma<sync_events::msc4186::Request>,
) -> Result<sync_events::msc4186::Response> {
let sender_user = body.identity.expect_sender_user()?;
let sender_device = body.identity.expect_sender_device()?;
@@ -142,12 +143,12 @@ pub(crate) async fn sync_events_v5_route(
}
// Get sticky parameters from cache
let known_rooms =
let (known_rooms, sticky_delivered) =
services
.sync
.update_snake_sync_request_with_cache(&snake_key, globalsince, &mut body);
let mut wake_receiver = services.sync.subscribe_to_wake(sender_user).await;
let mut wake_receiver = services.sync.subscribe_to_wake(sender_user);
let mut collection = collect_sync_response(
services,
sender_user,
@@ -155,6 +156,7 @@ pub(crate) async fn sync_events_v5_route(
&body,
globalsince,
&known_rooms,
&sticky_delivered,
)
.await?;
@@ -173,6 +175,7 @@ pub(crate) async fn sync_events_v5_route(
&body,
globalsince,
&known_rooms,
&sticky_delivered,
)
.await?;
}
@@ -202,13 +205,13 @@ async fn collect_sync_response(
services: &Services,
sender_user: &UserId,
sender_device: &DeviceId,
body: &sync_events::v5::Request,
body: &sync_events::msc4186::Request,
globalsince: u64,
known_rooms: &KnownRooms,
sticky_delivered: &StickyDelivered,
) -> Result<SyncCollection> {
// Bounds every read below and becomes the `pos` returned to the client.
// Zero would be echoed back as a request for an initial sync.
let next_batch = services.globals.current_count()?.max(1);
let next_batch = services.globals.next_count()?;
let all_joined_rooms = services
.rooms
@@ -262,7 +265,6 @@ async fn collect_sync_response(
let pos = next_batch.to_string();
let mut todo_rooms: TodoRooms = BTreeMap::new();
let mut sticky_rooms = BTreeSet::new();
let sync_info: SyncInfo<'_> = (sender_user, sender_device, globalsince, body);
@@ -277,16 +279,16 @@ async fn collect_sync_response(
let (account_data, e2ee, to_device, receipts) =
try_join4(account_data, e2ee, to_device, receipts).await?;
let extensions = assign!(sync_events::v5::response::Extensions::default(), {
let extensions = assign!(sync_events::msc4186::response::Extensions::default(), {
account_data,
e2ee,
to_device,
receipts,
typing: sync_events::v5::response::Typing::default(),
sticky_events: sync_events::v5::response::StickyEvents::default(),
typing: sync_events::msc4186::response::Typing::default(),
sticky_events: sync_events::msc4186::response::StickyEvents::default(),
});
let mut response = assign!(sync_events::v5::Response::new(pos), {
let mut response = assign!(sync_events::msc4186::Response::new(pos), {
txn_id: body.txn_id.clone(),
lists: BTreeMap::new(),
rooms: BTreeMap::new(),
@@ -319,7 +321,6 @@ async fn collect_sync_response(
all_rooms,
&direct_rooms,
&mut todo_rooms,
&mut sticky_rooms,
known_rooms,
&mut response,
)
@@ -329,7 +330,6 @@ async fn collect_sync_response(
"subscriptions".to_owned(),
fetch_subscriptions(services, body, known_rooms, &allowed_rooms, &mut todo_rooms).await,
);
sticky_rooms.extend(body.room_subscriptions.keys().cloned());
let mut timeline_event_ids = BTreeSet::new();
response.rooms = process_rooms(
@@ -346,25 +346,31 @@ async fn collect_sync_response(
)
.await?;
response.extensions.sticky_events = collect_sticky_events(
let (sticky_events, sticky_delivered) = collect_sticky_events(
services,
sender_user,
body,
&sticky_rooms,
next_batch,
sticky_delivered,
&known_room_updates,
&joined_room_ids,
&todo_rooms,
&timeline_event_ids,
)
.await?;
.await;
response.extensions.sticky_events = sticky_events;
response.extensions.typing =
collect_typing_events(services, sender_user, body, &todo_rooms, &known_room_updates)
.await?;
Ok(SyncCollection { response, known_room_updates })
Ok(SyncCollection {
response,
known_room_updates,
sticky_delivered,
})
}
fn response_is_empty(response: &sync_events::v5::Response) -> bool {
fn response_is_empty(response: &sync_events::msc4186::Response) -> bool {
let no_account_data = response.extensions.account_data.global.is_empty()
&& response
.extensions
@@ -395,7 +401,7 @@ async fn commit_sync_collection(
services: &Services,
sender_user: &UserId,
sender_device: &DeviceId,
body: &sync_events::v5::Request,
body: &sync_events::msc4186::Request,
globalsince: u64,
snake_key: &SnakeConnectionsKey,
collection: &SyncCollection,
@@ -408,9 +414,10 @@ async fn commit_sync_collection(
.parse()
.expect("generated sync position"),
collection.known_room_updates.clone(),
collection.sticky_delivered.clone(),
);
if body.extensions.to_device.enabled.unwrap_or(false) {
if body.extensions.to_device.enabled {
services
.users
.remove_to_device_events(sender_user, sender_device, globalsince)
@@ -420,7 +427,7 @@ async fn commit_sync_collection(
async fn fetch_subscriptions(
services: &Services,
body: &sync_events::v5::Request,
body: &sync_events::msc4186::Request,
known_rooms: &KnownRooms,
allowed_rooms: &BTreeSet<OwnedRoomId>,
todo_rooms: &mut TodoRooms,
@@ -480,15 +487,14 @@ async fn fetch_subscriptions(
async fn handle_lists<'a, Rooms, AllRooms>(
services: &Services,
sender_user: &UserId,
body: &sync_events::v5::Request,
body: &sync_events::msc4186::Request,
all_invited_rooms: Rooms,
all_joined_rooms: Rooms,
all_rooms: AllRooms,
direct_rooms: &HashSet<OwnedRoomId>,
todo_rooms: &'a mut TodoRooms,
sticky_rooms: &mut BTreeSet<OwnedRoomId>,
known_rooms: &'a KnownRooms,
response: &'_ mut sync_events::v5::Response,
response: &'_ mut sync_events::msc4186::Response,
) -> KnownRoomUpdates
where
Rooms: Iterator<Item = &'a RoomId> + Clone + Send + 'a,
@@ -579,7 +585,6 @@ where
.await;
sort_rooms_by_activity(&mut active_rooms);
let active_rooms: Vec<_> = active_rooms.into_iter().map(at!(0)).collect();
sticky_rooms.extend(active_rooms.iter().map(|room_id| (*room_id).to_owned()));
let mut new_known_rooms: BTreeSet<OwnedRoomId> = BTreeSet::new();
@@ -631,7 +636,7 @@ where
}
response.lists.insert(
list_id.clone(),
assign!(sync_events::v5::response::List::default(), {
assign!(sync_events::msc4186::response::List::default(), {
count: ruma_from_usize(active_rooms.len()),
}),
);
@@ -749,10 +754,10 @@ async fn process_rooms<'a, Rooms>(
all_invited_rooms: Rooms,
all_knocked_rooms: Rooms,
todo_rooms: &TodoRooms,
response: &mut sync_events::v5::Response,
body: &sync_events::v5::Request,
response: &mut sync_events::msc4186::Response,
body: &sync_events::msc4186::Request,
timeline_event_ids: &mut BTreeSet<OwnedEventId>,
) -> Result<BTreeMap<OwnedRoomId, sync_events::v5::response::Room>>
) -> Result<BTreeMap<OwnedRoomId, sync_events::msc4186::response::Room>>
where
Rooms: Iterator<Item = &'a RoomId> + Clone + Send + 'a,
{
@@ -787,7 +792,7 @@ where
rooms.insert(
room_id.clone(),
assign!(sync_events::v5::response::Room::new(), {
assign!(sync_events::msc4186::response::Room::new(), {
initial: Some(roomsince == &0),
invite_state,
limited: true,
@@ -821,7 +826,7 @@ where
rooms.insert(
room_id.clone(),
assign!(sync_events::v5::response::Room::new(), {
assign!(sync_events::msc4186::response::Room::new(), {
initial: Some(roomsince == &0),
invite_state: Some(knock_state),
limited: true,
@@ -988,7 +993,7 @@ where
.state_accessor
.get_member(room_id, &user_id)
.map_ok(|member_event| {
assign!(sync_events::v5::response::Hero::new(user_id.clone()), {
assign!(sync_events::msc4186::response::Hero::new(user_id.clone()), {
name: member_event.displayname,
avatar: member_event.avatar_url,
})
@@ -1032,7 +1037,7 @@ where
rooms.insert(
room_id.clone(),
assign!(sync_events::v5::response::Room::new(), {
assign!(sync_events::msc4186::response::Room::new(), {
name: services
.rooms
.state_accessor
@@ -1103,64 +1108,61 @@ where
Ok(rooms)
}
#[expect(clippy::too_many_arguments)]
async fn collect_sticky_events(
services: &Services,
sender_user: &UserId,
body: &sync_events::v5::Request,
sticky_rooms: &BTreeSet<OwnedRoomId>,
body: &sync_events::msc4186::Request,
next_batch: u64,
sticky_delivered: &StickyDelivered,
known_room_updates: &KnownRoomUpdates,
joined_room_ids: &BTreeSet<OwnedRoomId>,
todo_rooms: &TodoRooms,
timeline_event_ids: &BTreeSet<OwnedEventId>,
) -> Result<sync_events::v5::response::StickyEvents> {
if !services.config.allow_sticky_events
|| !body.extensions.sticky_events.enabled.unwrap_or(false)
{
return Ok(sync_events::v5::response::StickyEvents::default());
) -> (sync_events::msc4186::response::StickyEvents, StickyDelivered) {
let mut response = sync_events::msc4186::response::StickyEvents::default();
let mut delivered = StickyDelivered::new();
let sticky_events = &body.extensions.sticky_events;
if !sticky_events.enabled.unwrap_or(false) {
return (response, delivered);
}
let since = body
.extensions
.sticky_events
.since
.as_deref()
.and_then(|token| token.parse::<u64>().ok())
.unwrap_or(0);
let limit = body
.extensions
.sticky_events
let scope = extension_scope(
sticky_events.lists.as_deref(),
sticky_events.rooms.as_deref(),
body.lists.keys().map(String::as_str),
known_room_updates,
);
let limit = sticky_events
.limit
.map_or(DEFAULT_STICKY_LIMIT, usize_from_ruma)
.clamp(1, DEFAULT_STICKY_LIMIT);
let now = u64::from(MilliSecondsSinceUnixEpoch::now().get());
let oldest_sticky_ts = now.saturating_sub(sticky::MAX_DURATION_MS);
let mut backlog = Vec::new();
let mut stream = Vec::new();
for room_id in sticky_rooms
.iter()
.filter(|room_id| joined_room_ids.contains(*room_id))
{
// a room the client has not seen before needs its whole backlog, which
// a single stream position cannot express
let initial = todo_rooms
.get(room_id)
.is_some_and(|&(_, _, roomsince)| roomsince == 0);
for room_id in scope.intersection(joined_room_ids) {
let since = sticky_delivered.get(room_id).copied();
let mut pending = Vec::new();
let pdus = services.rooms.timeline.pdus_rev(room_id, None).ignore_err();
pin_mut!(pdus);
while let Some((count, pdu)) = pdus.next().await {
// nothing older than this can still be sticky, and on the stream we
// have already delivered everything up to `since`
if u64::from(pdu.origin_server_ts) < oldest_sticky_ts
|| (!initial && count <= PduCount::Normal(since))
{
break;
}
let PduCount::Normal(count) = count else {
continue;
};
if count > next_batch {
continue;
}
// Nothing older than this can still be sticky, and everything up to
// `since` has already been delivered
if u64::from(pdu.origin_server_ts) < oldest_sticky_ts
|| since.is_some_and(|since| count <= since)
{
break;
}
let is_sticky = pdu
.sticky
.as_deref()
@@ -1177,38 +1179,26 @@ async fn collect_sticky_events(
continue;
}
if count > since {
stream.push((count, room_id.clone(), pdu));
} else {
backlog.push((room_id.clone(), pdu));
}
pending.push((count, pdu));
}
}
stream.sort_by_key(|(count, ..)| *count);
let mut response = sync_events::v5::response::StickyEvents::default();
pending.reverse();
let truncated = pending.len() > limit;
let mut last_count = next_batch;
for (count, pdu) in pending.into_iter().take(limit) {
push_sticky_event(services, &mut response, sender_user, room_id.clone(), pdu).await;
last_count = count;
}
// MSC4480 lets us ignore the limit for a newly visible room's backlog
for (room_id, pdu) in backlog {
push_sticky_event(services, &mut response, sender_user, room_id, pdu).await;
delivered.insert(room_id.clone(), if truncated { last_count } else { next_batch });
}
let mut next_batch = None;
for (count, room_id, pdu) in stream.into_iter().take(limit) {
push_sticky_event(services, &mut response, sender_user, room_id, pdu).await;
next_batch = Some(count);
}
if !response.rooms.is_empty() {
response.next_batch = Some(next_batch.unwrap_or(since).to_string());
}
Ok(response)
(response, delivered)
}
async fn push_sticky_event(
services: &Services,
response: &mut sync_events::v5::response::StickyEvents,
response: &mut sync_events::msc4186::response::StickyEvents,
sender_user: &UserId,
room_id: OwnedRoomId,
mut pdu: PduEvent,
@@ -1275,12 +1265,12 @@ async fn collect_required_state(
async fn collect_typing_events(
services: &Services,
sender_user: &UserId,
body: &sync_events::v5::Request,
body: &sync_events::msc4186::Request,
todo_rooms: &TodoRooms,
known_room_updates: &KnownRoomUpdates,
) -> Result<sync_events::v5::response::Typing> {
) -> Result<sync_events::msc4186::response::Typing> {
if !body.extensions.typing.enabled.unwrap_or(false) {
return Ok(sync_events::v5::response::Typing::default());
return Ok(sync_events::msc4186::response::Typing::default());
}
let typing = &body.extensions.typing;
let scope = extension_scope(
@@ -1290,10 +1280,10 @@ async fn collect_typing_events(
known_room_updates,
);
if scope.is_empty() {
return Ok(sync_events::v5::response::Typing::default());
return Ok(sync_events::msc4186::response::Typing::default());
}
let mut typing_response = sync_events::v5::response::Typing::default();
let mut typing_response = sync_events::msc4186::response::Typing::default();
for (room_id, (_, _, roomsince)) in todo_rooms {
if !scope.contains(room_id) {
continue;
@@ -1373,12 +1363,17 @@ fn extension_scope<'a>(
async fn collect_account_data(
services: &Services,
(sender_user, _, globalsince, body): (&UserId, &DeviceId, u64, &sync_events::v5::Request),
) -> sync_events::v5::response::AccountData {
let mut account_data = sync_events::v5::response::AccountData::default();
(sender_user, _, globalsince, body): (
&UserId,
&DeviceId,
u64,
&sync_events::msc4186::Request,
),
) -> sync_events::msc4186::response::AccountData {
let mut account_data = sync_events::msc4186::response::AccountData::default();
if !body.extensions.account_data.enabled.unwrap_or(false) {
return sync_events::v5::response::AccountData::default();
return sync_events::msc4186::response::AccountData::default();
}
account_data.global = services
@@ -1413,15 +1408,15 @@ async fn collect_e2ee<'a, Rooms>(
&UserId,
&DeviceId,
u64,
&sync_events::v5::Request,
&sync_events::msc4186::Request,
),
all_joined_rooms: Rooms,
) -> Result<sync_events::v5::response::E2EE>
) -> Result<sync_events::msc4186::response::E2EE>
where
Rooms: Iterator<Item = &'a RoomId> + Send + 'a,
{
if !body.extensions.e2ee.enabled.unwrap_or(false) {
return Ok(sync_events::v5::response::E2EE::default());
if !body.extensions.e2ee.enabled {
return Ok(sync_events::msc4186::response::E2EE::default());
}
let mut left_encrypted_users = HashSet::new(); // Users that have left any encrypted rooms the sender was in
let mut device_list_changes = HashSet::new();
@@ -1608,7 +1603,7 @@ where
}
}
Ok(assign!(sync_events::v5::response::E2EE::default(), {
Ok(assign!(sync_events::msc4186::response::E2EE::default(), {
device_unused_fallback_key_types: None,
device_one_time_keys_count: services
@@ -1627,12 +1622,12 @@ async fn collect_to_device(
services: &Services,
(sender_user, sender_device, globalsince, body): SyncInfo<'_>,
next_batch: u64,
) -> Option<sync_events::v5::response::ToDevice> {
if !body.extensions.to_device.enabled.unwrap_or(false) {
) -> Option<sync_events::msc4186::response::ToDevice> {
if !body.extensions.to_device.enabled {
return None;
}
Some(assign!(sync_events::v5::response::ToDevice::default(), {
Some(assign!(sync_events::msc4186::response::ToDevice::default(), {
next_batch: next_batch.to_string(),
events: services
.users
@@ -1643,9 +1638,9 @@ async fn collect_to_device(
}))
}
async fn collect_receipts(_services: &Services) -> sync_events::v5::response::Receipts {
async fn collect_receipts(_services: &Services) -> sync_events::msc4186::response::Receipts {
// TODO: get explicitly requested read receipts
sync_events::v5::response::Receipts::default()
sync_events::msc4186::response::Receipts::default()
}
#[cfg(test)]
@@ -1658,23 +1653,25 @@ mod tests {
fn custom_room_type() -> RoomTypeFilter { RoomTypeFilter::from(Some("com.example")) }
fn response() -> sync_events::v5::Response { sync_events::v5::Response::new("1".to_owned()) }
fn response() -> sync_events::msc4186::Response {
sync_events::msc4186::Response::new("1".to_owned())
}
fn typing_scope_request() -> sync_events::v5::Request {
let mut request = sync_events::v5::Request::new();
fn typing_scope_request() -> sync_events::msc4186::Request {
let mut request = sync_events::msc4186::Request::new();
request
.lists
.insert("first".to_owned(), sync_events::v5::request::List::default());
.insert("first".to_owned(), sync_events::msc4186::request::List::default());
request
.lists
.insert("second".to_owned(), sync_events::v5::request::List::default());
.insert("second".to_owned(), sync_events::msc4186::request::List::default());
request.room_subscriptions.insert(
owned_room_id!("!subscription-a:example.com"),
sync_events::v5::request::RoomSubscription::default(),
sync_events::msc4186::request::RoomSubscription::default(),
);
request.room_subscriptions.insert(
owned_room_id!("!subscription-b:example.com"),
sync_events::v5::request::RoomSubscription::default(),
sync_events::msc4186::request::RoomSubscription::default(),
);
request
}
@@ -1768,9 +1765,10 @@ mod tests {
#[test]
fn a_room_with_no_events_is_still_empty() {
let mut response = response();
response
.rooms
.insert(owned_room_id!("!a:example.com"), sync_events::v5::response::Room::default());
response.rooms.insert(
owned_room_id!("!a:example.com"),
sync_events::msc4186::response::Room::default(),
);
assert!(response_is_empty(&response));
}
@@ -1781,7 +1779,7 @@ mod tests {
let mut response = response();
response
.rooms
.insert(room_id.to_owned(), sync_events::v5::response::Room::default());
.insert(room_id.to_owned(), sync_events::msc4186::response::Room::default());
response
.extensions
.receipts
@@ -1846,7 +1844,7 @@ mod tests {
#[test]
fn to_device_without_events_is_empty() {
let mut response = response();
response.extensions.to_device = Some(sync_events::v5::response::ToDevice::default());
response.extensions.to_device = Some(sync_events::msc4186::response::ToDevice::default());
assert!(response_is_empty(&response));
}
+2 -7
View File
@@ -27,12 +27,7 @@ pub(crate) async fn get_supported_versions_route(
State(services): State<crate::State>,
_body: Ruma<get_supported_versions::Request>,
) -> Result<get_supported_versions::Response> {
let mut unstable_features = unstable_features();
if services.config.allow_sticky_events {
// sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354)
unstable_features.insert("org.matrix.msc4354".to_owned(), true);
}
let unstable_features = unstable_features(&services.config.experiments);
Ok(assign!(get_supported_versions::Response::new(versions()), {
unstable_features
@@ -64,7 +59,7 @@ pub(crate) async fn continuwuity_local_user_count(
.stream_local_users()
.filter_map(async |user_id| {
if !services.users.status(&user_id).await.is_active()
|| services.appservice.is_exclusive_user_id(&user_id).await
|| services.appservice.is_exclusive_user_id(&user_id)
{
None
} else {
+1 -3
View File
@@ -5,9 +5,7 @@ use conduwuit::{
};
use futures::{FutureExt, StreamExt, pin_mut};
use ruma::{
api::client::user_directory::search_users::{self},
assign,
events::room::join_rules::JoinRule,
api::client::user_directory::search_users, assign, events::room::join_rules::JoinRule,
};
use crate::Ruma;
+3 -3
View File
@@ -43,9 +43,9 @@ pub(crate) async fn well_known_client(
/// homeserver, implementing MSC4143.
pub(crate) async fn get_rtc_transports(
State(services): State<crate::State>,
_body: Ruma<ruma::api::client::rtc::transports::v1::Request>,
) -> Result<ruma::api::client::rtc::transports::v1::Response> {
Ok(ruma::api::client::rtc::transports::v1::Response::new(
_body: Ruma<ruma::api::client::rtc::transports::msc4143::Request>,
) -> Result<ruma::api::client::rtc::transports::msc4143::Response> {
Ok(ruma::api::client::rtc::transports::msc4143::Response::new(
services.config.matrix_rtc.foci.clone(),
))
}
-3
View File
@@ -16,6 +16,3 @@ pub mod client_ip;
pub mod admin;
pub(crate) use self::router::{Ruma, RumaResponse, State};
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
+31 -45
View File
@@ -8,9 +8,9 @@ use std::str::FromStr;
use axum::{
Router,
response::{IntoResponse, Redirect},
routing::{any, get, post},
routing::{any, get},
};
use conduwuit::err;
use conduwuit::{config::experiments::ToggledExperiment, err};
pub(super) use conduwuit_service::state::State;
use http::{Uri, uri};
@@ -52,6 +52,7 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::set_pushrule_actions_route)
.ruma_route(&client::delete_pushrule_route)
.ruma_route(&client::get_room_event_route)
.ruma_route(&client::get_event_by_timestamp_route)
.ruma_route(&client::get_room_aliases_route)
.ruma_route(&client::get_filter_route)
.ruma_route(&client::create_filter_route)
@@ -162,10 +163,6 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::update_device_route)
.ruma_route(&client::delete_device_route)
.ruma_route(&client::delete_devices_route)
.ruma_route(&client::put_dehydrated_device_route)
.ruma_route(&client::delete_dehydrated_device_route)
.ruma_route(&client::get_dehydrated_device_route)
.ruma_route(&client::get_dehydrated_events_route)
.ruma_route(&client::get_tags_route)
.ruma_route(&client::update_tag_route)
.ruma_route(&client::delete_tag_route)
@@ -193,11 +190,26 @@ 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)
.ruma_route(&client::get_authorization_server_metadata_route)
.merge(client::oauth::router(state))
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
.ruma_route(&admin::rooms::ban::ban_room)
.ruma_route(&admin::rooms::list::list_rooms);
if config.experiments.msc3814.is_enabled() {
router = router
.ruma_route(&client::put_dehydrated_device_route)
.ruma_route(&client::delete_dehydrated_device_route)
.ruma_route(&client::get_dehydrated_device_route)
.ruma_route(&client::get_dehydrated_events_route);
}
if config.experiments.msc4560.is_enabled() {
router = router.ruma_route(&client::get_stripped_state_route);
}
if config.allow_prometheus_metrics {
router = router.route("/_continuwuity/metrics", get(client::continuwuity_metrics));
@@ -236,6 +248,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&server::get_content_route)
.ruma_route(&server::get_content_thumbnail_route)
.route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count));
if config.experiments.msc4560.is_enabled() {
router = router.ruma_route(&server::get_stripped_state_route);
}
} else {
router = router
.route("/_matrix/federation/{*path}", any(federation_disabled))
@@ -248,45 +263,16 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
// and other functionality will continue to work
router = router.ruma_route(&server::get_openid_userinfo_route);
if config.allow_legacy_media {
router = router
.ruma_route(&client::get_media_config_legacy_route)
.ruma_route(&client::get_media_preview_legacy_route)
.ruma_route(&client::get_content_legacy_route)
.ruma_route(&client::get_content_as_filename_legacy_route)
.ruma_route(&client::get_content_thumbnail_legacy_route)
.route("/_matrix/media/v1/config", get(client::get_media_config_legacy_legacy_route))
.route("/_matrix/media/v1/upload", post(client::create_content_legacy_route))
.route(
"/_matrix/media/v1/preview_url",
get(client::get_media_preview_legacy_legacy_route),
)
.route(
"/_matrix/media/v1/download/{server_name}/{media_id}",
get(client::get_content_legacy_legacy_route),
)
.route(
"/_matrix/media/v1/download/{server_name}/{media_id}/{file_name}",
get(client::get_content_as_filename_legacy_legacy_route),
)
.route(
"/_matrix/media/v1/thumbnail/{server_name}/{media_id}",
get(client::get_content_thumbnail_legacy_legacy_route),
);
} else {
router = router
.route("/_matrix/media/v1/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/v3/config", any(legacy_media_disabled))
.route("/_matrix/media/v3/download/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/v3/thumbnail/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/v3/preview_url", any(redirect_legacy_preview))
.route("/_matrix/media/r0/config", any(legacy_media_disabled))
.route("/_matrix/media/r0/download/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/r0/thumbnail/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/r0/preview_url", any(redirect_legacy_preview));
}
router
.route("/_matrix/media/v1/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/v3/config", any(legacy_media_disabled))
.route("/_matrix/media/v3/download/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/v3/thumbnail/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/v3/preview_url", any(redirect_legacy_preview))
.route("/_matrix/media/r0/config", any(legacy_media_disabled))
.route("/_matrix/media/r0/download/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/r0/thumbnail/{*path}", any(legacy_media_disabled))
.route("/_matrix/media/r0/preview_url", any(redirect_legacy_preview))
}
async fn redirect_legacy_preview(uri: Uri) -> impl IntoResponse {
@@ -307,7 +293,7 @@ async fn redirect_legacy_preview(uri: Uri) -> impl IntoResponse {
}
async fn legacy_media_disabled() -> impl IntoResponse {
err!(Request(Forbidden("Unauthenticated media is disabled.")))
err!(Request(NotFound("Unauthenticated media is disabled.")))
}
async fn federation_disabled() -> impl IntoResponse {
+13 -4
View File
@@ -1,18 +1,21 @@
use std::ops::Deref;
use std::{
net::{IpAddr, Ipv4Addr},
ops::Deref,
};
use axum::{
RequestExt, RequestPartsExt,
body::Body,
extract::{FromRequest, Path, Query},
};
use conduwuit::{Error, Result, err};
use conduwuit::{Error, Result, err, error};
use ruma::{
CanonicalJsonObject,
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
};
use serde::Deserialize;
use crate::{State, router::auth::CheckAuth};
use crate::{State, client_ip::ClientIp, router::auth::CheckAuth};
/// Query parameters needed to authenticate requests
#[derive(Deserialize)]
@@ -87,6 +90,11 @@ where
let Path(path): Path<Vec<String>> = parts.extract().await?;
let borrowed_path: Vec<_> = path.iter().map(String::as_str).collect();
let Query(auth_query): Query<AuthQueryParams> = parts.extract().await?;
let ClientIp(ip) = parts
.extract_with_state(services)
.await
.inspect_err(|err| error!("Failed to extract client IP: {err:?}"))
.unwrap_or(ClientIp(IpAddr::V4(Ipv4Addr::UNSPECIFIED)));
// Assemble a new request from the read body and parts
let request = hyper::Request::from_parts(parts, body.as_ref());
@@ -102,7 +110,8 @@ where
})?;
let identity =
R::Authentication::check::<R>(services, &request, authentication, auth_query).await?;
R::Authentication::check::<R>(services, &request, ip, authentication, auth_query)
.await?;
// Deserialize the body
let body = R::try_from_http_request(request, &borrowed_path)
+53 -16
View File
@@ -1,10 +1,13 @@
use std::{
any::{Any, TypeId},
collections::BTreeSet,
net::IpAddr,
};
use conduwuit::{
Err, Error, Result, err,
Err, Error, Result,
config::experiments::ToggledExperiment,
err,
utils::{IterStream, millis_since_unix_epoch},
};
use http::StatusCode;
@@ -18,7 +21,10 @@ use ruma::{
AuthScheme, NoAccessToken, NoAuthentication,
},
client,
error::{ErrorKind, InsufficientUserAuthenticationErrorData, UnknownTokenErrorData},
error::{
ErrorKind, InsufficientUserAuthenticationErrorData, LimitExceededErrorData,
UnknownTokenErrorData,
},
federation::authentication::ServerSignatures,
},
assign,
@@ -90,6 +96,7 @@ pub(crate) trait CheckAuth: AuthScheme {
fn check<R: IncomingRequest<Authentication = Self> + Any>(
services: &Services,
incoming_request: &hyper::Request<&[u8]>,
request_ip: IpAddr,
authentication: Self::Output,
query: AuthQueryParams,
) -> impl Future<Output = Result<Self::Identity>> + Send;
@@ -101,6 +108,7 @@ impl CheckAuth for ServerSignatures {
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
services: &Services,
incoming_request: &hyper::Request<&[u8]>,
_request_ip: IpAddr,
authentication: Self::Output,
_query: AuthQueryParams,
) -> Result<Self::Identity> {
@@ -161,6 +169,7 @@ impl CheckAuth for AccessToken {
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
services: &Services,
_incoming_request: &hyper::Request<&[u8]>,
_request_ip: IpAddr,
authentication: Self::Output,
query: AuthQueryParams,
) -> Result<Self::Identity> {
@@ -181,6 +190,7 @@ impl CheckAuth for AccessTokenOptional {
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
services: &Services,
_incoming_request: &hyper::Request<&[u8]>,
request_ip: IpAddr,
authentication: Self::Output,
query: AuthQueryParams,
) -> Result<Self::Identity> {
@@ -195,6 +205,10 @@ impl CheckAuth for AccessTokenOptional {
.await
.map(Some)
} else {
if R::RATE_LIMITED {
check_unauthenticated_request_ratelimiting(services, request_ip)?;
}
Ok(None)
}
}
@@ -206,6 +220,7 @@ impl CheckAuth for AppserviceToken {
async fn check<R: IncomingRequest + Any>(
services: &Services,
_incoming_request: &hyper::Request<&[u8]>,
_request_ip: IpAddr,
authentication: Self::Output,
_query: AuthQueryParams,
) -> Result<Self::Identity> {
@@ -219,6 +234,7 @@ impl CheckAuth for AppserviceTokenOptional {
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
services: &Services,
_incoming_request: &hyper::Request<&[u8]>,
_request_ip: IpAddr,
authentication: Self::Output,
_query: AuthQueryParams,
) -> Result<Self::Identity> {
@@ -238,6 +254,7 @@ impl CheckAuth for NoAuthentication {
fn check<R: IncomingRequest<Authentication = Self> + Any>(
_services: &Services,
_incoming_request: &hyper::Request<&[u8]>,
_request_ip: IpAddr,
_authentication: Self::Output,
_query: AuthQueryParams,
) -> impl Future<Output = Result<Self::Identity>> + Send {
@@ -251,6 +268,7 @@ impl CheckAuth for NoAccessToken {
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
services: &Services,
incoming_request: &hyper::Request<&[u8]>,
request_ip: IpAddr,
_authentication: Self::Output,
query: AuthQueryParams,
) -> Result<Self::Identity> {
@@ -267,6 +285,10 @@ impl CheckAuth for NoAccessToken {
.await
.map(Some)
} else {
if R::RATE_LIMITED {
check_unauthenticated_request_ratelimiting(services, request_ip)?;
}
Ok(None)
}
}
@@ -318,17 +340,19 @@ async fn check_access_token(
.map(Box::new);
// Make sure the user has the right scopes to use the route
let user_scopes = if let Some(session_info) = &session_info {
let mut user_scopes = if let Some(session_info) = &session_info {
session_info.scopes()
} else {
let mut scopes = BTreeSet::from_iter([OAuthClientScope::ApiFullAccess]);
if services.admin.user_is_admin(&sender_user).await {
scopes.insert(OAuthClientScope::ServerAdministration);
}
scopes
BTreeSet::from_iter([OAuthClientScope::ApiFullAccess])
};
if (!services.config.experiments.msc4484.is_enabled() || session_info.is_none())
&& services.admin.user_is_admin(&sender_user).await
{
// This is required to make sure admin APIs still work when msc4484
// is disabled.
// https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2533#issuecomment-40042
user_scopes.insert(OAuthClientScope::ServerAdministration);
}
if !required_scopes
.iter()
@@ -346,7 +370,7 @@ async fn check_access_token(
}
Ok(ClientIdentity::User { sender_user, sender_device })
} else if let Ok(appservice_info) = services.appservice.find_from_token(token).await {
} else if let Ok(appservice_info) = services.appservice.find_from_token(token) {
let Ok(sender_user) = query.user_id.clone().map_or_else(
|| {
UserId::parse_with_server_name(
@@ -379,10 +403,7 @@ async fn check_access_token(
.await
.is_err()
{
return Err!(Request(Forbidden(
"Device does not exist for user or appservice cannot masquerade as this \
device."
)));
return Err!(Request(UnknownDevice("Device does not exist for this user.")));
}
Some(device_id.to_owned())
@@ -405,9 +426,25 @@ async fn check_access_token(
}
async fn check_appservice_token(services: &Services, token: &str) -> Result<RegistrationInfo> {
let Ok(appservice_info) = services.appservice.find_from_token(token).await else {
let Ok(appservice_info) = services.appservice.find_from_token(token) else {
return Err!(Request(Unauthorized("Invalid appservice token.")));
};
Ok(appservice_info)
}
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
if services
.config
.unauthenticated_request_ratelimit
.check_key(&ip)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::LimitExceeded(LimitExceededErrorData::new()),
"Rate limit exceeded.",
));
}
Ok(())
}
+7 -2
View File
@@ -1,7 +1,10 @@
use std::{borrow::Borrow, iter::once};
use axum::extract::State;
use conduwuit::{Err, Event, Result, info, utils::stream::ReadyExt};
use conduwuit::{
Err, Event, Result, info,
utils::stream::{BroadbandExt, ReadyExt},
};
use futures::StreamExt;
use ruma::api::federation::authorization::get_event_authorization;
@@ -64,7 +67,9 @@ pub(crate) async fn get_event_authorization_route(
.auth_chain
.event_ids_iter(&body.room_id, once(body.event_id.borrow()))
.ready_filter_map(Result::ok)
.filter_map(|id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() })
.broad_filter_map(
|id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() },
)
.then(|pdu| services.sending.convert_to_outgoing_federation_event(pdu))
.collect()
.await;
+12 -2
View File
@@ -1,7 +1,7 @@
use std::collections::{HashSet, VecDeque};
use axum::extract::State;
use conduwuit::{Err, Event, Result, debug, info, trace, utils::to_canonical_object, warn};
use conduwuit::{Err, Event, Result, debug, debug_warn, info, trace, utils::to_canonical_object};
use ruma::{OwnedEventId, api::federation::event::get_missing_events};
use serde_json::value::RawValue;
use service::rooms::event_handler::GET_MISSING_EVENTS_MAX_BATCH_SIZE;
@@ -44,6 +44,10 @@ pub(crate) async fn get_missing_events_route(
.unwrap_or(10)
.min(GET_MISSING_EVENTS_MAX_BATCH_SIZE);
if body.latest_events.len() > limit {
return Err!(Request(InvalidParam("Too many latest_events")));
}
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
let mut queue: VecDeque<OwnedEventId> = VecDeque::from(body.latest_events.clone());
@@ -64,7 +68,9 @@ pub(crate) async fn get_missing_events_route(
let mut pdu = match services.rooms.timeline.get_pdu(&next_event_id).await {
| Ok(pdu) => pdu,
| Err(e) => {
warn!("could not find event {next_event_id} while walking missing events: {e}");
debug_warn!(
"could not find event {next_event_id} while walking missing events: {e}"
);
continue;
},
};
@@ -74,6 +80,10 @@ pub(crate) async fn get_missing_events_route(
body.room_id
)));
}
if pdu.depth < body.min_depth {
debug!(%next_event_id, %pdu.depth, %body.min_depth, "event is below minimum depth, not traversing");
continue;
}
if services
.rooms
.pdu_metadata
+27 -24
View File
@@ -209,31 +209,35 @@ async fn create_invite(
services.sync.wake(&recipient_user).await;
for appservice in services.appservice.read().await.values() {
if appservice.is_user_match(&recipient_user) {
let transaction_id = general_purpose::URL_SAFE_NO_PAD
.encode(sha256::hash(pdu.event_id.as_bytes()))
.into();
let matching_appservices: Vec<_> = services
.appservice
.read()
.values()
.filter(|appservice| appservice.is_user_match(&recipient_user))
.cloned()
.collect();
let request = ruma::api::appservice::event::push_events::v1::Request::new(
transaction_id,
vec![pdu.to_format()],
);
for appservice in matching_appservices {
let transaction_id = general_purpose::URL_SAFE_NO_PAD
.encode(sha256::hash(pdu.event_id.as_bytes()))
.into();
services
.sending
.send_appservice_request(appservice.registration.clone(), request)
.await
.map_err(|e| {
error!(
"failed to notify appservice {} about incoming invite: {e}",
appservice.registration.id
);
err!(BadServerResponse(
"Failed to notify appservice about incoming invite."
))
})?;
}
let request = ruma::api::appservice::event::push_events::v1::Request::new(
transaction_id,
vec![pdu.to_format()],
);
services
.sending
.send_appservice_request(appservice.registration.clone(), request)
.await
.map_err(|e| {
error!(
"failed to notify appservice {} about incoming invite: {e}",
appservice.registration.id
);
err!(BadServerResponse("Failed to notify appservice about incoming invite."))
})?;
}
}
@@ -417,7 +421,6 @@ async fn validate_invite_create_event(
if !state_res::auth_check(
room_version_rules,
pdu,
None,
|_, _| async {
unreachable!("No state should be fetched when processing a lone create event");
},
+9 -9
View File
@@ -212,15 +212,15 @@ async fn acquire_keys_as_notary(
if server_keys.notary_may_contact_origin(&remote) {
debug_info!("Asking remote directly for verify keys");
if let Ok(res) = server_keys.origin_request(remote.clone(), start).await
&& let Ok(ssk) = sign_ssk(&server_keys, res.clone(), &remote, &my_name).await
&& let Ok(ssk) = sign_ssk(&server_keys, res.parsed.clone(), &remote, &my_name).await
{
let index = results.len();
results.push(ssk);
for key_id in res.verify_keys.keys().chain(res.old_verify_keys.keys()) {
for key_id in res.parsed.verify_keys.keys().chain(res.parsed.old_verify_keys.keys()) {
if fetch_all
|| queries.get(key_id).is_some_and(|c| {
c.minimum_valid_until_ts
.is_none_or(|m| res.valid_until_ts >= m)
.is_none_or(|m| res.parsed.valid_until_ts >= m)
}) {
queries.remove(key_id);
keymap.insert(key_id.to_owned(), index);
@@ -241,11 +241,11 @@ async fn acquire_keys_as_notary(
let my_name = &my_name;
let server_keys = &server_keys;
async move {
if ssk.valid_until_ts > in_one_week() || ssk.valid_until_ts < start {
if ssk.parsed.valid_until_ts > in_one_week() || ssk.valid_until_ts < start {
return None;
}
sign_ssk(server_keys, ssk.clone(), server_name, my_name)
sign_ssk(server_keys, ssk.parsed.clone(), server_name, my_name)
.await
.map(|signed_ssk| (ssk, signed_ssk))
.ok()
@@ -254,7 +254,7 @@ async fn acquire_keys_as_notary(
.ready_for_each(|(ssk, signed_ssk)| {
let idx = results.len();
results.push(signed_ssk);
for key_id in ssk.verify_keys.keys().chain(ssk.old_verify_keys.keys()) {
for key_id in ssk.parsed.verify_keys.keys().chain(ssk.old_verify_keys.keys()) {
keymap.insert(key_id.to_owned(), idx);
}
})
@@ -346,7 +346,7 @@ pub(crate) async fn get_remote_server_keys_route(
{
return sign_ssk(
&services.server_keys,
response,
response.parsed,
&body.server_name,
services.globals.server_name(),
)
@@ -360,13 +360,13 @@ pub(crate) async fn get_remote_server_keys_route(
.broad_filter_map(|ssk| {
let server_name = body.server_name.clone();
async move {
if ssk.valid_until_ts > in_one_week() || ssk.valid_until_ts < min_valid_ts {
if ssk.parsed.valid_until_ts > in_one_week() || ssk.parsed.valid_until_ts < min_valid_ts {
return None;
}
sign_ssk(
&services.server_keys,
ssk,
ssk.parsed,
server_name.as_ref(),
services.globals.server_name(),
)
+67 -185
View File
@@ -1,29 +1,19 @@
use std::{borrow::ToOwned, pin::pin};
use axum::extract::State;
use conduwuit::{
Err, Error, Result, debug, debug_info, info, matrix::pdu::PartialPdu, utils, warn,
};
use conduwuit_service::Services;
use futures::StreamExt;
use conduwuit::{Err, Error, Result, info, matrix::pdu::PartialPdu, utils};
use ruma::{
OwnedUserId, RoomId, UserId,
OwnedUserId,
api::{
error::{ErrorKind, IncompatibleRoomVersionErrorData},
federation::membership::prepare_join_event,
},
assign,
events::{
StateEventType,
room::{
join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent},
},
events::room::{
join_rules::JoinRule,
member::{MembershipState, RoomMemberEventContent},
},
};
use serde_json::value::to_raw_value;
use service::rooms::state::RoomMutexGuard;
use tokio::join;
use service::rooms::membership::{JoinConditionEntity, JoinConditionResult};
use crate::Ruma;
@@ -35,9 +25,6 @@ pub(crate) async fn create_join_event_template_route(
State(services): State<crate::State>,
body: Ruma<prepare_join_event::v1::Request>,
) -> Result<prepare_join_event::v1::Response> {
if !services.rooms.metadata.exists(&body.room_id).await {
return Err!(Request(NotFound("Room is unknown to this server.")));
}
if !services
.rooms
.state_cache
@@ -63,18 +50,6 @@ pub(crate) async fn create_join_event_template_route(
.acl_check(&body.identity, &body.room_id)
.await?;
if services
.moderation
.is_remote_server_forbidden(&body.identity)
{
warn!(
"Server {} for remote user {} tried joining room ID {} which has a server name that \
is globally forbidden. Rejecting.",
body.identity, &body.user_id, &body.room_id,
);
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
let room_version_rules = room_version.rules().unwrap();
if !body.ver.contains(&room_version) {
@@ -87,41 +62,78 @@ pub(crate) async fn create_join_event_template_route(
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
let (is_invited, is_joined) = join!(
services
.rooms
.state_cache
.is_invited(&body.user_id, &body.room_id),
services
.rooms
.state_cache
.is_joined(&body.user_id, &body.room_id)
);
let current_membership = services
.rooms
.state_accessor
.get_member(&body.room_id, &body.user_id)
.await
.ok()
.map_or(MembershipState::Leave, |content| content.membership);
let join_authorized_via_users_server: Option<OwnedUserId> = {
if is_joined || is_invited {
// User is already joined or invited and consequently does not need
// an authorising user
if matches!(
current_membership,
MembershipState::Join | MembershipState::Invite | MembershipState::Knock
) {
// User is already joined, invited, or knocked, and consequently
// does not need an authorising user
None
} else if !room_version_rules.authorization.restricted_join_rule {
// room version does not support restricted join rules
// Room version does not support restricted join rules
None
} else if user_can_perform_restricted_join(&services, &body.user_id, &body.room_id)
.await?
{
Some(
select_authorising_user(&services, &body.room_id, &body.user_id, &state_lock)
.await?,
)
} else {
None
let join_rules = services
.rooms
.state_accessor
.get_join_rules(&body.room_id)
.await;
if let JoinRule::Restricted(conditions) | JoinRule::KnockRestricted(conditions) =
join_rules
{
match services
.rooms
.membership
.evaluate_join_conditions(
&body.room_id,
JoinConditionEntity::User(&body.user_id),
&conditions,
)
.await
{
| JoinConditionResult::Satisfied => {
// Try to find an authorizing user
services
.rooms
.membership
.select_authorizing_user(&body.room_id, &body.user_id, &state_lock)
.await
.map(Some)?
},
| JoinConditionResult::Unsatisfied => {
return Err!(Request(Forbidden(
"You do not satisfy this room's join conditions."
)));
},
| JoinConditionResult::UnableToAuthorizeJoin => {
return Err!(Request(UnableToAuthorizeJoin(
"This server cannot check this room's join conditions."
)));
},
}
} else {
None
}
}
};
if services.antispam.check_all_joins() && join_authorized_via_users_server.is_none() {
if services.antispam.check_all_joins() {
if services
.antispam
.meowlnir_accept_make_join(body.room_id.clone(), body.user_id.clone())
.await
.is_err()
!= JoinConditionResult::Satisfied
{
return Err!(Request(Forbidden("Antispam rejected join request.")));
}
@@ -153,133 +165,3 @@ pub(crate) async fn create_join_event_template_route(
}),
)
}
/// Attempts to find a user who is able to issue an invite in the target room.
pub(crate) async fn select_authorising_user<'a>(
services: &Services,
room_id: &'a RoomId,
user_id: &'a UserId,
state_lock: &'a RoomMutexGuard,
) -> Result<OwnedUserId> {
let candidates = services.rooms.state_cache.local_users_in_room(room_id);
let mut candidates = pin!(candidates);
while let Some(candidate) = candidates.next().await {
if services
.rooms
.state_accessor
.user_can_invite(room_id, &candidate, user_id, state_lock)
.await
{
return Ok(candidate);
}
}
Err!(Request(UnableToGrantJoin(
"No user on this server is able to assist in joining."
)))
}
/// Checks whether the given user can join the given room via a restricted join.
pub(crate) async fn user_can_perform_restricted_join(
services: &Services,
user_id: &UserId,
room_id: &RoomId,
) -> Result<bool> {
let Ok(join_rules_event_content) = services
.rooms
.state_accessor
.room_state_get_content::<RoomJoinRulesEventContent>(
room_id,
&StateEventType::RoomJoinRules,
"",
)
.await
else {
// No join rules means there's nothing to authorise (defaults to invite)
return Ok(false);
};
let (JoinRule::Restricted(r) | JoinRule::KnockRestricted(r)) =
join_rules_event_content.join_rule
else {
// This is not a restricted room
return Ok(false);
};
if r.allow.is_empty() {
// This will never be authorisable, return forbidden.
return Err!(Request(Forbidden("You are not invited to this room.")));
}
let mut could_satisfy = true;
for allow_rule in &r.allow {
match allow_rule {
| AllowRule::RoomMembership(membership) => {
if !services
.rooms
.state_cache
.server_in_room(services.globals.server_name(), &membership.room_id)
.await
{
// Since we can't check this room, mark could_satisfy as
// false so that we can return
// M_UNABLE_TO_AUTHORIZE_JOIN later.
could_satisfy = false;
continue;
}
if services
.rooms
.state_cache
.is_joined(user_id, &membership.room_id)
.await
{
debug!(
"User {} is allowed to join room {} via membership in room {}",
user_id, room_id, membership.room_id
);
return Ok(true);
}
},
| other if other.rule_type() == "fi.mau.spam_checker" =>
return match services
.antispam
.meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned())
.await
{
| Ok(()) => Ok(true),
| Err(_) => Err!(Request(Forbidden("Antispam rejected join request."))),
},
| _ => {
// We don't recognise this join rule, so we cannot satisfy the
// request.
could_satisfy = false;
debug_info!(
"Unsupported allow rule in restricted join for room {}: {:?}",
room_id,
allow_rule
);
},
}
}
if could_satisfy {
// We were able to check all the restrictions and can be certain that
// the prospective member is not permitted to join.
Err!(Request(Forbidden(
"You do not belong to any of the rooms or spaces required to join this room."
)))
} else {
// We were unable to check all the restrictions. This usually means we
// aren't in one of the rooms this one is restricted to, ergo can't
// check its state for the user's membership, and consequently the
// user *might* be able to join if they ask another server.
Err!(Request(UnableToAuthorizeJoin(
"You do not belong to any of the recognised rooms or spaces required to join this \
room, but this server is unable to verify every requirement. You may be able to \
join via another server."
)))
}
}
+2
View File
@@ -18,6 +18,7 @@ pub(super) mod send_knock;
pub(super) mod send_leave;
pub(super) mod state;
pub(super) mod state_ids;
pub(super) mod stripped_state;
pub(super) mod user;
pub(super) mod version;
pub(super) mod well_known;
@@ -42,6 +43,7 @@ pub(super) use send_knock::*;
pub(super) use send_leave::*;
pub(super) use state::*;
pub(super) use state_ids::*;
pub(super) use stripped_state::*;
pub(super) use user::*;
pub(super) use version::*;
pub(super) use well_known::*;
+16 -23
View File
@@ -332,6 +332,7 @@ async fn handle_room(
room_id: OwnedRoomId,
pdus: impl Iterator<Item = Pdu> + Send,
) -> std::result::Result<Vec<(OwnedEventId, Result)>, TransactionError> {
let arrived = millis_since_unix_epoch();
let _room_lock = services
.rooms
.event_handler
@@ -392,7 +393,7 @@ async fn handle_room(
.federation_incoming_pdu_duration
.record(start.elapsed().as_secs_f64(), std::slice::from_ref(&outcome));
if let (Ok(()), Some(ts)) = (&result, origin_server_ts) {
let lag = millis_since_unix_epoch().saturating_sub(ts);
let lag = arrived.saturating_sub(ts);
instruments
.federation_incoming_pdu_lag
.record(Duration::from_millis(lag).as_secs_f64(), &[]);
@@ -581,28 +582,20 @@ async fn handle_edu_receipt_room_user(
}
let data = &user_updates.data;
user_updates
.event_ids
.into_iter()
.stream()
.for_each_concurrent(automatic_width(), |event_id| async move {
let user_data = [(user_id.to_owned(), data.clone())];
let receipts = [(ReceiptType::Read, BTreeMap::from(user_data))];
let content = [(event_id.clone(), BTreeMap::from(receipts))];
services
.rooms
.read_receipt
.readreceipt_update(
user_id,
room_id,
ReceiptEvent::new(
room_id.to_owned(),
ReceiptEventContent::from_iter(content),
),
)
.await;
})
.await;
for event_id in user_updates.event_ids {
let user_data = [(user_id.to_owned(), data.clone())];
let receipts = [(ReceiptType::Read, BTreeMap::from(user_data))];
let content = [(event_id, BTreeMap::from(receipts))];
services
.rooms
.read_receipt
.readreceipt_update(
user_id,
room_id,
ReceiptEvent::new(room_id.to_owned(), ReceiptEventContent::from_iter(content)),
)
.await;
}
}
async fn handle_edu_typing(services: &Services, origin: &ServerName, typing: TypingContent) {
+50 -10
View File
@@ -16,9 +16,11 @@ use ruma::{
TimelineEventType,
room::member::{MembershipState, RoomMemberEventContent},
},
room::JoinRule,
room_version_rules::RoomVersionRules,
};
use serde_json::value::to_raw_value;
use service::rooms::membership::{JoinConditionEntity, JoinConditionResult};
use crate::{Ruma, server::utils::validate_any_membership_event};
@@ -108,18 +110,56 @@ async fn create_join_event(
they cannot authorise your join."
)));
}
if !super::user_can_perform_restricted_join(services, &sender, room_id).await? {
return Err!(Request(UnableToAuthorizeJoin(
"Joining user did not pass restricted room's rules."
// If the user is invited or joined we don't need to check the join
// conditions, but in that case the requesting server shouldn't
// have set `join_authorized_via_users_server` in the first place.
let join_rules = services.rooms.state_accessor.get_join_rules(room_id).await;
if let JoinRule::Restricted(conditions) | JoinRule::KnockRestricted(conditions) =
join_rules
{
match services
.rooms
.membership
.evaluate_join_conditions(
room_id,
JoinConditionEntity::User(&sender),
&conditions,
)
.await
{
| JoinConditionResult::Satisfied => {
// Sign the join to prove that we checked the conditions.
services
.server_keys
.hash_and_sign_event(&mut pdu, room_version_rules)
.map_err(|e| {
err!(Request(InvalidParam(warn!(
"Failed to sign send_join event: {e}"
))))
})?;
},
| JoinConditionResult::Unsatisfied => {
return Err!(Request(Forbidden(
"You do not satisfy this room's join conditions."
)));
},
| JoinConditionResult::UnableToAuthorizeJoin => {
return Err!(Request(UnableToAuthorizeJoin(
"This server cannot check this room's join conditions."
)));
},
}
} else {
// We can't sign this, and if we don't sign it our event will fail
// the auth check, so we have to bail out here.
return Err!(Request(InvalidParam(
"join_authorized_via_users_server was supplied for a room that is not restricted"
)));
}
services
.server_keys
.hash_and_sign_event(&mut pdu, room_version_rules)
.map_err(|e| {
err!(Request(InvalidParam(warn!("Failed to sign send_join event: {e}"))))
})?;
}
let mutex_lock = services
+54
View File
@@ -0,0 +1,54 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use ruma::{
api::federation::event::get_stripped_state, assign, events::ALLOWED_STRIPPED_STATE_EVENTS,
};
use service::rooms::summary::{Accessibility, RoomStrippedState};
use crate::Ruma;
/// # `POST /_matrix/federation/unstable/org.continuwuity.msc4560.stripped_state/{room_id}` ([MSC4560])
///
/// Returns a room's stripped state.
///
/// [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560
pub(crate) async fn get_stripped_state_route(
State(services): State<crate::State>,
body: Ruma<get_stripped_state::msc4560::Request>,
) -> Result<get_stripped_state::msc4560::Response> {
if let Some(forbidden_type) = body
.state
.iter()
.find(|event_type| !ALLOWED_STRIPPED_STATE_EVENTS.contains(event_type))
{
return Err!(Request(InvalidParam(
"Event type {forbidden_type} may not be requested as stripped state."
)));
}
if services.rooms.metadata.is_banned(&body.room_id).await {
return Err!(Request(Forbidden("This room is banned on this homeserver.")));
}
match services
.rooms
.summary
.get_local_stripped_state_for_server(
&body.identity,
&body.room_id,
&body.state,
body.num_joined_members,
)
.await
{
| Accessibility::Accessible(RoomStrippedState { state, num_joined_members, .. }) => Ok(
assign!(get_stripped_state::msc4560::Response::default(), { state, num_joined_members }),
),
| Accessibility::Inaccessible => {
Err!(Request(Forbidden("You may not access this room's stripped state.")))
},
| Accessibility::NotFound => {
Err!(Request(NotFound("This room is not known to this server.")))
},
}
}