use std::{ collections::{BTreeSet, HashSet}, pin::pin, sync::Arc, }; use conduwuit::{ Err, Event, Result, debug, info, utils::{IterStream, ReadyExt, TryFutureExtExt, stream::BroadbandExt}, warn, }; use futures::{FutureExt, StreamExt, TryFutureExt}; use ruma::{ OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, ServerName, UInt, UserId, api::{ client::space::SpaceHierarchyRoomsChunk, error::ErrorKind, federation::{ event::get_stripped_state, space::{SpaceHierarchyParentSummary, get_hierarchy}, }, }, assign, events::{ AnyStrippedStateEvent, StateEventType, room::member::MembershipState, space::child::{HierarchySpaceChildEvent, SpaceChildEventContent}, }, room::{JoinRule, RoomSummary, RoomType}, serde::Raw, }; use crate::{ Dep, globals, rooms::{self, membership::JoinConditionResult}, sending, }; pub struct Service { services: Services, } struct Services { event_handler: Dep, globals: Dep, membership: Dep, sending: Dep, state: Dep, state_accessor: Dep, state_cache: Dep, timeline: Dep, } pub enum Accessibility { Accessible(T), Inaccessible, NotFound, } struct SpaceSummaryAndChildren { /// The summary of the space. summary: SpaceHierarchyRoomsChunk, /// All child rooms of the space. children: Vec, /// Child rooms of the space which are not accessible to the local server. inaccessible_children: Vec, } struct SpaceChild { room_id: OwnedRoomId, via: Vec, } #[derive(Default)] #[non_exhaustive] pub struct RoomStrippedState { pub state: Vec>, pub num_joined_members: Option, } impl crate::Service for Service { fn build(args: crate::Args<'_>) -> Result> { Ok(Arc::new(Self { services: Services { event_handler: args .depend::("rooms::event_handler"), globals: args.depend::("globals"), membership: args.depend::("rooms::membership"), sending: args.depend::("sending"), state: args.depend::("rooms::state"), state_accessor: args .depend::("rooms::state_accessor"), state_cache: args.depend::("rooms::state_cache"), timeline: args.depend::("rooms::timeline"), }, })) } fn name(&self) -> &str { crate::service::make_name(std::module_path!()) } } impl Service { /// Summarize a room for a local user, possibly by querying over federation /// if we don't have the room locally. pub async fn get_room_summary_for_user( &self, querying_user: Option<&UserId>, room_id: &RoomId, via: &[OwnedServerName], ) -> Result> { let summary = { if let Some(summary) = self.build_local_room_summary(room_id).await { // We have this room locally. // Check if the room is visible to the querying user. if !self.user_may_see_summary(querying_user, room_id).await { return Ok(Accessibility::Inaccessible); } summary } else if let Some((SpaceHierarchyParentSummary { summary, .. }, _)) = self.fetch_remote_room_summary(room_id, via, false).await { // A via has this room. summary } else { // We don't have this room and none of the vias have it either. return Ok(Accessibility::NotFound); } }; Ok(Accessibility::Accessible(summary)) } /// Fetch information about a room and its children, possibly by querying /// over federation if we don't have the room locally. /// /// This is similar to [`Self::get_room_summary_for_user`] but includes /// additional data which is needed to traverse the room hierarchy. async fn get_room_summary_and_children_for_user( &self, querying_user: Option<&UserId>, room_id: &RoomId, via: Option<&[OwnedServerName]>, suggested_only: bool, ) -> Result> { let (summary, inaccessible_children) = { if let Some(summary) = self.build_local_room_summary(room_id).await { // We have this room locally. if !self.user_may_see_summary(querying_user, room_id).await { return Ok(Accessibility::Inaccessible); } let children_state = if matches!(summary.room_type, Some(RoomType::Space)) { self.get_space_child_events(room_id, suggested_only).await } else { vec![] }; // All of the room's children are accessible to this server // (because we have the full room and its state), although // some of them may not be accessible to the querying user. (SpaceHierarchyRoomsChunk::new(summary, children_state), vec![]) } else if let Some(via) = via && let Some(( SpaceHierarchyParentSummary { summary, children_state, .. }, inaccessible_children, )) = self .fetch_remote_room_summary(room_id, via, suggested_only) .await { // A via has this room. (SpaceHierarchyRoomsChunk::new(summary, children_state), inaccessible_children) } else { // We don't have this room and none of the vias have it either. return Ok(Accessibility::NotFound); } }; let mut children: Vec<_> = summary .children_state .iter() // Ignore deserialization failures .flat_map(Raw::deserialize) // Filter out non-suggested children if suggested_only is set .filter(|child| !suggested_only || child.content.suggested) .collect(); children.sort(); let children = children .into_iter() .rev() .map(|child| SpaceChild { room_id: child.state_key, via: child.content.via, }) .collect(); Ok(Accessibility::Accessible(SpaceSummaryAndChildren { summary, children, inaccessible_children, })) } /// Summarize a room and its children for a local user, possibly by querying /// over federation if we don't have the space locally. pub async fn get_room_hierarchy_for_user( &self, querying_user: &UserId, room_id: OwnedRoomId, max_depth: Option, suggested_only: bool, ) -> Result>> { // This function traverses the space hierarchy tree depth-first as // required by the specification. // Check accessibility of the root room first, because we need to error // out if it isn't accessible. // TODO refactor this once the Try trait is stable let root_summary = match self .get_room_summary_and_children_for_user( Some(querying_user), &room_id, // Clients can't specify vias for the root room None, suggested_only, ) .await? { | Accessibility::Accessible(root_summary) => root_summary, | Accessibility::Inaccessible => return Ok(Accessibility::Inaccessible), | Accessibility::NotFound => return Ok(Accessibility::NotFound), }; let mut queue = vec![root_summary.children]; let mut summaries = vec![root_summary.summary]; let mut inaccessible_children: HashSet<_> = root_summary.inaccessible_children.into_iter().collect(); // Rooms already included in the response. The spec requires each room // to appear at most once, and this also terminates traversal of // cyclic space graphs (e.g. a space containing itself). let mut visited: HashSet = HashSet::from([room_id]); // TODO refactor this with Vec::peek_mut once it's stabilized while let Some(layer) = queue.last_mut() { let Some(SpaceChild { room_id, via }) = layer.pop() else { // If this layer is empty, discard it from the queue and // continue queue.pop(); continue; }; // The root room is at depth zero, so the current layer is the depth // of the child about to be processed. let depth = u64::try_from(queue.len()).expect("hierarchy depth should fit into u64"); if max_depth.is_some_and(|max_depth| depth > max_depth.into()) { continue; } // Do not request rooms which have been determined to be // inaccessible if inaccessible_children.contains(&room_id) { continue; } // Skip rooms already present in the response if !visited.insert(room_id.clone()) { continue; } let summary = match self .get_room_summary_and_children_for_user( Some(querying_user), &room_id, Some(&via), suggested_only, ) .await { | Ok(Accessibility::Accessible(summary)) => summary, | Ok(Accessibility::Inaccessible) => { // Mark this room as inaccessible and skip it inaccessible_children.insert(room_id); continue; }, | Ok(Accessibility::NotFound) => { // Skip children which we can't find continue; }, | Err(_) => { // Skip children which we failed to fetch over federation continue; }, }; summaries.push(summary.summary); inaccessible_children.extend(summary.inaccessible_children); // Bail out if more than fifty rooms are queued to prevent a DOS // when traversing incredibly large hierarchies. If you // actually have over fifty nested rooms, and you're // looking at this function to figure out what the issue // is, I suggest you reconsider some of the choices you // made which led you to this point. if queue.len() > 50 { return Err!(Request(TooLarge("Space hierarchy is unreasonably large"))); } // Add accessible children as a new layer if !summary.children.is_empty() { queue.push(summary.children); } } Ok(Accessibility::Accessible(summaries)) } /// Summarize a _local_ room and its children for a remote server. pub async fn get_local_room_summary_for_server( &self, querying_server: &ServerName, room_id: &RoomId, suggested_only: bool, ) -> Accessibility { let Some(summary) = self.build_local_room_summary(room_id).await else { return Accessibility::NotFound; }; // Check if the server can see the root room's summary if !self.server_may_see_summary(querying_server, room_id).await { return Accessibility::Inaccessible; } let children_state = if matches!(summary.room_type.as_ref(), Some(RoomType::Space)) { self.get_space_child_events(room_id, suggested_only).await } else { vec![] }; let (accessible_children, inaccessible_children) = children_state .iter() // Ignore deserialization failures .flat_map(Raw::deserialize) // Fetch summaries for the children in parallel .stream() .broad_then(async |child| { let summary = { if let Some(summary) = self.build_local_room_summary(&child.state_key).await { if self .server_may_see_summary(querying_server, &child.state_key) .await { Accessibility::Accessible(summary) } else { Accessibility::Inaccessible } } else { Accessibility::NotFound } }; (child.state_key, summary) }) // Sort the children into two Vecs by accessibility .ready_fold_default( |(mut accessible_children, mut inaccessible_children): (Vec<_>, Vec<_>), (room_id, summary)| { match summary { | Accessibility::Accessible(summary) => { accessible_children.push(summary); }, | Accessibility::Inaccessible => { inaccessible_children.push(room_id); }, | Accessibility::NotFound => { // Skip inaccessible children }, } (accessible_children, inaccessible_children) }, ) .await; Accessibility::Accessible(assign!( get_hierarchy::v1::Response::new(SpaceHierarchyParentSummary::new(summary, children_state)), { children: accessible_children, inaccessible_children: inaccessible_children } )) } /// Prepare a summary of a room known to this server. pub async fn build_local_room_summary(&self, room_id: &RoomId) -> Option { // If we can't find a version for this room, it doesn't exist. let room_version = self.services.state.get_room_version(room_id).await.ok()?; debug!(%room_id, "Preparing local summary for room"); let ( join_rule, guest_can_join, num_joined_members, world_readable, canonical_alias, name, topic, avatar_url, room_type, encryption, ) = async { futures::join!( self.services.state_accessor.get_join_rules(room_id), self.services.state_accessor.guest_can_join(room_id), self.services .state_cache .room_joined_count(room_id) .unwrap_or(0), self.services.state_accessor.is_world_readable(room_id), self.services .state_accessor .get_canonical_alias(room_id) .ok(), self.services.state_accessor.get_name(room_id).ok(), self.services.state_accessor.get_room_topic(room_id).ok(), self.services .state_accessor .get_avatar(room_id) .map(|res| res.into_option().unwrap_or_default().url), self.services.state_accessor.get_room_type(room_id).ok(), self.services .state_accessor .get_room_encryption(room_id) .ok(), ) } .boxed() .await; let summary = assign!( RoomSummary::new( room_id.to_owned(), join_rule.into(), guest_can_join, num_joined_members.try_into().expect("number of joined members should fit into a UInt"), world_readable, ), { canonical_alias: canonical_alias, name: name, topic: topic, avatar_url: avatar_url, room_type: room_type, encryption: encryption, room_version: Some(room_version), } ); Some(summary) } /// Query remote servers for the summary of a room. async fn fetch_remote_room_summary( &self, room_id: &RoomId, via: &[OwnedServerName], suggested_only: bool, ) -> Option<(SpaceHierarchyParentSummary, Vec)> { if via.is_empty() { return None; } info!(%room_id, ?via, "Asking for room summary over federation"); let request = assign!(get_hierarchy::v1::Request::new(room_id.to_owned()), { suggested_only: suggested_only }); for server in via { match self .services .sending .send_federation_request(server, request.clone()) .await { | Ok(get_hierarchy::v1::Response { room, inaccessible_children, .. }) => { if room.summary.room_id != room_id { warn!( %server, expected_room = %room_id, returned_room = %room.summary.room_id, "Server didn't return the room we asked for" ); continue; } info!(%room_id, %server, "Got room summary"); return Some((room, inaccessible_children)); }, | Err(err) => { info!(%room_id, %server, %err, "Server could not provide a summary for this room"); }, } } info!(%room_id, "No servers queried could provide a summary for this room"); None } /// Get the stripped m.space.child events of a room. async fn get_space_child_events( &self, room_id: &RoomId, suggested_only: bool, ) -> Vec> { let current_shortstatehash = self .services .state .get_room_shortstatehash(room_id) .await .expect("room should have a current state"); self.services .state_accessor .state_keys_with_ids(current_shortstatehash, &StateEventType::SpaceChild) .broad_filter_map(move |(state_key, event_id): (_, OwnedEventId)| async move { self.services .timeline .get_pdu(&event_id) .map_ok(move |pdu| (state_key, pdu)) .ok() .await }) .ready_filter_map(move |(state_key, pdu)| { let Ok(content) = pdu.get_content::() else { return None; }; if content.via.is_empty() { return None; } if suggested_only && !content.suggested { return None; } if RoomId::parse(&state_key).is_err() { return None; } Some(pdu.into_format()) }) .collect() .await } /// Prepares the stripped state of a local or remote room for a user. pub async fn get_stripped_state_for_user( &self, querying_user: Option<&UserId>, room_id: &RoomId, via: &[OwnedServerName], state: &BTreeSet, num_joined_members: bool, ) -> Accessibility<(OwnedServerName, RoomStrippedState)> { if let Some(state) = self .build_local_stripped_state(room_id, state, num_joined_members) .await { if self.user_may_see_summary(querying_user, room_id).await { Accessibility::Accessible((self.services.globals.server_name().to_owned(), state)) } else { Accessibility::Inaccessible } } else { self.fetch_remote_stripped_state(room_id, via, state, num_joined_members) .await } } /// Prepares the stripped state of a local room for a server. pub async fn get_local_stripped_state_for_server( &self, querying_server: &ServerName, room_id: &RoomId, state: &BTreeSet, num_joined_members: bool, ) -> Accessibility { if let Some(state) = self .build_local_stripped_state(room_id, state, num_joined_members) .await { if self.server_may_see_summary(querying_server, room_id).await { Accessibility::Accessible(state) } else { Accessibility::Inaccessible } } else { Accessibility::NotFound } } /// Build a local room's stripped state. Returns None if we don't have the /// room. async fn build_local_stripped_state( &self, room_id: &RoomId, state: &BTreeSet, num_joined_members: bool, ) -> Option { if !self .services .state_cache .server_in_room(self.services.globals.server_name(), room_id) .await { return None; } let current_shortstatehash = self .services .state .get_room_shortstatehash(room_id) .await .expect("room should have state"); let state = state .iter() .stream() .broad_flat_map(|event_type| { self.services .state_accessor .state_keys_with_ids::(current_shortstatehash, event_type) }) .broad_filter_map(async |(_, event_id)| { self.services.timeline.get_pdu(&event_id).ok().await }) .ready_filter_map(|pdu| Some(pdu.into_format())) .collect() .await; let num_joined_members = if num_joined_members { Some( self.services .state_cache .room_joined_count(room_id) .await .expect("room should have a joined count") .try_into() .expect("joined count should fit into uint"), ) } else { None }; Some(RoomStrippedState { state, num_joined_members }) } /// Ask remote servers for a room's stripped state. async fn fetch_remote_stripped_state( &self, room_id: &RoomId, via: &[OwnedServerName], state: &BTreeSet, num_joined_members: bool, ) -> Accessibility<(OwnedServerName, RoomStrippedState)> { if via.is_empty() { return Accessibility::NotFound; } let request = assign!(get_stripped_state::unstable::Request::new(room_id.to_owned()), { state: state.to_owned(), num_joined_members }); let mut responses = pin!(via.iter().stream().broad_then(async |server| { match self .services .sending .send_federation_request(server, request.clone()) .await { | Ok(response) => Accessibility::Accessible((server.to_owned(), response)), | Err(err) => match err.kind() { | ErrorKind::Forbidden => Accessibility::Inaccessible, | _ => Accessibility::NotFound, }, } })); let mut got_inaccessible = false; while let Some(response) = responses.next().await { match response { | Accessibility::Accessible((server, response)) => { // The via has the room. return Accessibility::Accessible((server, RoomStrippedState { state: response.state, num_joined_members: response.num_joined_members, })); }, | Accessibility::Inaccessible => { // The via has the room and was able to determine that we // can't access it. We don't stop // checking in case it's malicious or wrong, // but we do switch to returning M_FORBIDDEN instead of // M_NOT_FOUND if no other via lets us // see the room. got_inaccessible = true; continue; }, | Accessibility::NotFound => { // The via doesn't have the room. continue; }, } } if got_inaccessible { Accessibility::Inaccessible } else { Accessibility::NotFound } } /// Determine if a user (possibly anonymous) may view a room summary. async fn user_may_see_summary( &self, querying_user: Option<&UserId>, room_id: &RoomId, ) -> bool { // Anyone can view the summary of world-readable rooms. if self .services .state_accessor .is_world_readable(room_id) .await { return true; } // If the user is joined or invited they may always view the summary. if let Some(querying_user) = querying_user { let membership = self .services .state_accessor .get_member(room_id, querying_user) .await .ok() .map_or_else(|| MembershipState::Leave, |content| content.membership); if matches!(membership, MembershipState::Join | MembershipState::Invite) { return true; } } // Otherwise, visibility depends on the join rule. let join_rule = self.services.state_accessor.get_join_rules(room_id).await; match (join_rule, querying_user) { // Anyone can view summaries for `public`, `knock`, and // `knock_restricted` rooms. | (JoinRule::Public | JoinRule::Knock | JoinRule::KnockRestricted(_), _) => true, // The user may be able to view the summary for a `restricted` room, // even if they aren't invited, provided they fulfill the join // rules. | (JoinRule::Restricted(conditions), Some(querying_user)) => self.services .membership .evaluate_join_conditions(room_id, querying_user.into(), &conditions) .await == JoinConditionResult::Satisfied, // In all other cases, the user may not view the summary. | _ => false, } } // Determine if a remote server may view a room summary. async fn server_may_see_summary( &self, querying_server: &ServerName, room_id: &RoomId, ) -> bool { // Servers may not see summaries of rooms they're ACLed from. if self .services .event_handler .acl_check(querying_server, room_id) .await .is_err() { return false; } // Servers may always see summaries if any of their users are // participating in the room. The server really should have generated a // summary itself, instead of asking us for it, but we might as // well save ourselves a bit of time checking the other rules. if self .services .state_cache .server_in_room(querying_server, room_id) .await { return true; } let join_rule = self.services.state_accessor.get_join_rules(room_id).await; // Servers may see summaries in restricted rooms if they satisfy the // join conditions. if let JoinRule::Restricted(conditions) = join_rule { return self .services .membership .evaluate_join_conditions(room_id, querying_server.into(), &conditions) .await == JoinConditionResult::Satisfied; } // If the server isn't in the room, the same visibility rules apply as // for anonymous summary requests. self.user_may_see_summary(None, room_id).await } }