de-global server_is_ours / user_is_local

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-07-22 07:43:51 +00:00
parent 010e4ee35a
commit 59efabbbc2
34 changed files with 179 additions and 169 deletions

View file

@ -2,7 +2,7 @@ use std::fmt::Write;
use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduit::debug_info;
use conduit::{debug_info, error, info, utils, warn, Error, Result};
use register::RegistrationKind;
use ruma::{
api::client::{
@ -18,14 +18,9 @@ use ruma::{
events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType},
push, OwnedRoomId, UserId,
};
use tracing::{error, info, warn};
use super::{join_room_by_id_helper, DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
use crate::{
service::user_is_local,
utils::{self},
Error, Result, Ruma,
};
use crate::Ruma;
const RANDOM_USER_ID_LENGTH: usize = 10;
@ -48,7 +43,7 @@ pub(crate) async fn get_register_available_route(
// Validate user id
let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services.globals.server_name())
.ok()
.filter(|user_id| !user_id.is_historical() && user_is_local(user_id))
.filter(|user_id| !user_id.is_historical() && services.globals.user_is_local(user_id))
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
// Check if username is creative enough
@ -136,7 +131,7 @@ pub(crate) async fn register_route(
let proposed_user_id =
UserId::parse_with_server_name(username.to_lowercase(), services.globals.server_name())
.ok()
.filter(|user_id| !user_id.is_historical() && user_is_local(user_id))
.filter(|user_id| !user_id.is_historical() && services.globals.user_is_local(user_id))
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
if services.users.exists(&proposed_user_id)? {

View file

@ -1,4 +1,5 @@
use axum::extract::State;
use conduit::{debug, Error, Result};
use rand::seq::SliceRandom;
use ruma::{
api::client::{
@ -7,12 +8,9 @@ use ruma::{
},
OwnedServerName, RoomAliasId, RoomId,
};
use tracing::debug;
use service::Services;
use crate::{
service::{server_is_ours, Services},
Error, Result, Ruma,
};
use crate::Ruma;
/// # `PUT /_matrix/client/v3/directory/room/{roomAlias}`
///
@ -142,7 +140,7 @@ fn room_available_servers(
// prefer the room alias server first
if let Some(server_index) = servers
.iter()
.position(|server_name| server_is_ours(server_name))
.position(|server_name| services.globals.server_is_ours(server_name))
{
servers.swap_remove(server_index);
servers.insert(0, services.globals.server_name().to_owned());

View file

@ -20,11 +20,9 @@ use ruma::{
},
uint, RoomId, ServerName, UInt, UserId,
};
use service::Services;
use crate::{
service::{server_is_ours, Services},
Ruma,
};
use crate::Ruma;
/// # `POST /_matrix/client/v3/publicRooms`
///
@ -187,7 +185,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
services: &Services, server: Option<&ServerName>, limit: Option<UInt>, since: Option<&str>, filter: &Filter,
_network: &RoomNetwork,
) -> Result<get_public_rooms_filtered::v3::Response> {
if let Some(other_server) = server.filter(|server_name| !server_is_ours(server_name)) {
if let Some(other_server) = server.filter(|server_name| !services.globals.server_is_ours(server_name)) {
let response = services
.sending
.send_federation_request(

View file

@ -4,7 +4,7 @@ use std::{
};
use axum::extract::State;
use conduit::{utils, utils::math::continue_exponential_backoff_secs, Error, Result};
use conduit::{debug, utils, utils::math::continue_exponential_backoff_secs, Error, Result};
use futures_util::{stream::FuturesUnordered, StreamExt};
use ruma::{
api::{
@ -19,8 +19,6 @@ use ruma::{
DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
};
use serde_json::json;
use service::user_is_local;
use tracing::debug;
use super::SESSION_ID_LENGTH;
use crate::{service::Services, Ruma};
@ -266,7 +264,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool + Send>(
for (user_id, device_ids) in device_keys_input {
let user_id: &UserId = user_id;
if !user_is_local(user_id) {
if !services.globals.user_is_local(user_id) {
get_over_federation
.entry(user_id.server_name())
.or_insert_with(Vec::new)
@ -459,7 +457,7 @@ pub(crate) async fn claim_keys_helper(
let mut get_over_federation = BTreeMap::new();
for (user_id, map) in one_time_keys_input {
if !user_is_local(user_id) {
if !services.globals.user_is_local(user_id) {
get_over_federation
.entry(user_id.server_name())
.or_insert_with(Vec::new)

View file

@ -4,7 +4,15 @@ use std::{io::Cursor, time::Duration};
use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduit::{debug, error, utils::math::ruma_from_usize, warn};
use conduit::{
debug, debug_warn, error,
utils::{
self,
content_disposition::{content_disposition_type, make_content_disposition, sanitise_filename},
math::ruma_from_usize,
},
warn, Error, Result,
};
use image::io::Reader as ImgReader;
use ipaddress::IPAddress;
use reqwest::Url;
@ -15,20 +23,13 @@ use ruma::api::client::{
get_media_preview,
},
};
use service::{
media::{FileMeta, UrlPreviewData},
Services,
};
use webpage::HTML;
use crate::{
debug_warn,
service::{
media::{FileMeta, UrlPreviewData},
server_is_ours, Services,
},
utils::{
self,
content_disposition::{content_disposition_type, make_content_disposition, sanitise_filename},
},
Error, Result, Ruma, RumaResponse,
};
use crate::{Ruma, RumaResponse};
/// generated MXC ID (`media-id`) length
const MXC_LENGTH: usize = 32;
@ -218,7 +219,7 @@ pub(crate) async fn get_content_route(
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
})
} else if !server_is_ours(&body.server_name) && body.allow_remote {
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
let response = get_remote_content(
services,
&mxc,
@ -308,7 +309,7 @@ pub(crate) async fn get_content_as_filename_route(
cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()),
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
})
} else if !server_is_ours(&body.server_name) && body.allow_remote {
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
match get_remote_content(
services,
&mxc,
@ -408,7 +409,7 @@ pub(crate) async fn get_content_thumbnail_route(
cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()),
content_disposition,
})
} else if !server_is_ours(&body.server_name) && body.allow_remote {
} else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote {
if services
.globals
.prevent_media_downloads_from()

View file

@ -8,8 +8,11 @@ use std::{
use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduit::{
debug, debug_warn, error, info, trace, utils, utils::math::continue_exponential_backoff_secs, warn, Error,
PduEvent, Result,
debug, debug_warn, error, info,
pdu::{gen_event_id_canonical_json, PduBuilder},
trace, utils,
utils::math::continue_exponential_backoff_secs,
warn, Error, PduEvent, Result,
};
use ruma::{
api::{
@ -36,15 +39,11 @@ use ruma::{
OwnedUserId, RoomId, RoomVersionId, ServerName, UserId,
};
use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use service::{rooms::state::RoomMutexGuard, Services};
use tokio::sync::RwLock;
use crate::{
client::{update_avatar_url, update_displayname},
service::{
pdu::{gen_event_id_canonical_json, PduBuilder},
rooms::state::RoomMutexGuard,
server_is_ours, user_is_local, Services,
},
Ruma,
};
@ -675,7 +674,7 @@ pub async fn join_room_by_id_helper(
.state_cache
.server_in_room(services.globals.server_name(), room_id)?
|| servers.is_empty()
|| (servers.len() == 1 && server_is_ours(&servers[0]))
|| (servers.len() == 1 && services.globals.server_is_ours(&servers[0]))
{
join_room_by_id_helper_local(services, sender_user, room_id, reason, servers, third_party_signed, state_lock)
.await
@ -1049,7 +1048,7 @@ async fn join_room_by_id_helper_local(
.state_cache
.room_members(room_id)
.filter_map(Result::ok)
.filter(|user| user_is_local(user))
.filter(|user| services.globals.user_is_local(user))
.collect::<Vec<OwnedUserId>>();
let mut join_authorized_via_users_server: Option<OwnedUserId> = None;
@ -1110,7 +1109,7 @@ async fn join_room_by_id_helper_local(
if !restriction_rooms.is_empty()
&& servers
.iter()
.any(|server_name| !server_is_ours(server_name))
.any(|server_name| !services.globals.server_is_ours(server_name))
{
warn!("We couldn't do the join locally, maybe federation can help to satisfy the restricted join requirements");
let (make_join_response, remote_server) = make_join_request(services, sender_user, room_id, servers).await?;
@ -1259,7 +1258,7 @@ async fn make_join_request(
let mut incompatible_room_version_count: u8 = 0;
for remote_server in servers {
if server_is_ours(remote_server) {
if services.globals.server_is_ours(remote_server) {
continue;
}
info!("Asking {remote_server} for make_join ({make_join_counter})");
@ -1389,7 +1388,7 @@ pub(crate) async fn invite_helper(
));
}
if !user_is_local(user_id) {
if !services.globals.user_is_local(user_id) {
let (pdu, pdu_json, invite_room_state) = {
let state_lock = services.rooms.state.mutex.lock(room_id).await;
let content = to_raw_value(&RoomMemberEventContent {

View file

@ -1,4 +1,5 @@
use axum::extract::State;
use conduit::{pdu::PduBuilder, warn, Error, Result};
use ruma::{
api::{
client::{
@ -12,12 +13,9 @@ use ruma::{
OwnedMxcUri, OwnedRoomId, OwnedUserId,
};
use serde_json::value::to_raw_value;
use tracing::warn;
use service::Services;
use crate::{
service::{pdu::PduBuilder, user_is_local, Services},
Error, Result, Ruma,
};
use crate::Ruma;
/// # `PUT /_matrix/client/r0/profile/{userId}/displayname`
///
@ -56,7 +54,7 @@ pub(crate) async fn set_displayname_route(
pub(crate) async fn get_displayname_route(
State(services): State<crate::State>, body: Ruma<get_display_name::v3::Request>,
) -> Result<get_display_name::v3::Response> {
if !user_is_local(&body.user_id) {
if !services.globals.user_is_local(&body.user_id) {
// Create and update our local copy of the user
if let Ok(response) = services
.sending
@ -147,7 +145,7 @@ pub(crate) async fn set_avatar_url_route(
pub(crate) async fn get_avatar_url_route(
State(services): State<crate::State>, body: Ruma<get_avatar_url::v3::Request>,
) -> Result<get_avatar_url::v3::Response> {
if !user_is_local(&body.user_id) {
if !services.globals.user_is_local(&body.user_id) {
// Create and update our local copy of the user
if let Ok(response) = services
.sending
@ -205,7 +203,7 @@ pub(crate) async fn get_avatar_url_route(
pub(crate) async fn get_profile_route(
State(services): State<crate::State>, body: Ruma<get_profile::v3::Request>,
) -> Result<get_profile::v3::Response> {
if !user_is_local(&body.user_id) {
if !services.globals.user_is_local(&body.user_id) {
// Create and update our local copy of the user
if let Ok(response) = services
.sending

View file

@ -1,7 +1,7 @@
use std::sync::Arc;
use axum::extract::State;
use conduit::{debug_info, error};
use conduit::{debug_info, error, pdu::PduBuilder, Error, Result};
use ruma::{
api::client::{
error::ErrorKind,
@ -18,11 +18,9 @@ use ruma::{
serde::Raw,
EventId, RoomId, UserId,
};
use service::Services;
use crate::{
service::{pdu::PduBuilder, server_is_ours, Services},
Error, Result, Ruma, RumaResponse,
};
use crate::{Ruma, RumaResponse};
/// # `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}`
///
@ -250,7 +248,7 @@ async fn allowed_to_send_state_event(
}
for alias in aliases {
if !server_is_ours(alias.server_name())
if !services.globals.server_is_ours(alias.server_name())
|| services
.rooms
.alias

View file

@ -1,6 +1,7 @@
use std::collections::BTreeMap;
use axum::extract::State;
use conduit::{Error, Result};
use ruma::{
api::{
client::{error::ErrorKind, to_device::send_event_to_device},
@ -9,7 +10,7 @@ use ruma::{
to_device::DeviceIdOrAllDevices,
};
use crate::{user_is_local, Error, Result, Ruma};
use crate::Ruma;
/// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}`
///
@ -31,7 +32,7 @@ pub(crate) async fn send_event_to_device_route(
for (target_user_id, map) in &body.messages {
for (target_device_id_maybe, event) in map {
if !user_is_local(target_user_id) {
if !services.globals.user_is_local(target_user_id) {
let mut map = BTreeMap::new();
map.insert(target_device_id_maybe.clone(), event.clone());
let mut messages = BTreeMap::new();

View file

@ -7,8 +7,8 @@ pub mod server;
extern crate conduit_core as conduit;
extern crate conduit_service as service;
pub(crate) use conduit::{debug_info, debug_warn, pdu::PduEvent, utils, Error, Result};
pub(crate) use service::{services, user_is_local};
pub(crate) use conduit::{debug_info, pdu::PduEvent, utils, Error, Result};
pub(crate) use service::services;
pub use crate::router::State;
pub(crate) use crate::router::{Ruma, RumaResponse};

View file

@ -7,7 +7,6 @@ use ruma::{
serde::JsonObject,
CanonicalJsonValue, EventId, OwnedUserId,
};
use service::server_is_ours;
use crate::Ruma;
@ -88,7 +87,7 @@ pub(crate) async fn create_invite_route(
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "state_key is not a user ID."))?;
if !server_is_ours(invited_user.server_name()) {
if !services.globals.server_is_ours(invited_user.server_name()) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"User does not belong to this homeserver.",

View file

@ -1,4 +1,5 @@
use axum::extract::State;
use conduit::{Error, Result};
use get_profile_information::v1::ProfileField;
use rand::seq::SliceRandom;
use ruma::{
@ -9,7 +10,7 @@ use ruma::{
OwnedServerName,
};
use crate::{service::server_is_ours, Error, Result, Ruma};
use crate::Ruma;
/// # `GET /_matrix/federation/v1/query/directory`
///
@ -64,7 +65,7 @@ pub(crate) async fn get_profile_information_route(
));
}
if !server_is_ours(body.user_id.server_name()) {
if !services.globals.server_is_ours(body.user_id.server_name()) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"User does not belong to this server.",

View file

@ -3,7 +3,7 @@
use std::collections::BTreeMap;
use axum::extract::State;
use conduit::{Error, Result};
use conduit::{pdu::gen_event_id_canonical_json, warn, Error, Result};
use ruma::{
api::{client::error::ErrorKind, federation::membership::create_join_event},
events::{
@ -13,9 +13,8 @@ use ruma::{
CanonicalJsonValue, OwnedServerName, OwnedUserId, RoomId, ServerName,
};
use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use service::{pdu::gen_event_id_canonical_json, user_is_local, Services};
use service::Services;
use tokio::sync::RwLock;
use tracing::warn;
use crate::Ruma;
@ -126,7 +125,7 @@ async fn create_join_event(
if content
.join_authorized_via_users_server
.is_some_and(|user| user_is_local(&user))
.is_some_and(|user| services.globals.user_is_local(&user))
&& super::user_can_perform_restricted_join(services, &sender, room_id, &room_version_id).unwrap_or_default()
{
ruma::signatures::hash_and_sign_event(

View file

@ -3,6 +3,7 @@
use std::collections::BTreeMap;
use axum::extract::State;
use conduit::{Error, Result};
use ruma::{
api::{client::error::ErrorKind, federation::membership::create_leave_event},
events::{
@ -15,8 +16,8 @@ use serde_json::value::RawValue as RawJsonValue;
use tokio::sync::RwLock;
use crate::{
service::{pdu::gen_event_id_canonical_json, server_is_ours, Services},
Error, Result, Ruma,
service::{pdu::gen_event_id_canonical_json, Services},
Ruma,
};
/// # `PUT /_matrix/federation/v1/send_leave/{roomId}/{eventId}`
@ -174,7 +175,7 @@ async fn create_leave_event(
.state_cache
.room_servers(room_id)
.filter_map(Result::ok)
.filter(|server| !server_is_ours(server));
.filter(|server| !services.globals.server_is_ours(server));
services.sending.send_pdu_servers(servers, &pdu_id)?;

View file

@ -1,4 +1,5 @@
use axum::extract::State;
use conduit::{Error, Result};
use ruma::api::{
client::error::ErrorKind,
federation::{
@ -9,8 +10,7 @@ use ruma::api::{
use crate::{
client::{claim_keys_helper, get_keys_helper},
service::user_is_local,
Error, Result, Ruma,
Ruma,
};
/// # `GET /_matrix/federation/v1/user/devices/{userId}`
@ -19,7 +19,7 @@ use crate::{
pub(crate) async fn get_devices_route(
State(services): State<crate::State>, body: Ruma<get_devices::v1::Request>,
) -> Result<get_devices::v1::Response> {
if !user_is_local(&body.user_id) {
if !services.globals.user_is_local(&body.user_id) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Tried to access user from other server.",
@ -72,7 +72,11 @@ pub(crate) async fn get_devices_route(
pub(crate) async fn get_keys_route(
State(services): State<crate::State>, body: Ruma<get_keys::v1::Request>,
) -> Result<get_keys::v1::Response> {
if body.device_keys.iter().any(|(u, _)| !user_is_local(u)) {
if body
.device_keys
.iter()
.any(|(u, _)| !services.globals.user_is_local(u))
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"User does not belong to this server.",
@ -101,7 +105,11 @@ pub(crate) async fn get_keys_route(
pub(crate) async fn claim_keys_route(
State(services): State<crate::State>, body: Ruma<claim_keys::v1::Request>,
) -> Result<claim_keys::v1::Response> {
if body.one_time_keys.iter().any(|(u, _)| !user_is_local(u)) {
if body
.one_time_keys
.iter()
.any(|(u, _)| !services.globals.user_is_local(u))
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Tried to access user from other server.",