refactor fed membership endpoints, add missing checks, some cleanup, reduce line width

Signed-off-by: strawberry <strawberry@puppygock.gay>
This commit is contained in:
strawberry 2024-12-07 01:07:01 -05:00
parent 61670370ed
commit 9d59f777d2
12 changed files with 474 additions and 498 deletions

View file

@ -1,8 +1,5 @@
use axum::extract::State;
use conduit::{
utils::{IterStream, ReadyExt},
warn,
};
use conduit::{debug_info, utils::IterStream, warn, Err};
use futures::StreamExt;
use ruma::{
api::{client::error::ErrorKind, federation::membership::prepare_join_event},
@ -13,7 +10,7 @@ use ruma::{
},
StateEventType,
},
CanonicalJsonObject, RoomId, RoomVersionId, UserId,
CanonicalJsonObject, OwnedUserId, RoomId, RoomVersionId, UserId,
};
use serde_json::value::to_raw_value;
@ -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
@ -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() {
@ -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."
))));
}
}
@ -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
@ -155,37 +141,39 @@ 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 {
return Ok(false);
};
// restricted rooms are not supported on <=v7
if matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6 | V7) {
return Ok(false);
}
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);
};
if r.allow.is_empty() {
debug_info!("{room_id} is restricted but the allow key is empty");
return Ok(false);
}
if r.allow
.iter()
.filter_map(|rule| {
@ -201,22 +189,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(())
}
}