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

@ -90,7 +90,7 @@ pub(super) async fn remote_user_in_rooms(_body: Vec<&str>, user_id: Box<UserId>)
.state_cache
.rooms_joined(&user_id)
.filter_map(Result::ok)
.map(|room_id| get_room_info(&room_id))
.map(|room_id| get_room_info(services(), &room_id))
.collect();
if rooms.is_empty() {

View file

@ -19,7 +19,7 @@ extern crate conduit_core as conduit;
extern crate conduit_service as service;
pub(crate) use conduit::{mod_ctor, mod_dtor, Result};
pub(crate) use service::{services, user_is_local};
pub(crate) use service::services;
pub(crate) use crate::utils::{escape_html, get_room_info};

View file

@ -39,7 +39,7 @@ pub(super) async fn list(
true
})
.map(|room_id| get_room_info(&room_id))
.map(|room_id| get_room_info(services(), &room_id))
})
.collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1);

View file

@ -29,7 +29,7 @@ pub(super) async fn process(command: RoomDirectoryCommand, _body: Vec<&str>) ->
.directory
.public_rooms()
.filter_map(Result::ok)
.map(|id: OwnedRoomId| get_room_info(&id))
.map(|id: OwnedRoomId| get_room_info(services(), &id))
.collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1);
rooms.reverse();

View file

@ -1,9 +1,9 @@
use api::client::leave_room;
use conduit::{debug, error, info, warn, Result};
use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomAliasId, RoomId, RoomOrAliasId};
use tracing::{debug, error, info, warn};
use super::RoomModerationCommand;
use crate::{get_room_info, services, user_is_local, Result};
use crate::{get_room_info, services};
pub(super) async fn process(command: RoomModerationCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
match command {
@ -110,11 +110,11 @@ async fn ban_room(
.room_members(&room_id)
.filter_map(|user| {
user.ok().filter(|local_user| {
user_is_local(local_user)
services().globals.user_is_local(local_user)
// additional wrapped check here is to avoid adding remote users
// who are in the admin room to the list of local users (would
// fail auth check)
&& (user_is_local(local_user)
&& (services().globals.user_is_local(local_user)
// since this is a force operation, assume user is an admin
// if somehow this fails
&& services()
@ -484,7 +484,7 @@ async fn list_banned_rooms(_body: Vec<&str>) -> Result<RoomMessageEventContent>
let mut rooms = room_ids
.into_iter()
.map(|room_id| get_room_info(&room_id))
.map(|room_id| get_room_info(services(), &room_id))
.collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1);
rooms.reverse();

View file

@ -36,7 +36,7 @@ pub(super) async fn create(
_body: Vec<&str>, username: String, password: Option<String>,
) -> Result<RoomMessageEventContent> {
// Validate user id
let user_id = parse_local_user_id(&username)?;
let user_id = parse_local_user_id(services(), &username)?;
if services().users.exists(&user_id)? {
return Ok(RoomMessageEventContent::text_plain(format!("Userid {user_id} already exists")));
@ -134,7 +134,7 @@ pub(super) async fn deactivate(
_body: Vec<&str>, no_leave_rooms: bool, user_id: String,
) -> Result<RoomMessageEventContent> {
// Validate user id
let user_id = parse_local_user_id(&user_id)?;
let user_id = parse_local_user_id(services(), &user_id)?;
// don't deactivate the server service account
if user_id == services().globals.server_user {
@ -170,7 +170,7 @@ pub(super) async fn deactivate(
}
pub(super) async fn reset_password(_body: Vec<&str>, username: String) -> Result<RoomMessageEventContent> {
let user_id = parse_local_user_id(&username)?;
let user_id = parse_local_user_id(services(), &username)?;
if user_id == services().globals.server_user {
return Ok(RoomMessageEventContent::text_plain(
@ -211,7 +211,7 @@ pub(super) async fn deactivate_all(
let mut admins = Vec::new();
for username in usernames {
match parse_active_local_user_id(username) {
match parse_active_local_user_id(services(), username) {
Ok(user_id) => {
if services().users.is_admin(&user_id)? && !force {
services()
@ -292,14 +292,14 @@ pub(super) async fn deactivate_all(
pub(super) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Result<RoomMessageEventContent> {
// Validate user id
let user_id = parse_local_user_id(&user_id)?;
let user_id = parse_local_user_id(services(), &user_id)?;
let mut rooms: Vec<(OwnedRoomId, u64, String)> = services()
.rooms
.state_cache
.rooms_joined(&user_id)
.filter_map(Result::ok)
.map(|room_id| get_room_info(&room_id))
.map(|room_id| get_room_info(services(), &room_id))
.collect();
if rooms.is_empty() {
@ -344,10 +344,13 @@ pub(super) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Resu
pub(super) async fn force_join_room(
_body: Vec<&str>, user_id: String, room_id: OwnedRoomOrAliasId,
) -> Result<RoomMessageEventContent> {
let user_id = parse_local_user_id(&user_id)?;
let user_id = parse_local_user_id(services(), &user_id)?;
let room_id = services().rooms.alias.resolve(&room_id).await?;
assert!(service::user_is_local(&user_id), "Parsed user_id must be a local user");
assert!(
services().globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
join_room_by_id_helper(services(), &user_id, &room_id, None, &[], None).await?;
Ok(RoomMessageEventContent::notice_markdown(format!(
@ -356,13 +359,16 @@ pub(super) async fn force_join_room(
}
pub(super) async fn make_user_admin(_body: Vec<&str>, user_id: String) -> Result<RoomMessageEventContent> {
let user_id = parse_local_user_id(&user_id)?;
let user_id = parse_local_user_id(services(), &user_id)?;
let displayname = services()
.users
.displayname(&user_id)?
.unwrap_or_else(|| user_id.to_string());
assert!(service::user_is_local(&user_id), "Parsed user_id must be a local user");
assert!(
services().globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
services()
.admin
.make_user_admin(&user_id, displayname)
@ -376,7 +382,7 @@ pub(super) async fn make_user_admin(_body: Vec<&str>, user_id: String) -> Result
pub(super) async fn put_room_tag(
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>, tag: String,
) -> Result<RoomMessageEventContent> {
let user_id = parse_active_local_user_id(&user_id)?;
let user_id = parse_active_local_user_id(services(), &user_id)?;
let event = services()
.account_data
@ -411,7 +417,7 @@ pub(super) async fn put_room_tag(
pub(super) async fn delete_room_tag(
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>, tag: String,
) -> Result<RoomMessageEventContent> {
let user_id = parse_active_local_user_id(&user_id)?;
let user_id = parse_active_local_user_id(services(), &user_id)?;
let event = services()
.account_data
@ -443,7 +449,7 @@ pub(super) async fn delete_room_tag(
pub(super) async fn get_room_tags(
_body: Vec<&str>, user_id: String, room_id: Box<RoomId>,
) -> Result<RoomMessageEventContent> {
let user_id = parse_active_local_user_id(&user_id)?;
let user_id = parse_active_local_user_id(services(), &user_id)?;
let event = services()
.account_data

View file

@ -1,8 +1,6 @@
use conduit_core::{err, Err};
use conduit_core::{err, Err, Result};
use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
use service::user_is_local;
use crate::{services, Result};
use service::Services;
pub(crate) fn escape_html(s: &str) -> String {
s.replace('&', "&amp;")
@ -10,17 +8,17 @@ pub(crate) fn escape_html(s: &str) -> String {
.replace('>', "&gt;")
}
pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) {
pub(crate) fn get_room_info(services: &Services, id: &RoomId) -> (OwnedRoomId, u64, String) {
(
id.into(),
services()
services
.rooms
.state_cache
.room_joined_count(id)
.ok()
.flatten()
.unwrap_or(0),
services()
services
.rooms
.state_accessor
.get_name(id)
@ -31,16 +29,16 @@ pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) {
}
/// Parses user ID
pub(crate) fn parse_user_id(user_id: &str) -> Result<OwnedUserId> {
UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name())
pub(crate) fn parse_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
UserId::parse_with_server_name(user_id.to_lowercase(), services.globals.server_name())
.map_err(|e| err!("The supplied username is not a valid username: {e}"))
}
/// Parses user ID as our local user
pub(crate) fn parse_local_user_id(user_id: &str) -> Result<OwnedUserId> {
let user_id = parse_user_id(user_id)?;
pub(crate) fn parse_local_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
let user_id = parse_user_id(services, user_id)?;
if !user_is_local(&user_id) {
if !services.globals.user_is_local(&user_id) {
return Err!("User {user_id:?} does not belong to our server.");
}
@ -48,14 +46,14 @@ pub(crate) fn parse_local_user_id(user_id: &str) -> Result<OwnedUserId> {
}
/// Parses user ID that is an active (not guest or deactivated) local user
pub(crate) fn parse_active_local_user_id(user_id: &str) -> Result<OwnedUserId> {
let user_id = parse_local_user_id(user_id)?;
pub(crate) fn parse_active_local_user_id(services: &Services, user_id: &str) -> Result<OwnedUserId> {
let user_id = parse_local_user_id(services, user_id)?;
if !services().users.exists(&user_id)? {
if !services.users.exists(&user_id)? {
return Err!("User {user_id:?} does not exist on this server.");
}
if services().users.is_deactivated(&user_id)? {
if services.users.is_deactivated(&user_id)? {
return Err!("User {user_id:?} is deactivated.");
}

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.",

View file

@ -109,4 +109,7 @@ impl Server {
#[inline]
pub fn running(&self) -> bool { !self.stopping.load(Ordering::Acquire) }
#[inline]
pub fn is_ours(&self, name: &str) -> bool { name == self.config.server_name }
}

View file

@ -22,7 +22,7 @@ use ruma::{
use serde_json::value::to_raw_value;
use tokio::sync::{Mutex, RwLock};
use crate::{globals, rooms, rooms::state::RoomMutexGuard, user_is_local, Dep};
use crate::{globals, rooms, rooms::state::RoomMutexGuard, Dep};
pub struct Service {
services: Services,
@ -301,7 +301,7 @@ impl Service {
}
// only allow public escaped commands by local admins
if is_public_escape && !user_is_local(&pdu.sender) {
if is_public_escape && !self.services.globals.user_is_local(&pdu.sender) {
return false;
}

View file

@ -21,7 +21,7 @@ use ruma::{
use tokio::sync::Mutex;
use url::Url;
use crate::{service, services};
use crate::service;
pub struct Service {
pub db: Data,
@ -302,13 +302,11 @@ impl Service {
true
}
/// checks if `user_id` is local to us via server_name comparison
#[inline]
pub fn user_is_local(&self, user_id: &UserId) -> bool { self.server_is_ours(user_id.server_name()) }
#[inline]
pub fn server_is_ours(&self, server_name: &ServerName) -> bool { server_name == self.config.server_name }
}
#[inline]
#[must_use]
pub fn server_is_ours(server_name: &ServerName) -> bool { server_name == services().globals.config.server_name }
/// checks if `user_id` is local to us via server_name comparison
#[inline]
#[must_use]
pub fn user_is_local(user_id: &UserId) -> bool { server_is_ours(user_id.server_name()) }

View file

@ -33,10 +33,7 @@ use conduit::{Result, Server};
use database::Database;
pub(crate) use service::{Args, Dep, Service};
pub use crate::{
globals::{server_is_ours, user_is_local},
services::Services,
};
pub use crate::services::Services;
conduit::mod_ctor! {}
conduit::mod_dtor! {}

View file

@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
use tokio::{sync::Mutex, time::sleep};
use self::data::Data;
use crate::{user_is_local, users, Dep};
use crate::{globals, users, Dep};
/// Represents data required to be kept in order to implement the presence
/// specification.
@ -80,6 +80,7 @@ pub struct Service {
struct Services {
server: Arc<Server>,
globals: Dep<globals::Service>,
users: Dep<users::Service>,
}
@ -93,6 +94,7 @@ impl crate::Service for Service {
Ok(Arc::new(Self {
services: Services {
server: args.server.clone(),
globals: args.depend::<globals::Service>("globals"),
users: args.depend::<users::Service>("users"),
},
db: Data::new(&args),
@ -185,7 +187,7 @@ impl Service {
self.db
.set_presence(user_id, presence_state, currently_active, last_active_ago, status_msg)?;
if self.timeout_remote_users || user_is_local(user_id) {
if self.timeout_remote_users || self.services.globals.user_is_local(user_id) {
let timeout = match presence_state {
PresenceState::Online => self.services.server.config.presence_idle_timeout_s,
_ => self.services.server.config.presence_offline_timeout_s,

View file

@ -14,7 +14,7 @@ use ruma::{
};
use self::data::Data;
use crate::{admin, appservice, appservice::RegistrationInfo, globals, rooms, sending, server_is_ours, Dep};
use crate::{admin, appservice, appservice::RegistrationInfo, globals, rooms, sending, Dep};
pub struct Service {
db: Data,
@ -85,7 +85,10 @@ impl Service {
pub async fn resolve_alias(
&self, room_alias: &RoomAliasId, servers: Option<&Vec<OwnedServerName>>,
) -> Result<(OwnedRoomId, Option<Vec<OwnedServerName>>)> {
if !server_is_ours(room_alias.server_name())
if !self
.services
.globals
.server_is_ours(room_alias.server_name())
&& (!servers
.as_ref()
.is_some_and(|servers| servers.contains(&self.services.globals.server_name().to_owned()))
@ -195,7 +198,11 @@ impl Service {
pub async fn appservice_checks(
&self, room_alias: &RoomAliasId, appservice_info: &Option<RegistrationInfo>,
) -> Result<()> {
if !server_is_ours(room_alias.server_name()) {
if !self
.services
.globals
.server_is_ours(room_alias.server_name())
{
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server."));
}

View file

@ -12,7 +12,7 @@ use ruma::{
OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, ServerName, UserId,
};
use crate::{appservice::RegistrationInfo, globals, user_is_local, users, Dep};
use crate::{appservice::RegistrationInfo, globals, users, Dep};
type StrippedStateEventIter<'a> = Box<dyn Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnyStrippedStateEvent>>)>> + 'a>;
type AnySyncStateEventIter<'a> = Box<dyn Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnySyncStateEvent>>)>> + 'a>;
@ -355,7 +355,7 @@ impl Data {
Box::new(
self.room_members(room_id)
.filter_map(Result::ok)
.filter(|user| user_is_local(user)),
.filter(|user| self.services.globals.user_is_local(user)),
)
}

View file

@ -21,7 +21,7 @@ use ruma::{
OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, ServerName, UserId,
};
use crate::{account_data, appservice::RegistrationInfo, rooms, user_is_local, users, Dep};
use crate::{account_data, appservice::RegistrationInfo, globals, rooms, users, Dep};
pub struct Service {
services: Services,
@ -30,6 +30,7 @@ pub struct Service {
struct Services {
account_data: Dep<account_data::Service>,
globals: Dep<globals::Service>,
state_accessor: Dep<rooms::state_accessor::Service>,
users: Dep<users::Service>,
}
@ -39,6 +40,7 @@ impl crate::Service for Service {
Ok(Arc::new(Self {
services: Services {
account_data: args.depend::<account_data::Service>("account_data"),
globals: args.depend::<globals::Service>("globals"),
state_accessor: args.depend::<rooms::state_accessor::Service>("rooms::state_accessor"),
users: args.depend::<users::Service>("users"),
},
@ -65,7 +67,7 @@ impl Service {
// TODO: use futures to update remote profiles without blocking the membership
// update
#[allow(clippy::collapsible_if)]
if !user_is_local(user_id) {
if !self.services.globals.user_is_local(user_id) {
if !self.services.users.exists(user_id)? {
self.services.users.create(user_id, None)?;
}

View file

@ -41,7 +41,7 @@ use tokio::sync::RwLock;
use self::data::Data;
use crate::{
account_data, admin, appservice, appservice::NamespaceRegex, globals, pusher, rooms,
rooms::state_compressor::CompressedStateEvent, sending, server_is_ours, Dep,
rooms::state_compressor::CompressedStateEvent, sending, Dep,
};
// Update Relationships
@ -846,7 +846,7 @@ impl Service {
.state_cache
.room_members(room_id)
.filter_map(Result::ok)
.filter(|m| server_is_ours(m.server_name()) && m != target)
.filter(|m| self.services.globals.server_is_ours(m.server_name()) && m != target)
.count();
if count < 2 {
warn!("Last admin cannot leave from admins room");
@ -871,7 +871,7 @@ impl Service {
.state_cache
.room_members(room_id)
.filter_map(Result::ok)
.filter(|m| server_is_ours(m.server_name()) && m != target)
.filter(|m| self.services.globals.server_is_ours(m.server_name()) && m != target)
.count();
if count < 2 {
warn!("Last admin cannot be banned in admins room");
@ -1092,7 +1092,7 @@ impl Service {
.unwrap_or_default();
let room_mods = power_levels.users.iter().filter_map(|(user_id, level)| {
if level > &power_levels.users_default && !server_is_ours(user_id.server_name()) {
if level > &power_levels.users_default && !self.services.globals.user_is_local(user_id) {
Some(user_id.server_name().to_owned())
} else {
None
@ -1106,7 +1106,7 @@ impl Service {
.filter_map(|alias| {
alias
.ok()
.filter(|alias| !server_is_ours(alias.server_name()))
.filter(|alias| !self.services.globals.server_is_ours(alias.server_name()))
.map(|alias| alias.server_name().to_owned())
});
@ -1114,7 +1114,7 @@ impl Service {
.chain(room_alias_servers)
.chain(self.services.server.config.trusted_servers.clone())
.filter(|server_name| {
if server_is_ours(server_name) {
if self.services.globals.server_is_ours(server_name) {
return false;
}

View file

@ -8,7 +8,7 @@ use ruma::{
};
use tokio::sync::{broadcast, RwLock};
use crate::{globals, sending, user_is_local, Dep};
use crate::{globals, sending, Dep};
pub struct Service {
server: Arc<Server>,
@ -63,7 +63,7 @@ impl Service {
}
// update federation
if user_is_local(user_id) {
if self.services.globals.user_is_local(user_id) {
self.federation_send(room_id, user_id, true)?;
}
@ -89,7 +89,7 @@ impl Service {
}
// update federation
if user_is_local(user_id) {
if self.services.globals.user_is_local(user_id) {
self.federation_send(room_id, user_id, false)?;
}
@ -145,7 +145,7 @@ impl Service {
// update federation
for user in removable {
if user_is_local(&user) {
if self.services.globals.user_is_local(&user) {
self.federation_send(room_id, &user, false)?;
}
}
@ -184,7 +184,11 @@ impl Service {
}
fn federation_send(&self, room_id: &RoomId, user_id: &UserId, typing: bool) -> Result<()> {
debug_assert!(user_is_local(user_id), "tried to broadcast typing status of remote user",);
debug_assert!(
self.services.globals.user_is_local(user_id),
"tried to broadcast typing status of remote user",
);
if !self.server.config.allow_outgoing_typing {
return Ok(());
}

View file

@ -13,7 +13,7 @@ use ruma::{
};
use tokio::sync::Mutex;
use crate::{account_data, client, globals, presence, pusher, resolver, rooms, server_is_ours, users, Dep};
use crate::{account_data, client, globals, presence, pusher, resolver, rooms, users, Dep};
pub struct Service {
server: Arc<Server>,
@ -136,7 +136,7 @@ impl Service {
.state_cache
.room_servers(room_id)
.filter_map(Result::ok)
.filter(|server_name| !server_is_ours(server_name));
.filter(|server_name| !self.services.globals.server_is_ours(server_name));
self.send_pdu_servers(servers, pdu_id)
}
@ -185,7 +185,7 @@ impl Service {
.state_cache
.room_servers(room_id)
.filter_map(Result::ok)
.filter(|server_name| !server_is_ours(server_name));
.filter(|server_name| !self.services.globals.server_is_ours(server_name));
self.send_edu_servers(servers, serialized)
}
@ -222,7 +222,7 @@ impl Service {
.state_cache
.room_servers(room_id)
.filter_map(Result::ok)
.filter(|server_name| !server_is_ours(server_name));
.filter(|server_name| !self.services.globals.server_is_ours(server_name));
self.flush_servers(servers)
}

View file

@ -29,7 +29,6 @@ use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use tokio::time::sleep_until;
use super::{appservice, Destination, Msg, SendingEvent, Service};
use crate::user_is_local;
#[derive(Debug)]
enum TransactionStatus {
@ -264,7 +263,7 @@ impl Service {
.users
.keys_changed(room_id.as_ref(), since, None)
.filter_map(Result::ok)
.filter(|user_id| user_is_local(user_id)),
.filter(|user_id| self.services.globals.user_is_local(user_id)),
);
if self.server.config.allow_outgoing_read_receipts
@ -306,7 +305,7 @@ impl Service {
for (user_id, count, presence_bytes) in self.services.presence.presence_since(since) {
*max_edu_count = cmp::max(count, *max_edu_count);
if !user_is_local(&user_id) {
if !self.services.globals.user_is_local(&user_id) {
continue;
}
@ -358,7 +357,7 @@ impl Service {
let (user_id, count, read_receipt) = r?;
*max_edu_count = cmp::max(count, *max_edu_count);
if !user_is_local(&user_id) {
if !self.services.globals.user_is_local(&user_id) {
continue;
}