Skip to content

Commit

Permalink
refactor fed membership endpoints, add missing checks, some cleanup, …
Browse files Browse the repository at this point in the history
…reduce line width

Signed-off-by: strawberry <[email protected]>
  • Loading branch information
girlbossceo committed Dec 8, 2024
1 parent f82537e commit 61a63f9
Show file tree
Hide file tree
Showing 12 changed files with 463 additions and 492 deletions.
490 changes: 233 additions & 257 deletions src/api/client/membership.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/api/client/user_directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub(crate) async fn search_users_route(
State(services): State<crate::State>, body: Ruma<search_users::v3::Request>,
) -> Result<search_users::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let limit = usize::try_from(body.limit).unwrap_or(10); // default limit is 10
let limit = usize::try_from(body.limit).map_or(10, usize::from).min(100); // default limit is 10

let users = services.users.stream().filter_map(|user_id| async {
// Filter out buggy users (they should not exist, but you never know...)
Expand Down
34 changes: 17 additions & 17 deletions src/api/server/invite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,24 +145,24 @@ pub(crate) async fn create_invite_route(
true,
)
.await?;
}

for appservice in services.appservice.read().await.values() {
if appservice.is_user_match(&invited_user) {
services
.sending
.send_appservice_request(
appservice.registration.clone(),
ruma::api::appservice::event::push_events::v1::Request {
events: vec![pdu.to_room_event()],
txn_id: general_purpose::URL_SAFE_NO_PAD
.encode(sha256::hash(pdu.event_id.as_bytes()))
.into(),
ephemeral: Vec::new(),
to_device: Vec::new(),
},
)
.await?;
for appservice in services.appservice.read().await.values() {
if appservice.is_user_match(&invited_user) {
services
.sending
.send_appservice_request(
appservice.registration.clone(),
ruma::api::appservice::event::push_events::v1::Request {
events: vec![pdu.to_room_event()],
txn_id: general_purpose::URL_SAFE_NO_PAD
.encode(sha256::hash(pdu.event_id.as_bytes()))
.into(),
ephemeral: Vec::new(),
to_device: Vec::new(),
},
)
.await?;
}
}
}

Expand Down
131 changes: 56 additions & 75 deletions src/api/server/make_join.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use axum::extract::State;
use conduit::{
utils::{IterStream, ReadyExt},
warn,
};
use conduit::{utils::IterStream, warn, Err};
use futures::StreamExt;
use ruma::{
api::{client::error::ErrorKind, federation::membership::prepare_join_event},
Expand All @@ -13,7 +10,7 @@ use ruma::{
},
StateEventType,
},
CanonicalJsonObject, RoomId, RoomVersionId, UserId,
CanonicalJsonObject, OwnedUserId, RoomId, RoomVersionId, UserId,
};
use serde_json::value::to_raw_value;

Expand All @@ -29,14 +26,11 @@ 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(Error::BadRequest(ErrorKind::NotFound, "Room is unknown to this server."));
return Err!(Request(NotFound("Room is unknown to this server.")));
}

if body.user_id.server_name() != body.origin() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to join on behalf of another server/user",
));
return Err!(Request(BadJson("Not allowed to join on behalf of another server/user.")));
}

// ACL check origin server
Expand All @@ -59,10 +53,7 @@ pub(crate) async fn create_join_event_template_route(
&body.user_id,
&body.room_id,
);
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}

if let Some(server) = body.room_id.server_name() {
Expand All @@ -72,10 +63,9 @@ pub(crate) async fn create_join_event_template_route(
.forbidden_remote_server_names
.contains(&server.to_owned())
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
return Err!(Request(Forbidden(warn!(
"Room ID server name {server} is banned on this homeserver."
))));
}
}

Expand All @@ -91,39 +81,35 @@ pub(crate) async fn create_join_event_template_route(

let state_lock = services.rooms.state.mutex.lock(&body.room_id).await;

let join_authorized_via_users_server = if (services
.rooms
.state_cache
.is_left(&body.user_id, &body.room_id)
.await)
&& user_can_perform_restricted_join(&services, &body.user_id, &body.room_id, &room_version_id).await?
{
let auth_user = services
.rooms
.state_cache
.room_members(&body.room_id)
.ready_filter(|user| user.server_name() == services.globals.server_name())
.filter(|user| {
services
.rooms
.state_accessor
.user_can_invite(&body.room_id, user, &body.user_id, &state_lock)
})
.boxed()
.next()
.await
.map(ToOwned::to_owned);

if auth_user.is_some() {
auth_user
let join_authorized_via_users_server: Option<OwnedUserId> = {
use RoomVersionId::*;
if matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6 | V7) {
// room version does not support restricted join rules
None
} else if user_can_perform_restricted_join(&services, &body.user_id, &body.room_id, &room_version_id).await? {
let Some(auth_user) = services
.rooms
.state_cache
.local_users_in_room(&body.room_id)
.filter(|user| {
services
.rooms
.state_accessor
.user_can_invite(&body.room_id, user, &body.user_id, &state_lock)
})
.boxed()
.next()
.await
.map(ToOwned::to_owned)
else {
return Err!(Request(UnableToGrantJoin(
"No user on this server is able to assist in joining."
)));
};
Some(auth_user)
} else {
return Err(Error::BadRequest(
ErrorKind::UnableToGrantJoin,
"No user on this server is able to assist in joining.",
));
None
}
} else {
None
};

let (_pdu, mut pdu_json) = services
Expand Down Expand Up @@ -155,33 +141,30 @@ pub(crate) async fn create_join_event_template_route(
}

/// Checks whether the given user can join the given room via a restricted join.
/// This doesn't check the current user's membership. This should be done
/// externally, either by using the state cache or attempting to authorize the
/// event.
pub(crate) async fn user_can_perform_restricted_join(
services: &Services, user_id: &UserId, room_id: &RoomId, room_version_id: &RoomVersionId,
) -> Result<bool> {
use RoomVersionId::*;

let join_rules_event = services
.rooms
.state_accessor
.room_state_get(room_id, &StateEventType::RoomJoinRules, "")
.await;

let Ok(Ok(join_rules_event_content)) = join_rules_event.as_ref().map(|join_rules_event| {
serde_json::from_str::<RoomJoinRulesEventContent>(join_rules_event.content.get()).map_err(|e| {
warn!("Invalid join rules event in database: {e}");
Error::bad_database("Invalid join rules event in database")
})
}) else {
// restricted rooms are not supported on <=v7
if matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6 | V7) {
return Ok(false);
};
}

if matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6 | V7) {
if services.rooms.state_cache.is_joined(user_id, room_id).await {
// joining user is already joined, there is nothing we need to do
return Ok(false);
}

let Ok(join_rules_event_content) = services
.rooms
.state_accessor
.room_state_get_content::<RoomJoinRulesEventContent>(room_id, &StateEventType::RoomJoinRules, "")
.await
else {
return Ok(false);
};

let (JoinRule::Restricted(r) | JoinRule::KnockRestricted(r)) = join_rules_event_content.join_rule else {
return Ok(false);
};
Expand All @@ -201,22 +184,20 @@ pub(crate) async fn user_can_perform_restricted_join(
{
Ok(true)
} else {
Err(Error::BadRequest(
ErrorKind::UnableToAuthorizeJoin,
"User is not known to be in any required room.",
))
Err!(Request(UnableToAuthorizeJoin(
"Joining user is not known to be in any required room."
)))
}
}

pub(crate) fn maybe_strip_event_id(pdu_json: &mut CanonicalJsonObject, room_version_id: &RoomVersionId) -> Result<()> {
pub(crate) fn maybe_strip_event_id(pdu_json: &mut CanonicalJsonObject, room_version_id: &RoomVersionId) -> Result {
use RoomVersionId::*;

match room_version_id {
V1 | V2 => {},
V1 | V2 => Ok(()),
_ => {
pdu_json.remove("event_id");
Ok(())
},
};

Ok(())
}
}
7 changes: 2 additions & 5 deletions src/api/server/make_knock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,11 @@ pub(crate) async fn create_knock_event_template_route(
State(services): State<crate::State>, body: Ruma<create_knock_event_template::v1::Request>,
) -> Result<create_knock_event_template::v1::Response> {
if !services.rooms.metadata.exists(&body.room_id).await {
return Err(Error::BadRequest(ErrorKind::NotFound, "Room is unknown to this server."));
return Err!(Request(NotFound("Room is unknown to this server.")));
}

if body.user_id.server_name() != body.origin() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to knock on behalf of another server/user",
));
return Err!(Request(BadJson("Not allowed to knock on behalf of another server/user.")));
}

// ACL check origin server
Expand Down
11 changes: 4 additions & 7 deletions src/api/server/make_leave.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use axum::extract::State;
use conduit::{Error, Result};
use conduit::{Err, Result};
use ruma::{
api::{client::error::ErrorKind, federation::membership::prepare_leave_event},
api::federation::membership::prepare_leave_event,
events::room::member::{MembershipState, RoomMemberEventContent},
};
use serde_json::value::to_raw_value;
Expand All @@ -16,14 +16,11 @@ pub(crate) async fn create_leave_event_template_route(
State(services): State<crate::State>, body: Ruma<prepare_leave_event::v1::Request>,
) -> Result<prepare_leave_event::v1::Response> {
if !services.rooms.metadata.exists(&body.room_id).await {
return Err(Error::BadRequest(ErrorKind::NotFound, "Room is unknown to this server."));
return Err!(Request(NotFound("Room is unknown to this server.")));
}

if body.user_id.server_name() != body.origin() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Not allowed to leave on behalf of another server/user",
));
return Err!(Request(BadJson("Not allowed to leave on behalf of another server/user.")));
}

// ACL check origin
Expand Down
Loading

0 comments on commit 61a63f9

Please sign in to comment.