From a21b0918dc7946bec82fe14123d08d46497ada87 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Thu, 15 Oct 2026 05:17:59 +0000 Subject: [PATCH 001/342] chore(deps): update rust crate rustls to v0.23.46 [security] --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a718f824f..deac9fff4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5290,9 +5290,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "log", From 08301fba2abd967525db051b0d23094d4d830216 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Thu, 15 Oct 2026 11:22:04 +0100 Subject: [PATCH 002/342] fix: Correctly rebuild the build metadata crate when git changes --- src/build_metadata/build.rs | 71 ++++++++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 8 deletions(-) diff --git a/src/build_metadata/build.rs b/src/build_metadata/build.rs index b605b7578..8e99a85e1 100644 --- a/src/build_metadata/build.rs +++ b/src/build_metadata/build.rs @@ -1,5 +1,10 @@ use std::{ - collections::BTreeMap, env, fmt::Write as FmtWrite, fs, io::Write, path::Path, + collections::BTreeMap, + env, + fmt::Write as FmtWrite, + fs, + io::Write, + path::{Path, PathBuf}, process::Command, }; @@ -130,18 +135,68 @@ fn main() { } // --- Rerun Triggers --- - // TODO: The git rerun triggers seem to always run - // // Rerun if the git HEAD changes - // println!("cargo:rerun-if-changed=.git/HEAD"); - // // Rerun if the ref pointed to by HEAD changes (e.g., new commit on - // branch) if let Some(ref_path) = run_git_command(&["symbolic-ref", - // "--quiet", "HEAD"]) { println!("cargo:rerun-if-changed=.git/{ref_path}" - // ); } + let resolve_git_path = |path_str: &str| -> PathBuf { + let p = Path::new(path_str); + if p.is_absolute() { + p.to_path_buf() + } else { + Path::new(&manifest_dir).join(p) + } + }; + + // If workspace root has a .git file (e.g., git worktree or submodule), + // watch it + let workspace_git = metadata.workspace_root.as_std_path().join(".git"); + if workspace_git.is_file() { + println!("cargo:rerun-if-changed={}", workspace_git.display()); + } + + // Rerun if the git HEAD changes + if let Some(git_head) = run_git_command(&["rev-parse", "--git-path", "HEAD"]) { + let head_path = resolve_git_path(&git_head); + if head_path.exists() { + println!("cargo:rerun-if-changed={}", head_path.display()); + } + } + + // Rerun if the ref pointed to by HEAD changes (e.g., new commit on branch) + if let Some(ref_name) = run_git_command(&["symbolic-ref", "--quiet", "HEAD"]) { + if let Some(git_ref) = run_git_command(&["rev-parse", "--git-path", &ref_name]) { + let ref_path = resolve_git_path(&git_ref); + if ref_path.exists() { + println!("cargo:rerun-if-changed={}", ref_path.display()); + } else { + // If the loose ref file does not exist (e.g. refs are packed), + // watch the nearest existing ancestor directory + // so newly created refs trigger rerun. + let mut dir = ref_path.parent(); + while let Some(d) = dir { + if d.exists() { + println!("cargo:rerun-if-changed={}", d.display()); + break; + } + dir = d.parent(); + } + } + } + } + + // If packed-refs exists, watch it so git pack-refs or updates to packed + // refs trigger rerun + if let Some(git_packed) = run_git_command(&["rev-parse", "--git-path", "packed-refs"]) { + let packed_path = resolve_git_path(&git_packed); + if packed_path.exists() { + println!("cargo:rerun-if-changed={}", packed_path.display()); + } + } println!("cargo:rerun-if-env-changed=GIT_COMMIT_HASH"); println!("cargo:rerun-if-env-changed=GIT_COMMIT_HASH_SHORT"); println!("cargo:rerun-if-env-changed=GIT_REMOTE_URL"); println!("cargo:rerun-if-env-changed=GIT_REMOTE_COMMIT_URL"); + println!("cargo:rerun-if-env-changed=CONTINUWUITY_VERSION_EXTRA"); + println!("cargo:rerun-if-env-changed=CONDUWUIT_VERSION_EXTRA"); + println!("cargo:rerun-if-env-changed=CONDUIT_VERSION_EXTRA"); } fn generate_features_code(features: &BTreeMap>) -> String { From 4f21fa2bda3ad61ac82a910c8596183a223d0900 Mon Sep 17 00:00:00 2001 From: Ginger Date: Mon, 12 Oct 2026 11:12:49 -0400 Subject: [PATCH 003/342] refactor: Clean up join rule evaluation logic --- src/api/server/make_join.rs | 248 +++++------------- src/api/server/send_join.rs | 56 +++- src/service/antispam/mod.rs | 32 ++- src/service/rooms/membership/mod.rs | 388 +++++++++++++--------------- 4 files changed, 314 insertions(+), 410 deletions(-) diff --git a/src/api/server/make_join.rs b/src/api/server/make_join.rs index 411a322f5..f9776933c 100644 --- a/src/api/server/make_join.rs +++ b/src/api/server/make_join.rs @@ -1,29 +1,19 @@ -use std::{borrow::ToOwned, pin::pin}; - use axum::extract::State; -use conduwuit::{ - Err, Error, Result, debug, debug_info, info, matrix::pdu::PartialPdu, utils, warn, -}; -use conduwuit_service::Services; -use futures::StreamExt; +use conduwuit::{Err, Error, Result, info, matrix::pdu::PartialPdu, utils}; use ruma::{ - OwnedUserId, RoomId, UserId, + OwnedUserId, api::{ error::{ErrorKind, IncompatibleRoomVersionErrorData}, federation::membership::prepare_join_event, }, assign, - events::{ - StateEventType, - room::{ - join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent}, - member::{MembershipState, RoomMemberEventContent}, - }, + events::room::{ + join_rules::JoinRule, + member::{MembershipState, RoomMemberEventContent}, }, }; use serde_json::value::to_raw_value; -use service::rooms::state::RoomMutexGuard; -use tokio::join; +use service::rooms::membership::JoinConditionResult; use crate::Ruma; @@ -35,9 +25,6 @@ pub(crate) async fn create_join_event_template_route( State(services): State, body: Ruma, ) -> Result { - if !services.rooms.metadata.exists(&body.room_id).await { - return Err!(Request(NotFound("Room is unknown to this server."))); - } if !services .rooms .state_cache @@ -63,18 +50,6 @@ pub(crate) async fn create_join_event_template_route( .acl_check(&body.identity, &body.room_id) .await?; - if services - .moderation - .is_remote_server_forbidden(&body.identity) - { - warn!( - "Server {} for remote user {} tried joining room ID {} which has a server name that \ - is globally forbidden. Rejecting.", - body.identity, &body.user_id, &body.room_id, - ); - return Err!(Request(Forbidden("Server is banned on this homeserver."))); - } - let room_version = services.rooms.state.get_room_version(&body.room_id).await?; let room_version_rules = room_version.rules().unwrap(); if !body.ver.contains(&room_version) { @@ -87,41 +62,74 @@ pub(crate) async fn create_join_event_template_route( } let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await; - let (is_invited, is_joined) = join!( - services - .rooms - .state_cache - .is_invited(&body.user_id, &body.room_id), - services - .rooms - .state_cache - .is_joined(&body.user_id, &body.room_id) - ); + + let current_membership = services + .rooms + .state_accessor + .get_member(&body.room_id, &body.user_id) + .await + .ok() + .map_or_else(|| MembershipState::Leave, |content| content.membership); + let join_authorized_via_users_server: Option = { - if is_joined || is_invited { - // User is already joined or invited and consequently does not need - // an authorising user + if matches!( + current_membership, + MembershipState::Join | MembershipState::Invite | MembershipState::Knock + ) { + // User is already joined, invited, or knocked, and consequently + // does not need an authorising user None } else if !room_version_rules.authorization.restricted_join_rule { - // room version does not support restricted join rules + // Room version does not support restricted join rules None - } else if user_can_perform_restricted_join(&services, &body.user_id, &body.room_id) - .await? - { - Some( - select_authorising_user(&services, &body.room_id, &body.user_id, &state_lock) - .await?, - ) } else { - None + let join_rules = services + .rooms + .state_accessor + .get_join_rules(&body.room_id) + .await; + + if let JoinRule::Restricted(conditions) | JoinRule::KnockRestricted(conditions) = + join_rules + { + match services + .rooms + .membership + .evaluate_join_conditions(&body.room_id, &body.user_id, &conditions) + .await + { + | JoinConditionResult::Satisfied => { + // Try to find an authorizing user + services + .rooms + .membership + .select_authorizing_user(&body.room_id, &body.user_id, &state_lock) + .await + .map(Some)? + }, + | JoinConditionResult::Unsatisfied => { + return Err!(Request(Forbidden( + "You do not satisfy this room's join conditions." + ))); + }, + | JoinConditionResult::UnableToAuthorizeJoin => { + return Err!(Request(UnableToAuthorizeJoin( + "This server cannot check this room's join conditions." + ))); + }, + } + } else { + None + } } }; - if services.antispam.check_all_joins() && join_authorized_via_users_server.is_none() { + + if services.antispam.check_all_joins() { if services .antispam .meowlnir_accept_make_join(body.room_id.clone(), body.user_id.clone()) .await - .is_err() + != JoinConditionResult::Satisfied { return Err!(Request(Forbidden("Antispam rejected join request."))); } @@ -153,133 +161,3 @@ pub(crate) async fn create_join_event_template_route( }), ) } - -/// Attempts to find a user who is able to issue an invite in the target room. -pub(crate) async fn select_authorising_user<'a>( - services: &Services, - room_id: &'a RoomId, - user_id: &'a UserId, - state_lock: &'a RoomMutexGuard, -) -> Result { - let candidates = services.rooms.state_cache.local_users_in_room(room_id); - - let mut candidates = pin!(candidates); - - while let Some(candidate) = candidates.next().await { - if services - .rooms - .state_accessor - .user_can_invite(room_id, &candidate, user_id, state_lock) - .await - { - return Ok(candidate); - } - } - - Err!(Request(UnableToGrantJoin( - "No user on this server is able to assist in joining." - ))) -} - -/// Checks whether the given user can join the given room via a restricted join. -pub(crate) async fn user_can_perform_restricted_join( - services: &Services, - user_id: &UserId, - room_id: &RoomId, -) -> Result { - let Ok(join_rules_event_content) = services - .rooms - .state_accessor - .room_state_get_content::( - room_id, - &StateEventType::RoomJoinRules, - "", - ) - .await - else { - // No join rules means there's nothing to authorise (defaults to invite) - return Ok(false); - }; - - let (JoinRule::Restricted(r) | JoinRule::KnockRestricted(r)) = - join_rules_event_content.join_rule - else { - // This is not a restricted room - return Ok(false); - }; - - if r.allow.is_empty() { - // This will never be authorisable, return forbidden. - return Err!(Request(Forbidden("You are not invited to this room."))); - } - - let mut could_satisfy = true; - for allow_rule in &r.allow { - match allow_rule { - | AllowRule::RoomMembership(membership) => { - if !services - .rooms - .state_cache - .server_in_room(services.globals.server_name(), &membership.room_id) - .await - { - // Since we can't check this room, mark could_satisfy as - // false so that we can return - // M_UNABLE_TO_AUTHORIZE_JOIN later. - could_satisfy = false; - continue; - } - - if services - .rooms - .state_cache - .is_joined(user_id, &membership.room_id) - .await - { - debug!( - "User {} is allowed to join room {} via membership in room {}", - user_id, room_id, membership.room_id - ); - return Ok(true); - } - }, - | other if other.rule_type() == "fi.mau.spam_checker" => - return match services - .antispam - .meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned()) - .await - { - | Ok(()) => Ok(true), - | Err(_) => Err!(Request(Forbidden("Antispam rejected join request."))), - }, - | _ => { - // We don't recognise this join rule, so we cannot satisfy the - // request. - could_satisfy = false; - debug_info!( - "Unsupported allow rule in restricted join for room {}: {:?}", - room_id, - allow_rule - ); - }, - } - } - - if could_satisfy { - // We were able to check all the restrictions and can be certain that - // the prospective member is not permitted to join. - Err!(Request(Forbidden( - "You do not belong to any of the rooms or spaces required to join this room." - ))) - } else { - // We were unable to check all the restrictions. This usually means we - // aren't in one of the rooms this one is restricted to, ergo can't - // check its state for the user's membership, and consequently the - // user *might* be able to join if they ask another server. - Err!(Request(UnableToAuthorizeJoin( - "You do not belong to any of the recognised rooms or spaces required to join this \ - room, but this server is unable to verify every requirement. You may be able to \ - join via another server." - ))) - } -} diff --git a/src/api/server/send_join.rs b/src/api/server/send_join.rs index dd9b12e14..aa91957d0 100644 --- a/src/api/server/send_join.rs +++ b/src/api/server/send_join.rs @@ -16,9 +16,11 @@ use ruma::{ TimelineEventType, room::member::{MembershipState, RoomMemberEventContent}, }, + room::JoinRule, room_version_rules::RoomVersionRules, }; use serde_json::value::to_raw_value; +use service::rooms::membership::JoinConditionResult; use crate::{Ruma, server::utils::validate_any_membership_event}; @@ -108,18 +110,52 @@ async fn create_join_event( they cannot authorise your join." ))); } - if !super::user_can_perform_restricted_join(services, &sender, room_id).await? { - return Err!(Request(UnableToAuthorizeJoin( - "Joining user did not pass restricted room's rules." + + // If the user is invited or joined we don't need to check the join + // conditions, but in that case the requesting server shouldn't + // have set `join_authorized_via_users_server` in the first place. + + let join_rules = services.rooms.state_accessor.get_join_rules(room_id).await; + + if let JoinRule::Restricted(conditions) | JoinRule::KnockRestricted(conditions) = + join_rules + { + match services + .rooms + .membership + .evaluate_join_conditions(room_id, &sender, &conditions) + .await + { + | JoinConditionResult::Satisfied => { + // Sign the join to prove that we checked the conditions. + + services + .server_keys + .hash_and_sign_event(&mut pdu, room_version_rules) + .map_err(|e| { + err!(Request(InvalidParam(warn!( + "Failed to sign send_join event: {e}" + )))) + })?; + }, + | JoinConditionResult::Unsatisfied => { + return Err!(Request(Forbidden( + "You do not satisfy this room's join conditions." + ))); + }, + | JoinConditionResult::UnableToAuthorizeJoin => { + return Err!(Request(UnableToAuthorizeJoin( + "This server cannot check this room's join conditions." + ))); + }, + } + } else { + // We can't sign this, and if we don't sign it our event will fail + // the auth check, so we have to bail out here. + return Err!(Request(InvalidParam( + "join_authorized_via_users_server was supplied for a room that is not restricted" ))); } - - services - .server_keys - .hash_and_sign_event(&mut pdu, room_version_rules) - .map_err(|e| { - err!(Request(InvalidParam(warn!("Failed to sign send_join event: {e}")))) - })?; } let mutex_lock = services diff --git a/src/service/antispam/mod.rs b/src/service/antispam/mod.rs index 3e235e264..93eda539b 100644 --- a/src/service/antispam/mod.rs +++ b/src/service/antispam/mod.rs @@ -8,7 +8,7 @@ use ruma::{ }; use ruminuwuity::{draupnir_antispam, meowlnir_antispam}; -use crate::{client, config, sending, service::Dep}; +use crate::{client, config, rooms::membership::JoinConditionResult, sending, service::Dep}; struct Services { server: Arc, @@ -103,7 +103,7 @@ impl Service { } else { Ok(()) }; - self.record("user_may_invite", &result); + self.record("user_may_invite", if result.is_ok() { "allowed" } else { "denied" }); return result; } Ok(()) @@ -149,7 +149,7 @@ impl Service { } else { Ok(()) }; - self.record("user_may_join_room", &result); + self.record("user_may_join_room", if result.is_ok() { "allowed" } else { "denied" }); return result; } Ok(()) @@ -161,10 +161,10 @@ impl Service { &self, room_id: OwnedRoomId, user_id: OwnedUserId, - ) -> Result<()> { + ) -> JoinConditionResult { if let Some(Antispam { meowlnir: Some(meowlnir), .. }) = &self.services.config.antispam { debug!(?room_id, ?user_id, "Asking meowlnir for accept_make_join"); - let result = self + match self .send_antispam_request( meowlnir.base_url.as_str(), &meowlnir.secret, @@ -175,18 +175,24 @@ impl Service { ), ) .await - .inspect(|_| debug!("meowlnir allowed the make_join")) - .inspect_err(|e| debug!("meowlnir denied the make_join: {e:?}")) - .map(|_| ()); - self.record("accept_make_join", &result); - result + { + | Ok(_) => { + debug!("meowlnir allowed the make_join"); + self.record("accept_make_join", "allowed"); + JoinConditionResult::Satisfied + }, + | Err(err) => { + debug!("meowlnir denied the make_join: {err:?}"); + self.record("accept_make_join", "denied"); + JoinConditionResult::Unsatisfied + }, + } } else { - Ok(()) + JoinConditionResult::UnableToAuthorizeJoin } } - fn record(&self, check: &'static str, result: &Result) { - let outcome = if result.is_ok() { "allowed" } else { "denied" }; + fn record(&self, check: &'static str, outcome: &'static str) { self.services .server .metrics diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index 2f9a926c5..b8a2ed299 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -2,7 +2,6 @@ use std::{collections::HashMap, iter::once, sync::Arc}; use conduwuit::{ Err, Event, Pdu, Result, Server, debug, debug_info, debug_warn, defer, err, error, info, - is_true, matrix::{ StateKey, event::{gen_event_id, gen_event_id_canonical_json}, @@ -24,12 +23,9 @@ use ruma::{ canonical_json::to_canonical_value, events::{ StateEventType, StaticEventContent, - room::{ - join_rules::RoomJoinRulesEventContent, - member::{MembershipState, RoomMemberEventContent}, - }, + room::member::{MembershipState, RoomMemberEventContent}, }, - room::{AllowRule, JoinRule}, + room::{AllowRule, JoinRule, Restricted, RoomMembership}, }; use crate::{ @@ -44,6 +40,18 @@ use crate::{ sending, server_keys, sync, users, }; +#[derive(PartialEq, Eq)] +pub enum JoinConditionResult { + /// The local server verified that the user satisfies at least one join + /// condition. + Satisfied, + /// The local server verified that the user does not satisfy any join + /// conditions. + Unsatisfied, + /// The local server could not check all join conditions. + UnableToAuthorizeJoin, +} + pub struct Service { services: Services, } @@ -110,16 +118,36 @@ impl Service { ) -> Result { assert!(self.services.globals.user_is_local(sender_user), "user should be local"); + let servers: Vec<_> = servers + .iter() + .filter(|server| !self.services.globals.server_is_ours(server)) + .collect(); + let state_lock = self.services.state.mutex.lock(room_id).await; - if self + let server_in_room = self .services .state_cache - .is_joined(sender_user, room_id) - .await - { - debug_warn!("{sender_user} is already joined in {room_id}"); + .server_in_room(self.services.globals.server_name(), room_id) + .await; + + // Only check our known membership if we're already in the room. + // See: https://forgejo.ellis.link/continuwuation/continuwuity/issues/855 + let current_membership = if server_in_room { + self.services + .state_accessor + .get_member(room_id, sender_user) + .await + .ok() + .map_or_else(|| MembershipState::Leave, |content| content.membership) + } else { + MembershipState::Leave + }; + + if current_membership == MembershipState::Join { return Ok(room_id.to_owned()); + } else if current_membership == MembershipState::Ban { + return Err!(Request(Forbidden("You are banned from this room."))); } if let Err(e) = self @@ -137,31 +165,16 @@ impl Service { { warn!("Antispam prevented user {} from joining room {}: {}", sender_user, room_id, e); return Err!(Request(Forbidden("You are not allowed to join this room."))); - } - - let server_in_room = self - .services - .state_cache - .server_in_room(self.services.globals.server_name(), room_id) - .await; - - // Only check our known membership if we're already in the room. - // See: https://forgejo.ellis.link/continuwuation/continuwuity/issues/855 - let membership = if server_in_room { - self.services - .state_accessor - .get_member(room_id, sender_user) + } else if self.services.antispam.check_all_joins() { + if self + .services + .antispam + .meowlnir_accept_make_join(room_id.to_owned(), sender_user.to_owned()) .await - } else { - debug!("Ignoring local state for join {room_id}, we aren't in the room yet."); - Ok(RoomMemberEventContent::new(MembershipState::Leave)) - }; - - if let Ok(m) = membership { - if m.membership == MembershipState::Ban { - debug_warn!("{sender_user} is banned from {room_id} but attempted to join"); - // TODO: return reason - return Err!(Request(Forbidden("You are banned from the room."))); + != JoinConditionResult::Satisfied + { + warn!("Antispam prevented user {} from joining room {}", sender_user, room_id); + return Err!(Request(Forbidden("Antispam rejected join request."))); } } @@ -172,31 +185,38 @@ impl Service { ))); } - if self.services.antispam.check_all_joins() { - if let Err(e) = self - .services - .antispam - .meowlnir_accept_make_join(room_id.to_owned(), sender_user.to_owned()) + if server_in_room { + // Try to join the room locally. + match self + .join_local_room( + sender_user, + room_id, + current_membership, + reason.clone(), + &state_lock, + ) + .boxed() .await { - warn!( - "Antispam prevented user {} from joining room {}: {}", - sender_user, room_id, e - ); - return Err!(Request(Forbidden("Antispam rejected join request."))); + | Ok(()) => { + // We were able to authorize a local join. + info!("Joined room locally"); + return Ok(room_id.to_owned()); + }, + | Err(err) => { + // We couldn't authorize a local join, probably because it's + // restricted and we couldn't satisfy + // the join rules ourselves. + info!(?err, "Failed to join room locally, trying over federation instead"); + }, } } - if server_in_room { - self.join_local_room(sender_user, room_id, reason, servers, state_lock) - .boxed() - .await?; - } else { - // Ask a remote server if we are not participating in this room - self.join_remote_room(sender_user, room_id, reason, servers, state_lock) - .boxed() - .await?; - } + // If we aren't participating in the room, or failed to join locally, + // try to join over federation. + self.join_remote_room(sender_user, room_id, reason, &servers, &state_lock) + .boxed() + .await?; Ok(room_id.to_owned()) } @@ -206,39 +226,39 @@ impl Service { &self, sender_user: &UserId, room_id: &RoomId, + current_membership: MembershipState, reason: Option, - servers: &[OwnedServerName], - state_lock: RoomMutexGuard, + state_lock: &RoomMutexGuard, ) -> Result { info!("Joining room locally"); - let (room_version, join_rules, is_invited) = join!( + let (room_version, join_rules) = join!( self.services.state.get_room_version(room_id), self.services.state_accessor.get_join_rules(room_id), - self.services.state_cache.is_invited(sender_user, room_id) ); let room_version = room_version?; let room_version_rules = room_version.rules().unwrap(); let mut auth_user: Option = None; - if !is_invited - && matches!(join_rules, JoinRule::Restricted(_) | JoinRule::KnockRestricted(_)) + + if !matches!(current_membership, MembershipState::Invite | MembershipState::Knock) + && let JoinRule::Restricted(conditions) | JoinRule::KnockRestricted(conditions) = + &join_rules { if room_version_rules.authorization.restricted_join_rule { // This is a restricted room, check if we can complete the join // requirements locally. - let needs_auth_user = self - .user_can_perform_restricted_join(sender_user, room_id) - .await; - if needs_auth_user.is_ok_and(is_true!()) { - // If there was an error or the value is false, we'll try - // joining over federation. Since it's Ok(true), we can - // authorise this locally. If we can't select a local - // user, this will remain None, the join will fail, and - // we'll fall back to federation. + if self + .evaluate_join_conditions(room_id, sender_user, conditions) + .await + == JoinConditionResult::Satisfied + { + // Try to find an authorizing user. If we can't find one, + // the local join will fail to authorize and we'll fall back + // to federation. auth_user = self - .select_authorising_user(room_id, sender_user, &state_lock) + .select_authorizing_user(room_id, sender_user, state_lock) .await .ok(); } @@ -251,54 +271,27 @@ impl Service { content.reason.clone_from(&reason); content.join_authorized_via_users_server = auth_user; - // Try normal join first - let Err(error) = self - .services + self.services .timeline .build_and_append_pdu( PartialPdu::state(sender_user.to_string(), &content), sender_user, Some(room_id), - &state_lock, + state_lock, ) - .await - else { - info!("Joined room locally"); - return Ok(()); - }; + .await?; - if servers.is_empty() - || servers.len() == 1 && self.services.globals.server_is_ours(&servers[0]) - { - if !self.services.metadata.exists(room_id).await { - return Err!(Request( - Unknown( - "Room was not found locally and no servers were found to help us \ - discover it" - ), - NOT_FOUND - )); - } - - return Err(error); - } - - info!( - ?error, - remote_servers = %servers.len(), - "Could not join room locally, attempting remote join", - ); - Box::pin(self.join_remote_room(sender_user, room_id, reason, servers, state_lock)).await + Ok(()) } #[tracing::instrument(skip_all, fields(%sender_user, %room_id), name = "join_remote_room", level = "info")] - pub async fn join_remote_room( + async fn join_remote_room( &self, sender_user: &UserId, room_id: &RoomId, reason: Option, - servers: &[OwnedServerName], - state_lock: RoomMutexGuard, + servers: &[&OwnedServerName], + state_lock: &RoomMutexGuard, ) -> Result { // public so the admin command force-join-room-remotely works info!("Joining {room_id} over federation."); @@ -657,7 +650,7 @@ impl Service { debug!("Forcing state for new room"); self.services .state - .force_state(room_id, statehash_before_join, added, removed, &state_lock) + .force_state(room_id, statehash_before_join, added, removed, state_lock) .await?; debug!("Updating joined counts for new room"); @@ -679,7 +672,7 @@ impl Service { &parsed_join_pdu, join_event, once(parsed_join_pdu.event_id.as_ref()), - &state_lock, + state_lock, room_id, ) .await?; @@ -694,7 +687,7 @@ impl Service { // exist self.services .state - .set_room_state(room_id, statehash_after_join, &state_lock); + .set_room_state(room_id, statehash_after_join, state_lock); if !resident_before { // NOTE: We replace local extremities for this room if we were not a // resident before. We might be doing a remote join to satisfy @@ -704,7 +697,7 @@ impl Service { info!("Replacing local forward extremities"); self.services .state - .set_forward_extremities(room_id, once(parsed_join_pdu.event_id()), &state_lock) + .set_forward_extremities(room_id, once(parsed_join_pdu.event_id()), state_lock) .await; } drop(cork); @@ -722,7 +715,7 @@ impl Service { &self, sender_user: &UserId, room_id: &RoomId, - servers: &[OwnedServerName], + servers: &[&OwnedServerName], ) -> Result<(federation::membership::prepare_join_event::v1::Response, OwnedServerName)> { let mut make_join_counter: usize = 1; @@ -762,7 +755,7 @@ impl Service { warn!("make_join response from {remote_server} failed validation: {e}"); continue; } - return Ok((response, remote_server.clone())); + return Ok((response, (*remote_server).clone())); }, | Err(e) => match e.kind() { | ErrorKind::UnableToAuthorizeJoin => { @@ -810,7 +803,7 @@ impl Service { /// Attempts to find a user who is able to issue an invite in the target /// room. - pub async fn select_authorising_user<'a>( + pub async fn select_authorizing_user<'a>( &self, room_id: &'a RoomId, user_id: &'a UserId, @@ -838,108 +831,99 @@ impl Service { /// Checks whether the given user can join the given room via a restricted /// join. - pub(crate) async fn user_can_perform_restricted_join( + pub async fn evaluate_join_conditions( &self, - user_id: &UserId, room_id: &RoomId, - ) -> Result { - let Ok(join_rules_event_content) = self - .services - .state_accessor - .room_state_get_content::( - room_id, - &StateEventType::RoomJoinRules, - "", - ) - .await - else { - // No join rules means there's nothing to authorise (defaults to - // invite) - return Ok(false); - }; - - let (JoinRule::Restricted(r) | JoinRule::KnockRestricted(r)) = - join_rules_event_content.join_rule - else { - // This is not a restricted room - return Ok(false); - }; - - if r.allow.is_empty() { + user_id: &UserId, + conditions: &Restricted, + ) -> JoinConditionResult { + if conditions.allow.is_empty() { // This will never be authorisable, return forbidden. - return Err!(Request(Forbidden("You are not invited to this room."))); + return JoinConditionResult::Unsatisfied; } - let mut could_satisfy = true; - for allow_rule in &r.allow { - match allow_rule { - | AllowRule::RoomMembership(membership) => { - if !self - .services - .state_cache - .server_in_room(self.services.globals.server_name(), &membership.room_id) - .await - { - // Since we can't check this room, mark could_satisfy as - // false so that we can return - // M_UNABLE_TO_AUTHORIZE_JOIN later. - could_satisfy = false; - continue; - } + let mut unable_to_authorize = false; - if self - .services - .state_cache - .is_joined(user_id, &membership.room_id) - .await - { - debug!( - "User {} is allowed to join room {} via membership in room {}", - user_id, room_id, membership.room_id - ); - return Ok(true); - } + for rule in &conditions.allow { + match self.evaluate_allow_rule(room_id, user_id, rule).await { + | JoinConditionResult::Satisfied => { + // This allow rule is satisfied, the user can join. + return JoinConditionResult::Satisfied; }, - | other if other.rule_type() == "fi.mau.spam_checker" => - return match self - .services - .antispam - .meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned()) - .await - { - | Ok(()) => Ok(true), - | Err(_) => Err!(Request(Forbidden("Antispam rejected join request."))), - }, - | _ => { - // We don't recognise this join rule, so we cannot satisfy - // the request. - could_satisfy = false; - debug_info!( - "Unsupported allow rule in restricted join for room {}: {:?}", - room_id, - allow_rule - ); + | JoinConditionResult::Unsatisfied => { + // This allow rule is not satisfied, but the user might be + // able to join if they satisfy another + // rule. Keep checking. + continue; + }, + | JoinConditionResult::UnableToAuthorizeJoin => { + // We couldn't check this allow rule, but the user might be + // able to join if they satisfy another + // rule. Keep checking. + unable_to_authorize = true; + continue; }, } } - if could_satisfy { - // We were able to check all the restrictions and can be certain - // that the prospective member is not permitted to join. - Err!(Request(Forbidden( - "You do not belong to any of the rooms or spaces required to join this room." - ))) + if unable_to_authorize { + // We couldn't conclusively determine if the user satisfies some + // rules. + JoinConditionResult::UnableToAuthorizeJoin } else { - // We were unable to check all the restrictions. This usually means - // we aren't in one of the rooms this one is restricted to, ergo - // can't check its state for the user's membership, and - // consequently the user *might* be able to join if - // they ask another server. - Err!(Request(UnableToAuthorizeJoin( - "You do not belong to any of the recognised rooms or spaces required to join \ - this room, but this server is unable to verify every requirement. You may be \ - able to join via another server." - ))) + // We determined that the user does not satisfy any rules. + JoinConditionResult::Unsatisfied + } + } + + async fn evaluate_allow_rule( + &self, + room_id: &RoomId, + user_id: &UserId, + rule: &AllowRule, + ) -> JoinConditionResult { + match rule { + | AllowRule::RoomMembership(RoomMembership { room_id: condition_room, .. }) => { + if self + .services + .state_cache + .server_in_room(self.services.globals.server_name(), condition_room) + .await + { + if self + .services + .state_cache + .is_joined(user_id, condition_room) + .await + { + debug!( + ?user_id, + ?room_id, + ?condition_room, + "User may join via membership in {condition_room}" + ); + JoinConditionResult::Satisfied + } else { + JoinConditionResult::Unsatisfied + } + } else { + JoinConditionResult::UnableToAuthorizeJoin + } + }, + | other if other.rule_type() == "fi.mau.spam_checker" => + self.services + .antispam + .meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned()) + .await, + | unknown => { + debug!( + ?user_id, + ?room_id, + rule_type = unknown.rule_type(), + "Could not check unknown allow rule" + ); + JoinConditionResult::UnableToAuthorizeJoin + }, } } } From e6ca06a501ac3601b0bbe3a1f26c18cbc0798b49 Mon Sep 17 00:00:00 2001 From: Ginger Date: Mon, 12 Oct 2026 14:13:15 -0400 Subject: [PATCH 004/342] feat: Add support for MSC4560 --- Cargo.lock | 22 +- Cargo.toml | 5 +- changelog.d/+01d550e6.feature.md | 3 + src/api/client/room/mod.rs | 5 +- src/api/client/room/stripped_state.rs | 71 ++++++ src/api/client/room/summary.rs | 9 +- src/api/router.rs | 2 + src/api/server/make_join.rs | 8 +- src/api/server/mod.rs | 2 + src/api/server/send_join.rs | 8 +- src/api/server/stripped_state.rs | 54 +++++ src/core/matrix/versions.rs | 2 + src/service/rooms/membership/mod.rs | 68 ++++-- src/service/rooms/summary/mod.rs | 326 +++++++++++++++++++------- 14 files changed, 460 insertions(+), 125 deletions(-) create mode 100644 changelog.d/+01d550e6.feature.md create mode 100644 src/api/client/room/stripped_state.rs create mode 100644 src/api/server/stripped_state.rs diff --git a/Cargo.lock b/Cargo.lock index deac9fff4..6d72cea40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5019,7 +5019,7 @@ dependencies = [ [[package]] name = "ruma" version = "0.17.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "assign", "js_int", @@ -5038,7 +5038,7 @@ dependencies = [ [[package]] name = "ruma-appservice-api" version = "0.17.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "http", "js_int", @@ -5051,7 +5051,7 @@ dependencies = [ [[package]] name = "ruma-client-api" version = "0.25.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "as_variant", "assign", @@ -5073,7 +5073,7 @@ dependencies = [ [[package]] name = "ruma-common" version = "0.20.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "as_variant", "base64 0.23.1", @@ -5106,7 +5106,7 @@ dependencies = [ [[package]] name = "ruma-events" version = "0.35.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "as_variant", "indexmap 2.14.2", @@ -5127,7 +5127,7 @@ dependencies = [ [[package]] name = "ruma-federation-api" version = "0.16.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "bytes", "http", @@ -5149,7 +5149,7 @@ dependencies = [ [[package]] name = "ruma-identifiers-validation" version = "0.12.1" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "js_int", "thiserror 2.0.21", @@ -5158,7 +5158,7 @@ dependencies = [ [[package]] name = "ruma-macros" version = "0.20.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "as_variant", "cfg-if", @@ -5174,7 +5174,7 @@ dependencies = [ [[package]] name = "ruma-push-gateway-api" version = "0.16.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "js_int", "ruma-common", @@ -5186,7 +5186,7 @@ dependencies = [ [[package]] name = "ruma-signatures" version = "0.22.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "base64 0.23.1", "ed25519-dalek 3.0.0", @@ -5203,7 +5203,7 @@ dependencies = [ [[package]] name = "ruma-state-res" version = "0.18.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" dependencies = [ "js_int", "ruma-common", diff --git a/Cargo.toml b/Cargo.toml index fc1b2ef88..c70d5de05 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -347,8 +347,8 @@ version = "1.1.1" # Used for matrix spec type definitions and helpers [workspace.dependencies.ruma] -git = "https://github.com/ruma/ruma.git" -rev = "f5e5e1c885f598036fd4326c566e9d1928027d5d" +git = "https://github.com/gingershaped/ruwuma.git" +rev = "ef98d8d0b111f563fab960c3f696493979fba3a7" features = [ "appservice-api-c", "client-api", @@ -388,6 +388,7 @@ features = [ "unstable-msc4494", "unstable-msc4484", "unstable-msc4540", + "unstable-msc4560", "unstable-extensible-events", ] diff --git a/changelog.d/+01d550e6.feature.md b/changelog.d/+01d550e6.feature.md new file mode 100644 index 000000000..bb9a865ac --- /dev/null +++ b/changelog.d/+01d550e6.feature.md @@ -0,0 +1,3 @@ +Implemented unstable support for [MSC4560] (Stripped state requests over federation). Contributed by @ginger. + +[MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 diff --git a/src/api/client/room/mod.rs b/src/api/client/room/mod.rs index e249e18b6..1d3125d3e 100644 --- a/src/api/client/room/mod.rs +++ b/src/api/client/room/mod.rs @@ -2,11 +2,12 @@ mod aliases; mod create; mod event; mod initial_sync; +mod stripped_state; mod summary; mod upgrade; pub(crate) use self::{ aliases::get_room_aliases_route, create::create_room_route, event::get_room_event_route, - initial_sync::room_initial_sync_route, summary::get_room_summary, - upgrade::upgrade_room_route, + initial_sync::room_initial_sync_route, stripped_state::get_stripped_state_route, + summary::get_room_summary, upgrade::upgrade_room_route, }; diff --git a/src/api/client/room/stripped_state.rs b/src/api/client/room/stripped_state.rs new file mode 100644 index 000000000..d30655721 --- /dev/null +++ b/src/api/client/room/stripped_state.rs @@ -0,0 +1,71 @@ +use axum::extract::State; +use conduwuit::{Err, Result}; +use ruma::{ + api::client::state::get_stripped_state, assign, events::ALLOWED_STRIPPED_STATE_EVENTS, +}; +use service::rooms::summary::{Accessibility, RoomStrippedState}; + +use crate::{Ruma, router::ClientIdentity}; + +/// # `POST /_matrix/client/unstable/org.continuwuity.msc4560.stripped_state/{room_id_or_alias}` ([MSC4560]) +/// +/// Returns a room's stripped state. +/// +/// [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +#[tracing::instrument(skip_all, name = "stripped_state", level = "info")] +pub(crate) async fn get_stripped_state_route( + State(services): State, + body: Ruma, +) -> Result { + let user_id = body.identity.as_ref().and_then(ClientIdentity::sender_user); + + if body.via.len() > get_stripped_state::unstable::MAX_VIAS { + return Err!(Request(TooLarge("Too many vias, please be less indecisive."))); + } + + if let Some(forbidden_type) = body + .state + .iter() + .find(|event_type| !ALLOWED_STRIPPED_STATE_EVENTS.contains(event_type)) + { + return Err!(Request(InvalidParam( + "Event type {forbidden_type} may not be requested as stripped state." + ))); + } + + let (room_id, _) = services + .rooms + .alias + .resolve_with_servers(&body.room_id_or_alias, Some(body.via.clone())) + .await?; + + if services.rooms.metadata.is_banned(&room_id).await { + return Err!(Request(Forbidden("This room is banned on this homeserver."))); + } + + match services + .rooms + .summary + .get_stripped_state_for_user( + user_id, + &room_id, + &body.via, + &body.state, + body.num_joined_members, + ) + .await + { + | Accessibility::Accessible(( + via, + RoomStrippedState { state, num_joined_members, .. }, + )) => Ok( + assign!(get_stripped_state::unstable::Response::new(via), { state, num_joined_members }), + ), + | Accessibility::Inaccessible => { + Err!(Request(Forbidden("You may not request this room's stripped state."))) + }, + | Accessibility::NotFound => { + Err!(Request(NotFound("This room does not exist."))) + }, + } +} diff --git a/src/api/client/room/summary.rs b/src/api/client/room/summary.rs index da6958242..836dba890 100644 --- a/src/api/client/room/summary.rs +++ b/src/api/client/room/summary.rs @@ -13,7 +13,7 @@ pub(crate) async fn get_room_summary( State(services): State, body: Ruma, ) -> Result { - let (room_id, servers) = services + let (room_id, _) = services .rooms .alias .resolve_with_servers(&body.room_id_or_alias, Some(body.via.clone())) @@ -27,12 +27,9 @@ pub(crate) async fn get_room_summary( .rooms .summary .get_room_summary_for_user( - body.identity - .as_ref() - .map(ClientIdentity::expect_sender_user) - .transpose()?, + body.identity.as_ref().and_then(ClientIdentity::sender_user), &room_id, - &servers, + &body.via, ) .await?; diff --git a/src/api/router.rs b/src/api/router.rs index 5fbe21134..09681c0b1 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -184,6 +184,7 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&client::get_mutual_rooms_unstable_route) .ruma_route(&client::get_mutual_rooms_route) .ruma_route(&client::get_room_summary) + .ruma_route(&client::get_stripped_state_route) .ruma_route(&client::get_suspended_status) .ruma_route(&client::put_suspended_status) .ruma_route(&client::get_lock_status) @@ -229,6 +230,7 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&server::get_keys_route) .ruma_route(&server::claim_keys_route) .ruma_route(&server::get_hierarchy_route) + .ruma_route(&server::get_stripped_state_route) .ruma_route(&server::well_known_server) .ruma_route(&server::get_content_route) .ruma_route(&server::get_content_thumbnail_route) diff --git a/src/api/server/make_join.rs b/src/api/server/make_join.rs index f9776933c..dcb74d433 100644 --- a/src/api/server/make_join.rs +++ b/src/api/server/make_join.rs @@ -13,7 +13,7 @@ use ruma::{ }, }; use serde_json::value::to_raw_value; -use service::rooms::membership::JoinConditionResult; +use service::rooms::membership::{JoinConditionEntity, JoinConditionResult}; use crate::Ruma; @@ -95,7 +95,11 @@ pub(crate) async fn create_join_event_template_route( match services .rooms .membership - .evaluate_join_conditions(&body.room_id, &body.user_id, &conditions) + .evaluate_join_conditions( + &body.room_id, + JoinConditionEntity::User(&body.user_id), + &conditions, + ) .await { | JoinConditionResult::Satisfied => { diff --git a/src/api/server/mod.rs b/src/api/server/mod.rs index 5c1ff3f79..b115ccabb 100644 --- a/src/api/server/mod.rs +++ b/src/api/server/mod.rs @@ -18,6 +18,7 @@ pub(super) mod send_knock; pub(super) mod send_leave; pub(super) mod state; pub(super) mod state_ids; +pub(super) mod stripped_state; pub(super) mod user; pub(super) mod version; pub(super) mod well_known; @@ -42,6 +43,7 @@ pub(super) use send_knock::*; pub(super) use send_leave::*; pub(super) use state::*; pub(super) use state_ids::*; +pub(super) use stripped_state::*; pub(super) use user::*; pub(super) use version::*; pub(super) use well_known::*; diff --git a/src/api/server/send_join.rs b/src/api/server/send_join.rs index aa91957d0..d25fd8156 100644 --- a/src/api/server/send_join.rs +++ b/src/api/server/send_join.rs @@ -20,7 +20,7 @@ use ruma::{ room_version_rules::RoomVersionRules, }; use serde_json::value::to_raw_value; -use service::rooms::membership::JoinConditionResult; +use service::rooms::membership::{JoinConditionEntity, JoinConditionResult}; use crate::{Ruma, server::utils::validate_any_membership_event}; @@ -123,7 +123,11 @@ async fn create_join_event( match services .rooms .membership - .evaluate_join_conditions(room_id, &sender, &conditions) + .evaluate_join_conditions( + room_id, + JoinConditionEntity::User(&sender), + &conditions, + ) .await { | JoinConditionResult::Satisfied => { diff --git a/src/api/server/stripped_state.rs b/src/api/server/stripped_state.rs new file mode 100644 index 000000000..9680583ce --- /dev/null +++ b/src/api/server/stripped_state.rs @@ -0,0 +1,54 @@ +use axum::extract::State; +use conduwuit::{Err, Result}; +use ruma::{ + api::federation::event::get_stripped_state, assign, events::ALLOWED_STRIPPED_STATE_EVENTS, +}; +use service::rooms::summary::{Accessibility, RoomStrippedState}; + +use crate::Ruma; + +/// # `POST /_matrix/federation/unstable/org.continuwuity.msc4560.stripped_state/{room_id}` ([MSC4560]) +/// +/// Returns a room's stripped state. +/// +/// [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +pub(crate) async fn get_stripped_state_route( + State(services): State, + body: Ruma, +) -> Result { + if let Some(forbidden_type) = body + .state + .iter() + .find(|event_type| !ALLOWED_STRIPPED_STATE_EVENTS.contains(event_type)) + { + return Err!(Request(InvalidParam( + "Event type {forbidden_type} may not be requested as stripped state." + ))); + } + + if services.rooms.metadata.is_banned(&body.room_id).await { + return Err!(Request(Forbidden("This room is banned on this homeserver."))); + } + + match services + .rooms + .summary + .get_local_stripped_state_for_server( + &body.identity, + &body.room_id, + &body.state, + body.num_joined_members, + ) + .await + { + | Accessibility::Accessible(RoomStrippedState { state, num_joined_members, .. }) => Ok( + assign!(get_stripped_state::unstable::Response::default(), { state, num_joined_members }), + ), + | Accessibility::Inaccessible => { + Err!(Request(Forbidden("You may not access this room's stripped state."))) + }, + | Accessibility::NotFound => { + Err!(Request(NotFound("This room is not known to this server."))) + }, + } +} diff --git a/src/core/matrix/versions.rs b/src/core/matrix/versions.rs index ae681e3ca..3ea538b62 100644 --- a/src/core/matrix/versions.rs +++ b/src/core/matrix/versions.rs @@ -50,5 +50,7 @@ pub fn unstable_features() -> BTreeMap { ("uk.timedout.msc4494".to_owned(), true), // server administration OAuth scope (https://github.com/matrix-org/matrix-spec-proposals/pull/4484) ("org.continuwuity.msc4484.unstable".to_owned(), true), + // stripped state over federation (https://github.com/matrix-org/matrix-spec-proposals/pull/4560) + ("org.continuwuity.msc4560".to_owned(), true), ]) } diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index b8a2ed299..5445b15ac 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -15,7 +15,7 @@ use database::Database; use futures::{FutureExt, StreamExt, TryFutureExt, join}; use ruma::{ CanonicalJsonObject, CanonicalJsonValue, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, - RoomVersionId, UserId, + RoomVersionId, ServerName, UserId, api::{ error::{ErrorKind, IncompatibleRoomVersionErrorData}, federation, @@ -52,6 +52,20 @@ pub enum JoinConditionResult { UnableToAuthorizeJoin, } +#[derive(Copy, Clone, Debug)] +pub enum JoinConditionEntity<'id> { + User(&'id UserId), + Server(&'id ServerName), +} + +impl<'id> From<&'id UserId> for JoinConditionEntity<'id> { + fn from(value: &'id UserId) -> Self { Self::User(value) } +} + +impl<'id> From<&'id ServerName> for JoinConditionEntity<'id> { + fn from(value: &'id ServerName) -> Self { Self::Server(value) } +} + pub struct Service { services: Services, } @@ -250,7 +264,7 @@ impl Service { // This is a restricted room, check if we can complete the join // requirements locally. if self - .evaluate_join_conditions(room_id, sender_user, conditions) + .evaluate_join_conditions(room_id, sender_user.into(), conditions) .await == JoinConditionResult::Satisfied { @@ -834,7 +848,7 @@ impl Service { pub async fn evaluate_join_conditions( &self, room_id: &RoomId, - user_id: &UserId, + entity: JoinConditionEntity<'_>, conditions: &Restricted, ) -> JoinConditionResult { if conditions.allow.is_empty() { @@ -845,7 +859,7 @@ impl Service { let mut unable_to_authorize = false; for rule in &conditions.allow { - match self.evaluate_allow_rule(room_id, user_id, rule).await { + match self.evaluate_allow_rule(room_id, entity, rule).await { | JoinConditionResult::Satisfied => { // This allow rule is satisfied, the user can join. return JoinConditionResult::Satisfied; @@ -879,7 +893,7 @@ impl Service { async fn evaluate_allow_rule( &self, room_id: &RoomId, - user_id: &UserId, + entity: JoinConditionEntity<'_>, rule: &AllowRule, ) -> JoinConditionResult { match rule { @@ -890,17 +904,25 @@ impl Service { .server_in_room(self.services.globals.server_name(), condition_room) .await { - if self - .services - .state_cache - .is_joined(user_id, condition_room) - .await - { + let is_joined = match entity { + | JoinConditionEntity::User(user_id) => + self.services + .state_cache + .is_joined(user_id, condition_room) + .await, + | JoinConditionEntity::Server(server) => + self.services + .state_cache + .server_in_room(server, room_id) + .await, + }; + + if is_joined { debug!( - ?user_id, + ?entity, ?room_id, ?condition_room, - "User may join via membership in {condition_room}" + "Entity may join via membership" ); JoinConditionResult::Satisfied } else { @@ -910,14 +932,22 @@ impl Service { JoinConditionResult::UnableToAuthorizeJoin } }, - | other if other.rule_type() == "fi.mau.spam_checker" => - self.services - .antispam - .meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned()) - .await, + | other if other.rule_type() == "fi.mau.spam_checker" => { + if let JoinConditionEntity::User(user_id) = entity { + self.services + .antispam + .meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned()) + .await + } else { + // We can't currently check server names against the spam + // checker, so we just assume that they + // can't access the room for now. + JoinConditionResult::Unsatisfied + } + }, | unknown => { debug!( - ?user_id, + ?entity, ?room_id, rule_type = unknown.rule_type(), "Could not check unknown allow rule" diff --git a/src/service/rooms/summary/mod.rs b/src/service/rooms/summary/mod.rs index f2d56eb52..014e2fa57 100644 --- a/src/service/rooms/summary/mod.rs +++ b/src/service/rooms/summary/mod.rs @@ -1,4 +1,8 @@ -use std::{collections::HashSet, sync::Arc}; +use std::{ + collections::{BTreeSet, HashSet}, + pin::pin, + sync::Arc, +}; use conduwuit::{ Err, Event, Result, debug, info, @@ -10,18 +14,27 @@ use ruma::{ OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, ServerName, UInt, UserId, api::{ client::space::SpaceHierarchyRoomsChunk, - federation::space::{SpaceHierarchyParentSummary, get_hierarchy}, + error::ErrorKind, + federation::{ + event::get_stripped_state, + space::{SpaceHierarchyParentSummary, get_hierarchy}, + }, }, assign, events::{ - StateEventType, + AnyStrippedStateEvent, StateEventType, + room::member::MembershipState, space::child::{HierarchySpaceChildEvent, SpaceChildEventContent}, }, - room::{JoinRuleSummary, RestrictedSummary, RoomSummary, RoomType}, + room::{JoinRule, RoomSummary, RoomType}, serde::Raw, }; -use crate::{Dep, rooms, sending}; +use crate::{ + Dep, globals, + rooms::{self, membership::JoinConditionResult}, + sending, +}; pub struct Service { services: Services, @@ -29,7 +42,8 @@ pub struct Service { struct Services { event_handler: Dep, - metadata: Dep, + globals: Dep, + membership: Dep, sending: Dep, state: Dep, state_accessor: Dep, @@ -57,13 +71,21 @@ struct SpaceChild { 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"), - metadata: args.depend::("rooms::metadata"), + globals: args.depend::("globals"), + membership: args.depend::("rooms::membership"), sending: args.depend::("sending"), state: args.depend::("rooms::state"), state_accessor: args @@ -92,7 +114,7 @@ impl Service { summary } else if let Some((SpaceHierarchyParentSummary { summary, .. }, _)) = - self.fetch_remote_summary(room_id, via, false).await? + self.fetch_remote_room_summary(room_id, via, false).await { // A via has this room. @@ -105,7 +127,7 @@ impl Service { }; // Check if the room is visible to the querying user. - if !self.user_may_see_summary(querying_user, &summary).await { + if !self.user_may_see_summary(querying_user, room_id).await { return Ok(Accessibility::Inaccessible); } @@ -138,8 +160,8 @@ impl Service { SpaceHierarchyParentSummary { summary, children_state, .. }, inaccessible_children, )) = self - .fetch_remote_summary(room_id, via, suggested_only) - .await? + .fetch_remote_room_summary(room_id, via, suggested_only) + .await { // A via has this room. @@ -152,10 +174,7 @@ impl Service { }; // Check if the room is visible to the querying user. - if !self - .user_may_see_summary(querying_user, &summary.summary) - .await - { + if !self.user_may_see_summary(querying_user, room_id).await { return Ok(Accessibility::Inaccessible); } @@ -312,7 +331,7 @@ impl Service { }; // Check if the server can see the root room's summary - if !self.server_may_see_summary(querying_server, &summary).await { + if !self.server_may_see_summary(querying_server, room_id).await { return Accessibility::Inaccessible; } @@ -331,7 +350,10 @@ impl Service { .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, &summary).await { + if self + .server_may_see_summary(querying_server, &child.state_key) + .await + { Accessibility::Accessible(summary) } else { Accessibility::Inaccessible @@ -439,20 +461,14 @@ impl Service { } /// Query remote servers for the summary of a room. - async fn fetch_remote_summary( + async fn fetch_remote_room_summary( &self, room_id: &RoomId, via: &[OwnedServerName], suggested_only: bool, - ) -> Result)>> { - if self.services.metadata.is_disabled(room_id).await { - return Err!(Request(Forbidden("This room is blocked by this server."))); - } - + ) -> Option<(SpaceHierarchyParentSummary, Vec)> { if via.is_empty() { - return Err!(Request(MissingParam( - "No servers were provided with which to query this room's summary." - ))); + return None; } info!(%room_id, ?via, "Asking for room summary over federation"); @@ -477,7 +493,7 @@ impl Service { } info!(%room_id, %server, "Got room summary"); - return Ok(Some((room, inaccessible_children))); + return Some((room, inaccessible_children)); }, | Err(err) => { info!(%room_id, %server, %err, "Server could not provide a summary for this room"); @@ -486,7 +502,7 @@ impl Service { } info!(%room_id, "No servers queried could provide a summary for this room"); - Ok(None) + None } /// Get the stripped m.space.child events of a room. @@ -536,54 +552,207 @@ impl Service { .await } + 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 + } + } + + 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 + } + } + + 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 }) + } + + 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)) => { + return Accessibility::Accessible((server, RoomStrippedState { + state: response.state, + num_joined_members: response.num_joined_members, + })); + }, + | Accessibility::Inaccessible => { + got_inaccessible = true; + }, + | Accessibility::NotFound => { + 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>, - summary: &RoomSummary, + room_id: &RoomId, ) -> bool { // Anyone can view the summary of world-readable rooms. - if summary.world_readable { - return true; - } - - // If the user is joined or invited they may always view the summary. - if let Some(querying_user) = querying_user - && (self - .services - .state_cache - .is_joined(querying_user, &summary.room_id) - .await - || self - .services - .state_cache - .is_invited(querying_user, &summary.room_id) - .await) + 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. - match (&summary.join_rule, querying_user) { + 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. - | ( - JoinRuleSummary::Public - | JoinRuleSummary::Knock - | JoinRuleSummary::KnockRestricted(_), - _, - ) => true, + | (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're in one of the allowed rooms. - | ( - JoinRuleSummary::Restricted(RestrictedSummary { allowed_room_ids, .. }), - Some(querying_user), - ) => + // aren't invited, provided they fulfill the join rules. + | (JoinRule::Restricted(conditions), Some(querying_user)) => self.services - .state_cache - .rooms_joined(querying_user) - .ready_any(|room_id| allowed_room_ids.contains(&room_id)) - .await, + .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, @@ -594,13 +763,13 @@ impl Service { async fn server_may_see_summary( &self, querying_server: &ServerName, - summary: &RoomSummary, + room_id: &RoomId, ) -> bool { // Servers may not see summaries of rooms they're ACLed from. if self .services .event_handler - .acl_check(querying_server, &summary.room_id) + .acl_check(querying_server, room_id) .await .is_err() { @@ -613,32 +782,27 @@ impl Service { if self .services .state_cache - .server_in_room(querying_server, &summary.room_id) + .server_in_room(querying_server, room_id) .await { return true; } - // For restricted rooms, federation responses must include the summary - // when a user on the querying server can satisfy one of the join - // conditions. - if let JoinRuleSummary::Restricted(RestrictedSummary { allowed_room_ids, .. }) = - &summary.join_rule - { - for room_id in allowed_room_ids { - 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, summary).await + self.user_may_see_summary(None, room_id).await } } From 98c694eaa3e5507a0ee4a9bf27b663ad12e0da74 Mon Sep 17 00:00:00 2001 From: Ginger Date: Mon, 12 Oct 2026 14:36:51 -0400 Subject: [PATCH 005/342] chore: Add some comments --- src/service/rooms/summary/mod.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/service/rooms/summary/mod.rs b/src/service/rooms/summary/mod.rs index 014e2fa57..96f633e93 100644 --- a/src/service/rooms/summary/mod.rs +++ b/src/service/rooms/summary/mod.rs @@ -552,6 +552,7 @@ impl Service { .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>, @@ -575,6 +576,7 @@ impl Service { } } + /// Prepares the stripped state of a local room for a server. pub async fn get_local_stripped_state_for_server( &self, querying_server: &ServerName, @@ -596,6 +598,8 @@ impl Service { } } + /// 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, @@ -650,6 +654,7 @@ impl Service { 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, @@ -686,15 +691,24 @@ impl Service { 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; }, } From 138dd61f82c41816bf2977a7d42a291e81f08413 Mon Sep 17 00:00:00 2001 From: Ginger Date: Thu, 15 Oct 2026 22:51:02 -0400 Subject: [PATCH 006/342] chore: Switch to upstream ruma --- Cargo.lock | 22 +++++++++++----------- Cargo.toml | 4 ++-- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6d72cea40..4d0d21836 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5019,7 +5019,7 @@ dependencies = [ [[package]] name = "ruma" version = "0.17.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "assign", "js_int", @@ -5038,7 +5038,7 @@ dependencies = [ [[package]] name = "ruma-appservice-api" version = "0.17.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "http", "js_int", @@ -5051,7 +5051,7 @@ dependencies = [ [[package]] name = "ruma-client-api" version = "0.25.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "as_variant", "assign", @@ -5073,7 +5073,7 @@ dependencies = [ [[package]] name = "ruma-common" version = "0.20.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "as_variant", "base64 0.23.1", @@ -5106,7 +5106,7 @@ dependencies = [ [[package]] name = "ruma-events" version = "0.35.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "as_variant", "indexmap 2.14.2", @@ -5127,7 +5127,7 @@ dependencies = [ [[package]] name = "ruma-federation-api" version = "0.16.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "bytes", "http", @@ -5149,7 +5149,7 @@ dependencies = [ [[package]] name = "ruma-identifiers-validation" version = "0.12.1" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "js_int", "thiserror 2.0.21", @@ -5158,7 +5158,7 @@ dependencies = [ [[package]] name = "ruma-macros" version = "0.20.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "as_variant", "cfg-if", @@ -5174,7 +5174,7 @@ dependencies = [ [[package]] name = "ruma-push-gateway-api" version = "0.16.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "js_int", "ruma-common", @@ -5186,7 +5186,7 @@ dependencies = [ [[package]] name = "ruma-signatures" version = "0.22.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "base64 0.23.1", "ed25519-dalek 3.0.0", @@ -5203,7 +5203,7 @@ dependencies = [ [[package]] name = "ruma-state-res" version = "0.18.0" -source = "git+https://github.com/gingershaped/ruwuma.git?rev=ef98d8d0b111f563fab960c3f696493979fba3a7#ef98d8d0b111f563fab960c3f696493979fba3a7" +source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" dependencies = [ "js_int", "ruma-common", diff --git a/Cargo.toml b/Cargo.toml index c70d5de05..7bce7584b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -347,8 +347,8 @@ version = "1.1.1" # Used for matrix spec type definitions and helpers [workspace.dependencies.ruma] -git = "https://github.com/gingershaped/ruwuma.git" -rev = "ef98d8d0b111f563fab960c3f696493979fba3a7" +git = "https://github.com/ruma/ruma.git" +rev = "62659d64f712adf3cad126df6b8969f785414bd5" features = [ "appservice-api-c", "client-api", From ab939da0362370e97c42ca00e2702a53e0b0d6bd Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Fri, 16 Oct 2026 05:02:46 +0000 Subject: [PATCH 007/342] chore(deps): update rust to v1.99.1 --- rust-toolchain.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 8965f816a..c84026107 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -10,7 +10,7 @@ [toolchain] profile = "minimal" -channel = "1.99.0" +channel = "1.99.1" components = [ # For rust-analyzer "rust-src", From a973f3e10c4ff4476f77e4ba49c536b91d54daa2 Mon Sep 17 00:00:00 2001 From: renovate Date: Fri, 16 Oct 2026 05:07:35 +0000 Subject: [PATCH 008/342] chore(Nix): Updated flake hashes --- nix/rust.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/rust.nix b/nix/rust.nix index 0d4ee40a4..53800cbe0 100644 --- a/nix/rust.nix +++ b/nix/rust.nix @@ -12,7 +12,7 @@ target: target.fromToolchainName { name = (lib.importTOML "${inputs.self}/rust-toolchain.toml").toolchain.channel; - sha256 = "sha256-zm3dyIY2T414ZRR3EhLOvptzG6gta4WZUcawzMUWtqI="; + sha256 = "sha256-+xUr6Al1wZSqX8aEsq7DpuFOK4Ve/i+qTl+K5uWQ9GM="; }; in { From fe02b03d15ac20ac10a859e8ce679a61f700b3f0 Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 16 Oct 2026 18:11:55 +0100 Subject: [PATCH 009/342] style: Stop warning when encountering an unknown event in get_missing_events This is actually an expected condition, but it's retained as a debug warning as it may be relevant in debugging --- src/api/server/get_missing_events.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/server/get_missing_events.rs b/src/api/server/get_missing_events.rs index 7c5b8799f..a1c9b0496 100644 --- a/src/api/server/get_missing_events.rs +++ b/src/api/server/get_missing_events.rs @@ -1,7 +1,7 @@ use std::collections::{HashSet, VecDeque}; use axum::extract::State; -use conduwuit::{Err, Event, Result, debug, info, trace, utils::to_canonical_object, warn}; +use conduwuit::{debug, debug_warn, info, trace, utils::to_canonical_object, Err, Event, Result}; use ruma::{OwnedEventId, api::federation::event::get_missing_events}; use serde_json::value::RawValue; use service::rooms::event_handler::GET_MISSING_EVENTS_MAX_BATCH_SIZE; @@ -64,7 +64,7 @@ pub(crate) async fn get_missing_events_route( let mut pdu = match services.rooms.timeline.get_pdu(&next_event_id).await { | Ok(pdu) => pdu, | Err(e) => { - warn!("could not find event {next_event_id} while walking missing events: {e}"); + debug_warn!("could not find event {next_event_id} while walking missing events: {e}"); continue; }, }; From 17ddd3966d8e3c5749119b63803c9e52248e8341 Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 16 Oct 2026 18:19:22 +0100 Subject: [PATCH 010/342] fix: Apply proper limits to get_missing_events --- src/api/server/get_missing_events.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/api/server/get_missing_events.rs b/src/api/server/get_missing_events.rs index a1c9b0496..335e8fc09 100644 --- a/src/api/server/get_missing_events.rs +++ b/src/api/server/get_missing_events.rs @@ -1,7 +1,7 @@ use std::collections::{HashSet, VecDeque}; use axum::extract::State; -use conduwuit::{debug, debug_warn, info, trace, utils::to_canonical_object, Err, Event, Result}; +use conduwuit::{Err, Event, Result, debug, debug_warn, info, trace, utils::to_canonical_object}; use ruma::{OwnedEventId, api::federation::event::get_missing_events}; use serde_json::value::RawValue; use service::rooms::event_handler::GET_MISSING_EVENTS_MAX_BATCH_SIZE; @@ -44,6 +44,13 @@ pub(crate) async fn get_missing_events_route( .unwrap_or(10) .min(GET_MISSING_EVENTS_MAX_BATCH_SIZE); + if body.latest_events.len() > limit { + return Err!(Request(InvalidParam("Too many latest_events"))); + } + if body.earliest_events.len() > limit { + return Err!(Request(InvalidParam("Too many earliest_events"))); + } + let room_version = services.rooms.state.get_room_version(&body.room_id).await?; let mut queue: VecDeque = VecDeque::from(body.latest_events.clone()); @@ -64,7 +71,9 @@ pub(crate) async fn get_missing_events_route( let mut pdu = match services.rooms.timeline.get_pdu(&next_event_id).await { | Ok(pdu) => pdu, | Err(e) => { - debug_warn!("could not find event {next_event_id} while walking missing events: {e}"); + debug_warn!( + "could not find event {next_event_id} while walking missing events: {e}" + ); continue; }, }; @@ -74,6 +83,10 @@ pub(crate) async fn get_missing_events_route( body.room_id ))); } + if pdu.depth < body.min_depth { + debug!(%next_event_id, %pdu.depth, %body.min_depth, "event is below minimum depth, not traversing"); + continue; + } if services .rooms .pdu_metadata From b0a5caf57606b34baa94afc5f348d0484f5c0f3b Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 16 Oct 2026 18:32:38 +0100 Subject: [PATCH 011/342] perf: Fetch auth chain events in parallel --- src/api/server/event_auth.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/api/server/event_auth.rs b/src/api/server/event_auth.rs index 5cd49b834..f4ed82f6d 100644 --- a/src/api/server/event_auth.rs +++ b/src/api/server/event_auth.rs @@ -1,7 +1,10 @@ use std::{borrow::Borrow, iter::once}; use axum::extract::State; -use conduwuit::{Err, Event, Result, info, utils::stream::ReadyExt}; +use conduwuit::{ + Err, Event, Result, info, + utils::stream::{BroadbandExt, ReadyExt}, +}; use futures::StreamExt; use ruma::api::federation::authorization::get_event_authorization; @@ -64,7 +67,9 @@ pub(crate) async fn get_event_authorization_route( .auth_chain .event_ids_iter(&body.room_id, once(body.event_id.borrow())) .ready_filter_map(Result::ok) - .filter_map(|id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() }) + .broad_filter_map( + |id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() }, + ) .then(|pdu| services.sending.convert_to_outgoing_federation_event(pdu)) .collect() .await; From d72a27b249e5cae33597288914809432cf0123e7 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 19 Oct 2026 05:19:59 +0000 Subject: [PATCH 012/342] chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.167.5 --- .forgejo/workflows/renovate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/renovate.yml b/.forgejo/workflows/renovate.yml index d9e688b05..135e282a3 100644 --- a/.forgejo/workflows/renovate.yml +++ b/.forgejo/workflows/renovate.yml @@ -43,7 +43,7 @@ jobs: name: Renovate runs-on: ubuntu-latest container: - image: ghcr.io/renovatebot/renovate:44.151.2@sha256:29b3bf193f855c6f4b7027395a9c66c3417ad8bb6f30458090e1c2363d04eef7 + image: ghcr.io/renovatebot/renovate:44.167.5@sha256:0474cd0a251ec76d6dddfd64945d2c21aecd6fb35af9e0d5d883f2cc5a7cef32 options: --tmpfs /tmp:exec steps: - name: Checkout From 2f93711a0969bb858fe5faa032c683096c82c333 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 20 Oct 2026 05:17:52 +0000 Subject: [PATCH 013/342] chore(deps): update https://github.com/taiki-e/install-action digest to 8cca091 --- .forgejo/actions/timelord/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/actions/timelord/action.yml b/.forgejo/actions/timelord/action.yml index b03254be0..b545769b2 100644 --- a/.forgejo/actions/timelord/action.yml +++ b/.forgejo/actions/timelord/action.yml @@ -71,7 +71,7 @@ runs: - name: Install timelord-cli and git-warp-time if: steps.check-binaries.outputs.need-install == 'true' - uses: https://github.com/taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2 + uses: https://github.com/taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2 with: tool: git-warp-time,timelord-cli@3.0.1 From 783a68cc904667f4f0b5f635f7f1a01e0724e26b Mon Sep 17 00:00:00 2001 From: Ginger Date: Wed, 21 Oct 2026 18:27:42 -0400 Subject: [PATCH 014/342] fix: Add link to the account management panel to the first run web UI --- src/web/pages/templates/index.html.j2 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/web/pages/templates/index.html.j2 b/src/web/pages/templates/index.html.j2 index cf0c97b0f..54a41d702 100644 --- a/src/web/pages/templates/index.html.j2 +++ b/src/web/pages/templates/index.html.j2 @@ -11,8 +11,9 @@

Continuwuity is successfully installed and working.

{%- if first_run %} -

To get started, check the server logs for instructions on how to create the first account.

+

To get started, create the first account through your Matrix client or through Continuwuity.

For support, take a look at the documentation or join the Continuwuity Matrix room.

+

Create the first account

{%- else %}

To get started, choose a client and connect to {{ server_name }}.

Manage your account

From 4a20fd62a935be6d9d6d52391106ad9b66936459 Mon Sep 17 00:00:00 2001 From: Ginger Date: Wed, 21 Oct 2026 18:29:30 -0400 Subject: [PATCH 015/342] chore: News fragment --- changelog.d/+8da3c370.feature.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/+8da3c370.feature.md diff --git a/changelog.d/+8da3c370.feature.md b/changelog.d/+8da3c370.feature.md new file mode 100644 index 000000000..b561f4e97 --- /dev/null +++ b/changelog.d/+8da3c370.feature.md @@ -0,0 +1 @@ +The first-run version of the web UI now includes a link to the registration page. Contributed by @ginger From 3b2afe03ac5439b4bb9c1c9dc242cbbe14e860e6 Mon Sep 17 00:00:00 2001 From: Filip Kszczot Date: Tue, 6 Oct 2026 16:13:07 +0200 Subject: [PATCH 016/342] docs(deploying/generic): add haproxy host header quirk Signed-off-by: Filip Kszczot --- docs/deploying/generic.mdx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/deploying/generic.mdx b/docs/deploying/generic.mdx index cbcac08ac..0dafb150a 100644 --- a/docs/deploying/generic.mdx +++ b/docs/deploying/generic.mdx @@ -199,6 +199,11 @@ header, making federation non-functional. If you find a workaround, please share Furthermore, Nginx users need to increase the `client_max_body_size` setting (default is 1M) to match the `max_request_size` defined in conduwuit.toml. +- For HAProxy, ensure that the ACL for the `Host` header matches both the domain and the domain with the port, as federation requests are often sent with the port included. This can be done by using the `host_only` directive: + ``` + acl matrix-host hdr(host),host_only -i example.com + ``` + ## Starting Your Server Now you can start Continuwuity with: From c5b70958cfe44ff26cb02860917f8e7becc1b654 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 23 Oct 2026 23:19:45 +0200 Subject: [PATCH 017/342] fix: preserve event order during state resolution Signed-off-by: Erwan Leboucher --- changelog.d/+state-res-auth-order.bugfix.md | 1 + src/core/matrix/state_res/mod.rs | 66 ++++++++++++++++++++- 2 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+state-res-auth-order.bugfix.md diff --git a/changelog.d/+state-res-auth-order.bugfix.md b/changelog.d/+state-res-auth-order.bugfix.md new file mode 100644 index 000000000..cbb961545 --- /dev/null +++ b/changelog.d/+state-res-auth-order.bugfix.md @@ -0,0 +1 @@ +Fix state resolution applying events out of order, which could undo room joins. Contributed by @eleboucher. diff --git a/src/core/matrix/state_res/mod.rs b/src/core/matrix/state_res/mod.rs index 77948c323..2a6b2fde1 100644 --- a/src/core/matrix/state_res/mod.rs +++ b/src/core/matrix/state_res/mod.rs @@ -39,7 +39,7 @@ use crate::{ debug, debug_error, err, matrix::{Event, StateKey}, trace, - utils::stream::{BroadbandExt, IterStream, ReadyExt, TryBroadbandExt, WidebandExt}, + utils::stream::{BroadbandExt, IterStream, ReadyExt, TryWidebandExt, WidebandExt}, warn, }; @@ -706,7 +706,7 @@ where let events_to_check: Vec<_> = events_to_check .map(Result::Ok) - .broad_and_then(async |event_id| { + .wide_and_then(async |event_id| { fetch_event(event_id.to_owned()) .await .ok_or_else(|| Error::NotFound(format!("Failed to find {event_id}"))) @@ -1123,6 +1123,68 @@ mod tests { utils::stream::IterStream, }; + #[tokio::test] + async fn iterative_auth_check_keeps_event_order() { + let mut events = INITIAL_EVENTS(); + let initial_state = ["CREATE", "IPOWER", "IJR", "IMB"] + .into_iter() + .map(|id| { + let event = &events[&event_id(id)]; + ( + event + .event_type() + .with_state_key(event.state_key().unwrap()), + event.event_id.clone(), + ) + }) + .collect(); + let leave = to_pdu_event( + "LEAVE", + bob(), + TimelineEventType::RoomMember, + Some(bob().as_str()), + to_raw_json_value(&json!({ "membership": "leave" })).unwrap(), + &["CREATE", "IPOWER", "IMB"], + &["IMB"], + ); + let rejoin = to_pdu_event( + "REJOIN", + bob(), + TimelineEventType::RoomMember, + Some(bob().as_str()), + member_content_join(), + &["CREATE", "IPOWER", "IJR", "LEAVE"], + &["LEAVE"], + ); + let ordered_events = [leave.event_id.clone(), rejoin.event_id.clone()]; + for event in [leave, rejoin] { + events.insert(event.event_id.clone(), event); + } + let fetcher = |id: OwnedEventId| { + let events = &events; + async move { + // Let the rejoin fetch finish before the leave. + if id == event_id("LEAVE") { + tokio::task::yield_now().await; + } + events.get(&id).cloned() + } + }; + let resolved = super::iterative_auth_check( + &RoomVersionRules::V6, + ordered_events.iter().map(AsRef::as_ref).stream(), + initial_state, + &fetcher, + ) + .await + .unwrap(); + + assert_eq!( + resolved[&StateEventType::RoomMember.with_state_key(bob().as_str())], + event_id("REJOIN"), + ); + } + /// Events at the start of a room have no `m.room.power_levels` in their /// auth events, so the sender's power for sort ordering comes from the /// create event instead. From 9c27441acf2e65f85c106ccff5c6b6c37030ddca Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 23 Oct 2026 23:37:51 +0200 Subject: [PATCH 018/342] style: Reformat with nightly --- src/core/config/mod.rs | 4 +- src/core/matrix/state_res/mod.rs | 4 +- src/service/client/mod.rs | 4 +- src/service/migrations.rs | 50 ++++++++++--------- .../fetch_and_handle_outliers.rs | 4 +- src/service/rooms/summary/mod.rs | 8 +-- src/service/rooms/timeline/create.rs | 3 +- src/service/threepid/mod.rs | 5 +- src/web/mod.rs | 3 +- src/web/pages/components/form.rs | 11 ++-- src/web/pages/mod.rs | 7 +-- 11 files changed, 56 insertions(+), 47 deletions(-) diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 36baee18d..d5318c9a8 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -65,8 +65,8 @@ use crate::{Result, err, error::Error, utils::sys}; ignore = "config_paths catchall" )] pub struct Config { - // Paths to config file(s). Not supposed to be set manually in the config file, - // only updated dynamically from the --config option given at runtime. + // Paths to config file(s). Not supposed to be set manually in the config + // file, only updated dynamically from the --config option given at runtime. pub config_paths: Option>, /// The server_name is the pretty name of this server. It is used as a diff --git a/src/core/matrix/state_res/mod.rs b/src/core/matrix/state_res/mod.rs index 2a6b2fde1..a48860ac3 100644 --- a/src/core/matrix/state_res/mod.rs +++ b/src/core/matrix/state_res/mod.rs @@ -590,8 +590,8 @@ where .find(|aev| is_type_and_key(*aev, &TimelineEventType::RoomPowerLevels, "")); let content: PowerLevelsContentFields = match pl { - // With no m.room.power_levels in scope the create event's defaults apply, - // under which the room creator holds 100 and everyone else 0. + // With no m.room.power_levels in scope the create event's defaults + // apply, under which the room creator holds 100 and everyone else 0. | None => return Ok(if sender_is_creator { int!(100) } else { int!(0) }), | Some(ev) => from_json_str(ev.content().get())?, }; diff --git a/src/service/client/mod.rs b/src/service/client/mod.rs index fc139a144..234b50956 100644 --- a/src/service/client/mod.rs +++ b/src/service/client/mod.rs @@ -146,8 +146,8 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(2)) .build()?, - // MSC4174 recommends against following redirects, since the destination - // is only checked before the request is sent. + // MSC4174 recommends against following redirects, since the + // destination is only checked before the request is sent. webpush: base(config)? .connect_timeout(Duration::from_secs(config.pusher_conn_timeout)) .timeout(Duration::from_secs(config.pusher_timeout)) diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 894dd5aa3..3ed2d28a4 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -109,35 +109,37 @@ migration!(stringify!($name) => $name) migration!(fix_readreceiptid_readreceipt_duplicates), // End pre-fork logic. - // v18: `fix_corrupt_msc4133_fields` will change the `us.cloke.msc4175.tz` field - // in a way that old versions don't understand. + // v18: `fix_corrupt_msc4133_fields` will change the + // `us.cloke.msc4175.tz` field in a way that old versions don't + // understand. VersionBump(18), migration!(fix_corrupt_msc4133_fields), - // v19: `populate_userroomid_leftstate_table` will put data in the values of - // `userroomid_leftstate` that old versions will fail to deserialize because - // they expect the values to be empty. + // v19: `populate_userroomid_leftstate_table` will put data in the + // values of `userroomid_leftstate` that old versions will fail to + // deserialize because they expect the values to be empty. VersionBump(19), migration!(populate_userroomid_leftstate_table), - // This is backwards compatible because it fixes some data that clients care about but we - // don't. + // This is backwards compatible because it fixes some data that clients + // care about but we don't. migration!(fix_local_invite_state), - // v20: Old versions expect remote users to be tracked in `userid_password`. This - // migration moves them to a different keyspace. + // v20: Old versions expect remote users to be tracked in + // `userid_password`. This migration moves them to a different keyspace. VersionBump(20), migration!(split_userid_password), - // This is backwards compatible because old versions will recreate the keyspace if it's - // missing. + // This is backwards compatible because old versions will recreate the + // keyspace if it's missing. migration!("drop_roomsynctoken_shortstatehash" => obliterate_roomsynctoken_shortstatehash_with_extreme_prejudice), - // v21: `unembed_unsigned_info` will remove `unsigned` data from PDUs that old versions - // expect to be embedded. + // v21: `unembed_unsigned_info` will remove `unsigned` data from PDUs + // that old versions expect to be embedded. VersionBump(21), - // This migration can take several hours on old databases, so we run it in the background - // to keep the service manager from killing us for taking too long to start. - // Future maintainers: !!! BE VERY CAREFUL !!! if you need to write more migrations like - // this! This one is fine because it deletes data that we don't check anymore, - // but migrations which replace existing data that we do check should NOT run in - // the background. If they do, the server will finish starting up and might - // access data that the migration hasn't gotten to yet. + // This migration can take several hours on old databases, so we run it + // in the background to keep the service manager from killing us for + // taking too long to start. Future maintainers: !!! BE VERY CAREFUL !!! + // if you need to write more migrations like this! This one is fine + // because it deletes data that we don't check anymore, but migrations + // which replace existing data that we do check should NOT run in + // the background. If they do, the server will finish starting up and + // might access data that the migration hasn't gotten to yet. Migration("unembed_unsigned_info", |services| { Box::pin(async { if services.db["global"] @@ -158,11 +160,11 @@ migration!(stringify!($name) => $name) Ok(()) }) }), - // This is backwards compatible because old versions will recreate the keyspace if it's - // missing. + // This is backwards compatible because old versions will recreate the + // keyspace if it's missing. migration!(drop_server_signingkeys), - // v22: Old versions will fail to deserialize the fixed OAuth scope names, - // preventing users from signing in. + // v22: Old versions will fail to deserialize the fixed OAuth scope + // names, preventing users from signing in. VersionBump(22), migration!(fix_oauth_scope_names), ] diff --git a/src/service/rooms/event_handler/fetch_and_handle_outliers.rs b/src/service/rooms/event_handler/fetch_and_handle_outliers.rs index 3fbe57c30..38a25b914 100644 --- a/src/service/rooms/event_handler/fetch_and_handle_outliers.rs +++ b/src/service/rooms/event_handler/fetch_and_handle_outliers.rs @@ -203,8 +203,8 @@ impl super::Service { "GET_MISSING_EVENTS_MAX_BATCH_SIZE (usize) should fit in u16 (<=65536)", )) .max( - // This max call ensures we fetch *at least* all the prev events the - // head has. + // This max call ensures we fetch *at least* all the prev + // events the head has. u16::try_from(head.prev_events.len()) .expect("cannot have more than 20 prev events, which fits in u16"), ); diff --git a/src/service/rooms/summary/mod.rs b/src/service/rooms/summary/mod.rs index 96f633e93..4c2e21e86 100644 --- a/src/service/rooms/summary/mod.rs +++ b/src/service/rooms/summary/mod.rs @@ -756,11 +756,13 @@ impl Service { 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. + // 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. + // 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 diff --git a/src/service/rooms/timeline/create.rs b/src/service/rooms/timeline/create.rs index 2f33db721..1e7284492 100644 --- a/src/service/rooms/timeline/create.rs +++ b/src/service/rooms/timeline/create.rs @@ -193,7 +193,8 @@ impl super::Service { let redacts = match redacts { // If this isn't a real redaction event, there's no redacts field. | _ if event_type != TimelineEventType::RoomRedaction || state_key.is_some() => None, - // If the redaction is itself in the event content, we don't set the top-level field. + // If the redaction is itself in the event content, we don't set the + // top-level field. | Some(_) if room_version_rules.redaction.content_field_redacts => None, // Otherwise, we do if it's present | other => other, diff --git a/src/service/threepid/mod.rs b/src/service/threepid/mod.rs index db0d08d9f..7e4ffa968 100644 --- a/src/service/threepid/mod.rs +++ b/src/service/threepid/mod.rs @@ -124,8 +124,9 @@ impl Service { let mut sessions = self.sessions.lock().await; let session = match sessions.get_session_by_client_secret(client_secret) { - // If a validation session already exists for this client secret, we can either - // reuse it with a new token or return early because it's already valid. + // If a validation session already exists for this client secret, we + // can either reuse it with a new token or return early because it's + // already valid. | Some(session) => { if session.email != recipient.email { return Err!(Request(InvalidParam("Wrong email for session."))); diff --git a/src/web/mod.rs b/src/web/mod.rs index ac881c26b..43dab6746 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -94,7 +94,8 @@ impl IntoResponse for WebError { error: self, status, context: TemplateContext { - // Statically set false to prevent error pages from being indexed. + // Statically set false to prevent error pages from being + // indexed. allow_indexing: false, csp_nonce: String::new(), }, diff --git a/src/web/pages/components/form.rs b/src/web/pages/components/form.rs index 55b07bda3..4880efd6c 100644 --- a/src/web/pages/components/form.rs +++ b/src/web/pages/components/form.rs @@ -48,11 +48,12 @@ pub(crate) struct FormInput<'a> { pub autocomplete: &'a str, // This is a hack to make the form! macro's support for client-only fields - // work properly. Client-only fields are specified in the macro without a type and aren't - // included in the POST body or as a field in the generated struct. - // To keep the field from being included in the POST body, its `name` property needs not to - // be set in the template. Because of limitations of macro_rules!'s repetition feature, this - // field needs to exist to allow the template to check if the field is client-only. + // work properly. Client-only fields are specified in the macro without a + // type and aren't included in the POST body or as a field in the generated + // struct. To keep the field from being included in the POST body, its + // `name` property needs not to be set in the template. Because of + // limitations of macro_rules!'s repetition feature, this field needs to + // exist to allow the template to check if the field is client-only. #[doc(hidden)] pub type_name: Option<&'static str>, } diff --git a/src/web/pages/mod.rs b/src/web/pages/mod.rs index a9c169810..28a442785 100644 --- a/src/web/pages/mod.rs +++ b/src/web/pages/mod.rs @@ -61,9 +61,10 @@ pub(super) async fn template_context_middleware( response.headers_mut().insert( header::CONTENT_SECURITY_POLICY, HeaderValue::from_str(&format!( - // TODO: `unsafe-inline` for `style-src` defeats the purpose of having it, but - // it's necessary to set CSS variables using the `style` attribute without - // JavaScript. Come back to this once there's a less shitty solution. + // TODO: `unsafe-inline` for `style-src` defeats the purpose of + // having it, but it's necessary to set CSS variables using the + // `style` attribute without JavaScript. Come back to this once + // there's a less shitty solution. "default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; \ script-src 'nonce-{csp_nonce}'; child-src {child_src};" )) From ef1378509e5db5601a37ee7e02b861c0df0daf9b Mon Sep 17 00:00:00 2001 From: Ginger Date: Sat, 24 Oct 2026 15:14:01 -0400 Subject: [PATCH 019/342] fix: Remove deactivate link from account page --- changelog.d/2383.bugfix.md | 1 + src/web/pages/templates/account.html.j2 | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 changelog.d/2383.bugfix.md diff --git a/changelog.d/2383.bugfix.md b/changelog.d/2383.bugfix.md new file mode 100644 index 000000000..5a551ede9 --- /dev/null +++ b/changelog.d/2383.bugfix.md @@ -0,0 +1 @@ +The OAuth identity reset page is no longer linked from the account management UI to reduce confusion. Contributed by @ginger. diff --git a/src/web/pages/templates/account.html.j2 b/src/web/pages/templates/account.html.j2 index 5efd122da..a1f478f99 100644 --- a/src/web/pages/templates/account.html.j2 +++ b/src/web/pages/templates/account.html.j2 @@ -67,7 +67,6 @@ Your account Settings here may affect the integrity of your account.

From a13a50836b17e539c2fb4ae2b7210d6b6dbdf9ea Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sun, 25 Oct 2026 05:19:08 +0000 Subject: [PATCH 020/342] chore(deps): update rust-non-major --- Cargo.lock | 219 ++++++++++++++++++++++++----------------------------- 1 file changed, 100 insertions(+), 119 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4d0d21836..b005e5a29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -208,7 +208,7 @@ dependencies = [ "rustc-hash", "serde", "serde_derive", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -270,7 +270,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -296,9 +296,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.18.1" +version = "1.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" dependencies = [ "aws-lc-sys", "zeroize", @@ -306,9 +306,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.45.0" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" dependencies = [ "cc", "cmake", @@ -708,7 +708,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" dependencies = [ "semver", "serde", - "toml 1.1.6+spec-1.1.0", + "toml 1.1.8+spec-1.1.0", ] [[package]] @@ -828,7 +828,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -1076,7 +1076,7 @@ dependencies = [ "tikv-jemallocator", "tokio", "tokio-metrics", - "toml 1.1.6+spec-1.1.0", + "toml 1.1.8+spec-1.1.0", "tracing", "tracing-core", "tracing-subscriber", @@ -1111,7 +1111,7 @@ dependencies = [ "itertools 0.15.0", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -1668,7 +1668,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -1690,7 +1690,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core 0.24.1", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -1840,7 +1840,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -1949,9 +1949,9 @@ dependencies = [ [[package]] name = "either" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" dependencies = [ "serde", ] @@ -2175,16 +2175,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" -[[package]] -name = "futf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" -dependencies = [ - "mac", - "new_debug_unreachable", -] - [[package]] name = "futures" version = "0.3.34" @@ -2241,7 +2231,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2653,16 +2643,12 @@ dependencies = [ [[package]] name = "html5ever" -version = "0.27.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c13771afe0e6e846f1e67d038d4cb29998a6779f93c809212e4e9c32efd244d4" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" dependencies = [ "log", - "mac", "markup5ever", - "proc-macro2", - "quote", - "syn 2.0.119", ] [[package]] @@ -2736,9 +2722,9 @@ dependencies = [ [[package]] name = "hyper" -version = "1.11.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -3428,12 +3414,6 @@ dependencies = [ "libc", ] -[[package]] -name = "mac" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" - [[package]] name = "maplit" version = "1.0.2" @@ -3442,23 +3422,20 @@ checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" [[package]] name = "markup5ever" -version = "0.12.1" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16ce3abbeba692c8b8441d036ef91aea6df8da2c6b6e21c7e14d3c18e526be45" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" dependencies = [ "log", - "phf", - "phf_codegen", - "string_cache", - "string_cache_codegen", "tendril", + "web_atoms", ] [[package]] name = "markup5ever_rcdom" -version = "0.3.0" +version = "0.39.0+unofficial" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edaa21ab3701bfee5099ade5f7e1f84553fd19228cf332f13cd6e964bf59be18" +checksum = "3ac010f19d6c4af81eeb4018a39d7a115de9d285af45c126a4ac02e6fc5716b7" dependencies = [ "html5ever", "markup5ever", @@ -3522,9 +3499,9 @@ dependencies = [ [[package]] name = "minicbor" -version = "2.3.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c12b4033ffaa92fbf9df03df38d19324f52bad130dd223f811734a8006dd2d69" +checksum = "e7244eafd1e09e7c4e33043881997aa6ab6dffff3ed2cee3395a278980481d6e" [[package]] name = "minicbor-serde" @@ -3628,7 +3605,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -3812,7 +3789,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64 0.22.1", + "base64 0.21.7", "chrono", "getrandom 0.2.17", "http", @@ -4318,18 +4295,19 @@ dependencies = [ [[package]] name = "phf" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ "phf_shared", + "serde", ] [[package]] name = "phf_codegen" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" dependencies = [ "phf_generator", "phf_shared", @@ -4337,19 +4315,19 @@ dependencies = [ [[package]] name = "phf_generator" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" dependencies = [ + "fastrand", "phf_shared", - "rand 0.8.8", ] [[package]] name = "phf_shared" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" dependencies = [ "siphasher", ] @@ -4535,7 +4513,7 @@ dependencies = [ "proc-macro-error-attr3", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -4832,7 +4810,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -4957,11 +4935,10 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" [[package]] name = "resolvematrix" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f072176a8b0cbe7c3df2281991ef00a09889d8ec789f2878e7fee43a3b978a6f" +checksum = "9e7767f4eb1d58880d6b33135a6c098cc8fbccecb259a833b44448c0de144dac" dependencies = [ - "futures", "hickory-resolver", "num-traits", "parking_lot", @@ -4969,6 +4946,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "tokio-stream", "tracing", ] @@ -5167,8 +5145,8 @@ dependencies = [ "quote", "ruma-identifiers-validation", "serde", - "syn 3.0.6", - "toml 1.1.6+spec-1.1.0", + "syn 3.0.9", + "toml 1.1.8+spec-1.1.0", ] [[package]] @@ -5654,7 +5632,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8050abb251097357e24aff63ba2c52a6309ecb7d23a5474023df960a02694d8" dependencies = [ "annotate-snippets", - "base64 0.23.1", + "base64 0.21.7", "encoding_rs_io", "granit-parser", "nohash-hasher", @@ -5691,7 +5669,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -5709,9 +5687,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -5761,9 +5739,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" dependencies = [ "serde_core", ] @@ -5810,7 +5788,7 @@ dependencies = [ "darling 0.24.1", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -5984,9 +5962,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.1" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" dependencies = [ "serde", ] @@ -6050,9 +6028,9 @@ checksum = "f42444fea5b87a39db4218d9422087e66a85d0e7a0963a439b07bcdf91804006" [[package]] name = "string_cache" -version = "0.8.9" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" dependencies = [ "new_debug_unreachable", "parking_lot", @@ -6063,9 +6041,9 @@ dependencies = [ [[package]] name = "string_cache_codegen" -version = "0.5.4" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" dependencies = [ "phf_generator", "phf_shared", @@ -6098,9 +6076,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.6" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -6156,13 +6134,11 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" [[package]] name = "tendril" -version = "0.4.3" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" dependencies = [ - "futf", - "mac", - "utf-8", + "new_debug_unreachable", ] [[package]] @@ -6228,7 +6204,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -6339,7 +6315,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -6403,14 +6379,14 @@ dependencies = [ [[package]] name = "toml" -version = "1.1.6+spec-1.1.0" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ "indexmap 2.14.2", "serde_core", - "serde_spanned 1.1.1", - "toml_datetime 1.1.1+spec-1.1.0", + "serde_spanned 1.1.2", + "toml_datetime 1.1.2+spec-1.1.0", "toml_parser", "toml_writer", "winnow 1.0.4", @@ -6427,9 +6403,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" dependencies = [ "serde_core", ] @@ -6455,16 +6431,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" dependencies = [ "indexmap 2.14.2", - "toml_datetime 1.1.1+spec-1.1.0", + "toml_datetime 1.1.2+spec-1.1.0", "toml_parser", "winnow 1.0.4", ] [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow 1.0.4", ] @@ -6477,9 +6453,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" [[package]] name = "tonic" @@ -6877,12 +6853,6 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - [[package]] name = "utf8_iter" version = "1.0.4" @@ -6959,9 +6929,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -7023,7 +6993,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "wasm-bindgen-shared", ] @@ -7084,10 +7054,22 @@ dependencies = [ ] [[package]] -name = "webpage" -version = "2.0.1" +name = "web_atoms" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70862efc041d46e6bbaa82bb9c34ae0596d090e86cbd14bd9e93b36ee6802eac" +checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" +dependencies = [ + "phf", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webpage" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5547a459b8cab203b5bf7d1f97855b3d6ae706da7c93773328614309432c9e4c" dependencies = [ "html5ever", "markup5ever_rcdom", @@ -7127,9 +7109,9 @@ checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" [[package]] name = "wildmatch" -version = "2.6.1" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29333c3ea1ba8b17211763463ff24ee84e41c78224c16b001cd907e663a38c68" +checksum = "f18219fbd41a807dec044965d4106bb4fdb1d3a4b70aac4e5510aacc80a9f140" [[package]] name = "winapi" @@ -7346,12 +7328,11 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "xml5ever" -version = "0.18.1" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bbb26405d8e919bc1547a5aa9abc95cbfa438f04844f5fdd9dc7596b748bf69" +checksum = "5ab627f34ff61b80d756180d556f9c68801d836d271b3b8c094504ceca69d221" dependencies = [ "log", - "mac", "markup5ever", ] @@ -7471,7 +7452,7 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] From 0ad4fc1c25c0ceaf8a53964b12e3e6f661e652b3 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sun, 25 Oct 2026 05:19:25 +0000 Subject: [PATCH 021/342] chore(deps): update dependency cargo-bins/cargo-binstall to v1.26.1 --- docker/Dockerfile | 2 +- docker/musl.Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 1c32a245c..3f5b99ff6 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -50,7 +50,7 @@ EOF # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.25.3 +ENV BINSTALL_VERSION=1.26.1 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree diff --git a/docker/musl.Dockerfile b/docker/musl.Dockerfile index 80dacba77..a4f2978f6 100644 --- a/docker/musl.Dockerfile +++ b/docker/musl.Dockerfile @@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \ # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.25.3 +ENV BINSTALL_VERSION=1.26.1 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree From 263ccd6b0b127e0d68d6c509c1275038c03b9dfa Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 19 Oct 2026 05:19:42 +0000 Subject: [PATCH 022/342] chore(deps): update rust-zerover-patch-updates --- Cargo.lock | 65 +++++++++++++++++++++++------------------------------- 1 file changed, 28 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b005e5a29..b355dfeee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1067,7 +1067,7 @@ dependencies = [ "serde-saphyr", "serde_json", "serde_regex", - "sha2 0.11.0", + "sha2 0.11.1", "smallstr", "smallvec", "thiserror 2.0.21", @@ -1194,7 +1194,7 @@ dependencies = [ "serde-saphyr", "serde_json", "serde_urlencoded", - "sha2 0.11.0", + "sha2 0.11.1", "termimad", "tokio", "tracing", @@ -1941,7 +1941,7 @@ dependencies = [ "curve25519-dalek 5.0.0", "ed25519 3.0.0", "serde", - "sha2 0.11.0", + "sha2 0.11.1", "signature 3.0.0", "subtle", "zeroize", @@ -3047,15 +3047,6 @@ dependencies = [ "either", ] -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.15.0" @@ -3287,9 +3278,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -3505,9 +3496,9 @@ checksum = "e7244eafd1e09e7c4e33043881997aa6ab6dffff3ed2cee3395a278980481d6e" [[package]] name = "minicbor-serde" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7abdec9761edcb452764c68564ae4b77ec62f6c1a361aa68f5de15fd788c679" +checksum = "b05ae1ca1d2c55196b389c8308119aa0e2aa8d31115f018dcc23ba3c5d350eb3" dependencies = [ "minicbor", "serde", @@ -4026,9 +4017,9 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] name = "opentelemetry" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cdb0b1b267eb9db3331b434ed9ddab10d50e280a9adf9d13e5233e2002b61b5" +checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" dependencies = [ "futures-core", "futures-sink", @@ -4040,9 +4031,9 @@ dependencies = [ [[package]] name = "opentelemetry-http" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee2c3625b8aa04209f7e01e513bc8044da9687fa38a9eacf59628ca5f3b87300" +checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" dependencies = [ "async-trait", "bytes", @@ -4070,9 +4061,9 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "699a67345e21962a231955b9059a157e428b219fa5df8efe11f08346fb23a344" +checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" dependencies = [ "http", "httpdate", @@ -4090,9 +4081,9 @@ dependencies = [ [[package]] name = "opentelemetry-prometheus" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "274c2e3a2ad55524484500d5a78dffbfee23e4a1e4c3d3fcbd881b61b033e6df" +checksum = "b9b52a5722eb64d198d6b6f1189e6b75a3c5ddfd224f48ede00c4330e0f11c66" dependencies = [ "once_cell", "opentelemetry", @@ -4103,9 +4094,9 @@ dependencies = [ [[package]] name = "opentelemetry-proto" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25da1ac11a0aeccf38d7f77ee0348715adaf8340f65ad46c94a02c6b20e2f65d" +checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" dependencies = [ "opentelemetry", "opentelemetry_sdk", @@ -4116,15 +4107,15 @@ dependencies = [ [[package]] name = "opentelemetry-semantic-conventions" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d288b1e1bc3590052fbb8f0f635ef248dd9022cf1fbaeb6582b7ad6081a17b87" +checksum = "7a3cf639fefd3e852869114f9925b578da6dd8e99281a2089bb0e773ead46962" [[package]] name = "opentelemetry_sdk" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb39533d9d1c912123efd7d41d7e0c29d16917b60ce15b4c8d87cb1af7f67520" +checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" dependencies = [ "futures-channel", "futures-executor", @@ -4569,7 +4560,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools 0.10.5", "proc-macro2", "quote", "syn 2.0.119", @@ -5174,7 +5165,7 @@ dependencies = [ "ruma-common", "ruma-events", "serde_json", - "sha2 0.11.0", + "sha2 0.11.1", "thiserror 2.0.21", ] @@ -5826,9 +5817,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -6143,9 +6134,9 @@ dependencies = [ [[package]] name = "termimad" -version = "0.35.4" +version = "0.35.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2374179aac8b77011a1aefe2f44d0c34eb680c9b4bd1c369a88991262c60c85a" +checksum = "092b11fb38404fa873f019f8e5f300fa5787f381b7a58b923546d94b5a9065fd" dependencies = [ "coolor", "crokey", @@ -7030,7 +7021,7 @@ dependencies = [ "hkdf 0.13.0", "http", "p256", - "sha2 0.11.0", + "sha2 0.11.1", ] [[package]] From ffef3911e76e04136ab772ff5644fa8e7b25701b Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 19 Oct 2026 05:41:22 +0000 Subject: [PATCH 023/342] chore(deps): update rust crate loole to 0.6.0 --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b355dfeee..8b24ee354 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3372,9 +3372,9 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "loole" -version = "0.4.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a3932a13b27d6b2d37efec3e4047017d59a8c9f2283a29bde29151d22f00fe9" +checksum = "45a6f2ee852ef619dac448846d7a80fb56a08e842674202d1ffe509fc319165c" dependencies = [ "futures-core", "futures-sink", diff --git a/Cargo.toml b/Cargo.toml index 7bce7584b..1508b5267 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -330,7 +330,7 @@ version = "2.1.1" # used for MPSC channels [workspace.dependencies.loole] -version = "0.4.0" +version = "0.6.0" # used for MPMC channels [workspace.dependencies.async-channel] From 3295427af6de75b8a0a7347f29e71c7b340830e7 Mon Sep 17 00:00:00 2001 From: Ginger Date: Sat, 24 Oct 2026 15:04:44 -0400 Subject: [PATCH 024/342] fix: Don't check room summary access rules on remote rooms --- changelog.d/+b5e913f8.bugfix.md | 1 + src/service/rooms/summary/mod.rs | 47 ++++++++++++++++---------------- 2 files changed, 25 insertions(+), 23 deletions(-) create mode 100644 changelog.d/+b5e913f8.bugfix.md diff --git a/changelog.d/+b5e913f8.bugfix.md b/changelog.d/+b5e913f8.bugfix.md new file mode 100644 index 000000000..cea4cfece --- /dev/null +++ b/changelog.d/+b5e913f8.bugfix.md @@ -0,0 +1 @@ +Room summary visibility checks are no longer incorrectly applied for remote rooms. Contributed by @ginger. diff --git a/src/service/rooms/summary/mod.rs b/src/service/rooms/summary/mod.rs index 4c2e21e86..42a277c17 100644 --- a/src/service/rooms/summary/mod.rs +++ b/src/service/rooms/summary/mod.rs @@ -112,6 +112,11 @@ impl Service { 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 @@ -126,11 +131,6 @@ impl Service { } }; - // 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); - } - Ok(Accessibility::Accessible(summary)) } @@ -146,10 +146,18 @@ impl Service { via: Option<&[OwnedServerName]>, suggested_only: bool, ) -> Result> { - let (mut summary, inaccessible_children) = { + let (summary, inaccessible_children) = { if let Some(summary) = self.build_local_room_summary(room_id).await { // We have this room locally. - let children_state = self.get_space_child_events(room_id, suggested_only).await; + 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 @@ -173,15 +181,6 @@ impl Service { } }; - // 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); - } - - if !matches!(summary.summary.room_type.as_ref(), Some(RoomType::Space)) { - summary.children_state.clear(); - } - let mut children: Vec<_> = summary .children_state .iter() @@ -301,11 +300,12 @@ impl Service { summaries.push(summary.summary); inaccessible_children.extend(summary.inaccessible_children); - // Bail out if queue length exceeds 50 to keep cycles in the space - // graph from blowing up the traversal. If you actually have over - // fifty nested spaces, 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. + // 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"))); } @@ -793,8 +793,9 @@ impl Service { } // Servers may always see summaries if any of their users are - // participating in the room. It's the requesting server's job to - // restrict visibility on a per-user basis. + // 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 From b848aed1bb8aa5f12579d73b1b7f71c7512222cb Mon Sep 17 00:00:00 2001 From: Ginger Date: Sun, 25 Oct 2026 13:33:31 -0400 Subject: [PATCH 025/342] chore: Update git-blame-ignore-revs --- .git-blame-ignore-revs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 74805ccd4..8c42d4f7b 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -7,6 +7,7 @@ f419c64aca300a338096b4e0db4c73ace54f23d0 5998a0d883d31b866f7c8c46433a8857eae51a89 # trailing whitespace and newlines 46c193e74b2ce86c48ce802333a0aabce37fd6e9 -# rustfmt update that rewrapped tons of comments +# rustfmt updates that rewrapped tons of comments 9fbabe221051e6956a05d8824142092ede68971e b0c0905472b882ff0cc79232e73d307fd0b5035b +9c27441acf2e65f85c106ccff5c6b6c37030ddca From 81c62c4a35aacca830c6268a96602537a9c22855 Mon Sep 17 00:00:00 2001 From: Ginger Date: Sun, 25 Oct 2026 13:47:36 -0400 Subject: [PATCH 026/342] fix: Silence tower_sessions warning --- src/web/session/store.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/web/session/store.rs b/src/web/session/store.rs index a05adb6cd..c7e051dd2 100644 --- a/src/web/session/store.rs +++ b/src/web/session/store.rs @@ -32,6 +32,19 @@ impl SessionStore for RocksDbSessionStore { Ok(()) } + async fn create(&self, session: &mut Record) -> Result<(), Error> { + while self + .websessionid_session + .exists(&session.id.0.to_be_bytes()) + .await + .is_ok() + { + session.id = Id::default(); + } + + self.save(session).await + } + async fn load(&self, session_id: &Id) -> Result, Error> { let Some(session) = self .websessionid_session From 8fff8f66d398512a34396cf6bd20dd19c71fc9be Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 26 Oct 2026 05:01:31 +0000 Subject: [PATCH 027/342] chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.181.10 --- .forgejo/workflows/renovate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/renovate.yml b/.forgejo/workflows/renovate.yml index 135e282a3..32efcbfa6 100644 --- a/.forgejo/workflows/renovate.yml +++ b/.forgejo/workflows/renovate.yml @@ -43,7 +43,7 @@ jobs: name: Renovate runs-on: ubuntu-latest container: - image: ghcr.io/renovatebot/renovate:44.167.5@sha256:0474cd0a251ec76d6dddfd64945d2c21aecd6fb35af9e0d5d883f2cc5a7cef32 + image: ghcr.io/renovatebot/renovate:44.181.10@sha256:5bd4b2744264b2ed6107a8457b7ec4daf6b08b20057423551ee7a41ced2c081e options: --tmpfs /tmp:exec steps: - name: Checkout From be5c94074c7aadd1658b722bb238ac65e574f074 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 27 Oct 2026 05:19:19 +0000 Subject: [PATCH 028/342] chore(deps): update github-actions-digest --- .forgejo/actions/create-docker-manifest/action.yml | 2 +- .forgejo/actions/prepare-docker-build/action.yml | 2 +- .forgejo/actions/timelord/action.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.forgejo/actions/create-docker-manifest/action.yml b/.forgejo/actions/create-docker-manifest/action.yml index a04df94d7..1415f0458 100644 --- a/.forgejo/actions/create-docker-manifest/action.yml +++ b/.forgejo/actions/create-docker-manifest/action.yml @@ -44,7 +44,7 @@ runs: - name: Login to builtin registry if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }} - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4 with: registry: ${{ env.BUILTIN_REGISTRY }} username: ${{ inputs.registry_user }} diff --git a/.forgejo/actions/prepare-docker-build/action.yml b/.forgejo/actions/prepare-docker-build/action.yml index 81d168e3f..4c52a2fc3 100644 --- a/.forgejo/actions/prepare-docker-build/action.yml +++ b/.forgejo/actions/prepare-docker-build/action.yml @@ -79,7 +79,7 @@ runs: - name: Login to builtin registry if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }} - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4 with: registry: ${{ env.BUILTIN_REGISTRY }} username: ${{ inputs.registry_user }} diff --git a/.forgejo/actions/timelord/action.yml b/.forgejo/actions/timelord/action.yml index b545769b2..8522b20f7 100644 --- a/.forgejo/actions/timelord/action.yml +++ b/.forgejo/actions/timelord/action.yml @@ -71,7 +71,7 @@ runs: - name: Install timelord-cli and git-warp-time if: steps.check-binaries.outputs.need-install == 'true' - uses: https://github.com/taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2 + uses: https://github.com/taiki-e/install-action@5488ac5a951645ce95062214902ac4b6bc1a1037 # v2 with: tool: git-warp-time,timelord-cli@3.0.1 From 747a612fd120082120b676559aa266fcf4101538 Mon Sep 17 00:00:00 2001 From: Jade Date: Tue, 27 Oct 2026 11:01:46 +0000 Subject: [PATCH 029/342] docs: Update funding yaml --- .github/FUNDING.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index f4fdf4d4f..d28e9584d 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,3 +1,4 @@ +open_collective: continuwuity github: [JadedBlueEyes, timedoutuk, gingershaped] custom: - https://timedout.uk/donate.html From 2b18fa12bf09fb85f45ed3411d8dcc91fbe6efed Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 28 Oct 2026 05:17:21 +0000 Subject: [PATCH 030/342] chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.190.1 --- .forgejo/workflows/renovate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/renovate.yml b/.forgejo/workflows/renovate.yml index 32efcbfa6..c6a43a6de 100644 --- a/.forgejo/workflows/renovate.yml +++ b/.forgejo/workflows/renovate.yml @@ -43,7 +43,7 @@ jobs: name: Renovate runs-on: ubuntu-latest container: - image: ghcr.io/renovatebot/renovate:44.181.10@sha256:5bd4b2744264b2ed6107a8457b7ec4daf6b08b20057423551ee7a41ced2c081e + image: ghcr.io/renovatebot/renovate:44.190.1@sha256:1b1306e7f1f0bafc56f6c471b6c309760ab990e9a60901623bcd14016717a528 options: --tmpfs /tmp:exec steps: - name: Checkout From 2badf2dfe90484b28d76fa7a9b25ac649f36f210 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 28 Oct 2026 05:21:37 +0000 Subject: [PATCH 031/342] chore(deps): update dependency node to v26 --- .forgejo/workflows/documentation.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/documentation.yml b/.forgejo/workflows/documentation.yml index d6113a210..e66a66957 100644 --- a/.forgejo/workflows/documentation.yml +++ b/.forgejo/workflows/documentation.yml @@ -34,7 +34,7 @@ jobs: if: steps.runner-env.outputs.node_major == '' || steps.runner-env.outputs.node_major < '20' uses: https://github.com/actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version: 24 + node-version: 26 - name: Cache npm dependencies uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 From 9c4f84940e07553190189e28750c099242101d11 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 17:46:51 +0100 Subject: [PATCH 032/342] fix(service): Prevent remote join lock inversion Do not hold state.mutex across join_remote_room to prevent an ABBA deadlock against mutex_federation. --- src/service/rooms/membership/mod.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index 5445b15ac..034599c80 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -226,9 +226,10 @@ impl Service { } } + drop(state_lock); // If we aren't participating in the room, or failed to join locally, // try to join over federation. - self.join_remote_room(sender_user, room_id, reason, &servers, &state_lock) + self.join_remote_room(sender_user, room_id, reason, &servers) .boxed() .await?; @@ -305,7 +306,6 @@ impl Service { room_id: &RoomId, reason: Option, servers: &[&OwnedServerName], - state_lock: &RoomMutexGuard, ) -> Result { // public so the admin command force-join-room-remotely works info!("Joining {room_id} over federation."); @@ -662,9 +662,10 @@ impl Service { .await?; debug!("Forcing state for new room"); + let state_lock = self.services.state.mutex.lock(room_id).await; self.services .state - .force_state(room_id, statehash_before_join, added, removed, state_lock) + .force_state(room_id, statehash_before_join, added, removed, &state_lock) .await?; debug!("Updating joined counts for new room"); @@ -686,7 +687,7 @@ impl Service { &parsed_join_pdu, join_event, once(parsed_join_pdu.event_id.as_ref()), - state_lock, + &state_lock, room_id, ) .await?; @@ -701,7 +702,7 @@ impl Service { // exist self.services .state - .set_room_state(room_id, statehash_after_join, state_lock); + .set_room_state(room_id, statehash_after_join, &state_lock); if !resident_before { // NOTE: We replace local extremities for this room if we were not a // resident before. We might be doing a remote join to satisfy @@ -711,7 +712,7 @@ impl Service { info!("Replacing local forward extremities"); self.services .state - .set_forward_extremities(room_id, once(parsed_join_pdu.event_id()), state_lock) + .set_forward_extremities(room_id, once(parsed_join_pdu.event_id()), &state_lock) .await; } drop(cork); From 35d606eeb75eb9f9294b0a57d296ef99286082e8 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 17:48:05 +0100 Subject: [PATCH 033/342] fix(main): Prevent re-entrant read lock deadlock during reload Reuse the already-held main_lock when checking module staleness in run() instead of re-acquiring server.mods.read(). --- src/main/mods.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/mods.rs b/src/main/mods.rs index 6140cc6e3..c0a945497 100644 --- a/src/main/mods.rs +++ b/src/main/mods.rs @@ -69,7 +69,7 @@ pub(crate) async fn run(server: &Arc, starts: bool) -> Result<(bool, boo let reloads = server.server.reloading.swap(false, Ordering::AcqRel); - let stops = !reloads || stale(server).await? <= restart_thresh(); + let stops = !reloads || stale_from_mods(&main_lock)? <= restart_thresh(); let starts = reloads && stops; if stops { let stop = main_mod.get::("stop")?; @@ -140,7 +140,10 @@ async fn stale_count(server: &Arc) -> usize { async fn stale(server: &Arc) -> Result { let mods_lock = server.mods.read().await; - let mods: &Vec = &mods_lock; + stale_from_mods(&mods_lock) +} + +fn stale_from_mods(mods: &[mods::Module]) -> Result { for (i, module) in mods.iter().enumerate() { if module.deleted()? { return Ok(i); From 938b3d28258fdab4ef4754768af131004e99bc30 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 17:49:39 +0100 Subject: [PATCH 034/342] refactor(admin): Release handle lock before command execution Change admin service handle to SyncRwLock and copy the handler function pointer before awaiting execution to prevent deadlock. --- src/admin/mod.rs | 12 ++++-------- src/router/run.rs | 4 ++-- src/service/admin/mod.rs | 12 +++++++----- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/admin/mod.rs b/src/admin/mod.rs index fd73c3f15..6c4a421cc 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -39,17 +39,13 @@ conduwuit::mod_dtor! {} pub use crate::admin::AdminCommand; /// Install the admin command processor -pub async fn init(admin_service: &service::admin::Service) { +pub fn init(admin_service: &service::admin::Service) { _ = admin_service.complete.write().insert(processor::complete); - _ = admin_service - .handle - .write() - .await - .insert(processor::dispatch); + _ = admin_service.handle.write().insert(processor::dispatch); } /// Uninstall the admin command handler -pub async fn fini(admin_service: &service::admin::Service) { - _ = admin_service.handle.write().await.take(); +pub fn fini(admin_service: &service::admin::Service) { + _ = admin_service.handle.write().take(); _ = admin_service.complete.write().take(); } diff --git a/src/router/run.rs b/src/router/run.rs index bff30367a..f5a2ebb2f 100644 --- a/src/router/run.rs +++ b/src/router/run.rs @@ -25,7 +25,7 @@ pub(crate) async fn run(services: Arc) -> Result<()> { debug!("Start"); // Install the admin room callback here for now - admin::init(&services.admin).await; + admin::init(&services.admin); // Setup shutdown/signal handling let handle = ServerHandle::new(); @@ -60,7 +60,7 @@ pub(crate) async fn run(services: Arc) -> Result<()> { _ = sigs.await; // Remove the admin room callback - admin::fini(&services.admin).await; + admin::fini(&services.admin); debug_info!("Finish"); res diff --git a/src/service/admin/mod.rs b/src/service/admin/mod.rs index 15dc33d50..923c2f15c 100644 --- a/src/service/admin/mod.rs +++ b/src/service/admin/mod.rs @@ -27,7 +27,6 @@ use ruma::{ }, }, }; -use tokio::sync::RwLock; use crate::{ Dep, account_data, config, globals, @@ -38,7 +37,7 @@ use crate::{ pub struct Service { services: Services, channel: (Sender, Receiver), - pub handle: RwLock>, + pub handle: SyncRwLock>, pub complete: SyncRwLock>, #[cfg(feature = "console")] pub console: Arc, @@ -131,7 +130,7 @@ impl crate::Service for Service { media: args.depend::("media"), }, channel: loole::bounded(COMMAND_QUEUE_LIMIT), - handle: RwLock::new(None), + handle: SyncRwLock::new(None), complete: SyncRwLock::new(None), #[cfg(feature = "console")] console: console::Console::new(&args), @@ -372,8 +371,11 @@ impl Service { } async fn process_command(&self, command: CommandInput) -> ProcessorResult { - let handle_guard = self.handle.read().await; - let handle = handle_guard.as_ref().expect("Admin module is not loaded"); + let handle = *self + .handle + .read() + .as_ref() + .expect("Admin module is not loaded"); let services = self .services From ad0181a3d87626ff91732997a4f4276d8cbd8158 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 17:50:10 +0100 Subject: [PATCH 035/342] refactor(service): Scope services.manager lock during lifecycle calls Avoid holding the services.manager lock across manager.start(), manager.stop(), and manager.poll() async invocations. --- src/service/services.rs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/service/services.rs b/src/service/services.rs index b2cd60b1b..96df263f7 100644 --- a/src/service/services.rs +++ b/src/service/services.rs @@ -142,13 +142,8 @@ impl Services { super::migrations::migrations(self) .await .inspect_err(|e| error!("Migrations failed: {e}"))?; - self.manager - .lock() - .await - .insert(Manager::new(self)) - .clone() - .start() - .await?; + let manager = self.manager.lock().await.insert(Manager::new(self)).clone(); + manager.start().await?; // reset dormant online/away statuses to offline, and set the server // user as online @@ -177,7 +172,8 @@ impl Services { } self.interrupt(); - if let Some(manager) = self.manager.lock().await.as_ref() { + let manager = self.manager.lock().await.clone(); + if let Some(manager) = manager { manager.stop().await; } @@ -187,7 +183,8 @@ impl Services { } pub async fn poll(&self) -> Result<()> { - if let Some(manager) = self.manager.lock().await.as_ref() { + let manager = self.manager.lock().await.clone(); + if let Some(manager) = manager { return manager.poll().await; } From 98ae1fcaa10be90721f39ae947844dea403c720a Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 17:53:08 +0100 Subject: [PATCH 036/342] refactor(oauth): Avoid holding pending grants lock across async calls Convert pending grants and tickets to SyncMutex and scope locks tightly before awaiting external calls in grant_info and redeem_token. --- src/service/oauth/mod.rs | 136 ++++++++++++++++++----------------- src/web/pages/oauth/grant.rs | 1 - 2 files changed, 69 insertions(+), 68 deletions(-) diff --git a/src/service/oauth/mod.rs b/src/service/oauth/mod.rs index c3db66a57..bddad5f76 100644 --- a/src/service/oauth/mod.rs +++ b/src/service/oauth/mod.rs @@ -1,12 +1,12 @@ use std::{ collections::{BTreeSet, HashMap}, - sync::{Arc, Mutex}, + sync::Arc, time::{Duration, SystemTime}, }; use base64::Engine; use conduwuit::{ - Result, info, + Result, SyncMutex, info, utils::{self, hash::sha256}, }; use database::{Deserialized, Json, Map}; @@ -36,9 +36,9 @@ pub mod grant; pub struct Service { services: Services, db: Data, - tickets: Mutex>>, - pending_auth_code_grants: tokio::sync::Mutex>, - pending_device_code_grants: tokio::sync::Mutex>, + tickets: SyncMutex>>, + pending_auth_code_grants: SyncMutex>, + pending_device_code_grants: SyncMutex>, } struct Data { @@ -169,13 +169,9 @@ impl crate::Service for Service { userdeviceid_oauthsessioninfo: args.db["userdeviceid_oauthsessioninfo"].clone(), refreshtoken_refreshtokeninfo: args.db["refreshtoken_refreshtokeninfo"].clone(), }, - tickets: Mutex::default(), - pending_auth_code_grants: tokio::sync::Mutex::new(LruCache::new( - Self::MAX_PENDING_GRANTS, - )), - pending_device_code_grants: tokio::sync::Mutex::new(LruCache::new( - Self::MAX_PENDING_GRANTS, - )), + tickets: SyncMutex::default(), + pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), + pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), })) } @@ -328,7 +324,6 @@ impl Service { self.pending_auth_code_grants .lock() - .await .insert(code, pending_grant); Ok(redirect_uri) @@ -383,7 +378,6 @@ impl Service { self.pending_device_code_grants .lock() - .await .insert(device_code.clone(), pending_grant); Ok(DeviceCodeResponse { @@ -399,32 +393,36 @@ impl Service { &self, supplied_user_code: &str, ) -> Option { - let pending_grants = self.pending_device_code_grants.lock().await; + let (device_code, client_id, requested_scopes) = { + let pending_grants = self.pending_device_code_grants.lock(); - let (device_code, grant) = pending_grants - .iter() - .find(|(_, grant)| { - matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code) - })?; + let (device_code, grant) = pending_grants + .iter() + .find(|(_, grant)| { + matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code) + })?; + + (device_code.clone(), grant.client_id.clone(), grant.requested_scopes.clone()) + }; let client_metadata = self - .get_client_metadata(&grant.client_id) + .get_client_metadata(&client_id) .await .expect("client should exist"); Some(DeviceCodeGrantInfo { - device_code: device_code.clone(), + device_code, client_metadata, - requested_scopes: grant.requested_scopes.clone(), + requested_scopes, }) } - pub async fn validate_device_code( + pub fn validate_device_code( &self, authorizing_user: OwnedUserId, device_code: &str, ) -> Result<(), String> { - let mut pending_grants = self.pending_device_code_grants.lock().await; + let mut pending_grants = self.pending_device_code_grants.lock(); let Some(pending_grant) = pending_grants.get_mut(device_code) else { return Err("Invalid device code".to_owned()); @@ -460,25 +458,29 @@ impl Service { match request { | TokenRequestType::AuthorizationCode { code, redirect_uri, code_verifier } => { - let mut pending_grants = self.pending_auth_code_grants.lock().await; + let pending_grant = { + let mut pending_grants = self.pending_auth_code_grants.lock(); - let Some(pending_grant) = pending_grants - .remove(&code) - .filter(|grant| grant.is_valid_for(&client_id)) - else { - return Err(OAuthError::invalid_grant("Invalid authorization code")); + let Some(pending_grant) = pending_grants + .remove(&code) + .filter(|grant| grant.is_valid_for(&client_id)) + else { + return Err(OAuthError::invalid_grant("Invalid authorization code")); + }; + + if redirect_uri != pending_grant.expected_redirect_uri { + return Err(OAuthError::invalid_grant("Invalid redirect URI")); + } + + let expected_code_challenge = base64::prelude::BASE64_URL_SAFE_NO_PAD + .encode(sha256::hash(&code_verifier)); + if expected_code_challenge != pending_grant.code_challenge { + return Err(OAuthError::invalid_grant("Invalid code challenge")); + } + + pending_grant }; - if redirect_uri != pending_grant.expected_redirect_uri { - return Err(OAuthError::invalid_grant("Invalid redirect URI")); - } - - let expected_code_challenge = - base64::prelude::BASE64_URL_SAFE_NO_PAD.encode(sha256::hash(&code_verifier)); - if expected_code_challenge != pending_grant.code_challenge { - return Err(OAuthError::invalid_grant("Invalid code challenge")); - } - self.create_session( pending_grant.authorizing_user, pending_grant.requested_scopes, @@ -488,36 +490,38 @@ impl Service { .await }, | TokenRequestType::DeviceCode { device_code } => { - let mut pending_grants = self.pending_device_code_grants.lock().await; + let (authorizing_user, requested_scopes, client_name) = { + let mut pending_grants = self.pending_device_code_grants.lock(); - let Some(pending_grant) = pending_grants - .remove(&device_code) - .filter(|grant| grant.is_valid_for(&client_id)) - else { - return Err(OAuthError::new_static( - ErrorCode::ExpiredToken, - "Invalid device code", - )); - }; + let Some(pending_grant) = pending_grants + .remove(&device_code) + .filter(|grant| grant.is_valid_for(&client_id)) + else { + return Err(OAuthError::new_static( + ErrorCode::ExpiredToken, + "Invalid device code", + )); + }; - match &pending_grant.state { - | DeviceCodeGrantState::Unverified { .. } => { - pending_grants.insert(device_code, pending_grant); + match &pending_grant.state { + | DeviceCodeGrantState::Unverified { .. } => { + pending_grants.insert(device_code, pending_grant); - Err(OAuthError::new_static( - ErrorCode::AuthorizationPending, - "Authorization is pending", - )) - }, - | DeviceCodeGrantState::Verified { authorizing_user } => - self.create_session( + return Err(OAuthError::new_static( + ErrorCode::AuthorizationPending, + "Authorization is pending", + )); + }, + | DeviceCodeGrantState::Verified { authorizing_user } => ( authorizing_user.to_owned(), pending_grant.requested_scopes, pending_grant.client_name, - client_id, - ) - .await, - } + ), + } + }; + + self.create_session(authorizing_user, requested_scopes, client_name, client_id) + .await }, | TokenRequestType::RefreshToken { refresh_token } => self.refresh_session(client_id, refresh_token).await, @@ -773,7 +777,6 @@ impl Service { pub fn issue_ticket(&self, localpart: String, ticket: OAuthTicket) { self.tickets .lock() - .unwrap() .entry(localpart) .or_default() .insert(ticket, SystemTime::now()); @@ -785,7 +788,6 @@ impl Service { self.tickets .lock() - .unwrap() .get_mut(localpart) .and_then(|tickets| tickets.remove(&ticket)) .is_some_and(|issued| { diff --git a/src/web/pages/oauth/grant.rs b/src/web/pages/oauth/grant.rs index bde0b7d48..1cb268102 100644 --- a/src/web/pages/oauth/grant.rs +++ b/src/web/pages/oauth/grant.rs @@ -242,7 +242,6 @@ async fn route_device_code( services .oauth .validate_device_code(user_id, &device_code) - .await .map_err(WebError::BadRequest)?; response!(DeviceCodeGrant::new(context, user_card, DeviceCodeGrantBody::Success)) From 18f5f4fbfa10ceaa7f7a7c9b33be1249db06a0c4 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 17:58:57 +0100 Subject: [PATCH 037/342] refactor(threepid): Use SyncMutex and decouple guard from ValidSession Change threepid sessions and send_attempts to SyncMutex and avoid holding the sessions mutex across callers of get_valid_session. --- src/api/client/account/threepid.rs | 1 - src/service/threepid/mod.rs | 146 ++++++++++++------------ src/service/uiaa/mod.rs | 37 +++--- src/web/pages/account/email.rs | 1 - src/web/pages/account/password/reset.rs | 1 - src/web/pages/account/register.rs | 1 - src/web/pages/threepid.rs | 1 - 7 files changed, 90 insertions(+), 98 deletions(-) diff --git a/src/api/client/account/threepid.rs b/src/api/client/account/threepid.rs index 93531eb02..edcd9017d 100644 --- a/src/api/client/account/threepid.rs +++ b/src/api/client/account/threepid.rs @@ -135,7 +135,6 @@ pub(crate) async fn add_3pid_route( let email = services .threepid .get_valid_session(&body.sid, &body.client_secret) - .await .map_err(|message| err!(Request(ThreepidAuthFailed("{message}"))))? .consume(); diff --git a/src/service/threepid/mod.rs b/src/service/threepid/mod.rs index 7e4ffa968..cbc1fd080 100644 --- a/src/service/threepid/mod.rs +++ b/src/service/threepid/mod.rs @@ -1,6 +1,8 @@ use std::{borrow::Cow, collections::HashMap, sync::Arc}; -use conduwuit::{Err, Error, Result, config::OidcProfileKeyImportMode, result::FlatOk}; +use conduwuit::{ + Err, Error, Result, SyncMutex, config::OidcProfileKeyImportMode, result::FlatOk, +}; use database::{Deserialized, Map}; use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter}; use lettre::{Address, message::Mailbox}; @@ -9,7 +11,6 @@ use ruma::{ ClientSecret, OwnedClientSecret, OwnedSessionId, SessionId, api::error::{ErrorKind, LimitExceededErrorData}, }; -use tokio::sync::MutexGuard; pub mod session; @@ -22,8 +23,8 @@ use crate::{ pub struct Service { db: Data, services: Services, - sessions: tokio::sync::Mutex, - send_attempts: std::sync::Mutex>, + sessions: SyncMutex, + send_attempts: SyncMutex>, ratelimiter: DefaultKeyedRateLimiter
, } @@ -71,8 +72,8 @@ impl crate::Service for Service { config: args.depend("config"), mailer: args.depend("mailer"), }, - sessions: tokio::sync::Mutex::default(), - send_attempts: std::sync::Mutex::default(), + sessions: SyncMutex::default(), + send_attempts: SyncMutex::default(), ratelimiter: RateLimiter::keyed(Self::EMAIL_RATELIMIT), })) } @@ -121,65 +122,69 @@ impl Service { send_attempt: usize, ) -> Result { let mailer = self.services.mailer.expect_mailer()?; - let mut sessions = self.sessions.lock().await; + let (session_id, token_str) = { + let mut sessions = self.sessions.lock(); - let session = match sessions.get_session_by_client_secret(client_secret) { - // If a validation session already exists for this client secret, we - // can either reuse it with a new token or return early because it's - // already valid. - | Some(session) => { - if session.email != recipient.email { - return Err!(Request(InvalidParam("Wrong email for session."))); - } + let session = match sessions.get_session_by_client_secret(client_secret) { + // If a validation session already exists for this client secret, we + // can either reuse it with a new token or return early because it's + // already valid. + | Some(session) => { + if session.email != recipient.email { + return Err!(Request(InvalidParam("Wrong email for session."))); + } - match session.validation_state { - | ValidationState::Validated => { - // If the existing session is already valid, don't send - // an email. - return Ok(session.session_id.clone()); - }, - | ValidationState::Pending(ref mut token) => { - // Check ratelimiting for the target address. - if self.ratelimiter.check_key(&session.email).is_err() { - return Err(Error::BadRequest( - ErrorKind::LimitExceeded(LimitExceededErrorData::new()), - "You're sending emails too fast, try again in a few minutes.", - )); - } - - // Check the send attempt for this session. - let mut send_attempts = self.send_attempts.lock().unwrap(); - - let last_send_attempt = send_attempts - .entry((session.client_secret.clone(), session.email.clone())) - .or_default(); - - if send_attempt <= *last_send_attempt { - // If the supplied send attempt isn't higher than - // the last one, don't send an email. + match session.validation_state { + | ValidationState::Validated => { + // If the existing session is already valid, don't + // send an email. return Ok(session.session_id.clone()); - } + }, + | ValidationState::Pending(ref mut token) => { + // Check ratelimiting for the target address. + if self.ratelimiter.check_key(&session.email).is_err() { + return Err(Error::BadRequest( + ErrorKind::LimitExceeded(LimitExceededErrorData::new()), + "You're sending emails too fast, try again in a few minutes.", + )); + } - // Save this send attempt. - *last_send_attempt = send_attempt; - drop(send_attempts); + // Check the send attempt for this session. + let mut send_attempts = self.send_attempts.lock(); - // Create a new token for the existing session. - *token = ValidationToken::new_random(); + let last_send_attempt = send_attempts + .entry((session.client_secret.clone(), session.email.clone())) + .or_default(); - session - }, - } - }, - // If no session exists, create a new one. - | None => sessions.create_session(recipient.email.clone(), client_secret.to_owned()), - }; + if send_attempt <= *last_send_attempt { + // If the supplied send attempt isn't higher + // than the last + // one, don't send an email. + return Ok(session.session_id.clone()); + } - // Clone this so it can outlive the lock we're holding on `sessions` - let session_id = session.session_id.clone(); + // Save this send attempt. + *last_send_attempt = send_attempt; + drop(send_attempts); - let ValidationState::Pending(token) = &session.validation_state else { - unreachable!("session should be pending") + // Create a new token for the existing session. + *token = ValidationToken::new_random(); + + session + }, + } + }, + // If no session exists, create a new one. + | None => + sessions.create_session(recipient.email.clone(), client_secret.to_owned()), + }; + + let session_id = session.session_id.clone(); + let ValidationState::Pending(token) = &session.validation_state else { + unreachable!("session should be pending") + }; + + (session_id, token.token.clone()) }; let mut validation_url = self @@ -192,11 +197,7 @@ impl Service { validation_url .query_pairs_mut() .append_pair("session", session_id.as_str()) - .append_pair("token", &token.token); - - // Once the validation URL is built, we don't need any data borrowed - // from `sessions` anymore and can release our lock - drop(sessions); + .append_pair("token", &token_str); let message = prepare_body(validation_url.to_string()); @@ -206,12 +207,12 @@ impl Service { } /// Attempt to mark a validation session as valid using a validation token. - pub async fn try_validate_session( + pub fn try_validate_session( &self, session_id: &SessionId, supplied_token: &str, ) -> Result<(), Cow<'static, str>> { - let mut sessions = self.sessions.lock().await; + let mut sessions = self.sessions.lock(); let Some(session) = sessions.get_session(session_id) else { return Err("Validation session does not exist".into()); @@ -240,12 +241,12 @@ impl Service { } /// Get a validated validation session. - pub async fn get_valid_session( + pub fn get_valid_session( &self, session_id: &SessionId, client_secret: &ClientSecret, ) -> Result, Cow<'static, str>> { - let mut sessions = self.sessions.lock().await; + let mut sessions = self.sessions.lock(); let Some(session) = sessions.get_session(session_id) else { return Err("Validation session does not exist".into()); @@ -259,7 +260,7 @@ impl Service { Ok(ValidSession { email, session_id: session_id.to_owned(), - sessions, + service: self, }) } else { Err("This email address has not been validated. Did you use the link that was sent \ @@ -337,18 +338,21 @@ impl Service { } } -pub struct ValidSession<'lock> { +pub struct ValidSession<'a> { pub email: Address, session_id: OwnedSessionId, - sessions: MutexGuard<'lock, ValidationSessions>, + service: &'a Service, } impl ValidSession<'_> { /// Consume this session, removing it from the database and releasing the /// lock it holds. #[must_use] - pub fn consume(mut self) -> Address { - self.sessions.remove_session(&self.session_id); + pub fn consume(self) -> Address { + self.service + .sessions + .lock() + .remove_session(&self.session_id); self.email } diff --git a/src/service/uiaa/mod.rs b/src/service/uiaa/mod.rs index f78bbe923..0aebaed7e 100644 --- a/src/service/uiaa/mod.rs +++ b/src/service/uiaa/mod.rs @@ -492,31 +492,24 @@ impl Service { | AuthData::EmailIdentity(EmailIdentity { thirdparty_id_creds: ThirdpartyIdCredentials { client_secret, sid, .. }, .. - }) => { - match self - .services - .threepid - .get_valid_session(sid, client_secret) - .await - { - | Ok(session) => { - let email = session.consume(); + }) => match self.services.threepid.get_valid_session(sid, client_secret) { + | Ok(session) => { + let email = session.consume(); - if let Some(localpart) = - self.services.threepid.get_localpart_for_email(&email).await - { - identity.try_set_localpart(localpart)?; - } + if let Some(localpart) = + self.services.threepid.get_localpart_for_email(&email).await + { + identity.try_set_localpart(localpart)?; + } - identity.try_set_email(email)?; + identity.try_set_email(email)?; - Ok(AuthType::EmailIdentity) - }, - | Err(message) => Err(StandardErrorBody::new( - ErrorKind::ThreepidAuthFailed, - message.into_owned(), - )), - } + Ok(AuthType::EmailIdentity) + }, + | Err(message) => Err(StandardErrorBody::new( + ErrorKind::ThreepidAuthFailed, + message.into_owned(), + )), }, #[allow(clippy::useless_let_if_seq)] | AuthData::Password(Password { identifier, password, .. }) => { diff --git a/src/web/pages/account/email.rs b/src/web/pages/account/email.rs index 1d9ca64b2..bace631df 100644 --- a/src/web/pages/account/email.rs +++ b/src/web/pages/account/email.rs @@ -167,7 +167,6 @@ async fn get_change_email_validate( let Ok(session) = services .threepid .get_valid_session(&session_id, &client_secret) - .await else { return response!(ChangeEmailValidate::new( context, diff --git a/src/web/pages/account/password/reset.rs b/src/web/pages/account/password/reset.rs index 20b2732d9..917c86cc9 100644 --- a/src/web/pages/account/password/reset.rs +++ b/src/web/pages/account/password/reset.rs @@ -189,7 +189,6 @@ async fn route_reset_password_validate( let body = match services .threepid .get_valid_session(&query.threepid.session_id, &query.threepid.client_secret) - .await { | Ok(session) => { let Some(localpart) = services diff --git a/src/web/pages/account/register.rs b/src/web/pages/account/register.rs index 5abff481e..cdce43fea 100644 --- a/src/web/pages/account/register.rs +++ b/src/web/pages/account/register.rs @@ -289,7 +289,6 @@ async fn get_register_email_validate( let Ok(session) = services .threepid .get_valid_session(&session_id, &client_secret) - .await else { return response!(RegisterEmailValidate::new(context, session_id, client_secret, true)); }; diff --git a/src/web/pages/threepid.rs b/src/web/pages/threepid.rs index 5aefcf6f0..3d8b8b746 100644 --- a/src/web/pages/threepid.rs +++ b/src/web/pages/threepid.rs @@ -33,7 +33,6 @@ async fn threepid_validation( services .threepid .try_validate_session(&query.session, &query.token) - .await .map_err(|message| WebError::BadRequest(message.into_owned()))?; Ok(ThreepidValidation::new(context)) From 5297e013574f2733c1899910f5d140ccdd14aa99 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 18:01:23 +0100 Subject: [PATCH 038/342] refactor(metrics): Replace std::sync::Mutex with SyncMutex Replace std::sync::Mutex with parking_lot::Mutex (SyncMutex) in core::metrics::runtime_intervals. Note that info::introspection retains std::sync::Mutex because parking_lot panics in dtor after thread locals are destroyed. --- src/core/metrics/mod.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/core/metrics/mod.rs b/src/core/metrics/mod.rs index d3f1a1da2..bb06368a8 100644 --- a/src/core/metrics/mod.rs +++ b/src/core/metrics/mod.rs @@ -14,6 +14,8 @@ use tokio_metrics::TaskMonitor; use tokio_metrics::{RuntimeIntervals, RuntimeMonitor}; pub use self::instruments::{Instruments, duration_buckets}; +#[cfg(tokio_unstable)] +use crate::SyncMutex; use crate::{Err, Result}; pub struct Metrics { @@ -27,7 +29,7 @@ pub struct Metrics { _runtime_monitor: Option, #[cfg(tokio_unstable)] - runtime_intervals: std::sync::Mutex>, + runtime_intervals: SyncMutex>, // TODO: move stats pub requests_handle_active: AtomicU32, @@ -69,7 +71,7 @@ impl Metrics { _runtime_monitor: runtime_monitor, #[cfg(tokio_unstable)] - runtime_intervals: std::sync::Mutex::new(runtime_intervals), + runtime_intervals: SyncMutex::new(runtime_intervals), requests_handle_active: AtomicU32::new(0), requests_handle_finished: AtomicU32::new(0), @@ -81,7 +83,6 @@ impl Metrics { pub fn runtime_interval(&self) -> Option { self.runtime_intervals .lock() - .expect("locked") .as_mut() .map(Iterator::next) .expect("next interval") From 24b1e2ebe8289a7647cce765372908cdb757b5b1 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 18:15:03 +0100 Subject: [PATCH 039/342] refactor(service): Use SyncRwLock and SyncMutex for in-memory services Convert in-memory data structures in appservice, rooms::typing, and sync wakers to use SyncRwLock and SyncMutex. Drop appservice locks before making outbound network requests in room alias queries and federation invites. --- src/admin/appservice/commands.rs | 14 +++---- src/admin/query/appservice.rs | 2 +- src/api/client/alias.rs | 6 +-- src/api/client/room/create.rs | 6 +-- src/api/client/sync/v3/mod.rs | 2 +- src/api/client/sync/v5.rs | 2 +- src/api/client/unversioned.rs | 2 +- src/api/router/auth.rs | 4 +- src/api/server/invite.rs | 50 +++++++++++++------------ src/core/mod.rs | 5 ++- src/service/appservice/mod.rs | 48 ++++++++---------------- src/service/migrations.rs | 2 +- src/service/rooms/alias/mod.rs | 41 +++++++++++---------- src/service/rooms/timeline/append.rs | 1 - src/service/rooms/typing/mod.rs | 29 ++++++--------- src/service/sending/mod.rs | 1 - src/service/sending/sender.rs | 2 +- src/service/sync/mod.rs | 55 ++++++++++++++-------------- src/service/users/account.rs | 6 +-- src/service/users/device.rs | 8 +--- 20 files changed, 126 insertions(+), 160 deletions(-) diff --git a/src/admin/appservice/commands.rs b/src/admin/appservice/commands.rs index 9bccc643d..86fa51f27 100644 --- a/src/admin/appservice/commands.rs +++ b/src/admin/appservice/commands.rs @@ -1,4 +1,4 @@ -use conduwuit::{Err, Result, checked}; +use conduwuit::{Err, Result, checked, utils::ReadyExt}; use futures::{FutureExt, StreamExt, TryFutureExt}; impl crate::Context<'_> { @@ -49,7 +49,6 @@ impl crate::Context<'_> { .services .appservice .get_registration(&appservice_identifier) - .await { | None => return Err!("Appservice does not exist."), | Some(config) => { @@ -78,12 +77,11 @@ impl crate::Context<'_> { self.services .users .stream_local_users() - .filter_map(async |user_id| { - if self.services.appservice.is_user_id(&user_id).await { - Some(user_id) - } else { - None - } + .ready_filter_map(|user_id| { + self.services + .appservice + .is_user_id(&user_id) + .then_some(user_id) }) .for_each(async |user_id| { self.services diff --git a/src/admin/query/appservice.rs b/src/admin/query/appservice.rs index e2f04acf3..45dec01e5 100644 --- a/src/admin/query/appservice.rs +++ b/src/admin/query/appservice.rs @@ -24,7 +24,7 @@ pub(super) async fn process(subcommand: AppserviceCommand, context: &Context<'_> match subcommand { | AppserviceCommand::GetRegistration { appservice_id } => { let timer = tokio::time::Instant::now(); - let results = services.appservice.get_registration(&appservice_id).await; + let results = services.appservice.get_registration(&appservice_id); let query_time = timer.elapsed(); diff --git a/src/api/client/alias.rs b/src/api/client/alias.rs index 5d4dec081..f10e03083 100644 --- a/src/api/client/alias.rs +++ b/src/api/client/alias.rs @@ -20,8 +20,7 @@ pub(crate) async fn create_alias_route( services .rooms .alias - .appservice_checks(&body.room_alias, body.identity.appservice_info()) - .await?; + .appservice_checks(&body.room_alias, body.identity.appservice_info())?; // this isn't apart of alias_checks or delete alias route because we should // allow removing forbidden room aliases @@ -69,8 +68,7 @@ pub(crate) async fn delete_alias_route( services .rooms .alias - .appservice_checks(&body.room_alias, body.identity.appservice_info()) - .await?; + .appservice_checks(&body.room_alias, body.identity.appservice_info())?; services .rooms diff --git a/src/api/client/room/create.rs b/src/api/client/room/create.rs index 582169346..a2acf5ec1 100644 --- a/src/api/client/room/create.rs +++ b/src/api/client/room/create.rs @@ -758,11 +758,7 @@ async fn room_alias_check( if !info.aliases.is_match(full_room_alias.as_str()) { return Err!(Request(Exclusive("Room alias is not in namespace."))); } - } else if services - .appservice - .is_exclusive_alias(&full_room_alias) - .await - { + } else if services.appservice.is_exclusive_alias(&full_room_alias) { return Err!(Request(Exclusive("Room alias reserved by appservice.",))); } diff --git a/src/api/client/sync/v3/mod.rs b/src/api/client/sync/v3/mod.rs index 4987534cf..e6ac768f0 100644 --- a/src/api/client/sync/v3/mod.rs +++ b/src/api/client/sync/v3/mod.rs @@ -201,7 +201,7 @@ pub(crate) async fn sync_events_route( .update_device_last_seen(sender_user, Some(sender_device), client_ip) .await; - let mut wake_receiver = services.sync.subscribe_to_wake(sender_user).await; + let mut wake_receiver = services.sync.subscribe_to_wake(sender_user); let response = build_sync_events(&services, &body).await?; if body.body.full_state || !(response.rooms.is_empty() diff --git a/src/api/client/sync/v5.rs b/src/api/client/sync/v5.rs index 7f8997aec..4f21c1930 100644 --- a/src/api/client/sync/v5.rs +++ b/src/api/client/sync/v5.rs @@ -147,7 +147,7 @@ pub(crate) async fn sync_events_v5_route( .sync .update_snake_sync_request_with_cache(&snake_key, globalsince, &mut body); - let mut wake_receiver = services.sync.subscribe_to_wake(sender_user).await; + let mut wake_receiver = services.sync.subscribe_to_wake(sender_user); let mut collection = collect_sync_response( services, sender_user, diff --git a/src/api/client/unversioned.rs b/src/api/client/unversioned.rs index 814ee0d9e..207bcb620 100644 --- a/src/api/client/unversioned.rs +++ b/src/api/client/unversioned.rs @@ -64,7 +64,7 @@ pub(crate) async fn continuwuity_local_user_count( .stream_local_users() .filter_map(async |user_id| { if !services.users.status(&user_id).await.is_active() - || services.appservice.is_exclusive_user_id(&user_id).await + || services.appservice.is_exclusive_user_id(&user_id) { None } else { diff --git a/src/api/router/auth.rs b/src/api/router/auth.rs index cac270ee0..e731245df 100644 --- a/src/api/router/auth.rs +++ b/src/api/router/auth.rs @@ -346,7 +346,7 @@ async fn check_access_token( } Ok(ClientIdentity::User { sender_user, sender_device }) - } else if let Ok(appservice_info) = services.appservice.find_from_token(token).await { + } else if let Ok(appservice_info) = services.appservice.find_from_token(token) { let Ok(sender_user) = query.user_id.clone().map_or_else( || { UserId::parse_with_server_name( @@ -405,7 +405,7 @@ async fn check_access_token( } async fn check_appservice_token(services: &Services, token: &str) -> Result { - let Ok(appservice_info) = services.appservice.find_from_token(token).await else { + let Ok(appservice_info) = services.appservice.find_from_token(token) else { return Err!(Request(Unauthorized("Invalid appservice token."))); }; diff --git a/src/api/server/invite.rs b/src/api/server/invite.rs index 89069e050..06ee9f2b1 100644 --- a/src/api/server/invite.rs +++ b/src/api/server/invite.rs @@ -209,31 +209,35 @@ async fn create_invite( services.sync.wake(&recipient_user).await; - for appservice in services.appservice.read().await.values() { - if appservice.is_user_match(&recipient_user) { - let transaction_id = general_purpose::URL_SAFE_NO_PAD - .encode(sha256::hash(pdu.event_id.as_bytes())) - .into(); + let matching_appservices: Vec<_> = services + .appservice + .read() + .values() + .filter(|appservice| appservice.is_user_match(&recipient_user)) + .cloned() + .collect(); - let request = ruma::api::appservice::event::push_events::v1::Request::new( - transaction_id, - vec![pdu.to_format()], - ); + for appservice in matching_appservices { + let transaction_id = general_purpose::URL_SAFE_NO_PAD + .encode(sha256::hash(pdu.event_id.as_bytes())) + .into(); - services - .sending - .send_appservice_request(appservice.registration.clone(), request) - .await - .map_err(|e| { - error!( - "failed to notify appservice {} about incoming invite: {e}", - appservice.registration.id - ); - err!(BadServerResponse( - "Failed to notify appservice about incoming invite." - )) - })?; - } + let request = ruma::api::appservice::event::push_events::v1::Request::new( + transaction_id, + vec![pdu.to_format()], + ); + + services + .sending + .send_appservice_request(appservice.registration.clone(), request) + .await + .map_err(|e| { + error!( + "failed to notify appservice {} about incoming invite: {e}", + appservice.registration.id + ); + err!(BadServerResponse("Failed to notify appservice about incoming invite.")) + })?; } } diff --git a/src/core/mod.rs b/src/core/mod.rs index 20d49fc50..f176593c4 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -36,7 +36,10 @@ pub use config::Config; pub use error::Error; pub use info::version::*; pub use matrix::{Event, EventTypeExt, Pdu, PduCount, PduEvent, PduId, pdu, state_res}; -pub use parking_lot::{Mutex as SyncMutex, RwLock as SyncRwLock}; +pub use parking_lot::{ + Mutex as SyncMutex, RwLock as SyncRwLock, RwLockReadGuard as SyncRwLockReadGuard, + RwLockWriteGuard as SyncRwLockWriteGuard, +}; pub use server::Server; pub use utils::{result, result::Result}; diff --git a/src/service/appservice/mod.rs b/src/service/appservice/mod.rs index 9a4d6f772..8a69921a3 100644 --- a/src/service/appservice/mod.rs +++ b/src/service/appservice/mod.rs @@ -1,20 +1,19 @@ mod namespace_regex; mod registration_info; -use std::{collections::BTreeMap, iter::IntoIterator, sync::Arc}; +use std::{collections::BTreeMap, sync::Arc}; use async_trait::async_trait; -use conduwuit::{Err, Result, err, utils::stream::IterStream}; +use conduwuit::{Err, Result, SyncRwLock, SyncRwLockReadGuard, err, utils::stream::IterStream}; use database::Map; -use futures::{Future, FutureExt, Stream, TryStreamExt}; +use futures::{Stream, TryStreamExt}; use ruma::{RoomAliasId, RoomId, UserId, api::appservice::Registration}; -use tokio::sync::{RwLock, RwLockReadGuard}; pub use self::{namespace_regex::NamespaceRegex, registration_info::RegistrationInfo}; use crate::{Dep, globals, sending, users}; pub struct Service { - registration_info: RwLock, + registration_info: SyncRwLock, services: Services, db: Data, } @@ -35,7 +34,7 @@ type Registrations = BTreeMap; impl crate::Service for Service { fn build(args: crate::Args<'_>) -> Result> { Ok(Arc::new(Self { - registration_info: RwLock::new(BTreeMap::new()), + registration_info: SyncRwLock::new(BTreeMap::new()), services: Services { globals: args.depend::("globals"), sending: args.depend::("sending"), @@ -123,7 +122,6 @@ impl Service { self.registration_info .write() - .await .insert(id, registration.try_into()?); Ok(()) @@ -139,7 +137,7 @@ impl Service { // Check for token collision with other appservices (allow // re-registration of same appservice) - if let Ok(existing) = self.find_from_token(®istration.as_token).await { + if let Ok(existing) = self.find_from_token(®istration.as_token) { if existing.registration.id != registration.id { return Err(err!(Request(InvalidParam( "Cannot register appservice: Token is already used by appservice '{}'. \ @@ -182,7 +180,6 @@ impl Service { // removes the appservice registration info self.registration_info .write() - .await .remove(appservice_id) .ok_or_else(|| err!("Appservice not found"))?; @@ -197,19 +194,17 @@ impl Service { .await } - pub async fn get_registration(&self, id: &str) -> Option { + pub fn get_registration(&self, id: &str) -> Option { self.registration_info .read() - .await .get(id) .cloned() .map(|info| info.registration) } /// Returns Result to match users::find_from_token for select_ok usage - pub async fn find_from_token(&self, token: &str) -> Result { + pub fn find_from_token(&self, token: &str) -> Result { self.read() - .await .values() .find(|info| info.registration.as_token == token) .cloned() @@ -217,26 +212,21 @@ impl Service { } /// Checks if a given user id matches any exclusive appservice regex - pub async fn is_exclusive_user_id(&self, user_id: &UserId) -> bool { + pub fn is_exclusive_user_id(&self, user_id: &UserId) -> bool { self.read() - .await .values() .any(|info| info.is_exclusive_user_match(user_id)) } /// Checks if a given user id matches any appservice regex, exclusive or /// otherwise - pub async fn is_user_id(&self, user_id: &UserId) -> bool { - self.read() - .await - .values() - .any(|info| info.is_user_match(user_id)) + pub fn is_user_id(&self, user_id: &UserId) -> bool { + self.read().values().any(|info| info.is_user_match(user_id)) } /// Checks if a given room alias matches any exclusive appservice regex - pub async fn is_exclusive_alias(&self, alias: &RoomAliasId) -> bool { + pub fn is_exclusive_alias(&self, alias: &RoomAliasId) -> bool { self.read() - .await .values() .any(|info| info.aliases.is_exclusive_match(alias.as_str())) } @@ -245,19 +235,15 @@ impl Service { /// /// TODO: use this? #[allow(dead_code)] - pub async fn is_exclusive_room_id(&self, room_id: &RoomId) -> bool { + pub fn is_exclusive_room_id(&self, room_id: &RoomId) -> bool { self.read() - .await .values() .any(|info| info.rooms.is_exclusive_match(room_id.as_str())) } pub fn iter_ids(&self) -> impl Stream + Send { - self.read() - .map(|info| info.keys().cloned().collect::>()) - .map(IntoIterator::into_iter) - .map(IterStream::stream) - .flatten_stream() + let ids: Vec = self.read().keys().cloned().collect(); + ids.stream() } pub fn iter_db_ids(&self) -> impl Stream> + Send { @@ -281,7 +267,5 @@ impl Service { }) } - pub fn read(&self) -> impl Future> + Send { - self.registration_info.read() - } + pub fn read(&self) -> SyncRwLockReadGuard<'_, Registrations> { self.registration_info.read() } } diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 3ed2d28a4..81ff11dd8 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -853,7 +853,7 @@ async fn split_userid_password(services: &Services) -> Result { userid_password.remove(&user_id); remote_users = remote_users.saturating_add(1); } else if hash.is_empty() { - if !(services.appservice.is_user_id(&user_id).await + if !(services.appservice.is_user_id(&user_id) || user_id == services.globals.server_user) { info!("Marking {user_id} as deactivated"); diff --git a/src/service/rooms/alias/mod.rs b/src/service/rooms/alias/mod.rs index 5056a02fc..bed0fd3c7 100644 --- a/src/service/rooms/alias/mod.rs +++ b/src/service/rooms/alias/mod.rs @@ -269,18 +269,26 @@ impl Service { ) -> Result> { use ruma::api::appservice::query::query_room_alias; - for appservice in self.services.appservice.read().await.values() { - if appservice.aliases.is_match(room_alias.as_str()) - && matches!( - self.services - .sending - .send_appservice_request( - appservice.registration.clone(), - query_room_alias::v1::Request::new(room_alias.to_owned()), - ) - .await, - Ok(Some(_opt_result)) - ) { + let matching_appservices: Vec<_> = self + .services + .appservice + .read() + .values() + .filter(|appservice| appservice.aliases.is_match(room_alias.as_str())) + .cloned() + .collect(); + + for appservice in matching_appservices { + if matches!( + self.services + .sending + .send_appservice_request( + appservice.registration.clone(), + query_room_alias::v1::Request::new(room_alias.to_owned()), + ) + .await, + Ok(Some(_opt_result)) + ) { return self .resolve_local_alias(room_alias) .await @@ -292,7 +300,7 @@ impl Service { Ok(None) } - pub async fn appservice_checks( + pub fn appservice_checks( &self, room_alias: &RoomAliasId, appservice_info: Option<&RegistrationInfo>, @@ -309,12 +317,7 @@ impl Service { if !info.aliases.is_match(room_alias.as_str()) { return Err!(Request(Exclusive("Room alias is not in namespace."))); } - } else if self - .services - .appservice - .is_exclusive_alias(room_alias) - .await - { + } else if self.services.appservice.is_exclusive_alias(room_alias) { return Err!(Request(Exclusive("Room alias reserved by appservice."))); } diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index 5f09c4638..663f98543 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -809,7 +809,6 @@ impl super::Service { .services .appservice .read() - .await .values() .map(ToOwned::to_owned) // TODO: is this to_owned expensive? .collect::>(); diff --git a/src/service/rooms/typing/mod.rs b/src/service/rooms/typing/mod.rs index 113b3cebf..0cd6385fa 100644 --- a/src/service/rooms/typing/mod.rs +++ b/src/service/rooms/typing/mod.rs @@ -1,7 +1,7 @@ use std::{collections::BTreeMap, sync::Arc}; use conduwuit::{ - Result, Server, debug_info, + Result, Server, SyncRwLock, debug_info, result::LogErr, utils::{self, IterStream}, }; @@ -14,7 +14,6 @@ use ruma::{ }, events::{EphemeralRoomEvent, SyncEphemeralRoomEvent, typing::TypingEventContent}, }; -use tokio::sync::RwLock; use crate::{Dep, globals, sending, sending::EduBuf, sync, users}; @@ -22,9 +21,9 @@ pub struct Service { server: Arc, services: Services, /// u64 is unix timestamp of timeout - pub typing: RwLock>>, + pub typing: SyncRwLock>>, /// timestamp of the last change to typing users - pub last_typing_update: RwLock>, + pub last_typing_update: SyncRwLock>, } struct Services { @@ -44,8 +43,8 @@ impl crate::Service for Service { sync: args.depend::("sync"), users: args.depend::("users"), }, - typing: RwLock::new(BTreeMap::new()), - last_typing_update: RwLock::new(BTreeMap::new()), + typing: SyncRwLock::new(BTreeMap::new()), + last_typing_update: SyncRwLock::new(BTreeMap::new()), })) } @@ -65,14 +64,12 @@ impl Service { // update clients self.typing .write() - .await .entry(room_id.to_owned()) .or_default() .insert(user_id.to_owned(), timeout); self.last_typing_update .write() - .await .insert(room_id.to_owned(), self.services.globals.next_count()?); self.services.sync.wake_all_joined(room_id).await; @@ -94,14 +91,12 @@ impl Service { // update clients self.typing .write() - .await .entry(room_id.to_owned()) .or_default() .remove(user_id); self.last_typing_update .write() - .await .insert(room_id.to_owned(), self.services.globals.next_count()?); self.services.sync.wake_all_joined(room_id).await; @@ -123,7 +118,7 @@ impl Service { let mut removable = Vec::new(); { - let typing = self.typing.read().await; + let typing = self.typing.read(); let Some(room) = typing.get(room_id) else { return Ok(()); }; @@ -139,7 +134,7 @@ impl Service { return Ok(()); } { - let mut typing = self.typing.write().await; + let mut typing = self.typing.write(); let room = typing.entry(room_id.to_owned()).or_default(); for user in &removable { debug_info!("typing timeout {user:?} in {room_id:?}"); @@ -150,7 +145,6 @@ impl Service { // update clients self.last_typing_update .write() - .await .insert(room_id.to_owned(), self.services.globals.next_count()?); self.services.sync.wake_all_joined(room_id).await; @@ -174,15 +168,14 @@ impl Service { Ok(self .last_typing_update .read() - .await .get(room_id) .copied() .unwrap_or(0)) } /// Returns a new typing EDU's content. - pub async fn typings_content(&self, room_id: &RoomId) -> TypingEventContent { - let room_typing_indicators = self.typing.read().await.get(room_id).cloned(); + pub fn typings_content(&self, room_id: &RoomId) -> TypingEventContent { + let room_typing_indicators = self.typing.read().get(room_id).cloned(); let Some(typing_indicators) = room_typing_indicators else { return TypingEventContent::new(Vec::new()); @@ -203,7 +196,7 @@ impl Service { room_id: &RoomId, sender_user: &UserId, ) -> Result> { - let room_typing_indicators = self.typing.read().await.get(room_id).cloned(); + let room_typing_indicators = self.typing.read().get(room_id).cloned(); let Some(typing_indicators) = room_typing_indicators else { return Ok(Vec::new()); @@ -265,7 +258,7 @@ impl Service { async fn appservice_send(&self, room_id: &RoomId) -> Result<()> { let edu = EphemeralData::Typing(EphemeralRoomEvent::new( room_id.to_owned(), - self.typings_content(room_id).await, + self.typings_content(room_id), )); let mut buf = EduBuf::new(); diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index 8cb1010cf..cc518f5a5 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -270,7 +270,6 @@ impl Service { .services .appservice .read() - .await .values() .filter(|appservice| appservice.registration.receive_ephemeral && filter(appservice)) .cloned() diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index 308dcbd79..0967abb38 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -810,7 +810,7 @@ impl Service { id: String, events: Vec, ) -> SendingResult { - let Some(appservice) = self.services.appservice.get_registration(&id).await else { + let Some(appservice) = self.services.appservice.get_registration(&id) else { return Err(( Destination::Appservice(id.clone()), Box::new(err!(Database(warn!(?id, "Missing appservice registration")))), diff --git a/src/service/sync/mod.rs b/src/service/sync/mod.rs index 5b50b38de..e3a07c40d 100644 --- a/src/service/sync/mod.rs +++ b/src/service/sync/mod.rs @@ -8,7 +8,7 @@ use futures::StreamExt; use ruma::{ OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId, api::client::sync::sync_events::v5, }; -use tokio::sync::{Mutex, watch}; +use tokio::sync::watch; use crate::{Dep, rooms}; @@ -71,28 +71,27 @@ pub type SnakeConnectionsKey = (OwnedUserId, OwnedDeviceId, Option); type SnakeConnectionsVal = Arc>; #[derive(Default)] -struct Wakers(Mutex>>); +struct Wakers(SyncMutex>>); impl Wakers { - async fn subscribe(&self, user: &UserId) -> watch::Receiver { + fn subscribe(&self, user: &UserId) -> watch::Receiver { self.0 .lock() - .await .entry(user.to_owned()) .or_insert_with(|| watch::channel(0).0) .subscribe() } - async fn wake(&self, user: &UserId) { - let mut wakers = self.0.lock().await; + fn wake(&self, user: &UserId) { + let mut wakers = self.0.lock(); wake_waker(&mut wakers, user); } - async fn wake_all(&self, users: I) + fn wake_all(&self, users: I) where - I: IntoIterator + Send, + I: IntoIterator, { - let mut wakers = self.0.lock().await; + let mut wakers = self.0.lock(); for user in users { wake_waker(&mut wakers, &user); } @@ -129,8 +128,8 @@ impl crate::Service for Service { } impl Service { - pub async fn subscribe_to_wake(&self, user: &UserId) -> watch::Receiver { - self.wakers.subscribe(user).await + pub fn subscribe_to_wake(&self, user: &UserId) -> watch::Receiver { + self.wakers.subscribe(user) } /// Wake the target user's sync loop. Call this when something @@ -143,7 +142,7 @@ impl Service { pub async fn wake(&self, user: &UserId) { trace!(?user, "Waking user's sync loops"); - self.wakers.wake(user).await; + self.wakers.wake(user); } /// Wake all of our users who are joined to the specified room. @@ -156,7 +155,7 @@ impl Service { .collect() .await; - self.wakers.wake_all(users).await; + self.wakers.wake_all(users); } pub fn snake_connection_cached(&self, key: &SnakeConnectionsKey) -> bool { @@ -359,11 +358,11 @@ mod tests { async fn wake_after_subscription_is_observable() { let wakers = Wakers::default(); let user = UserId::parse("@alice:example.com").unwrap(); - let mut receiver = wakers.subscribe(&user).await; + let mut receiver = wakers.subscribe(&user); let generation = *receiver.borrow_and_update(); - wakers.wake(&user).await; - wakers.wake(&user).await; + wakers.wake(&user); + wakers.wake(&user); receiver.changed().await.unwrap(); assert_eq!(*receiver.borrow_and_update(), generation.wrapping_add(2)); @@ -373,10 +372,10 @@ mod tests { async fn wake_notifies_all_subscribers() { let wakers = Wakers::default(); let user = UserId::parse("@alice:example.com").unwrap(); - let mut first = wakers.subscribe(&user).await; - let mut second = wakers.subscribe(&user).await; + let mut first = wakers.subscribe(&user); + let mut second = wakers.subscribe(&user); - wakers.wake(&user).await; + wakers.wake(&user); first.changed().await.unwrap(); second.changed().await.unwrap(); @@ -387,24 +386,24 @@ mod tests { let wakers = Wakers::default(); let user = UserId::parse("@alice:example.com").unwrap(); - wakers.wake(&user).await; - assert!(wakers.0.lock().await.is_empty()); + wakers.wake(&user); + assert!(wakers.0.lock().is_empty()); - drop(wakers.subscribe(&user).await); - assert_eq!(wakers.0.lock().await.len(), 1); + drop(wakers.subscribe(&user)); + assert_eq!(wakers.0.lock().len(), 1); - wakers.wake(&user).await; - assert!(wakers.0.lock().await.is_empty()); + wakers.wake(&user); + assert!(wakers.0.lock().is_empty()); } #[tokio::test] async fn subscriber_still_woken_after_a_sibling_disconnects() { let wakers = Wakers::default(); let user = UserId::parse("@alice:example.com").unwrap(); - let mut receiver = wakers.subscribe(&user).await; - drop(wakers.subscribe(&user).await); + let mut receiver = wakers.subscribe(&user); + drop(wakers.subscribe(&user)); - wakers.wake(&user).await; + wakers.wake(&user); receiver.changed().await.unwrap(); } diff --git a/src/service/users/account.rs b/src/service/users/account.rs index 39cadab32..9fc78d339 100644 --- a/src/service/users/account.rs +++ b/src/service/users/account.rs @@ -405,11 +405,7 @@ impl super::Service { "Username is not in this appservice's namespace." ))); } - } else if self - .services - .appservice - .is_exclusive_user_id(&user_id) - .await + } else if self.services.appservice.is_exclusive_user_id(&user_id) && !emergency_mode_enabled { return Err!(Request(Exclusive("Username is reserved by an appservice."))); diff --git a/src/service/users/device.rs b/src/service/users/device.rs index f5f40c57c..6933ea715 100644 --- a/src/service/users/device.rs +++ b/src/service/users/device.rs @@ -175,13 +175,7 @@ impl super::Service { } // Check for token collision with appservices - if self - .services - .appservice - .find_from_token(&token) - .await - .is_ok() - { + if self.services.appservice.find_from_token(&token).is_ok() { return Err!(Request(InvalidParam( "Token conflicts with an existing appservice token" ))); From addd1875d37d585cfe261f3f3c008ef297fbc506 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Mon, 12 Oct 2026 18:17:20 +0100 Subject: [PATCH 040/342] refactor(uiaa): Defer uiaa_sessions lock until session insert Do not hold the uiaa_sessions lock across device lookup in OAuth or during initial validation. Lock the map only when inserting the newly created session. --- src/service/uiaa/mod.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/service/uiaa/mod.rs b/src/service/uiaa/mod.rs index 0aebaed7e..96a92eb0f 100644 --- a/src/service/uiaa/mod.rs +++ b/src/service/uiaa/mod.rs @@ -278,8 +278,6 @@ impl Service { params: Box, initiator: Option>, ) -> Result { - let mut uiaa_sessions = self.uiaa_sessions.lock().await; - let session_id = utils::random_string(Self::SESSION_ID_LENGTH); let mut info = assign!(UiaaInfo::new(flows), { params: Some(params), session: Some(session_id.clone()) }); @@ -355,7 +353,10 @@ impl Service { ))); } - uiaa_sessions.insert(session_id, UiaaSession { session_metadata, info: info.clone() }); + self.uiaa_sessions + .lock() + .await + .insert(session_id, UiaaSession { session_metadata, info: info.clone() }); Ok(info) } From 0ceabb4b3e6e2244dfaf23cbba66c04edd812410 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Thu, 15 Oct 2026 12:52:49 +0100 Subject: [PATCH 041/342] chore: Changelog --- changelog.d/2351.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2351.bugfix.md diff --git a/changelog.d/2351.bugfix.md b/changelog.d/2351.bugfix.md new file mode 100644 index 000000000..873310447 --- /dev/null +++ b/changelog.d/2351.bugfix.md @@ -0,0 +1 @@ +Fix some possible deadlocks/freezes and reduce lock contention (improving performance). Contributed by @Jade From 6fae2475b82b08542df4b2c96249eda8fd07a7b0 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 28 Oct 2026 21:56:38 +0000 Subject: [PATCH 042/342] style: Format --- src/service/threepid/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/service/threepid/mod.rs b/src/service/threepid/mod.rs index cbc1fd080..ea39ef552 100644 --- a/src/service/threepid/mod.rs +++ b/src/service/threepid/mod.rs @@ -126,9 +126,9 @@ impl Service { let mut sessions = self.sessions.lock(); let session = match sessions.get_session_by_client_secret(client_secret) { - // If a validation session already exists for this client secret, we - // can either reuse it with a new token or return early because it's - // already valid. + // If a validation session already exists for this client + // secret, we can either reuse it with a new token or return + // early because it's already valid. | Some(session) => { if session.email != recipient.email { return Err!(Request(InvalidParam("Wrong email for session."))); From e8593eeaca53d99d336a64de53799c569510f8d2 Mon Sep 17 00:00:00 2001 From: Freek Date: Mon, 12 Oct 2026 19:40:38 +0200 Subject: [PATCH 043/342] docs(oidc): Add Authelia to OIDC instructions --- docs/authentication/oidc.mdx | 54 +++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx index 815d60af2..6c2dad3bc 100644 --- a/docs/authentication/oidc.mdx +++ b/docs/authentication/oidc.mdx @@ -14,7 +14,9 @@ A simple OIDC configuration is as easy as creating a new OIDC application in you ### Configuring the OIDC provider -This guide will use [**Kanidm**][kanidm] as an example, but the described steps are broadly applicable to other identity providers. Contributions for them are welcome. +This guide will cover [**Kanidm**][kanidm] and [**Authelia**][authelia], but the described steps are broadly applicable to other identity providers. Contributions for them are welcome. + +#### KanIDM First, create a new application for Continuwuity in your identity provider. @@ -46,6 +48,50 @@ d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr [kanidm]: https://kanidm.com +#### Authelia + +These instructions assume you have already set up Authelia as an OIDC provider and are just adding Continuwuity to it. If you are looking how to set up your Authelia as an OIDC provider, [this article](https://blog.stonegarden.dev/articles/2025/06/authelia-oidc/) is very useful. +To create a new client in your identity provider, it is [recommended](https://www.authelia.com/integration/openid-connect/frequently-asked-questions/#how-do-i-generate-a-client-identifier-or-client-secret) to randomly generate both the client id and client secret. The commands below should get you those: + +```sh +# Generate client ID: +authelia crypto rand --length 72 --charset rfc3986 +# or using Docker: +docker run --rm authelia/authelia:latest authelia crypto rand --length 72 --charset rfc3986 +``` + +Generate the client secret (shown as password in output) and its digest: +```sh +authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 +# or using Docker: +docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 +``` + +Authelia only needs to know the digest (hash) of the secret, whereas Continuwuity requires the secret itself. + +Also note the domain that clients can reach Continuwuity at, which may not be the same as your server name if you have configured well-known delegation. In this example, we will use `https://matrix.yourdomain.com` for that (your server name in this case may be `yourdomain.com`). + +Now we have everything we need to add Continuwuity to Authelia's OIDC client configuration. Go to your Authelia configuration file, find the `identity_provers` block, and add to the `clients` list: + +```yaml +identity_providers: + oidc: + jwks: + # This part has the JWKs and is what you configured previously + [...] + clients: + # Add this block below + - client_name: continuwuity + client_id: "client-id-goes-here" + client_secret: "client-secret-DIGEST-goes-here" + redirect_uris: ["https://matrix.yourdomain.com/_continuwuity/oidc/complete"] + scopes: [openid] +``` + +The discovery URL that continuwuity can use with Authelia is simply the root domain at which your Authelia can be reached by clients, which should be something like `https://authelia.example.com`. + +[authelia]: https://www.authelia.com + ### Configuring Continuwuity Configure Continuwuity with the client ID, client secret, and discovery URL provided from the steps above. Kanidm has a different discovery URL for each client, but other identity providers may have a single discovery URL at the root of their domain. @@ -54,10 +100,10 @@ Configure Continuwuity with the client ID, client secret, and discovery URL prov [global.oauth.oidc] # `/.well-known/openid-configuration` will be appended automatically -discovery_url = "https://idm.example.com/oauth2/openid/c10y" +# Choose the appropriate option from below, not both +discovery_url = "https://idm.example.com/oauth2/openid/c10y" # For KanIDM +discovery_url = "https://authelia.example.com/" # For Authelia -# This may be randomly generated by your identity provider. Kanidm requires -# you to set it manually when you create the application. client_id = "c10y" # From the previous step From 4cd0e737db3bddf6d4c584364ad26e3c8807ac3c Mon Sep 17 00:00:00 2001 From: Freek Date: Mon, 12 Oct 2026 19:40:38 +0200 Subject: [PATCH 044/342] docs(oidc): PR feedback: Use tabs for different identity providers, make "Configuring Continuwuity" section more idp-independent --- docs/authentication/oidc.mdx | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx index 6c2dad3bc..f238c6364 100644 --- a/docs/authentication/oidc.mdx +++ b/docs/authentication/oidc.mdx @@ -1,3 +1,5 @@ +import { Tab, Tabs } from '@rspress/core/theme'; + # Delegated authentication with OIDC Continuwuity supports delegating user authentication to an external identity provider that implements the OpenID Connect (OIDC) specification, such as Authentik, Kanidm, or Keycloak. @@ -16,7 +18,8 @@ A simple OIDC configuration is as easy as creating a new OIDC application in you This guide will cover [**Kanidm**][kanidm] and [**Authelia**][authelia], but the described steps are broadly applicable to other identity providers. Contributions for them are welcome. -#### KanIDM + + First, create a new application for Continuwuity in your identity provider. @@ -46,10 +49,10 @@ kanidm system oauth2 show-basic-secret c10y d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr ``` -[kanidm]: https://kanidm.com - -#### Authelia +If you followed these steps, the discovery URL for KanIDM is: https://idm.example.com/oauth2/openid/c10y + + These instructions assume you have already set up Authelia as an OIDC provider and are just adding Continuwuity to it. If you are looking how to set up your Authelia as an OIDC provider, [this article](https://blog.stonegarden.dev/articles/2025/06/authelia-oidc/) is very useful. To create a new client in your identity provider, it is [recommended](https://www.authelia.com/integration/openid-connect/frequently-asked-questions/#how-do-i-generate-a-client-identifier-or-client-secret) to randomly generate both the client id and client secret. The commands below should get you those: @@ -89,25 +92,32 @@ identity_providers: ``` The discovery URL that continuwuity can use with Authelia is simply the root domain at which your Authelia can be reached by clients, which should be something like `https://authelia.example.com`. + + +Whichever identity provider you\'re using, you should now have 3 things, which you\'ll need in the next section to configure Continuwuity itself: + +- Client Identifier (or client id) +- Client Secret +- Discovery URL + +[kanidm]: https://kanidm.com [authelia]: https://www.authelia.com ### Configuring Continuwuity -Configure Continuwuity with the client ID, client secret, and discovery URL provided from the steps above. Kanidm has a different discovery URL for each client, but other identity providers may have a single discovery URL at the root of their domain. +Configure Continuwuity with the client ID, client secret, and discovery URL provided from the steps above. ```toml [global.oauth.oidc] # `/.well-known/openid-configuration` will be appended automatically # Choose the appropriate option from below, not both -discovery_url = "https://idm.example.com/oauth2/openid/c10y" # For KanIDM -discovery_url = "https://authelia.example.com/" # For Authelia +discovery_url = "https://your-discovery-url" -client_id = "c10y" +client_id = "your-client-id" -# From the previous step -client_secret = "d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr" +client_secret = "your-client-secret" ``` ### Testing that it works From 0adfd32b0c28071932c74a0fb4a9185d459bc7b1 Mon Sep 17 00:00:00 2001 From: Freek Date: Mon, 12 Oct 2026 19:40:37 +0200 Subject: [PATCH 045/342] docs(oidc): Simplify, deduplicate and improve consistency --- docs/authentication/oidc.mdx | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx index f238c6364..5c64a0eb1 100644 --- a/docs/authentication/oidc.mdx +++ b/docs/authentication/oidc.mdx @@ -16,18 +16,18 @@ A simple OIDC configuration is as easy as creating a new OIDC application in you ### Configuring the OIDC provider -This guide will cover [**Kanidm**][kanidm] and [**Authelia**][authelia], but the described steps are broadly applicable to other identity providers. Contributions for them are welcome. +This guide will cover [**Kanidm**][kanidm] and [**Authelia**][authelia], but the basic concepts apply to most identity providers. Contributions for them are welcome. + +Before you start, note the domain that clients can reach Continuwuity at, which may not be the same as your server name if you have configured well-known delegation. In this example, we will use `https://matrix.yourdomain.com`. -First, create a new application for Continuwuity in your identity provider. +Create a new application for continuwuity in kanidm. ```sh # Here, `c10y` is the client ID that Kanidm will use, and `Continuwuity` is the display name. # Other identity providers may generate a client ID for you. -# Use the domain that clients can reach Continuwuity at, which may not be the same as your server name -# if you have configured well-known delegation. kanidm system oauth2 create c10y Continuwuity https://matrix.yourdomain.com ``` @@ -37,22 +37,23 @@ Configure the redirect URL that Continuwuity uses. kanidm system oauth2 add-redirect-url c10y https://matrix.yourdomain.com/_continuwuity/oidc/complete ``` -Allow Continuwuity to request the `openid` scope. Other identity providers may not require this step. +Allow Continuwuity to request the `openid` scope. ```sh kanidm system oauth2 update-scope-map c10y idm_all_persons openid ``` -Find the client secret that was generated. Other identity providers may show this information in their web UI. +Find the client secret that was generated. ```sh kanidm system oauth2 show-basic-secret c10y d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr ``` -If you followed these steps, the discovery URL for KanIDM is: https://idm.example.com/oauth2/openid/c10y +Now the discovery URL for KanIDM is: https://idm.yourdomain.com/oauth2/openid/c10y + These instructions assume you have already set up Authelia as an OIDC provider and are just adding Continuwuity to it. If you are looking how to set up your Authelia as an OIDC provider, [this article](https://blog.stonegarden.dev/articles/2025/06/authelia-oidc/) is very useful. To create a new client in your identity provider, it is [recommended](https://www.authelia.com/integration/openid-connect/frequently-asked-questions/#how-do-i-generate-a-client-identifier-or-client-secret) to randomly generate both the client id and client secret. The commands below should get you those: @@ -72,8 +73,6 @@ docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 -- Authelia only needs to know the digest (hash) of the secret, whereas Continuwuity requires the secret itself. -Also note the domain that clients can reach Continuwuity at, which may not be the same as your server name if you have configured well-known delegation. In this example, we will use `https://matrix.yourdomain.com` for that (your server name in this case may be `yourdomain.com`). - Now we have everything we need to add Continuwuity to Authelia's OIDC client configuration. Go to your Authelia configuration file, find the `identity_provers` block, and add to the `clients` list: ```yaml @@ -90,16 +89,13 @@ identity_providers: redirect_uris: ["https://matrix.yourdomain.com/_continuwuity/oidc/complete"] scopes: [openid] ``` +Then restart Authelia to load the new configuration. + +The discovery URL is simply the root domain at which your Authelia can be reached by clients, which should be something like `https://authelia.yourdomain.com`. -The discovery URL that continuwuity can use with Authelia is simply the root domain at which your Authelia can be reached by clients, which should be something like `https://authelia.example.com`. -Whichever identity provider you\'re using, you should now have 3 things, which you\'ll need in the next section to configure Continuwuity itself: - -- Client Identifier (or client id) -- Client Secret -- Discovery URL [kanidm]: https://kanidm.com [authelia]: https://www.authelia.com From c6d220dc607f8255f2284ce67c156d3a92ad8848 Mon Sep 17 00:00:00 2001 From: Freek Date: Mon, 12 Oct 2026 19:40:35 +0200 Subject: [PATCH 046/342] docs(oidc): Styling and QoL fixes --- docs/authentication/oidc.mdx | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx index 5c64a0eb1..5fd51fa55 100644 --- a/docs/authentication/oidc.mdx +++ b/docs/authentication/oidc.mdx @@ -18,7 +18,9 @@ A simple OIDC configuration is as easy as creating a new OIDC application in you This guide will cover [**Kanidm**][kanidm] and [**Authelia**][authelia], but the basic concepts apply to most identity providers. Contributions for them are welcome. -Before you start, note the domain that clients can reach Continuwuity at, which may not be the same as your server name if you have configured well-known delegation. In this example, we will use `https://matrix.yourdomain.com`. +:::important Server domain or account domain? +Before you start, note the domain that clients can reach Continuwuity at, which may not be the same as your account domain if you have configured well-known delegation. In this example, we will use `https://matrix.yourdomain.com` for the server domain. +::: @@ -57,32 +59,39 @@ Now the discovery URL for KanIDM is: https://idm.yourdomain.com/oauth2/openid/c1 These instructions assume you have already set up Authelia as an OIDC provider and are just adding Continuwuity to it. If you are looking how to set up your Authelia as an OIDC provider, [this article](https://blog.stonegarden.dev/articles/2025/06/authelia-oidc/) is very useful. To create a new client in your identity provider, it is [recommended](https://www.authelia.com/integration/openid-connect/frequently-asked-questions/#how-do-i-generate-a-client-identifier-or-client-secret) to randomly generate both the client id and client secret. The commands below should get you those: + + ```sh -# Generate client ID: +echo "Random value for Client ID:" authelia crypto rand --length 72 --charset rfc3986 -# or using Docker: -docker run --rm authelia/authelia:latest authelia crypto rand --length 72 --charset rfc3986 -``` - -Generate the client secret (shown as password in output) and its digest: -```sh +echo "\nClient Secret (labeled Random Password) and its Digest:" authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 -# or using Docker: +``` + + +```sh +echo "Random value for Client ID:" +docker run --rm authelia/authelia:latest authelia crypto rand --length 72 --charset rfc3986 +echo "\nClient Secret (labeled Random Password) and its Digest:" docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 ``` + + -Authelia only needs to know the digest (hash) of the secret, whereas Continuwuity requires the secret itself. +:::important client secret or digest? +Authelia only needs to know the digest of the secret, whereas Continuwuity requires the secret itself. +::: -Now we have everything we need to add Continuwuity to Authelia's OIDC client configuration. Go to your Authelia configuration file, find the `identity_provers` block, and add to the `clients` list: +Go to your Authelia configuration file, find the `identity_provers` block, and add a block for Continuwuity to the `clients` list: ```yaml identity_providers: oidc: jwks: # This part has the JWKs and is what you configured previously - [...] + # ... clients: - # Add this block below + # Add this block below to the clients list - client_name: continuwuity client_id: "client-id-goes-here" client_secret: "client-secret-DIGEST-goes-here" From 1c82c57d9f15459150b32ec93ef5c973c4423a2b Mon Sep 17 00:00:00 2001 From: Freek Date: Mon, 12 Oct 2026 19:40:30 +0200 Subject: [PATCH 047/342] docs(oidc): PR feedback --- docs/authentication/oidc.mdx | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx index 5fd51fa55..259752c34 100644 --- a/docs/authentication/oidc.mdx +++ b/docs/authentication/oidc.mdx @@ -14,14 +14,16 @@ An account on the homeserver can only be associated with one OIDC subject claim A simple OIDC configuration is as easy as creating a new OIDC application in your identity provider's settings and supplying Continuwuity with the client ID and client secret. +:::important Server domain or account domain? +Before you start, note the server domain that clients can reach Continuwuity at, which may not be the same as your account domain if you have [configured well-known delegation](../guides/delegation). +::: + +In this guide, we will use https://matrix.yourdomain.com for the homeserver address that clients can reach, and https://idm.yourdomain.com for the identity provider address. + ### Configuring the OIDC provider This guide will cover [**Kanidm**][kanidm] and [**Authelia**][authelia], but the basic concepts apply to most identity providers. Contributions for them are welcome. -:::important Server domain or account domain? -Before you start, note the domain that clients can reach Continuwuity at, which may not be the same as your account domain if you have configured well-known delegation. In this example, we will use `https://matrix.yourdomain.com` for the server domain. -::: - @@ -56,31 +58,28 @@ Now the discovery URL for KanIDM is: https://idm.yourdomain.com/oauth2/openid/c1 -These instructions assume you have already set up Authelia as an OIDC provider and are just adding Continuwuity to it. If you are looking how to set up your Authelia as an OIDC provider, [this article](https://blog.stonegarden.dev/articles/2025/06/authelia-oidc/) is very useful. -To create a new client in your identity provider, it is [recommended](https://www.authelia.com/integration/openid-connect/frequently-asked-questions/#how-do-i-generate-a-client-identifier-or-client-secret) to randomly generate both the client id and client secret. The commands below should get you those: +To create a new client in Authelia, it is [recommended][authelia-faq-client-secret] to randomly generate both the client id and client secret. The commands below should get you those: ```sh -echo "Random value for Client ID:" +# Random value for Client ID: authelia crypto rand --length 72 --charset rfc3986 -echo "\nClient Secret (labeled Random Password) and its Digest:" +# Client Secret (labeled Random Password) and its Digest: authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 ``` ```sh -echo "Random value for Client ID:" +# Random value for Client ID: docker run --rm authelia/authelia:latest authelia crypto rand --length 72 --charset rfc3986 -echo "\nClient Secret (labeled Random Password) and its Digest:" +# Client Secret (labeled Random Password) and its Digest: docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 ``` -:::important client secret or digest? Authelia only needs to know the digest of the secret, whereas Continuwuity requires the secret itself. -::: Go to your Authelia configuration file, find the `identity_provers` block, and add a block for Continuwuity to the `clients` list: @@ -94,13 +93,14 @@ identity_providers: # Add this block below to the clients list - client_name: continuwuity client_id: "client-id-goes-here" + # Use the client secret's DIGEST, not the client secret itself client_secret: "client-secret-DIGEST-goes-here" redirect_uris: ["https://matrix.yourdomain.com/_continuwuity/oidc/complete"] scopes: [openid] ``` Then restart Authelia to load the new configuration. -The discovery URL is simply the root domain at which your Authelia can be reached by clients, which should be something like `https://authelia.yourdomain.com`. +The discovery URL is simply the root domain at which your Authelia can be reached by clients, which should be something like `https://idm.yourdomain.com`. @@ -108,6 +108,7 @@ The discovery URL is simply the root domain at which your Authelia can be reache [kanidm]: https://kanidm.com [authelia]: https://www.authelia.com +[authelia-faq-client-secret]: https://www.authelia.com/integration/openid-connect/frequently-asked-questions/#how-do-i-generate-a-client-identifier-or-client-secret ### Configuring Continuwuity From f2cf1b23315c153907e012d87376ee3671079aa0 Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 12 Oct 2026 13:18:36 +0000 Subject: [PATCH 048/342] docs(oidc): Sweepfixes for PR2341 * Replaces yourdomain.com with example.com (other pages use this) * Improve initial domain instructions, remove important block there * Capitalize "Bare Metal/Docker" tabs --- docs/authentication/oidc.mdx | 38 +++++++++++++++--------------------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx index 259752c34..709eef1d2 100644 --- a/docs/authentication/oidc.mdx +++ b/docs/authentication/oidc.mdx @@ -14,11 +14,10 @@ An account on the homeserver can only be associated with one OIDC subject claim A simple OIDC configuration is as easy as creating a new OIDC application in your identity provider's settings and supplying Continuwuity with the client ID and client secret. -:::important Server domain or account domain? -Before you start, note the server domain that clients can reach Continuwuity at, which may not be the same as your account domain if you have [configured well-known delegation](../guides/delegation). -::: +The instructions below make the following assumptions: -In this guide, we will use https://matrix.yourdomain.com for the homeserver address that clients can reach, and https://idm.yourdomain.com for the identity provider address. +- Continuwuity's base URL: `https://matrix.example.com`. Note that if you employ [well-known delegation](../guides/delegation), this must match the client well-known domain rather than your server name. +- OIDC provider's base URL: `https://idm.example.com` ### Configuring the OIDC provider @@ -27,18 +26,16 @@ This guide will cover [**Kanidm**][kanidm] and [**Authelia**][authelia], but the -Create a new application for continuwuity in kanidm. +Create a new application for continuwuity in kanidm. We will use `c10y` as the client ID. ```sh -# Here, `c10y` is the client ID that Kanidm will use, and `Continuwuity` is the display name. -# Other identity providers may generate a client ID for you. -kanidm system oauth2 create c10y Continuwuity https://matrix.yourdomain.com +kanidm system oauth2 create c10y Continuwuity https://matrix.example.com ``` Configure the redirect URL that Continuwuity uses. ```sh -kanidm system oauth2 add-redirect-url c10y https://matrix.yourdomain.com/_continuwuity/oidc/complete +kanidm system oauth2 add-redirect-url c10y https://matrix.example.com/_continuwuity/oidc/complete ``` Allow Continuwuity to request the `openid` scope. @@ -53,27 +50,27 @@ kanidm system oauth2 show-basic-secret c10y d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr ``` -Now the discovery URL for KanIDM is: https://idm.yourdomain.com/oauth2/openid/c10y +Now the discovery URL for KanIDM is: `https://idm.example.com/oauth2/openid/c10y` To create a new client in Authelia, it is [recommended][authelia-faq-client-secret] to randomly generate both the client id and client secret. The commands below should get you those: - - + + ```sh -# Random value for Client ID: +# Generate random value for Client ID authelia crypto rand --length 72 --charset rfc3986 -# Client Secret (labeled Random Password) and its Digest: +# Generate Client Secret (labeled Random Password) and its Digest authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 ``` - + ```sh -# Random value for Client ID: +# Generate random value for Client ID docker run --rm authelia/authelia:latest authelia crypto rand --length 72 --charset rfc3986 -# Client Secret (labeled Random Password) and its Digest: +# Generate Client Secret (labeled Random Password) and its Digest docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 ``` @@ -95,17 +92,16 @@ identity_providers: client_id: "client-id-goes-here" # Use the client secret's DIGEST, not the client secret itself client_secret: "client-secret-DIGEST-goes-here" - redirect_uris: ["https://matrix.yourdomain.com/_continuwuity/oidc/complete"] + redirect_uris: ["https://matrix.example.com/_continuwuity/oidc/complete"] scopes: [openid] ``` Then restart Authelia to load the new configuration. -The discovery URL is simply the root domain at which your Authelia can be reached by clients, which should be something like `https://idm.yourdomain.com`. +The discovery URL is simply the root domain of your Authelia can be reached by clients, i.e. `https://idm.example.com`. - [kanidm]: https://kanidm.com [authelia]: https://www.authelia.com [authelia-faq-client-secret]: https://www.authelia.com/integration/openid-connect/frequently-asked-questions/#how-do-i-generate-a-client-identifier-or-client-secret @@ -118,11 +114,9 @@ Configure Continuwuity with the client ID, client secret, and discovery URL prov [global.oauth.oidc] # `/.well-known/openid-configuration` will be appended automatically -# Choose the appropriate option from below, not both discovery_url = "https://your-discovery-url" client_id = "your-client-id" - client_secret = "your-client-secret" ``` From ea5d2f4d4c12e9d78921acbe06bc446f25823f19 Mon Sep 17 00:00:00 2001 From: Freek Date: Mon, 12 Oct 2026 19:40:21 +0200 Subject: [PATCH 049/342] fix: spelling --- docs/authentication/oidc.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx index 709eef1d2..eafb82d73 100644 --- a/docs/authentication/oidc.mdx +++ b/docs/authentication/oidc.mdx @@ -97,7 +97,7 @@ identity_providers: ``` Then restart Authelia to load the new configuration. -The discovery URL is simply the root domain of your Authelia can be reached by clients, i.e. `https://idm.example.com`. +The discovery URL is simply the root domain of your Authelia, where it can be reached by clients, i.e. `https://idm.example.com`. From a96fec4cbcaa14d7c421377598c23b03a28833c2 Mon Sep 17 00:00:00 2001 From: Freek Date: Tue, 13 Oct 2026 12:02:36 +0200 Subject: [PATCH 050/342] chore: Add changelog --- changelog.d/2341.doc.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2341.doc.md diff --git a/changelog.d/2341.doc.md b/changelog.d/2341.doc.md new file mode 100644 index 000000000..16438a402 --- /dev/null +++ b/changelog.d/2341.doc.md @@ -0,0 +1 @@ +Instructions for Authelia added to the [OIDC guide](https://continuwuity.org/authentication/oidc.html). Contributed by @fhoekstra From bdb376c8fd585643e7e5b3269d08afe8a704761b Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 26 Oct 2026 06:06:27 +0000 Subject: [PATCH 051/342] chore(deps): update rust crate lock_api to 0.5.0 --- Cargo.lock | 21 +++++++++++++++------ Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8b24ee354..e5ab0949a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1045,7 +1045,7 @@ dependencies = [ "lettre", "libc", "libloading 0.9.0", - "lock_api", + "lock_api 0.5.0", "log", "maplit", "nix", @@ -3364,6 +3364,15 @@ dependencies = [ "scopeguard", ] +[[package]] +name = "lock_api" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -3780,7 +3789,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "chrono", "getrandom 0.2.17", "http", @@ -4190,7 +4199,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ - "lock_api", + "lock_api 0.4.14", "parking_lot_core", ] @@ -4560,7 +4569,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.13.0", "proc-macro2", "quote", "syn 2.0.119", @@ -5623,7 +5632,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8050abb251097357e24aff63ba2c52a6309ecb7d23a5474023df960a02694d8" dependencies = [ "annotate-snippets", - "base64 0.21.7", + "base64 0.23.1", "encoding_rs_io", "granit-parser", "nohash-hasher", @@ -5982,7 +5991,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d96d2d1d716fb500937168cc09353ffdc7a012be8475ac7308e1bdf0e3923300" dependencies = [ - "lock_api", + "lock_api 0.4.14", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1508b5267..97569afa9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -544,7 +544,7 @@ features = ["hardware-lock-elision", "deadlock_detection"] # TODO: Check if dead # Use this when extending with_lock::WithLock to parking_lot [workspace.dependencies.lock_api] -version = "0.4.13" +version = "0.5.0" [workspace.dependencies.bytesize] version = "2.0" From a825b7db8baf7434a7801e0edee8bbe2d97f32ea Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 27 Oct 2026 05:19:26 +0000 Subject: [PATCH 052/342] chore(deps): update ruma digest to e03080c --- Cargo.lock | 40 ++++++++++++++++++++-------------------- Cargo.toml | 2 +- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e5ab0949a..07a843926 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4996,8 +4996,8 @@ dependencies = [ [[package]] name = "ruma" -version = "0.17.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.17.2" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "assign", "js_int", @@ -5015,8 +5015,8 @@ dependencies = [ [[package]] name = "ruma-appservice-api" -version = "0.17.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.17.1" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "http", "js_int", @@ -5028,8 +5028,8 @@ dependencies = [ [[package]] name = "ruma-client-api" -version = "0.25.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.25.2" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "as_variant", "assign", @@ -5050,8 +5050,8 @@ dependencies = [ [[package]] name = "ruma-common" -version = "0.20.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.20.2" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "as_variant", "base64 0.23.1", @@ -5083,8 +5083,8 @@ dependencies = [ [[package]] name = "ruma-events" -version = "0.35.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.35.2" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "as_variant", "indexmap 2.14.2", @@ -5104,8 +5104,8 @@ dependencies = [ [[package]] name = "ruma-federation-api" -version = "0.16.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.16.1" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "bytes", "http", @@ -5126,8 +5126,8 @@ dependencies = [ [[package]] name = "ruma-identifiers-validation" -version = "0.12.1" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.14.0" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "js_int", "thiserror 2.0.21", @@ -5135,8 +5135,8 @@ dependencies = [ [[package]] name = "ruma-macros" -version = "0.20.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.20.2" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "as_variant", "cfg-if", @@ -5152,7 +5152,7 @@ dependencies = [ [[package]] name = "ruma-push-gateway-api" version = "0.16.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "js_int", "ruma-common", @@ -5163,8 +5163,8 @@ dependencies = [ [[package]] name = "ruma-signatures" -version = "0.22.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +version = "0.22.1" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "base64 0.23.1", "ed25519-dalek 3.0.0", @@ -5181,7 +5181,7 @@ dependencies = [ [[package]] name = "ruma-state-res" version = "0.18.0" -source = "git+https://github.com/ruma/ruma.git?rev=62659d64f712adf3cad126df6b8969f785414bd5#62659d64f712adf3cad126df6b8969f785414bd5" +source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" dependencies = [ "js_int", "ruma-common", diff --git a/Cargo.toml b/Cargo.toml index 97569afa9..c49437807 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -348,7 +348,7 @@ version = "1.1.1" # Used for matrix spec type definitions and helpers [workspace.dependencies.ruma] git = "https://github.com/ruma/ruma.git" -rev = "62659d64f712adf3cad126df6b8969f785414bd5" +rev = "e03080c0790ba7b24ea37f9fd11794678cc975b0" features = [ "appservice-api-c", "client-api", From c5e976f4bc54550ebb616d3292165b94d74cd295 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Mon, 19 Oct 2026 17:24:44 +0200 Subject: [PATCH 053/342] fix: Store event_id on state events received from send_knock --- src/api/client/membership/knock.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/api/client/membership/knock.rs b/src/api/client/membership/knock.rs index f24ede158..d4d3417d6 100644 --- a/src/api/client/membership/knock.rs +++ b/src/api/client/membership/knock.rs @@ -587,7 +587,7 @@ async fn knock_room_helper_remote( let mut state_map: HashMap = HashMap::new(); - for event in state { + for mut event in state { let Some(state_key) = event.get("state_key") else { debug_warn!("send_knock stripped state event missing state_key: {event:?}"); continue; @@ -614,6 +614,7 @@ async fn knock_room_helper_remote( .get_or_create_shortstatekey(&event_type, &state_key) .await; + event.insert("event_id".into(), CanonicalJsonValue::String(event_id.to_string())); services.rooms.outlier.add_pdu_outlier(&event_id, &event); state_map.insert(shortstatekey, event_id.clone()); } From 2604b13ef620d0b533564c57728f2de267987d94 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Mon, 19 Oct 2026 17:55:44 +0200 Subject: [PATCH 054/342] chore: Add changelog --- changelog.d/2387.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2387.bugfix.md diff --git a/changelog.d/2387.bugfix.md b/changelog.d/2387.bugfix.md new file mode 100644 index 000000000..7c82bdffd --- /dev/null +++ b/changelog.d/2387.bugfix.md @@ -0,0 +1 @@ +Fixed a worker panic when knocking on a room over federation. Contributed by @eleboucher. From 17d575c3e3ca3951ecc9e57cef5513665c427a2a Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 12 Oct 2026 18:06:16 +0000 Subject: [PATCH 055/342] docs(docker): Use bind mounts instead of docker volumes Old volumes of `db` are replaced with bind mounts of `continuwuity-data`. Other volumes are also converted. This is more beginner-friendly. --- docs/deploying/docker.mdx | 33 +++++++--- .../delegated.docker-compose.for-traefik.yml | 2 +- ...gated.docker-compose.with-caddy-labels.yml | 7 +-- .../delegated.docker-compose.with-caddy.yml | 7 +-- .../delegated.docker-compose.with-traefik.yml | 8 +-- .../deploying/docker-compose.for-traefik.yml | 7 +-- .../docker-compose.with-caddy-labels.yml | 4 +- .../deploying/docker-compose.with-caddy.yml | 7 +-- .../deploying/docker-compose.with-traefik.yml | 8 +-- docs/public/deploying/docker-compose.yml | 63 +++++++++---------- 10 files changed, 68 insertions(+), 78 deletions(-) diff --git a/docs/deploying/docker.mdx b/docs/deploying/docker.mdx index d7133ee68..7a0a65dd7 100644 --- a/docs/deploying/docker.mdx +++ b/docs/deploying/docker.mdx @@ -53,7 +53,7 @@ For more setups with `.well-known` delegation and split-domain deployments, cons Docker Compose is the recommended deployment method for Continuwuity containers. The following environment variables will be set: - `CONTINUWUITY_SERVER_NAME` - Your Matrix server's domain name. **This CANNOT be changed later without a data wipe.** -- `CONTINUWUITY_DATABASE_PATH` - Where to store your database. This must match the docker volume mount. +- `CONTINUWUITY_DATABASE_PATH` - Where to store your database. This must match the docker bind mount. - `CONTINUWUITY_ADDRESS` - Bind address (for Docker, use `0.0.0.0` to listen on all interfaces). Alternatively, you can specify a path to mount the configuration file using the `CONTINUWUITY_CONFIG` environment variable. @@ -89,7 +89,9 @@ Consult the [**DNS tuning guide (recommended)**](../guides/dns.mdx) for full sol docker-compose.with-caddy.yml ([view raw](/deploying/docker-compose.with-caddy.yml)) -Create a Caddyfile with the following content: +Create a directory called `caddy-data`, which will store TLS certs obtained by Caddy. + +Then, create a Caddyfile with the following content: ``` https://example.com:443, https://example.com:8448 { @@ -97,7 +99,7 @@ https://example.com:443, https://example.com:8448 { } ``` -Then, for the docker-compose: +Then, for the docker compose file: ```yaml file="../public/deploying/docker-compose.with-caddy.yml" @@ -110,6 +112,10 @@ Then, for the docker-compose:
docker-compose.with-caddy-labels.yml ([view raw](/deploying/docker-compose.with-caddy-labels.yml)) +Create a directory called `caddy-data`, which will store TLS certs obtained by Caddy. + +Then, for the docker compose file: + ```yaml file="../public/deploying/docker-compose.with-caddy-labels.yml" ``` @@ -132,6 +138,10 @@ Then, for the docker-compose:
docker-compose.with-traefik.yml ([view raw](/deploying/docker-compose.with-traefik.yml)) +Create a directory called `traefik-acme-data`, which will store TLS certs obtained by Caddy. + +Then, for the docker compose file: + ```yaml file="../public/deploying/docker-compose.with-traefik.yml" ``` @@ -164,10 +174,15 @@ See the [Other reverse proxies](generic.mdx#setting-up-the-reverse-proxy) sectio ### Starting Your Server -1. Choose your compose file from the above, and rename it to `docker-compose.yml`. Replace `example.com` with your homeserver's domain name, and edit other values as you see fit. -2. If using the override file, rename it to `docker-compose.override.yml` and - edit your values. -3. Start the server: +1. Create a directory named `continuwuity-data`. This will be where your server's database lives. + +2. Choose your compose file from the above, and rename it to `docker-compose.yml`. Replace `example.com` with your homeserver's domain name, and edit other values as you see fit. + + - Follow all extra instructions as needed. + + - If using the override file, rename it to `docker-compose.override.yml` and edit your values. + +3. Start the server with the following command: ```bash docker compose up -d @@ -189,9 +204,7 @@ See the [Other reverse proxies](generic.mdx#setting-up-the-reverse-proxy) sectio Pick your own username and password! ``` -5. Log in to your server with any Matrix client, and register for an account with the registration token from step 4. You'll automatically be invited to the admin room where you can [manage your server](../reference/admin). - -See the [generic deployment guide](generic.mdx) for more deployment options. +5. Log in to your server with any Matrix client, and register for an account with the registration token from the previous step. You'll automatically be invited to the admin room where you can [manage your server](../reference/admin). ## Testing diff --git a/docs/public/advanced/delegated.docker-compose.for-traefik.yml b/docs/public/advanced/delegated.docker-compose.for-traefik.yml index 4b5d0fed8..c0e034d78 100644 --- a/docs/public/advanced/delegated.docker-compose.for-traefik.yml +++ b/docs/public/advanced/delegated.docker-compose.for-traefik.yml @@ -6,7 +6,7 @@ services: restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's #- ./continuwuity.toml:/etc/continuwuity.toml networks: diff --git a/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml b/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml index 3a0f9566b..f1509f756 100644 --- a/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml +++ b/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml @@ -12,7 +12,7 @@ services: - proxy volumes: - /var/run/docker.sock:/var/run/docker.sock - - ./data:/data + - ./caddy-data:/data restart: unless-stopped labels: caddy: example.com @@ -23,7 +23,7 @@ services: restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's # - ./continuwuity.toml:/etc/continuwuity.toml environment: @@ -46,8 +46,5 @@ services: caddy: matrix.example.com caddy.reverse_proxy: "{{upstreams 8008}}" -volumes: - db: - networks: proxy: diff --git a/docs/public/advanced/delegated.docker-compose.with-caddy.yml b/docs/public/advanced/delegated.docker-compose.with-caddy.yml index 99c3b3435..4385ed3eb 100644 --- a/docs/public/advanced/delegated.docker-compose.with-caddy.yml +++ b/docs/public/advanced/delegated.docker-compose.with-caddy.yml @@ -9,7 +9,7 @@ services: networks: - caddy volumes: - - ./data:/data + - ./caddy-data:/data # mount your created Caddyfile into the container - ./Caddyfile:/etc/caddy/Caddyfile restart: unless-stopped @@ -19,7 +19,7 @@ services: restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's # - ./continuwuity.toml:/etc/continuwuity.toml environment: @@ -41,6 +41,3 @@ services: networks: proxy: - -volumes: - db: diff --git a/docs/public/advanced/delegated.docker-compose.with-traefik.yml b/docs/public/advanced/delegated.docker-compose.with-traefik.yml index 675f2a18e..54aea19ec 100644 --- a/docs/public/advanced/delegated.docker-compose.with-traefik.yml +++ b/docs/public/advanced/delegated.docker-compose.with-traefik.yml @@ -6,7 +6,7 @@ services: restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's #- ./continuwuity.toml:/etc/continuwuity.toml networks: @@ -40,7 +40,7 @@ services: - "443:443" volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - - "acme:/etc/traefik/acme" + - "./traefik-acme-data:/etc/traefik/acme" labels: - "traefik.enable=true" @@ -77,9 +77,5 @@ services: TRAEFIK_PROVIDERS_DOCKER_ENDPOINT: "unix:///var/run/docker.sock" TRAEFIK_PROVIDERS_DOCKER_EXPOSEDBYDEFAULT: false -volumes: - db: - acme: - networks: proxy: diff --git a/docs/public/deploying/docker-compose.for-traefik.yml b/docs/public/deploying/docker-compose.for-traefik.yml index 61cdb1bea..229a95a66 100644 --- a/docs/public/deploying/docker-compose.for-traefik.yml +++ b/docs/public/deploying/docker-compose.for-traefik.yml @@ -6,7 +6,7 @@ services: restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's #- ./continuwuity.toml:/etc/continuwuity.toml networks: @@ -18,7 +18,7 @@ services: - "traefik.http.routers.continuwuity.tls=true" - "traefik.http.routers.continuwuity.service=continuwuity" - "traefik.http.services.continuwuity.loadbalancer.server.port=8008" - # possibly, depending on your config: + # enable tls with the `letsencrypt` certificate resolver (actual name dependant on your static config) # - "traefik.http.routers.continuwuity.tls.certresolver=letsencrypt" environment: CONTINUWUITY_SERVER_NAME: example.com @@ -34,9 +34,6 @@ services: server=example.com:443 } -volumes: - db: - networks: # This must match the network name that Traefik listens on proxy: diff --git a/docs/public/deploying/docker-compose.with-caddy-labels.yml b/docs/public/deploying/docker-compose.with-caddy-labels.yml index 078e7802b..ab55f93ec 100644 --- a/docs/public/deploying/docker-compose.with-caddy-labels.yml +++ b/docs/public/deploying/docker-compose.with-caddy-labels.yml @@ -12,7 +12,7 @@ services: - proxy volumes: - /var/run/docker.sock:/var/run/docker.sock - - ./data:/data + - ./caddy-data:/data restart: unless-stopped homeserver: @@ -20,7 +20,7 @@ services: restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's # - ./continuwuity.toml:/etc/continuwuity.toml environment: diff --git a/docs/public/deploying/docker-compose.with-caddy.yml b/docs/public/deploying/docker-compose.with-caddy.yml index 7f8d83fbf..04f827f57 100644 --- a/docs/public/deploying/docker-compose.with-caddy.yml +++ b/docs/public/deploying/docker-compose.with-caddy.yml @@ -10,7 +10,7 @@ services: networks: - proxy volumes: - - ./data:/data + - ./caddy-data:/data # mount your created Caddyfile into the container - ./Caddyfile:/etc/caddy/Caddyfile restart: unless-stopped @@ -20,7 +20,7 @@ services: restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's # - ./continuwuity.toml:/etc/continuwuity.toml environment: @@ -43,6 +43,3 @@ services: networks: proxy: - -volumes: - db: diff --git a/docs/public/deploying/docker-compose.with-traefik.yml b/docs/public/deploying/docker-compose.with-traefik.yml index 9eac48e82..a45217af1 100644 --- a/docs/public/deploying/docker-compose.with-traefik.yml +++ b/docs/public/deploying/docker-compose.with-traefik.yml @@ -6,7 +6,7 @@ services: restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's #- ./continuwuity.toml:/etc/continuwuity.toml networks: @@ -40,7 +40,7 @@ services: - "443:443" volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - - "acme:/etc/traefik/acme" + - "./traefik-acme-data:/etc/traefik/acme" labels: - "traefik.enable=true" @@ -77,9 +77,5 @@ services: TRAEFIK_PROVIDERS_DOCKER_ENDPOINT: "unix:///var/run/docker.sock" TRAEFIK_PROVIDERS_DOCKER_EXPOSEDBYDEFAULT: false -volumes: - db: - acme: - networks: proxy: diff --git a/docs/public/deploying/docker-compose.yml b/docs/public/deploying/docker-compose.yml index a9d4491e0..342a94615 100644 --- a/docs/public/deploying/docker-compose.yml +++ b/docs/public/deploying/docker-compose.yml @@ -1,41 +1,38 @@ # Continuwuity - Bare Configuration (for other reverse proxies) services: - homeserver: - image: "forgejo.ellis.link/continuwuation/continuwuity:latest" - restart: unless-stopped - command: /sbin/conduwuit - ports: + homeserver: + image: "forgejo.ellis.link/continuwuation/continuwuity:latest" + restart: unless-stopped + command: /sbin/conduwuit + ports: - # If your reverse proxy is on the host, use this - # and configure it to connect to `127.0.0.1:8008` - - 127.0.0.1:8008:8008 + # If your reverse proxy is on the host, use this + # and configure it to connect to `127.0.0.1:8008` + - 127.0.0.1:8008:8008 - # If your reverse proxy is on another machine, use this - # and configure it to connect to :8008 - # - 8008:8008 + # If your reverse proxy is on another machine, use this + # and configure it to connect to :8008 + # - 8008:8008 - # If your reverse proxy is a docker container on the same network, - # comment out the entire `ports` section, and configure it to connect to `continuwuity:8008` + # If your reverse proxy is a docker container on the same network, + # comment out the entire `ports` section, and configure it to connect to `continuwuity:8008` - volumes: - - db:/var/lib/continuwuity - - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's - #- ./continuwuity.toml:/etc/continuwuity.toml - environment: - CONTINUWUITY_SERVER_NAME: example.com # EDIT THIS - CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity - CONTINUWUITY_ADDRESS: 0.0.0.0 - CONTINUWUITY_PORT: 8008 - #CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above + volumes: + - ./continuwuity-data:/var/lib/continuwuity + - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's + #- ./continuwuity.toml:/etc/continuwuity.toml + environment: + CONTINUWUITY_SERVER_NAME: example.com # EDIT THIS + CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity + CONTINUWUITY_ADDRESS: 0.0.0.0 + CONTINUWUITY_PORT: 8008 + #CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above - ## (Optional) Serve .well-known files to tell others to reach Continuwuity on port :443 - ## If you do this, remove all routes to port :8448 on your reverse proxy - # CONTINUWUITY_WELL_KNOWN: | - # { - # client=https://example.com, - # server=example.com:443 - # } - -volumes: - db: + ## (Optional) Serve .well-known files to tell others to reach Continuwuity on port :443 + ## If you do this, remove all routes to port :8448 on your reverse proxy + # CONTINUWUITY_WELL_KNOWN: | + # { + # client=https://example.com, + # server=example.com:443 + # } From c5f28c8276084357963a619896e45cfbc3662cf5 Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 12 Oct 2026 18:13:03 +0000 Subject: [PATCH 056/342] docs(docker): Document volumes usage in Appendix section --- docs/deploying/docker.mdx | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/docs/deploying/docker.mdx b/docs/deploying/docker.mdx index 7a0a65dd7..dbda5af94 100644 --- a/docs/deploying/docker.mdx +++ b/docs/deploying/docker.mdx @@ -283,12 +283,6 @@ Get a working Continuwuity server with an admin user in four steps: Once configured, log in to your server with any Matrix client, and register for an account with the registration token from step 3. If you did not configure step 4., log in via the `http://:8008` address. You will be automatically invited to the admin room where you can [manage your server](../reference/admin). -### (Optional) Building Custom Images - -For information on building your own Continuwuity Docker images, see the -[Building Docker Images](../development/index.mdx#building-docker-images) -section in the development documentation. - ### Accessing the Server's Console Before you can access the server's console and [send admin commands](../reference/admin/index.md) from the CLI, you will need to make the container interactive and allocate a pseudo-tty. Make sure you set `admin_console_automatic` to `true` in [the config](../reference/config.mdx) as well for Continuwuity to activate the CLI on startup. @@ -310,3 +304,28 @@ From there you can access the server's console by running `docker attach Date: Mon, 12 Oct 2026 18:20:43 +0000 Subject: [PATCH 057/342] docs(docker): Add backup/restore instructions --- docs/deploying/docker.mdx | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/deploying/docker.mdx b/docs/deploying/docker.mdx index dbda5af94..23f5f280e 100644 --- a/docs/deploying/docker.mdx +++ b/docs/deploying/docker.mdx @@ -212,7 +212,9 @@ Test that your setup works by following these [instructions](./generic.mdx#how-d Check your container logs using `docker-compose logs --follow` to debug any issues. See the [Troubleshooting](../troubleshooting.mdx) page for common errors and how to fix them. -## Updating +## Maintenance + +### Updating To update to a new version of Continuwuity, use the following commands: @@ -225,6 +227,10 @@ docker compose pull docker compose up -d ``` +### Backups + +The database in `./continuwuity-data` is present on the host system as a regular directory, and therefore can be backed up using normal mechanisms. See the [Backup](../maintenance.mdx#backups) section of the Maintenance page for more details. + ## What's next? Navigate to [Post-installation](../deploying.mdx#post-installation) for next steps. @@ -321,8 +327,11 @@ The example compose files above utilizes [bind mounts][docker-bind-mounts]. If y + continuwuity-data: ``` +Consult the [Docker docs][docker-volumes-backup-restore] for details on backing up and restoring Docker volumes + [docker-bind-mounts]: https://docs.docker.com/engine/storage/bind-mounts/ [docker-volumes]: https://docs.docker.com/engine/storage/volumes/ +[docker-volumes-backup-restore]: https://docs.docker.com/engine/storage/volumes/#back-up-restore-or-migrate-data-volumes ### Building Custom Images From b07093c7ab3469a1f372efea2832b0362dc7f4ea Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 12 Oct 2026 19:16:01 +0000 Subject: [PATCH 058/342] chore: Add changelog for #2353 --- changelog.d/2353.doc.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2353.doc.md diff --git a/changelog.d/2353.doc.md b/changelog.d/2353.doc.md new file mode 100644 index 000000000..d5533bda1 --- /dev/null +++ b/changelog.d/2353.doc.md @@ -0,0 +1 @@ +Docker compose examples now use bind mounts by default, instead of Docker volumes, as they are easier to work with esp. for backup/restore. Contributed by @stratself. \ No newline at end of file From 206aaf689346a1dfb7818baa392fea66300ec47b Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 12 Oct 2026 19:30:58 +0000 Subject: [PATCH 059/342] fix: Newline --- changelog.d/2353.doc.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/2353.doc.md b/changelog.d/2353.doc.md index d5533bda1..38722d0bc 100644 --- a/changelog.d/2353.doc.md +++ b/changelog.d/2353.doc.md @@ -1 +1 @@ -Docker compose examples now use bind mounts by default, instead of Docker volumes, as they are easier to work with esp. for backup/restore. Contributed by @stratself. \ No newline at end of file +Docker compose examples now use bind mounts by default, instead of Docker volumes, as they are easier to work with esp. for backup/restore. Contributed by @stratself. From e769ceb147d26ef5938f102757b0e2677c681176 Mon Sep 17 00:00:00 2001 From: stratself Date: Thu, 1 Oct 2026 20:23:34 +0000 Subject: [PATCH 060/342] docs(troubleshooting): Initialize docker troubleshooting section --- docs/troubleshooting.mdx | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 025e69bd7..87a0f905e 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -1,9 +1,9 @@ # Troubleshooting Continuwuity -:::warning{title="Docker users:"} -Docker can be difficult to use and debug. It's common for Docker -misconfigurations to cause issues, particularly with networking and permissions. -Please check that your issues are not due to problems with your Docker setup. +:::warning{title="For Docker users"} +It's common for Docker misconfigurations to cause issues, particularly with networking and +permissions. Before continuing, please first check that your issues are **not** due Docker +problems. See the dedicated section on [Docker](#docker) for more details. ::: ## Continuwuity issues @@ -119,6 +119,12 @@ much possible corruption is restored - If all goes will, you should be able to restore back to using `TolerateCorruptedTailRecords` and you have successfully recovered your database +## Docker issues {#docker} + +### Debugging Docker containers + +### Docker loopback networking issues + ## Debugging Note that users should not really need to debug things. If you find yourself From 0d9bb6ba7cf6f0a3c5081953e0d54c16d2bf7005 Mon Sep 17 00:00:00 2001 From: stratself Date: Sun, 4 Oct 2026 19:04:10 +0000 Subject: [PATCH 061/342] docs(troubleshooting): Add networking issues for docker --- docs/troubleshooting.mdx | 49 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 87a0f905e..07148e528 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -3,7 +3,7 @@ :::warning{title="For Docker users"} It's common for Docker misconfigurations to cause issues, particularly with networking and permissions. Before continuing, please first check that your issues are **not** due Docker -problems. See the dedicated section on [Docker](#docker) for more details. +problems. See the dedicated section on [Docker](#docker-issues) for more details. ::: ## Continuwuity issues @@ -119,12 +119,55 @@ much possible corruption is restored - If all goes will, you should be able to restore back to using `TolerateCorruptedTailRecords` and you have successfully recovered your database -## Docker issues {#docker} +## Docker issues -### Debugging Docker containers +### Debugging Docker networking + +The Continuwuity image does not ship with any shell or internal debugging utilities. To debug network conditions for Continuwuity, run another sidecar container that is attached to its network namespace. For example, using the `curl` container: + +```bash +docker run --rm -it \ + --network container:continuwuity \ + docker.io/curlimages/curl \ + curl https://continuwuity.org/.well-known/matrix/server +``` ### Docker loopback networking issues +Some distros disallow Docker containers in bridge networks to reach out to their host's public IP by default. This can cause connectivity issues between Continuwuity and other services that are on the same host machine, such as LiveKit or a push server. + +One can test if this is the case by cURLing those services with a sidecar container: + +```bash +docker run --rm -it --network container:continuwuity docker.io/curlimages/curl curl https://push.example.com +# --- some errors --- +``` + +To fix this, use the `extra_hosts` parameter to map local service domains to `host-gateway` - a special Docker value that resolves to the internal IP address of the host. + +```diff +# in docker-compose.yaml +services: + continuwuity: + ... ++ extra_hosts: ++ - "push.example.com:host-gateway" ++ - "livekit.example.com:host-gateway" + + lk-jwt-service: + ... ++ extra_hosts: ++ - "livekit.example.com:host-gateway" ++ - "matrix.example.com:host-gateway" +``` + +Reload the compose file, and connections between these services (as well as the sidecar container test above) should now work. + +For more information about the `host-gateway` parameter, kindly consult [this link][docker-custom-dns] and the [`--add-host` documentation for Docker][docker-add-host]. + +[docker-custom-dns]: https://docs.docker.com/compose/how-tos/networking/#custom-dns-with-extra_hosts +[docker-add-host]: https://docs.docker.com/reference/cli/docker/container/run/#add-host + ## Debugging Note that users should not really need to debug things. If you find yourself From 1247cf1c80d6c1a667cc37512b667b218a124251 Mon Sep 17 00:00:00 2001 From: stratself Date: Sun, 4 Oct 2026 19:11:18 +0000 Subject: [PATCH 062/342] docs(livekit): Shorten redundant docker loopback section --- docs/calls/livekit.mdx | 23 ++--------------------- docs/troubleshooting.mdx | 2 +- 2 files changed, 3 insertions(+), 22 deletions(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index 7a1a0d57d..9337e9c93 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -303,33 +303,14 @@ For browser-based clients, you can also inspect connections using DevTools' Netw ### Docker loopback networking issues -Some distros do not allow Docker containers in bridge networks to connect to their host's public IP by default. This makes `lk-jwt-service` fail connecting to `livekit` or `continuwuity` on the same host, causing refused and timed out connections to appear in the log entries of the JWT service, even when `LIVEKIT_URL` has been configured correctly. - -You can also test that this is the case by cURLing from a sidecar container: +Some distros do not allow Docker containers to connect to the host's public IP, and this breaks connections from `lk-jwt-service` towards `livekit` and `continuwuity` if they're on the same host. This can be tested by the following command: ```bash docker run --rm --net container:lk-jwt-service docker.io/curlimages/curl https://livekit.example.com # --- some errors --- ``` -To resolve this, configure an `extra_hosts` file mapping LiveKit's and Continuwuity's domain names to Docker's custom host loopback address, represented here by `host-gateway`: - -```diff -# in docker-compose.yaml -services: - lk-jwt-service: - ... -+ extra_hosts: -+ - "livekit.example.com:host-gateway" -+ - "matrix.example.com:host-gateway" -``` - -After implementing the changes and restarting your compose, `lk-jwt-service` should now connect to your other services. The sidecar container test above should now return an `OK` from LiveKit. - -For more information about the `host-gateway` parameter, kindly refer to the `--add-host` documentation for [Docker][docker-add-host] and [Podman][podman-add-host]. Should you have further difficulties, feel free to enquire in the support rooms. - -[docker-add-host]: https://docs.docker.com/reference/cli/docker/container/run/#add-host -[podman-add-host]: https://docs.podman.io/en/latest/markdown/podman-run.1.html#add-host-hostname-hostname-ip +To resolve this, follow the steps in [Docker loopback networking issues](../troubleshooting.mdx#docker-loopback-networking-issues) of the Troubleshooting page. ### Incorrect IP address for LiveKit diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 07148e528..883f97cc5 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -140,7 +140,7 @@ One can test if this is the case by cURLing those services with a sidecar contai ```bash docker run --rm -it --network container:continuwuity docker.io/curlimages/curl curl https://push.example.com -# --- some errors --- +# --- some timeout or refused connection errors --- ``` To fix this, use the `extra_hosts` parameter to map local service domains to `host-gateway` - a special Docker value that resolves to the internal IP address of the host. From d4ae9f9ac10a7a0fdcbf883ed665a28b5a017df5 Mon Sep 17 00:00:00 2001 From: stratself Date: Sun, 4 Oct 2026 19:19:39 +0000 Subject: [PATCH 063/342] docs(troubleshooting): Add redirs to other troubleshooting topics in other pages --- docs/troubleshooting.mdx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 883f97cc5..8aee3f01e 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -128,7 +128,7 @@ The Continuwuity image does not ship with any shell or internal debugging utilit ```bash docker run --rm -it \ --network container:continuwuity \ - docker.io/curlimages/curl \ + docker.io/curlimages/curl \ curl https://continuwuity.org/.well-known/matrix/server ``` @@ -247,3 +247,10 @@ and is not easy for non-developers to understand. [unbound-tuning]: https://unbound.docs.nlnetlabs.nl/en/latest/topics/core/performance.html [unbound-arch]: https://wiki.archlinux.org/title/Unbound + +## Other troubleshooting topics + +- [LiveKit troubleshooting](./calls/livekit.mdx#troubleshooting) +- [TURN server troubleshooting](./calls/turn.mdx#troubleshooting) +- [Delegation/split-domain troubleshooting](./guides/delegation.mdx#troubleshooting) +- [Push notifications troubleshooting](./guides/push.mdx#troubleshooting) From d4bfb38bd5c86072a2de8f6f075c8f10d86adf04 Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 5 Oct 2026 04:49:41 +0000 Subject: [PATCH 064/342] docs(troubleshooting): Update complex debug log filters --- docs/troubleshooting.mdx | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 8aee3f01e..708d905ea 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -172,7 +172,7 @@ For more information about the `host-gateway` parameter, kindly consult [this li Note that users should not really need to debug things. If you find yourself debugging and find the issue, please let us know and/or how we can fix it. -Various debug commands can be [found in `!admin debug`](./reference/admin/debug). +Various debug commands can be found in [`!admin debug`](./reference/admin/debug). ### Debug/Trace log level @@ -185,23 +185,34 @@ you need to access debug/trace log levels, you will need to build without the Continuwuity supports changing the tracing log environment filter on-the-fly using the admin command `!admin debug change-log-level `. This accepts -a string **without quotes** the same format as the `log` config option. +a string **without quotes** in the same format as the `log` config option. Complex +filters are also supported as well. -Example: `!admin debug change-log-level debug` +```bash +# set log level to debug +!admin debug change-log-level debug -This can also accept complex filters such as: -`!admin debug change-log-level info,conduit_service[{dest="example.com"}]=trace,ruma_state_res=trace` -`!admin debug change-log-level info,conduit_service[{dest="example.com"}]=trace,conduit_service[send{dest="example.org"}]=trace` +# trace logs for all outgoing federation to `example.com` +!admin debug change-log-level info,conduwuit_service::federation[{dest="example.com"}]=trace -And to reset the log level to the one that was set at startup / last config -load, simply pass the `--reset` flag. +# trace logs for client syncs +!admin debug change-log-level info,conduwuit_api::client=trace -`!admin debug change-log-level --reset` +# debug logs for everything except h2 and presence +!admin debug change-log-level trace,h2=off,conduwuit_service::presence=off +``` + +To reset the log level to the one that was set at last config +load, simply do: + +```bash +!admin debug change-log-level --reset +``` ### Pinging servers Continuwuity can ping other servers using `!admin debug ping `. This takes -a server name and goes through the server discovery process and queries +a server name, goes through the server discovery process, and queries `/_matrix/federation/v1/version`. Errors are outputted. While it does measure the latency of the request, it is not indicative of From b70131c301ea24dd897c5886359fc9c0e23710a7 Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 5 Oct 2026 04:56:05 +0000 Subject: [PATCH 065/342] docs(troubleshooting): Improve wordings a little bit --- docs/troubleshooting.mdx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 708d905ea..9e364011d 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -2,8 +2,8 @@ :::warning{title="For Docker users"} It's common for Docker misconfigurations to cause issues, particularly with networking and -permissions. Before continuing, please first check that your issues are **not** due Docker -problems. See the dedicated section on [Docker](#docker-issues) for more details. +permissions. Before continuing, please first check that your issues are notdue Docker +problems. See the dedicated [**Docker issues**](#docker-issues) section for more details. ::: ## Continuwuity issues @@ -145,17 +145,20 @@ docker run --rm -it --network container:continuwuity docker.io/curlimages/curl c To fix this, use the `extra_hosts` parameter to map local service domains to `host-gateway` - a special Docker value that resolves to the internal IP address of the host. -```diff -# in docker-compose.yaml +```diff title="docker-compose.yaml" services: continuwuity: ... +# allow Continuwuity to reach out to the push server and livekit +# via the host gateway loopback address + extra_hosts: + - "push.example.com:host-gateway" + - "livekit.example.com:host-gateway" lk-jwt-service: ... +# allow jwt service to reach out to Continuwuity and livekit +# via the host gateway loopback address + extra_hosts: + - "livekit.example.com:host-gateway" + - "matrix.example.com:host-gateway" @@ -163,7 +166,7 @@ services: Reload the compose file, and connections between these services (as well as the sidecar container test above) should now work. -For more information about the `host-gateway` parameter, kindly consult [this link][docker-custom-dns] and the [`--add-host` documentation for Docker][docker-add-host]. +For more information about the `host-gateway` parameter, kindly consult the Docker docs on [custom DNS with `extra_hosts`][docker-custom-dns] and the [`--add-host` option][docker-add-host]. [docker-custom-dns]: https://docs.docker.com/compose/how-tos/networking/#custom-dns-with-extra_hosts [docker-add-host]: https://docs.docker.com/reference/cli/docker/container/run/#add-host From 028ffabebf8f953ec03afd2101d9218c2834cc2f Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 5 Oct 2026 08:01:39 +0000 Subject: [PATCH 066/342] docs(troubleshooting,perf): Simplify trusted servers wordings --- docs/guides/performance.mdx | 4 ++-- docs/troubleshooting.mdx | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/guides/performance.mdx b/docs/guides/performance.mdx index 08ecf7ac0..4756b0af2 100644 --- a/docs/guides/performance.mdx +++ b/docs/guides/performance.mdx @@ -113,7 +113,7 @@ https://matrix.example.com { ### Tuning your trusted servers -:::info Vet your trusted servers! +:::important Important: Vet your trusted servers! Trusted servers are your first point of contact when obtaining public keys from other servers, and they could theoretically impersonate other servers and cause significant harm to your deployment. Please thoroughly verify your trusted servers' credibility before adding them to your configuration. If you need suggestions for trusted servers, ask in the Continuwuity main room. @@ -128,7 +128,7 @@ trusted_servers = ["codestorm.net","starstruck.systems","unredacted.org","matrix Avoid prioritising `matrix.org` as your primary trusted server, as it tends to be quite slow. -Some users have also reported that increasing `trusted_server_batch_size` has helped with faster joins for huge rooms. Start with doubling the default to `2048` until you find a suitable value. +Some users have also reported that increasing `trusted_server_batch_size` helps with faster joins for huge rooms. Start with doubling the default to `2048` until you find a suitable value. ### Enable HTTP/3 on your reverse proxy diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 9e364011d..be145114b 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -13,9 +13,9 @@ problems. See the dedicated [**Docker issues**](#docker-issues) section for more Some slowness is to be expected if you're the first person on your homeserver to join a room (which will always be the case for single-user homeservers). In this situation, your homeserver has to verify the signatures of all of the state events sent by other servers before your join. To make this process as fast as possible, make sure you have -[multiple fast, trusted servers](./guides/performance.mdx#tuning-your-trusted-servers) listed in `trusted_servers` in your configuration, and ensure -`query_trusted_key_servers_first_on_join` is set to true (the default). -If you need suggestions for trusted servers, ask in the Continuwuity main room. +multiple fast, trusted servers listed in `trusted_servers` in your configuration, and ensure +`query_trusted_key_servers_first_on_join` is set to true (the default). Read the +[Tuning your trusted servers](./guides/performance.mdx#tuning-your-trusted-servers) section for more details on doing so. However, _very_ slow joins, especially to rooms with only a few users in them or rooms created by another user on your homeserver, may be caused by [issue !779](https://forgejo.ellis.link/continuwuation/continuwuity/issues/779), From a6b8bfe2c9ea8e0453ea8c96b3688acbc872279e Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 12 Oct 2026 17:25:50 +0000 Subject: [PATCH 067/342] chore: Add changelog for 2324 --- changelog.d/2324.doc..md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2324.doc..md diff --git a/changelog.d/2324.doc..md b/changelog.d/2324.doc..md new file mode 100644 index 000000000..3d767b04b --- /dev/null +++ b/changelog.d/2324.doc..md @@ -0,0 +1 @@ +Add a section on [troubleshooting Docker issues](https://continuwuity.org/troubleshooting#docker-issues). Contributed by @stratself. From 4c62b968214162b7e5561a20cbf751e6cf11cf85 Mon Sep 17 00:00:00 2001 From: Julian Anderson Date: Tue, 27 Oct 2026 17:08:42 -0500 Subject: [PATCH 068/342] chore: Bump sentry and update config to required builder pattern --- Cargo.lock | 44 ++++++++++++++++++++-------------------- Cargo.toml | 6 +++--- changelog.d/2423.misc.md | 1 + src/main/sentry.rs | 40 +++++++++++++++--------------------- 4 files changed, 42 insertions(+), 49 deletions(-) create mode 100644 changelog.d/2423.misc.md diff --git a/Cargo.lock b/Cargo.lock index 07a843926..4343d5692 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5484,9 +5484,9 @@ dependencies = [ [[package]] name = "sentry" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d631477761f57c76148456e55e80e9a479ff3fa4c65b2b4a0c3acf1167fd4638" +checksum = "9fa951f4e644464ebfd2347a7ab03b0828c512d2448a76262cad2607b343dff4" dependencies = [ "cfg_aliases", "httpdate", @@ -5504,9 +5504,9 @@ dependencies = [ [[package]] name = "sentry-backtrace" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "448b0981fbde6cdc9eb087ba3dc01035a253fef9a0d9e79aaf198fc26acb2e64" +checksum = "f4f27cf048aa63ccd5bc94c29989133eabb82e9c6bf7441b58e9d4a95837a105" dependencies = [ "backtrace", "regex", @@ -5515,9 +5515,9 @@ dependencies = [ [[package]] name = "sentry-contexts" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5e909d02170ba6d1dc5ebd05bef7999280f5d960e3eaee5d1a18d88d41b334" +checksum = "c5ed680585dbdacdf9859c2b4dc53358ff02bd256766882e22e343836db36b22" dependencies = [ "hostname", "libc", @@ -5529,11 +5529,11 @@ dependencies = [ [[package]] name = "sentry-core" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecf0b1a4a4e9ec88395b52e6fa4868b95564c1fa96b26a0606f5f6288a0f7149" +checksum = "c3ed398494bb8fc412a11a182c1883a10ae147587b8f6314abd222d1d626f31b" dependencies = [ - "rand 0.9.5", + "rand 0.10.3", "sentry-types", "serde", "serde_json", @@ -5542,9 +5542,9 @@ dependencies = [ [[package]] name = "sentry-debug-images" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81d7749c57fc78ed52134889e8121da874065bc40da788d5798cce0f8c19f15" +checksum = "55854bb40681e84ffd2a69578ad4ef9bfaf5bf2bf1380a745578b591fa24af22" dependencies = [ "findshlibs", "sentry-core", @@ -5552,9 +5552,9 @@ dependencies = [ [[package]] name = "sentry-log" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ffc7737b6d4f1cb3707284703c7364e9f5f056118abc523dd52e732f13cbe1" +checksum = "9a3dc14009e1c24b07a8ff9ff8e1bcd0913b3e448b1565e679414776f2e58651" dependencies = [ "bitflags 2.13.2", "log", @@ -5563,9 +5563,9 @@ dependencies = [ [[package]] name = "sentry-panic" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7d93d6ecb55d2251c5fc084c55c03a2bc68904918d76117e602c999e92f00f" +checksum = "b7153e68642b761ed3aa62c022795c11b2facc728b2db7484084492373c944f9" dependencies = [ "sentry-backtrace", "sentry-core", @@ -5573,9 +5573,9 @@ dependencies = [ [[package]] name = "sentry-tower" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a64a8a0a33239c65f95ff719fcb56655f398f4e4e74a01af8daca725cf7c2b5f" +checksum = "624ee2c60caf72fa2cd6be00334b3a3ce0c6df3b1f01941ea62e3d244492d334" dependencies = [ "http", "pin-project", @@ -5587,9 +5587,9 @@ dependencies = [ [[package]] name = "sentry-tracing" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58d26379236c4ef97eaf081bca3c7bf0ef6f06b3aa881eca2ee8e8dbc923e5b8" +checksum = "e7e7db1aefdf623f4e48e21ec9e4af535024187aeafb2a4cc7e29d035def5a13" dependencies = [ "bitflags 2.13.2", "sentry-backtrace", @@ -5600,13 +5600,13 @@ dependencies = [ [[package]] name = "sentry-types" -version = "0.48.5" +version = "0.49.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2239099d47e76857b0825a182ecdb90159add7aa1097b60247c6e7ca6bf49c6a" +checksum = "1c18bf7b159bdfc7c8f97816f476b4947a1937fb6bea9d38d3479e58631614ac" dependencies = [ "debugid", "hex", - "rand 0.9.5", + "rand 0.10.3", "serde", "serde_json", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index c49437807..3d4896609 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -453,7 +453,7 @@ features = ["http", "grpc-tonic", "trace", "logs", "metrics"] # optional sentry metrics for crash/panic reporting [workspace.dependencies.sentry] -version = "0.48.0" +version = "0.49.0" default-features = false features = [ "backtrace", @@ -468,9 +468,9 @@ features = [ ] [workspace.dependencies.sentry-tracing] -version = "0.48.0" +version = "0.49.0" [workspace.dependencies.sentry-tower] -version = "0.48.0" +version = "0.49.0" # jemalloc usage [workspace.dependencies.tikv-jemalloc-sys] diff --git a/changelog.d/2423.misc.md b/changelog.d/2423.misc.md new file mode 100644 index 000000000..bb1cb186c --- /dev/null +++ b/changelog.d/2423.misc.md @@ -0,0 +1 @@ +Updated internal Sentry integration setup to the new pattern required by the SDK. diff --git a/src/main/sentry.rs b/src/main/sentry.rs index 0a013fa66..775d63406 100644 --- a/src/main/sentry.rs +++ b/src/main/sentry.rs @@ -1,19 +1,12 @@ #![cfg(feature = "sentry_telemetry")] -use std::{ - borrow::Cow, - str::FromStr, - sync::{Arc, OnceLock}, -}; +use std::{borrow::Cow, sync::OnceLock}; use conduwuit_build_metadata as build; use conduwuit_core::{config::Config, debug, trace}; use sentry::{ Breadcrumb, ClientOptions, Level, - types::{ - Dsn, - protocol::v7::{Context, Event}, - }, + types::protocol::v7::{Context, Event}, }; static SEND_PANIC: OnceLock = OnceLock::new(); @@ -37,22 +30,21 @@ fn options(config: &Config) -> ClientOptions { .expect("init_sentry should only be called if sentry is enabled and this is not None") .as_str(); - let server_name = config - .sentry_send_server_name - .then(|| config.server_name.to_string().into()); + let options = ClientOptions::new() + .dsn(dsn) + .traces_sample_rate(config.sentry_traces_sample_rate) + .debug(cfg!(debug_assertions)) + .maybe_release(release_name()) + .user_agent(conduwuit_core::user_agent()) + .attach_stacktrace(config.sentry_attach_stacktrace) + .before_send(before_send) + .before_breadcrumb(before_breadcrumb); - ClientOptions { - dsn: Some(Dsn::from_str(dsn).expect("sentry_endpoint must be a valid URL")), - server_name, - traces_sample_rate: config.sentry_traces_sample_rate, - debug: cfg!(debug_assertions), - release: release_name(), - user_agent: conduwuit_core::user_agent().into(), - attach_stacktrace: config.sentry_attach_stacktrace, - before_send: Some(Arc::new(before_send)), - before_breadcrumb: Some(Arc::new(before_breadcrumb)), - ..Default::default() - } + config + .sentry_send_server_name + .then(|| config.server_name.to_string()) + .into_iter() + .fold(options, ClientOptions::server_name) } fn before_send(event: Event<'static>) -> Option> { From 18bd828b8b4e9553efe7c4d30a3e022ceb3af276 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 27 Oct 2026 05:19:11 +0000 Subject: [PATCH 069/342] chore(deps): update rust crate tokio to v1.53.3 [security] --- Cargo.lock | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4343d5692..348c8ff11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2030,7 +2030,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4669,7 +4669,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5263,7 +5263,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5322,7 +5322,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6292,9 +6292,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.53.1" +version = "1.53.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" dependencies = [ "bytes", "libc", @@ -7135,7 +7135,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] From 7358712fb924970be2ed71ddb9235b50edf55dcb Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 26 Oct 2026 06:06:52 +0000 Subject: [PATCH 070/342] chore(deps): update rust crate tower-sec-fetch to 0.2.0 --- Cargo.lock | 4 ++-- src/web/Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 348c8ff11..7bca821a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6598,9 +6598,9 @@ checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" [[package]] name = "tower-sec-fetch" -version = "0.1.2" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff1e78d241de2527d3ef67e49d65d8cb08468c644c3aafac7a988c4accd76547" +checksum = "88a13d0fc16129bf9e98fb869f369e867090afab7730d91ab4f68084bd037093" dependencies = [ "futures", "http", diff --git a/src/web/Cargo.toml b/src/web/Cargo.toml index c40c461e6..5cdfcd58b 100644 --- a/src/web/Cargo.toml +++ b/src/web/Cargo.toml @@ -38,7 +38,7 @@ serde_json.workspace = true serde_urlencoded.workspace = true thiserror.workspace = true tower-http.workspace = true -tower-sec-fetch = { features = ["tracing"], version = "0.1.2" } +tower-sec-fetch = { features = ["tracing"], version = "0.2.0" } tower-sessions = { default-features = false, features = [ "axum-core", ], version = "0.15.0" } From 3c192065341048c770731e4b93ecc51c817caa42 Mon Sep 17 00:00:00 2001 From: timedout Date: Sat, 24 Oct 2026 17:56:21 +0200 Subject: [PATCH 071/342] fix: Perform PDU checks 1, 2, and 3 before yielding a gapfilled PDU Fixes #2386 --- .../fetch_and_handle_outliers.rs | 48 ++++++++++++++----- src/service/rooms/event_handler/pdu_checks.rs | 2 + 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/src/service/rooms/event_handler/fetch_and_handle_outliers.rs b/src/service/rooms/event_handler/fetch_and_handle_outliers.rs index 38a25b914..e450b0d79 100644 --- a/src/service/rooms/event_handler/fetch_and_handle_outliers.rs +++ b/src/service/rooms/event_handler/fetch_and_handle_outliers.rs @@ -9,7 +9,7 @@ use assign::assign; use conduwuit::error; use conduwuit::{ Err, Event, PduEvent, Result, debug, debug_info, debug_warn, err, - result::FlatOk, + result::{FlatOk, LogErr}, state_res::lexicographical_topological_sort, trace, utils::{IterStream, math::Expected, stream::BroadbandExt}, @@ -387,6 +387,7 @@ impl super::Service { remote: OwnedServerName, event_id: OwnedEventId, room_version_rules: &RoomVersionRules, + create_event_id: &EventId, ) -> Result<(OwnedEventId, CanonicalJsonObject)> { let res = self .services @@ -399,21 +400,28 @@ impl super::Service { .await?; if calculated_event_id != event_id { - Err!(Request(BadJson(warn!( + return Err!(Request(BadJson(warn!( expected=%event_id, received=%calculated_event_id, "Server didn't return event id we requested", - )))) - } else { - Ok((event_id, value)) + )))); } + + Self::pdu_format_check_1(&value, room_version_rules, create_event_id)?; + self.signature_hash_check_2_3(value, room_version_rules) + .await + .map(|value| (calculated_event_id, value)) } + /// Fetches an event from multiple candidates in parallel (by calling + /// fetch_event_via on each candidate), returning the first successful + /// result. async fn fetch_event_vias( &self, candidates: impl Iterator, event_id: &EventId, room_version_rules: &RoomVersionRules, + create_event_id: &EventId, ) -> Result<(OwnedEventId, CanonicalJsonObject)> { if let Ok(pdu_json) = self.services.timeline.get_pdu_json(event_id).await { return Ok((event_id.to_owned(), pdu_json)); @@ -424,6 +432,7 @@ impl super::Service { remote.to_owned(), event_id.to_owned(), room_version_rules, + create_event_id, )) }) .collect::>(); @@ -511,7 +520,12 @@ impl super::Service { })?; debug!(elapsed=?start.elapsed(), "Fetching {target_id} over federation"); let value = match self - .fetch_event_vias(candidates.iter(), &target_id, room_version_rules) + .fetch_event_vias( + candidates.iter(), + &target_id, + room_version_rules, + create_event.event_id(), + ) .await { | Ok((_, value)) => { @@ -657,8 +671,13 @@ impl super::Service { debug_warn!(error=?e, "Not attempting to pull missing prev event"); continue; } - let pdu = match self - .fetch_event_vias(candidates.iter(), &next_id, room_version_rules) + let pdu_json = match self + .fetch_event_vias( + candidates.iter(), + &next_id, + room_version_rules, + create_event.event_id(), + ) .await { | Ok((_, data)) => { @@ -676,7 +695,7 @@ impl super::Service { }, }; - let prev_events = match expect_event_id_array(&pdu, "prev_events").map_err(|e| { + let prev_events = match expect_event_id_array(&pdu_json, "prev_events").map_err(|e| { err!(Request(BadJson(warn!( event_id=%next_id, "Failed to parse event fetched from remote: {e}" @@ -698,11 +717,14 @@ impl super::Service { }) .collect::>() .await; + let Ok(pdu) = PduEvent::from_id_val(&next_id, pdu_json.clone()) + .map_err(|e| err!("Failed to parse already validated PDU {next_id}: {e:?}")) + .log_err() + else { + continue; + }; todo.extend(missing_prev); - discovered_events.insert( - next_id.clone(), - PduEvent::from_id_val(&next_id, pdu).expect("fetched PDU was already validated"), - ); + discovered_events.insert(next_id, pdu); } discovered_events diff --git a/src/service/rooms/event_handler/pdu_checks.rs b/src/service/rooms/event_handler/pdu_checks.rs index 458ff4f3b..3ea693fde 100644 --- a/src/service/rooms/event_handler/pdu_checks.rs +++ b/src/service/rooms/event_handler/pdu_checks.rs @@ -66,6 +66,8 @@ impl super::Service { if pdu_json.get("room_id").is_none() { return Err!(Request(BadJson("Missing required PDU field: `room_id`"))); } + } else if pdu_json.get("room_id").is_some() { + return Err!(Request(BadJson("Unexpected PDU field: `room_id`"))); } let auth_events = expect_event_id_array(pdu_json, "auth_events")?; From b580379a2dffdfe4dc66a536a6e3224d65b2dc7f Mon Sep 17 00:00:00 2001 From: timedout Date: Sat, 24 Oct 2026 18:10:24 +0200 Subject: [PATCH 072/342] fix: Only check that room_id is not present on create events in PDU check 1 --- src/service/rooms/event_handler/pdu_checks.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/service/rooms/event_handler/pdu_checks.rs b/src/service/rooms/event_handler/pdu_checks.rs index 3ea693fde..e2a664f8d 100644 --- a/src/service/rooms/event_handler/pdu_checks.rs +++ b/src/service/rooms/event_handler/pdu_checks.rs @@ -62,14 +62,6 @@ impl super::Service { return Err!(Request(TooLarge("PDU is too large"))); } - if event_format.require_room_create_room_id { - if pdu_json.get("room_id").is_none() { - return Err!(Request(BadJson("Missing required PDU field: `room_id`"))); - } - } else if pdu_json.get("room_id").is_some() { - return Err!(Request(BadJson("Unexpected PDU field: `room_id`"))); - } - let auth_events = expect_event_id_array(pdu_json, "auth_events")?; if auth_events.len() > 10 { return Err!(Request(BadJson("PDU has too many auth events"))); @@ -92,6 +84,9 @@ impl super::Service { let is_create_event = event_type == "m.room.create" && state_key == Some(""); if !is_create_event { + if pdu_json.get("room_id").is_none() { + return Err!(Request(BadJson("Missing required PDU field: `room_id`"))); + } let create_event_in_auth_events = auth_events.iter().any(|id| id == create_event_id); if !event_format.allow_room_create_in_auth_events && create_event_in_auth_events { return Err!(Request(BadJson("PDU references a create event"))); @@ -100,6 +95,8 @@ impl super::Service { { return Err!(Request(BadJson("PDU does not reference the room create event"))); } + } else if !event_format.require_room_create_room_id && pdu_json.get("room_id").is_some() { + return Err!(Request(BadJson("Unexpected PDU field: `room_id`"))); } let prev_events = expect_event_id_array(pdu_json, "prev_events")?; From 3b0fc25cd3371a0d270ec6268b16dc95fa1f5398 Mon Sep 17 00:00:00 2001 From: timedout Date: Thu, 29 Oct 2026 02:58:07 +0000 Subject: [PATCH 073/342] chore: Add newsfrag --- changelog.d/2400.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2400.bugfix.md diff --git a/changelog.d/2400.bugfix.md b/changelog.d/2400.bugfix.md new file mode 100644 index 000000000..406586732 --- /dev/null +++ b/changelog.d/2400.bugfix.md @@ -0,0 +1 @@ +Perform more validation on events received during atomic gapfill from remote servers, fixing a panic if bad data was persisted by another server and later lazily fetched by us. From 3eb2788eb9022fc8cd3104db472148eeb5fc5436 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 00:20:26 +0100 Subject: [PATCH 074/342] feat: Only track appended extremities --- src/api/client/membership/knock.rs | 22 +-- src/database/maps.rs | 2 +- src/service/rooms/membership/mod.rs | 12 +- src/service/rooms/pdu_metadata/data.rs | 20 +-- src/service/rooms/pdu_metadata/mod.rs | 14 -- src/service/rooms/state/mod.rs | 18 ++- src/service/rooms/timeline/append.rs | 206 ++++++++----------------- src/service/rooms/timeline/backfill.rs | 7 - src/service/rooms/timeline/build.rs | 30 +--- 9 files changed, 95 insertions(+), 236 deletions(-) diff --git a/src/api/client/membership/knock.rs b/src/api/client/membership/knock.rs index d4d3417d6..cbe2a90cc 100644 --- a/src/api/client/membership/knock.rs +++ b/src/api/client/membership/knock.rs @@ -1,4 +1,4 @@ -use std::{borrow::Borrow, collections::HashMap, iter::once, sync::Arc}; +use std::{borrow::Borrow, collections::HashMap, sync::Arc}; use axum::extract::State; use conduwuit::{ @@ -461,14 +461,8 @@ async fn knock_room_helper_local( services .rooms .timeline - .append_pdu( - &parsed_knock_pdu, - knock_event, - once(parsed_knock_pdu.event_id.borrow()), - &state_lock, - room_id, - ) - .await?; + .append_pdu(&parsed_knock_pdu, knock_event, room_id) + .await; Ok(()) } @@ -663,14 +657,8 @@ async fn knock_room_helper_remote( services .rooms .timeline - .append_pdu( - &parsed_knock_pdu, - knock_event, - once(parsed_knock_pdu.event_id.borrow()), - &state_lock, - room_id, - ) - .await?; + .append_pdu(&parsed_knock_pdu, knock_event, room_id) + .await; info!("Setting final room state for new room"); // We set the room state after inserting the pdu, so that we never have a diff --git a/src/database/maps.rs b/src/database/maps.rs index 013fc9270..d1092c176 100644 --- a/src/database/maps.rs +++ b/src/database/maps.rs @@ -171,7 +171,7 @@ pub(super) static MAPS: &[Descriptor] = &[ }, Descriptor { name: "referencedevents", - ..descriptor::RANDOM + ..descriptor::DROPPED }, Descriptor { name: "refreshtoken_refreshtokeninfo", diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index 034599c80..7300474ab 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -683,14 +683,8 @@ impl Service { info!("Appending new room join event"); self.services .timeline - .append_pdu( - &parsed_join_pdu, - join_event, - once(parsed_join_pdu.event_id.as_ref()), - &state_lock, - room_id, - ) - .await?; + .append_pdu(&parsed_join_pdu, join_event, room_id) + .await; self.services .metadata .maybe_set_mindepth(room_id, parsed_join_pdu.depth.into()) @@ -712,7 +706,7 @@ impl Service { info!("Replacing local forward extremities"); self.services .state - .set_forward_extremities(room_id, once(parsed_join_pdu.event_id()), &state_lock) + .replace_forward_extremities(room_id, once(parsed_join_pdu.event_id()), &state_lock) .await; } drop(cork); diff --git a/src/service/rooms/pdu_metadata/data.rs b/src/service/rooms/pdu_metadata/data.rs index db3973f06..4920df5e7 100644 --- a/src/service/rooms/pdu_metadata/data.rs +++ b/src/service/rooms/pdu_metadata/data.rs @@ -12,7 +12,7 @@ use conduwuit::{ }; use database::Map; use futures::{Stream, StreamExt}; -use ruma::{EventId, RoomId, UserId, api::Direction}; +use ruma::{EventId, UserId, api::Direction}; use crate::{ Dep, @@ -25,7 +25,6 @@ use crate::{ pub(super) struct Data { tofrom_relation: Arc, - referencedevents: Arc, softfailedeventids: Arc, rejectedeventids: Arc, services: Services, @@ -40,7 +39,6 @@ impl Data { let db = &args.db; Self { tofrom_relation: db["tofrom_relation"].clone(), - referencedevents: db["referencedevents"].clone(), softfailedeventids: db["softfailedeventids"].clone(), rejectedeventids: db["rejectedeventids"].clone(), services: Services { @@ -106,22 +104,6 @@ impl Data { }) } - #[inline] - pub(super) fn mark_as_referenced<'a, I>(&self, room_id: &RoomId, event_ids: I) - where - I: Iterator, - { - for prev in event_ids { - let key = (room_id, prev); - self.referencedevents.put_raw(key, []); - } - } - - pub(super) async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool { - let key = (room_id, event_id); - self.referencedevents.qry(&key).await.is_ok() - } - pub(super) fn mark_event_soft_failed(&self, event_id: &EventId) { self.softfailedeventids.insert(event_id, []); } diff --git a/src/service/rooms/pdu_metadata/mod.rs b/src/service/rooms/pdu_metadata/mod.rs index 7c22f408b..33c3d968b 100644 --- a/src/service/rooms/pdu_metadata/mod.rs +++ b/src/service/rooms/pdu_metadata/mod.rs @@ -115,20 +115,6 @@ impl Service { pdus } - #[tracing::instrument(skip_all, level = "debug")] - pub fn mark_as_referenced<'a, I>(&self, room_id: &RoomId, event_ids: I) - where - I: Iterator, - { - self.db.mark_as_referenced(room_id, event_ids); - } - - #[inline] - #[tracing::instrument(skip(self), level = "debug")] - pub async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool { - self.db.is_event_referenced(room_id, event_id).await - } - #[inline] #[tracing::instrument(skip(self), level = "debug")] pub fn mark_event_soft_failed(&self, event_id: &EventId) { diff --git a/src/service/rooms/state/mod.rs b/src/service/rooms/state/mod.rs index 200e03f7f..f2740a84c 100644 --- a/src/service/rooms/state/mod.rs +++ b/src/service/rooms/state/mod.rs @@ -420,7 +420,11 @@ impl Service { .ignore_err() } - pub async fn set_forward_extremities<'a, I>( + /// Replaces the forward extremity set whole-sale. + /// + /// This should only be done during room joins, where our only source of + /// extremities is the join itself. + pub async fn replace_forward_extremities<'a, I>( &'a self, room_id: &'a RoomId, event_ids: I, @@ -442,6 +446,18 @@ impl Service { } } + /// Appends a forward extremity to the extremity tracker. + pub fn add_forward_extremity(&self, room_id: &RoomId, event_id: &EventId) { + let key = (room_id, event_id); + self.db.roomid_pduleaves.put_raw(key, []); + } + + /// Removes a forward extremity from the extremity tracker. + pub fn remove_forward_extremity(&self, room_id: &RoomId, event_id: &EventId) { + let key = (room_id, event_id); + self.db.roomid_pduleaves.del(key); + } + /// This fetches auth events from the current state. #[tracing::instrument(skip(self, content, room_version_rules), level = "trace")] pub async fn get_auth_events( diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index 663f98543..b41f78673 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -1,17 +1,13 @@ use std::{ - borrow::Borrow, collections::{BTreeMap, HashMap, HashSet, VecDeque}, iter::once, - ops::Not, sync::Arc, - time::Instant, }; use conduwuit::{ - Err, Result, debug, debug_warn, + Result, debug, debug_warn, matrix::{Event, PduEvent}, pdu::{Count, ShortRoomId}, - trace, utils::{ IterStream, TryFutureExtExt, mutex_map::Guard, @@ -20,15 +16,15 @@ use conduwuit::{ warn, }; use conduwuit_core::{ - err, error, + error, matrix::pdu::{PduCount, PduId, RawPduId, sticky}, result::LogErr, utils::{self, stream::TryIgnore}, }; use futures::{FutureExt, StreamExt, TryFutureExt, pin_mut}; use ruma::{ - CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId, OwnedServerName, - RoomId, RoomVersionId, ServerName, UserId, + CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, + RoomVersionId, ServerName, UserId, events::{ AnySyncTimelineEvent, GlobalAccountDataEventType, TimelineEventType, push_rules::PushRulesEvent, @@ -94,29 +90,14 @@ impl super::Service { // We do this BEFORE setting the extremities so that there's never a // point in time where we have fresh extremities referencing stale // state. - let extremities = self - .progress_state_and_extremities( - pdu, - room_version_rules, - state_before.clone(), - self.services - .state - .get_forward_extremities(&room_id) - .collect() - .await, - state_lock, - ) - .await?; + if pdu.state_key().is_some() { + debug!("Event is a state-event. Deriving new room state"); + self.derive_new_state(pdu, &room_id, room_version_rules, state_before, state_lock) + .await?; + } + self.progress_extremities(pdu).await?; - let pdu_id = self - .append_pdu( - pdu, - pdu_json, - extremities.iter().map(Borrow::borrow), - state_lock, - &room_id, - ) - .await?; + let pdu_id = self.append_pdu(pdu, pdu_json, &room_id).await; // Process admin commands for federation events if *pdu.kind() == TimelineEventType::RoomMessage { @@ -156,105 +137,66 @@ impl super::Service { } /// Derives new room state from the incoming event and filters forward - /// extremities accordingly. Does not set forward extremities. + /// extremities accordingly. /// /// Only call this function if the incoming PDU is not soft-failed or /// rejected. - async fn progress_state_and_extremities( - &self, - incoming_pdu: &PduEvent, - room_version_rules: &RoomVersionRules, - state_before: HashMap, - current_extremities: Vec, - state_lock: &Guard, - ) -> Result> { - if incoming_pdu.state_key().is_some() { - debug!("Event is a state-event. Deriving new room state"); - self.derive_new_state(incoming_pdu, room_version_rules, state_before, state_lock) - .await?; - } + pub async fn progress_extremities(&self, incoming_pdu: &PduEvent) -> Result<()> { + // Add this PDU to the list of extremities (unreferenced events). + // Note that we add it *again* as a no-op in append_pdu. This is done + // now so that there's never a point in time where we have zero forward + // extremities. + self.services + .state + .add_forward_extremity(&incoming_pdu.room_id_or_hash(), incoming_pdu.event_id()); + let Some(room_id) = incoming_pdu.room_id() else { + // If there's no room ID, this is a v12+ create event, which never + // has any predecessors, and consequently will be the + // only forward extremity. + return Ok(()); + }; - let start = Instant::now(); - trace!("Calculating extremities"); - // Start with the current extremity set, to avoid dropping unreferenced - // events. - let mut new_extremities: HashSet = - current_extremities.into_iter().collect(); - // Add the incoming event - new_extremities.insert(incoming_pdu.event_id().to_owned()); - // Remove any extremities that have since been referenced but not - // removed(?) - new_extremities = new_extremities - .into_iter() - .stream() - .broad_filter_map(|extremity| async { - self.services - .pdu_metadata - .is_event_referenced(&incoming_pdu.room_id_or_hash(), &extremity) - .await - .not() - .then_some(extremity) - }) - .collect() - .await; - - // Also iteratively walk prev events to ensure we drop any ancestors - // which are referenced regardless of soft-fail or rejection status. - // Soft-failed events and rejected events are not added as forward - // extremities, and as such do not remove their own prevs from the - // extremity set. This can lead to a situation where extremities build - // up because there's lots of soft-fails in the room, ultimately - // resulting in excessive cross-state boundary dummy events being - // created to squash the references. By walking the prevs until we stop - // reaching soft-fails, we can ensure that we properly prune all events - // which have actually been referenced, regardless of their soft-fail - // or rejection status. - let mut ancestors_todo: VecDeque = - VecDeque::from_iter(incoming_pdu.prev_events.clone()); - let room_id = incoming_pdu.room_id_or_hash(); + // Walk backwards from this event to find any rejected or soft-failed + // events. Discovering these events may discover implicitly + // referenced extremities that we can now remove. Doing the walk + // from the prev events also means they will all automatically be + // removed from the extremity set. + let mut ancestors_todo = VecDeque::from_iter(incoming_pdu.prev_events.clone()); while let Some(prev_event_id) = ancestors_todo.pop_front() { - new_extremities.remove(&prev_event_id); + assert_ne!( + incoming_pdu.event_id, prev_event_id, + "Current event appeared in extremity purge path (cycle)" + ); + // This event is known to be referenced, so we can remove it. self.services - .pdu_metadata - .mark_as_referenced(&room_id, once(prev_event_id.as_ref())); + .state + .remove_forward_extremity(room_id, &prev_event_id); let Ok(prev_event) = self.get_pdu(&prev_event_id).await else { + // If we don't have this PDU, we can't walk its prev events. continue; }; - // Only retain prevs that we have, which are themselves not - // referenced AND soft-failed/rejected/outlier. + // Now we collect all the prev events of this predecessor and filter + // for ones that we 1. know, and 2. have rejected/soft-failed. let outlier_prevs = prev_event .prev_events() .map(ToOwned::to_owned) .stream() .broad_filter_map(|prev_id| async { - let (exists, referenced, is_outlier, is_soft_failed, is_rejected) = tokio::join!( + let (is_known, is_accepted) = tokio::join!( self.pdu_exists(&prev_id), - self.services - .pdu_metadata - .is_event_referenced(&room_id, &prev_id), - self.db.outlier_pdu_exists(&prev_id).is_ok(), - self.services.pdu_metadata.is_event_soft_failed(&prev_id), - self.services.pdu_metadata.is_event_rejected(&prev_id) + self.services.pdu_metadata.is_event_accepted(&prev_id), ); - (exists && !referenced && (is_outlier || is_soft_failed || is_rejected)) - .then_some(prev_id) + (is_known && !is_accepted).then_some(prev_id) }) .collect::>() .await; + // We then add them to the queue to repeat the process. + // Eventually, we might end up walking back far enough to discover + // an accepted event that was added as a forward extremity, which + // means (since we can reach it) we can now remove it. ancestors_todo.extend(outlier_prevs); } - - debug!( - "Retained {} extremities against {} prev_events in {:?}", - new_extremities.len(), - incoming_pdu.prev_events().count(), - start.elapsed(), - ); - if new_extremities.is_empty() { - Err!("Resolved extremity set was empty after processing incoming event") - } else { - Ok(new_extremities.into_iter().collect()) - } + Ok(()) } /// Derives a new room state by adding the incoming PDU to the state before @@ -267,11 +209,11 @@ impl super::Service { async fn derive_new_state( &self, incoming_pdu: &PduEvent, + room_id: &RoomId, room_version_rules: &RoomVersionRules, state_before: HashMap, state_lock: &Guard, ) -> Result { - let room_id = incoming_pdu.room_id_or_hash(); // We also add state after incoming event to the fork states let mut state_at_incoming_event = state_before; let shortstatekey = self @@ -290,19 +232,19 @@ impl super::Service { let new_room_state = self .services .event_handler - .resolve_state(&room_id, room_version_rules, state_at_incoming_event) + .resolve_state(room_id, room_version_rules, state_at_incoming_event) .await?; debug!("Forcing new room state"); let HashSetCompressStateEvent { shortstatehash, added, removed } = self .services .state_compressor - .save_state(&room_id, new_room_state) + .save_state(room_id, new_room_state) .await?; self.services .state - .force_state(&room_id, shortstatehash, added, removed, state_lock) + .force_state(room_id, shortstatehash, added, removed, state_lock) .await } @@ -341,23 +283,18 @@ impl super::Service { ); } - /// Creates a new persisted data unit and adds it to a room. + /// Creates a new persistent data unit and adds it to a room. /// /// By this point the incoming event should be fully authenticated, no auth /// happens in `append_pdu`. /// /// Returns pdu id - pub async fn append_pdu<'a, Leaves>( - &'a self, - pdu: &'a PduEvent, + pub async fn append_pdu( + &self, + pdu: &PduEvent, mut pdu_json: CanonicalJsonObject, - leaves: Leaves, - state_lock: &'a RoomMutexGuard, - room_id: &'a RoomId, - ) -> Result - where - Leaves: Iterator + Send + 'a, - { + room_id: &RoomId, + ) -> RawPduId { // Coalesce database writes for the remainder of this scope. let _cork = self.db.db.cork_and_flush(); @@ -366,30 +303,14 @@ impl super::Service { .short .get_shortroomid(room_id) .await - .map_err(|_| err!(Database("Room does not exist")))?; + .expect("room ID must have a short room ID"); // Make unsigned fields correct. This is not properly documented in the // spec, but state events need to have previous content in the // unsigned field, so clients can easily interpret things like // membership changes - - // TODO: This needs to be refactored to add this information on the fly. - // Because the prev content becomes part of the unsigned object in the - // PDU, we unintentionally leak redacted or hidden content to local - // users. See: https://forgejo.ellis.link/continuwuation/continuwuity/issues/1103 self.populate_unsigned(pdu, &mut pdu_json).await; - // We must keep track of all events that have been referenced. - self.services - .pdu_metadata - .mark_as_referenced(room_id, pdu.prev_events().map(AsRef::as_ref)); - - trace!("setting forward extremities"); - self.services - .state - .set_forward_extremities(room_id, leaves, state_lock) - .await; - let insert_lock = self.mutex_insert.lock(room_id).await; let count1 = self.services.globals.next_count().unwrap(); @@ -401,6 +322,9 @@ impl super::Service { self.db .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2) .await; + self.services + .state + .add_forward_extremity(room_id, pdu.event_id()); drop(insert_lock); @@ -432,7 +356,7 @@ impl super::Service { self.send_to_interested_appservices(pdu, &pdu_id, room_id) .await; - Ok(pdu_id) + pdu_id } /// Notifies local users of the incoming event with a power levels context. diff --git a/src/service/rooms/timeline/backfill.rs b/src/service/rooms/timeline/backfill.rs index ece996f6e..85efcd5a1 100644 --- a/src/service/rooms/timeline/backfill.rs +++ b/src/service/rooms/timeline/backfill.rs @@ -228,13 +228,6 @@ impl super::Service { self.db.prepend_backfill_pdu(&pdu_id, &event_id, &value); drop(insert_lock); - - // Backfilled events skip append_pdu, so this is the only place their - // prev_events can be marked as referenced. See issue #2115. - self.services - .pdu_metadata - .mark_as_referenced(&room_id, pdu.prev_events().map(AsRef::as_ref)); - if pdu.kind == TimelineEventType::RoomMessage { let content: ExtractBody = pdu.get_content()?; if let Some(body) = content.body { diff --git a/src/service/rooms/timeline/build.rs b/src/service/rooms/timeline/build.rs index 6e0a7282c..276e5f9a4 100644 --- a/src/service/rooms/timeline/build.rs +++ b/src/service/rooms/timeline/build.rs @@ -1,4 +1,4 @@ -use std::{collections::HashSet, iter::once}; +use std::collections::HashSet; use conduwuit::trace; use conduwuit_core::{ @@ -8,7 +8,7 @@ use conduwuit_core::{ }; use futures::{FutureExt, StreamExt}; use ruma::{ - EventId, OwnedEventId, OwnedServerName, RoomId, UserId, + OwnedEventId, OwnedServerName, RoomId, UserId, events::{ TimelineEventType, room::{ @@ -113,32 +113,8 @@ impl super::Service { let statehashid = self.services.state.append_to_state(&pdu, &room_id).await?; trace!("State hash ID for {room_id}: {statehashid:?}"); - // prev_events is capped at the room version's limit, so this PDU does - // not necessarily reference every extremity. Any it did not reference - // is still a head of the DAG and has to be kept. - let prev_events: HashSet<&EventId> = pdu.prev_events().collect(); - let unreferenced: Vec = self - .services - .state - .get_forward_extremities(&room_id) - .ready_filter(|extremity| !prev_events.contains(&**extremity)) - .collect() - .await; - trace!("Generating raw ID for PDU {}", pdu.event_id()); - let pdu_id = self - .append_pdu( - &pdu, - pdu_json, - unreferenced - .iter() - .map(AsRef::as_ref) - .chain(once(pdu.event_id())), - state_lock, - &room_id, - ) - .boxed() - .await?; + let pdu_id = self.append_pdu(&pdu, pdu_json, &room_id).boxed().await; // Process admin commands for locally sent events if *pdu.kind() == TimelineEventType::RoomMessage { From bc15b7b6688dd801f627630f698e2d3bd342bb7b Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 01:39:40 +0100 Subject: [PATCH 075/342] fix: Remove dead references to mark_event_referenced --- src/service/rooms/membership/mod.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index 7300474ab..210b9643c 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -540,9 +540,6 @@ impl Service { } self.services.outlier.add_pdu_outlier(&event_id, &value); self.services.pdu_metadata.clear_pdu_markers(&event_id); - self.services - .pdu_metadata - .mark_as_referenced(room_id, once(event_id.as_ref())); if let Some(state_key) = &pdu.state_key { let shortstatekey = self .services @@ -575,9 +572,6 @@ impl Service { trace!(%event_id, "Adding PDU as an outlier from send_join auth_chain"); self.services.outlier.add_pdu_outlier(&event_id, &value); self.services.pdu_metadata.clear_pdu_markers(&event_id); - self.services - .pdu_metadata - .mark_as_referenced(room_id, once(event_id.as_ref())); let state_key = value .get("state_key") .and_then(|s| s.as_str()) From b04ffd7e6a5de7bb3eea0a7711f7e17cede7d66b Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 02:44:07 +0100 Subject: [PATCH 076/342] fix: Correctly remove extremities after creating a new event --- src/api/client/membership/knock.rs | 2 ++ src/service/rooms/membership/mod.rs | 1 + src/service/rooms/timeline/build.rs | 1 + 3 files changed, 4 insertions(+) diff --git a/src/api/client/membership/knock.rs b/src/api/client/membership/knock.rs index cbe2a90cc..fab6e2936 100644 --- a/src/api/client/membership/knock.rs +++ b/src/api/client/membership/knock.rs @@ -458,6 +458,7 @@ async fn knock_room_helper_local( .await?; info!("Appending room knock event locally"); + services.rooms.timeline.progress_extremities(&parsed_knock_pdu).await?; services .rooms .timeline @@ -654,6 +655,7 @@ async fn knock_room_helper_remote( .await?; info!("Appending room knock event locally"); + services.rooms.timeline.progress_extremities(&parsed_knock_pdu).await?; services .rooms .timeline diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index 210b9643c..c993e18ae 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -668,6 +668,7 @@ impl Service { // We append to state before appending the pdu, so we don't have a // moment in time with the pdu without it's state. This is okay // because append_pdu can't fail. + self.services.timeline.progress_extremities(&parsed_join_pdu).await?; let statehash_after_join = self .services .state diff --git a/src/service/rooms/timeline/build.rs b/src/service/rooms/timeline/build.rs index 276e5f9a4..ef46d245d 100644 --- a/src/service/rooms/timeline/build.rs +++ b/src/service/rooms/timeline/build.rs @@ -111,6 +111,7 @@ impl super::Service { // because append_pdu can't fail. trace!("Appending {} state for room {room_id}", pdu.event_id()); let statehashid = self.services.state.append_to_state(&pdu, &room_id).await?; + self.progress_extremities(&pdu).await?; trace!("State hash ID for {room_id}: {statehashid:?}"); trace!("Generating raw ID for PDU {}", pdu.event_id()); From 30f62eef25d7bcb20928c9337ed91e934845ecd8 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 02:44:49 +0100 Subject: [PATCH 077/342] style: reformat --- src/api/client/membership/knock.rs | 12 ++++++++++-- src/service/rooms/membership/mod.rs | 11 +++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/api/client/membership/knock.rs b/src/api/client/membership/knock.rs index fab6e2936..a29d80929 100644 --- a/src/api/client/membership/knock.rs +++ b/src/api/client/membership/knock.rs @@ -458,7 +458,11 @@ async fn knock_room_helper_local( .await?; info!("Appending room knock event locally"); - services.rooms.timeline.progress_extremities(&parsed_knock_pdu).await?; + services + .rooms + .timeline + .progress_extremities(&parsed_knock_pdu) + .await?; services .rooms .timeline @@ -655,7 +659,11 @@ async fn knock_room_helper_remote( .await?; info!("Appending room knock event locally"); - services.rooms.timeline.progress_extremities(&parsed_knock_pdu).await?; + services + .rooms + .timeline + .progress_extremities(&parsed_knock_pdu) + .await?; services .rooms .timeline diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index c993e18ae..67aee9ada 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -668,7 +668,10 @@ impl Service { // We append to state before appending the pdu, so we don't have a // moment in time with the pdu without it's state. This is okay // because append_pdu can't fail. - self.services.timeline.progress_extremities(&parsed_join_pdu).await?; + self.services + .timeline + .progress_extremities(&parsed_join_pdu) + .await?; let statehash_after_join = self .services .state @@ -701,7 +704,11 @@ impl Service { info!("Replacing local forward extremities"); self.services .state - .replace_forward_extremities(room_id, once(parsed_join_pdu.event_id()), &state_lock) + .replace_forward_extremities( + room_id, + once(parsed_join_pdu.event_id()), + &state_lock, + ) .await; } drop(cork); From ae26d5c23932fdfaf2a5cac1f15f01619207f808 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 03:53:04 +0100 Subject: [PATCH 078/342] fix: Add startup migration to re-process existing extremities on-disk --- src/service/migrations.rs | 75 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 81ff11dd8..13733159c 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -8,12 +8,12 @@ use std::{ }; use conduwuit::{ - Err, Error, Event, Pdu, Result, debug, debug_info, debug_warn, err, error, info, + Err, Error, Event, Pdu, PduCount, Result, debug, debug_info, debug_warn, err, error, info, result::NotFound, trace, utils::{ IterStream, ReadyExt, - stream::{TryExpect, TryIgnore}, + stream::{TryExpect, TryIgnore, automatic_width}, to_canonical_object, }, warn, @@ -167,6 +167,11 @@ migration!(stringify!($name) => $name) // names, preventing users from signing in. VersionBump(22), migration!(fix_oauth_scope_names), + // Removes any extremities in roomid_pduleaves that we do not know about (and + // consequently should not reference). + migration!(remove_unknown_extremities), + // Re-calculates extremities for any rooms that actually lack any extremities at all. + migration!(consistency_check_extremity_tracker), ] }; @@ -979,3 +984,69 @@ async fn fix_oauth_scope_names(services: &Services) -> Result { Ok(()) } + +async fn remove_unknown_extremities(services: &Services) -> Result { + services.db["roomid_pduleaves"] + .keys() + .ignore_err() + .for_each_concurrent( + automatic_width(), + |(room_id, event_id): (OwnedRoomId, OwnedEventId)| async move { + if !services.rooms.timeline.pdu_exists(&event_id).await { + debug!("Removing unknown extremity in {room_id}: {event_id}"); + services + .rooms + .state + .remove_forward_extremity(&room_id, &event_id); + } + }, + ) + .await; + Ok(()) +} + +async fn consistency_check_extremity_tracker(services: &Services) -> Result { + let mut rooms = services.rooms.metadata.iter_ids(); + + // For every room the server is a member of, + while let Some(room_id) = rooms.next().await { + // If this room has no extremities, re-calculate + if services + .rooms + .state + .get_forward_extremities(&room_id) + .count() + .await + >= 1 + { + continue; + } + + warn!( + "Room {room_id} is missing extremity information, recalculating. This may take a \ + long time if this room is old." + ); + services + .rooms + .timeline + .pdus(&room_id, Some(PduCount::Normal(0))) + .ignore_err() + .for_each(|(_, pdu)| { + let room_id = &room_id; + async move { + services + .rooms + .timeline + .progress_extremities(&pdu) + .await + .inspect_err(|e| { + error!("Failed to progress extremities in {room_id}: {e:?}"); + }) + .ok(); + } + }) + .await; + } + + Ok(()) +} From 224cf049363b7c2443b8c4b404f81661dbb0066d Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 03:59:58 +0100 Subject: [PATCH 079/342] fix: Never allow unknown/backfilled PDUs to become extremities --- src/service/rooms/timeline/append.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index b41f78673..2e4bdeadd 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -176,17 +176,21 @@ impl super::Service { continue; }; // Now we collect all the prev events of this predecessor and filter - // for ones that we 1. know, and 2. have rejected/soft-failed. + // for ones that we 1. know, 2. are not backfilled, and 3. have + // rejected/soft-failed. let outlier_prevs = prev_event .prev_events() .map(ToOwned::to_owned) .stream() .broad_filter_map(|prev_id| async { - let (is_known, is_accepted) = tokio::join!( + let (exists, count, is_accepted) = tokio::join!( self.pdu_exists(&prev_id), + self.get_pdu_count(&prev_id) + .unwrap_or(PduCount::Backfilled(i64::MIN)), self.services.pdu_metadata.is_event_accepted(&prev_id), ); - (is_known && !is_accepted).then_some(prev_id) + (exists && !matches!(count, PduCount::Backfilled(_)) && !is_accepted) + .then_some(prev_id) }) .collect::>() .await; From 5208efcb5e04002e4e98cd70f2f10605925a5921 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 04:11:25 +0100 Subject: [PATCH 080/342] fix: Make migration handle excessive extremities too --- src/service/migrations.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 13733159c..7d9f1af8b 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -985,6 +985,7 @@ async fn fix_oauth_scope_names(services: &Services) -> Result { Ok(()) } +#[tracing::instrument(skip_all)] async fn remove_unknown_extremities(services: &Services) -> Result { services.db["roomid_pduleaves"] .keys() @@ -1005,27 +1006,36 @@ async fn remove_unknown_extremities(services: &Services) -> Result { Ok(()) } +#[tracing::instrument(skip_all)] async fn consistency_check_extremity_tracker(services: &Services) -> Result { let mut rooms = services.rooms.metadata.iter_ids(); // For every room the server is a member of, while let Some(room_id) = rooms.next().await { // If this room has no extremities, re-calculate - if services + let extremity_count = services .rooms .state .get_forward_extremities(&room_id) .count() - .await - >= 1 + .await; + + if extremity_count > 20 { - continue; + warn!(%extremity_count, "Room {room_id} has an abnormal number of forward extremities, attempting to re-calculate to a sane value. This might take a while."); + services + .rooms + .state + .get_forward_extremities(&room_id) + .ready_for_each(|event_id| services.rooms.state.remove_forward_extremity(&room_id, &event_id)) + .await; + } else if extremity_count == 0 { + warn!( + "Room {room_id} is missing extremity information, recalculating. This may take a \ + long time if this room is old." + ); } - warn!( - "Room {room_id} is missing extremity information, recalculating. This may take a \ - long time if this room is old." - ); services .rooms .timeline From 14f5f62182ae54d59bed2bf0bf9812273cd24a3c Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 05:15:20 +0100 Subject: [PATCH 081/342] fix: Only consider accepted PDUs in extremity consistency check --- src/service/migrations.rs | 22 +++++++++++++++++----- src/service/rooms/state/mod.rs | 14 +++++++++----- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 7d9f1af8b..cd2d33682 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -1020,19 +1020,23 @@ async fn consistency_check_extremity_tracker(services: &Services) -> Result { .count() .await; - if extremity_count > 20 - { + if extremity_count > 20 { warn!(%extremity_count, "Room {room_id} has an abnormal number of forward extremities, attempting to re-calculate to a sane value. This might take a while."); services .rooms .state .get_forward_extremities(&room_id) - .ready_for_each(|event_id| services.rooms.state.remove_forward_extremity(&room_id, &event_id)) + .ready_for_each(|event_id| { + services + .rooms + .state + .remove_forward_extremity(&room_id, &event_id); + }) .await; } else if extremity_count == 0 { warn!( - "Room {room_id} is missing extremity information, recalculating. This may take a \ - long time if this room is old." + "Room {room_id} is missing extremity information, recalculating. This may take \ + a long time if this room is old." ); } @@ -1044,6 +1048,14 @@ async fn consistency_check_extremity_tracker(services: &Services) -> Result { .for_each(|(_, pdu)| { let room_id = &room_id; async move { + if !services + .rooms + .pdu_metadata + .is_event_accepted(pdu.event_id()) + .await + { + return; + } services .rooms .timeline diff --git a/src/service/rooms/state/mod.rs b/src/service/rooms/state/mod.rs index f2740a84c..09aab86f2 100644 --- a/src/service/rooms/state/mod.rs +++ b/src/service/rooms/state/mod.rs @@ -432,6 +432,15 @@ impl Service { ) where I: Iterator + Send + 'a, { + self.clear_forward_extremities(room_id).await; + + for event_id in event_ids { + let key = (room_id, event_id); + self.db.roomid_pduleaves.put_raw(key, event_id); + } + } + + pub async fn clear_forward_extremities(&self, room_id: &RoomId) { let prefix = (room_id, Interfix); self.db .roomid_pduleaves @@ -439,11 +448,6 @@ impl Service { .ignore_err() .ready_for_each(|key| self.db.roomid_pduleaves.remove(key)) .await; - - for event_id in event_ids { - let key = (room_id, event_id); - self.db.roomid_pduleaves.put_raw(key, event_id); - } } /// Appends a forward extremity to the extremity tracker. From c6832372c280b4ca6d425e38639012c418bcb3eb Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 20:01:18 +0100 Subject: [PATCH 082/342] feat: Add command to enumerate extremities --- src/admin/debug/commands.rs | 42 ++++++++++++++++++++++++++++++++++++- src/admin/debug/mod.rs | 4 ++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/admin/debug/commands.rs b/src/admin/debug/commands.rs index 9fc69aae9..7b5e82dc6 100644 --- a/src/admin/debug/commands.rs +++ b/src/admin/debug/commands.rs @@ -14,7 +14,7 @@ use conduwuit::{ state_res::EventTypeExt, trace, utils, utils::{ - stream::{IterStream, ReadyExt}, + stream::{BroadbandExt, IterStream, ReadyExt}, string::EMPTY, to_canonical_object, }, @@ -1207,6 +1207,46 @@ impl crate::Context<'_> { .await } + pub(super) async fn room_extremities(&self, room_id: OwnedRoomId) -> Result { + let mut extremities = self + .services + .rooms + .state + .get_forward_extremities(&room_id) + .broad_filter_map(|event_id| async move { + self.services.rooms.timeline.get_pdu(&event_id).await.ok() + }) + .collect::>() + .await; + extremities.sort_by_key(|pdu| (pdu.depth, pdu.origin_server_ts)); + if extremities.is_empty() { + return Err!("No room extremities."); + } + self.write_str("| Event ID | Kind | Sender | Timestamp | Depth |\n") + .await?; + self.write_str("| -------- | ---- | ------ | --------- | ----- |\n") + .await?; + for pdu in extremities { + let url = format!( + "https://matrix.to/#/{}/{}?via={}", + room_id, + pdu.event_id(), + self.services.server.name + ); + self.write_str(&format!( + "| [`{}`]({url}) | `{}` | `{}` | `{}` | `{}` |\n", + pdu.event_id(), + pdu.kind(), + pdu.sender(), + pdu.origin_server_ts, + pdu.depth + )) + .await?; + } + + Ok(()) + } + pub(super) async fn servers_in_backoff( &self, room_id: Option, diff --git a/src/admin/debug/mod.rs b/src/admin/debug/mod.rs index f544637ab..9bf3647b3 100644 --- a/src/admin/debug/mod.rs +++ b/src/admin/debug/mod.rs @@ -234,6 +234,10 @@ pub enum DebugCommand { page: Option, }, + RoomExtremities { + room_id: OwnedRoomId, + }, + /// Lists remote servers that are currently in a "backoff" state. /// /// Servers in this list will not be contacted until the retry time elapses, From d128207d712e65cd6acdc6721c018fdcc4f69c9e Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 13 Oct 2026 20:26:26 +0100 Subject: [PATCH 083/342] fix: Make the extremity check consistency migration faster --- src/service/migrations.rs | 135 ++++++++++++++++++++++++++------------ 1 file changed, 92 insertions(+), 43 deletions(-) diff --git a/src/service/migrations.rs b/src/service/migrations.rs index cd2d33682..86690bc52 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -13,7 +13,7 @@ use conduwuit::{ trace, utils::{ IterStream, ReadyExt, - stream::{TryExpect, TryIgnore, automatic_width}, + stream::{TryExpect, TryIgnore, WidebandExt, automatic_width}, to_canonical_object, }, warn, @@ -994,7 +994,18 @@ async fn remove_unknown_extremities(services: &Services) -> Result { automatic_width(), |(room_id, event_id): (OwnedRoomId, OwnedEventId)| async move { if !services.rooms.timeline.pdu_exists(&event_id).await { - debug!("Removing unknown extremity in {room_id}: {event_id}"); + info!("Removing unknown extremity in {room_id}: {event_id}"); + services + .rooms + .state + .remove_forward_extremity(&room_id, &event_id); + } else if !services + .rooms + .pdu_metadata + .is_event_accepted(&event_id) + .await + { + info!("Removing failed extremity in {room_id}: {event_id}"); services .rooms .state @@ -1020,54 +1031,92 @@ async fn consistency_check_extremity_tracker(services: &Services) -> Result { .count() .await; - if extremity_count > 20 { - warn!(%extremity_count, "Room {room_id} has an abnormal number of forward extremities, attempting to re-calculate to a sane value. This might take a while."); - services - .rooms - .state - .get_forward_extremities(&room_id) - .ready_for_each(|event_id| { - services - .rooms - .state - .remove_forward_extremity(&room_id, &event_id); - }) - .await; - } else if extremity_count == 0 { + if extremity_count == 0 { warn!( "Room {room_id} is missing extremity information, recalculating. This may take \ a long time if this room is old." ); - } - - services - .rooms - .timeline - .pdus(&room_id, Some(PduCount::Normal(0))) - .ignore_err() - .for_each(|(_, pdu)| { - let room_id = &room_id; - async move { - if !services - .rooms - .pdu_metadata - .is_event_accepted(pdu.event_id()) - .await - { - return; + let epoch_ts = services + .rooms + .timeline + .first_pdu_in_room(&room_id) + .await + .map_or_default(|e| e.origin_server_ts().0); + services + .rooms + .timeline + .pdus(&room_id, Some(PduCount::Normal(0))) + .ignore_err() + .for_each(|(_, pdu)| { + let room_id = &room_id; + async move { + if pdu.origin_server_ts < epoch_ts { + return; + } + if !services + .rooms + .pdu_metadata + .is_event_accepted(pdu.event_id()) + .await + { + return; + } + services + .rooms + .timeline + .progress_extremities(&pdu) + .await + .inspect_err(|e| { + error!("Failed to progress extremities in {room_id}: {e:?}"); + }) + .ok(); } + }) + .await; + } else if extremity_count > 20 { + warn!( + %extremity_count, + "Room {room_id} has an abnormal number of forward extremities, retaining latest 20" + ); + let mut thinned = services + .rooms + .state + .get_forward_extremities(&room_id) + .wide_filter_map(|event_id| { + let room_id = &room_id; + async move { + let Ok(pdu) = + services.rooms.timeline.get_non_outlier_pdu(&event_id).await + else { + services + .rooms + .state + .remove_forward_extremity(room_id, &event_id); + return None; + }; + Some(pdu) + } + }) + .collect::>() + .await; + thinned.sort_by_key(|pdu| { + ( + i64::from(pdu.depth).saturating_mul(-1), + i64::from(pdu.origin_server_ts).saturating_mul(-1), + ) + }); + thinned + .into_iter() + .stream() + .skip(20) + .ready_for_each(move |pdu| { services .rooms - .timeline - .progress_extremities(&pdu) - .await - .inspect_err(|e| { - error!("Failed to progress extremities in {room_id}: {e:?}"); - }) - .ok(); - } - }) - .await; + .state + .remove_forward_extremity(&room_id, pdu.event_id()); + }) + .await; + } } Ok(()) From 363097b31b4e3989e968401fbc5d766b3ee98fd7 Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 23 Oct 2026 22:57:39 +0200 Subject: [PATCH 084/342] fix: Centralise extremity progression --- src/service/rooms/timeline/append.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index 2e4bdeadd..60b3900e5 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -95,7 +95,6 @@ impl super::Service { self.derive_new_state(pdu, &room_id, room_version_rules, state_before, state_lock) .await?; } - self.progress_extremities(pdu).await?; let pdu_id = self.append_pdu(pdu, pdu_json, &room_id).await; @@ -326,9 +325,7 @@ impl super::Service { self.db .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2) .await; - self.services - .state - .add_forward_extremity(room_id, pdu.event_id()); + self.progress_extremities(pdu).await.expect("progressing extremities should never fail"); drop(insert_lock); From 60de549cf9c90a404d55c8deabd19eadfe9af698 Mon Sep 17 00:00:00 2001 From: timedout Date: Thu, 29 Oct 2026 02:55:12 +0000 Subject: [PATCH 085/342] perf: Write empty rows when replacing extremities --- src/service/rooms/state/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/service/rooms/state/mod.rs b/src/service/rooms/state/mod.rs index 09aab86f2..147e944a7 100644 --- a/src/service/rooms/state/mod.rs +++ b/src/service/rooms/state/mod.rs @@ -436,7 +436,7 @@ impl Service { for event_id in event_ids { let key = (room_id, event_id); - self.db.roomid_pduleaves.put_raw(key, event_id); + self.db.roomid_pduleaves.put_raw(key, []); } } From 068ba883782716b5911c9ed9b7448b88c555cddb Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 30 Oct 2026 00:54:52 +0000 Subject: [PATCH 086/342] style: Fix formatting --- src/service/rooms/timeline/append.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index 60b3900e5..e1044514a 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -325,7 +325,9 @@ impl super::Service { self.db .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2) .await; - self.progress_extremities(pdu).await.expect("progressing extremities should never fail"); + self.progress_extremities(pdu) + .await + .expect("progressing extremities should never fail"); drop(insert_lock); From cb27a2082d199eec5d7ebc82ce53e0ab4dc23e3d Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 30 Oct 2026 00:56:10 +0000 Subject: [PATCH 087/342] chore: Add newsfrag --- changelog.d/2356.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2356.bugfix.md diff --git a/changelog.d/2356.bugfix.md b/changelog.d/2356.bugfix.md new file mode 100644 index 000000000..2836d94f2 --- /dev/null +++ b/changelog.d/2356.bugfix.md @@ -0,0 +1 @@ +Once again fixed how room extremities are handled, fixing a problem that made continuwuity gradually make rooms needlessly complex, which also caused more frequent state resets. From abf8f878bc307e6623914bdf97dce96a0cfdc1f0 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 31 Oct 2026 08:57:02 +0100 Subject: [PATCH 088/342] fix: gap fill outliers that are missing prev events Signed-off-by: Erwan Leboucher --- changelog.d/+gap-fill-outlier-missing-prevs.bugfix.md | 1 + src/service/rooms/event_handler/fetch_and_handle_outliers.rs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+gap-fill-outlier-missing-prevs.bugfix.md diff --git a/changelog.d/+gap-fill-outlier-missing-prevs.bugfix.md b/changelog.d/+gap-fill-outlier-missing-prevs.bugfix.md new file mode 100644 index 000000000..76c5a059f --- /dev/null +++ b/changelog.d/+gap-fill-outlier-missing-prevs.bugfix.md @@ -0,0 +1 @@ +Fix gap filling skipping outlier events that are missing their previous events. Contributed by @eleboucher. diff --git a/src/service/rooms/event_handler/fetch_and_handle_outliers.rs b/src/service/rooms/event_handler/fetch_and_handle_outliers.rs index e450b0d79..24ef24f54 100644 --- a/src/service/rooms/event_handler/fetch_and_handle_outliers.rs +++ b/src/service/rooms/event_handler/fetch_and_handle_outliers.rs @@ -310,9 +310,9 @@ impl super::Service { .stream() .fold(0_u8, |i, event_id| async move { if self.services.timeline.pdu_exists(event_id).await { - i.expected_add(1) - } else { i + } else { + i.expected_add(1) } }) .await; From dc03f2136a981e909590a53f1f95ffab6cad1544 Mon Sep 17 00:00:00 2001 From: Ginger Date: Tue, 27 Oct 2026 22:44:05 -0400 Subject: [PATCH 089/342] fix: Validate OAuth HTTPS redirect URIs are subdomains of the client domain --- src/service/oauth/client_metadata.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/service/oauth/client_metadata.rs b/src/service/oauth/client_metadata.rs index 75d6d15b3..4ee946e8e 100644 --- a/src/service/oauth/client_metadata.rs +++ b/src/service/oauth/client_metadata.rs @@ -81,6 +81,15 @@ impl ClientMetadata { if !uri.username().is_empty() || uri.password().is_some() { return Err("HTTPS redirect URIs must not contain credentials."); } + + if !uri + .domain() + .is_some_and(|domain| is_subdomain(domain, client_domain)) + { + return Err( + "All HTTPS redirect URIs must be subdomains of the client URI." + ); + } }, | "http" if self.application_type == ApplicationType::Native => { if uri From 5a4f3acae460ffb9f15e152d0bdabba540e85eaf Mon Sep 17 00:00:00 2001 From: Ginger Date: Sat, 31 Oct 2026 00:22:15 -0400 Subject: [PATCH 090/342] chore: Changelog --- changelog.d/2421.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2421.bugfix.md diff --git a/changelog.d/2421.bugfix.md b/changelog.d/2421.bugfix.md new file mode 100644 index 000000000..f5c1e842d --- /dev/null +++ b/changelog.d/2421.bugfix.md @@ -0,0 +1 @@ +Redirect URIs in OAuth clients' metadata are now properly validated to be on a subdomain of the OAuth issuer URL domain. Contributed by @ginger. From f3d8e8d688ca7ca66f2e8bba2a2a6fcc65af2aaf Mon Sep 17 00:00:00 2001 From: timedout Date: Mon, 2 Nov 2026 00:50:41 +0000 Subject: [PATCH 091/342] chore: Reformat --- src/service/migrations.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 86690bc52..727bcce17 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -167,10 +167,11 @@ migration!(stringify!($name) => $name) // names, preventing users from signing in. VersionBump(22), migration!(fix_oauth_scope_names), - // Removes any extremities in roomid_pduleaves that we do not know about (and - // consequently should not reference). + // Removes any extremities in roomid_pduleaves that we do not know about + // (and consequently should not reference). migration!(remove_unknown_extremities), - // Re-calculates extremities for any rooms that actually lack any extremities at all. + // Re-calculates extremities for any rooms that actually lack any + // extremities at all. migration!(consistency_check_extremity_tracker), ] }; From ddbdd1ed0c87b0900868163be5fd4947ad8e4f52 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Fri, 30 Oct 2026 05:02:31 +0000 Subject: [PATCH 092/342] chore(deps): update ruma digest to 0ed7fba --- Cargo.lock | 22 +++++++++++----------- Cargo.toml | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7bca821a5..a41dde29b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4997,7 +4997,7 @@ dependencies = [ [[package]] name = "ruma" version = "0.17.2" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "assign", "js_int", @@ -5016,7 +5016,7 @@ dependencies = [ [[package]] name = "ruma-appservice-api" version = "0.17.1" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "http", "js_int", @@ -5029,7 +5029,7 @@ dependencies = [ [[package]] name = "ruma-client-api" version = "0.25.2" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "as_variant", "assign", @@ -5051,7 +5051,7 @@ dependencies = [ [[package]] name = "ruma-common" version = "0.20.2" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "as_variant", "base64 0.23.1", @@ -5084,7 +5084,7 @@ dependencies = [ [[package]] name = "ruma-events" version = "0.35.2" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "as_variant", "indexmap 2.14.2", @@ -5105,7 +5105,7 @@ dependencies = [ [[package]] name = "ruma-federation-api" version = "0.16.1" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "bytes", "http", @@ -5127,7 +5127,7 @@ dependencies = [ [[package]] name = "ruma-identifiers-validation" version = "0.14.0" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "js_int", "thiserror 2.0.21", @@ -5136,7 +5136,7 @@ dependencies = [ [[package]] name = "ruma-macros" version = "0.20.2" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "as_variant", "cfg-if", @@ -5152,7 +5152,7 @@ dependencies = [ [[package]] name = "ruma-push-gateway-api" version = "0.16.0" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "js_int", "ruma-common", @@ -5164,7 +5164,7 @@ dependencies = [ [[package]] name = "ruma-signatures" version = "0.22.1" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "base64 0.23.1", "ed25519-dalek 3.0.0", @@ -5181,7 +5181,7 @@ dependencies = [ [[package]] name = "ruma-state-res" version = "0.18.0" -source = "git+https://github.com/ruma/ruma.git?rev=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0" +source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "js_int", "ruma-common", diff --git a/Cargo.toml b/Cargo.toml index 3d4896609..df7566608 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -348,7 +348,7 @@ version = "1.1.1" # Used for matrix spec type definitions and helpers [workspace.dependencies.ruma] git = "https://github.com/ruma/ruma.git" -rev = "e03080c0790ba7b24ea37f9fd11794678cc975b0" +rev = "0ed7fba34213f18a628a56f527c6cc795cd7eef5" features = [ "appservice-api-c", "client-api", From d8229a7933ea6e8d86fa9001d2d52f825de8fc0f Mon Sep 17 00:00:00 2001 From: Ginger Date: Mon, 2 Nov 2026 14:03:52 -0500 Subject: [PATCH 093/342] fix(ci): Use local versions of workflows hosted on tomfos.tr --- .forgejo/actions/sccache/action.yml | 2 +- .forgejo/actions/setup-llvm-with-apt/action.yml | 2 +- .forgejo/actions/setup-rust/action.yml | 4 ++-- .forgejo/workflows/build-debian.yml | 2 +- .forgejo/workflows/documentation.yml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.forgejo/actions/sccache/action.yml b/.forgejo/actions/sccache/action.yml index f84b4410e..fd22591ae 100644 --- a/.forgejo/actions/sccache/action.yml +++ b/.forgejo/actions/sccache/action.yml @@ -7,7 +7,7 @@ runs: using: composite steps: - name: Install sccache - uses: https://git.tomfos.tr/tom/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1 - name: Configure sccache uses: https://github.com/actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: diff --git a/.forgejo/actions/setup-llvm-with-apt/action.yml b/.forgejo/actions/setup-llvm-with-apt/action.yml index a24c9a8b3..213f3abb1 100644 --- a/.forgejo/actions/setup-llvm-with-apt/action.yml +++ b/.forgejo/actions/setup-llvm-with-apt/action.yml @@ -29,7 +29,7 @@ runs: steps: - name: Detect runner OS id: runner-os - uses: https://git.tomfos.tr/actions/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1 - name: Configure cross-compilation architecture if: inputs.dpkg-arch != '' diff --git a/.forgejo/actions/setup-rust/action.yml b/.forgejo/actions/setup-rust/action.yml index 70b9f2892..52126179c 100644 --- a/.forgejo/actions/setup-rust/action.yml +++ b/.forgejo/actions/setup-rust/action.yml @@ -39,7 +39,7 @@ runs: steps: - name: Detect runner OS id: runner-os - uses: https://git.tomfos.tr/actions/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1 - name: Configure Cargo environment shell: bash @@ -147,7 +147,7 @@ runs: run: echo "::group::📦 Restoring build cache" - name: Setup sccache - uses: https://git.tomfos.tr/tom/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1 - name: End build cache restore group shell: bash diff --git a/.forgejo/workflows/build-debian.yml b/.forgejo/workflows/build-debian.yml index 8e3094cff..20a4a5955 100644 --- a/.forgejo/workflows/build-debian.yml +++ b/.forgejo/workflows/build-debian.yml @@ -60,7 +60,7 @@ jobs: cargo-debian-${{ steps.debian-version.outputs.distribution }}-${{ matrix.arch }}- - name: Setup sccache - uses: https://git.tomfos.tr/tom/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1 - name: Configure sccache environment run: | diff --git a/.forgejo/workflows/documentation.yml b/.forgejo/workflows/documentation.yml index e66a66957..aed562591 100644 --- a/.forgejo/workflows/documentation.yml +++ b/.forgejo/workflows/documentation.yml @@ -28,7 +28,7 @@ jobs: - name: Detect runner environment id: runner-env - uses: https://git.tomfos.tr/actions/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1 - name: Setup Node.js if: steps.runner-env.outputs.node_major == '' || steps.runner-env.outputs.node_major < '20' From 0e5baa93992fc9154a032a2bc56f53a7fd1e1ac8 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 3 Nov 2026 05:03:31 +0000 Subject: [PATCH 094/342] chore(deps): update https://github.com/taiki-e/install-action digest to 682ce6c --- .forgejo/actions/timelord/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/actions/timelord/action.yml b/.forgejo/actions/timelord/action.yml index 8522b20f7..0275bb93e 100644 --- a/.forgejo/actions/timelord/action.yml +++ b/.forgejo/actions/timelord/action.yml @@ -71,7 +71,7 @@ runs: - name: Install timelord-cli and git-warp-time if: steps.check-binaries.outputs.need-install == 'true' - uses: https://github.com/taiki-e/install-action@5488ac5a951645ce95062214902ac4b6bc1a1037 # v2 + uses: https://github.com/taiki-e/install-action@682ce6c3c696a4cd5168a05f98e51aa02b877941 # v2 with: tool: git-warp-time,timelord-cli@3.0.1 From 0727d564a2096dbf5901c98d819b42e7846b6f01 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 3 Nov 2026 09:52:43 +0000 Subject: [PATCH 095/342] fix: Avoid v12 room ID collisions when creating rooms concurrently Fixes #2424. v12 rooms created by the same user in the same millisecond got the same room ID, so they ended up as one room. Reviewed-on: https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2433 Reviewed-by: nex Reviewed-by: Jade Ellis --- changelog.d/2424.bugfix.md | 1 + src/api/client/room/create.rs | 24 ++++++++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 changelog.d/2424.bugfix.md diff --git a/changelog.d/2424.bugfix.md b/changelog.d/2424.bugfix.md new file mode 100644 index 000000000..be4e5be70 --- /dev/null +++ b/changelog.d/2424.bugfix.md @@ -0,0 +1 @@ +Fix v12 rooms created by the same user in the same millisecond ending up as the same room. Contributed by @eleboucher. diff --git a/src/api/client/room/create.rs b/src/api/client/room/create.rs index a2acf5ec1..279b267c5 100644 --- a/src/api/client/room/create.rs +++ b/src/api/client/room/create.rs @@ -1,18 +1,21 @@ -use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::{ + collections::{BTreeMap, BTreeSet, HashSet}, + sync::atomic::{AtomicU64, Ordering::SeqCst}, +}; use axum::extract::State; use conduwuit::{ Err, Error, Result, debug, debug_info, err, info, matrix::{StateKey, pdu::PartialPdu}, trace, - utils::to_canonical_object, + utils::{self, to_canonical_object}, warn, }; use conduwuit_service::{Services, appservice::RegistrationInfo}; use futures::FutureExt; use ruma::{ CanonicalJsonObject, CanonicalJsonValue, Int, MilliSecondsSinceUnixEpoch, OwnedRoomAliasId, - OwnedUserId, RoomAliasId, RoomId, + OwnedUserId, RoomAliasId, RoomId, UInt, api::{ client::room::{ self, @@ -46,6 +49,8 @@ use serde_json::value::to_raw_value; use crate::{Ruma, client::invite_helper}; +static LAST_CREATE_TS: AtomicU64 = AtomicU64::new(0); + // We use this to keep around extra data in the `creation_content` // while still parsing and validating keys that we care about. #[derive(Deserialize, Default)] @@ -307,6 +312,17 @@ pub(crate) async fn create_room_route( .map(MilliSecondsSinceUnixEpoch) }; + // v12+ room IDs are the create event's hash, so give each create event a + // unique timestamp to avoid collisions. + let create_timestamp = custom_origin_server_ts.or_else(|| { + room_id.is_none().then(|| { + let now = utils::millis_since_unix_epoch(); + let next = |last: u64| now.max(last.saturating_add(1)); + let prev = LAST_CREATE_TS.update(SeqCst, SeqCst, next); + MilliSecondsSinceUnixEpoch(UInt::new_saturating(next(prev))) + }) + }); + let mut create_event_content = to_canonical_object(create_event_content) .expect("should be able to serialize create event content"); @@ -322,7 +338,7 @@ pub(crate) async fn create_room_route( event_type: TimelineEventType::RoomCreate, content: to_raw_value(&create_event_content)?, state_key: Some(StateKey::new()), - timestamp: custom_origin_server_ts, + timestamp: create_timestamp, ..Default::default() }, sender_user, From c77bbf6d18a4c72b4df6876fbef98257238eca46 Mon Sep 17 00:00:00 2001 From: Ginger Date: Tue, 3 Nov 2026 20:41:11 -0500 Subject: [PATCH 096/342] fix: Fix busted `url_preview` feature gate --- src/service/media/preview.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index ac10fa40c..084aa9a1b 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -7,17 +7,13 @@ use std::time::SystemTime; -#[cfg(feature = "url_preview")] -use conduwuit::utils::response::LimitReadExt; -use conduwuit::{Err, Result, debug, err}; +use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt}; use ipaddress::IPAddress; -#[cfg(feature = "url_preview")] use ruma::OwnedMxcUri; use serde::Serialize; use url::Url; use super::Service; -#[cfg(feature = "url_preview")] use crate::media::mxc::Mxc; #[derive(Serialize, Default)] From 2ee28c1b8249e85124a9a60b45e4bf5b0ac2c843 Mon Sep 17 00:00:00 2001 From: Ginger Date: Tue, 3 Nov 2026 20:48:58 -0500 Subject: [PATCH 097/342] fix: Fix busted axum feature list --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index df7566608..520c9abcc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -104,6 +104,7 @@ version = "0.8.8" default-features = false features = [ "form", + "query", "http1", "http2", "json", From d2eeae34a94a8a9154f185219df0ef0da1bacc94 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 4 Nov 2026 05:01:50 +0000 Subject: [PATCH 098/342] chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.210.1 --- .forgejo/workflows/renovate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/renovate.yml b/.forgejo/workflows/renovate.yml index c6a43a6de..57a6c3048 100644 --- a/.forgejo/workflows/renovate.yml +++ b/.forgejo/workflows/renovate.yml @@ -43,7 +43,7 @@ jobs: name: Renovate runs-on: ubuntu-latest container: - image: ghcr.io/renovatebot/renovate:44.190.1@sha256:1b1306e7f1f0bafc56f6c471b6c309760ab990e9a60901623bcd14016717a528 + image: ghcr.io/renovatebot/renovate:44.210.1@sha256:45cc73346c44a9afe037f2d19766f2b545b59b2ed31b937b5b09017d2958e45f options: --tmpfs /tmp:exec steps: - name: Checkout From 34c5787af065c910d45a76453b0c8f2b2765cdc3 Mon Sep 17 00:00:00 2001 From: Ginger Date: Wed, 4 Nov 2026 12:23:19 -0500 Subject: [PATCH 099/342] fix: Fix join rule evaluation for servers again Reviewed-by: timedout Reviewed-by: Jade Ellis --- src/service/rooms/membership/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index 67aee9ada..dd7263de0 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -901,7 +901,7 @@ impl Service { .server_in_room(self.services.globals.server_name(), condition_room) .await { - let is_joined = match entity { + let is_joined_to_condition_room = match entity { | JoinConditionEntity::User(user_id) => self.services .state_cache @@ -910,11 +910,11 @@ impl Service { | JoinConditionEntity::Server(server) => self.services .state_cache - .server_in_room(server, room_id) + .server_in_room(server, condition_room) .await, }; - if is_joined { + if is_joined_to_condition_room { debug!( ?entity, ?room_id, From dad9e1426cf1ae04d5b71ad5e4610a96d659d239 Mon Sep 17 00:00:00 2001 From: Bardi Harborow Date: Wed, 4 Nov 2026 22:03:24 +1100 Subject: [PATCH 100/342] fix: Advertise m.forget_forced_upon_leave capability according to config --- changelog.d/2452.bugfix.md | 1 + src/api/client/capabilities.rs | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 changelog.d/2452.bugfix.md diff --git a/changelog.d/2452.bugfix.md b/changelog.d/2452.bugfix.md new file mode 100644 index 000000000..451d8a020 --- /dev/null +++ b/changelog.d/2452.bugfix.md @@ -0,0 +1 @@ +The `m.forget_forced_upon_leave` capability now reflects the `forget_forced_upon_leave` config option instead of always being advertised as enabled. diff --git a/src/api/client/capabilities.rs b/src/api/client/capabilities.rs index 28a5e0fc5..d5d6e9f56 100644 --- a/src/api/client/capabilities.rs +++ b/src/api/client/capabilities.rs @@ -46,7 +46,8 @@ pub(crate) async fn get_capabilities_route( capabilities.get_login_token = GetLoginTokenCapability::new(services.server.config.login_via_existing_session); - capabilities.forget_forced_upon_leave.enabled = true; + capabilities.forget_forced_upon_leave.enabled = + services.server.config.forget_forced_upon_leave; if services.users.is_admin(sender_user).await { capabilities.account_moderation.lock = true; From 42609eab021952e5f48f58a910bddec3db290a0b Mon Sep 17 00:00:00 2001 From: Bardi Harborow Date: Wed, 4 Nov 2026 21:26:16 +1100 Subject: [PATCH 101/342] fix: Return M_KEY_TOO_LARGE for oversize profile keys Profile keys longer than 255 bytes were rejected with 413 M_TOO_LARGE. The spec requires 400 M_KEY_TOO_LARGE, which ruma now provides. --- changelog.d/2451.bugfix.1.md | 1 + src/service/users/profile.rs | 6 +----- 2 files changed, 2 insertions(+), 5 deletions(-) create mode 100644 changelog.d/2451.bugfix.1.md diff --git a/changelog.d/2451.bugfix.1.md b/changelog.d/2451.bugfix.1.md new file mode 100644 index 000000000..c102c6bd5 --- /dev/null +++ b/changelog.d/2451.bugfix.1.md @@ -0,0 +1 @@ +Setting a profile key longer than 255 bytes now returns 400 `M_KEY_TOO_LARGE` as required by the spec, instead of 413 `M_TOO_LARGE`. diff --git a/src/service/users/profile.rs b/src/service/users/profile.rs index 954b0eac4..b2c0c3e3b 100644 --- a/src/service/users/profile.rs +++ b/src/service/users/profile.rs @@ -51,12 +51,8 @@ impl super::Service { let field_name = change.field_name(); - // TODO: The spec mentions special error codes (M_PROFILE_TOO_LARGE, - // M_KEY_TOO_LARGE) for profile field size limits, but they're not in - // its list of error codes and Ruma doesn't have them. Should we - // return those, or is M_TOO_LARGE okay? if field_name.as_str().len() > MAX_KEY_LENGTH_BYTES { - return Err!(Request(TooLarge( + return Err!(Request(KeyTooLarge( "Individual profile keys must not exceed {MAX_KEY_LENGTH_BYTES} bytes in length." ))); } From 4d0ccd998fd0e8b4eb3fe22359f9c02453cc7711 Mon Sep 17 00:00:00 2001 From: Bardi Harborow Date: Wed, 4 Nov 2026 21:26:16 +1100 Subject: [PATCH 102/342] fix: Return M_PROFILE_TOO_LARGE for oversize profiles Profile updates that would push the profile over 64 KiB were rejected with an untyped error, producing a 500. The spec requires 400 M_PROFILE_TOO_LARGE, which ruma now provides. --- changelog.d/2451.bugfix.2.md | 1 + src/service/users/profile.rs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 changelog.d/2451.bugfix.2.md diff --git a/changelog.d/2451.bugfix.2.md b/changelog.d/2451.bugfix.2.md new file mode 100644 index 000000000..49cf46a52 --- /dev/null +++ b/changelog.d/2451.bugfix.2.md @@ -0,0 +1 @@ +Setting profile data that would make the profile exceed 64 KiB now returns 400 `M_PROFILE_TOO_LARGE` as required by the spec, instead of a 500 error. diff --git a/src/service/users/profile.rs b/src/service/users/profile.rs index b2c0c3e3b..cad67765c 100644 --- a/src/service/users/profile.rs +++ b/src/service/users/profile.rs @@ -80,10 +80,10 @@ impl super::Service { .len() > MAX_PROFILE_LENGTH_BYTES { - return Err!( + return Err!(Request(ProfileTooLarge( "Profile data must not exceed {MAX_PROFILE_LENGTH_BYTES} bytes in \ length." - ); + ))); } } else { return Err!(Request(BadJson("Failed to canonicalize profile."))); From 219e8d2e1e3caa401f0cad5357719453c7698f7e Mon Sep 17 00:00:00 2001 From: Bardi Harborow Date: Wed, 4 Nov 2026 21:20:25 +1100 Subject: [PATCH 103/342] fix: Return M_UNKNOWN_DEVICE for unknown masqueraded appservice devices When an appservice masqueraded as a device_id that does not exist for the user, we returned 403 M_FORBIDDEN. The spec requires 400 M_UNKNOWN_DEVICE. --- changelog.d/2451.bugfix.3.md | 1 + src/api/router/auth.rs | 5 +---- 2 files changed, 2 insertions(+), 4 deletions(-) create mode 100644 changelog.d/2451.bugfix.3.md diff --git a/changelog.d/2451.bugfix.3.md b/changelog.d/2451.bugfix.3.md new file mode 100644 index 000000000..f75d21824 --- /dev/null +++ b/changelog.d/2451.bugfix.3.md @@ -0,0 +1 @@ +Appservices masquerading as a device that does not exist now receive 400 `M_UNKNOWN_DEVICE` as required by the spec, instead of 403 `M_FORBIDDEN`. diff --git a/src/api/router/auth.rs b/src/api/router/auth.rs index e731245df..af19fb03b 100644 --- a/src/api/router/auth.rs +++ b/src/api/router/auth.rs @@ -379,10 +379,7 @@ async fn check_access_token( .await .is_err() { - return Err!(Request(Forbidden( - "Device does not exist for user or appservice cannot masquerade as this \ - device." - ))); + return Err!(Request(UnknownDevice("Device does not exist for this user."))); } Some(device_id.to_owned()) From 223e8894596eb46aa46e5fc6a60f7c00f184ba72 Mon Sep 17 00:00:00 2001 From: Bardi Harborow Date: Wed, 4 Nov 2026 21:24:13 +1100 Subject: [PATCH 104/342] fix: Return 405 when setting m.fully_read via account data The spec requires servers to reject client writes to server-managed account data types with 405 M_BAD_JSON. We returned 400. --- changelog.d/2451.bugfix.4.md | 1 + src/api/client/account_data.rs | 11 +++++++---- 2 files changed, 8 insertions(+), 4 deletions(-) create mode 100644 changelog.d/2451.bugfix.4.md diff --git a/changelog.d/2451.bugfix.4.md b/changelog.d/2451.bugfix.4.md new file mode 100644 index 000000000..10f6a4da1 --- /dev/null +++ b/changelog.d/2451.bugfix.4.md @@ -0,0 +1 @@ +Setting `m.fully_read` via the account data endpoints now returns 405 `M_BAD_JSON` as required by the spec, instead of 400. diff --git a/src/api/client/account_data.rs b/src/api/client/account_data.rs index 60fec42ab..bc9dc4bab 100644 --- a/src/api/client/account_data.rs +++ b/src/api/client/account_data.rs @@ -117,10 +117,13 @@ async fn set_account_data( data: &RawJsonValue, ) -> Result { if event_type_s == "m.fully_read" { - return Err!(Request(BadJson( - "This endpoint cannot be used for marking a room as fully read (setting \ - m.fully_read)" - ))); + return Err!(Request( + BadJson( + "This endpoint cannot be used for marking a room as fully read (setting \ + m.fully_read)" + ), + METHOD_NOT_ALLOWED + )); } let data: serde_json::Value = serde_json::from_str(data.get()) From db86d42801695fe822f2ab25dbab420394849065 Mon Sep 17 00:00:00 2001 From: Bardi Harborow Date: Wed, 4 Nov 2026 23:16:00 +1100 Subject: [PATCH 105/342] fix: Compare push `user_is_target` against the notified user `user_is_target` was set by comparing a member event's `state_key` to its sender, rather than to the user receiving the notification. --- changelog.d/2454.bugfix.md | 1 + src/service/pusher/mod.rs | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 changelog.d/2454.bugfix.md diff --git a/changelog.d/2454.bugfix.md b/changelog.d/2454.bugfix.md new file mode 100644 index 000000000..6dfd7b5df --- /dev/null +++ b/changelog.d/2454.bugfix.md @@ -0,0 +1 @@ +Fixed push notifications for membership events setting `user_is_target` based on the sender rather than the user being notified. diff --git a/src/service/pusher/mod.rs b/src/service/pusher/mod.rs index 1dd51495a..778457f42 100644 --- a/src/service/pusher/mod.rs +++ b/src/service/pusher/mod.rs @@ -532,6 +532,7 @@ impl Service { let notify = self .build_notification( + user, pusher, &http.data, http.format.as_ref(), @@ -549,6 +550,7 @@ impl Service { | PusherKind::WebPush(data) => { let notify = self .build_notification( + user, pusher, &data.data, data.format.as_ref(), @@ -564,8 +566,10 @@ impl Service { } } + #[allow(clippy::too_many_arguments)] async fn build_notification( &self, + user: &UserId, pusher: &Pusher, data: &JsonObject, format: Option<&PushFormat>, @@ -614,7 +618,7 @@ impl Service { notify.content = serde_json::value::to_raw_value(event.content()).ok(); if *event.kind() == TimelineEventType::RoomMember { - notify.user_is_target = event.state_key() == Some(event.sender().as_str()); + notify.user_is_target = event.state_key() == Some(user.as_str()); } notify.sender_display_name = From fb389cb6f9b028a65ca2762c8057c49aa56cac0d Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Mon, 2 Nov 2026 20:07:29 +0100 Subject: [PATCH 106/342] fix: Record device list changes before syncs can read their count Signed-off-by: Erwan Leboucher --- changelog.d/+device-list-count-race.bugfix.md | 1 + src/service/globals/data.rs | 8 +++-- src/service/globals/mod.rs | 5 +++ src/service/users/keys.rs | 31 ++++++++++++------- 4 files changed, 32 insertions(+), 13 deletions(-) create mode 100644 changelog.d/+device-list-count-race.bugfix.md diff --git a/changelog.d/+device-list-count-race.bugfix.md b/changelog.d/+device-list-count-race.bugfix.md new file mode 100644 index 000000000..ef40e7e07 --- /dev/null +++ b/changelog.d/+device-list-count-race.bugfix.md @@ -0,0 +1 @@ +Fix new devices sometimes never reaching other users' device lists. Contributed by @eleboucher. diff --git a/src/service/globals/data.rs b/src/service/globals/data.rs index 07f1de5c6..ee2f7d232 100644 --- a/src/service/globals/data.rs +++ b/src/service/globals/data.rs @@ -21,7 +21,9 @@ impl Data { } } - pub fn next_count(&self) -> Result { + pub fn next_count(&self) -> Result { self.next_count_with(|_| ()) } + + pub fn next_count_with(&self, write: impl FnOnce(u64)) -> Result { let _cork = self.db.cork(); let mut lock = self.counter.write(); let counter: &mut u64 = &mut lock; @@ -30,7 +32,9 @@ impl Data { "counter mismatch" ); - *counter = counter.checked_add(1).unwrap_or(*counter); + let next = counter.checked_add(1).unwrap_or(*counter); + write(next); + *counter = next; self.global.insert(COUNTER, counter.to_be_bytes()); diff --git a/src/service/globals/mod.rs b/src/service/globals/mod.rs index 23c3f8db4..b88e99206 100644 --- a/src/service/globals/mod.rs +++ b/src/service/globals/mod.rs @@ -80,6 +80,11 @@ impl Service { #[inline] pub fn next_count(&self) -> Result { self.db.next_count() } + #[inline] + pub fn next_count_with(&self, write: impl FnOnce(u64)) -> Result { + self.db.next_count_with(write) + } + #[inline] pub fn current_count(&self) -> Result { Ok(self.db.current_count()) } diff --git a/src/service/users/keys.rs b/src/service/users/keys.rs index 2f0227d14..682bfb02b 100644 --- a/src/service/users/keys.rs +++ b/src/service/users/keys.rs @@ -442,9 +442,8 @@ impl super::Service { /// Marks that a user's device keys have been updated, so that other users /// can be notified of the change. pub async fn mark_device_key_update(&self, user_id: &UserId) { - let count = self.services.globals.next_count().unwrap(); - - self.services + let encrypted_rooms: Vec<_> = self + .services .state_cache .rooms_joined(user_id) // Don't send key updates to unencrypted rooms @@ -460,16 +459,26 @@ impl super::Service { None } }) - .for_each(async |room_id| { - let key = (&room_id, count); - self.db.keychangeid_userid.put_raw(key, user_id); - - self.services.sync.wake_all_joined(&room_id).await; - }) + .collect() .await; - let key = (user_id, count); - self.db.keychangeid_userid.put_raw(key, user_id); + self.services + .globals + .next_count_with(|count| { + self.db + .keychangeid_userid + .put_raw((user_id, count), user_id); + for room_id in &encrypted_rooms { + self.db + .keychangeid_userid + .put_raw((room_id, count), user_id); + } + }) + .unwrap(); + + for room_id in &encrypted_rooms { + self.services.sync.wake_all_joined(room_id).await; + } } /// Returns the device identity keys for a given device. From 8c720e54278321438ce7cc78d4aa04cdb4f3518e Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 4 Nov 2026 13:53:55 +0100 Subject: [PATCH 107/342] fix: Store to-device messages before syncs can read their count --- changelog.d/+to-device-count-race.bugfix.md | 1 + src/service/users/device.rs | 24 +++++++++++---------- 2 files changed, 14 insertions(+), 11 deletions(-) create mode 100644 changelog.d/+to-device-count-race.bugfix.md diff --git a/changelog.d/+to-device-count-race.bugfix.md b/changelog.d/+to-device-count-race.bugfix.md new file mode 100644 index 000000000..57b847f00 --- /dev/null +++ b/changelog.d/+to-device-count-race.bugfix.md @@ -0,0 +1 @@ +Fix to-device messages, including room keys, sometimes being lost before delivery. Contributed by @eleboucher. diff --git a/src/service/users/device.rs b/src/service/users/device.rs index 6933ea715..be666d7ca 100644 --- a/src/service/users/device.rs +++ b/src/service/users/device.rs @@ -216,17 +216,19 @@ impl super::Service { event_type: &str, content: serde_json::Value, ) { - let count = self.services.globals.next_count().unwrap(); - - let key = (target_user_id, target_device_id, count); - self.db.todeviceid_events.put( - key, - Json(json!({ - "type": event_type, - "sender": sender, - "content": content, - })), - ); + let event = Json(json!({ + "type": event_type, + "sender": sender, + "content": content, + })); + self.services + .globals + .next_count_with(|count| { + self.db + .todeviceid_events + .put((target_user_id, target_device_id, count), event); + }) + .unwrap(); self.services.sync.wake(target_user_id).await; } From b095103e236b5613c6c20e1803adb1c8bfa3cd22 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 14 Oct 2026 04:55:44 +0000 Subject: [PATCH 108/342] docs: Use `continuwuity` instead of `homeserver` for the docker service This commit replaces all references of `homeserver` to `continuwuity` The `docker-compose.yml` file also receives 2-space linting --- docs/deploying/docker.mdx | 6 +++--- docs/guides/delegation.mdx | 4 ++-- docs/guides/dns.mdx | 2 +- .../advanced/delegated.docker-compose.for-traefik.yml | 2 +- .../advanced/delegated.docker-compose.with-caddy-labels.yml | 4 ++-- .../public/advanced/delegated.docker-compose.with-caddy.yml | 2 +- .../advanced/delegated.docker-compose.with-traefik.yml | 2 +- .../calls/livekit.docker-compose.with-caddy-labels.yml | 4 ++-- docs/public/deploying/docker-compose.for-traefik.yml | 2 +- docs/public/deploying/docker-compose.override.yml | 2 +- docs/public/deploying/docker-compose.with-caddy-labels.yml | 2 +- docs/public/deploying/docker-compose.with-caddy.yml | 2 +- docs/public/deploying/docker-compose.with-traefik.yml | 2 +- 13 files changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/deploying/docker.mdx b/docs/deploying/docker.mdx index 23f5f280e..c7b105e2e 100644 --- a/docs/deploying/docker.mdx +++ b/docs/deploying/docker.mdx @@ -69,7 +69,7 @@ Docker's default DNS resolver is known to [**cause timeout issues**](../troubles ```yaml title='docker-compose.yml' services: - homeserver: + continuwuity: # ... volumes: - ./continuwuity-resolv.conf:/etc/resolv.conf @@ -95,7 +95,7 @@ Then, create a Caddyfile with the following content: ``` https://example.com:443, https://example.com:8448 { - reverse_proxy http://homeserver:8008 + reverse_proxy http://continuwuity:8008 } ``` @@ -297,7 +297,7 @@ For Docker Compose deployments this means adding `stdin_open: true` and `tty: tr ```yaml services: - homeserver: + continuwuity: stdin_open: true tty: true # ... diff --git a/docs/guides/delegation.mdx b/docs/guides/delegation.mdx index 7ce397e88..d3a379f03 100644 --- a/docs/guides/delegation.mdx +++ b/docs/guides/delegation.mdx @@ -226,10 +226,10 @@ The following Compose files are taken from [Docker deployment instructions](../d ```txt title="Caddyfile" https://matrix.example.com:443 { - reverse_proxy http://homeserver:8008 + reverse_proxy http://continuwuity:8008 } https://example.com:443 { - reverse_proxy /.well-known/matrix* http://homeserver:8008 + reverse_proxy /.well-known/matrix* http://continuwuity:8008 } ``` diff --git a/docs/guides/dns.mdx b/docs/guides/dns.mdx index cfe8995fc..6e880c114 100644 --- a/docs/guides/dns.mdx +++ b/docs/guides/dns.mdx @@ -37,7 +37,7 @@ networks: - subnet: "10.10.10.0/24" services: - homeserver: + continuwuity: # ... volume: - ./continuwuity-resolv.conf:/etc/resolv.conf:ro diff --git a/docs/public/advanced/delegated.docker-compose.for-traefik.yml b/docs/public/advanced/delegated.docker-compose.for-traefik.yml index c0e034d78..b339968a9 100644 --- a/docs/public/advanced/delegated.docker-compose.for-traefik.yml +++ b/docs/public/advanced/delegated.docker-compose.for-traefik.yml @@ -1,7 +1,7 @@ # Continuwuity - Behind Traefik Reverse Proxy services: - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit diff --git a/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml b/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml index f1509f756..9cf49aec6 100644 --- a/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml +++ b/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml @@ -16,9 +16,9 @@ services: restart: unless-stopped labels: caddy: example.com - caddy.reverse_proxy: /.well-known/matrix/* homeserver:8008 + caddy.reverse_proxy: /.well-known/matrix/* continuwuity:8008 - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit diff --git a/docs/public/advanced/delegated.docker-compose.with-caddy.yml b/docs/public/advanced/delegated.docker-compose.with-caddy.yml index 4385ed3eb..9a1178315 100644 --- a/docs/public/advanced/delegated.docker-compose.with-caddy.yml +++ b/docs/public/advanced/delegated.docker-compose.with-caddy.yml @@ -14,7 +14,7 @@ services: - ./Caddyfile:/etc/caddy/Caddyfile restart: unless-stopped - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit diff --git a/docs/public/advanced/delegated.docker-compose.with-traefik.yml b/docs/public/advanced/delegated.docker-compose.with-traefik.yml index 54aea19ec..9c9d744e0 100644 --- a/docs/public/advanced/delegated.docker-compose.with-traefik.yml +++ b/docs/public/advanced/delegated.docker-compose.with-traefik.yml @@ -1,7 +1,7 @@ # Continuwuity - With Traefik Reverse Proxy services: - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit diff --git a/docs/public/calls/livekit.docker-compose.with-caddy-labels.yml b/docs/public/calls/livekit.docker-compose.with-caddy-labels.yml index 93dd6dae5..7eb68e19e 100644 --- a/docs/public/calls/livekit.docker-compose.with-caddy-labels.yml +++ b/docs/public/calls/livekit.docker-compose.with-caddy-labels.yml @@ -37,7 +37,7 @@ services: # If you already configured `[global.well_known]` with Continuwuity, # comment out the *_respond labels and uncomment the line below: - # caddy.reverse_proxy: /.well-known/matrix/* homeserver:8008 + # caddy.reverse_proxy: /.well-known/matrix/* continuwuity:8008 # If you are having problems with continuwuity serving headers, # uncomment the header section below. @@ -48,7 +48,7 @@ services: # caddy.0_header.Access-Control-Allow-Headers: "Authorization" # caddy.0_header.Content-Type: "application/json" - homeserver: + continuwuity: image: forgejo.ellis.link/continuwuation/continuwuity:latest restart: unless-stopped # add additional environment, volume, and network config here... diff --git a/docs/public/deploying/docker-compose.for-traefik.yml b/docs/public/deploying/docker-compose.for-traefik.yml index 229a95a66..7394886a9 100644 --- a/docs/public/deploying/docker-compose.for-traefik.yml +++ b/docs/public/deploying/docker-compose.for-traefik.yml @@ -1,7 +1,7 @@ # Continuwuity - Behind Traefik Reverse Proxy services: - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit diff --git a/docs/public/deploying/docker-compose.override.yml b/docs/public/deploying/docker-compose.override.yml index 5906bb314..be1ef8522 100644 --- a/docs/public/deploying/docker-compose.override.yml +++ b/docs/public/deploying/docker-compose.override.yml @@ -1,7 +1,7 @@ # Continuwuity - Traefik Reverse Proxy Labels (override file) services: - homeserver: + continuwuity: labels: - "traefik.enable=true" - "traefik.docker.network=proxy" # Change this to the name of your Traefik docker proxy network diff --git a/docs/public/deploying/docker-compose.with-caddy-labels.yml b/docs/public/deploying/docker-compose.with-caddy-labels.yml index ab55f93ec..3099ee176 100644 --- a/docs/public/deploying/docker-compose.with-caddy-labels.yml +++ b/docs/public/deploying/docker-compose.with-caddy-labels.yml @@ -15,7 +15,7 @@ services: - ./caddy-data:/data restart: unless-stopped - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit diff --git a/docs/public/deploying/docker-compose.with-caddy.yml b/docs/public/deploying/docker-compose.with-caddy.yml index 04f827f57..3e7609e4a 100644 --- a/docs/public/deploying/docker-compose.with-caddy.yml +++ b/docs/public/deploying/docker-compose.with-caddy.yml @@ -15,7 +15,7 @@ services: - ./Caddyfile:/etc/caddy/Caddyfile restart: unless-stopped - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit diff --git a/docs/public/deploying/docker-compose.with-traefik.yml b/docs/public/deploying/docker-compose.with-traefik.yml index a45217af1..afc084300 100644 --- a/docs/public/deploying/docker-compose.with-traefik.yml +++ b/docs/public/deploying/docker-compose.with-traefik.yml @@ -1,7 +1,7 @@ # Continuwuity - With Traefik Reverse Proxy services: - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit From a57e0945eb4e56282d99bf44a14af65ea302f304 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 14 Oct 2026 04:59:32 +0000 Subject: [PATCH 109/342] chore: Add changelog for `continuwuity` --> `homeserver` --- changelog.d/+f05dfc14.doc.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/+f05dfc14.doc.md diff --git a/changelog.d/+f05dfc14.doc.md b/changelog.d/+f05dfc14.doc.md new file mode 100644 index 000000000..542314fb9 --- /dev/null +++ b/changelog.d/+f05dfc14.doc.md @@ -0,0 +1 @@ +The documentation now refers to the Continuwuity Docker service as `continuwuity` instead of `homeserver`. From 15f7aabca63d696430c8e10153e8a81b5a366c86 Mon Sep 17 00:00:00 2001 From: Bardi Harborow Date: Thu, 5 Nov 2026 02:45:34 +1100 Subject: [PATCH 110/342] fix(complement): Build with the openreg feature Since challengeless registration was gated behind the `openreg` feature, building with plain `cargo build -p conduwuit` produces a server that refuses Complement's registrations, so almost every test fails. This commit updates the testing docs and the runner's build hints to enable the feature. --- bin/complement | 4 ++-- docs/development/testing.mdx | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/bin/complement b/bin/complement index f1ac017d1..1c4281987 100755 --- a/bin/complement +++ b/bin/complement @@ -53,7 +53,7 @@ fi # The base docker image to use for complement tests # You can build the default with `docker build -t continuwuity:complement -f ./docker/complement.Dockerfile .` -# after running `cargo build`. Only the debug binary is used. +# after running `cargo build -p conduwuit --features openreg`. Only the debug binary is used. COMPLEMENT_BASE_IMAGE="${COMPLEMENT_BASE_IMAGE:-continuwuity:complement}" # Complement tests that are skipped due to flakiness/reliability issues or we don't implement such features and won't for a long time @@ -99,7 +99,7 @@ fi if ! docker image inspect "$COMPLEMENT_BASE_IMAGE" > /dev/null 2>&1; then echo "Complement base image not found: $COMPLEMENT_BASE_IMAGE" - echo "Build it with: cargo build -p conduwuit && docker build -t $COMPLEMENT_BASE_IMAGE -f docker/complement.Dockerfile ." + echo "Build it with: cargo build -p conduwuit --features openreg && docker build -t $COMPLEMENT_BASE_IMAGE -f docker/complement.Dockerfile ." exit 1 fi diff --git a/docs/development/testing.mdx b/docs/development/testing.mdx index 6a2568698..3e6aa0201 100644 --- a/docs/development/testing.mdx +++ b/docs/development/testing.mdx @@ -12,11 +12,14 @@ Install Git, Rust, Docker, Go, and `jq`. From this repository's root, build the server image and run the suite: ```bash -cargo build -p conduwuit +cargo build -p conduwuit --features openreg docker build -t continuwuity:complement -f docker/complement.Dockerfile . ./bin/complement ``` +The `openreg` feature is required: without it the server refuses the open +registrations Complement uses to create test users, and almost every test fails. + The run can take up to an hour. The runner writes the full Go test stream to `tests/test_results/complement/test_logs.jsonl` and a sorted pass/fail/skip summary to `tests/test_results/complement/test_results.jsonl`. It exits nonzero From 4a3b0366ac76c4b9080fdd90f58af42420130b4d Mon Sep 17 00:00:00 2001 From: Ginger Date: Mon, 2 Nov 2026 15:22:47 -0500 Subject: [PATCH 111/342] feat: Ratelimit CSAPI endpoints --- Cargo.lock | 1 + conduwuit-example.toml | 7 +++++++ src/api/router/args.rs | 17 ++++++++++++---- src/api/router/auth.rs | 38 +++++++++++++++++++++++++++++++++++- src/core/Cargo.toml | 1 + src/core/config/mod.rs | 44 +++++++++++++++++++++++++++++++++++++++++- 6 files changed, 102 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a41dde29b..5f2f7dfdc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1037,6 +1037,7 @@ dependencies = [ "either", "figment", "futures", + "governor", "hardened_malloc-rs", "http", "http-body-util", diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 1eab12cdb..e52fb7463 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -685,6 +685,13 @@ # env: CONTINUWUITY_SENDER_SHUTDOWN_TIMEOUT #sender_shutdown_timeout = 5 +# Maximum number of requests per minute that unauthenticated clients +# may make to ratelimited client-server API routes. This ratelimit is +# global across all endpoints for each IP. +# +# env: CONTINUWUITY_UNAUTHENTICATED_REQUEST_RATELIMIT +#unauthenticated_request_ratelimit = 30 + # Enables registration. If set to false, no users can register on this # server. # diff --git a/src/api/router/args.rs b/src/api/router/args.rs index beee4a3d0..cc18438c0 100644 --- a/src/api/router/args.rs +++ b/src/api/router/args.rs @@ -1,18 +1,21 @@ -use std::ops::Deref; +use std::{ + net::{IpAddr, Ipv4Addr}, + ops::Deref, +}; use axum::{ RequestExt, RequestPartsExt, body::Body, extract::{FromRequest, Path, Query}, }; -use conduwuit::{Error, Result, err}; +use conduwuit::{Error, Result, err, error}; use ruma::{ CanonicalJsonObject, api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme}, }; use serde::Deserialize; -use crate::{State, router::auth::CheckAuth}; +use crate::{State, client_ip::ClientIp, router::auth::CheckAuth}; /// Query parameters needed to authenticate requests #[derive(Deserialize)] @@ -87,6 +90,11 @@ where let Path(path): Path> = parts.extract().await?; let borrowed_path: Vec<_> = path.iter().map(String::as_str).collect(); let Query(auth_query): Query = parts.extract().await?; + let ClientIp(ip) = parts + .extract_with_state(services) + .await + .inspect_err(|err| error!("Failed to extract client IP: {err:?}")) + .unwrap_or(ClientIp(IpAddr::V4(Ipv4Addr::UNSPECIFIED))); // Assemble a new request from the read body and parts let request = hyper::Request::from_parts(parts, body.as_ref()); @@ -102,7 +110,8 @@ where })?; let identity = - R::Authentication::check::(services, &request, authentication, auth_query).await?; + R::Authentication::check::(services, &request, ip, authentication, auth_query) + .await?; // Deserialize the body let body = R::try_from_http_request(request, &borrowed_path) diff --git a/src/api/router/auth.rs b/src/api/router/auth.rs index af19fb03b..543910cba 100644 --- a/src/api/router/auth.rs +++ b/src/api/router/auth.rs @@ -1,6 +1,7 @@ use std::{ any::{Any, TypeId}, collections::BTreeSet, + net::IpAddr, }; use conduwuit::{ @@ -18,7 +19,10 @@ use ruma::{ AuthScheme, NoAccessToken, NoAuthentication, }, client, - error::{ErrorKind, InsufficientUserAuthenticationErrorData, UnknownTokenErrorData}, + error::{ + ErrorKind, InsufficientUserAuthenticationErrorData, LimitExceededErrorData, + UnknownTokenErrorData, + }, federation::authentication::ServerSignatures, }, assign, @@ -90,6 +94,7 @@ pub(crate) trait CheckAuth: AuthScheme { fn check + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, + request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> impl Future> + Send; @@ -101,6 +106,7 @@ impl CheckAuth for ServerSignatures { async fn check + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { @@ -161,6 +167,7 @@ impl CheckAuth for AccessToken { async fn check + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> Result { @@ -181,6 +188,7 @@ impl CheckAuth for AccessTokenOptional { async fn check + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, + request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> Result { @@ -195,6 +203,10 @@ impl CheckAuth for AccessTokenOptional { .await .map(Some) } else { + if R::RATE_LIMITED { + check_unauthenticated_request_ratelimiting(services, request_ip)?; + } + Ok(None) } } @@ -206,6 +218,7 @@ impl CheckAuth for AppserviceToken { async fn check( services: &Services, _incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { @@ -219,6 +232,7 @@ impl CheckAuth for AppserviceTokenOptional { async fn check + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { @@ -238,6 +252,7 @@ impl CheckAuth for NoAuthentication { fn check + Any>( _services: &Services, _incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, _authentication: Self::Output, _query: AuthQueryParams, ) -> impl Future> + Send { @@ -251,6 +266,7 @@ impl CheckAuth for NoAccessToken { async fn check + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, + request_ip: IpAddr, _authentication: Self::Output, query: AuthQueryParams, ) -> Result { @@ -267,6 +283,10 @@ impl CheckAuth for NoAccessToken { .await .map(Some) } else { + if R::RATE_LIMITED { + check_unauthenticated_request_ratelimiting(services, request_ip)?; + } + Ok(None) } } @@ -408,3 +428,19 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result Result<()> { + if services + .config + .unauthenticated_request_ratelimit + .check_key(&ip) + .is_err() + { + return Err(Error::BadRequest( + ErrorKind::LimitExceeded(LimitExceededErrorData::new()), + "Rate limit exceeded.", + )); + } + + Ok(()) +} diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 109535949..ca4071ae8 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -77,6 +77,7 @@ cyborgtime.workspace = true either.workspace = true figment.workspace = true futures.workspace = true +governor.workspace = true http-body-util.workspace = true http.workspace = true ipaddress.workspace = true diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index d5318c9a8..2c58cd14f 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -5,7 +5,10 @@ pub mod proxy; use std::{ collections::{BTreeMap, BTreeSet, HashMap}, + hash::Hash, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, + num::NonZero, + ops::Deref, path::PathBuf, time::Duration, }; @@ -17,6 +20,7 @@ use either::{ }; use figment::providers::{Env, Format, Toml}; pub use figment::{Figment, value::Value as FigmentValue}; +use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter}; use lettre::message::Mailbox; use openidconnect::{Audience, ClientId, ClientSecret, Scope}; use regex::RegexSet; @@ -40,7 +44,7 @@ use crate::{Result, err, error::Error, utils::sys}; /// All the config options for continuwuity. #[allow(clippy::struct_excessive_bools)] #[allow(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)] -#[derive(Clone, Debug, Deserialize)] +#[derive(Debug, Deserialize)] #[config_example_generator( filename = "conduwuit-example.toml", section = "global", @@ -790,6 +794,14 @@ pub struct Config { #[serde(default = "default_sender_shutdown_timeout")] pub sender_shutdown_timeout: u64, + /// Maximum number of requests per minute that unauthenticated clients + /// may make to ratelimited client-server API routes. This ratelimit is + /// global across all endpoints for each IP. + /// + /// default: 30 + #[serde(default = "default_unauthenticated_request_ratelimit")] + pub unauthenticated_request_ratelimit: PerMinuteRatelimiter, + /// Enables registration. If set to false, no users can register on this /// server. /// @@ -2960,6 +2972,32 @@ impl TrustedServerConfig { } } +#[derive(Debug)] +pub struct PerMinuteRatelimiter { + ratelimiter: DefaultKeyedRateLimiter, +} + +impl PerMinuteRatelimiter { + fn new(quota: Quota) -> Self { Self { ratelimiter: RateLimiter::keyed(quota) } } +} + +impl Deref for PerMinuteRatelimiter { + type Target = DefaultKeyedRateLimiter; + + fn deref(&self) -> &Self::Target { &self.ratelimiter } +} + +impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter { + fn deserialize(deserializer: D) -> std::prelude::v1::Result + where + D: serde::Deserializer<'de>, + { + let max_burst = NonZero::::deserialize(deserializer)?; + + Ok(Self::new(Quota::per_minute(max_burst))) + } +} + const DEPRECATED_KEYS: &[&str] = &[ "cache_capacity", "conduit_cache_capacity_modifier", @@ -3403,3 +3441,7 @@ fn default_preferred_username_claim() -> String { "preferred_username".to_owned( fn default_profile_key_map() -> HashMap { HashMap::from_iter([(ProfileFieldName::DisplayName.to_string(), "name".to_owned())]) } + +fn default_unauthenticated_request_ratelimit() -> PerMinuteRatelimiter { + PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap())) +} From 02aed4fb23504f54ed068c51175959c2cc71d8d0 Mon Sep 17 00:00:00 2001 From: Ginger Date: Mon, 2 Nov 2026 15:30:47 -0500 Subject: [PATCH 112/342] chore: News fragment --- changelog.d/2444.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2444.bugfix.md diff --git a/changelog.d/2444.bugfix.md b/changelog.d/2444.bugfix.md new file mode 100644 index 000000000..27d87e4d0 --- /dev/null +++ b/changelog.d/2444.bugfix.md @@ -0,0 +1 @@ +Client-server API endpoints are now properly ratelimited for unauthenticated requests. Contributed by @ginger. From c3f0d2ffa532b26f8ba718ed449bdaab1410ad5e Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 15:06:06 +0000 Subject: [PATCH 113/342] chore(deps): Upgrade rustls Closes #2472 --- Cargo.lock | 30 +++++++++++++++--------------- Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5f2f7dfdc..8c794338e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -713,9 +713,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.4.6" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" dependencies = [ "find-msvc-tools", "jobserver", @@ -734,9 +734,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" @@ -2031,7 +2031,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2106,9 +2106,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.12" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" [[package]] name = "findshlibs" @@ -4670,7 +4670,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5264,7 +5264,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5323,7 +5323,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -6797,9 +6797,9 @@ checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-segmentation" @@ -7136,7 +7136,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -7419,9 +7419,9 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.9.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zerotrie" diff --git a/Cargo.toml b/Cargo.toml index 520c9abcc..8320a8440 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -152,7 +152,7 @@ features = [ ] [workspace.dependencies.rustls] -version = "0.23.25" +version = "0.23.46" default-features = false [workspace.dependencies.reqwest] From 1af92add880e77482feff14da286e4e51d0a43f0 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 16:54:23 +0000 Subject: [PATCH 114/342] chore(deps): Upgrade rocksdb and jemalloc --- Cargo.lock | 53 +++++++++++++++++++++++------------------------------ Cargo.toml | 8 ++++---- 2 files changed, 27 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8c794338e..a04a5c998 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -500,19 +500,18 @@ dependencies = [ [[package]] name = "bindgen" -version = "0.72.1" +version = "0.73.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa" dependencies = [ "bitflags 2.13.2", "cexpr", "clang-sys", - "itertools 0.13.0", "proc-macro2", "quote", "regex", "rustc-hash", - "shlex 1.3.0", + "shlex", "syn 2.0.119", ] @@ -720,7 +719,7 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex 2.0.1", + "shlex", ] [[package]] @@ -3311,9 +3310,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libz-sys" -version = "1.1.29" +version = "1.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +checksum = "69965d2409bff8c8cea3829009fff66a86f05a0570656552ef70f616e8e4bd85" dependencies = [ "cc", "pkg-config", @@ -4229,12 +4228,6 @@ dependencies = [ "phc", ] -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - [[package]] name = "pear" version = "0.2.9" @@ -5208,8 +5201,8 @@ dependencies = [ [[package]] name = "rust-librocksdb-sys" -version = "0.45.1+11.1.1" -source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8" +version = "0.49.0+11.12.0" +source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=6021299f3e0e9455dc3f2e39c65e1dc217be8903#6021299f3e0e9455dc3f2e39c65e1dc217be8903" dependencies = [ "bindgen", "bzip2-sys", @@ -5219,14 +5212,15 @@ dependencies = [ "libz-sys", "lz4-sys", "pkg-config", + "rustflags", "tikv-jemalloc-sys", "zstd-sys", ] [[package]] name = "rust-rocksdb" -version = "0.49.1" -source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8" +version = "0.54.0" +source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=6021299f3e0e9455dc3f2e39c65e1dc217be8903#6021299f3e0e9455dc3f2e39c65e1dc217be8903" dependencies = [ "libc", "parking_lot", @@ -5254,6 +5248,12 @@ dependencies = [ "semver", ] +[[package]] +name = "rustflags" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a39e0e9135d7a7208ee80aa4e3e4b88f0f5ad7be92153ed70686c38a03db2e63" + [[package]] name = "rustix" version = "1.1.4" @@ -5858,12 +5858,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - [[package]] name = "shlex" version = "2.0.1" @@ -6219,18 +6213,17 @@ dependencies = [ [[package]] name = "tikv-jemalloc-ctl" -version = "0.6.1" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +version = "0.7.0" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=ac4d4861b335b199f812807996e8c9166961041a#ac4d4861b335b199f812807996e8c9166961041a" dependencies = [ "libc", - "paste", "tikv-jemalloc-sys", ] [[package]] name = "tikv-jemalloc-sys" -version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +version = "0.7.0+5.4.0-0-g7a34f18502e7b222724097cdcd499b437d189acc" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=ac4d4861b335b199f812807996e8c9166961041a#ac4d4861b335b199f812807996e8c9166961041a" dependencies = [ "cc", "libc", @@ -6238,8 +6231,8 @@ dependencies = [ [[package]] name = "tikv-jemallocator" -version = "0.6.1" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +version = "0.7.0" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=ac4d4861b335b199f812807996e8c9166961041a#ac4d4861b335b199f812807996e8c9166961041a" dependencies = [ "libc", "tikv-jemalloc-sys", diff --git a/Cargo.toml b/Cargo.toml index 8320a8440..df6137cb1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -395,7 +395,7 @@ features = [ [workspace.dependencies.rust-rocksdb] git = "https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1" -rev = "0a25ff92f7c09b55eec496b9c192c7d5136ab2b8" +rev = "6021299f3e0e9455dc3f2e39c65e1dc217be8903" default-features = false features = [ "multi-threaded-cf", @@ -476,7 +476,7 @@ version = "0.49.0" # jemalloc usage [workspace.dependencies.tikv-jemalloc-sys] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +rev = "ac4d4861b335b199f812807996e8c9166961041a" default-features = false features = [ "background_threads_runtime_support", @@ -484,7 +484,7 @@ features = [ ] [workspace.dependencies.tikv-jemallocator] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +rev = "ac4d4861b335b199f812807996e8c9166961041a" default-features = false features = [ "background_threads_runtime_support", @@ -492,7 +492,7 @@ features = [ ] [workspace.dependencies.tikv-jemalloc-ctl] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +rev = "ac4d4861b335b199f812807996e8c9166961041a" default-features = false features = ["use_std"] From 02f96d311b4fa1eb6e39dadba4ea2c1149ecac25 Mon Sep 17 00:00:00 2001 From: renovate Date: Sun, 8 Nov 2026 17:04:25 +0000 Subject: [PATCH 115/342] chore(Nix): Updated flake hashes --- nix/packages/rocksdb.nix | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nix/packages/rocksdb.nix b/nix/packages/rocksdb.nix index b4427dbc4..8b5076535 100644 --- a/nix/packages/rocksdb.nix +++ b/nix/packages/rocksdb.nix @@ -18,13 +18,13 @@ inherit enableJemalloc; }).overrideAttrs ({ - version = "continuwuity-v0.5.0-unstable-2026-05-19"; + version = "continuwuity-v0.5.0-unstable-2026-11-08"; src = fetchFromGitea { domain = "forgejo.ellis.link"; owner = "continuwuation"; repo = "rocksdb"; - rev = "3756b2b905e13216d8b56bcc783d814e7b073aff"; - hash = "sha256-rSv4fr2bf9JJwdodgeuPCuceeh7k97KVxrAOC0wyPQY="; + rev = "722fa3219df4169610fda8962221a1ff74026fdb"; + hash = "sha256-ZuXXp83Hgj0B5v499CNxa9oNQUS/ZKYOAZEhmarUifc="; }; # We have this already at https://forgejo.ellis.link/continuwuation/rocksdb/commit/a935c0273e1ba44eacf88ce3685a9b9831486155 From 6075e6e3adfa16f326fa4e537c50da7254e9bedb Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 17:40:13 +0000 Subject: [PATCH 116/342] chore: Upgrade other dependencies --- Cargo.lock | 1031 ++++++++++++++------------- Cargo.toml | 116 +-- src/main/Cargo.toml | 2 +- src/main/logging.rs | 10 +- src/ruminuwuity/Cargo.toml | 2 +- src/service/pusher/webpush/vapid.rs | 4 +- src/web/Cargo.toml | 4 +- xtask/Cargo.toml | 2 +- 8 files changed, 612 insertions(+), 559 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a04a5c998..85ad0f58d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "addr2line" -version = "0.25.1" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" dependencies = [ "gimli", ] @@ -23,7 +23,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ - "crypto-common 0.1.6", + "crypto-common 0.1.7", "generic-array", ] @@ -61,34 +61,19 @@ dependencies = [ "memchr", ] -[[package]] -name = "alloc-no-stdlib" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" - [[package]] name = "alloc-no-stdlib" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" -[[package]] -name = "alloc-stdlib" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" -dependencies = [ - "alloc-no-stdlib 2.0.4", -] - [[package]] name = "alloc-stdlib" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ - "alloc-no-stdlib 3.0.0", + "alloc-no-stdlib", ] [[package]] @@ -108,22 +93,22 @@ dependencies = [ [[package]] name = "annotate-snippets" -version = "0.12.16" +version = "0.12.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f211a51805bc641f3ad5b7664c77d2547af685cc33b4cd8d31964027a46f13f1" +checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176" dependencies = [ "anstyle", "memchr", - "unicode-width 0.2.2", + "unicode-width 0.2.3", ] [[package]] name = "ansi-width" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219e3ce6f2611d83b51ec2098a12702112c29e57203a6b0a0929b2cddb486608" +checksum = "90759a65f5178dbbd1b0eecc97b187996401bced0eb4a943d9ac6d7a6304d111" dependencies = [ - "unicode-width 0.1.14", + "unicode-width 0.2.3", ] [[package]] @@ -140,9 +125,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "arc-swap" -version = "1.9.2" +version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +checksum = "db4c94f57a570fce5d381be3289b3f79aef6332d72948fe82ab5772e423ccf92" dependencies = [ "rustversion", ] @@ -230,7 +215,7 @@ dependencies = [ "serde", "serde_derive", "unicode-ident", - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] @@ -252,9 +237,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.46" +version = "0.4.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f10dafd0c8d2e51ae9a748805777613ed0bbe17bf586b76c8311f45c020a32f" +checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459" dependencies = [ "compression-codecs", "compression-core", @@ -296,9 +281,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.18.2" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "zeroize", @@ -306,9 +291,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.46.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", @@ -446,14 +431,14 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.76" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" dependencies = [ "addr2line", "cfg-if", "libc", - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "object", "rustc-demangle", "windows-link", @@ -466,10 +451,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" [[package]] -name = "base64" -version = "0.21.7" +name = "base16ct" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" [[package]] name = "base64" @@ -504,7 +489,7 @@ version = "0.73.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa" dependencies = [ - "bitflags 2.13.2", + "bitflags", "cexpr", "clang-sys", "proc-macro2", @@ -512,15 +497,9 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.119", + "syn 3.0.9", ] -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - [[package]] name = "bitflags" version = "2.13.2" @@ -565,44 +544,23 @@ dependencies = [ [[package]] name = "brotli" -version = "8.0.4" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ - "alloc-no-stdlib 2.0.4", - "alloc-stdlib 0.2.4", - "brotli-decompressor 5.0.3", -] - -[[package]] -name = "brotli" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b" -dependencies = [ - "alloc-no-stdlib 3.0.0", - "alloc-stdlib 0.3.0", - "brotli-decompressor 6.0.0", + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", ] [[package]] name = "brotli-decompressor" -version = "5.0.3" +version = "6.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +checksum = "97d9071e5b45944c5a9c06baf13a7a65ffa2c88c204015967852c90869692c05" dependencies = [ - "alloc-no-stdlib 2.0.4", - "alloc-stdlib 0.2.4", -] - -[[package]] -name = "brotli-decompressor" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46087801e40b785410c352bee60e9b6226312709cf52d5fff92776cdf5cf6490" -dependencies = [ - "alloc-no-stdlib 3.0.0", - "alloc-stdlib 0.3.0", + "alloc-no-stdlib", + "alloc-stdlib", ] [[package]] @@ -668,9 +626,9 @@ dependencies = [ [[package]] name = "camino" -version = "1.2.5" +version = "1.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb1307f12aa967b5a58416e87b3653360e0fd614a016b6e970db08fecbb1b80d" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" dependencies = [ "serde_core", ] @@ -707,14 +665,14 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" dependencies = [ "semver", "serde", - "toml 1.1.8+spec-1.1.0", + "toml 1.2.1+spec-1.1.0", ] [[package]] name = "cc" -version = "1.8.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", "jobserver", @@ -783,7 +741,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common 0.1.6", + "crypto-common 0.1.7", "inout", ] @@ -832,9 +790,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" [[package]] name = "client-ip" @@ -868,9 +826,9 @@ checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -878,11 +836,11 @@ dependencies = [ [[package]] name = "compression-codecs" -version = "0.4.41" +version = "0.4.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58a6d0db8759036a783bc7c3f7a07f8cef3bf9470eb1db3bc86e8bcd1c5d0fe8" +checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43" dependencies = [ - "brotli 8.0.4", + "brotli", "compression-core", "flate2", "memchr", @@ -892,9 +850,9 @@ dependencies = [ [[package]] name = "compression-core" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" [[package]] name = "concurrent-queue" @@ -1076,7 +1034,7 @@ dependencies = [ "tikv-jemallocator", "tokio", "tokio-metrics", - "toml 1.1.8+spec-1.1.0", + "toml 1.2.1+spec-1.1.0", "tracing", "tracing-core", "tracing-subscriber", @@ -1181,7 +1139,7 @@ dependencies = [ "lru-cache", "nonzero_ext", "openidconnect", - "p256", + "p256 0.14.0", "rand 0.10.3", "regex", "reqwest 0.13.5", @@ -1373,6 +1331,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1393,9 +1357,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" dependencies = [ "cfg-if", ] @@ -1408,9 +1372,9 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" [[package]] name = "crokey" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "074bc31bff1084f74e5a145ad5f6ac74469fa312159faa5144f0b1c4506b8d80" +checksum = "c41f5f8d5dba70b6f48daa17fee79ac7c3a13cc1b164f41d0de50c803e0266f2" dependencies = [ "crokey-proc_macros", "crossterm", @@ -1421,15 +1385,15 @@ dependencies = [ [[package]] name = "crokey-proc_macros" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b88c4ff2d5717616c3bb4a31d06b0b241ed811c7c0c41d077d77631bee7caad0" +checksum = "2ca5122126412913548025b1d5574181121bcf7a06f8b530f4be713ebd81d418" dependencies = [ "crossterm", "proc-macro2", "quote", "strict", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -1494,7 +1458,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ - "bitflags 2.13.2", + "bitflags", "crossterm_winapi", "derive_more", "document-features", @@ -1529,10 +1493,26 @@ dependencies = [ ] [[package]] -name = "crypto-common" -version = "0.1.6" +name = "crypto-bigint" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", "rand_core 0.6.4", @@ -1545,7 +1525,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", ] [[package]] @@ -1569,27 +1551,12 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", -] - -[[package]] -name = "curve25519-dalek" -version = "4.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "curve25519-dalek-derive", - "digest 0.10.7", - "fiat-crypto 0.2.9", - "rustc_version", "subtle", - "zeroize", ] [[package]] @@ -1602,7 +1569,7 @@ dependencies = [ "cpufeatures 0.3.1", "curve25519-dalek-derive", "digest 0.11.3", - "fiat-crypto 0.3.0", + "fiat-crypto", "rustc_version", "subtle", "zeroize", @@ -1715,37 +1682,6 @@ dependencies = [ "uuid", ] -[[package]] -name = "defmt" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" -dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "defmt-parser" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" -dependencies = [ - "thiserror 2.0.21", -] - [[package]] name = "der" version = "0.7.10" @@ -1753,25 +1689,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "pem-rfc7468", + "pem-rfc7468 0.7.0", "zeroize", ] [[package]] name = "der" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" dependencies = [ "serde_core", ] @@ -1806,7 +1743,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "const-oid 0.9.6", - "crypto-common 0.1.6", + "crypto-common 0.1.7", "subtle", ] @@ -1828,7 +1765,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", ] @@ -1881,12 +1818,27 @@ checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ "der 0.7.10", "digest 0.10.7", - "elliptic-curve", - "rfc6979", + "elliptic-curve 0.13.8", + "rfc6979 0.4.0", "signature 2.2.0", "spki 0.7.3", ] +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der 0.8.3", + "digest 0.11.3", + "elliptic-curve 0.14.3", + "rfc6979 0.6.0", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", +] + [[package]] name = "ece-native" version = "0.5.0" @@ -1898,16 +1850,6 @@ dependencies = [ "sha2 0.10.9", ] -[[package]] -name = "ed25519" -version = "2.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" -dependencies = [ - "pkcs8 0.10.2", - "signature 2.2.0", -] - [[package]] name = "ed25519" version = "3.0.0" @@ -1918,28 +1860,14 @@ dependencies = [ "signature 3.0.0", ] -[[package]] -name = "ed25519-dalek" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" -dependencies = [ - "curve25519-dalek 4.1.3", - "ed25519 2.2.3", - "serde", - "sha2 0.10.9", - "subtle", - "zeroize", -] - [[package]] name = "ed25519-dalek" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" dependencies = [ - "curve25519-dalek 5.0.0", - "ed25519 3.0.0", + "curve25519-dalek", + "ed25519", "serde", "sha2 0.11.1", "signature 3.0.0", @@ -1962,17 +1890,38 @@ version = "0.13.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ - "base16ct", - "crypto-bigint", + "base16ct 0.2.0", + "crypto-bigint 0.5.5", "digest 0.10.7", - "ff", + "ff 0.13.1", "generic-array", - "group", + "group 0.13.0", "hkdf 0.12.4", - "pem-rfc7468", + "pem-rfc7468 0.7.0", "pkcs8 0.10.2", "rand_core 0.6.4", - "sec1", + "sec1 0.7.3", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct 1.0.0", + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sec1 0.8.1", "subtle", "zeroize", ] @@ -1995,13 +1944,12 @@ checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" [[package]] name = "encoding_rs" -version = "0.8.41" +version = "0.8.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5ef0006ac9ab233c38522f5ae99cae3625151de8f706cacee1cba4b8e2832a" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" dependencies = [ "cfg-if", "core_detect", - "multiversion", "multiversion_no_op", "rustversion", "scopeguard", @@ -2019,9 +1967,9 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" @@ -2078,10 +2026,14 @@ dependencies = [ ] [[package]] -name = "fiat-crypto" -version = "0.2.9" +name = "ff" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] [[package]] name = "fiat-crypto" @@ -2105,9 +2057,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "findshlibs" @@ -2129,9 +2081,9 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" [[package]] name = "flate2" -version = "1.1.10" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", "miniz_oxide 0.9.1", @@ -2161,9 +2113,9 @@ dependencies = [ [[package]] name = "fs-err" -version = "3.3.1" +version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91aa448ca50d7e79433bdf3ee8d99215430d2ec02ade5aefab2a073a1822e8a" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" dependencies = [ "autocfg", "tokio", @@ -2271,9 +2223,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.14.9" +version = "0.14.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", @@ -2341,9 +2293,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.32.3" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" [[package]] name = "glob" @@ -2372,9 +2324,9 @@ dependencies = [ [[package]] name = "granit-parser" -version = "1.3.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e20f99e46474f56bd905c56e817ebddcf377a611f94c53ac4649e4d3fa3c0cd0" +checksum = "05f05586d4d4df3d47123207826c40b252728b438a1a07bad3c01ee6bea401df" dependencies = [ "arraydeque", "smallvec", @@ -2386,16 +2338,27 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ - "ff", + "ff 0.13.1", "rand_core 0.6.4", "subtle", ] [[package]] -name = "h2" -version = "0.4.19" +name = "group" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2482,9 +2445,9 @@ dependencies = [ [[package]] name = "headers" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" +checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" dependencies = [ "base64 0.22.1", "bytes", @@ -2717,7 +2680,9 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] @@ -2744,9 +2709,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.9" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http", "hyper", @@ -2819,9 +2784,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -2833,9 +2798,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -2846,9 +2811,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -2860,15 +2825,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -2881,15 +2846,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -3031,18 +2996,9 @@ dependencies = [ [[package]] name = "itertools" -version = "0.10.5" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" dependencies = [ "either", ] @@ -3064,11 +3020,10 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.37" +version = "0.2.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" +checksum = "14ed8250fe4472173a765b89fea4b46f2c4aa12adc12a3e310f1dc6c108e041b" dependencies = [ - "defmt", "jiff-core", "jiff-static", "jiff-tzdb-platform", @@ -3081,19 +3036,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.1" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +checksum = "ecfc96f3a325d3a9b0ee6db9a81a83b40b94e781021c044a0a7f4c4630a1e482" dependencies = [ - "defmt", "log", ] [[package]] name = "jiff-static" -version = "0.2.37" +version = "0.2.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" +checksum = "e9522de39a5298859d9e844b660eb7d5e6fd1b63b9953f51535408a62f2d31b3" dependencies = [ "jiff-core", "proc-macro2", @@ -3103,9 +3057,9 @@ dependencies = [ [[package]] name = "jiff-tzdb" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" [[package]] name = "jiff-tzdb-platform" @@ -3177,9 +3131,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.105" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -3216,9 +3170,9 @@ dependencies = [ [[package]] name = "lazy-regex" -version = "3.6.1" +version = "3.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4994ba703f78b083e2f7946dac9251abd83fd43a0365f030e99b69be5b4b9ef9" +checksum = "f0a2cce8a22920a29fdcc8c9170aa5d29edd9fbcf8bea856e24c2cb1c2419f67" dependencies = [ "lazy-regex-proc_macros", "once_cell", @@ -3227,21 +3181,21 @@ dependencies = [ [[package]] name = "lazy-regex-proc_macros" -version = "3.6.1" +version = "3.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd97232314824e6dbef1918a871bb93f51070455e3715bf26e19a6d01aa977a0" +checksum = "6f1e4b1f1d8c71edb4ff2b2150ec4606445fd2ddf67ddc097655daf59286baa6" dependencies = [ "proc-macro2", "quote", "regex", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" dependencies = [ "spin", ] @@ -3351,9 +3305,9 @@ checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "litrs" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" [[package]] name = "lock_api" @@ -3375,9 +3329,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "loole" @@ -3471,7 +3425,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "191dc109c485eb7ee3bcab18993237be2cb290a9475debd4205ecb5f20d1f1ea" dependencies = [ "axum", - "brotli 9.0.0", + "brotli", "flate2", "fs-err", "mime_guess", @@ -3483,9 +3437,9 @@ dependencies = [ [[package]] name = "mime" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "mime_guess" @@ -3550,9 +3504,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.3" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "log", @@ -3587,27 +3541,6 @@ dependencies = [ "pxfm", ] -[[package]] -name = "multiversion" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ca4bea16ffc3f443cf7d866912118196bfef4c6a1556ca00f9f9b00bb43f7c" -dependencies = [ - "multiversion-macros", -] - -[[package]] -name = "multiversion-macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d416831a7317ef4b08bee00b69cbbb9c8763da7959a7026244d6266869f9c83" -dependencies = [ - "proc-macro2", - "quote", - "rustversion", - "syn 3.0.9", -] - [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -3632,7 +3565,7 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "cfg-if", "cfg_aliases", "libc", @@ -3805,9 +3738,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" dependencies = [ "objc2-encode", ] @@ -3818,7 +3751,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-foundation", ] @@ -3839,7 +3772,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags 2.13.2", + "bitflags", "dispatch2", "objc2", ] @@ -3850,7 +3783,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ - "bitflags 2.13.2", + "bitflags", "dispatch2", "objc2", "objc2-core-foundation", @@ -3883,7 +3816,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-core-foundation", "objc2-core-graphics", @@ -3901,7 +3834,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags 2.13.2", + "bitflags", "block2", "libc", "objc2", @@ -3914,7 +3847,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-core-foundation", ] @@ -3925,7 +3858,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-core-foundation", "objc2-foundation", @@ -3937,7 +3870,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" dependencies = [ - "bitflags 2.13.2", + "bitflags", "block2", "objc2", "objc2-cloud-kit", @@ -3964,9 +3897,9 @@ dependencies = [ [[package]] name = "object" -version = "0.37.3" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" dependencies = [ "memchr", ] @@ -3989,20 +3922,21 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "openidconnect" -version = "4.0.1" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c6709ba2ea764bbed26bce1adf3c10517113ddea6f2d4196e4851757ef2b2" +checksum = "df0d098a59353679624d406825940139e2b2d554a52b64c9fb1b1bc42a11fe5c" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "chrono", "dyn-clone", - "ed25519-dalek 2.2.0", + "ed25519-dalek", + "getrandom 0.4.3", "hmac 0.12.1", "http", - "itertools 0.10.5", + "itertools 0.14.0", "log", "oauth2", - "p256", + "p256 0.14.0", "p384", "rand 0.8.8", "rsa", @@ -4020,9 +3954,9 @@ dependencies = [ [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" [[package]] name = "opentelemetry" @@ -4169,22 +4103,37 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", "sha2 0.10.9", ] [[package]] -name = "p384" -version = "0.13.1" +name = "p256" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2 0.10.9", + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.1", +] + +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "fiat-crypto", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.1", ] [[package]] @@ -4260,6 +4209,15 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -4379,8 +4337,8 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" dependencies = [ - "der 0.8.2", - "spki 0.8.0", + "der 0.8.3", + "spki 0.8.1", ] [[package]] @@ -4395,7 +4353,7 @@ version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" dependencies = [ - "bitflags 2.13.2", + "bitflags", "crc32fast", "fdeflate", "flate2", @@ -4440,9 +4398,9 @@ dependencies = [ [[package]] name = "powerfmt" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "ppv-lite86" @@ -4470,13 +4428,40 @@ dependencies = [ "num-traits", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "primeorder" version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" dependencies = [ - "elliptic-curve", + "elliptic-curve 0.13.8", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve 0.14.3", + "once_cell", + "primefield", + "serdect", + "wnaf", ] [[package]] @@ -4485,7 +4470,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.15+spec-1.1.0", + "toml_edit 0.25.19+spec-1.1.0", ] [[package]] @@ -4563,7 +4548,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.13.0", + "itertools 0.14.0", "proc-macro2", "quote", "syn 2.0.119", @@ -4580,11 +4565,11 @@ dependencies = [ [[package]] name = "pulldown-cmark" -version = "0.13.4" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" dependencies = [ - "bitflags 2.13.2", + "bitflags", "memchr", "pulldown-cmark-escape", "unicase", @@ -4610,9 +4595,9 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" [[package]] name = "quinn" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", "cfg_aliases", @@ -4631,9 +4616,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.17" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", @@ -4654,9 +4639,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", @@ -4784,7 +4769,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.13.2", + "bitflags", ] [[package]] @@ -4954,6 +4939,16 @@ dependencies = [ "subtle", ] +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint 0.7.10", + "hmac 0.13.0", +] + [[package]] name = "ring" version = "0.17.14" @@ -5140,7 +5135,7 @@ dependencies = [ "ruma-identifiers-validation", "serde", "syn 3.0.9", - "toml 1.1.8+spec-1.1.0", + "toml 1.2.1+spec-1.1.0", ] [[package]] @@ -5161,7 +5156,7 @@ version = "0.22.1" source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" dependencies = [ "base64 0.23.1", - "ed25519-dalek 3.0.0", + "ed25519-dalek", "memchr", "pkcs8 0.11.0", "rand 0.10.3", @@ -5256,11 +5251,11 @@ checksum = "a39e0e9135d7a7208ee80aa4e3e4b88f0f5ad7be92153ed70686c38a03db2e63" [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags 2.13.2", + "bitflags", "errno", "libc", "linux-raw-sys", @@ -5285,9 +5280,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -5307,9 +5302,9 @@ dependencies = [ [[package]] name = "rustls-platform-verifier" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ "core-foundation 0.10.1", "core-foundation-sys", @@ -5328,15 +5323,15 @@ dependencies = [ [[package]] name = "rustls-platform-verifier-android" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -5390,9 +5385,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -5411,9 +5406,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", "ref-cast", @@ -5442,7 +5437,7 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ - "base16ct", + "base16ct 0.2.0", "der 0.7.10", "generic-array", "pkcs8 0.10.2", @@ -5450,13 +5445,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct 1.0.0", + "ctutils", + "der 0.8.3", + "hybrid-array", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -5485,9 +5494,9 @@ dependencies = [ [[package]] name = "sentry" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa951f4e644464ebfd2347a7ab03b0828c512d2448a76262cad2607b343dff4" +checksum = "e7c2c887f17023c9462a4202176efc33ca7228f9c30c0141c765ab534ab2d36b" dependencies = [ "cfg_aliases", "httpdate", @@ -5505,9 +5514,9 @@ dependencies = [ [[package]] name = "sentry-backtrace" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f27cf048aa63ccd5bc94c29989133eabb82e9c6bf7441b58e9d4a95837a105" +checksum = "c391d4330f3b37fdddf2b928151244e8c2dc0cfea1740e455cc8942af436f919" dependencies = [ "backtrace", "regex", @@ -5516,9 +5525,9 @@ dependencies = [ [[package]] name = "sentry-contexts" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5ed680585dbdacdf9859c2b4dc53358ff02bd256766882e22e343836db36b22" +checksum = "654dacb94135c713e1dcbff01314a83d333f0e62f76b91fed5ab87415075530c" dependencies = [ "hostname", "libc", @@ -5530,9 +5539,9 @@ dependencies = [ [[package]] name = "sentry-core" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3ed398494bb8fc412a11a182c1883a10ae147587b8f6314abd222d1d626f31b" +checksum = "edcb294ca821e5c5624edaf33535eb18b06ef4f8675201d3e4d81ce325741692" dependencies = [ "rand 0.10.3", "sentry-types", @@ -5543,9 +5552,9 @@ dependencies = [ [[package]] name = "sentry-debug-images" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55854bb40681e84ffd2a69578ad4ef9bfaf5bf2bf1380a745578b591fa24af22" +checksum = "74835055f6a57b78c0e13f941b460e39edc1899b05fe31dd47cd02367f70888f" dependencies = [ "findshlibs", "sentry-core", @@ -5553,20 +5562,20 @@ dependencies = [ [[package]] name = "sentry-log" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a3dc14009e1c24b07a8ff9ff8e1bcd0913b3e448b1565e679414776f2e58651" +checksum = "f24141aaeb20c731719b33077f1063a79e07eef63a4954530559c067ba046aad" dependencies = [ - "bitflags 2.13.2", + "bitflags", "log", "sentry-core", ] [[package]] name = "sentry-panic" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7153e68642b761ed3aa62c022795c11b2facc728b2db7484084492373c944f9" +checksum = "f5d28522f81ed90510ec43ed01cb1873a393b329dc719f93335b4c75fbef05d1" dependencies = [ "sentry-backtrace", "sentry-core", @@ -5574,9 +5583,9 @@ dependencies = [ [[package]] name = "sentry-tower" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624ee2c60caf72fa2cd6be00334b3a3ce0c6df3b1f01941ea62e3d244492d334" +checksum = "057730796d82b72f35f57e66fc41c2b9e334eb3edf5030dd18d3b1f88d062c78" dependencies = [ "http", "pin-project", @@ -5588,11 +5597,11 @@ dependencies = [ [[package]] name = "sentry-tracing" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e7db1aefdf623f4e48e21ec9e4af535024187aeafb2a4cc7e29d035def5a13" +checksum = "ec67c296aadc41d4d41b64738908c51cacddf99edebe7a2b476f9bf40de93ff5" dependencies = [ - "bitflags 2.13.2", + "bitflags", "sentry-backtrace", "sentry-core", "tracing-core", @@ -5601,9 +5610,9 @@ dependencies = [ [[package]] name = "sentry-types" -version = "0.49.3" +version = "0.49.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c18bf7b159bdfc7c8f97816f476b4947a1937fb6bea9d38d3479e58631614ac" +checksum = "83d84a36b6bdeeb7813976fb899fca45d94540d2e2b80eac91ba66b4c654d8f0" dependencies = [ "debugid", "hex", @@ -5628,9 +5637,9 @@ dependencies = [ [[package]] name = "serde-saphyr" -version = "1.3.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8050abb251097357e24aff63ba2c52a6309ecb7d23a5474023df960a02694d8" +checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe" dependencies = [ "annotate-snippets", "base64 0.23.1", @@ -5740,9 +5749,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] @@ -5761,9 +5770,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.23.0" +version = "3.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" dependencies = [ "base64 0.23.1", "bs58", @@ -5773,7 +5782,7 @@ dependencies = [ "indexmap 2.14.2", "jiff", "schemars 0.9.0", - "schemars 1.2.2", + "schemars 1.2.3", "serde_core", "serde_json", "serde_with_macros", @@ -5782,9 +5791,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.23.0" +version = "3.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d607aa01a3cb0ad757d6fd216136910db3c97b102fe686585689615a02dbcdc" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" dependencies = [ "darling 0.24.1", "proc-macro2", @@ -5792,6 +5801,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct 1.0.0", + "serde", +] + [[package]] name = "sha1" version = "0.10.7" @@ -5910,6 +5929,10 @@ name = "signature" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] [[package]] name = "simd-adler32" @@ -5935,9 +5958,9 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "siphasher" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" [[package]] name = "slab" @@ -5957,9 +5980,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.4" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] @@ -5982,9 +6005,9 @@ checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" [[package]] name = "spinning_top" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d96d2d1d716fb500937168cc09353ffdc7a012be8475ac7308e1bdf0e3923300" +checksum = "9cf02766a1eb909bc7653557c66b384e44edc3ad979e6257c6173c65ea51bc7d" dependencies = [ "lock_api 0.4.14", ] @@ -6001,12 +6024,12 @@ dependencies = [ [[package]] name = "spki" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" dependencies = [ "base64ct", - "der 0.8.2", + "der 0.8.3", ] [[package]] @@ -6091,13 +6114,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -6106,7 +6129,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags 2.13.2", + "bitflags", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -6270,9 +6293,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -6286,9 +6309,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.53.3" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -6326,9 +6349,9 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.5" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", @@ -6347,9 +6370,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.19" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", @@ -6373,17 +6396,17 @@ dependencies = [ [[package]] name = "toml" -version = "1.1.8+spec-1.1.0" +version = "1.2.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" dependencies = [ "indexmap 2.14.2", "serde_core", - "serde_spanned 1.1.2", - "toml_datetime 1.1.2+spec-1.1.0", + "serde_spanned 1.1.3", + "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", "toml_writer", - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] @@ -6397,9 +6420,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] @@ -6420,14 +6443,14 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.15+spec-1.1.0" +version = "0.25.19+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" dependencies = [ "indexmap 2.14.2", - "toml_datetime 1.1.2+spec-1.1.0", + "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] @@ -6436,7 +6459,7 @@ version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] @@ -6447,15 +6470,15 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "toml_writer" -version = "1.1.3+spec-1.1.0" +version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" [[package]] name = "tonic" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +checksum = "e2cdfc673aabd30fe8fee92e65837b644c37c5d47f0f97ae6d5e0f1237d15e1b" dependencies = [ "async-trait", "axum", @@ -6474,6 +6497,7 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-stream", + "tokio-util", "tower", "tower-layer", "tower-service", @@ -6482,9 +6506,9 @@ dependencies = [ [[package]] name = "tonic-prost" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" +checksum = "eba464054e2226f182a34489b8b079bf4c6e3e7ab5fd7fc30e024f24aa92a484" dependencies = [ "bytes", "prost", @@ -6493,9 +6517,9 @@ dependencies = [ [[package]] name = "tonic-types" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8" +checksum = "ccbb6c31deb8e99dcdf87df19c5289b7838a600da74a8224baa671e52fe7c5ad" dependencies = [ "prost", "prost-types", @@ -6544,7 +6568,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ "async-compression", - "bitflags 2.13.2", + "bitflags", "bytes", "futures-core", "futures-util", @@ -6567,7 +6591,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" dependencies = [ "async-compression", - "bitflags 2.13.2", + "bitflags", "bytes", "futures-core", "futures-util", @@ -6784,9 +6808,9 @@ dependencies = [ [[package]] name = "unicase" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" [[package]] name = "unicode-ident" @@ -6808,9 +6832,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "universal-hash" @@ -6818,7 +6842,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "crypto-common 0.1.6", + "crypto-common 0.1.7", "subtle", ] @@ -6849,15 +6873,24 @@ checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "uuid" -version = "1.26.1" +version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +checksum = "4a06f08a856b009bc7bbaf7d3e79808595d032dd19074c0c2ef26e49e03e6bdc" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -6947,12 +6980,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.128" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -6960,19 +6992,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.78" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.128" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6980,9 +7013,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.128" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", @@ -6993,9 +7026,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.128" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -7023,15 +7056,15 @@ dependencies = [ "ece-native", "hkdf 0.13.0", "http", - "p256", + "p256 0.13.2", "sha2 0.11.1", ] [[package]] name = "web-sys" -version = "0.3.105" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -7073,18 +7106,18 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" dependencies = [ "rustls-pki-types", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" dependencies = [ "rustls-pki-types", ] @@ -7301,9 +7334,9 @@ dependencies = [ [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" dependencies = [ "memchr", ] @@ -7314,6 +7347,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.4" @@ -7348,9 +7393,9 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -7359,30 +7404,30 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "synstructure", ] [[package]] name = "zerocopy" -version = "0.8.57" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.57" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -7400,13 +7445,13 @@ dependencies = [ [[package]] name = "zerofrom-derive" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "synstructure", ] @@ -7429,9 +7474,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -7440,9 +7485,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", @@ -7451,9 +7496,9 @@ dependencies = [ [[package]] name = "zlib-rs" -version = "0.6.7" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" [[package]] name = "zmij" @@ -7463,27 +7508,27 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zstd" -version = "0.14.0" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf06bd8162af0734b344780deb55b42a2429ae430870d13fcc12f238e880fe6e" +checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "8.0.0" +version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae42c0555055784c70058d19ba8e275528e8a99a706684868ace5da4e716a4ab" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.1.0+zstd.1.5.7" +version = "2.1.2+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" dependencies = [ "cc", "pkg-config", diff --git a/Cargo.toml b/Cargo.toml index df6137cb1..d3f88c3cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,11 +18,11 @@ version = "26.9.1" name = "conduwuit" [workspace.dependencies.arrayvec] -version = "0.7.6" +version = "0.7.8" features = ["serde"] [workspace.dependencies.smallvec] -version = "1.14.0" +version = "1.16.5" features = [ "const_generics", "const_new", @@ -39,10 +39,10 @@ features = ["ffi", "std", "union"] version = "1.1.0" [workspace.dependencies.ctor] -version = "1.0.6" +version = "1.0.13" [workspace.dependencies.dtor] -version = "1.0.0" +version = "1.0.6" [workspace.dependencies.cargo_toml] version = "1.0" @@ -50,7 +50,7 @@ default-features = false features = ["features"] [workspace.dependencies.toml] -version = "1.1.2" +version = "1.2.1" default-features = false features = ["parse", "serde"] @@ -58,7 +58,7 @@ features = ["parse", "serde"] version = "0.6.0" [workspace.dependencies.base64] -version = "0.23.0" +version = "0.23.1" default-features = false # used for TURN server authentication @@ -71,36 +71,36 @@ version = "0.5.0" default-features = false [workspace.dependencies.p256] -version = "0.13.2" +version = "0.14.0" default-features = false features = ["ecdsa", "std"] # used for checking if an IP is in specific subnets / CIDR ranges easier [workspace.dependencies.ipaddress] -version = "0.2.0" +version = "0.2.11" [workspace.dependencies.rand] -version = "0.10.1" +version = "0.10.3" # Used for the http request / response body type for Ruma endpoints used with reqwest [workspace.dependencies.bytes] -version = "1.10.1" +version = "1.12.1" [workspace.dependencies.http-body-util] -version = "0.1.3" +version = "0.1.5" [workspace.dependencies.http] -version = "1.3.1" +version = "1.5.0" # parses the HTTP-date form of Retry-After [workspace.dependencies.httpdate] version = "1.0.3" [workspace.dependencies.regex] -version = "1.11.1" +version = "1.13.1" [workspace.dependencies.axum] -version = "0.8.8" +version = "0.8.9" default-features = false features = [ "form", @@ -114,7 +114,7 @@ features = [ ] [workspace.dependencies.axum-extra] -version = "0.12.0" +version = "0.12.6" default-features = false features = ["typed-header", "tracing", "cookie"] @@ -133,12 +133,12 @@ default-features = false version = "0.2" [workspace.dependencies.tower] -version = "0.5.2" +version = "0.5.3" default-features = false features = ["util"] [workspace.dependencies.tower-http] -version = "0.7.0" +version = "0.7.1" default-features = false features = [ "add-extension", @@ -156,7 +156,7 @@ version = "0.23.46" default-features = false [workspace.dependencies.reqwest] -version = "0.13.2" +version = "0.13.5" default-features = false features = [ "rustls-no-provider", @@ -168,22 +168,22 @@ features = [ ] [workspace.dependencies.serde] -version = "1.0.219" +version = "1.0.229" default-features = false features = ["rc"] [workspace.dependencies.serde_json] -version = "1.0.140" +version = "1.0.154" default-features = false features = ["raw_value"] # Used for appservice registration files [workspace.dependencies.serde-saphyr] -version = "1.0.0" +version = "2.1.1" # Used to load forbidden room/user regex from config [workspace.dependencies.serde_regex] -version = "1.1.0" +version = "1.2.0" # Used for password hashing [workspace.dependencies.argon2] @@ -193,7 +193,7 @@ default-features = false # Used to generate thumbnails for images [workspace.dependencies.image] -version = "0.25.5" +version = "0.25.10" default-features = false features = [ "jpeg", @@ -204,29 +204,29 @@ features = [ # logging [workspace.dependencies.log] -version = "0.4.27" +version = "0.4.35" default-features = false [workspace.dependencies.tracing] -version = "0.1.41" +version = "0.1.44" default-features = false [workspace.dependencies.tracing-subscriber] -version = "0.3.20" +version = "0.3.23" default-features = false features = ["env-filter", "std", "tracing", "tracing-log", "ansi", "fmt"] [workspace.dependencies.tracing-journald] -version = "0.3.1" +version = "0.3.2" [workspace.dependencies.tracing-core] -version = "0.1.34" +version = "0.1.36" default-features = false # for URL previews [workspace.dependencies.webpage] -version = "2.0.1" +version = "2.1.0" default-features = false # used for conduwuit's CLI and admin room command parsing [workspace.dependencies.clap] -version = "4.5.35" +version = "4.6.7" default-features = false features = [ "derive", @@ -239,12 +239,12 @@ features = [ ] [workspace.dependencies.futures] -version = "0.3.31" +version = "0.3.34" default-features = false features = ["std", "async-await"] [workspace.dependencies.tokio] -version = "1.44.2" +version = "1.54.1" default-features = false features = [ "fs", @@ -259,25 +259,25 @@ features = [ ] [workspace.dependencies.tokio-metrics] -version = "0.5.0" +version = "0.5.2" [workspace.dependencies.libloading] version = "0.9.0" # Validating urls in config, was already a transitive dependency [workspace.dependencies.url] -version = "2.5.4" +version = "2.5.8" default-features = false features = ["serde"] # standard date and time tools [workspace.dependencies.chrono] -version = "0.4.38" +version = "0.4.45" features = ["alloc", "std"] default-features = false [workspace.dependencies.hyper] -version = "1.6.0" +version = "1.12.0" default-features = false features = [ "server", @@ -296,7 +296,7 @@ features = [ # to support multiple variations of setting a config option [workspace.dependencies.either] -version = "1.15.0" +version = "1.19.0" default-features = false features = ["serde"] @@ -307,7 +307,7 @@ default-features = false features = ["env", "toml"] [workspace.dependencies.hickory-resolver] -version = "0.26.0" +version = "0.26.3" default-features = false features = [ "serde", @@ -317,7 +317,7 @@ features = [ # Used for conduwuit::Error type [workspace.dependencies.thiserror] -version = "2.0.12" +version = "2.0.21" default-features = false # Used to make working with iterators easier, was already a transitive depdendency @@ -338,7 +338,7 @@ version = "0.6.0" version = "2.5.0" [workspace.dependencies.async-trait] -version = "0.1.88" +version = "0.1.92" [workspace.dependencies.lru-cache] version = "0.1.2" @@ -406,7 +406,7 @@ features = [ ] [workspace.dependencies.sha2] -version = "0.11.0" +version = "0.11.1" default-features = false [workspace.dependencies.sha1] @@ -414,11 +414,11 @@ version = "0.11.0" default-features = false [workspace.dependencies.openidconnect] -version = "4.0.1" +version = "4.1.0" # optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring [workspace.dependencies.opentelemetry] -version = "0.33.0" +version = "0.33.1" [workspace.dependencies.opentelemetry-instrumentation-tower] version = "0.19.0" @@ -426,7 +426,7 @@ default-features = false features = ["axum"] [workspace.dependencies.opentelemetry-semantic-conventions] -version = "0.33.0" +version = "0.33.1" features = ["semconv_experimental"] [workspace.dependencies.tracing-flame] @@ -436,25 +436,25 @@ version = "0.2.0" version = "0.34.0" [workspace.dependencies.opentelemetry_sdk] -version = "0.33.0" +version = "0.33.1" features = ["rt-tokio"] [workspace.dependencies.opentelemetry-prometheus] -version = "0.33.0" +version = "0.33.1" [workspace.dependencies.prometheus] version = "0.14.0" default-features = false [workspace.dependencies.opentelemetry-otlp] -version = "0.33.0" +version = "0.33.1" features = ["http", "grpc-tonic", "trace", "logs", "metrics"] # optional sentry metrics for crash/panic reporting [workspace.dependencies.sentry] -version = "0.49.0" +version = "0.49.5" default-features = false features = [ "backtrace", @@ -469,9 +469,9 @@ features = [ ] [workspace.dependencies.sentry-tracing] -version = "0.49.0" +version = "0.49.5" [workspace.dependencies.sentry-tower] -version = "0.49.0" +version = "0.49.5" # jemalloc usage [workspace.dependencies.tikv-jemalloc-sys] @@ -500,7 +500,7 @@ features = ["use_std"] version = "0.5" [workspace.dependencies.nix] -version = "0.31.0" +version = "0.31.3" default-features = false features = ["resource"] @@ -522,7 +522,7 @@ version = "0.4.9" default-features = false [workspace.dependencies.termimad] -version = "0.35.0" +version = "0.35.5" default-features = false [workspace.dependencies.checked_ops] @@ -548,7 +548,7 @@ features = ["hardware-lock-elision", "deadlock_detection"] # TODO: Check if dead version = "0.5.0" [workspace.dependencies.bytesize] -version = "2.0" +version = "2.7" [workspace.dependencies.core_affinity] version = "0.8.3" @@ -560,11 +560,11 @@ version = "0.2" version = "0.2" [workspace.dependencies.minicbor] -version = "2.1.1" +version = "2.3.1" features = ["std"] [workspace.dependencies.minicbor-serde] -version = "0.7.0" +version = "0.7.2" features = ["std"] [workspace.dependencies.maplit] @@ -574,10 +574,10 @@ version = "1.0.2" version = "1.0.1" [workspace.dependencies.askama] -version = "0.16.0" +version = "0.16.1" [workspace.dependencies.lettre] -version = "0.11.19" +version = "0.11.23" default-features = false features = ["smtp-transport", "pool", "hostname", "builder", "rustls", "rustls-native-certs", "tokio1", "rustls-no-provider", "tokio1-rustls", "tracing", "serde"] @@ -590,7 +590,7 @@ features = ["std"] version = "0.3.0" [workspace.dependencies.resolvematrix] -version = "1.3.0" +version = "1.4.0" [workspace.dependencies.serde_urlencoded] version = "0.7.1" diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index 3fbcbe3b4..394076898 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -245,7 +245,7 @@ tracing-journald = { workspace = true, optional = true } parking_lot.workspace = true reqwest = { workspace = true, default-features = false } rustls = { workspace = true, default-features = false } -aws-lc-rs = { version = "1.16.3", default-features = false, optional = true } +aws-lc-rs = { version = "1.19.0", default-features = false, optional = true } [target.'cfg(all(not(target_env = "msvc"), target_os = "linux"))'.dependencies] diff --git a/src/main/logging.rs b/src/main/logging.rs index c882fcb7f..8d54b1064 100644 --- a/src/main/logging.rs +++ b/src/main/logging.rs @@ -60,10 +60,18 @@ pub(crate) fn init( #[cfg(feature = "sentry_telemetry")] let subscriber = { + use tracing::Level; + use tracing_subscriber::filter::{LevelFilter, filter_fn}; + let sentry_filter = EnvFilter::try_new(&config.sentry_filter) .map_err(|e| err!(Config("sentry_filter", "{e}.")))?; - let sentry_layer = sentry_tracing::layer(); + let sentry_layer = sentry_tracing::SpanLayer::new() + .with_filter(LevelFilter::INFO) + .and_then(sentry_tracing::BreadcrumbLayer::new().with_filter(filter_fn(|metadata| { + matches!(*metadata.level(), Level::WARN | Level::INFO) + }))) + .and_then(sentry_tracing::ErrorLayer::new().with_filter(LevelFilter::ERROR)); let (sentry_reload_filter, sentry_reload_handle) = reload::Layer::new(sentry_filter); reload_handles.add("sentry", Box::new(sentry_reload_handle)); diff --git a/src/ruminuwuity/Cargo.toml b/src/ruminuwuity/Cargo.toml index 0bdcb2f90..19818776a 100644 --- a/src/ruminuwuity/Cargo.toml +++ b/src/ruminuwuity/Cargo.toml @@ -25,7 +25,7 @@ http.workspace = true ruma.workspace = true serde = { workspace = true } serde_json = { workspace = true } -wildmatch = "2.6.1" +wildmatch = "2.7.0" [dev-dependencies] diff --git a/src/service/pusher/webpush/vapid.rs b/src/service/pusher/webpush/vapid.rs index ad9a83cb7..2d7344f5b 100644 --- a/src/service/pusher/webpush/vapid.rs +++ b/src/service/pusher/webpush/vapid.rs @@ -8,7 +8,7 @@ use conduwuit_database::Database; use p256::{ SecretKey, ecdsa::{Signature, SigningKey, signature::Signer}, - elliptic_curve::sec1::ToEncodedPoint, + elliptic_curve::sec1::ToSec1Point, }; use serde_json::json; @@ -48,7 +48,7 @@ impl Vapid { }; let public_key = - URL_SAFE_NO_PAD.encode(secret.public_key().to_encoded_point(false).as_bytes()); + URL_SAFE_NO_PAD.encode(secret.public_key().to_sec1_point(false).as_bytes()); Ok(Self { secret, diff --git a/src/web/Cargo.toml b/src/web/Cargo.toml index 5cdfcd58b..6b5d6c71c 100644 --- a/src/web/Cargo.toml +++ b/src/web/Cargo.toml @@ -30,7 +30,7 @@ conduwuit-service.workspace = true form_urlencoded = "1.2.2" futures.workspace = true lettre.workspace = true -memory-serve = "2.1.0" +memory-serve = "2.4.0" openidconnect.workspace = true ruma.workspace = true serde.workspace = true @@ -48,7 +48,7 @@ url.workspace = true validator = { version = "0.21.0", features = ["derive"] } [build-dependencies] -memory-serve = "2.1.0" +memory-serve = "2.4.0" [lints] workspace = true diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index f11953fdc..8309f1937 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -13,7 +13,7 @@ version.workspace = true conduwuit-admin.workspace = true clap.workspace = true -askama = "0.16.0" +askama = "0.16.1" cargo_metadata = "0.23.1" [lints] From ce986d9c4003c7ae727d49ee66eb9b3cf6ed0427 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 17:49:03 +0000 Subject: [PATCH 117/342] docs: Changelog --- changelog.d/+4a4ebd67.misc.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/+4a4ebd67.misc.md diff --git a/changelog.d/+4a4ebd67.misc.md b/changelog.d/+4a4ebd67.misc.md new file mode 100644 index 000000000..f36da4938 --- /dev/null +++ b/changelog.d/+4a4ebd67.misc.md @@ -0,0 +1 @@ +Upgraded rocksdb from 11.1.1 to 11.12.0 and jemalloc to 5.4.0. From 1716913b1abbb3fc45525793bf6ee8398ef9b64e Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 18:19:30 +0000 Subject: [PATCH 118/342] fix(ci): Move permissions fields causing workflow warnings --- .forgejo/workflows/release-image.yml | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/.forgejo/workflows/release-image.yml b/.forgejo/workflows/release-image.yml index 6673755d2..cbf834433 100644 --- a/.forgejo/workflows/release-image.yml +++ b/.forgejo/workflows/release-image.yml @@ -27,15 +27,16 @@ env: BUILTIN_REGISTRY_ENABLED: "${{ ((vars.BUILTIN_REGISTRY_USER && secrets.BUILTIN_REGISTRY_PASSWORD) || (github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)) && 'true' || 'false' }}" IMAGE_PATH: forgejo.ellis.link/continuwuation/continuwuity +permissions: + contents: write + packages: write + attestations: write + id-token: write + jobs: build-release: name: "Build ${{ matrix.slug }} (release)" runs-on: dind - permissions: - contents: read - packages: write - attestations: write - id-token: write strategy: matrix: include: @@ -117,11 +118,6 @@ jobs: name: "Build ${{ matrix.slug }} (max-perf)" runs-on: dind needs: build-release - permissions: - contents: read - packages: write - attestations: write - id-token: write strategy: matrix: include: @@ -207,8 +203,6 @@ jobs: needs: - build-release - build-maxperf - permissions: - contents: write if: startsWith(github.ref, 'refs/tags/') steps: - name: Download binary artifacts From 7c451888aea7879220bba2b9c4c61fa12b310419 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 18:22:19 +0000 Subject: [PATCH 119/342] fix(ci): Pull base images on build to prevent using outdated base images --- .forgejo/workflows/release-image.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.forgejo/workflows/release-image.yml b/.forgejo/workflows/release-image.yml index cbf834433..6224c0f2f 100644 --- a/.forgejo/workflows/release-image.yml +++ b/.forgejo/workflows/release-image.yml @@ -85,6 +85,7 @@ jobs: outputs: | ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' && format('type=image,"name={0}",push-by-digest=true,name-canonical=true,push=true', env.IMAGE_PATH) || format('type=image,"name={0}",push=false', env.IMAGE_PATH) }} type=local,dest=/tmp/binaries + pull: true # Base images were becoming out of date env: SOURCE_DATE_EPOCH: ${{ env.TIMESTAMP }} - name: Upload Docker artifacts @@ -168,6 +169,7 @@ jobs: outputs: | ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' && format('type=image,"name={0}",push-by-digest=true,name-canonical=true,push=true', env.IMAGE_PATH) || format('type=image,"name={0}",push=false', env.IMAGE_PATH) }} type=local,dest=/tmp/binaries + pull: true # Base images were becoming out of date env: SOURCE_DATE_EPOCH: ${{ env.TIMESTAMP }} - name: Upload max-perf Docker artifacts From 15b4e8e2f9909d53121f92538ca7abb292f9735e Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Fri, 6 Nov 2026 17:24:49 -0500 Subject: [PATCH 120/342] fix: Correct relations pagination and recursion Ended up rewriting a fair bit, but should work better. --- src/api/client/relations.rs | 83 ++++----- src/core/matrix/event.rs | 7 +- src/core/matrix/event/relation.rs | 15 +- src/core/matrix/pdu/count.rs | 10 ++ .../pdu_metadata/bundled_aggregations.rs | 99 ++++------- src/service/rooms/pdu_metadata/data.rs | 62 +++---- src/service/rooms/pdu_metadata/mod.rs | 157 ++++++++++++------ 7 files changed, 232 insertions(+), 201 deletions(-) diff --git a/src/api/client/relations.rs b/src/api/client/relations.rs index 6d1bd4ffd..9a1e017dc 100644 --- a/src/api/client/relations.rs +++ b/src/api/client/relations.rs @@ -2,7 +2,7 @@ use axum::extract::State; use conduwuit::{ Err, Result, at, debug_warn, err, matrix::{Event, event::RelationTypeEqual, pdu::PduCount}, - utils::{IterStream, ReadyExt, result::FlatOk, stream::WidebandExt}, + utils::{IterStream, result::FlatOk, stream::WidebandExt}, }; use conduwuit_service::Services; use futures::StreamExt; @@ -147,28 +147,52 @@ async fn paginate_relations_with_filter( .unwrap_or(30) .min(100); - // Spec (v1.10) recommends depth of at least 3 - let depth: u8 = if recurse { 3 } else { 1 }; + // Spec (v1.10) recommends a depth of at least 3 + const RECURSION_DEPTH: u8 = 3; + const LEVELS_BELOW: u8 = RECURSION_DEPTH - 1; + let max_depth = if recurse { LEVELS_BELOW } else { 0 }; - let events: Vec<_> = services + // One more than the limit, to know whether there's another page + let mut events = services .rooms .pdu_metadata - .get_relations(sender_user, room_id, target, start, limit, depth, dir) - .await + .get_relations( + sender_user, + room_id, + target, + start, + limit.saturating_add(1), + max_depth, + dir, + |pdu| { + filter_event_type + .as_ref() + .is_none_or(|kind| kind == pdu.kind()) + && filter_rel_type + .as_ref() + .is_none_or(|rel_type| rel_type.relation_type_equal(pdu)) + }, + ) + .await; + + let past_to = to.and_then(|to| { + events + .iter() + .position(|(count, _)| !to.is_after(*count, dir)) + }); + if let Some(past_to) = past_to { + events.truncate(past_to); + } + + let has_more = past_to.is_none() && events.len() > limit; + events.truncate(limit); + + let next_batch = + has_more.then(|| events.last().map_or(start, |(count, _)| *count).to_string()); + + let chunk: Vec<_> = events .into_iter() - .filter(|(_, pdu)| { - filter_event_type - .as_ref() - .is_none_or(|kind| kind == pdu.kind()) - }) - .filter(|(_, pdu)| { - filter_rel_type - .as_ref() - .is_none_or(|rel_type| rel_type.relation_type_equal(pdu)) - }) .stream() - .ready_take_while(|(count, _)| Some(*count) != to) - .take(limit) .wide_filter_map(|item| visibility_filter(services, sender_user, item)) .wide_filter_map(|item| ignored_filter(services, item, sender_user)) .then(async |mut pdu| { @@ -182,32 +206,15 @@ async fn paginate_relations_with_filter( } pdu }) - .collect() - .await; - - // Determine if there are more events to fetch - let has_more = events.len() >= limit; - - let next_batch = if has_more { - match dir { - | Direction::Forward => events.last(), - | Direction::Backward => events.first(), - } - .map(|(count, _)| count.to_string()) - } else { - None - }; - - let chunk: Vec<_> = events - .into_iter() .map(at!(1)) .map(Event::into_format) - .collect(); + .collect() + .await; Ok(assign!(get_relating_events::v1::Response::new(chunk), { next_batch, prev_batch: from.map(Into::into), - recursion_depth: recurse.then_some(depth.into()), + recursion_depth: recurse.then_some(RECURSION_DEPTH.into()), })) } diff --git a/src/core/matrix/event.rs b/src/core/matrix/event.rs index 1b44b4ac1..18372e171 100644 --- a/src/core/matrix/event.rs +++ b/src/core/matrix/event.rs @@ -16,7 +16,12 @@ use ruma::{ use serde::Deserialize; use serde_json::{Value as JsonValue, value::RawValue as RawJsonValue}; -pub use self::{filter::Matches, id::*, relation::RelationTypeEqual, type_ext::TypeExt}; +pub use self::{ + filter::Matches, + id::*, + relation::{RelationTypeEqual, relation_type}, + type_ext::TypeExt, +}; use super::{pdu::Pdu, state_key::StateKey}; use crate::{Result, utils}; diff --git a/src/core/matrix/event/relation.rs b/src/core/matrix/event/relation.rs index 58324e863..7766433c2 100644 --- a/src/core/matrix/event/relation.rs +++ b/src/core/matrix/event/relation.rs @@ -8,7 +8,7 @@ pub trait RelationTypeEqual { } #[derive(Clone, Debug, Deserialize)] -struct ExtractRelatesToEventId { +struct ExtractRelatesToRelType { #[serde(rename = "m.relates_to")] relates_to: ExtractRelType, } @@ -18,11 +18,16 @@ struct ExtractRelType { rel_type: RelationType, } +/// The type of an event's relation, if it has one +pub fn relation_type(event: &E) -> Option { + event + .get_content() + .map(|c: ExtractRelatesToRelType| c.relates_to.rel_type) + .ok() +} + impl RelationTypeEqual for RelationType { fn relation_type_equal(&self, event: &E) -> bool { - event - .get_content() - .map(|c: ExtractRelatesToEventId| c.relates_to.rel_type) - .is_ok_and(|r| r == *self) + relation_type(event).is_some_and(|r| r == *self) } } diff --git a/src/core/matrix/pdu/count.rs b/src/core/matrix/pdu/count.rs index 7fb125745..8429db9ac 100644 --- a/src/core/matrix/pdu/count.rs +++ b/src/core/matrix/pdu/count.rs @@ -105,6 +105,16 @@ impl Count { } } + /// Whether this comes after `other` when going in the direction of `dir` + #[inline] + #[must_use] + pub fn is_after(self, other: Self, dir: Direction) -> bool { + match dir { + | Direction::Forward => self > other, + | Direction::Backward => self < other, + } + } + #[inline] #[must_use] pub fn saturating_add(self, add: u64) -> Self { diff --git a/src/service/rooms/pdu_metadata/bundled_aggregations.rs b/src/service/rooms/pdu_metadata/bundled_aggregations.rs index b6b1cb930..bc7204e8c 100644 --- a/src/service/rooms/pdu_metadata/bundled_aggregations.rs +++ b/src/service/rooms/pdu_metadata/bundled_aggregations.rs @@ -1,14 +1,16 @@ -use conduwuit::{Event, PduEvent, Result, err}; +use conduwuit::{ + Event, PduEvent, Result, err, + matrix::{PduCount, event::relation_type}, + utils::ReadyExt, +}; use ruma::{ UserId, api::Direction, - events::relation::{BundledMessageLikeRelations, BundledReference, ReferenceChunk}, + events::relation::{ + BundledMessageLikeRelations, BundledReference, ReferenceChunk, RelationType, + }, }; -use crate::rooms::timeline::PdusIterItem; - -const MAX_BUNDLED_RELATIONS: usize = 50; - impl super::Service { /// Gets bundled aggregations for an event according to the Matrix /// specification. @@ -26,52 +28,24 @@ impl super::Service { return Ok(None); } - let relations = self - .get_relations( - user_id, - &pdu.room_id_or_hash(), - pdu.event_id(), - conduwuit::PduCount::max(), - MAX_BUNDLED_RELATIONS, - 0, - Direction::Backward, - ) + let Some((room_id, target)) = self + .relation_target(&pdu.room_id_or_hash(), pdu.event_id()) + .await + else { + return Ok(None); + }; + + let mut replace_events = Vec::new(); + let mut reference_events = Vec::new(); + self.db + .get_relations(room_id, target, PduCount::max(), Direction::Backward) + .ready_for_each(|(_, relation)| match relation_type(&relation) { + | Some(RelationType::Replacement) => replace_events.push(relation), + | Some(RelationType::Reference) => reference_events.push(relation), + | _ => {}, + }) .await; - // The relations database code still handles the basic unsigned data - // We don't want to recursively fetch relations - - if relations.is_empty() { - return Ok(None); - } - - // Partition relations by type - let (replace_events, reference_events): (Vec<_>, Vec<_>) = relations - .iter() - .filter_map(|relation| { - let pdu = &relation.1; - let content = pdu.get_content_as_value(); - - content - .get("m.relates_to") - .and_then(|relates_to| relates_to.get("rel_type")) - .and_then(|rel_type| rel_type.as_str()) - .and_then(|rel_type_str| match rel_type_str { - | "m.replace" => Some(RelationType::Replace(relation)), - | "m.reference" => Some(RelationType::Reference(relation)), - | _ => None, /* Ignore other relation types (threads are in DB but not - * handled here) */ - }) - }) - .fold((Vec::new(), Vec::new()), |(mut replaces, mut references), rel_type| { - match rel_type { - | RelationType::Replace(r) => replaces.push(r), - | RelationType::Reference(r) => references.push(r), - } - (replaces, references) - }); - - // If no relations to bundle, return None if replace_events.is_empty() && reference_events.is_empty() { return Ok(None); } @@ -85,7 +59,9 @@ impl super::Service { .find_most_recent_valid_replacement(user_id, pdu, &replace_events) .await? { - bundled.replace = Some(Self::serialize_replacement(replacement)?); + bundled.replace = Some(Self::serialize_replacement( + &self.with_unsigned(user_id, replacement.clone()).await, + )?); } } @@ -93,7 +69,7 @@ impl super::Service { if !reference_events.is_empty() { let reference_chunk: Vec<_> = reference_events .into_iter() - .map(|relation| BundledReference::new(relation.1.event_id().to_owned())) + .map(|relation| BundledReference::new(relation.event_id().to_owned())) .collect(); if !reference_chunk.is_empty() { @@ -123,14 +99,12 @@ impl super::Service { &self, user_id: &UserId, original_event: &PduEvent, - replacement_events: &[&'a PdusIterItem], + replacement_events: &'a [PduEvent], ) -> Result> { // Filter valid replacements and find the maximum in a single pass let mut result: Option<&PduEvent> = None; - for relation in replacement_events { - let pdu = &relation.1; - + for pdu in replacement_events { // Validate replacement if !Self::is_valid_replacement_event(original_event, pdu).await? { continue; @@ -245,12 +219,7 @@ impl super::Service { /// Check if an event is itself a replacement #[inline] fn is_replacement_event(event: &PduEvent) -> bool { - event - .get_content_as_value() - .get("m.relates_to") - .and_then(|relates_to| relates_to.get("rel_type")) - .and_then(|rel_type| rel_type.as_str()) - .is_some_and(|rel_type| rel_type == "m.replace") + relation_type(event) == Some(RelationType::Replacement) } /// Check if event has m.new_content or is encrypted (where m.new_content @@ -262,12 +231,6 @@ impl super::Service { } } -/// Helper enum for partitioning relations -enum RelationType<'a> { - Replace(&'a PdusIterItem), - Reference(&'a PdusIterItem), -} - #[cfg(test)] mod tests { use conduwuit_core::pdu::{EventHash, PduEvent}; diff --git a/src/service/rooms/pdu_metadata/data.rs b/src/service/rooms/pdu_metadata/data.rs index 4920df5e7..d85c226cb 100644 --- a/src/service/rooms/pdu_metadata/data.rs +++ b/src/service/rooms/pdu_metadata/data.rs @@ -2,8 +2,7 @@ use std::{mem::size_of, sync::Arc}; use conduwuit::{ arrayvec::ArrayVec, - matrix::PduCount, - result::LogErr, + matrix::{PduCount, PduEvent}, utils::{ ReadyExt, stream::{TryIgnore, WidebandExt}, @@ -12,14 +11,14 @@ use conduwuit::{ }; use database::Map; use futures::{Stream, StreamExt}; -use ruma::{EventId, UserId, api::Direction}; +use ruma::{EventId, api::Direction}; use crate::{ Dep, rooms::{ self, - short::{ShortEventId, ShortRoomId}, - timeline::{PduId, PdusIterItem, RawPduId}, + short::ShortRoomId, + timeline::{PduId, RawPduId}, }, }; @@ -56,51 +55,34 @@ impl Data { pub(super) fn get_relations<'a>( &'a self, - user_id: &'a UserId, shortroomid: ShortRoomId, - target: ShortEventId, + target: u64, from: PduCount, dir: Direction, - ) -> impl Stream + Send + 'a { - // Query from exact position then filter excludes it (saturating_inc - // could skip events at min/max boundaries) - let from_unsigned = from.into_unsigned(); - let mut current = ArrayVec::::new(); - current.extend(target.to_be_bytes()); - current.extend(from_unsigned.to_be_bytes()); - let current = current.as_slice(); + ) -> impl Stream + Send + 'a { + let start_count = match from { + | PduCount::Normal(count) => count, + | PduCount::Backfilled(_) => 0, + }; + let mut start = ArrayVec::::new(); + start.extend(target.to_be_bytes()); + start.extend(start_count.to_be_bytes()); + let start = start.as_slice(); match dir { - | Direction::Forward => self.tofrom_relation.raw_keys_from(current).boxed(), - | Direction::Backward => self.tofrom_relation.rev_raw_keys_from(current).boxed(), + | Direction::Forward => self.tofrom_relation.raw_keys_from(start).boxed(), + | Direction::Backward => self.tofrom_relation.rev_raw_keys_from(start).boxed(), } .ignore_err() .ready_take_while(move |key| key.starts_with(&target.to_be_bytes())) .map(|to_from| u64_from_u8(&to_from[8..16])) - .map(PduCount::from_unsigned) - .ready_filter(move |count| { - if from == PduCount::min() || from == PduCount::max() { - true - } else { - let count_unsigned = count.into_unsigned(); - match dir { - | Direction::Forward => count_unsigned > from_unsigned, - | Direction::Backward => count_unsigned < from_unsigned, - } - } - }) - .wide_filter_map(move |shorteventid| async move { + // The scan includes `from` itself, which should be skipped + .ready_filter(move |&count| PduCount::Normal(count).is_after(from, dir)) + .wide_filter_map(move |count| async move { + let shorteventid = PduCount::Normal(count); let pdu_id: RawPduId = PduId { shortroomid, shorteventid }.into(); + let pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await.ok()?; - let mut pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await.ok()?; - - let ctx = self - .services - .timeline - .get_unsigned_context(&pdu, Some(user_id)) - .await; - pdu.set_unsigned(Some(ctx)).log_err().ok(); - - Some((shorteventid, pdu)) + Some((count, pdu)) }) } diff --git a/src/service/rooms/pdu_metadata/mod.rs b/src/service/rooms/pdu_metadata/mod.rs index 33c3d968b..2f6b11122 100644 --- a/src/service/rooms/pdu_metadata/mod.rs +++ b/src/service/rooms/pdu_metadata/mod.rs @@ -1,15 +1,20 @@ mod bundled_aggregations; mod data; -use std::sync::Arc; +use std::{collections::HashSet, sync::Arc}; -use conduwuit::{Result, matrix::PduCount}; +use conduwuit::{ + Result, + matrix::{PduCount, PduEvent}, + result::LogErr, + utils::{IterStream, ReadyExt, stream::WidebandExt}, +}; use futures::{StreamExt, future::try_join}; use ruma::{EventId, RoomId, UserId, api::Direction}; use self::data::Data; use crate::{ Dep, - rooms::{self, timeline::PdusIterItem}, + rooms::{self, short::ShortRoomId, timeline::PdusIterItem}, }; pub struct Service { @@ -51,7 +56,7 @@ impl Service { } #[allow(clippy::too_many_arguments)] - pub async fn get_relations<'a>( + pub async fn get_relations<'a, F>( &'a self, user_id: &'a UserId, room_id: &'a RoomId, @@ -60,59 +65,113 @@ impl Service { limit: usize, max_depth: u8, dir: Direction, - ) -> Vec { - let room_id = self.services.short.get_shortroomid(room_id); - - let target = self.services.timeline.get_pdu_count(target); - - let Ok((room_id, target)) = try_join(room_id, target).await else { + matches: F, + ) -> Vec + where + F: Fn(&PduEvent) -> bool + Send + Sync, + { + let Some((room_id, target)) = self.relation_target(room_id, target).await else { return Vec::new(); }; - let target = match target { - | PduCount::Normal(c) => c, - // TODO: Support backfilled relations - | _ => 0, // This will result in an empty iterator - }; - - let mut pdus: Vec<_> = self - .db - .get_relations(user_id, room_id, target, from, dir) - .collect() - .await; - - let mut stack: Vec<_> = pdus - .iter() - .filter(|_| max_depth > 0) - .map(|pdu| (pdu.clone(), 1)) - .collect(); - - 'limit: while let Some(stack_pdu) = stack.pop() { - let target = match stack_pdu.0.0 { - | PduCount::Normal(c) => c, - // TODO: Support backfilled relations - | PduCount::Backfilled(_) => 0, // This will result in an empty iterator - }; - - let relations: Vec<_> = self + // Direct relations are already in order + if max_depth == 0 { + return self .db - .get_relations(user_id, room_id, target, from, dir) + .get_relations(room_id, target, from, dir) + .ready_filter(|(_, pdu)| matches(pdu)) + .take(limit) + .wide_then(|relation| self.finish_relation(user_id, relation)) .collect() .await; - - for relation in relations { - if stack_pdu.1 < max_depth { - stack.push((relation.clone(), stack_pdu.1.saturating_add(1))); - } - - pdus.push(relation); - if pdus.len() >= limit { - break 'limit; - } - } } - pdus + let scan_from = match dir { + | Direction::Forward => PduCount::min(), + | Direction::Backward => from, + }; + + // An event can relate to two others in the tree, like a thread reply + // that also replies to another reply in the thread, so it's only kept + // and looked through the first time it's found + let mut seen = HashSet::new(); + let mut relations = Vec::new(); + let mut level: Vec<_> = self + .db + .get_relations(room_id, target, scan_from, dir) + .collect() + .await; + seen.extend(level.iter().map(|(count, _)| *count)); + for _ in 0..max_depth { + let next: Vec> = level + .iter() + .map(|(count, _)| *count) + .stream() + .wide_then(|target| { + self.db + .get_relations(room_id, target, scan_from, dir) + .collect::>() + }) + .collect() + .await; + relations.append(&mut level); + level = next + .into_iter() + .flatten() + .filter(|(count, _)| seen.insert(*count)) + .collect(); + } + relations.append(&mut level); + + relations + .retain(|(count, pdu)| PduCount::Normal(*count).is_after(from, dir) && matches(pdu)); + relations.sort_unstable_by(|(a, _), (b, _)| match dir { + | Direction::Forward => a.cmp(b), + | Direction::Backward => b.cmp(a), + }); + relations.truncate(limit); + + relations + .into_iter() + .stream() + .wide_then(|relation| self.finish_relation(user_id, relation)) + .collect() + .await + } + + /// The short room ID and count of `target` + async fn relation_target( + &self, + room_id: &RoomId, + target: &EventId, + ) -> Option<(ShortRoomId, u64)> { + let room_id = self.services.short.get_shortroomid(room_id); + let target = self.services.timeline.get_pdu_count(target); + + match try_join(room_id, target).await { + | Ok((room_id, PduCount::Normal(target))) => Some((room_id, target)), + // TODO: Support backfilled relations + | _ => None, + } + } + + async fn finish_relation( + &self, + user_id: &UserId, + (count, pdu): (u64, PduEvent), + ) -> PdusIterItem { + (PduCount::Normal(count), self.with_unsigned(user_id, pdu).await) + } + + async fn with_unsigned(&self, user_id: &UserId, mut pdu: PduEvent) -> PduEvent { + let ctx = self + .services + .timeline + .get_unsigned_context(&pdu, Some(user_id)) + .await; + pdu.set_unsigned(Some(ctx)).log_err().ok(); + + pdu } #[inline] From 2e43797d9555d806def43086f2ecdad51baab0f6 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Fri, 6 Nov 2026 17:37:36 -0500 Subject: [PATCH 121/342] chore: Make Clippy happy --- src/api/client/relations.rs | 7 ++++--- src/service/rooms/pdu_metadata/data.rs | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/api/client/relations.rs b/src/api/client/relations.rs index 9a1e017dc..1ef92898c 100644 --- a/src/api/client/relations.rs +++ b/src/api/client/relations.rs @@ -98,6 +98,10 @@ pub(crate) async fn get_relating_events_route( .await } +// Spec (v1.10) recommends a depth of at least 3 +const RECURSION_DEPTH: u8 = 3; +const LEVELS_BELOW: u8 = RECURSION_DEPTH - 1; + #[allow(clippy::too_many_arguments)] async fn paginate_relations_with_filter( services: &Services, @@ -147,9 +151,6 @@ async fn paginate_relations_with_filter( .unwrap_or(30) .min(100); - // Spec (v1.10) recommends a depth of at least 3 - const RECURSION_DEPTH: u8 = 3; - const LEVELS_BELOW: u8 = RECURSION_DEPTH - 1; let max_depth = if recurse { LEVELS_BELOW } else { 0 }; // One more than the limit, to know whether there's another page diff --git a/src/service/rooms/pdu_metadata/data.rs b/src/service/rooms/pdu_metadata/data.rs index d85c226cb..58ee0c8fe 100644 --- a/src/service/rooms/pdu_metadata/data.rs +++ b/src/service/rooms/pdu_metadata/data.rs @@ -53,13 +53,13 @@ impl Data { self.tofrom_relation.aput_raw::(key, []); } - pub(super) fn get_relations<'a>( - &'a self, + pub(super) fn get_relations( + &self, shortroomid: ShortRoomId, target: u64, from: PduCount, dir: Direction, - ) -> impl Stream + Send + 'a { + ) -> impl Stream + Send + '_ { let start_count = match from { | PduCount::Normal(count) => count, | PduCount::Backfilled(_) => 0, From 6782e122318c6653deae6f0d02ce74ef22cf4bbd Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Fri, 6 Nov 2026 19:54:47 -0500 Subject: [PATCH 122/342] chore: Add changelog to #2465 --- changelog.d/2465.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2465.bugfix.md diff --git a/changelog.d/2465.bugfix.md b/changelog.d/2465.bugfix.md new file mode 100644 index 000000000..685f054ab --- /dev/null +++ b/changelog.d/2465.bugfix.md @@ -0,0 +1 @@ +Reworked event relations to follow the spec more closely. Pagination of `/relations` now returns the correct pages and `next_batch` tokens, recursive relations are returned in the right order without duplicates, and bundled `m.reference` aggregations now include every reference. Contributed by @Henry-Hiles (QuadRadical). From 5ff6d71e7c739ede3d8972594b50d0f14dbe6f8d Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Sat, 7 Nov 2026 10:00:38 -0500 Subject: [PATCH 123/342] chore: Make walk use counts only --- src/service/rooms/pdu_metadata/data.rs | 29 ++++++++++--- src/service/rooms/pdu_metadata/mod.rs | 56 ++++++++++++++++---------- 2 files changed, 57 insertions(+), 28 deletions(-) diff --git a/src/service/rooms/pdu_metadata/data.rs b/src/service/rooms/pdu_metadata/data.rs index 58ee0c8fe..2f5cc38f7 100644 --- a/src/service/rooms/pdu_metadata/data.rs +++ b/src/service/rooms/pdu_metadata/data.rs @@ -60,6 +60,18 @@ impl Data { from: PduCount, dir: Direction, ) -> impl Stream + Send + '_ { + self.relation_counts(target, from, dir) + .wide_filter_map(move |count| self.get_relation_pdu(shortroomid, count)) + } + + /// The counts of the direct relations of `target`, in the order of `dir`, + /// starting after `from`. + pub(super) fn relation_counts( + &self, + target: u64, + from: PduCount, + dir: Direction, + ) -> impl Stream + Send + '_ { let start_count = match from { | PduCount::Normal(count) => count, | PduCount::Backfilled(_) => 0, @@ -77,13 +89,18 @@ impl Data { .map(|to_from| u64_from_u8(&to_from[8..16])) // The scan includes `from` itself, which should be skipped .ready_filter(move |&count| PduCount::Normal(count).is_after(from, dir)) - .wide_filter_map(move |count| async move { - let shorteventid = PduCount::Normal(count); - let pdu_id: RawPduId = PduId { shortroomid, shorteventid }.into(); - let pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await.ok()?; + } - Some((count, pdu)) - }) + pub(super) async fn get_relation_pdu( + &self, + shortroomid: ShortRoomId, + count: u64, + ) -> Option<(u64, PduEvent)> { + let shorteventid = PduCount::Normal(count); + let pdu_id: RawPduId = PduId { shortroomid, shorteventid }.into(); + let pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await.ok()?; + + Some((count, pdu)) } pub(super) fn mark_event_soft_failed(&self, event_id: &EventId) { diff --git a/src/service/rooms/pdu_metadata/mod.rs b/src/service/rooms/pdu_metadata/mod.rs index 2f6b11122..11d5d7568 100644 --- a/src/service/rooms/pdu_metadata/mod.rs +++ b/src/service/rooms/pdu_metadata/mod.rs @@ -8,7 +8,7 @@ use conduwuit::{ result::LogErr, utils::{IterStream, ReadyExt, stream::WidebandExt}, }; -use futures::{StreamExt, future::try_join}; +use futures::{Stream, StreamExt, future::try_join}; use ruma::{EventId, RoomId, UserId, api::Direction}; use self::data::Data; @@ -76,13 +76,9 @@ impl Service { // Direct relations are already in order if max_depth == 0 { + let counts = self.db.relation_counts(target, from, dir); return self - .db - .get_relations(room_id, target, from, dir) - .ready_filter(|(_, pdu)| matches(pdu)) - .take(limit) - .wide_then(|relation| self.finish_relation(user_id, relation)) - .collect() + .load_relations(user_id, room_id, counts, limit, &matches) .await; } @@ -95,45 +91,61 @@ impl Service { // that also replies to another reply in the thread, so it's only kept // and looked through the first time it's found let mut seen = HashSet::new(); - let mut relations = Vec::new(); + let mut counts = Vec::new(); let mut level: Vec<_> = self .db - .get_relations(room_id, target, scan_from, dir) + .relation_counts(target, scan_from, dir) .collect() .await; - seen.extend(level.iter().map(|(count, _)| *count)); + seen.extend(level.iter().copied()); for _ in 0..max_depth { let next: Vec> = level .iter() - .map(|(count, _)| *count) + .copied() .stream() .wide_then(|target| { self.db - .get_relations(room_id, target, scan_from, dir) + .relation_counts(target, scan_from, dir) .collect::>() }) .collect() .await; - relations.append(&mut level); + counts.append(&mut level); level = next .into_iter() .flatten() - .filter(|(count, _)| seen.insert(*count)) + .filter(|&count| seen.insert(count)) .collect(); } - relations.append(&mut level); + counts.append(&mut level); - relations - .retain(|(count, pdu)| PduCount::Normal(*count).is_after(from, dir) && matches(pdu)); - relations.sort_unstable_by(|(a, _), (b, _)| match dir { + counts.retain(|&count| PduCount::Normal(count).is_after(from, dir)); + counts.sort_unstable_by(|a, b| match dir { | Direction::Forward => a.cmp(b), | Direction::Backward => b.cmp(a), }); - relations.truncate(limit); - relations - .into_iter() - .stream() + self.load_relations(user_id, room_id, counts.into_iter().stream(), limit, &matches) + .await + } + + /// Loads the pdus of relations in the order of `counts` + async fn load_relations( + &self, + user_id: &UserId, + room_id: ShortRoomId, + counts: S, + limit: usize, + matches: &F, + ) -> Vec + where + S: Stream + Send, + F: Fn(&PduEvent) -> bool + Send + Sync, + { + counts + .wide_filter_map(|count| self.db.get_relation_pdu(room_id, count)) + .ready_filter(|(_, pdu)| matches(pdu)) + .take(limit) .wide_then(|relation| self.finish_relation(user_id, relation)) .collect() .await From be5ff91eb3da79941dc289391905987d201f626b Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Sun, 8 Nov 2026 14:09:56 -0500 Subject: [PATCH 124/342] chore: break out of loop when level is empty --- src/service/rooms/pdu_metadata/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/service/rooms/pdu_metadata/mod.rs b/src/service/rooms/pdu_metadata/mod.rs index 11d5d7568..6a0244cb1 100644 --- a/src/service/rooms/pdu_metadata/mod.rs +++ b/src/service/rooms/pdu_metadata/mod.rs @@ -99,6 +99,10 @@ impl Service { .await; seen.extend(level.iter().copied()); for _ in 0..max_depth { + if level.is_empty() { + break; + } + let next: Vec> = level .iter() .copied() @@ -110,6 +114,7 @@ impl Service { }) .collect() .await; + counts.append(&mut level); level = next .into_iter() From d6710a9f0063bc2e81f95b5e3506ddcae86e15b9 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sun, 8 Nov 2026 17:56:55 +0000 Subject: [PATCH 125/342] chore(deps): update dependency @rspress/plugin-sitemap to v2.1.1 --- package-lock.json | 495 +++++++++++++++++++++++++--------------------- 1 file changed, 266 insertions(+), 229 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2e62f2d1a..8f739b3f6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -125,13 +125,13 @@ } }, "node_modules/@rsbuild/core": { - "version": "2.2.11", - "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.2.11.tgz", - "integrity": "sha512-avPW0j6RaEbtV2mfl0AzTAJEimPX4Xj0pCcZyxNCrE9vkS91HmweM5V7XQj3kI5iTYfHRp9Y6To8RRHYLEvG7A==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.1.tgz", + "integrity": "sha512-dv5tL7djb8ex5z4sqnDmUbd5PnGNr/CXuFfiMD4RkUsF1JEZZkGH8lc+QW4fqYQIHM7RTvcMUakgvwVU/O9WMw==", "dev": true, "license": "MIT", "dependencies": { - "@rspack/core": "~2.2.8", + "@rspack/core": "~2.3.1", "@swc/helpers": "^0.5.23" }, "bin": { @@ -150,14 +150,14 @@ } }, "node_modules/@rsbuild/plugin-react": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@rsbuild/plugin-react/-/plugin-react-2.1.0.tgz", - "integrity": "sha512-RQTIAWB/CwPjoWt9iAl+8HixeQVgZ7kEIBrWPCixfITyHdiD84h0YpUTpEUuz6kGHw1KXT9mHZ3Rwy6WG7aRDA==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@rsbuild/plugin-react/-/plugin-react-2.1.1.tgz", + "integrity": "sha512-tLtUedsRtTLS6M4VtwzI6aakFLOFdgl9Sh1ZNBWvxb0Te3EnHrppaE7UiYEmDUXQDJ50gfr6yyirtxY5N6moyg==", "dev": true, "license": "MIT", "dependencies": { "@rspack/plugin-react-refresh": "^2.0.2", - "react-refresh": "^0.18.0" + "react-refresh": "^0.19.0" }, "peerDependencies": { "@rsbuild/core": "^2.0.0" @@ -169,32 +169,32 @@ } }, "node_modules/@rspack/binding": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.2.8.tgz", - "integrity": "sha512-c9flkSua3khHnOKBCRk8BkHGOwU9YB7niv+5JfQXiLZIvJmgKsZ7PD8QrFklMhsJT3oVAc6c9GN7/wy1YkACjA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.1.tgz", + "integrity": "sha512-pfCJGBFNK2tnNnoDP6ZoTbOjxbKr1U2eGFDJ8bIuZQai4FBNhWQlKFmNup+X5K935XYRulZBomIBAL6GL6W2YQ==", "dev": true, "license": "MIT", "optionalDependencies": { - "@rspack/binding-darwin-arm64": "2.2.8", - "@rspack/binding-darwin-x64": "2.2.8", - "@rspack/binding-linux-arm64-gnu": "2.2.8", - "@rspack/binding-linux-arm64-musl": "2.2.8", - "@rspack/binding-linux-ppc64-gnu": "2.2.8", - "@rspack/binding-linux-riscv64-gnu": "2.2.8", - "@rspack/binding-linux-riscv64-musl": "2.2.8", - "@rspack/binding-linux-s390x-gnu": "2.2.8", - "@rspack/binding-linux-x64-gnu": "2.2.8", - "@rspack/binding-linux-x64-musl": "2.2.8", - "@rspack/binding-wasm32-wasi": "2.2.8", - "@rspack/binding-win32-arm64-msvc": "2.2.8", - "@rspack/binding-win32-ia32-msvc": "2.2.8", - "@rspack/binding-win32-x64-msvc": "2.2.8" + "@rspack/binding-darwin-arm64": "2.3.1", + "@rspack/binding-darwin-x64": "2.3.1", + "@rspack/binding-linux-arm64-gnu": "2.3.1", + "@rspack/binding-linux-arm64-musl": "2.3.1", + "@rspack/binding-linux-ppc64-gnu": "2.3.1", + "@rspack/binding-linux-riscv64-gnu": "2.3.1", + "@rspack/binding-linux-riscv64-musl": "2.3.1", + "@rspack/binding-linux-s390x-gnu": "2.3.1", + "@rspack/binding-linux-x64-gnu": "2.3.1", + "@rspack/binding-linux-x64-musl": "2.3.1", + "@rspack/binding-wasm32-wasi": "2.3.1", + "@rspack/binding-win32-arm64-msvc": "2.3.1", + "@rspack/binding-win32-ia32-msvc": "2.3.1", + "@rspack/binding-win32-x64-msvc": "2.3.1" } }, "node_modules/@rspack/binding-darwin-arm64": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.2.8.tgz", - "integrity": "sha512-d6GuY/k7kJk7SOXmruIz0m+2fIXaLv2SnBHEYsbvBzE7ZO6QXq7fSABWFWNnSnNu+brYHA5Dr/skV81bXgTTCw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.1.tgz", + "integrity": "sha512-koLyL2r8PUcLD0StjuZ/n5XM6GJ0C8dzJN0IuIV9d7nQcibJxwjjSAWEPGVz6bm8WuzypvuVKNoa1+GGAHeMQA==", "cpu": [ "arm64" ], @@ -206,9 +206,9 @@ ] }, "node_modules/@rspack/binding-darwin-x64": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.2.8.tgz", - "integrity": "sha512-xCVou/jJASjEAjwy1T3hPJcJqA5QZASJfUwHqEk+nA0v44MagwH8tM8lsOvRfhzR7N2+YFac1rfZOUT8uM3awg==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.1.tgz", + "integrity": "sha512-YK39JLiu1YC6+3BMxkP7e848pHD7e2T/0OSNogDi7whfiZNg95wa9Ncd7I5ppAf0nhmV+FNew/sCBIFp5h67Jw==", "cpu": [ "x64" ], @@ -220,9 +220,9 @@ ] }, "node_modules/@rspack/binding-linux-arm64-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.2.8.tgz", - "integrity": "sha512-Zy/ss6YAQTjOWKDkcWrbKtu+pySltqT22wn68nlrWKygPWLNmMdU5anlsnwRTIuQ3MF0YJRS42ARauVtlqvRQw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.1.tgz", + "integrity": "sha512-Q+RCA/KM2tn6m6R5U4lktXDs5cCRm3SyleQk86iqqUFX7wKzVRUvr5BTsreg6K9of3gpYmQ6+g1PGT5cwo0rLA==", "cpu": [ "arm64" ], @@ -237,9 +237,9 @@ ] }, "node_modules/@rspack/binding-linux-arm64-musl": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.2.8.tgz", - "integrity": "sha512-lxgp5O8PhL3St9p82llHoNoeWzp9jltW5S9F00p00XPJZHUIuxbwfLSzn/6Wg86USEmafLoBkyD9CM8rBd3SNQ==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.1.tgz", + "integrity": "sha512-He+muVDON1fohGtdYamh3zHVwf6/E6fZu/+iEAkxjclE0P94bsCfYVcZW/a4/l1tJ2zvLZtB4jD7Qr6r4vG/WA==", "cpu": [ "arm64" ], @@ -254,9 +254,9 @@ ] }, "node_modules/@rspack/binding-linux-ppc64-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.2.8.tgz", - "integrity": "sha512-MY+YqpT02tcDCMgHy+IewQsaz7ql4mbJaAqqMlTIqvQwAUl9dXEP7BL352OgCxm9VRebTldE5lK99A3wVd3zqA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.1.tgz", + "integrity": "sha512-blIZUgyPt4FcSHkZL6sJ2xbzc7ACgDeU49An4mXLSebwdgnlhTzxeSFnh2VeJDlGza8CUaZYB/zS/6oZ2kCDcw==", "cpu": [ "ppc64" ], @@ -271,9 +271,9 @@ ] }, "node_modules/@rspack/binding-linux-riscv64-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.2.8.tgz", - "integrity": "sha512-wmN9OigSGNGCKY+AOYaWI8LJcIi8qvs5KjueBueCKOnTV6MPIEujA75QZH1pehTTYKvdGv7r2EtUXUmWpn7/SQ==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.1.tgz", + "integrity": "sha512-3FtW2DUFmXxhBORUA3zSc+ot4d6R/1/U6z/48TDN4jeIYDUG9VqYBF6LUohX4vBY6IP0DCyXb2N9WayD/9QXoA==", "cpu": [ "riscv64" ], @@ -288,9 +288,9 @@ ] }, "node_modules/@rspack/binding-linux-riscv64-musl": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.2.8.tgz", - "integrity": "sha512-ZcQMYR10hLh581zs9MFnFFn0F7wyt5fkDffyukeMHJEoPJrbkfl6cQtsUdpQnZ+mYGYS5KydD1DT9/eMH65jjw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.1.tgz", + "integrity": "sha512-+5qNgdNdXzp/K8f8BjgJ3m7tcbBKPENN7WPDfBcSHvWb5GF4+o/pbrX26c0+LEugo0bYUOAoitBNd94AwcNvpA==", "cpu": [ "riscv64" ], @@ -305,9 +305,9 @@ ] }, "node_modules/@rspack/binding-linux-s390x-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.2.8.tgz", - "integrity": "sha512-ahBiE+Ir1FMYvStYicihhSJlS2YRagxtry0jWH8zW287o7C0eiHJ+pteJHHC15T5RJqm0j6w5TuwYe+F9AYxxg==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.1.tgz", + "integrity": "sha512-yNcg/y1+MV0wZ984CVU4d1HAYYwMcDPXoQO0xynU+K5YuBxPWALHOxuRRCKCcykBdL1GIEshAIewEFrsW/cmJg==", "cpu": [ "s390x" ], @@ -322,9 +322,9 @@ ] }, "node_modules/@rspack/binding-linux-x64-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.2.8.tgz", - "integrity": "sha512-dncEI515NoPXh3zzWk06Rb3mhSV76myiFKqXiJ8K4fVAe5x/RlweMhvPhHhm7RnIMeBld7BeStzOqj38XFsWGA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.1.tgz", + "integrity": "sha512-ffclKBuH8wwimOBd6xGUxrBfVKKY5Ow4E7OFdHZeg4xffm2O8auGszmOgvFu1eoDoOYHaVJn+cEV6UD0KwZk8A==", "cpu": [ "x64" ], @@ -339,9 +339,9 @@ ] }, "node_modules/@rspack/binding-linux-x64-musl": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.2.8.tgz", - "integrity": "sha512-pfFyU03PjD0GaQG8zOQOHwq51rrJZetXjTGpMmz7iA1hq/f9lChJsDWrC8/7VXeQLwBofLZlOODqe8OM8OBzgA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.1.tgz", + "integrity": "sha512-qcDwwuyxR7TMtrW+r5Y9RIW25boXd1Ip/9jz04jhdq/OiU/Am7rCP2X90CH8sWdzovIF9UNmsGjY4KklR0F2Mg==", "cpu": [ "x64" ], @@ -356,9 +356,9 @@ ] }, "node_modules/@rspack/binding-wasm32-wasi": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.2.8.tgz", - "integrity": "sha512-3mOJuZTrF56jOh/GD9chLMJKbzPZ6Ty2OIML7+lLz0Yk2XS/xWRfLn85Dmnkb/O6UF65x7+p8VPAIZlBtLTclw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.1.tgz", + "integrity": "sha512-3dr6zjFaCK3A920ftCriSJkiRhEfhHtat7LtBdj6g0mcV5Rt+iealmli0vjeAvD0UdpE1u8EKWlfw82JLgFLSQ==", "cpu": [ "wasm32" ], @@ -372,9 +372,9 @@ } }, "node_modules/@rspack/binding-win32-arm64-msvc": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.2.8.tgz", - "integrity": "sha512-Cu/RMZT/16s+67xhl6X1pswetL3GLSQl+LnugKRh08Ul21A/tR7vxC4g4aih4u9k5SXCAngxFUt8zAjKnHIBqA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.1.tgz", + "integrity": "sha512-AZbuLPylt1xvWssN93AsirbYs3WgfcrA8tMsqHmVJIHahLu9E+JPKZ3Gmsw6IYEZk3EfnV3ujQzeQ1/VfF0Vsw==", "cpu": [ "arm64" ], @@ -386,9 +386,9 @@ ] }, "node_modules/@rspack/binding-win32-ia32-msvc": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.2.8.tgz", - "integrity": "sha512-H/erd6di8OapZhhM0raA/7XduPn9jusfLMeO1XF+AmF9WF3HzHgMjha1j+KwtPgQnaH69w6AhY+G2472VIwQmw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.1.tgz", + "integrity": "sha512-R5NVU68TePZcgRdYUzrQX9YFNxmcyXZEPwaPv40AAgsqNyacG3iRaYVmV79jt3rWYfa0QJaqvRLUchDe2SZ6zQ==", "cpu": [ "ia32" ], @@ -400,9 +400,9 @@ ] }, "node_modules/@rspack/binding-win32-x64-msvc": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.2.8.tgz", - "integrity": "sha512-BziHSUlIQM0MliCqdcHuBXSkQGtPoHQTXJce7fsgnTAzQFgPeog92qTNezYI4IrQ7pQouyiVJ2HPieUbVPRKQQ==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.1.tgz", + "integrity": "sha512-5T9DYjNPQpLbrNXjCssGd2B6xMQPlc3LxVOKHGUA1O0GV+88vBkTXAcryJ+Fo+yVEMPCzp4VvwBMGAVDpCjcSA==", "cpu": [ "x64" ], @@ -414,13 +414,13 @@ ] }, "node_modules/@rspack/core": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.2.8.tgz", - "integrity": "sha512-JugsVrnbMGNYzMH++7gR9enygpP/lAo9PbVRq3XmJg0ryIvCpST0XJjBcccaSjYaaPamsjrddihmgVLMFp+yXw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.1.tgz", + "integrity": "sha512-9BWfaiEJLgLK9U53Q4WVruBZ19Mu/XWHXHEu0UFla4lUtH8Z+/ET2m044tiqbtyIgqQyG58fMrxHeVIAiXMXHg==", "dev": true, "license": "MIT", "dependencies": { - "@rspack/binding": "2.2.8" + "@rspack/binding": "2.3.1" }, "engines": { "node": "^20.19.0 || >=22.12.0" @@ -455,40 +455,41 @@ } }, "node_modules/@rspress/core": { - "version": "2.0.23", - "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.0.23.tgz", - "integrity": "sha512-two8zdTxN9iJBSyiFXwRLLDXz/yLY2+4ycz8wHjJYzeeuFi/EN2eqsKw1nSpY7sxEGIssY1X74c6017JJUBTyA==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.1.tgz", + "integrity": "sha512-GArybZxyifQ/wC8N2SzVyFi5JCJpUXgajITV4if8ylOImjZr8j9Cgy+6o55tXEtq85r6XYYE5fbcEz2nxxCpnA==", "dev": true, "license": "MIT", "dependencies": { "@mdx-js/mdx": "^3.1.1", "@mdx-js/react": "^3.1.1", - "@rsbuild/core": "^2.2.10", - "@rsbuild/plugin-react": "~2.1.0", - "@rspress/shared": "2.0.23", + "@rsbuild/core": "^2.2.14", + "@rsbuild/plugin-react": "~2.1.1", + "@rspress/shared": "2.1.1", "@shikijs/rehype": "^4.2.0", + "@shikijs/transformers": "^4.2.0", "@types/mdast": "^4.0.4", - "@types/react": "^19.2.18", + "@types/react": "^19.3.0", "@unhead/react": "^2.1.17", "body-scroll-lock": "4.0.0-beta.0", "clsx": "2.1.1", "copy-to-clipboard": "^3.3.3", "flexsearch": "0.8.212", "hast-util-heading-rank": "^3.0.0", - "hast-util-to-jsx-runtime": "^2.3.6", + "hast-util-to-jsx-runtime": "^2.3.7", "mdast-util-mdx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.1", - "medium-zoom": "1.1.0", + "medium-zoom": "1.1.2", "nprogress": "^0.2.0", - "react": "^19.2.8", - "react-dom": "^19.2.8", + "react": "^19.3.1", + "react-dom": "^19.3.1", "react-lazy-with-preload": "^2.2.1", "react-render-to-markdown": "19.1.0", - "react-router-dom": "^7.18.4", + "react-router-dom": "^7.18.5", "rehype-external-links": "^3.0.0", "rehype-raw": "^7.0.0", - "remark-cjk-friendly": "^2.3.1", - "remark-cjk-friendly-gfm-strikethrough": "^2.3.1", + "remark-cjk-friendly": "^2.3.3", + "remark-cjk-friendly-gfm-strikethrough": "^2.3.2", "remark-gfm": "^4.0.1", "remark-mdx": "^3.1.1", "remark-parse": "^11.0.0", @@ -521,58 +522,58 @@ } }, "node_modules/@rspress/plugin-sitemap": { - "version": "2.0.23", - "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.0.23.tgz", - "integrity": "sha512-r37TvCP2wuQX8JbA7hHti8JXhVx4HiaJPn702NgFhGyolGJYIUTRQCO2/ixiP1FZJuxZ4c0yb4ZyNeDa9ZPMlw==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.1.tgz", + "integrity": "sha512-3Zk+dmitcx5QxiSPi1Wh4exexRnKa09Yyj3710x6UM4sW2cl72SctMZapO7X9ETNrgVt9fW52eQsFzW1y38gSg==", "dev": true, "license": "MIT", "engines": { "node": "^20.19.0 || >=22.12.0" }, "peerDependencies": { - "@rspress/core": "^2.0.10" + "@rspress/core": "^2.1.0-beta.2" } }, "node_modules/@rspress/shared": { - "version": "2.0.23", - "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.0.23.tgz", - "integrity": "sha512-kE2GXRCQ7GAl2wll1JBWRHEkZICKcWv3V86m8TkjiWb0eEdjACl3kns7j00KTq4UbE35kUPOs+0Lx8vGqK7q9w==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.1.tgz", + "integrity": "sha512-U+OEPt/Ze+ryJdLHvpJJv9hxiRp03rknn5pvhh6v0enjib9SuUrsku/cPzneal3EsNyDZB5kncghpH1iwVKxnA==", "dev": true, "license": "MIT", "dependencies": { - "@rsbuild/core": "^2.2.10", + "@rsbuild/core": "^2.2.14", "@shikijs/rehype": "^4.2.0", - "@types/react": "^19.2.18", + "@types/react": "^19.3.0", "mdast-util-mdx-jsx": "^3.2.0", "unified": "^11.0.5" } }, "node_modules/@shikijs/core": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.4.3.tgz", - "integrity": "sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.6.0.tgz", + "integrity": "sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/primitive": "4.4.3", - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/primitive": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5", - "hast-util-to-html": "^9.0.5" + "hast-util-to-html": "^9.0.6" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/engine-javascript": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.4.3.tgz", - "integrity": "sha512-FbOjFJp9VLdo1Wevs10BBtVxiTWwNLqZh5Gkhjgda/ioL15YOgeSl9n+6XMa3qRlPQzfhFNe641SrynFHYG0nQ==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.6.0.tgz", + "integrity": "sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "oniguruma-to-es": "^4.3.6" }, "engines": { @@ -580,41 +581,41 @@ } }, "node_modules/@shikijs/engine-oniguruma": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.4.3.tgz", - "integrity": "sha512-EcOQkxdxGQrc1Row/cC2c96/v1dbZqGnEVu1qTuT/MJmp6+cXCvQussowVmCv5Tqr3KuY3c7IbM6HTW3LJ1k9w==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.6.0.tgz", + "integrity": "sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2" + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/langs": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.4.3.tgz", - "integrity": "sha512-ePic0yfAJGOF83D5wBHK/00EjK65oahBYxFk5epgq33WRv7X9UuxLEV8PtR0szC0z8dl7INIpIodB99JRFlR+A==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.6.0.tgz", + "integrity": "sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3" + "@shikijs/types": "4.6.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/primitive": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.4.3.tgz", - "integrity": "sha512-m0wBeLDQDeIxRdUmrCPdQqfuUamDwRL5isCfYbguKD6NiaKpVbsv+3J81DyIKgNW5h4WAIIr8T4EkgQrBBxvaQ==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.6.0.tgz", + "integrity": "sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -622,44 +623,58 @@ } }, "node_modules/@shikijs/rehype": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/rehype/-/rehype-4.4.3.tgz", - "integrity": "sha512-vkG9jG1aRnrx05R31uAOKQHE8qpY7r1cBXE2sAZgFK2IaPnQHwaP4L1C6amQixmZ8thBsKwfbSsYxMDoo46UWQ==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/rehype/-/rehype-4.6.0.tgz", + "integrity": "sha512-qv3mGfYJuy+TW6UUyC2QrYSEmTxJNGXZ/NmCEsyH0NHfJIOYGvpWm0kNu6P2Ec14jmGwwTfVLMta/FZtY+MrJQ==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3", + "@shikijs/types": "4.6.0", "@types/hast": "^3.0.5", "hast-util-to-string": "^3.0.1", - "shiki": "4.4.3", + "shiki": "4.6.0", "unified": "^11.0.5", - "unist-util-visit": "^5.1.0" + "unist-util-visit": "^5.2.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/themes": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.4.3.tgz", - "integrity": "sha512-w8UHjeUnIR965KMWJHUPXOc2mNJUnK3vpVLYLvw5IYU2mnTTJ89E24OrJDBNiJDQ0qzb0tc4l7mrIXx5cFeIyw==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.6.0.tgz", + "integrity": "sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3" + "@shikijs/types": "4.6.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/transformers": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-4.6.0.tgz", + "integrity": "sha512-oZ28gYlPOYspv6AD74lCb14AAJugSY/+nJxRWjH42yDbdLAdftVU/PP36tOhb435Sfop2UGWcRGXY7HLLveKCg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "4.6.0", + "@shikijs/types": "4.6.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/types": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.4.3.tgz", - "integrity": "sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.6.0.tgz", + "integrity": "sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -667,21 +682,18 @@ } }, "node_modules/@shikijs/vscode-textmate": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", - "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz", + "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==", "dev": true, "license": "MIT" }, "node_modules/@swc/helpers": { - "version": "0.5.23", - "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", - "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz", + "integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==", "dev": true, - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.8.0" - } + "license": "Apache-2.0" }, "node_modules/@tybys/wasm-util": { "version": "0.10.4", @@ -1562,9 +1574,9 @@ "license": "Apache-2.0" }, "node_modules/get-east-asian-width": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", - "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", "dev": true, "license": "MIT", "engines": { @@ -1693,9 +1705,9 @@ } }, "node_modules/hast-util-to-html": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", - "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.6.tgz", + "integrity": "sha512-1SZUxCN3TtJAE7e2BQN2MBHsoZ1gnmi9GoCP5Di59CSWptIezSAW09yDZyVbanb78V9eCwrKqdQsjtfVTxYHWA==", "dev": true, "license": "MIT", "dependencies": { @@ -1717,9 +1729,9 @@ } }, "node_modules/hast-util-to-jsx-runtime": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", - "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==", + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.7.tgz", + "integrity": "sha512-F7DNV2NMcTxA4GqPVHnXzX+mpoPHAIY9rJAVH3CZ1FdBZOcBUEjUuvMkMpHVs/sicEtznh9tMGj5WUR9S4E2rg==", "dev": true, "license": "MIT", "dependencies": { @@ -1735,7 +1747,7 @@ "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", - "style-to-js": "^1.0.0", + "style-to-object": "^2.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" }, @@ -1744,6 +1756,23 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-to-jsx-runtime/node_modules/inline-style-parser": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.9.tgz", + "integrity": "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/hast-util-to-jsx-runtime/node_modules/style-to-object": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-2.0.2.tgz", + "integrity": "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inline-style-parser": "0.2.9" + } + }, "node_modules/hast-util-to-parse5": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/hast-util-to-parse5/-/hast-util-to-parse5-8.0.1.tgz", @@ -2043,9 +2072,9 @@ } }, "node_modules/mdast-util-gfm-strikethrough": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz", - "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.1.tgz", + "integrity": "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw==", "dev": true, "license": "MIT", "dependencies": { @@ -2212,9 +2241,9 @@ } }, "node_modules/mdast-util-to-markdown": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz", - "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==", + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.2.3.tgz", + "integrity": "sha512-dImdB6VZRMRac1SwAW6o1c0ESk/7pFFAMCMuKM+9v7LpTSthMM5nzXpqKw4Mjo66aXVKhNkyrP4bMB9MurPyWg==", "dev": true, "license": "MIT", "dependencies": { @@ -2223,8 +2252,10 @@ "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", + "micromark-util-character": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" }, @@ -2234,15 +2265,17 @@ } }, "node_modules/mdast-util-to-markdown-cjk-friendly": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly/-/mdast-util-to-markdown-cjk-friendly-1.0.0.tgz", - "integrity": "sha512-BoaAm8mlJ+LAYz0Qs532Y3ciTuQYgBUPZcSFbvC/ZKmEMAKgulw84YvQK1gI34t/vL2euSfuaWlqczkTBgamkw==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly/-/mdast-util-to-markdown-cjk-friendly-1.0.2.tgz", + "integrity": "sha512-1HCuZwTxQX3WfaNFk8PDb/VW8Ulvzn+nHD+W79Q9k5NXUSkGXH9Zv3eMJ4VI7GjZIz4Ff7WbruEFgMUaPmRJ8g==", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-to-markdown": "^2.1.2", + "mdast-util-to-markdown": "^2.1.3", "micromark-extension-cjk-friendly-util": "3.0.1", - "micromark-util-symbol": "^2.0.1" + "micromark-util-character": "^2.1.1", + "micromark-util-classify-character": "^2.0.1", + "micromark-util-html-tag-name": "^2.0.1" }, "engines": { "node": ">=18" @@ -2257,16 +2290,15 @@ } }, "node_modules/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough/-/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-1.0.0.tgz", - "integrity": "sha512-1ePVfB4P/vz3xSsm6H3D32r6VYGErxclnuLLFK02/2ReF+UdEKm7caulK6Vm0LBIp5gPRtB2Z1OYDznCkX3k2w==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough/-/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-1.0.2.tgz", + "integrity": "sha512-aidUweNq42Mok1p6KTJG7m0Ds0+njX3Sp6shhh3/VhwIkyWdn2SqEzkeiwJsK+Ksz0pL6vZUHrVFgFtyX9NMYg==", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-gfm-strikethrough": "^2.0.0", - "mdast-util-to-markdown": "^2.1.2", - "micromark-extension-cjk-friendly-util": "3.0.1", - "micromark-util-symbol": "^2.0.1" + "mdast-util-gfm-strikethrough": "^2.0.1", + "mdast-util-to-markdown": "^2.1.3", + "mdast-util-to-markdown-cjk-friendly": "1.0.2" }, "engines": { "node": ">=18" @@ -2295,11 +2327,15 @@ } }, "node_modules/medium-zoom": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/medium-zoom/-/medium-zoom-1.1.0.tgz", - "integrity": "sha512-ewyDsp7k4InCUp3jRmwHBRFGyjBimKps/AJLjRSox+2q/2H4p/PNpQf+pwONWlJiOudkBXtbdmVbFjqyybfTmQ==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/medium-zoom/-/medium-zoom-1.1.2.tgz", + "integrity": "sha512-0wTqeCQ4NGzjPghi7i2lMI6RyGj9N60fGvzY9HiNcxDTcvOw7S+ri7K3xVkrIZ+2uzUg4w/KSVMDdZXYMtHkdw==", "dev": true, - "license": "MIT" + "license": "MIT", + "workspaces": [ + "website", + "examples/*" + ] }, "node_modules/micromark": { "version": "4.0.2", @@ -2373,9 +2409,9 @@ } }, "node_modules/micromark-extension-cjk-friendly": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-extension-cjk-friendly/-/micromark-extension-cjk-friendly-2.0.1.tgz", - "integrity": "sha512-OkzoYVTL1ChbvQ8Cc1ayTIz7paFQz8iS9oIYmewncweUSwmWR+hkJF9spJ1lxB90XldJl26A1F4IkPOKS3bDXw==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-cjk-friendly/-/micromark-extension-cjk-friendly-2.0.2.tgz", + "integrity": "sha512-/BqZNCkDWg3Hj9zEEcRitZ5uMF3X78qmBFuP17oAjnVDZ0+H1GHiDKMJZDpJsXasCHEn/kzl6QHozUiWgCHtPQ==", "dev": true, "license": "MIT", "dependencies": { @@ -3212,9 +3248,9 @@ } }, "node_modules/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", - "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", "dev": true, "license": "MIT", "engines": { @@ -3222,16 +3258,16 @@ } }, "node_modules/react-dom": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", - "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", "dev": true, "license": "MIT", "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { - "react": "^19.3.0" + "react": "^19.3.1" } }, "node_modules/react-lazy-with-preload": { @@ -3265,9 +3301,9 @@ "license": "MIT" }, "node_modules/react-refresh": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz", - "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==", + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.19.0.tgz", + "integrity": "sha512-5HdstYgoJBbBofjapO5qCPcovECJCBfvjLb+iTcsmqDFVMRdqy0qs7iiInBJTUXmIFc2bjoc5b2HVLp2zRtYhQ==", "dev": true, "license": "MIT", "engines": { @@ -3288,9 +3324,9 @@ } }, "node_modules/react-router": { - "version": "7.18.4", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.4.tgz", - "integrity": "sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==", + "version": "7.18.5", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.5.tgz", + "integrity": "sha512-dTgvcXDOrLPrlLHrcZAqWveiK1hMSqN+rGAJzegP8HtmNkfRxOoshGWBNX3ZJ0cZjOHkRdlUJtaIhZMLLyGyPw==", "dev": true, "license": "MIT", "dependencies": { @@ -3311,13 +3347,13 @@ } }, "node_modules/react-router-dom": { - "version": "7.18.4", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.4.tgz", - "integrity": "sha512-yrfmJHIpDG7taCpqKjT1G5B6q3O2K+RN8/fgNf0lTjCwiPbQ0ei6vXX9ZjQR+7ld8Tr7Z5xmyMnZ8YJrphWQUw==", + "version": "7.18.5", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.5.tgz", + "integrity": "sha512-9HcfDMU6JJ/fp6gJZYGwNE6RknVGS4kBjH1HkNw959mCJi70TVwdipQWv2FEol9uGpi+SZTFtVpJPtEQfayeOw==", "dev": true, "license": "MIT", "dependencies": { - "react-router": "7.18.4" + "react-router": "7.18.5" }, "engines": { "node": ">=20.0.0" @@ -3477,14 +3513,14 @@ } }, "node_modules/remark-cjk-friendly": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.3.1.tgz", - "integrity": "sha512-f+pKZRxCRwNEGFBKNRAZAqU91GIK1SAo3ZyFHWRUgC9zcxRR0BXKd6YwqgSsxtW0rNpUDtONj7H5nje2WL3fcA==", + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.3.4.tgz", + "integrity": "sha512-xhBzjXkumeN5tKXXg6k/THSCZCP6AYV6+wSxnCsPTkxHt60bb9Yk0IWhdD87CFaDCiTqd86LKHtVObcJTmgcow==", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-to-markdown-cjk-friendly": "1.0.0", - "micromark-extension-cjk-friendly": "2.0.1" + "mdast-util-to-markdown-cjk-friendly": "1.0.2", + "micromark-extension-cjk-friendly": "2.0.2" }, "engines": { "node": ">=18" @@ -3500,13 +3536,13 @@ } }, "node_modules/remark-cjk-friendly-gfm-strikethrough": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/remark-cjk-friendly-gfm-strikethrough/-/remark-cjk-friendly-gfm-strikethrough-2.3.1.tgz", - "integrity": "sha512-JE3TGgouk/sy92SemNMEUhO5mNP4on04cmzOV3s3R5Dbk160ewmpM4tgPiinKKvoJ5UW2fTu7FOYsjVbusSA9w==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/remark-cjk-friendly-gfm-strikethrough/-/remark-cjk-friendly-gfm-strikethrough-2.3.3.tgz", + "integrity": "sha512-UBujdRd1TTgr79iPdXhCnB9ag7kaM54FBCzTa/jLCNfZFGPyZCZb8G6yoCA0k4M3HTKDvilIVKvPxU6K/05dDw==", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-to-markdown-cjk-friendly-gfm-strikethrough": "1.0.0", + "mdast-util-to-markdown-cjk-friendly-gfm-strikethrough": "1.0.2", "micromark-extension-cjk-friendly-gfm-strikethrough": "2.0.1" }, "engines": { @@ -3625,26 +3661,26 @@ } }, "node_modules/set-cookie-parser": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", - "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.3.tgz", + "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==", "dev": true, "license": "MIT" }, "node_modules/shiki": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.4.3.tgz", - "integrity": "sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.6.0.tgz", + "integrity": "sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/core": "4.4.3", - "@shikijs/engine-javascript": "4.4.3", - "@shikijs/engine-oniguruma": "4.4.3", - "@shikijs/langs": "4.4.3", - "@shikijs/themes": "4.4.3", - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/core": "4.6.0", + "@shikijs/engine-javascript": "4.6.0", + "@shikijs/engine-oniguruma": "4.6.0", + "@shikijs/langs": "4.6.0", + "@shikijs/themes": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -3737,11 +3773,12 @@ } }, "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "dev": true, - "license": "0BSD" + "license": "0BSD", + "optional": true }, "node_modules/typescript": { "version": "7.0.2", @@ -3868,15 +3905,15 @@ } }, "node_modules/unist-util-visit": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", - "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.2.0.tgz", + "integrity": "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ==", "dev": true, "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" + "unist-util-visit-parents": "^6.1.0" }, "funding": { "type": "opencollective", @@ -3898,9 +3935,9 @@ } }, "node_modules/unist-util-visit-parents": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", - "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==", "dev": true, "license": "MIT", "dependencies": { From bfabac095ff3bb9bb329acc21cce5ed1d8bf5f77 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Thu, 5 Nov 2026 05:03:01 +0000 Subject: [PATCH 126/342] chore(deps): update pre-commit hook crate-ci/committed to v1.1.12 --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1e74825c4..cc4bdf6c7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -32,7 +32,7 @@ repos: stages: [ commit-msg ] - repo: https://github.com/crate-ci/committed - rev: v1.1.11 + rev: v1.1.12 hooks: - id: committed From 2edd61062ce1bd62c119d7d4adcab2b0b638121a Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 4 Nov 2026 05:13:52 +0000 Subject: [PATCH 127/342] chore(deps): pin dependencies --- .forgejo/actions/sccache/action.yml | 2 +- .forgejo/actions/setup-llvm-with-apt/action.yml | 2 +- .forgejo/actions/setup-rust/action.yml | 4 ++-- .forgejo/workflows/build-debian.yml | 2 +- .forgejo/workflows/documentation.yml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.forgejo/actions/sccache/action.yml b/.forgejo/actions/sccache/action.yml index fd22591ae..3e0fbd540 100644 --- a/.forgejo/actions/sccache/action.yml +++ b/.forgejo/actions/sccache/action.yml @@ -7,7 +7,7 @@ runs: using: composite steps: - name: Install sccache - uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@b5ae5b4541ed5fb0f616e3cb616bf213fefa1c40 # v1 - name: Configure sccache uses: https://github.com/actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: diff --git a/.forgejo/actions/setup-llvm-with-apt/action.yml b/.forgejo/actions/setup-llvm-with-apt/action.yml index 213f3abb1..4deec4493 100644 --- a/.forgejo/actions/setup-llvm-with-apt/action.yml +++ b/.forgejo/actions/setup-llvm-with-apt/action.yml @@ -29,7 +29,7 @@ runs: steps: - name: Detect runner OS id: runner-os - uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@d39555789fed25b8eb8e086d9f199c514dfa311e # v1 - name: Configure cross-compilation architecture if: inputs.dpkg-arch != '' diff --git a/.forgejo/actions/setup-rust/action.yml b/.forgejo/actions/setup-rust/action.yml index 52126179c..a6d3988a5 100644 --- a/.forgejo/actions/setup-rust/action.yml +++ b/.forgejo/actions/setup-rust/action.yml @@ -39,7 +39,7 @@ runs: steps: - name: Detect runner OS id: runner-os - uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@d39555789fed25b8eb8e086d9f199c514dfa311e # v1 - name: Configure Cargo environment shell: bash @@ -147,7 +147,7 @@ runs: run: echo "::group::📦 Restoring build cache" - name: Setup sccache - uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@b5ae5b4541ed5fb0f616e3cb616bf213fefa1c40 # v1 - name: End build cache restore group shell: bash diff --git a/.forgejo/workflows/build-debian.yml b/.forgejo/workflows/build-debian.yml index 20a4a5955..15440b653 100644 --- a/.forgejo/workflows/build-debian.yml +++ b/.forgejo/workflows/build-debian.yml @@ -60,7 +60,7 @@ jobs: cargo-debian-${{ steps.debian-version.outputs.distribution }}-${{ matrix.arch }}- - name: Setup sccache - uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@b5ae5b4541ed5fb0f616e3cb616bf213fefa1c40 # v1 - name: Configure sccache environment run: | diff --git a/.forgejo/workflows/documentation.yml b/.forgejo/workflows/documentation.yml index aed562591..141551007 100644 --- a/.forgejo/workflows/documentation.yml +++ b/.forgejo/workflows/documentation.yml @@ -28,7 +28,7 @@ jobs: - name: Detect runner environment id: runner-env - uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@d39555789fed25b8eb8e086d9f199c514dfa311e # v1 - name: Setup Node.js if: steps.runner-env.outputs.node_major == '' || steps.runner-env.outputs.node_major < '20' From fcde5634daccee7dd698719a9d3cb0e14802bfcb Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sun, 1 Nov 2026 05:17:19 +0000 Subject: [PATCH 128/342] chore(deps): update dependency cargo-bins/cargo-binstall to v1.26.2 --- docker/Dockerfile | 2 +- docker/musl.Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 3f5b99ff6..30bad14a9 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -50,7 +50,7 @@ EOF # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.26.1 +ENV BINSTALL_VERSION=1.26.2 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree diff --git a/docker/musl.Dockerfile b/docker/musl.Dockerfile index a4f2978f6..143857898 100644 --- a/docker/musl.Dockerfile +++ b/docker/musl.Dockerfile @@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \ # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.26.1 +ENV BINSTALL_VERSION=1.26.2 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree From f4f0a69fe4ef78521fc23b987091f7ae41ad1d10 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sun, 8 Nov 2026 17:59:46 +0000 Subject: [PATCH 129/342] chore(deps): lock file maintenance --- Cargo.lock | 12 +-- flake.lock | 48 +++++------ package-lock.json | 197 ++++++++++++++++++++++++++++------------------ 3 files changed, 149 insertions(+), 108 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 85ad0f58d..4d54203ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3020,9 +3020,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.40" +version = "0.2.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14ed8250fe4472173a765b89fea4b46f2c4aa12adc12a3e310f1dc6c108e041b" +checksum = "fcefdcefac59ac8f8401852e3427d55610481fc41e6625c39bac62d2d771623a" dependencies = [ "jiff-core", "jiff-static", @@ -3036,18 +3036,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecfc96f3a325d3a9b0ee6db9a81a83b40b94e781021c044a0a7f4c4630a1e482" +checksum = "77a24020db0ee88d1c681d677681bd31f9f4ea189a455425223d52ce4f1508aa" dependencies = [ "log", ] [[package]] name = "jiff-static" -version = "0.2.40" +version = "0.2.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9522de39a5298859d9e844b660eb7d5e6fd1b63b9953f51535408a62f2d31b3" +checksum = "203edf9b0ce4083ec8fbf4adc823eac89768ea994b4953fc0dab1b90083234dd" dependencies = [ "jiff-core", "proc-macro2", diff --git a/flake.lock b/flake.lock index b7f225738..5834dcd97 100644 --- a/flake.lock +++ b/flake.lock @@ -3,11 +3,11 @@ "advisory-db": { "flake": false, "locked": { - "lastModified": 1789329924, - "narHash": "sha256-mykGMFabQ7yP6G373M3VHkrac9PJPKJstrhQz2D/Rdc=", + "lastModified": 1793979272, + "narHash": "sha256-oUcBtPbtS7PlEMuSrgTAN4wv49cXYbwKbQqhH2pah5w=", "owner": "rustsec", "repo": "advisory-db", - "rev": "455fd4bac659b5f1fca3810661c2d8b3c25dad05", + "rev": "309392b18f6b17022f82c701f300433126901068", "type": "github" }, "original": { @@ -18,11 +18,11 @@ }, "crane": { "locked": { - "lastModified": 1788465171, - "narHash": "sha256-Y1/TTVXjYXGF068IThQH9fPSZ0SIE74PABlUxnWTUH0=", + "lastModified": 1793836618, + "narHash": "sha256-TREenflwEjxOSq292FYwbc3kEm7TDRtXCZRNWEdjBmg=", "owner": "ipetkov", "repo": "crane", - "rev": "eb35abda9f232cc6610b1d1e3200d15c49b7ac54", + "rev": "79fd63528501446749c09f08cad486a58c7d173e", "type": "github" }, "original": { @@ -39,11 +39,11 @@ "rust-analyzer-src": "rust-analyzer-src" }, "locked": { - "lastModified": 1789298866, - "narHash": "sha256-6eaV5+MdWy1tAlN4HAFr64pTnYc9jiKGXBsu18cyVjE=", + "lastModified": 1794142885, + "narHash": "sha256-xWFSr7q8IerDAVRk4W7/CgTmi05hMy2qjZ0z3VYpOVk=", "owner": "nix-community", "repo": "fenix", - "rev": "1fc6f36a23fa16e3740987957266f6e4b915c3cd", + "rev": "f7d416b5073152c7f2e4de1a28d1a4330dd30a26", "type": "github" }, "original": { @@ -74,11 +74,11 @@ "nixpkgs-lib": "nixpkgs-lib" }, "locked": { - "lastModified": 1788450739, - "narHash": "sha256-glZLQlzIn1fXH6PazR2iUmTo7kzzyYSshrWhLS9TqCU=", + "lastModified": 1793576659, + "narHash": "sha256-V1h85lUaJBQoHFrB2vpXZOE0Ju1MYSnIpsehoVZYlDo=", "owner": "hercules-ci", "repo": "flake-parts", - "rev": "31729ca8cbdb4fa927b34e5f4353e6a83f39e993", + "rev": "ea2630b7470978622c7689a1ff75d2b389175399", "type": "github" }, "original": { @@ -89,11 +89,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1789149629, - "narHash": "sha256-H6GwaZzZf+4npqv0tph94w9tZddSjFjmQrVsW0z78uk=", + "lastModified": 1794042290, + "narHash": "sha256-ziZn2PvCJE5JEEpqTdxXwJpPB+L3YqoCpTAMCzyaP3U=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "eaad089433ca2bb662274377d33df3d0e51ef28b", + "rev": "f4a03c008967841f2a0b3cb7c436fc6fc31671f6", "type": "github" }, "original": { @@ -105,11 +105,11 @@ }, "nixpkgs-lib": { "locked": { - "lastModified": 1788057806, - "narHash": "sha256-DTQSMxzDWmT0zhguthvegnVkn7CFqGCv4IHCzk5ZUpM=", + "lastModified": 1793504054, + "narHash": "sha256-ThkfL3D/FhCiZFc9+3BtxwuMmpuK+/bGtXCSo1+yVew=", "owner": "nix-community", "repo": "nixpkgs.lib", - "rev": "596e2e3940e09b2abbeb03f75fa1828c57fcd72c", + "rev": "7851ba61fd862b277cb6a9cef37394bc18bb94e4", "type": "github" }, "original": { @@ -132,11 +132,11 @@ "rust-analyzer-src": { "flake": false, "locked": { - "lastModified": 1789128286, - "narHash": "sha256-KRxxgHiKIBp7R2n41IJuE5K4IUiLOpg47EEi3AxuSp8=", + "lastModified": 1794096810, + "narHash": "sha256-dWC+YtMX+cwH3e9ndiFB77ijTsKtO5I2OxfcvUY4j3k=", "owner": "rust-lang", "repo": "rust-analyzer", - "rev": "6aeeb8cf02741e5da07a1615a05faa506cecb21a", + "rev": "03ae6be57aa063bb373f69eead3b8e15168a45d2", "type": "github" }, "original": { @@ -153,11 +153,11 @@ ] }, "locked": { - "lastModified": 1786901030, - "narHash": "sha256-WSFCsDSE5ffgD2MqzkM2CYjeFiKhRF/dJUN8uedb6YE=", + "lastModified": 1791885023, + "narHash": "sha256-C3alQ2MEt0zVrUSho5NUDo3jmhbff72++bfwoqT9Omo=", "owner": "numtide", "repo": "treefmt-nix", - "rev": "27b3b12a8e6375f28ebe122f07d230ca5459bbfa", + "rev": "0d6d739a833ba9a9c93034862e4a7b061a062a1c", "type": "github" }, "original": { diff --git a/package-lock.json b/package-lock.json index 8f739b3f6..543133395 100644 --- a/package-lock.json +++ b/package-lock.json @@ -509,16 +509,16 @@ } }, "node_modules/@rspress/plugin-client-redirects": { - "version": "2.0.23", - "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.0.23.tgz", - "integrity": "sha512-TdpvO3TREv6s2mE32ztFvG3P232qUwjyQCKKsb9g0XT0q7rzcStZFRE7XT/L8i0XTzH/mfli1tVl4guTea/J3Q==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.1.tgz", + "integrity": "sha512-jrnh0UTczcTAk+xeJH6b2/LFLF2W7UzPYP992GxnW0mWJxPnvKQIk9v051bezD3gDuiGGRv8puFU7PMmwLOaHg==", "dev": true, "license": "MIT", "engines": { "node": "^20.19.0 || >=22.12.0" }, "peerDependencies": { - "@rspress/core": "^2.0.10" + "@rspress/core": "^2.1.0-beta.2" } }, "node_modules/@rspress/plugin-sitemap": { @@ -717,9 +717,9 @@ } }, "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", "dev": true, "license": "MIT" }, @@ -1148,9 +1148,9 @@ } }, "node_modules/acorn": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", - "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, "license": "MIT", "bin": { @@ -1380,13 +1380,13 @@ } }, "node_modules/entities": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", - "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", "dev": true, "license": "BSD-2-Clause", "engines": { - "node": ">=0.12" + "node": ">=20.19.0" }, "funding": { "url": "https://github.com/fb55/entities?sponsor=1" @@ -1587,9 +1587,9 @@ } }, "node_modules/hast-util-from-parse5": { - "version": "8.0.3", - "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-8.0.3.tgz", - "integrity": "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==", + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-8.0.4.tgz", + "integrity": "sha512-Yq7XlXor0Cpb71sI2E0zpv8QxQ5a6rfhDEETk4bcgrFX2SvJAY2PHocWwFtL6U9qyfiyByW3wZ6sZEfP2kW81g==", "dev": true, "license": "MIT", "dependencies": { @@ -1650,9 +1650,9 @@ } }, "node_modules/hast-util-raw": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/hast-util-raw/-/hast-util-raw-9.1.0.tgz", - "integrity": "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==", + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/hast-util-raw/-/hast-util-raw-9.2.0.tgz", + "integrity": "sha512-1zVq3M9AlZiBZ4mlMPnLtkK2rdd+I8VhmFLNLb//XJm6xA2AVH2tz19EHy25RgRWut6z6FpTARAs7P8rnmRJUQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1663,7 +1663,7 @@ "hast-util-to-parse5": "^8.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", - "parse5": "^7.0.0", + "parse5": "^8.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0", @@ -1822,9 +1822,9 @@ } }, "node_modules/hastscript": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-9.0.1.tgz", - "integrity": "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==", + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-9.0.3.tgz", + "integrity": "sha512-1ALZXSmCGmW3h8AMz4R4+QKSKFi7sNgXLVwmwB8FYVtl1CwQ3WDkSAEY/d5tp1g/vbQgq2s1WlHgfO3jbw1TsA==", "dev": true, "license": "MIT", "dependencies": { @@ -1840,9 +1840,9 @@ } }, "node_modules/hookable": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/hookable/-/hookable-6.1.1.tgz", - "integrity": "sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==", + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/hookable/-/hookable-6.1.2.tgz", + "integrity": "sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg==", "dev": true, "license": "MIT" }, @@ -1858,9 +1858,9 @@ } }, "node_modules/inline-style-parser": { - "version": "0.2.7", - "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", - "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==", + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.9.tgz", + "integrity": "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg==", "dev": true, "license": "MIT" }, @@ -1963,9 +1963,9 @@ } }, "node_modules/markdown-table": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz", - "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.1.0.tgz", + "integrity": "sha512-xpeSCdM+B+6P3ncfgaB7FoDbtJ30xAe6Z18TGT7AgXJsHqCElCICZovQqdRMm7kHgpTyYv36EupqewoFFSB8vw==", "dev": true, "license": "MIT", "funding": { @@ -1974,16 +1974,16 @@ } }, "node_modules/mdast-util-find-and-replace": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz", - "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.4.tgz", + "integrity": "sha512-z4B5c6jrnJ1ltOQemhWYPBSAo6y42Z8Gt2yEgfgNTMcLSU59B8bfj8Z8AnAlJrBGLnqkdAUZ7jdDEqQw3KuipQ==", "dev": true, "license": "MIT", "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" + "unist-util-visit-parents": "^6.1.0" }, "funding": { "type": "opencollective", @@ -1991,9 +1991,9 @@ } }, "node_modules/mdast-util-from-markdown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz", - "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz", + "integrity": "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A==", "dev": true, "license": "MIT", "dependencies": { @@ -2036,9 +2036,9 @@ } }, "node_modules/mdast-util-gfm-autolink-literal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz", - "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.1.0.tgz", + "integrity": "sha512-Jx6QSK8wDo558Bcf7q+1pe0v81g2PVs09Hlvu9xJHmCFRF3sAPW7vXFVIAwBncs3sde92WbsVqNxwdqViA2XnQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2088,9 +2088,9 @@ } }, "node_modules/mdast-util-gfm-table": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz", - "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.1.tgz", + "integrity": "sha512-fiIjPrAy4kz68/eFbPHhsiWDGHhqUSVoU1XsfLM5DsEPXw7MxgiVVyulUggFRckVWeT1KXQXkg5vm3kv4oMSOA==", "dev": true, "license": "MIT", "dependencies": { @@ -2098,7 +2098,9 @@ "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0" + "mdast-util-to-markdown": "^2.0.0", + "mdast-util-to-string": "^4.0.0", + "unist-util-visit": "^5.0.0" }, "funding": { "type": "opencollective", @@ -2106,9 +2108,9 @@ } }, "node_modules/mdast-util-gfm-task-list-item": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz", - "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.1.tgz", + "integrity": "sha512-jXVO1hvB2hs82g1esi7I9nIJDqiijbQLIyH2jDUb5s7jIAZMr/79h0VHSq7XHKTqpLARRm+DDNjduB7S9+6XZA==", "dev": true, "license": "MIT", "dependencies": { @@ -2160,9 +2162,9 @@ } }, "node_modules/mdast-util-mdx-jsx": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz", - "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.1.tgz", + "integrity": "sha512-oXp1GIa+E9IwIs3a106+tr3Bz2MlTTBvlXjOZMoIat11kk7vjqgmBnksB9WHmWv+gZh7k3IUgpAHlwHB7DH4GQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2338,9 +2340,9 @@ ] }, "node_modules/micromark": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", - "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", + "integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==", "dev": true, "funding": [ { @@ -2364,6 +2366,7 @@ "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", @@ -2374,9 +2377,9 @@ } }, "node_modules/micromark-core-commonmark": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz", - "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz", + "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==", "dev": true, "funding": [ { @@ -2394,18 +2397,19 @@ "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", - "micromark-factory-space": "^2.0.0", + "micromark-factory-space": "^2.1.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" + "micromark-util-types": "^2.0.3" } }, "node_modules/micromark-extension-cjk-friendly": { @@ -2791,9 +2795,9 @@ } }, "node_modules/micromark-factory-space": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz", - "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz", + "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==", "dev": true, "funding": [ { @@ -2984,6 +2988,26 @@ "micromark-util-symbol": "^2.0.0" } }, + "node_modules/micromark-util-edit-map": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz", + "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, "node_modules/micromark-util-encode": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", @@ -3147,9 +3171,9 @@ "license": "MIT" }, "node_modules/micromark-util-types": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", - "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", "dev": true, "funding": [ { @@ -3224,13 +3248,13 @@ "license": "MIT" }, "node_modules/parse5": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", - "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", "dev": true, "license": "MIT", "dependencies": { - "entities": "^6.0.0" + "entities": "^9.0.0" }, "funding": { "url": "https://github.com/inikulin/parse5?sponsor=1" @@ -3733,7 +3757,14 @@ "style-to-object": "1.0.14" } }, - "node_modules/style-to-object": { + "node_modules/style-to-js/node_modules/inline-style-parser": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", + "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==", + "dev": true, + "license": "MIT" + }, + "node_modules/style-to-js/node_modules/style-to-object": { "version": "1.0.14", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz", "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==", @@ -3743,6 +3774,16 @@ "inline-style-parser": "0.2.7" } }, + "node_modules/style-to-object": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-2.0.2.tgz", + "integrity": "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inline-style-parser": "0.2.9" + } + }, "node_modules/toggle-selection": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/toggle-selection/-/toggle-selection-1.0.6.tgz", @@ -3965,9 +4006,9 @@ } }, "node_modules/vfile-location": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/vfile-location/-/vfile-location-5.0.3.tgz", - "integrity": "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==", + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/vfile-location/-/vfile-location-5.0.4.tgz", + "integrity": "sha512-vEvxatYZCIpNvzGk2UD+u4I/sZkSKoOsdRCbkOIsN73QpJbriJ1qvvBAL1PeI0y55Leoqf7pORbaSPpG/smmOg==", "dev": true, "license": "MIT", "dependencies": { @@ -3980,9 +4021,9 @@ } }, "node_modules/vfile-message": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", - "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.4.tgz", + "integrity": "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg==", "dev": true, "license": "MIT", "dependencies": { From a484c28f9953b66b68d808a9c4fb39720d03891e Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Thu, 5 Nov 2026 00:44:23 +0100 Subject: [PATCH 130/342] fix: Don't try to use system resolv.conf when other servers are configured Previously, only HTTP clients targeting matrix servers (and using the resolution spec) would use the DNS servers configured in the c10y config. This happened because reqwest requires any DNS resolvers passed in to implement reqwest::dns::Resolve, which only the matrix resolver did, and no other HTTP client had a proper DNS resolver (which used the configured DNS servers) passed into it. To fix this we make a custom resolution struct based on reqwest's reqwest::dns::HickoryDnsResolver, which implements Request with no other modifications to the DNS response. HickoryDnsResolver itself isn't exported, which is why we re-created it instead of using it directly. no im not an LLM i just wrote this to remember my own changes later on Fixes: continuwuation/continuwuity#2441 --- src/admin/debug/commands.rs | 3 +- src/service/client/dns_resolver.rs | 44 +++++++++++ src/service/client/mod.rs | 115 ++++++++++++++++++----------- 3 files changed, 119 insertions(+), 43 deletions(-) create mode 100644 src/service/client/dns_resolver.rs diff --git a/src/admin/debug/commands.rs b/src/admin/debug/commands.rs index 7b5e82dc6..3109730cb 100644 --- a/src/admin/debug/commands.rs +++ b/src/admin/debug/commands.rs @@ -983,7 +983,8 @@ impl crate::Context<'_> { let resolver: &MatrixResolver = if no_cache { &MatrixResolverBuilder::new() .dangerous_tls_accept_invalid_certs(self.services.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure) - .http_client(self.services.client.dns.clone()) + .http_client(self.services.client.matrix_http_client.clone()) + .dns_resolver(self.services.client.dns_resolver.clone()) .build()? } else { &self.services.client.matrix_resolver diff --git a/src/service/client/dns_resolver.rs b/src/service/client/dns_resolver.rs new file mode 100644 index 000000000..84be16dcd --- /dev/null +++ b/src/service/client/dns_resolver.rs @@ -0,0 +1,44 @@ +use std::{ + net::{IpAddr, SocketAddr}, + sync::Arc, +}; + +use hickory_resolver::{Resolver, net::runtime::TokioRuntimeProvider}; +use reqwest::dns::{Addrs, Name, Resolve, Resolving}; + +/// A simple struct to implement reqwest::dns::Resolve, as that is what's +/// required by the reqwest client builder. Most code is based on +/// reqwest::dns::HickoryDnsResolver, which we here have to almost re-create +/// because it's pub(crate) instead of pub: +pub(crate) struct DnsResolver { + resolver: Arc>, +} + +impl DnsResolver { + pub(crate) fn new(resolver: Arc>) -> Self { Self { resolver } } +} + +struct SocketAddrs { + iter: std::vec::IntoIter, +} + +impl Iterator for SocketAddrs { + type Item = SocketAddr; + + fn next(&mut self) -> Option { + self.iter.next().map(|ip_addr| SocketAddr::new(ip_addr, 0)) + } +} + +impl Resolve for DnsResolver { + fn resolve(&self, name: Name) -> Resolving { + let resolver = self.resolver.clone(); + Box::pin(async move { + let lookup = resolver.lookup_ip(name.as_str()).await?; + let addrs: Addrs = Box::new(SocketAddrs { + iter: lookup.iter().collect::>().into_iter(), + }); + Ok(addrs) + }) + } +} diff --git a/src/service/client/mod.rs b/src/service/client/mod.rs index 234b50956..7d84a87ac 100644 --- a/src/service/client/mod.rs +++ b/src/service/client/mod.rs @@ -1,26 +1,36 @@ +mod dns_resolver; + use std::{sync::Arc, time::Duration}; use async_trait::async_trait; -use conduwuit::{Config, Result, Server, err, trace, utils::response::LimitReadExt, warn}; +use conduwuit::{ + Config, Result, Server, debug, err, info, trace, utils::response::LimitReadExt, warn, +}; +use dns_resolver::DnsResolver; use either::Either; use hickory_resolver::{ TokioResolver, - config::{ConnectionConfig, NameServerConfig}, + config::{ConnectionConfig, NameServerConfig, ResolverConfig}, net::runtime::TokioRuntimeProvider, proto::rr::IntoName, }; use ipaddress::IPAddress; -use reqwest::redirect; +use reqwest::{dns::Resolve, redirect}; use resolvematrix::server::{MatrixResolver, MatrixResolverBuilder}; use serde::Deserialize; use crate::service; pub struct Service { - pub matrix_resolver: Arc, + /// Regular DNS resolver pub dns_resolver: Arc, - pub dns: reqwest::Client, + /// Matrix server resolver according to server resolution spec + pub matrix_resolver: Arc, + + /// HTTP client used for fetching files during server resolution + pub matrix_http_client: reqwest::Client, + pub url_preview: reqwest::Client, pub external_resource: reqwest::Client, pub federation: reqwest::Client, @@ -38,9 +48,18 @@ impl crate::Service for Service { fn build(args: crate::Args<'_>) -> Result> { let config = &args.server.config; - let dns_resolver = get_dns_resolver(args.server)?; + // Regular DNS resolver + let tokio_dns_resolver = get_dns_resolver(args.server)?; - let dns_client = base(&args.server.config)? + // More different DNS resolver that also implements + // reqwest::dns::Resolve (which is required for reqwest to use it). + // Don't ask me, I just work here. - @silversys + let reqwest_dns_resolver = Arc::new(DnsResolver::new(tokio_dns_resolver.clone())); + + // Regular HTTP client that does regular HTTP requests with regular DNS + // resolution, but with timeouts for /.well-known/matrix/* files + // according to c10y config. + let matrix_http_client = base(&args.server.config, reqwest_dns_resolver.clone())? .connect_timeout(Duration::from_secs(args.server.config.well_known_conn_timeout)) .read_timeout(Duration::from_secs(args.server.config.well_known_timeout)) .timeout(Duration::from_secs(args.server.config.well_known_timeout)) @@ -48,12 +67,17 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(4)) .build()?; + // Resolves hostnames into ip+port or hostname+port server combinations + // according to the server resolution spec let matrix_resolver = Arc::new(MatrixResolverBuilder::new() - .dangerous_tls_accept_invalid_certs(args.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure) - .http_client(dns_client.clone()) - .dns_resolver(dns_resolver.clone()) - .build()?); - let matrix_dns_resolver = matrix_resolver.create_dns_resolver(); + .dangerous_tls_accept_invalid_certs(args.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure) + .http_client(matrix_http_client.clone()) + .dns_resolver(tokio_dns_resolver.clone()) + .build()?); + // Does the same as the above, but acts as a DNS resolver for reqwest + // (implementing caching and following the matrix server resolution + // spec) + let matrix_dns_resolver = Arc::new(matrix_resolver.create_dns_resolver()); let url_preview_bind_addr = config .url_preview_bound_interface @@ -72,11 +96,11 @@ impl crate::Service for Service { Ok(Arc::new(Self { matrix_resolver, - dns_resolver, + matrix_http_client, - dns: dns_client, + dns_resolver: tokio_dns_resolver, - url_preview: base(config) + url_preview: base(config, reqwest_dns_resolver.clone()) .and_then(|builder| { builder_interface(builder, url_preview_bind_iface.as_deref()) })? @@ -86,12 +110,11 @@ impl crate::Service for Service { .user_agent(url_preview_user_agent) .build()?, - external_resource: base(config)? + external_resource: base(config, reqwest_dns_resolver.clone())? .redirect(redirect::Policy::limited(3)) .build()?, - federation: base(config)? - .dns_resolver(matrix_dns_resolver.clone()) + federation: base(config, matrix_dns_resolver.clone())? .connect_timeout(Duration::from_secs(config.federation_conn_timeout)) .read_timeout(Duration::from_secs(config.federation_timeout)) .timeout(Duration::from_secs( @@ -104,8 +127,7 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(3)) .build()?, - federation_slow: base(config)? - .dns_resolver(matrix_dns_resolver.clone()) + federation_slow: base(config, matrix_dns_resolver.clone())? .connect_timeout(Duration::from_secs(config.federation_conn_timeout)) .read_timeout(Duration::from_secs(config.federation_timeout.saturating_mul(6))) .timeout(Duration::from_secs( @@ -118,8 +140,7 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(3)) .build()?, - sender: base(config)? - .dns_resolver(matrix_dns_resolver.clone()) + sender: base(config, matrix_dns_resolver)? .connect_timeout(Duration::from_secs(config.federation_conn_timeout)) .read_timeout(Duration::from_secs(config.sender_timeout)) .timeout(Duration::from_secs(config.sender_timeout)) @@ -128,8 +149,7 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(2)) .build()?, - appservice: base(config)? - .dns_resolver(matrix_dns_resolver) + appservice: base(config, reqwest_dns_resolver.clone())? .connect_timeout(Duration::from_secs(5)) .read_timeout(Duration::from_secs(config.appservice_timeout)) .timeout(Duration::from_secs(config.appservice_timeout)) @@ -138,7 +158,7 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(2)) .build()?, - pusher: base(config)? + pusher: base(config, reqwest_dns_resolver.clone())? .connect_timeout(Duration::from_secs(config.pusher_conn_timeout)) .timeout(Duration::from_secs(config.pusher_timeout)) .pool_max_idle_per_host(1) @@ -148,7 +168,7 @@ impl crate::Service for Service { // MSC4174 recommends against following redirects, since the // destination is only checked before the request is sent. - webpush: base(config)? + webpush: base(config, reqwest_dns_resolver)? .connect_timeout(Duration::from_secs(config.pusher_conn_timeout)) .timeout(Duration::from_secs(config.pusher_timeout)) .pool_max_idle_per_host(1) @@ -221,18 +241,22 @@ impl Service { } } -pub fn base(config: &Config) -> Result { +pub(crate) fn base( + config: &Config, + resolver: Arc, +) -> Result { let mut builder = reqwest::Client::builder() - .hickory_dns(true) - .connect_timeout(Duration::from_secs(config.request_conn_timeout)) - .read_timeout(Duration::from_secs(config.request_timeout)) - .timeout(Duration::from_secs(config.request_total_timeout)) - .pool_idle_timeout(Duration::from_secs(config.request_idle_timeout)) - .pool_max_idle_per_host(config.request_idle_per_host.into()) - .user_agent(conduwuit::user_agent()) - .redirect(redirect::Policy::limited(6)) + .hickory_dns(true) + .dns_resolver(resolver) + .connect_timeout(Duration::from_secs(config.request_conn_timeout)) + .read_timeout(Duration::from_secs(config.request_timeout)) + .timeout(Duration::from_secs(config.request_total_timeout)) + .pool_idle_timeout(Duration::from_secs(config.request_idle_timeout)) + .pool_max_idle_per_host(config.request_idle_per_host.into()) + .user_agent(conduwuit::user_agent()) + .redirect(redirect::Policy::limited(6)) .danger_accept_invalid_certs(config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure) - .connection_verbose(cfg!(debug_assertions)); + .connection_verbose(cfg!(debug_assertions)); #[cfg(feature = "gzip_compression")] { @@ -310,19 +334,21 @@ fn builder_interface( fn get_dns_resolver(server: &Arc) -> Result> { let config = &server.config; - let (sys_conf, mut opts) = hickory_resolver::system_conf::read_system_conf() + + let (system_resolver_config, mut opts) = hickory_resolver::system_conf::read_system_conf() .map_err(|e| err!(error!("Failed to configure DNS resolver from system: {e}")))?; - let mut conf = hickory_resolver::config::ResolverConfig::default(); + let mut conf = ResolverConfig::from_name_servers(vec![]); - if let Some(domain) = sys_conf.domain() { + // Set domain and search domains from system config (/etc/resolv.conf) + if let Some(domain) = system_resolver_config.domain() { conf.set_domain(domain.clone()); } - - for sys_conf in sys_conf.search() { + for sys_conf in system_resolver_config.search() { conf.add_search(sys_conf.clone()); } + // Read nameservers from c10y config file let config_nameservers: Vec = server .config .dns_servers @@ -330,11 +356,16 @@ fn get_dns_resolver(server: &Arc) -> Result> { .filter_map(IntoName::to_ip) .map(NameServerConfig::udp_and_tcp) .collect(); + let system_nameservers = system_resolver_config.name_servers().to_vec(); + let nameservers = if !config_nameservers.is_empty() { + debug!("Using DNS nameservers from config file"); config_nameservers } else { - sys_conf.name_servers().to_vec() + debug!("Using DNS nameservers from /etc/resolv.conf"); + system_nameservers }; + info!(?nameservers, "Resolved nameservers for DNS client"); for sys_conf in nameservers { let mut ns = sys_conf.clone(); From 60a0784a36c4d2f6ac218ea0e6990802460dfbca Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Thu, 5 Nov 2026 00:50:07 +0100 Subject: [PATCH 131/342] chore: Changelog --- changelog.d/2460.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2460.bugfix.md diff --git a/changelog.d/2460.bugfix.md b/changelog.d/2460.bugfix.md new file mode 100644 index 000000000..fc8955510 --- /dev/null +++ b/changelog.d/2460.bugfix.md @@ -0,0 +1 @@ +Ensure HTTP clients actually follow the `dns_servers` config option. Contributed by @silversys From 144777dab0d4fc0d012ae8e05d52086a50dc47a7 Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Thu, 5 Nov 2026 13:18:11 +0100 Subject: [PATCH 132/342] fix: Add DNS resolver to oidc crate as well Because openidconnect vendors reqwest (??), we have to re-implement the entire Resolve trait. No I don't like it, but I can't think of a better solution. --- src/service/client/dns_resolver.rs | 29 +++++++++++++++++++++++------ src/service/client/mod.rs | 6 +++++- src/service/oidc/mod.rs | 3 ++- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/src/service/client/dns_resolver.rs b/src/service/client/dns_resolver.rs index 84be16dcd..97c534704 100644 --- a/src/service/client/dns_resolver.rs +++ b/src/service/client/dns_resolver.rs @@ -4,18 +4,20 @@ use std::{ }; use hickory_resolver::{Resolver, net::runtime::TokioRuntimeProvider}; -use reqwest::dns::{Addrs, Name, Resolve, Resolving}; +use reqwest::dns::{Addrs, Resolving}; /// A simple struct to implement reqwest::dns::Resolve, as that is what's /// required by the reqwest client builder. Most code is based on /// reqwest::dns::HickoryDnsResolver, which we here have to almost re-create /// because it's pub(crate) instead of pub: -pub(crate) struct DnsResolver { - resolver: Arc>, +pub struct DnsResolver { + resolver: Arc, } +type TokioResolver = Resolver; + impl DnsResolver { - pub(crate) fn new(resolver: Arc>) -> Self { Self { resolver } } + pub(crate) fn new(resolver: Arc) -> Self { Self { resolver } } } struct SocketAddrs { @@ -30,8 +32,23 @@ impl Iterator for SocketAddrs { } } -impl Resolve for DnsResolver { - fn resolve(&self, name: Name) -> Resolving { +impl reqwest::dns::Resolve for DnsResolver { + fn resolve(&self, name: reqwest::dns::Name) -> Resolving { + let resolver = self.resolver.clone(); + Box::pin(async move { + let lookup = resolver.lookup_ip(name.as_str()).await?; + let addrs: Addrs = Box::new(SocketAddrs { + iter: lookup.iter().collect::>().into_iter(), + }); + Ok(addrs) + }) + } +} + +// openidconnect is weird and vendors reqwest (?), therefore we have to +// completely re-implement Resolve with different types +impl openidconnect::reqwest::dns::Resolve for DnsResolver { + fn resolve(&self, name: openidconnect::reqwest::dns::Name) -> Resolving { let resolver = self.resolver.clone(); Box::pin(async move { let lookup = resolver.lookup_ip(name.as_str()).await?; diff --git a/src/service/client/mod.rs b/src/service/client/mod.rs index 7d84a87ac..703e15f03 100644 --- a/src/service/client/mod.rs +++ b/src/service/client/mod.rs @@ -6,7 +6,7 @@ use async_trait::async_trait; use conduwuit::{ Config, Result, Server, debug, err, info, trace, utils::response::LimitReadExt, warn, }; -use dns_resolver::DnsResolver; +pub(crate) use dns_resolver::DnsResolver; use either::Either; use hickory_resolver::{ TokioResolver, @@ -25,6 +25,9 @@ pub struct Service { /// Regular DNS resolver pub dns_resolver: Arc, + /// Tokio system resolver wrapped + pub reqwest_resolver: Arc, + /// Matrix server resolver according to server resolution spec pub matrix_resolver: Arc, @@ -97,6 +100,7 @@ impl crate::Service for Service { Ok(Arc::new(Self { matrix_resolver, matrix_http_client, + reqwest_resolver: reqwest_dns_resolver.clone(), dns_resolver: tokio_dns_resolver, diff --git a/src/service/oidc/mod.rs b/src/service/oidc/mod.rs index d0369cf5e..220b29891 100644 --- a/src/service/oidc/mod.rs +++ b/src/service/oidc/mod.rs @@ -32,7 +32,7 @@ use tokio::{runtime, sync::SetOnce}; use url::Url; use crate::{ - Dep, config, globals, media, + Dep, client, config, globals, media, oauth::grant::AuthorizationCodeResponse, threepid, users::{self, AccountStatus, ProfileFieldChange}, @@ -163,6 +163,7 @@ impl crate::Service for Service { machine: SetOnce::new(), // This isn't in the client service because it has to use the `reqwest` shipped by `openidconnect` client: reqwest::ClientBuilder::new() + .dns_resolver(args.depend::("client").reqwest_resolver.clone()) .connect_timeout(Duration::from_secs(args.server.config.request_conn_timeout)) .read_timeout(Duration::from_secs(args.server.config.request_timeout)) .timeout(Duration::from_secs(args.server.config.request_total_timeout)) From a9bb74df6d2ad519e84d8fa1625024c1df6d7b4e Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Fri, 6 Nov 2026 10:49:07 +0100 Subject: [PATCH 133/342] chore: Disable hickory-dns feature from reqwest As we now pass in our own resolver (and hickory instance) for every client, having the hickory-dns feature enabled isn't necessary. --- Cargo.lock | 2 -- Cargo.toml | 1 - src/service/client/mod.rs | 1 - 3 files changed, 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4d54203ae..de15ed668 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4873,7 +4873,6 @@ dependencies = [ "h2", "h3", "h3-quinn", - "hickory-resolver", "http", "http-body", "http-body-util", @@ -4882,7 +4881,6 @@ dependencies = [ "hyper-util", "js-sys", "log", - "once_cell", "percent-encoding", "pin-project-lite", "quinn", diff --git a/Cargo.toml b/Cargo.toml index d3f88c3cb..176aa0038 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -161,7 +161,6 @@ default-features = false features = [ "rustls-no-provider", "socks", - "hickory-dns", "http2", "stream", "form", diff --git a/src/service/client/mod.rs b/src/service/client/mod.rs index 703e15f03..f258f5195 100644 --- a/src/service/client/mod.rs +++ b/src/service/client/mod.rs @@ -250,7 +250,6 @@ pub(crate) fn base( resolver: Arc, ) -> Result { let mut builder = reqwest::Client::builder() - .hickory_dns(true) .dns_resolver(resolver) .connect_timeout(Duration::from_secs(config.request_conn_timeout)) .read_timeout(Duration::from_secs(config.request_timeout)) From 87b2ca81a38264e3879b1bc4c890f78059796e1c Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 19:42:32 +0000 Subject: [PATCH 134/342] fix(ci): Kill the permissions blocks entirely, they don't do anything --- .forgejo/workflows/auto-labeler.yml | 5 ----- .forgejo/workflows/build-nix.yml | 2 -- .forgejo/workflows/check-changelog.yml | 5 ----- .forgejo/workflows/prek-checks.yml | 4 ---- .forgejo/workflows/release-image.yml | 6 ------ 5 files changed, 22 deletions(-) diff --git a/.forgejo/workflows/auto-labeler.yml b/.forgejo/workflows/auto-labeler.yml index 71b59eb19..af345b215 100644 --- a/.forgejo/workflows/auto-labeler.yml +++ b/.forgejo/workflows/auto-labeler.yml @@ -4,11 +4,6 @@ on: pull_request_target: types: [opened, reopened] -permissions: - contents: read - pull-requests: write - issues: write - jobs: auto-label: name: Apply labels based on changed files diff --git a/.forgejo/workflows/build-nix.yml b/.forgejo/workflows/build-nix.yml index ee16f0d25..2d203541c 100644 --- a/.forgejo/workflows/build-nix.yml +++ b/.forgejo/workflows/build-nix.yml @@ -54,8 +54,6 @@ jobs: runs-on: ubuntu-latest needs: - build - permissions: - contents: write if: startsWith(github.ref, 'refs/tags/') steps: - name: Download binary artifacts diff --git a/.forgejo/workflows/check-changelog.yml b/.forgejo/workflows/check-changelog.yml index eb4ecb66a..c67fc9de2 100644 --- a/.forgejo/workflows/check-changelog.yml +++ b/.forgejo/workflows/check-changelog.yml @@ -4,11 +4,6 @@ on: pull_request_target: types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled] -permissions: - contents: read - pull-requests: write - issues: write - jobs: check-changelog: name: Check changelog is added diff --git a/.forgejo/workflows/prek-checks.yml b/.forgejo/workflows/prek-checks.yml index 6c00a7e35..64f3f623e 100644 --- a/.forgejo/workflows/prek-checks.yml +++ b/.forgejo/workflows/prek-checks.yml @@ -7,10 +7,6 @@ on: - main workflow_dispatch: -permissions: - contents: read - pull-requests: read - jobs: fast-checks: name: Pre-commit & Formatting diff --git a/.forgejo/workflows/release-image.yml b/.forgejo/workflows/release-image.yml index 6224c0f2f..78fee4223 100644 --- a/.forgejo/workflows/release-image.yml +++ b/.forgejo/workflows/release-image.yml @@ -27,12 +27,6 @@ env: BUILTIN_REGISTRY_ENABLED: "${{ ((vars.BUILTIN_REGISTRY_USER && secrets.BUILTIN_REGISTRY_PASSWORD) || (github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false)) && 'true' || 'false' }}" IMAGE_PATH: forgejo.ellis.link/continuwuation/continuwuity -permissions: - contents: write - packages: write - attestations: write - id-token: write - jobs: build-release: name: "Build ${{ matrix.slug }} (release)" From e217ebb5e0d8fba418a33a7dd5de92c0b3a5bac9 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 19:58:13 +0000 Subject: [PATCH 135/342] chore(ci): Remove debug logs This was an artifact that has long outlived its usefulness --- docker/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 30bad14a9..6b581749c 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -192,7 +192,7 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \ jq -r ".target_directory")) mkdir /out/sbin PACKAGE=conduwuit - CARGO_LOG=debug xx-cargo build --locked --profile ${RUST_PROFILE} \ + xx-cargo build --locked --profile ${RUST_PROFILE} \ --no-default-features --features ${CARGO_FEATURES} \ -p $PACKAGE; BINARIES=($(cargo metadata --no-deps --format-version 1 | \ From 779374bb5475ecfe723d35d33365ec0a9a979b61 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 20:33:31 +0000 Subject: [PATCH 136/342] fix(deps): Properly use intended crypto backends --- Cargo.lock | 15 +++------------ Cargo.toml | 11 +++++++++++ src/main/Cargo.toml | 5 +++-- src/service/Cargo.toml | 2 ++ 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index de15ed668..bedd74222 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1142,6 +1142,7 @@ dependencies = [ "p256 0.14.0", "rand 0.10.3", "regex", + "reqwest 0.12.28", "reqwest 0.13.5", "resolvematrix", "ruma", @@ -2717,10 +2718,10 @@ dependencies = [ "hyper", "hyper-util", "rustls", + "rustls-native-certs", "tokio", "tokio-rustls", "tower-service", - "webpki-roots", ] [[package]] @@ -4840,8 +4841,8 @@ dependencies = [ "log", "percent-encoding", "pin-project-lite", - "quinn", "rustls", + "rustls-native-certs", "rustls-pki-types", "serde", "serde_json", @@ -4856,7 +4857,6 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots", ] [[package]] @@ -7111,15 +7111,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "webpki-roots" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "weezl" version = "0.1.12" diff --git a/Cargo.toml b/Cargo.toml index 176aa0038..fa8b5aa5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -166,6 +166,15 @@ features = [ "form", ] +# Needed for as long as openidconnect is on an outdated reqwest +[workspace.dependencies.reqwest_0_12] +package = "reqwest" +version = "0.12" +default-features = false +features = [ + "rustls-tls-native-roots-no-provider", +] + [workspace.dependencies.serde] version = "1.0.229" default-features = false @@ -414,6 +423,8 @@ default-features = false [workspace.dependencies.openidconnect] version = "4.1.0" +default-features = false +features = ["reqwest"] # optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring [workspace.dependencies.opentelemetry] diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index 394076898..8cc5c2975 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -105,11 +105,12 @@ http3 = [ "reqwest/http3" ] ring = [ - "rustls/ring" + "rustls/ring", ] + aws_lc_rs = [ "rustls/aws_lc_rs", - "dep:aws-lc-rs" + "dep:aws-lc-rs", ] io_uring = [ "conduwuit-database/io_uring", diff --git a/src/service/Cargo.toml b/src/service/Cargo.toml index 60a362608..6ff782c69 100644 --- a/src/service/Cargo.toml +++ b/src/service/Cargo.toml @@ -122,6 +122,8 @@ lettre.workspace = true resolvematrix.workspace = true serde_urlencoded.workspace = true openidconnect.workspace = true +# This is here to set features on the outdated openidconnect reqwest +reqwest_0_12.workspace = true rand.workspace = true [target.'cfg(all(unix, target_os = "linux"))'.dependencies] From bf028274f8740f1608f9877d6922320eab09fa41 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Mon, 9 Nov 2026 13:01:15 -0500 Subject: [PATCH 137/342] fix(nix): fix linking to RocksDB --- nix/packages/continuwuity.nix | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/nix/packages/continuwuity.nix b/nix/packages/continuwuity.nix index 8baf26b3d..7ba27815d 100644 --- a/nix/packages/continuwuity.nix +++ b/nix/packages/continuwuity.nix @@ -42,7 +42,12 @@ let env = { CARGO_PROFILE = profile; - RUSTFLAGS = rustflags; + # Rust links with its bundled rust-lld by default on linux-gnu targets. + # This bypasses nixpkgs' linker wrapper (and its rpaths), so we make it use the system one. + # `-C linker-features=-lld` is only stable on x86_64, but cc takes the last `-fuse-ld`. + RUSTFLAGS = lib.concatStringsSep " " ( + lib.optional stdenv.hostPlatform.isLinux "-C link-arg=-fuse-ld=bfd" ++ [ rustflags ] + ); GIT_COMMIT_HASH = self.rev or self.dirtyRev or ""; GIT_COMMIT_HASH_SHORT = self.shortRev or self.dirtyShortRev or ""; } @@ -60,18 +65,6 @@ craneLib.buildPackage ( inherit cargoExtraArgs; cargoArtifacts = craneLib.buildDepsOnly attrs; - # Needed to make continuwuity link to rocksdb - postFixup = lib.optionalString (stdenv.hostPlatform.isLinux && rocksdb != null) '' - old_rpath="$(patchelf --print-rpath $out/bin/conduwuit)" - extra_rpath="${ - lib.makeLibraryPath [ - rocksdb - ] - }" - - patchelf --set-rpath "$old_rpath:$extra_rpath" $out/bin/conduwuit - ''; - meta = { description = "A community-driven Matrix homeserver in Rust"; mainProgram = "conduwuit"; From db83bc4c6373fa4d7ced81137cd01ede43ef7036 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Mon, 9 Nov 2026 14:50:47 -0500 Subject: [PATCH 138/342] fix(nix): Disable broken checks for tzdata and sqlite --- nix/packages/default.nix | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/nix/packages/default.nix b/nix/packages/default.nix index 7cba9b870..26171e846 100644 --- a/nix/packages/default.nix +++ b/nix/packages/default.nix @@ -18,6 +18,23 @@ { packages = let + # These musl deps aren't in the binary cache, so they're built locally, and their + # test suites run (and break) when the builder can execute musl binaries. + # + # TODO: drop tzdata override once https://github.com/NixOS/nixpkgs/pull/582577 reaches nixos-unstable + # - tzdata: `now.ck` checks against the current date. + # TODO: drop sqlite override once https://github.com/NixOS/nixpkgs/issues/580629 is resolved + # - sqlite: its test runner fails to build `testfixture` when cross-compiling to musl. + muslOverlay = + _final: prev: + lib.genAttrs [ "tzdata" "sqlite" ] ( + name: + if prev.stdenv.hostPlatform.isMusl then + prev.${name}.overrideAttrs { doCheck = false; } + else + prev.${name} + ); + mkPackages = pkgs: let @@ -78,6 +95,7 @@ import inputs.nixpkgs { localSystem = system; crossSystem = "x86_64-unknown-linux-musl"; + overlays = [ muslOverlay ]; } ) )) @@ -86,6 +104,7 @@ import inputs.nixpkgs { localSystem = system; crossSystem = "aarch64-unknown-linux-musl"; + overlays = [ muslOverlay ]; } ) )); From 684b83491bc9c6a67e67dbd4c1d2cead797dc92f Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 10 Nov 2026 05:17:14 +0000 Subject: [PATCH 139/342] chore(deps): update github-actions-digest --- .forgejo/actions/create-docker-manifest/action.yml | 2 +- .forgejo/actions/prepare-docker-build/action.yml | 2 +- .forgejo/actions/timelord/action.yml | 2 +- .forgejo/workflows/build-nix.yml | 2 +- .forgejo/workflows/release-image.yml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.forgejo/actions/create-docker-manifest/action.yml b/.forgejo/actions/create-docker-manifest/action.yml index 1415f0458..a5151f9fa 100644 --- a/.forgejo/actions/create-docker-manifest/action.yml +++ b/.forgejo/actions/create-docker-manifest/action.yml @@ -44,7 +44,7 @@ runs: - name: Login to builtin registry if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }} - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 with: registry: ${{ env.BUILTIN_REGISTRY }} username: ${{ inputs.registry_user }} diff --git a/.forgejo/actions/prepare-docker-build/action.yml b/.forgejo/actions/prepare-docker-build/action.yml index 4c52a2fc3..baef6eb9f 100644 --- a/.forgejo/actions/prepare-docker-build/action.yml +++ b/.forgejo/actions/prepare-docker-build/action.yml @@ -79,7 +79,7 @@ runs: - name: Login to builtin registry if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }} - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 with: registry: ${{ env.BUILTIN_REGISTRY }} username: ${{ inputs.registry_user }} diff --git a/.forgejo/actions/timelord/action.yml b/.forgejo/actions/timelord/action.yml index 0275bb93e..5a5db6721 100644 --- a/.forgejo/actions/timelord/action.yml +++ b/.forgejo/actions/timelord/action.yml @@ -71,7 +71,7 @@ runs: - name: Install timelord-cli and git-warp-time if: steps.check-binaries.outputs.need-install == 'true' - uses: https://github.com/taiki-e/install-action@682ce6c3c696a4cd5168a05f98e51aa02b877941 # v2 + uses: https://github.com/taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2 with: tool: git-warp-time,timelord-cli@3.0.1 diff --git a/.forgejo/workflows/build-nix.yml b/.forgejo/workflows/build-nix.yml index 2d203541c..6370e8ec7 100644 --- a/.forgejo/workflows/build-nix.yml +++ b/.forgejo/workflows/build-nix.yml @@ -63,7 +63,7 @@ jobs: path: binaries merge-multiple: true - name: Create Release and Upload - uses: https://github.com/softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 + uses: https://github.com/softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3 with: draft: true files: binaries/* diff --git a/.forgejo/workflows/release-image.yml b/.forgejo/workflows/release-image.yml index 78fee4223..2c669ab8b 100644 --- a/.forgejo/workflows/release-image.yml +++ b/.forgejo/workflows/release-image.yml @@ -208,7 +208,7 @@ jobs: path: binaries merge-multiple: true - name: Create Release and Upload - uses: https://github.com/softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 + uses: https://github.com/softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3 with: draft: true files: binaries/* From d6774861004d80f1fdb7bfe63ace6caca5c7200a Mon Sep 17 00:00:00 2001 From: Ginger Date: Tue, 10 Nov 2026 11:45:37 -0500 Subject: [PATCH 140/342] chore: Fix docs build failing --- docs/calls/turn.mdx | 2 +- docs/maintenance.mdx | 2 +- package-lock.json | 41 ----------------------------------------- 3 files changed, 2 insertions(+), 43 deletions(-) diff --git a/docs/calls/turn.mdx b/docs/calls/turn.mdx index 82b71149c..fe6c7db77 100644 --- a/docs/calls/turn.mdx +++ b/docs/calls/turn.mdx @@ -348,7 +348,7 @@ After configuration and spin-up, the destination `turns:turn.example.com:443?tra Using static credentials :::caution -Static credentials are less secure than shared secrets because they don't expire and must be configured in coturn separately. It is strongly advised you use [shared secret authentication](#2-configuration). +Static credentials are less secure than shared secrets because they don't expire and must be configured in coturn separately. It is strongly advised you use [shared secret authentication](#2-configuring-coturn). ::: If you prefer static username/password credentials instead of shared secrets: diff --git a/docs/maintenance.mdx b/docs/maintenance.mdx index 362e92d2b..329629eb9 100644 --- a/docs/maintenance.mdx +++ b/docs/maintenance.mdx @@ -17,7 +17,7 @@ Continuwuity has moderation admin commands for: - fetching `/.well-known/matrix/support` from servers (`!admin federation`) - blocking incoming federation for certain rooms (not the same as room banning) (`!admin federation`) -- deleting media (see [the media section](#media)) +- deleting media Any commands with `-list` in them will require a codeblock in the message with each object being newline delimited. An example of doing this is: diff --git a/package-lock.json b/package-lock.json index 543133395..4e72790f8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -227,9 +227,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -244,9 +241,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -261,9 +255,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -278,9 +269,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -295,9 +283,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -312,9 +297,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -329,9 +311,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -346,9 +325,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1857,13 +1833,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/inline-style-parser": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.9.tgz", - "integrity": "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg==", - "dev": true, - "license": "MIT" - }, "node_modules/is-absolute-url": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-absolute-url/-/is-absolute-url-4.0.1.tgz", @@ -3774,16 +3743,6 @@ "inline-style-parser": "0.2.7" } }, - "node_modules/style-to-object": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-2.0.2.tgz", - "integrity": "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "inline-style-parser": "0.2.9" - } - }, "node_modules/toggle-selection": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/toggle-selection/-/toggle-selection-1.0.6.tgz", From 4d7a7d6cdc06a86fef5b31a6e3a9a2eb6cb44262 Mon Sep 17 00:00:00 2001 From: Ginger Date: Tue, 10 Nov 2026 13:24:05 -0500 Subject: [PATCH 141/342] chore(deps): Clean up features and remove unused dependencies --- Cargo.lock | 17 -------- Cargo.toml | 5 ++- src/admin/Cargo.toml | 3 -- src/api/Cargo.toml | 3 -- src/core/Cargo.toml | 3 -- src/core/utils/result/inspect_log.rs | 62 ---------------------------- src/database/Cargo.toml | 3 -- src/main/Cargo.toml | 38 +++-------------- src/router/Cargo.toml | 18 ++------ src/service/Cargo.toml | 15 ++++++- src/web/Cargo.toml | 6 +-- src/web/mod.rs | 3 +- xtask/Cargo.toml | 5 +++ 13 files changed, 38 insertions(+), 143 deletions(-) delete mode 100644 src/core/utils/result/inspect_log.rs diff --git a/Cargo.lock b/Cargo.lock index bedd74222..d5e2615ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -867,13 +867,9 @@ dependencies = [ name = "conduwuit" version = "26.9.1" dependencies = [ - "aws-lc-rs", "clap", - "conduwuit_admin", - "conduwuit_api", "conduwuit_build_metadata", "conduwuit_core", - "conduwuit_database", "conduwuit_macros", "conduwuit_router", "conduwuit_service", @@ -881,8 +877,6 @@ dependencies = [ "const-str", "ctor", "dtor", - "hardened_malloc-rs", - "log", "opentelemetry", "opentelemetry-otlp", "opentelemetry-prometheus", @@ -890,13 +884,10 @@ dependencies = [ "opentelemetry_sdk", "parking_lot", "prometheus", - "reqwest 0.13.5", "rustls", "sentry", - "sentry-tower", "sentry-tracing", "tokio", - "tokio-metrics", "tracing", "tracing-flame", "tracing-journald", @@ -919,7 +910,6 @@ dependencies = [ "dtor", "futures", "lettre", - "log", "resolvematrix", "ruma", "serde-saphyr", @@ -950,7 +940,6 @@ dependencies = [ "hyper", "itertools 0.15.0", "lettre", - "log", "rand 0.10.3", "reqwest 0.13.5", "ruma", @@ -1004,7 +993,6 @@ dependencies = [ "libc", "libloading 0.9.0", "lock_api 0.5.0", - "log", "maplit", "nix", "num-traits", @@ -1052,7 +1040,6 @@ dependencies = [ "ctor", "dtor", "futures", - "log", "minicbor", "minicbor-serde", "rust-rocksdb", @@ -1094,14 +1081,10 @@ dependencies = [ "http-body-util", "hyper", "hyper-util", - "log", "opentelemetry-instrumentation-tower", "ruma", - "rustls", "sd-notify", - "sentry", "sentry-tower", - "sentry-tracing", "serde_json", "tokio", "tower", diff --git a/Cargo.toml b/Cargo.toml index fa8b5aa5f..43a9efa85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1020,4 +1020,7 @@ collapsible_if = "allow" cognitive_complexity = "allow" [workspace.metadata.cargo-shear] -ignored = ["const-str", "ctor", "dtor"] +# All of these crates provide macros that are used across the codebase +# and that every crate depends on. cargo-shear can't tell this because +# it doesn't expand macros. +ignored = ["const-str", "ctor", "dtor", "tracing"] diff --git a/src/admin/Cargo.toml b/src/admin/Cargo.toml index 6495ad400..446276ff0 100644 --- a/src/admin/Cargo.toml +++ b/src/admin/Cargo.toml @@ -62,8 +62,6 @@ release_max_log_level = [ "conduwuit-service/release_max_log_level", "tracing/max_level_trace", "tracing/release_max_level_info", - "log/max_level_trace", - "log/release_max_level_info", ] zstd_compression = [ "conduwuit-api/zstd_compression", @@ -84,7 +82,6 @@ ctor.workspace = true dtor.workspace = true futures.workspace = true lettre.workspace = true -log.workspace = true ruma.workspace = true serde_json.workspace = true serde-saphyr.workspace = true diff --git a/src/api/Cargo.toml b/src/api/Cargo.toml index 4385fbe7f..329d934c4 100644 --- a/src/api/Cargo.toml +++ b/src/api/Cargo.toml @@ -51,8 +51,6 @@ jemalloc_stats = [ release_max_log_level = [ "conduwuit-core/release_max_log_level", "conduwuit-service/release_max_log_level", - "log/max_level_trace", - "log/release_max_level_info", "tracing/max_level_trace", "tracing/release_max_level_info", ] @@ -80,7 +78,6 @@ http-body-util.workspace = true hyper.workspace = true itertools.workspace = true lettre.workspace = true -log.workspace = true rand.workspace = true reqwest.workspace = true ruma.workspace = true diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index ca4071ae8..335ba023a 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -47,8 +47,6 @@ perf_measurements = [] release_max_log_level = [ "tracing/max_level_trace", "tracing/release_max_level_info", - "log/max_level_trace", - "log/release_max_level_info", ] sentry_telemetry = [] zstd_compression = [ @@ -84,7 +82,6 @@ ipaddress.workspace = true libc.workspace = true libloading.workspace = true libloading.optional = true -log.workspace = true lettre.workspace = true num-traits.workspace = true rand.workspace = true diff --git a/src/core/utils/result/inspect_log.rs b/src/core/utils/result/inspect_log.rs deleted file mode 100644 index e9f32663c..000000000 --- a/src/core/utils/result/inspect_log.rs +++ /dev/null @@ -1,62 +0,0 @@ -use std::fmt; - -use tracing::Level; - -use super::Result; -use crate::error; - -pub trait ErrLog -where - E: fmt::Display, -{ - fn log_err(self, level: Level) -> Self; - - #[inline] - fn err_log(self) -> Self - where - Self: Sized, - { - self.log_err(Level::ERROR) - } -} - -pub trait ErrDebugLog -where - E: fmt::Debug, -{ - fn log_err_debug(self, level: Level) -> Self; - - #[inline] - fn err_debug_log(self) -> Self - where - Self: Sized, - { - self.log_err_debug(Level::ERROR) - } -} - -impl ErrLog for Result -where - E: fmt::Display, -{ - #[inline] - fn log_err(self, level: Level) -> Self - where - Self: Sized, - { - self.inspect_err(|error| error::inspect_log_level(&error, level)) - } -} - -impl ErrDebugLog for Result -where - E: fmt::Debug, -{ - #[inline] - fn log_err_debug(self, level: Level) -> Self - where - Self: Sized, - { - self.inspect_err(|error| error::inspect_debug_log_level(&error, level)) - } -} diff --git a/src/database/Cargo.toml b/src/database/Cargo.toml index 6b04c624d..8512c1362 100644 --- a/src/database/Cargo.toml +++ b/src/database/Cargo.toml @@ -34,8 +34,6 @@ jemalloc_stats = [ ] release_max_log_level = [ "conduwuit-core/release_max_log_level", - "log/max_level_trace", - "log/release_max_level_info", "tracing/max_level_trace", "tracing/release_max_level_info", ] @@ -60,7 +58,6 @@ const-str.workspace = true ctor.workspace = true dtor.workspace = true futures.workspace = true -log.workspace = true minicbor.workspace = true minicbor-serde.workspace = true rust-rocksdb.workspace = true diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index 8cc5c2975..18cc054a7 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -77,7 +77,6 @@ full = [ ] brotli_compression = [ - "conduwuit-api/brotli_compression", "conduwuit-core/brotli_compression", "conduwuit-router/brotli_compression", "conduwuit-service/brotli_compression", @@ -89,11 +88,10 @@ direct_tls = [ "conduwuit-router/direct_tls" ] element_hacks = [ - "conduwuit-api/element_hacks", "conduwuit-service/element_hacks", + "conduwuit-router/element_hacks", ] gzip_compression = [ - "conduwuit-api/gzip_compression", "conduwuit-core/gzip_compression", "conduwuit-router/gzip_compression", "conduwuit-service/gzip_compression", @@ -102,7 +100,7 @@ hardened_malloc = [ "conduwuit-core/hardened_malloc", ] http3 = [ - "reqwest/http3" + "conduwuit-service/http3" ] ring = [ "rustls/ring", @@ -110,14 +108,13 @@ ring = [ aws_lc_rs = [ "rustls/aws_lc_rs", - "dep:aws-lc-rs", ] io_uring = [ - "conduwuit-database/io_uring", + "conduwuit-service/io_uring", ] jemalloc = [ "conduwuit-core/jemalloc", - "conduwuit-database/jemalloc", + "conduwuit-service/jemalloc", ] jemalloc_prof = [ "conduwuit-core/jemalloc_prof", @@ -146,19 +143,13 @@ perf_measurements = [ release_max_log_level = [ "tracing/max_level_trace", "tracing/release_max_level_info", - "log/max_level_trace", - "log/release_max_level_info", - "conduwuit-admin/release_max_log_level", - "conduwuit-api/release_max_log_level", "conduwuit-core/release_max_log_level", - "conduwuit-database/release_max_log_level", "conduwuit-router/release_max_log_level", "conduwuit-service/release_max_log_level", ] sentry_telemetry = [ "dep:sentry", "dep:sentry-tracing", - "dep:sentry-tower", "conduwuit-core/sentry_telemetry", "conduwuit-router/sentry_telemetry", ] @@ -181,9 +172,7 @@ url_preview = [ "conduwuit-service/url_preview", ] zstd_compression = [ - "conduwuit-api/zstd_compression", "conduwuit-core/zstd_compression", - "conduwuit-database/zstd_compression", "conduwuit-router/zstd_compression", "conduwuit-service/zstd_compression", ] @@ -193,10 +182,10 @@ conduwuit_mods = [ bindgen-static = [ # "bindgen/static" # "clang-sys/static" - "conduwuit-database/bindgen-static" + "conduwuit-service/bindgen-static" ] bindgen-runtime = [ - "conduwuit-database/bindgen-runtime" + "conduwuit-service/bindgen-runtime" ] [build-dependencies] @@ -204,10 +193,7 @@ bindgen-runtime = [ # clang-sys = {version = "1", default-features = false} [dependencies] -conduwuit-admin.workspace = true -conduwuit-api.workspace = true conduwuit-core.workspace = true -conduwuit-database.workspace = true conduwuit-router.workspace = true conduwuit-service.workspace = true conduwuit-build-metadata.workspace = true @@ -219,7 +205,6 @@ dtor.workspace = true console-subscriber.optional = true console-subscriber.workspace = true const-str.workspace = true -log.workspace = true opentelemetry.workspace = true opentelemetry-otlp.optional = true opentelemetry-otlp.workspace = true @@ -227,14 +212,10 @@ opentelemetry-prometheus.workspace = true opentelemetry-semantic-conventions.workspace = true opentelemetry_sdk.workspace = true prometheus.workspace = true -sentry-tower.optional = true -sentry-tower.workspace = true sentry-tracing.optional = true sentry-tracing.workspace = true sentry.optional = true sentry.workspace = true -tokio-metrics.optional = true -tokio-metrics.workspace = true tokio.workspace = true tracing-flame.optional = true tracing-flame.workspace = true @@ -244,14 +225,7 @@ tracing-subscriber.workspace = true tracing.workspace = true tracing-journald = { workspace = true, optional = true } parking_lot.workspace = true -reqwest = { workspace = true, default-features = false } rustls = { workspace = true, default-features = false } -aws-lc-rs = { version = "1.19.0", default-features = false, optional = true } - - -[target.'cfg(all(not(target_env = "msvc"), target_os = "linux"))'.dependencies] -hardened_malloc-rs.workspace = true -hardened_malloc-rs.optional = true [lints] workspace = true diff --git a/src/router/Cargo.toml b/src/router/Cargo.toml index e1e66373a..aa0bc9aca 100644 --- a/src/router/Cargo.toml +++ b/src/router/Cargo.toml @@ -25,9 +25,11 @@ brotli_compression = [ ] direct_tls = [ "axum-server/tls-rustls-no-provider", - "dep:rustls", "dep:axum-server-dual-protocol", ] +element_hacks = [ + "conduwuit-api/element_hacks", +] gzip_compression = [ "conduwuit-admin/gzip_compression", "conduwuit-api/gzip_compression", @@ -71,13 +73,9 @@ release_max_log_level = [ "conduwuit-service/release_max_log_level", "tracing/max_level_trace", "tracing/release_max_level_info", - "log/max_level_trace", - "log/release_max_level_info", ] sentry_telemetry = [ "conduwuit-core/sentry_telemetry", - "dep:sentry", - "dep:sentry-tracing", "dep:sentry-tower", ] systemd = [ @@ -110,17 +108,9 @@ http.workspace = true http-body-util.workspace = true hyper.workspace = true hyper-util.workspace = true -log.workspace = true opentelemetry-instrumentation-tower.workspace = true ruma.workspace = true -rustls.workspace = true -rustls.optional = true -sentry.optional = true -sentry.workspace = true -sentry-tower.optional = true -sentry-tower.workspace = true -sentry-tracing.optional = true -sentry-tracing.workspace = true +sentry-tower = { workspace = true, optional = true } serde_json.workspace = true tokio.workspace = true tower.workspace = true diff --git a/src/service/Cargo.toml b/src/service/Cargo.toml index 6ff782c69..f35a40aaa 100644 --- a/src/service/Cargo.toml +++ b/src/service/Cargo.toml @@ -16,6 +16,12 @@ crate-type = [ ] [features] +bindgen-runtime = [ + "conduwuit-database/bindgen-runtime" +] +bindgen-static = [ + "conduwuit-database/bindgen-static" +] brotli_compression = [ "conduwuit-core/brotli_compression", "reqwest/brotli", @@ -29,6 +35,9 @@ gzip_compression = [ "conduwuit-core/gzip_compression", "reqwest/gzip", ] +http3 = [ + "reqwest/http3" +] io_uring = [ "conduwuit-database/io_uring", ] @@ -122,7 +131,8 @@ lettre.workspace = true resolvematrix.workspace = true serde_urlencoded.workspace = true openidconnect.workspace = true -# This is here to set features on the outdated openidconnect reqwest +# We use this to set TLS backend features on the outdated reqwest bundled by openidconnect, +# which is necessary to call `danger_accept_invalid_certs`. reqwest_0_12.workspace = true rand.workspace = true @@ -132,3 +142,6 @@ sd-notify.optional = true [lints] workspace = true + +[package.metadata.cargo-shear] +ignored = ["reqwest_0_12"] diff --git a/src/web/Cargo.toml b/src/web/Cargo.toml index 6b5d6c71c..dd7187de9 100644 --- a/src/web/Cargo.toml +++ b/src/web/Cargo.toml @@ -54,11 +54,11 @@ memory-serve = "2.4.0" workspace = true [package.metadata.cargo-shear] +# All of these dependencies are only used in Askama templates, +# which are transformed into Rust by a proc macro. +# cargo-shear can't see them because it doesn't expand macros. ignored = [ "conduwuit_build_metadata", "form_urlencoded", - "reqwest_recaptcha", "serde_json", - "tower-sessions-core", - "tracing", ] diff --git a/src/web/mod.rs b/src/web/mod.rs index 43dab6746..5593ac017 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -11,7 +11,8 @@ use axum::{ use conduwuit_service::{Services, state}; use tower_http::catch_panic::CatchPanicLayer; use tower_sec_fetch::SecFetchLayer; -use tower_sessions::{ExpiredDeletion, SessionManagerLayer, cookie::SameSite}; +use tower_sessions::{SessionManagerLayer, cookie::SameSite}; +use tower_sessions_core::ExpiredDeletion; use crate::{ pages::TemplateContext, diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 8309f1937..bbd903840 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -18,3 +18,8 @@ cargo_metadata = "0.23.1" [lints] workspace = true + +[package.metadata.cargo-shear] +# Task modules are linked by a macro that cargo-shear doesn't expand, +# so we tell it to ignore them specifically. +ignored-paths = ["src/tasks/*/mod.rs"] From 036809779170dc14959198cd526226a3dca8978f Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 20:07:54 +0000 Subject: [PATCH 142/342] fix(service/sending): Prevent panics and fix receipt limit in federation sender --- src/service/sending/sender.rs | 47 +++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index 0967abb38..5467b36f4 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -579,21 +579,21 @@ impl Service { since: (u64, u64), max_edu_count: &AtomicU64, ) -> Option { - let mut num = 0; + let num = AtomicUsize::new(0); let receipts: BTreeMap = self .services .state_cache .server_rooms(server_name) - .broad_filter_map(|room_id| async move { + .broad_filter_map(|room_id| async { + if num.load(Ordering::Relaxed) >= SELECT_RECEIPT_LIMIT { + return None; + } + let receipt_map = self - .select_edus_receipts_room(&room_id, since, max_edu_count, &mut num) + .select_edus_receipts_room(&room_id, since, max_edu_count, &num) .await; - receipt_map - .read - .is_empty() - .eq(&false) - .then_some((room_id, receipt_map)) + (!receipt_map.read.is_empty()).then_some((room_id, receipt_map)) }) .collect() .await; @@ -612,13 +612,17 @@ impl Service { } /// Look for read receipts in this room - #[tracing::instrument(name = "receipts", level = "trace", skip(self, since, max_edu_count))] + #[tracing::instrument( + name = "receipts", + level = "trace", + skip(self, since, max_edu_count, num) + )] async fn select_edus_receipts_room( &self, room_id: &RoomId, since: (u64, u64), max_edu_count: &AtomicU64, - num: &mut usize, + num: &AtomicUsize, ) -> ReceiptMap { let receipts = self .services @@ -647,24 +651,23 @@ impl Service { continue; }; - let (event_id, mut receipt) = r - .content - .0 - .into_iter() - .next() - .expect("we only use one event per read receipt"); + let Some((event_id, mut receipt)) = r.content.0.into_iter().next() else { + error!(%user_id, %count, "Empty content in read_receipts"); + continue; + }; - let receipt = receipt + let Some(receipt) = receipt .remove(&ReceiptType::Read) - .expect("our read receipts always set this") - .remove(&user_id) - .expect("our read receipts always have the user here"); + .and_then(|mut u| u.remove(&user_id)) + else { + error!(%user_id, %count, "Missing user receipt for ReceiptType::Read in read_receipts"); + continue; + }; let receipt_data = ReceiptData::new(receipt, vec![event_id]); if read.insert(user_id, receipt_data).is_none() { - *num = num.saturating_add(1); - if *num >= SELECT_RECEIPT_LIMIT { + if num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT { break; } } From be2f540a9dcd0290e75f4e6ba1096f839c9408c6 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 20:14:57 +0000 Subject: [PATCH 143/342] fix(client): Accurately include receipt senders in lazy loading --- src/api/client/message.rs | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/src/api/client/message.rs b/src/api/client/message.rs index 72b1b29e5..bcaf7cfe9 100644 --- a/src/api/client/message.rs +++ b/src/api/client/message.rs @@ -22,7 +22,7 @@ use conduwuit_service::{ }; use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture, pin_mut}; use ruma::{ - RoomId, UserId, + EventId, RoomId, UserId, api::{ Direction, client::{filter::RoomEventFilter, message::get_message_events}, @@ -30,8 +30,9 @@ use ruma::{ }, assign, events::{ - AnyStateEvent, StateEventType, + AnyStateEvent, StateEventType, SyncEphemeralRoomEvent, TimelineEventType::{self, *}, + receipt::ReceiptEventContent, }, serde::Raw, }; @@ -209,36 +210,32 @@ pub(crate) async fn lazy_loading_witness<'a, I>( where I: Iterator + Clone + Send, { - let oldest = events - .clone() - .map(|(count, _)| count) - .copied() - .min() - .unwrap_or_else(PduCount::max); - - let newest = events - .clone() - .map(|(count, _)| count) - .copied() - .max() - .unwrap_or_else(PduCount::max); + let chunk_event_ids: std::collections::HashSet<&EventId> = + events.clone().map(|(_, event)| event.event_id()).collect(); let receipts = services .rooms .read_receipt - .readreceipts_since(lazy_loading_context.room_id, Some(oldest.into_unsigned())); + .readreceipts_since(lazy_loading_context.room_id, None); pin_mut!(receipts); + let receipt_users = receipts.ready_filter_map(|(user_id, _, raw)| { + let event = + serde_json::from_str::>(raw.json().get()) + .ok()?; + event + .content + .keys() + .any(|id| chunk_event_ids.contains(&**id)) + .then_some(user_id) + }); + let witness: MemberSet = events .stream() .map(ref_at!(1)) .map(Event::sender) .map(ToOwned::to_owned) - .chain( - receipts - .ready_take_while(|(_, c, _)| *c <= newest.into_unsigned()) - .map(|(user_id, ..)| user_id), - ) + .chain(receipt_users) .collect() .await; From e0d3d12654c388768a6fb7ef29ac9c597ef835b1 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 20:18:16 +0000 Subject: [PATCH 144/342] fix(sync/v3): Pack room receipts into single m.receipt event --- src/api/client/sync/v3/joined.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/api/client/sync/v3/joined.rs b/src/api/client/sync/v3/joined.rs index d2e8a8909..b47753518 100644 --- a/src/api/client/sync/v3/joined.rs +++ b/src/api/client/sync/v3/joined.rs @@ -15,7 +15,7 @@ use conduwuit::{ }, warn, }; -use conduwuit_service::Services; +use conduwuit_service::{Services, rooms::read_receipt::pack_receipts}; use futures::{ FutureExt, StreamExt, TryFutureExt, future::{OptionFuture, join, join3, join4, try_join, try_join3}, @@ -243,9 +243,14 @@ async fn build_ephemeral( let (receipt_events, typing_event, private_read_event) = join3(receipt_events, typing_event, private_read_event).await; - let mut edus = receipt_events; + let mut all_receipts = receipt_events; + all_receipts.extend(private_read_event); + + let mut edus = Vec::new(); + if !all_receipts.is_empty() { + edus.push(pack_receipts(all_receipts.into_iter()).cast()); + } edus.extend(typing_event); - edus.extend(private_read_event); Ok(assign!(Ephemeral::new(), { events: edus })) } From 76ace2bc09783294596a70e862b9a0b8b2a3ee15 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 20:19:56 +0000 Subject: [PATCH 145/342] fix(client): Allow setting read receipts on backfilled events --- src/api/client/read_marker.rs | 14 +++----------- src/service/rooms/read_receipt/mod.rs | 5 ++--- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/src/api/client/read_marker.rs b/src/api/client/read_marker.rs index 2f8b21a39..1d96f05d2 100644 --- a/src/api/client/read_marker.rs +++ b/src/api/client/read_marker.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; use axum::extract::State; -use conduwuit::{Err, PduCount, Result, err}; +use conduwuit::{Err, Result, err}; use ruma::{ MilliSecondsSinceUnixEpoch, api::client::{read_marker::set_read_marker, receipt::create_receipt}, @@ -94,11 +94,7 @@ pub(crate) async fn set_read_marker_route( .await .map_err(|_| err!(Request(NotFound("Event not found."))))?; - let PduCount::Normal(count) = count else { - return Err!(Request(InvalidParam( - "Event is a backfilled PDU and cannot be marked as read." - ))); - }; + let count = count.into_unsigned(); services .rooms @@ -192,11 +188,7 @@ pub(crate) async fn create_receipt_route( .await .map_err(|_| err!(Request(NotFound("Event not found."))))?; - let PduCount::Normal(count) = count else { - return Err!(Request(InvalidParam( - "Event is a backfilled PDU and cannot be marked as read." - ))); - }; + let count = count.into_unsigned(); services .rooms diff --git a/src/service/rooms/read_receipt/mod.rs b/src/service/rooms/read_receipt/mod.rs index 2815828fd..097c22b22 100644 --- a/src/service/rooms/read_receipt/mod.rs +++ b/src/service/rooms/read_receipt/mod.rs @@ -93,7 +93,7 @@ impl Service { }); let (pdu_count, shortroomid) = try_join!(pdu_count, shortroomid)?; - let shorteventid = PduCount::Normal(pdu_count); + let shorteventid = PduCount::from_unsigned(pdu_count); let pdu_id: RawPduId = PduId { shortroomid, shorteventid }.into(); let pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await?; @@ -101,8 +101,7 @@ impl Service { let user_id: OwnedUserId = user_id.to_owned(); let mut receipt = ruma::events::receipt::Receipt::default(); - // TODO: start storing the timestamp so we can return one - receipt.ts = None; + receipt.ts = Some(pdu.origin_server_ts()); receipt.thread = ruma::events::receipt::ReceiptThread::Unthreaded; let content: BTreeMap = BTreeMap::from_iter([( From 61a50a627b3499d02fce76fab1c476f644777f27 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 20:22:49 +0000 Subject: [PATCH 146/342] fix(client): Add membership checks to read markers --- src/api/client/read_marker.rs | 82 ++++++++++++++++++++++------------- 1 file changed, 53 insertions(+), 29 deletions(-) diff --git a/src/api/client/read_marker.rs b/src/api/client/read_marker.rs index 1d96f05d2..aeacd9adc 100644 --- a/src/api/client/read_marker.rs +++ b/src/api/client/read_marker.rs @@ -8,7 +8,7 @@ use ruma::{ events::{ RoomAccountDataEventType, fully_read::{FullyReadEvent, FullyReadEventContent}, - receipt::{Receipt, ReceiptEvent, ReceiptEventContent, ReceiptType}, + receipt::{Receipt, ReceiptEvent, ReceiptEventContent, ReceiptThread, ReceiptType}, }, }; @@ -27,6 +27,15 @@ pub(crate) async fn set_read_marker_route( ) -> Result { let sender_user = body.identity.expect_sender_user()?; + if !services + .rooms + .state_cache + .is_joined(sender_user, &body.room_id) + .await + { + return Err!(Request(Forbidden("You are not in this room."))); + } + if let Some(event) = &body.fully_read { let fully_read_event = FullyReadEvent::new(FullyReadEventContent::new(event.to_owned())); @@ -92,9 +101,8 @@ pub(crate) async fn set_read_marker_route( .timeline .get_pdu_count(event) .await - .map_err(|_| err!(Request(NotFound("Event not found."))))?; - - let count = count.into_unsigned(); + .map_err(|_| err!(Request(NotFound("Event not found."))))? + .into_unsigned(); services .rooms @@ -118,11 +126,26 @@ pub(crate) async fn create_receipt_route( ) -> Result { let sender_user = body.identity.expect_sender_user()?; + if !services + .rooms + .state_cache + .is_joined(sender_user, &body.room_id) + .await + { + return Err!(Request(Forbidden("You are not in this room."))); + } + services .users .update_device_last_seen(sender_user, body.identity.sender_device(), client_ip) .await; + if body.receipt_type == create_receipt::v3::ReceiptType::FullyRead + && body.thread != ReceiptThread::Unthreaded + { + return Err!(Request(InvalidParam("thread_id cannot be specified for m.fully_read"))); + } + if matches!( &body.receipt_type, create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate @@ -155,40 +178,41 @@ pub(crate) async fn create_receipt_route( ) .await?; }, - | create_receipt::v3::ReceiptType::Read => { - let receipt_content = [( - body.event_id.clone(), - BTreeMap::from_iter([( - ReceiptType::Read, + | create_receipt::v3::ReceiptType::Read => + if services.config.allow_local_read_receipts + && !services.users.is_suspended(sender_user).await? + { + let mut receipt = Receipt::new(MilliSecondsSinceUnixEpoch::now()); + receipt.thread = body.thread.clone(); + let receipt_content = [( + body.event_id.clone(), BTreeMap::from_iter([( - sender_user.to_owned(), - Receipt::new(MilliSecondsSinceUnixEpoch::now()), + ReceiptType::Read, + BTreeMap::from_iter([(sender_user.to_owned(), receipt)]), )]), - )]), - )]; + )]; - services - .rooms - .read_receipt - .readreceipt_update( - sender_user, - &body.room_id, - ReceiptEvent::new( - body.room_id.clone(), - ReceiptEventContent::from_iter(receipt_content), - ), - ) - .await; - }, + services + .rooms + .read_receipt + .readreceipt_update( + sender_user, + &body.room_id, + ReceiptEvent::new( + body.room_id.clone(), + ReceiptEventContent::from_iter(receipt_content), + ), + ) + .await; + }, | create_receipt::v3::ReceiptType::ReadPrivate => { let count = services .rooms .timeline .get_pdu_count(&body.event_id) .await - .map_err(|_| err!(Request(NotFound("Event not found."))))?; - - let count = count.into_unsigned(); + .map_err(|_| err!(Request(NotFound("Event not found."))))? + .into_unsigned(); services .rooms From c7aebd2b525fe46b9fea095bced76708944edf7f Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 20:28:40 +0000 Subject: [PATCH 147/342] fix: Deduplicate read receipts and preserve per-thread state --- src/api/server/send.rs | 36 +++++-------- src/service/rooms/read_receipt/data.rs | 75 +++++++++++++++++++++++--- src/service/rooms/read_receipt/mod.rs | 9 +++- 3 files changed, 90 insertions(+), 30 deletions(-) diff --git a/src/api/server/send.rs b/src/api/server/send.rs index 0a384717f..20da3572c 100644 --- a/src/api/server/send.rs +++ b/src/api/server/send.rs @@ -581,28 +581,20 @@ async fn handle_edu_receipt_room_user( } let data = &user_updates.data; - user_updates - .event_ids - .into_iter() - .stream() - .for_each_concurrent(automatic_width(), |event_id| async move { - let user_data = [(user_id.to_owned(), data.clone())]; - let receipts = [(ReceiptType::Read, BTreeMap::from(user_data))]; - let content = [(event_id.clone(), BTreeMap::from(receipts))]; - services - .rooms - .read_receipt - .readreceipt_update( - user_id, - room_id, - ReceiptEvent::new( - room_id.to_owned(), - ReceiptEventContent::from_iter(content), - ), - ) - .await; - }) - .await; + for event_id in user_updates.event_ids { + let user_data = [(user_id.to_owned(), data.clone())]; + let receipts = [(ReceiptType::Read, BTreeMap::from(user_data))]; + let content = [(event_id, BTreeMap::from(receipts))]; + services + .rooms + .read_receipt + .readreceipt_update( + user_id, + room_id, + ReceiptEvent::new(room_id.to_owned(), ReceiptEventContent::from_iter(content)), + ) + .await; + } } async fn handle_edu_typing(services: &Services, origin: &ServerName, typing: TypingContent) { diff --git a/src/service/rooms/read_receipt/data.rs b/src/service/rooms/read_receipt/data.rs index bcffd708c..3464d4c33 100644 --- a/src/service/rooms/read_receipt/data.rs +++ b/src/service/rooms/read_receipt/data.rs @@ -45,20 +45,67 @@ impl Data { user_id: &UserId, room_id: &RoomId, event: &ReceiptEvent, - ) { - // Remove old entry + ) -> bool { + let new_target = event.content.0.iter().find_map(|(ev_id, types)| { + types + .iter() + .find_map(|(rtype, users)| users.get(user_id).map(|r| (ev_id, rtype, &r.thread))) + }); + + // Find old entries for this user in this room let last_possible_key = (room_id, u64::MAX); + let mut keys = Vec::new(); self.readreceiptid_readreceipt .rev_keys_from_raw(&last_possible_key) .ignore_err() .ready_take_while(|key| key.starts_with(room_id.as_bytes())) - .ready_filter_map(|key| key.ends_with(user_id.as_bytes()).then_some(key)) - .ready_for_each(|key| self.readreceiptid_readreceipt.del(key)) + .ready_filter_map(|key| key.ends_with(user_id.as_bytes()).then(|| key.to_vec())) + .ready_for_each(|key| keys.push(key)) .await; + let mut to_del = Vec::new(); + let mut is_dup = false; + + for key in keys { + if let Ok(val) = self.readreceiptid_readreceipt.get(&key).await { + if let Ok(existing) = serde_json::from_slice::(&val) { + let existing_target = existing.content.0.iter().find_map(|(ev_id, types)| { + types.iter().find_map(|(rtype, users)| { + users.get(user_id).map(|r| (ev_id, rtype, &r.thread)) + }) + }); + + if let (Some(new_t), Some(old_t)) = (new_target, existing_target) { + if new_t.1 == old_t.1 && new_t.2 == old_t.2 { + if new_t.0 == old_t.0 { + is_dup = true; + } else { + to_del.push(key); + } + } + } else { + to_del.push(key); + } + } else { + to_del.push(key); + } + } else { + to_del.push(key); + } + } + + if is_dup { + return false; + } + + for key in to_del { + self.readreceiptid_readreceipt.del(&key); + } + let count = self.services.globals.next_count().unwrap(); let latest_id = (room_id, count, user_id); self.readreceiptid_readreceipt.put(latest_id, Json(event)); + true } pub(super) fn readreceipts_since<'a>( @@ -86,12 +133,28 @@ impl Data { .ignore_err() } - pub(super) fn private_read_set(&self, room_id: &RoomId, user_id: &UserId, pdu_count: u64) { + pub(super) async fn private_read_set( + &self, + room_id: &RoomId, + user_id: &UserId, + pdu_count: u64, + ) -> bool { let key = (room_id, user_id); - let next_count = self.services.globals.next_count().unwrap(); + if let Ok(current) = self + .roomuserid_privateread + .qry(&key) + .await + .deserialized::() + { + if current == pdu_count { + return false; + } + } + let next_count = self.services.globals.next_count().unwrap(); self.roomuserid_privateread.put(key, pdu_count); self.roomuserid_lastprivatereadupdate.put(key, next_count); + true } pub(super) async fn private_read_get_count( diff --git a/src/service/rooms/read_receipt/mod.rs b/src/service/rooms/read_receipt/mod.rs index 097c22b22..c463e264e 100644 --- a/src/service/rooms/read_receipt/mod.rs +++ b/src/service/rooms/read_receipt/mod.rs @@ -65,7 +65,10 @@ impl Service { room_id: &RoomId, event: ReceiptEvent, ) { - self.db.readreceipt_update(user_id, room_id, &event).await; + if !self.db.readreceipt_update(user_id, room_id, &event).await { + return; + } + self.services.sync.wake_all_joined(room_id).await; // update appservices let edu = EphemeralData::Receipt(event); @@ -142,7 +145,9 @@ impl Service { event_id: &EventId, count: u64, ) { - self.db.private_read_set(room_id, user_id, count); + if !self.db.private_read_set(room_id, user_id, count).await { + return; + } // update appservices matching the user's namespace (MSC2409) let receipt_content = [( From f42955602ed8277cb31597c8ec88f605061f8893 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 8 Nov 2026 20:33:42 +0000 Subject: [PATCH 148/342] test: Add unit test for merging threaded and private receipts --- src/service/rooms/read_receipt/mod.rs | 50 +++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/service/rooms/read_receipt/mod.rs b/src/service/rooms/read_receipt/mod.rs index c463e264e..346120d8b 100644 --- a/src/service/rooms/read_receipt/mod.rs +++ b/src/service/rooms/read_receipt/mod.rs @@ -271,4 +271,54 @@ mod tests { assert!(users.contains_key(user_id!("@alice:example.org"))); assert!(users.contains_key(user_id!("@bob:example.org"))); } + + #[test] + fn pack_receipts_merges_threaded_and_private_receipts() { + let event_a: OwnedEventId = "$event_a:example.org".try_into().expect("valid event ID"); + let event_b: OwnedEventId = "$event_b:example.org".try_into().expect("valid event ID"); + + let mut public_threaded_receipt = Receipt::default(); + public_threaded_receipt.thread = ruma::events::receipt::ReceiptThread::Main; + + let r1_content = ReceiptEventContent::from_iter([( + event_a.clone(), + BTreeMap::from([( + ReceiptType::Read, + BTreeMap::from([( + user_id!("@alice:example.org").to_owned(), + public_threaded_receipt, + )]), + )]), + )]); + let r1: Raw = Raw::from_json( + serde_json::value::to_raw_value(&SyncEphemeralRoomEvent::new(r1_content)).unwrap(), + ); + + let mut private_receipt = Receipt::default(); + private_receipt.thread = ruma::events::receipt::ReceiptThread::Unthreaded; + let r2_content = ReceiptEventContent::from_iter([( + event_b.clone(), + BTreeMap::from([( + ReceiptType::ReadPrivate, + BTreeMap::from([(user_id!("@alice:example.org").to_owned(), private_receipt)]), + )]), + )]); + let r2: Raw = Raw::from_json( + serde_json::value::to_raw_value(&SyncEphemeralRoomEvent::new(r2_content)).unwrap(), + ); + + let packed = pack_receipts([r1, r2].into_iter()); + let packed: SyncEphemeralRoomEvent = + serde_json::from_str(packed.json().get()).expect("packed receipt is valid"); + + assert_eq!( + packed.content[&event_a][&ReceiptType::Read][user_id!("@alice:example.org")].thread, + ruma::events::receipt::ReceiptThread::Main + ); + assert_eq!( + packed.content[&event_b][&ReceiptType::ReadPrivate][user_id!("@alice:example.org")] + .thread, + ruma::events::receipt::ReceiptThread::Unthreaded + ); + } } From e21d86161ce41812fbed10987321882f6fb5c52e Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Tue, 10 Nov 2026 16:37:32 +0000 Subject: [PATCH 149/342] chore: Add changelog --- changelog.d/2481.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2481.bugfix.md diff --git a/changelog.d/2481.bugfix.md b/changelog.d/2481.bugfix.md new file mode 100644 index 000000000..f0da8f388 --- /dev/null +++ b/changelog.d/2481.bugfix.md @@ -0,0 +1 @@ +Read receipts are now more spec compliant, will work better in threads and are less likely to end up causing loops with other software. Contributed by @Jade From 88441a409a1b6b4613fcb904381c8847b3c44f56 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Tue, 10 Nov 2026 17:16:35 +0000 Subject: [PATCH 150/342] refactor(rooms/timeline): Simplify deduplication of read receipts --- src/service/rooms/read_receipt/data.rs | 69 ++++++++++++-------------- 1 file changed, 31 insertions(+), 38 deletions(-) diff --git a/src/service/rooms/read_receipt/data.rs b/src/service/rooms/read_receipt/data.rs index 3464d4c33..496e76ece 100644 --- a/src/service/rooms/read_receipt/data.rs +++ b/src/service/rooms/read_receipt/data.rs @@ -8,7 +8,10 @@ use database::{Deserialized, Json, Map}; use futures::{Stream, StreamExt}; use ruma::{ CanonicalJsonObject, OwnedRoomId, OwnedUserId, RoomId, UserId, - events::{AnySyncEphemeralRoomEvent, receipt::ReceiptEvent}, + events::{ + AnySyncEphemeralRoomEvent, + receipt::{ReceiptEvent, ReceiptType}, + }, serde::Raw, }; @@ -46,58 +49,48 @@ impl Data { room_id: &RoomId, event: &ReceiptEvent, ) -> bool { - let new_target = event.content.0.iter().find_map(|(ev_id, types)| { - types - .iter() - .find_map(|(rtype, users)| users.get(user_id).map(|r| (ev_id, rtype, &r.thread))) - }); + let Some((new_event, new_receipt)) = + event.content.user_receipt(user_id, ReceiptType::Read) + else { + return false; + }; // Find old entries for this user in this room let last_possible_key = (room_id, u64::MAX); - let mut keys = Vec::new(); + let mut old_entries = Vec::new(); self.readreceiptid_readreceipt - .rev_keys_from_raw(&last_possible_key) + .rev_stream_from_raw(&last_possible_key) .ignore_err() - .ready_take_while(|key| key.starts_with(room_id.as_bytes())) - .ready_filter_map(|key| key.ends_with(user_id.as_bytes()).then(|| key.to_vec())) - .ready_for_each(|key| keys.push(key)) + .ready_take_while(|(key, _)| key.starts_with(room_id.as_bytes())) + .ready_filter_map(|(key, val)| { + key.ends_with(user_id.as_bytes()) + .then(|| (key.to_vec(), serde_json::from_slice::(val).ok())) + }) + .ready_for_each(|entry| old_entries.push(entry)) .await; let mut to_del = Vec::new(); - let mut is_dup = false; - for key in keys { - if let Ok(val) = self.readreceiptid_readreceipt.get(&key).await { - if let Ok(existing) = serde_json::from_slice::(&val) { - let existing_target = existing.content.0.iter().find_map(|(ev_id, types)| { - types.iter().find_map(|(rtype, users)| { - users.get(user_id).map(|r| (ev_id, rtype, &r.thread)) - }) - }); + for (key, existing) in old_entries { + let Some(existing) = existing else { + to_del.push(key); + continue; + }; + let Some((old_event, old_receipt)) = + existing.content.user_receipt(user_id, ReceiptType::Read) + else { + to_del.push(key); + continue; + }; - if let (Some(new_t), Some(old_t)) = (new_target, existing_target) { - if new_t.1 == old_t.1 && new_t.2 == old_t.2 { - if new_t.0 == old_t.0 { - is_dup = true; - } else { - to_del.push(key); - } - } - } else { - to_del.push(key); - } - } else { - to_del.push(key); + if old_receipt.thread == new_receipt.thread { + if old_event == new_event { + return false; } - } else { to_del.push(key); } } - if is_dup { - return false; - } - for key in to_del { self.readreceiptid_readreceipt.del(&key); } From 23a3ada3939609eda924e4d9f78d76ebabf98f1f Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 10 Nov 2026 20:39:07 +0000 Subject: [PATCH 151/342] fix: SEC36 Reviewed-By: Jacob Taylor Reviewed-By: Jade Ellis Reviewed-By: Ginger --- src/api/client/keys.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/api/client/keys.rs b/src/api/client/keys.rs index c9a002804..d48bfdb3e 100644 --- a/src/api/client/keys.rs +++ b/src/api/client/keys.rs @@ -523,7 +523,22 @@ where for (server, response) in futures { match response { | Ok(response) => { - for (user, master_key) in response.master_keys { + let is_wanted = |user_id: &UserId| { + user_id.server_name() == server && device_keys_input.contains_key(user_id) + }; + let filtered_master_keys = response + .master_keys + .into_iter() + .filter(|(user_id, _)| is_wanted(user_id)); + let filtered_self_signing_keys = response + .self_signing_keys + .into_iter() + .filter(|(user_id, _)| is_wanted(user_id)); + let filtered_device_keys = response + .device_keys + .into_iter() + .filter(|(user_id, _)| is_wanted(user_id)); + for (user, master_key) in filtered_master_keys { let (master_key_id, mut master_key) = parse_master_key(&user, &master_key)?; if let Ok(our_master_key) = services @@ -549,8 +564,8 @@ where } } - self_signing_keys.extend(response.self_signing_keys); - device_keys.extend(response.device_keys); + self_signing_keys.extend(filtered_self_signing_keys); + device_keys.extend(filtered_device_keys); }, | Err(e) => { failures.insert(server.to_string(), json!({ "error": e.to_string() })); From b2b9c79927600594360baad85aee74477b410380 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 10 Nov 2026 20:40:28 +0000 Subject: [PATCH 152/342] fix: SEC39 Reviewed-By: timedout Co-Authored-By: Ginger --- src/service/rooms/threads/mod.rs | 151 +++++++++++++++++++++------ src/service/rooms/timeline/redact.rs | 28 ++++- 2 files changed, 142 insertions(+), 37 deletions(-) diff --git a/src/service/rooms/threads/mod.rs b/src/service/rooms/threads/mod.rs index a29ca5511..fa0956abe 100644 --- a/src/service/rooms/threads/mod.rs +++ b/src/service/rooms/threads/mod.rs @@ -3,7 +3,10 @@ use std::{collections::BTreeMap, sync::Arc}; use conduwuit::result::LogErr; use conduwuit_core::{ Event, Result, err, - matrix::pdu::{PduCount, PduEvent, PduId, RawPduId}, + matrix::{ + event::RelationTypeEqual, + pdu::{PduCount, PduEvent, PduId, RawPduId}, + }, utils::{ ReadyExt, stream::{TryIgnore, WidebandExt}, @@ -12,9 +15,14 @@ use conduwuit_core::{ use conduwuit_database::{Deserialized, Map}; use futures::{Stream, StreamExt}; use ruma::{ - CanonicalJsonValue, EventId, OwnedUserId, RoomId, UserId, - api::client::threads::get_threads::v1::IncludeThreads, events::relation::BundledThread, - serde::Raw, uint, + CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedUserId, RoomId, UInt, UserId, + api::{Direction, client::threads::get_threads::v1::IncludeThreads}, + events::{ + AnySyncMessageLikeEvent, AnySyncTimelineEvent, + relation::{BundledThread, RelationType}, + }, + serde::Raw, + uint, }; use serde_json::json; @@ -27,6 +35,7 @@ pub struct Service { struct Services { short: Dep, + pdu_metadata: Dep, timeline: Dep, } @@ -42,6 +51,7 @@ impl crate::Service for Service { }, services: Services { short: args.depend::("rooms::short"), + pdu_metadata: args.depend::("rooms::pdu_metadata"), timeline: args.depend::("rooms::timeline"), }, })) @@ -51,6 +61,88 @@ impl crate::Service for Service { } impl Service { + /// Serializes an event for the `latest_event` of a thread's aggregation, + /// stripping `unsigned` as we don't want to send e.g. txnid to clients. + fn latest_event(event: &E) -> Raw + where + E: Event, + { + let mut latest_pdu = event.clone().into_pdu(); + latest_pdu.unsigned = None; + latest_pdu + .into_format::>() + .cast_unchecked() + } + + fn set_thread(unsigned: &mut CanonicalJsonObject, thread: BundledThread) { + let content = serde_json::to_value(thread).expect("to_value always works"); + unsigned.insert( + "m.relations".to_owned(), + json!({ "m.thread": content }) + .try_into() + .expect("thread is valid json"), + ); + } + + /// Remove `event` from the aggregation of the thread matching + /// `root_event_id` + pub async fn remove_from_thread(&self, root_event_id: &EventId, event: &E) -> Result + where + E: Event + Send + Sync, + { + let Ok(root_id) = self.services.timeline.get_pdu_id(root_event_id).await else { + return Ok(()); + }; + + let mut root_pdu_json = self + .services + .timeline + .get_pdu_json_from_id(&root_id) + .await + .map_err(|e| err!(Database("Thread root pdu not found: {e:?}")))?; + + let Some(CanonicalJsonValue::Object(unsigned)) = root_pdu_json.get_mut("unsigned") else { + return Ok(()); + }; + + let thread: Vec<_> = self + .services + .pdu_metadata + .get_relations( + event.sender(), + &event.room_id_or_hash(), + root_event_id, + PduCount::max(), + usize::MAX, + 0, + Direction::Backward, + ) + .await + .into_iter() + .filter(|(_, pdu)| RelationType::Thread.relation_type_equal(pdu)) + .collect(); + + match thread.first() { + | Some((_, latest)) => Self::set_thread( + unsigned, + BundledThread::new( + Self::latest_event(latest), + thread.len().try_into().unwrap_or(UInt::MAX), + true, + ), + ), + | None => { + // No events are left in the thread, or the root is backfilled + unsigned.remove("m.relations"); + }, + } + + self.services + .timeline + .replace_pdu(&root_id, &root_pdu_json) + .await + } + pub async fn add_to_thread(&self, root_event_id: &EventId, event: &E) -> Result where E: Event + Send + Sync, @@ -78,11 +170,20 @@ impl Service { .await .map_err(|e| err!(Request(InvalidParam("Thread root pdu not found: {e:?}"))))?; - if let CanonicalJsonValue::Object(unsigned) = root_pdu_json - .entry("unsigned".to_owned()) - .or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default())) + // get_relations doesn't support backfilled targets, so redactions + // couldn't update the aggregation of a backfilled root + // + // TODO: Support backfilled threads. This needs + // `src/service/rooms/pdu_metadata/mod.rs`'s + // (TODO: Relations with backfilled pdus) to be implemented, + // and then this check can be removed. + if matches!(root_id.pdu_count(), PduCount::Normal(_)) + && let CanonicalJsonValue::Object(unsigned) = root_pdu_json + .entry("unsigned".to_owned()) + .or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default())) { - if let Some(mut relations) = unsigned + let latest_event = Self::latest_event(event); + let thread = match unsigned .get("m.relations") .and_then(|r| r.as_object()) .and_then(|r| r.get("m.thread")) @@ -90,34 +191,16 @@ impl Service { serde_json::from_value::(relations.clone().into()).ok() }) { // Thread already existed - relations.count = relations.count.saturating_add(uint!(1)); - relations.latest_event = Raw::from_json(event.content().to_owned()); - - let content = serde_json::to_value(relations).expect("to_value always works"); - - unsigned.insert( - "m.relations".to_owned(), - json!({ "m.thread": content }) - .try_into() - .expect("thread is valid json"), - ); - } else { + | Some(mut thread) => { + thread.count = thread.count.saturating_add(uint!(1)); + thread.latest_event = latest_event; + thread + }, // New thread - let relations = BundledThread::new( - Raw::from_json(event.content().to_owned()), - uint!(1), - true, - ); + | None => BundledThread::new(latest_event, uint!(1), true), + }; - let content = serde_json::to_value(relations).expect("to_value always works"); - - unsigned.insert( - "m.relations".to_owned(), - json!({ "m.thread": content }) - .try_into() - .expect("thread is valid json"), - ); - } + Self::set_thread(unsigned, thread); self.services .timeline diff --git a/src/service/rooms/timeline/redact.rs b/src/service/rooms/timeline/redact.rs index efa19dff5..92e91cffb 100644 --- a/src/service/rooms/timeline/redact.rs +++ b/src/service/rooms/timeline/redact.rs @@ -2,10 +2,11 @@ use conduwuit_core::{ Result, err, matrix::event::Event, utils::{self}, + warn, }; -use ruma::EventId; +use ruma::{EventId, events::room::encrypted::Relation}; -use super::ExtractBody; +use super::{ExtractBody, ExtractRelatesTo}; use crate::rooms::short::ShortRoomId; impl super::Service { @@ -31,6 +32,12 @@ impl super::Service { err!(Database(error!(?pdu_id, %event_id, ?e, "PDU ID points to invalid PDU."))) })?; + let thread_root = match pdu.get_content::() { + | Ok(ExtractRelatesTo { relates_to: Relation::Thread(thread) }) => + Some(thread.event_id), + | _ => None, + }; + if let Ok(content) = pdu.get_content::() { if let Some(body) = content.body { self.services @@ -51,6 +58,21 @@ impl super::Service { err!(Database(error!(%event_id, ?e, "Failed to convert PDU to canonical JSON"))) })?; - self.replace_pdu(&pdu_id, &obj).await + self.replace_pdu(&pdu_id, &obj).await?; + + // So the thread's root doesn't keep the original content in its + // `latest_event` aggregation + if let Some(thread_root) = thread_root { + self.services + .threads + .remove_from_thread(&thread_root, &pdu) + .await + .inspect_err(|e| { + warn!("Failed to remove redacted event from thread {thread_root}: {e:?}"); + }) + .ok(); + } + + Ok(()) } } From 7a6bea70b2be67d7ae9acef479262b401b28db03 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 10 Nov 2026 20:41:19 +0000 Subject: [PATCH 153/342] fix: SEC34 Reviewed-By: Jade Ellis Reviewed-By: Ginger Reviewed-By: Jacob Taylor --- src/api/server/invite.rs | 1 - src/core/matrix/state_res/event_auth.rs | 311 ++++++++++++++---- src/core/matrix/state_res/mod.rs | 10 +- src/service/rooms/event_handler/pdu_checks.rs | 14 +- src/service/rooms/membership/mod.rs | 1 - src/service/rooms/timeline/create.rs | 13 +- src/web/pages/account/register.rs | 2 + 7 files changed, 258 insertions(+), 94 deletions(-) diff --git a/src/api/server/invite.rs b/src/api/server/invite.rs index 06ee9f2b1..a72aceac3 100644 --- a/src/api/server/invite.rs +++ b/src/api/server/invite.rs @@ -421,7 +421,6 @@ async fn validate_invite_create_event( if !state_res::auth_check( room_version_rules, pdu, - None, |_, _| async { unreachable!("No state should be fetched when processing a lone create event"); }, diff --git a/src/core/matrix/state_res/event_auth.rs b/src/core/matrix/state_res/event_auth.rs index e5693cf78..b5d719742 100644 --- a/src/core/matrix/state_res/event_auth.rs +++ b/src/core/matrix/state_res/event_auth.rs @@ -5,17 +5,21 @@ use futures::{ future::{OptionFuture, join, join3}, }; use ruma::{ - Int, OwnedUserId, RoomVersionId, UserId, + AnyKeyName, CanonicalJsonObject, Int, OwnedUserId, RoomVersionId, SigningKeyId, UserId, events::room::{ join_rules::{JoinRule, RoomJoinRulesEventContent}, - member::{MembershipState, ThirdPartyInvite}, + member::MembershipState, power_levels::{RoomPowerLevelsEventContent, UserPowerLevel}, + third_party_invite::PublicKey, }, int, room_version_rules::{RoomIdFormatVersion, RoomVersionRules}, - serde::Raw, + serde::{Raw, base64, base64::Standard}, + signatures, + signatures::to_canonical_json_string_for_signing, + third_party_invite::IdentityServerBase64PublicKey, }; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::{from_str as from_json_str, value::RawValue as RawJsonValue}; use super::{ @@ -25,7 +29,7 @@ use super::{ deserialize_power_levels_content_redact, }, }; -use crate::{debug, error, trace, warn}; +use crate::{debug, err, error, trace, warn}; // FIXME: field extracting could be bundled for `content` #[derive(Deserialize)] @@ -48,6 +52,40 @@ struct RoomCreateContentFields { federate: bool, } +// Workaround for https://github.com/matrix-org/matrix-spec/issues/2471 +#[derive(Deserialize, Debug)] +struct RoomThirdPartyInviteContentFields { + public_key: Option, + public_keys: Option>, +} + +// same here sort of (maintainers see https://forgejo.ellis.link/continuwuation/continuwuity-sec/issues/41) +#[derive(Deserialize, Debug)] +struct MemberThirdPartyInviteSignedContent { + signed: ThirdPartyInviteSignedObject, +} + +#[derive(Serialize, Deserialize, Debug)] +struct ThirdPartyInviteSignedObject(CanonicalJsonObject); + +impl ThirdPartyInviteSignedObject { + #[inline] + fn mxid(&self) -> Option { + self.0 + .get("mxid")? + .as_str() + .and_then(|raw| UserId::parse(raw).ok()) + } + + #[inline] + fn token(&self) -> Option<&str> { self.0.get("token")?.as_str() } + + #[inline] + fn signatures(&self) -> Option { + self.0.get("signatures")?.as_object().map(ToOwned::to_owned) + } +} + /// For the given event `kind` what are the relevant auth events that are needed /// to authenticate this `content`. /// @@ -61,7 +99,7 @@ pub fn auth_types_for_event( state_key: Option<&str>, content: &RawJsonValue, room_version: &RoomVersionRules, -) -> serde_json::Result> { +) -> crate::Result> { if kind == &TimelineEventType::RoomCreate { return Ok(vec![]); } @@ -84,7 +122,7 @@ pub fn auth_types_for_event( #[allow(unused)] struct RoomMemberContentFields { membership: Option>, - third_party_invite: Option>, + third_party_invite: Option>, join_authorised_via_users_server: Option>, } @@ -116,16 +154,24 @@ pub fn auth_types_for_event( auth_types.push(key); } - // TODO: restore this once 3pid support isn't broken - // if membership == MembershipState::Invite { - // if let Some(Ok(t_id)) = content.third_party_invite.map(|t| - // t.deserialize()) { let key = - // (StateEventType::RoomThirdPartyInvite, - // t_id.signed.token.into()); if !auth_types.contains(& - // key) { auth_types.push(key); - // } - // } - // } + if membership == MembershipState::Invite { + if let Some(Ok(t_id)) = content.third_party_invite.map(|t| t.deserialize()) { + let key = ( + StateEventType::RoomThirdPartyInvite, + t_id.signed + .token() + .ok_or_else(|| { + err!(Request(BadJson( + "Third party invite content missing a token" + ))) + })? + .into(), + ); + if !auth_types.contains(&key) { + auth_types.push(key); + } + } + } } } } @@ -179,12 +225,11 @@ fn get_user_power_level( pub async fn auth_check( room_version: &RoomVersionRules, incoming_event: &E, - current_third_party_invite: Option<&E>, fetch_state: F, create_event: &E, ) -> Result where - F: Fn(&StateEventType, &str) -> Fut + Send, + F: Fn(&StateEventType, &str) -> Fut + Send + Copy, Fut: Future> + Send, E: Event + Send + Sync, for<'a> &'a E: Event + Send, @@ -444,13 +489,15 @@ where sender, sender_member_event.as_ref(), incoming_event, - current_third_party_invite, + fetch_state, power_levels_event.as_ref(), join_rules_event.as_ref(), user_for_join_auth.as_deref(), &user_for_join_auth_membership, &room_create_event, - )? { + ) + .await? + { return Ok(false); } @@ -639,14 +686,14 @@ where /// event and the current State. #[allow(clippy::too_many_arguments)] #[allow(clippy::cognitive_complexity)] -fn valid_membership_change( +async fn valid_membership_change( room_version: &RoomVersionRules, target_user: &UserId, target_user_membership_event: Option<&E>, sender: &UserId, sender_membership_event: Option<&E>, current_event: &E, - current_third_party_invite: Option<&E>, + fetch_state: F, power_levels_event: Option<&E>, join_rules_event: Option<&E>, user_for_join_auth: Option<&UserId>, @@ -655,11 +702,13 @@ fn valid_membership_change( ) -> Result where E: Event + Send + Sync, + F: Fn(&StateEventType, &str) -> Fut + Send + Copy, + Fut: Future> + Send, for<'a> &'a E: Event + Send, { #[derive(Deserialize)] struct GetThirdPartyInvite { - third_party_invite: Option>, + third_party_invite: Option>, } let create_content = from_json_str::(create_room.content().get())?; let creator = if room_version.authorization.use_room_create_sender { @@ -901,22 +950,18 @@ where | MembershipState::Invite => { // If content has third_party_invite key trace!("starting target_membership=invite check"); - match third_party_invite.and_then(|i| i.deserialize().ok()) { - | Some(tp_id) => + match third_party_invite { + | Some(raw_tp_id) => if target_user_current_membership == MembershipState::Ban { warn!(?target_user_membership_event_id, "Can't invite banned user"); false } else { - let allow = verify_third_party_invite( - Some(target_user), - sender, - &tp_id, - current_third_party_invite, - ); - if !allow { - warn!("Third party invite invalid"); - } - allow + let Ok(tp_id) = raw_tp_id.deserialize() else { + warn!("Invite third party content is invalid"); + return Ok(false); + }; + verify_third_party_invite(Some(target_user), sender, &tp_id, fetch_state) + .await }, | _ => if !sender_is_joined { @@ -1435,14 +1480,133 @@ fn get_send_level( .unwrap_or_else(|| if state_key.is_some() { int!(50) } else { int!(0) }) } -fn verify_third_party_invite( - _target_user: Option<&UserId>, - _sender: &UserId, - _tp_id: &ThirdPartyInvite, - _current_third_party_invite: Option<&impl Event>, -) -> bool { - // TODO: implement proper verification here - true +async fn verify_third_party_invite( + target_user: Option<&UserId>, + sender: &UserId, + tp_id: &MemberThirdPartyInviteSignedContent, + fetch_state: F, +) -> bool +where + F: Fn(&StateEventType, &str) -> Fut + Send, + Fut: Future> + Send, + E: Event + Send + Sync, +{ + // If content.third_party_invite does not have a signed property, reject. + // ^ This would be a deserialization error before this function call, which + // equates to a rejection + let signed = &tp_id.signed; + // If signed does not have mxid and token properties, reject. + let Some(mxid) = signed.mxid() else { + warn!("Invite third party signed content is missing or has invalid `mxid` property"); + return false; + }; + let Some(token) = signed.token() else { + warn!("Invite third party signed content is missing or has invalid `token` property"); + return false; + }; + if let Err(e) = mxid.validate_historical() { + warn!(error=?e, ?mxid, "Invite third party signed content has invalid `mxid` property"); + return false; + } + // If mxid does not match state_key, reject. + // N.B. target_user is the state_key + if target_user.is_none_or(|u| u != mxid) { + warn!(?target_user, %mxid, "Invite third party mxid does not match membership state key"); + return false; + } + // If there is no m.room.third_party_invite event in the current room state + // with state_key matching token, reject. + let Some(current_third_party_invite) = + fetch_state(&StateEventType::RoomThirdPartyInvite, token).await + else { + warn!("No third party invite associated with the invite's third party invite found"); + return false; + }; + let Ok(tpi_content) = current_third_party_invite + .get_content::() + .inspect_err( + |e| warn!(error=?e, "Third party invite event content is invalid (cannot deserialize)"), + ) + else { + return false; + }; + if current_third_party_invite.state_key() != Some(token) { + warn!( + state_key=?current_third_party_invite.state_key(), + %token, + "Third party invite state key mismatch with signed invite token" + ); + return false; + } + // If sender does not match sender of the m.room.third_party_invite, reject. + if sender != current_third_party_invite.sender() { + warn!( + ?sender, + third_party_invite_sender=%current_third_party_invite.sender(), + "Third party invite sender does not match invite membership sender" + ); + return false; + } + // If any signature in signed matches any public key in the + // m.room.third_party_invite event, allow. The public keys are in content of + // m.room.third_party_invite as: + // + // A single public key in the public_key property. + // A list of public keys in the public_keys property. + + // NOTE: Technically the two below operations shouldn't be fallible at this + // point in execution, but if we can't de/serialize them now, we won't be + // able to in the future, so rejecting the event is the right way to go. + // We log an error though since this is unexpected. + let Ok(signed_json) = to_canonical_json_string_for_signing(&signed.0).inspect_err( + |e| error!(error=?e, "Canonical signed object cannot be cast to a signing string"), + ) else { + return false; + }; + let signatures = signed + .signatures() + .unwrap_or_default() // Empty sigs object will never pass so this is fine + .values() + .filter_map(|signatures| signatures.as_object()) + .flat_map(|signatures| { + signatures.iter().map(|(key, sig)| { + let key_id = SigningKeyId::::parse(key).ok()?; + base64::Base64::::parse(sig.as_str()?) + .map(|parsed| (key_id.algorithm(), parsed)) + .ok() + }) + }) + .flatten() + .collect::>(); + + for public_key_bytes in tpi_content + .public_key + .into_iter() + .chain( + tpi_content + .public_keys + .unwrap_or_default() + .iter() + .map(|pk| pk.public_key.clone()), + ) + .filter_map(|pk| pk.decode().ok()) + { + for (algorithm, signature) in &signatures { + if signatures::verify_canonical_json_bytes( + algorithm, + &public_key_bytes, + signature.as_bytes(), + signed_json.as_bytes(), + ) + .is_ok() + { + return true; + } + } + } + + warn!("Invite via third party was not signed by any associated public keys"); + false } #[cfg(test)] @@ -1461,7 +1625,7 @@ mod tests { use serde_json::value::to_raw_value as to_raw_json_value; use crate::{ - matrix::{Event, EventTypeExt, Pdu as PduEvent}, + matrix::{Event, EventTypeExt}, state_res::{ StateMap, event_auth::valid_membership_change, @@ -1472,8 +1636,8 @@ mod tests { }, }; - #[test] - fn test_ban_pass() { + #[tokio::test] + async fn test_ban_pass() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1495,6 +1659,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = charlie(); let sender = alice(); @@ -1506,19 +1672,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_join_non_creator() { + #[tokio::test] + async fn test_join_non_creator() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1540,6 +1707,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = charlie(); let sender = charlie(); @@ -1551,19 +1720,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_join_creator() { + #[tokio::test] + async fn test_join_creator() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1585,6 +1755,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = alice(); let sender = alice(); @@ -1596,19 +1768,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_ban_fail() { + #[tokio::test] + async fn test_ban_fail() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1630,6 +1803,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = alice(); let sender = charlie(); @@ -1641,19 +1816,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_restricted_join_rule() { + #[tokio::test] + async fn test_restricted_join_rule() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1692,6 +1868,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = ella(); let sender = ella(); @@ -1703,13 +1881,14 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), Some(alice()), &MembershipState::Join, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); @@ -1721,19 +1900,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), Some(ella()), &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_knock() { + #[tokio::test] + async fn test_knock() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1764,6 +1944,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = ella(); let sender = ella(); @@ -1775,13 +1957,14 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } diff --git a/src/core/matrix/state_res/mod.rs b/src/core/matrix/state_res/mod.rs index a48860ac3..96a953ade 100644 --- a/src/core/matrix/state_res/mod.rs +++ b/src/core/matrix/state_res/mod.rs @@ -757,7 +757,8 @@ where Some(state_key), event.content(), room_version, - )?; + ) + .map_err(|e| Error::InvalidPdu(e.to_string()))?; trace!(list = ?auth_types, event_id = event.event_id().as_str(), "auth types for event"); let mut auth_state = StateMap::new(); @@ -830,12 +831,6 @@ where debug!(event_id = event.event_id().as_str(), "Running auth checks"); - // The key for this is (eventType + a state_key of the signed token not - // sender) so search for it - let current_third_party = auth_state.iter().find_map(|(_, pdu)| { - (*pdu.event_type() == TimelineEventType::RoomThirdPartyInvite).then_some(pdu) - }); - let fetch_state = |ty: &StateEventType, key: &str| { future::ready( auth_state @@ -847,7 +842,6 @@ where let auth_result = auth_check( room_version, &event, - current_third_party, fetch_state, &fetch_state(&StateEventType::RoomCreate, "") .await diff --git a/src/service/rooms/event_handler/pdu_checks.rs b/src/service/rooms/event_handler/pdu_checks.rs index e2a664f8d..af0338a97 100644 --- a/src/service/rooms/event_handler/pdu_checks.rs +++ b/src/service/rooms/event_handler/pdu_checks.rs @@ -159,15 +159,9 @@ impl super::Service { ready(auth_events_by_key.get(&key).map(ToOwned::to_owned)) }; - state_res::event_auth::auth_check( - room_version_rules, - pdu, - None, // TODO: third party invite - state_fetch, - create_event, - ) - .await - .map_err(|e| err!("Event self-authentication failed: {e:?}")) + state_res::event_auth::auth_check(room_version_rules, pdu, state_fetch, create_event) + .await + .map_err(|e| err!("Event self-authentication failed: {e:?}")) } /// Checks that the event passes PDU check 5, which ensures that the event @@ -241,7 +235,6 @@ impl super::Service { let auth_check = state_res::event_auth::auth_check( room_version_rules, incoming_pdu, - None, // TODO: third party invite |ty, sk| state_fetch(ty.clone(), sk.into()), create_event.as_pdu(), ) @@ -291,7 +284,6 @@ impl super::Service { state_res::event_auth::auth_check( room_version_rules, incoming_pdu, - None, // third-party invite state_fetch, create_event.as_pdu(), ) diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index dd7263de0..e7bd6037d 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -617,7 +617,6 @@ impl Service { let auth_check = state_res::event_auth::auth_check( &room_version.rules().unwrap(), &parsed_join_pdu, - None, // TODO: third party invite |k, s| state_fetch(k.clone(), s.into()), &create_event, ) diff --git a/src/service/rooms/timeline/create.rs b/src/service/rooms/timeline/create.rs index 1e7284492..d53bb14fd 100644 --- a/src/service/rooms/timeline/create.rs +++ b/src/service/rooms/timeline/create.rs @@ -256,15 +256,10 @@ impl super::Service { | _ => create_pdu.as_ref().unwrap().as_pdu(), }; - let auth_check = state_res::auth_check( - &room_version_rules, - &pdu, - None, // TODO: third_party_invite - auth_fetch, - create_event, - ) - .await - .map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?; + let auth_check = + state_res::auth_check(&room_version_rules, &pdu, auth_fetch, create_event) + .await + .map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?; if !auth_check { return Err!(Request(Forbidden("Event is not authorized."))); diff --git a/src/web/pages/account/register.rs b/src/web/pages/account/register.rs index cdce43fea..0bd686adb 100644 --- a/src/web/pages/account/register.rs +++ b/src/web/pages/account/register.rs @@ -313,6 +313,7 @@ async fn get_register_email_validate( Some(email), &client ) + .boxed() .await? ) } @@ -504,6 +505,7 @@ async fn begin_registration( // If email isn't required we can immediately complete registration Ok(response!( complete_registration(services, session_store, completed_registration, None, client) + .boxed() .await? )) } From 3abb32dd75daef70d6b87a119410828c94fb5e43 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 10 Nov 2026 20:41:38 +0000 Subject: [PATCH 154/342] fix: SEC31 Reviewed-By: Jade Ellis Reviewed-By: Ginger --- src/api/client/room/event.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/api/client/room/event.rs b/src/api/client/room/event.rs index 268ca92c1..c316a7813 100644 --- a/src/api/client/room/event.rs +++ b/src/api/client/room/event.rs @@ -24,7 +24,7 @@ pub(crate) async fn get_room_event_route( services.rooms.state_accessor.is_world_readable(room_id) ); if !joined && !world_readable { - return Err!(Request(NotFound("Event {} not found.", event_id))); + return Err!(Request(NotFound("Event {event_id} not found."))); } services @@ -32,10 +32,15 @@ pub(crate) async fn get_room_event_route( .timeline .get_remote_pdu(room_id, event_id) .await - .map_err(|_| err!(Request(NotFound("Event {} not found.", event_id))))? + .map_err(|_| err!(Request(NotFound("Event {event_id} not found."))))? }, | Err(e) => return Err(e), }; + if !event.room_id_or_hash().eq(room_id) { + // Return not found instead of invalid param to avoid revealing the + // existence of events the user might not be allowed to know about. + return Err!(Request(NotFound("Event {event_id} not found."))); + } // NOTE: checked after fetching, as visibility of an unknown event cannot // be determined (user_can_see_event returns true for those). From 4a721dad075c0f2af284fb0502e4c3bc1b9bfcbc Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 10 Nov 2026 20:42:04 +0000 Subject: [PATCH 155/342] fix: SEC15 Reviewed-By: Jade Ellis Reviewed-By: Ginger --- src/service/rooms/state_accessor/user_can.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/service/rooms/state_accessor/user_can.rs b/src/service/rooms/state_accessor/user_can.rs index 4754935ee..7e7340bc6 100644 --- a/src/service/rooms/state_accessor/user_can.rs +++ b/src/service/rooms/state_accessor/user_can.rs @@ -77,12 +77,20 @@ impl super::Service { room_id: &RoomId, event_id: &EventId, ) -> bool { - let Ok(shortstatehash) = self.pdu_shortstatehash(event_id).await else { - return true; - }; - let currently_member = self.services.state_cache.is_joined(user_id, room_id).await; + let Ok(shortstatehash) = self.pdu_shortstatehash(event_id).await else { + // We haven't calculated the state at this event, so we can't + // properly history visibility check it. This happens for outliers + // and backfilled events. Since continuwuity is primarily targeting + // single-user/trusted deployments, an acceptable compromise for now + // is to ensure that the user is currently joined to the room. + // Federation fails closed here, but if that was replicated for the + // check used for client-server, nobody would be allowed to see + // events before their server started participating in the room. + return currently_member; + }; + let history_visibility = self .state_get_content(shortstatehash, &StateEventType::RoomHistoryVisibility, "") .await From 79b49134f4b318011b42d534ac5fca66a149b00c Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Tue, 10 Nov 2026 21:01:48 +0000 Subject: [PATCH 156/342] fix: Correct conflict in patch --- src/service/rooms/threads/mod.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/service/rooms/threads/mod.rs b/src/service/rooms/threads/mod.rs index fa0956abe..4274933aa 100644 --- a/src/service/rooms/threads/mod.rs +++ b/src/service/rooms/threads/mod.rs @@ -105,7 +105,7 @@ impl Service { return Ok(()); }; - let thread: Vec<_> = self + let thread = self .services .pdu_metadata .get_relations( @@ -116,11 +116,9 @@ impl Service { usize::MAX, 0, Direction::Backward, + |pdu| RelationType::Thread.relation_type_equal(pdu), ) - .await - .into_iter() - .filter(|(_, pdu)| RelationType::Thread.relation_type_equal(pdu)) - .collect(); + .await; match thread.first() { | Some((_, latest)) => Self::set_thread( From 0a52421b65ce737714dd5031dfab2b5eea2a83b4 Mon Sep 17 00:00:00 2001 From: timedout Date: Thu, 5 Nov 2026 23:50:15 +0000 Subject: [PATCH 157/342] fix: Re-introduce edge reference tracking --- src/database/maps.rs | 2 +- src/service/rooms/pdu_metadata/data.rs | 16 ++++++++++- src/service/rooms/pdu_metadata/mod.rs | 8 ++++++ src/service/rooms/timeline/append.rs | 38 ++++++++++++++++++++++---- 4 files changed, 56 insertions(+), 8 deletions(-) diff --git a/src/database/maps.rs b/src/database/maps.rs index d1092c176..013fc9270 100644 --- a/src/database/maps.rs +++ b/src/database/maps.rs @@ -171,7 +171,7 @@ pub(super) static MAPS: &[Descriptor] = &[ }, Descriptor { name: "referencedevents", - ..descriptor::DROPPED + ..descriptor::RANDOM }, Descriptor { name: "refreshtoken_refreshtokeninfo", diff --git a/src/service/rooms/pdu_metadata/data.rs b/src/service/rooms/pdu_metadata/data.rs index 2f5cc38f7..2b40f6e52 100644 --- a/src/service/rooms/pdu_metadata/data.rs +++ b/src/service/rooms/pdu_metadata/data.rs @@ -11,7 +11,7 @@ use conduwuit::{ }; use database::Map; use futures::{Stream, StreamExt}; -use ruma::{EventId, api::Direction}; +use ruma::{EventId, RoomId, api::Direction}; use crate::{ Dep, @@ -26,6 +26,7 @@ pub(super) struct Data { tofrom_relation: Arc, softfailedeventids: Arc, rejectedeventids: Arc, + referencedevents: Arc, services: Services, } @@ -40,6 +41,7 @@ impl Data { tofrom_relation: db["tofrom_relation"].clone(), softfailedeventids: db["softfailedeventids"].clone(), rejectedeventids: db["rejectedeventids"].clone(), + referencedevents: db["referencedevents"].clone(), services: Services { timeline: args.depend::("rooms::timeline"), }, @@ -132,4 +134,16 @@ impl Data { self.unmark_event_rejected(event_id); self.unmark_event_soft_failed(event_id); } + + #[inline] + pub(super) fn mark_as_referenced(&self, room_id: &RoomId, event_id: &EventId) { + let key = (room_id, event_id); + self.referencedevents.put_raw(key, []); + } + + #[inline] + pub(super) async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool { + let key = (room_id, event_id); + self.referencedevents.qry(&key).await.is_ok() + } } diff --git a/src/service/rooms/pdu_metadata/mod.rs b/src/service/rooms/pdu_metadata/mod.rs index 6a0244cb1..0ff50402c 100644 --- a/src/service/rooms/pdu_metadata/mod.rs +++ b/src/service/rooms/pdu_metadata/mod.rs @@ -207,6 +207,14 @@ impl Service { self.db.is_event_rejected(event_id).await } + pub async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool { + self.db.is_event_referenced(room_id, event_id).await + } + + pub fn mark_as_referenced(&self, room_id: &RoomId, event_id: &EventId) { + self.db.mark_as_referenced(room_id, event_id); + } + pub fn mark_event_rejected(&self, event_id: &EventId) { self.db.mark_event_rejected(event_id); } diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index e1044514a..d0cfd058e 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -145,9 +145,17 @@ impl super::Service { // Note that we add it *again* as a no-op in append_pdu. This is done // now so that there's never a point in time where we have zero forward // extremities. - self.services - .state - .add_forward_extremity(&incoming_pdu.room_id_or_hash(), incoming_pdu.event_id()); + let effective_room_id = incoming_pdu.room_id_or_hash(); + if !self + .services + .pdu_metadata + .is_event_referenced(&effective_room_id, incoming_pdu.event_id()) + .await + { + self.services + .state + .add_forward_extremity(&incoming_pdu.room_id_or_hash(), incoming_pdu.event_id()); + } let Some(room_id) = incoming_pdu.room_id() else { // If there's no room ID, this is a v12+ create event, which never // has any predecessors, and consequently will be the @@ -177,19 +185,37 @@ impl super::Service { // Now we collect all the prev events of this predecessor and filter // for ones that we 1. know, 2. are not backfilled, and 3. have // rejected/soft-failed. + // Additionally, drop any events that were referenced late. let outlier_prevs = prev_event .prev_events() .map(ToOwned::to_owned) .stream() .broad_filter_map(|prev_id| async { - let (exists, count, is_accepted) = tokio::join!( + let (exists, count, is_accepted, is_referenced) = tokio::join!( self.pdu_exists(&prev_id), self.get_pdu_count(&prev_id) .unwrap_or(PduCount::Backfilled(i64::MIN)), self.services.pdu_metadata.is_event_accepted(&prev_id), + self.services + .pdu_metadata + .is_event_referenced(room_id, &prev_id) ); - (exists && !matches!(count, PduCount::Backfilled(_)) && !is_accepted) - .then_some(prev_id) + let is_backfilled = matches!(count, PduCount::Backfilled(_)); + if is_referenced { + self.services + .state + .remove_forward_extremity(room_id, &prev_id); + } else { + // If we got here, that means there's now at least an + // indirect reference to the event. + self.services + .pdu_metadata + .mark_as_referenced(room_id, &prev_id); + } + if is_referenced || !exists || !is_accepted || is_backfilled { + return None; + } + Some(prev_id) }) .collect::>() .await; From b570420b9f72d2c03e1e2d898ed0fbf65524a315 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 24 Oct 2026 13:35:01 +0200 Subject: [PATCH 158/342] fix: preserve predecessors sharing a state-before ID Signed-off-by: Erwan Leboucher --- Cargo.lock | 2 + changelog.d/+state-before-forks.bugfix.md | 1 + src/service/Cargo.toml | 4 + .../rooms/event_handler/state_at_incoming.rs | 5 +- .../event_handler/state_at_incoming/tests.rs | 275 ++++++++++++++++++ 5 files changed, 286 insertions(+), 1 deletion(-) create mode 100644 changelog.d/+state-before-forks.bugfix.md create mode 100644 src/service/rooms/event_handler/state_at_incoming/tests.rs diff --git a/Cargo.lock b/Cargo.lock index d5e2615ef..5e9fc7351 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1122,6 +1122,7 @@ dependencies = [ "lru-cache", "nonzero_ext", "openidconnect", + "opentelemetry", "p256 0.14.0", "rand 0.10.3", "regex", @@ -1130,6 +1131,7 @@ dependencies = [ "resolvematrix", "ruma", "ruminuwuity", + "rustls", "rustyline-async", "sd-notify", "serde", diff --git a/changelog.d/+state-before-forks.bugfix.md b/changelog.d/+state-before-forks.bugfix.md new file mode 100644 index 000000000..70e3eadd7 --- /dev/null +++ b/changelog.d/+state-before-forks.bugfix.md @@ -0,0 +1 @@ +Fix incoming federation events losing state changes when predecessors share the same state-before snapshot. Contributed by @eleboucher. diff --git a/src/service/Cargo.toml b/src/service/Cargo.toml index f35a40aaa..41d1220fd 100644 --- a/src/service/Cargo.toml +++ b/src/service/Cargo.toml @@ -145,3 +145,7 @@ workspace = true [package.metadata.cargo-shear] ignored = ["reqwest_0_12"] + +[dev-dependencies] +opentelemetry.workspace = true +rustls = { workspace = true, features = ["ring"] } diff --git a/src/service/rooms/event_handler/state_at_incoming.rs b/src/service/rooms/event_handler/state_at_incoming.rs index e232df7bc..7025077c7 100644 --- a/src/service/rooms/event_handler/state_at_incoming.rs +++ b/src/service/rooms/event_handler/state_at_incoming.rs @@ -15,6 +15,9 @@ use ruma::{OwnedEventId, RoomId, room_version_rules::RoomVersionRules}; use crate::rooms::short::ShortStateHash; +#[cfg(test)] +mod tests; + impl super::Service { /// Resolves the state before the incoming event. /// @@ -124,7 +127,7 @@ impl super::Service { .pdu_shortstatehash(prev_eventid) .map_ok(move |sstatehash| (sstatehash, prev_event)) }) - .try_collect::>() + .try_collect::>() .inspect_err(|e| debug_error!("failed to calculate N-degree short state hashes: {e}")) .await else { diff --git a/src/service/rooms/event_handler/state_at_incoming/tests.rs b/src/service/rooms/event_handler/state_at_incoming/tests.rs new file mode 100644 index 000000000..bf7e0035b --- /dev/null +++ b/src/service/rooms/event_handler/state_at_incoming/tests.rs @@ -0,0 +1,275 @@ +use std::sync::Arc; + +use conduwuit::{ + Config, PduEvent, Server, + log::{Log, LogLevelReloadHandles}, + metrics::Metrics, +}; +use futures::StreamExt; +use ruma::{RoomId, RoomVersionId, events::StateEventType}; +use serde_json::json; + +#[tokio::test] +async fn admitted_joins_do_not_disappear_after_a_merge() { + use conduwuit::matrix::PartialPdu; + use ruma::{ + UserId, + events::room::{ + join_rules::{JoinRule, RoomJoinRulesEventContent}, + member::{MembershipState, RoomMemberEventContent}, + }, + }; + + let (services, path) = test_services().await; + let alice = UserId::parse("@alice:test.example").unwrap(); + let bob = UserId::parse("@bob:bob.example").unwrap(); + let charlie = UserId::parse("@charlie:charlie.example").unwrap(); + let dave = UserId::parse("@dave:dave.example").unwrap(); + let mut remote_keys = Vec::new(); + for user in [&bob, &charlie, &dave] { + let key = ruma::signatures::Ed25519KeyPair::from_der( + &ruma::signatures::Ed25519KeyPair::generate(), + "test".into(), + ) + .unwrap(); + cache_key(&services, user.server_name(), &key); + remote_keys.push(key); + } + let bootstrap = services + .rooms + .state + .mutex + .lock("!bootstrap:test.example") + .await; + let create_id = services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu { + event_type: "m.room.create".into(), + content: serde_json::value::to_raw_value(&json!({ "room_version": "12" })) + .unwrap(), + state_key: Some("".into()), + ..Default::default() + }, + &alice, + None, + &bootstrap, + ) + .await + .unwrap(); + drop(bootstrap); + let room = RoomId::parse(create_id.as_str().replacen('$', "!", 1)).unwrap(); + let lock = services.rooms.state.mutex.lock(&room).await; + services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu::state( + alice.to_string(), + &RoomMemberEventContent::new(MembershipState::Join), + ), + &alice, + Some(&room), + &lock, + ) + .await + .unwrap(); + let rules_id = services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu::state("", &RoomJoinRulesEventContent::new(JoinRule::Public)), + &alice, + Some(&room), + &lock, + ) + .await + .unwrap(); + drop(lock); + let rules = services.rooms.timeline.get_pdu(&rules_id).await.unwrap(); + let (dave_join, json) = signed_remote_event( + json!({ + "room_id": room, "sender": dave, "type": "m.room.member", "state_key": dave, + "content": { "membership": "join" }, "auth_events": [rules_id], "prev_events": [rules_id], + "depth": rules.depth + ruma::uint!(1), "origin_server_ts": conduwuit::utils::millis_since_unix_epoch(), + }), + dave.server_name(), + &remote_keys[2], + ); + assert!( + services + .rooms + .event_handler + .handle_incoming_pdu(dave.server_name(), &room, &dave_join.event_id, json, false) + .await + .unwrap() + .is_some() + ); + let mut joins = Vec::new(); + for (user, key) in [&bob, &charlie].into_iter().zip(&remote_keys) { + let signed = signed_remote_event( + json!({ + "room_id": room, "sender": user, "type": "m.room.member", "state_key": user, + "content": { "membership": "join" }, "auth_events": [rules_id], "prev_events": [dave_join.event_id], + "depth": dave_join.depth + ruma::uint!(1), "origin_server_ts": conduwuit::utils::millis_since_unix_epoch(), + }), + user.server_name(), + key, + ); + joins.push(signed); + } + for ((pdu, json), user) in joins.iter().zip([&bob, &charlie]) { + let accepted = services + .rooms + .event_handler + .handle_incoming_pdu(user.server_name(), &room, &pdu.event_id, json.clone(), false) + .await + .unwrap(); + assert!(accepted.is_some()); + } + let bob_hash = services + .rooms + .state_accessor + .pdu_shortstatehash(&joins[0].0.event_id) + .await + .unwrap(); + let charlie_hash = services + .rooms + .state_accessor + .pdu_shortstatehash(&joins[1].0.event_id) + .await + .unwrap(); + assert_eq!(bob_hash, charlie_hash); + let (merge, json) = signed_remote_event( + json!({ + "room_id": room, "sender": dave, "type": "m.room.message", + "content": { "msgtype": "m.text", "body": "merge" }, + "auth_events": [dave_join.event_id], + "prev_events": [joins[0].0.event_id, joins[1].0.event_id], + "depth": joins[0].0.depth + ruma::uint!(1), + "origin_server_ts": conduwuit::utils::millis_since_unix_epoch(), + }), + dave.server_name(), + &remote_keys[2], + ); + assert!( + services + .rooms + .event_handler + .handle_incoming_pdu(dave.server_name(), &room, &merge.event_id, json, false) + .await + .unwrap() + .is_some() + ); + let mut results = Vec::new(); + for ((user, key), (join, _)) in [&bob, &charlie].into_iter().zip(&remote_keys).zip(&joins) { + let membership = services + .rooms + .state_accessor + .room_state_get_content::( + &room, + &StateEventType::RoomMember, + user.as_str(), + ) + .await + .unwrap(); + assert_eq!(membership.membership, MembershipState::Join); + let prev_events = services + .rooms + .state + .get_forward_extremities(&room) + .collect::>() + .await; + let depth = services + .rooms + .timeline + .get_pdu(&prev_events[0]) + .await + .unwrap() + .depth + + ruma::uint!(1); + let (message, json) = signed_remote_event( + json!({ + "room_id": room, "sender": user, "type": "m.room.message", + "content": { "msgtype": "m.text", "body": format!("message from {user}") }, + "auth_events": [join.event_id], "prev_events": prev_events, + "depth": depth, "origin_server_ts": conduwuit::utils::millis_since_unix_epoch(), + }), + user.server_name(), + key, + ); + let result = services + .rooms + .event_handler + .handle_incoming_pdu(user.server_name(), &room, &message.event_id, json, false) + .await; + results.push(result.is_ok_and(|pdu| pdu.is_some())); + } + services.stop().await; + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(results, [true, true], "both joined users must be able to send messages"); +} + +async fn test_services() -> (Arc, std::path::PathBuf) { + let _ = rustls::crypto::ring::default_provider().install_default(); + let path = std::env::temp_dir() + .join(format!("continuwuity-shared-state-{:016x}", rand::random::())); + std::fs::create_dir(&path).unwrap(); + let config: Config = serde_json::from_value(json!({ + "server_name": "test.example", + "database_path": path, + "db_cache_capacity_mb": 16.0, + "rocksdb_write_buffer_capacity_mb": 4.0, + "allow_local_presence": false + })) + .unwrap(); + let runtime = tokio::runtime::Handle::current(); + let server = Arc::new(Server::new( + config, + Some(runtime.clone()), + Log { + reload: LogLevelReloadHandles::default(), + capture: Arc::default(), + }, + Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None), + )); + let services = crate::Services::build(server).await.unwrap(); + (services, path) +} + +fn cache_key( + services: &crate::Services, + server: &ruma::ServerName, + key: &ruma::signatures::Ed25519KeyPair, +) { + let mut response = ruma::api::federation::discovery::ServerSigningKeys::new( + server.to_owned(), + crate::server_keys::in_one_week(), + ); + let id: ruma::OwnedServerSigningKeyId = + format!("ed25519:{}", key.version()).try_into().unwrap(); + response.verify_keys.insert( + id.clone(), + ruma::api::federation::discovery::VerifyKey::new(ruma::serde::Base64::new( + key.public_key().to_vec(), + )), + ); + services.db["servernamekeyid_response"] + .put((server.as_str(), id.as_str()), database::Json(&response)); +} + +fn signed_remote_event( + value: serde_json::Value, + server: &ruma::ServerName, + key: &ruma::signatures::Ed25519KeyPair, +) -> (PduEvent, ruma::CanonicalJsonObject) { + let rules = RoomVersionId::V12.rules().unwrap(); + let mut value = serde_json::from_value(value).unwrap(); + ruma::signatures::hash_and_sign_event(server.as_str(), key, &mut value, &rules.redaction) + .unwrap(); + let id = conduwuit::matrix::event::gen_event_id(&value, &rules).unwrap(); + let pdu = PduEvent::from_id_val(&id, value.clone()).unwrap(); + (pdu, value) +} From f1798c004a3476e50626f01bf5c052c2ce085d6e Mon Sep 17 00:00:00 2001 From: stratself Date: Sun, 11 Oct 2026 12:31:35 +0000 Subject: [PATCH 159/342] docs(calls): Redirect to support room --- docs/calls/livekit.mdx | 10 +++++++--- docs/calls/turn.mdx | 3 ++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index 9337e9c93..5a8f29b64 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -2,12 +2,14 @@ import { Tab, Tabs} from '@rspress/core/theme'; # MatrixRTC/Element Call Setup -This guide assumes that you are using docker compose for deployment. +This guide assumes that you are using `docker compose` for deployment. :::tip -You can find help setting up MatrixRTC in our dedicated room - [#matrixrtc:continuwuity.org](https://matrix.to/#/%23matrixrtc%3Acontinuwuity.org) +You can find help setting up MatrixRTC in our support room - [`#continuwuity:continuwuity.org`][support-room] ::: +[support-room]: https://matrix.to/#/%23continuwuity:continuwuity.org + ## Instructions ### 1. Set up your domain @@ -58,7 +60,9 @@ services: - ./livekit.yaml:/etc/livekit.yaml:ro network_mode: "host" # /!\ LiveKit binds to all addresses by default. # Make sure port 7880 is blocked by your firewall to prevent access bypassing your reverse proxy - # Alternatively, uncomment the lines below and comment `network_mode: "host"` above to specify port mappings. + + # Alternatively, uncomment the lines below and comment out `network_mode: "host"` + # above to specify port mappings. # ports: # - "127.0.0.1:7880:7880/tcp" # - "7881:7881/tcp" diff --git a/docs/calls/turn.mdx b/docs/calls/turn.mdx index fe6c7db77..1e65813b5 100644 --- a/docs/calls/turn.mdx +++ b/docs/calls/turn.mdx @@ -5,12 +5,13 @@ Continuwuity recommends using [coturn][coturn] as your TURN/STUN server, which is available as a Docker image or a distro package. This guide assumes that you are using docker compose for deployment. :::tip -You can find help setting up TURN/STUN in our MatrixRTC room - [#matrixrtc:continuwuity.org](https://matrix.to/#/%23matrixrtc%3Acontinuwuity.org) +You can find help setting up TURN/STUN in our support room - [`#continuwuity:continuwuity.org`][support-room] ::: [turn]: https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT [stun]: https://en.wikipedia.org/wiki/STUN [coturn]: https://github.com/coturn/coturn +[support-room]: https://matrix.to/#/%23continuwuity:continuwuity.org ## Installing coturn From dd11fc5a25755814506a03fdc64b987c6f7b7107 Mon Sep 17 00:00:00 2001 From: stratself Date: Sun, 11 Oct 2026 12:32:45 +0000 Subject: [PATCH 160/342] docs(livekit): Remove workaround for non-federating servers Fixed by #2326 --- docs/calls/livekit.mdx | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index 5a8f29b64..b0be6e8d7 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -329,20 +329,6 @@ rtc: + node_ip: "1.2.3.4" ``` -### Workaround for non-federating servers - -When deploying on servers with federation disabled (`allow_federation = false`), LiveKit will fail as it can't fetch the required [OpenID endpoint](https://spec.matrix.org/v1.17/server-server-api/#get_matrixfederationv1openiduserinfo) via federation paths. - -As a workaround, you can enable federation, but forbid all remote servers via the following config parameters: - -```toml -### in your continuwuity.toml file ### -allow_federation = true -forbidden_remote_server_names = [".*"] -``` - -Subscribe to issue [!1440](https://forgejo.ellis.link/continuwuation/continuwuity/issues/1440) for future updates on this matter. - ## Related Documentation Guides: From bbf3bd12940a2db43c7cd09592bcdd8c421e3e57 Mon Sep 17 00:00:00 2001 From: stratself Date: Sun, 11 Oct 2026 12:37:44 +0000 Subject: [PATCH 161/342] docs(calls): Small fixup of wordings * Use indirect links and fix them * Make Livekit's TURN configuration optional --- docs/calls.mdx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/calls.mdx b/docs/calls.mdx index 0f1fea978..a4bba12d6 100644 --- a/docs/calls.mdx +++ b/docs/calls.mdx @@ -2,12 +2,15 @@ Matrix supports two types of calls: -- Element Call powered by [MatrixRTC](https://half-shot.github.io/msc-crafter/#msc/4143) and [LiveKit](https://github.com/livekit/livekit) +- Element Call powered by [MatrixRTC][MSC4143] and [LiveKit][livekit-server-github] - Legacy calls, supported by a STUN/TURN server. +[MSC4143]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143 +[livekit-server-github]: https://github.com/livekit/livekit + Both types of calls are supported by different sets of clients, but most clients are moving towards MatrixRTC / Element Call. For either one to work correctly, you have to do some additional setup: -- For legacy calls to work, you need to set up a TURN/STUN server. [Read the TURN guide for tips on how to set up coturn](./calls/turn.mdx) -- For MatrixRTC / Element Call to work, you have to set up the LiveKit backend. LiveKit also uses TURN/STUN to increase reliability - you can set up its built-in TURN server, or integrate with an existing one. [Read the LiveKit guide](./calls/livekit.mdx) +- For legacy calls to work, you need to set up a TURN/STUN server. [Read the TURN guide for instructions on how to set up coturn](./calls/turn.mdx) +- For MatrixRTC / Element Call to work, you have to set up the LiveKit backend, and optionally configure a TURN server for increased reliability. [Read the LiveKit guide](./calls/livekit.mdx) From 2173577bac022e7b3aaaa7944b795c3ac9dac24f Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 4 Nov 2026 16:50:53 +0000 Subject: [PATCH 162/342] docs(livekit): Update Element Call UI errors --- docs/calls/livekit.mdx | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index b0be6e8d7..b0dad2e86 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -297,11 +297,18 @@ Use this token to test at the [LiveKit Connection Tester][livekit-connection-tes To debug any issues, you can place a call or redo the Testing instructions, and check the container logs for any specific errors. Use `docker compose logs --follow` to follow these logs in real-time. +Before debugging, ensure the following prerequisites: + +- The user has permissions to send call events into the room. For legacy calls, this require them to hold a power level (usually 50 or more). +- WebRTC is enabled, if using a browser client. + ### Common errors in Element Call UI -- `MISSING_MATRIX_RTC_FOCUS`/`MISSING_MATRIX_RTC_TRANSPORT`: LiveKit is missing from Continuwuity's config file -- "Waiting for media" popup always showing for yourself: a LiveKit URL has been configured in Continuwuity, but your client cannot connect to it for some reason -- `OPEN_ID_ERROR`: Your client can reach out to `lk-jwt-service`, but has problems authenticating with it. In this case, check `lk-jwt-service` logs for more details +- `MISSING_MATRIX_RTC_FOCUS`/`MISSING_MATRIX_RTC_TRANSPORT`: the client cannot find a suitable SFU. This is likely due to LiveKit being missing from Continuwuity's config file, and therefore not being exposed properly. + +- `OPEN_ID_ERROR`: Your client can reach out to `lk-jwt-service`, but `lk-jwt-service` has problems authenticating you against Continuwuity. In this case, check `lk-jwt-service` logs for more details. The section below on [Docker loopback networking issues](#docker-loopback-networking-issues) may be of help. + +- Calls fail to start with `ServerUnreachable` error: a LiveKit URL has been properly configured and exposed in Continuwuity, but the client cannot connect to it for some reason. For browser-based clients, you can also inspect connections using DevTools' Networking tab, to see which requests are erroring out. From 304bf69c324dbe67d13a5cac5cb7d13d0c54a955 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 4 Nov 2026 17:27:56 +0000 Subject: [PATCH 163/342] docs(livekit): Add LiveKit advertised IP addresses restrictions --- docs/calls/livekit.mdx | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index b0dad2e86..af2f29ed9 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -299,7 +299,7 @@ To debug any issues, you can place a call or redo the Testing instructions, and Before debugging, ensure the following prerequisites: -- The user has permissions to send call events into the room. For legacy calls, this require them to hold a power level (usually 50 or more). +- The user has permissions to send call events into the room. For legacy/compatibility mode, this require them to hold a power level (usually 50 or more). - WebRTC is enabled, if using a browser client. ### Common errors in Element Call UI @@ -323,9 +323,9 @@ docker run --rm --net container:lk-jwt-service docker.io/curlimages/curl https:/ To resolve this, follow the steps in [Docker loopback networking issues](../troubleshooting.mdx#docker-loopback-networking-issues) of the Troubleshooting page. -### Incorrect IP address for LiveKit +### Incorrect IP addresses for LiveKit -By default, LiveKit automatically finds its public IP address(es), which can be seen in the "Establishing WebRTC connection" section of the connection test page. If these IPs are incorrect, you may want to hardcode your own IP by doing the following: +By default, LiveKit automatically finds its public IP address(es), which are reflected in the "Establishing WebRTC connection" section of the connection test page. If these IPs are incorrect, you may want to hardcode your own IP by doing the following: ```diff ### in your livekit.yaml ### @@ -336,6 +336,21 @@ rtc: + node_ip: "1.2.3.4" ``` +Run the LiveKit tests again, and the new updated `node_ip` should be included as one of the candidates. + +You may further restrict the advertised address to only the `node_ip` with the following configurations: + +```diff +### in your livekit.yaml ### +rtc: + # ... other configs here ... ++ enable_loopback_candidate: false ++ interfaces: ++ includes: [] ++ ips: ++ includes: [ "1.2.3.4/32" ] +``` + ## Related Documentation Guides: From 9ace03c107d596b634323c73d1b9a0b69b6463be Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 4 Nov 2026 17:31:14 +0000 Subject: [PATCH 164/342] docs(livekit): Add more relevant MSCs --- docs/calls/livekit.mdx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index af2f29ed9..ecf86d2fa 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -371,9 +371,13 @@ Specifications: - [MSC4143: MatrixRTC \- Real-time communication over Matrix][MSC4143] - [MSC4195: MatrixRTC Transport using LiveKit Backend][MSC4195] +- [MSC3401: Native Group VoIP Signalling][MSC3401] - state events for legacy calls +- [MSC4075: MatrixRTC invites and notifications - #4075][MSC4075] - for ringing users [MSC4143]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143 [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195 +[MSC3401]: https://github.com/matrix-org/matrix-spec-proposals/pull/3401 +[MSC4075]: https://github.com/matrix-org/matrix-spec-proposals/pull/4075 Source code: From 6f6fba4310ad7ff78a9a8872562f7850e1bf5436 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 4 Nov 2026 17:33:12 +0000 Subject: [PATCH 165/342] docs(livekit): Pin token exchange flow link to jwt-svc 0.6.0 --- docs/calls/livekit.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index ecf86d2fa..3670a6809 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -222,7 +222,9 @@ Start up the services using your usual method - for example `docker compose up - ## Testing -To test that LiveKit is successfully integrated with Continuwuity, you will need to replicate its [Token Exchange Flow](https://github.com/element-hq/lk-jwt-service#%EF%B8%8F-how-it-works--token-exchange-flow). Follow the steps below while checking Docker logs (`docker compose logs --follow`), in order to help [troubleshooting](#troubleshooting) any issues. +To test that LiveKit is successfully integrated with Continuwuity, you will need to replicate its [Token Exchange Flow][token-exchange-flow]. Follow the steps below while checking Docker logs (`docker compose logs --follow`), in order to help [troubleshooting](#troubleshooting) any issues. + +[token-exchange-flow]: https://github.com/element-hq/lk-jwt-service/tree/v0.6.0#%EF%B8%8F-how-it-works--token-exchange-flow First, you will need an access token for your current login session. These can be found in your client's settings or obtained via [this website][starstruck-mxtoken2]. From fb3113ea6968b9092698583f62657f6716683c69 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 4 Nov 2026 17:48:16 +0000 Subject: [PATCH 166/342] docs(livekit): Add appendix section on calling modes --- docs/calls/livekit.mdx | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index 3670a6809..fae599158 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -301,7 +301,7 @@ To debug any issues, you can place a call or redo the Testing instructions, and Before debugging, ensure the following prerequisites: -- The user has permissions to send call events into the room. For legacy/compatibility mode, this require them to hold a power level (usually 50 or more). +- The user has permissions to send call events into the room. See the Appendix section on [call modes](#call-modes) for more details. - WebRTC is enabled, if using a browser client. ### Common errors in Element Call UI @@ -374,7 +374,8 @@ Specifications: - [MSC4143: MatrixRTC \- Real-time communication over Matrix][MSC4143] - [MSC4195: MatrixRTC Transport using LiveKit Backend][MSC4195] - [MSC3401: Native Group VoIP Signalling][MSC3401] - state events for legacy calls -- [MSC4075: MatrixRTC invites and notifications - #4075][MSC4075] - for ringing users +- [MSC4075: MatrixRTC invites and notifications][MSC4075] - for ringing users +- [MSC4354: Sticky Events] - for MatrixRTC 2.0 calls [MSC4143]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143 [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195 @@ -399,6 +400,18 @@ Other: ## Appendix +### MatrixRTC calling modes and enabling sticky events {#call-modes} + +MatrixRTC currently supports 3 calling modes: + +- **Legacy mode** (deprecated): calls are established by sending state events to a room. The call initiator's SFU hosts the entire call for all remote and local participants. +- **Compatibility mode*: same as Legacy mode, but utilizes multiple SFUs between federating servers. Clients publish media streams to their own SFUs, and fetch remote streams from remote SFUs. This is the most commonly used mode nowadays. +- **MatrixRTC 2.0 mode**: also utilizes multiple SFUs, but establishes calls with [sticky events] instead of state events. + +To support Legacy and Compatibility mode, ensure that the user is allowed to send the relevant state events. Usually, this means promoting them to a power level of 50 or above. Alternatively, set the power level required to send `org.matrix.msc3401.call.member` events to 0. + +To support MatrixRTC 2.0 mode, sticky events has to be enabled on the Matrix server. In Continuwuity, this is as easy as setting `enable_sticky_events = true` in the config file. + ### Additional TURN-over-TLS on 443 configuration Most of the time, LiveKit [**does not need TURN**][sspaeth-matrix-voip-turn] to function. However, there are situations where clients may be unable to use nonstandard ports or UDP connections, such as in highly restrictive networks. In such cases, a TURN-over-TLS server on port 443 could relay traffic for the clients. From c67f08a208f419bcee6a0c409b3a329790c68281 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 4 Nov 2026 18:01:44 +0000 Subject: [PATCH 167/342] docs(livekit): Add appendix sectionon creating livekit tokens via livekit-cli --- docs/calls/livekit.mdx | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index fae599158..35438cf8a 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -285,7 +285,7 @@ You can then send this payload to the lk-jwt-service: curl -X POST -d @payload.json https://livekit.example.com/get_token ``` -The lk-jwt-service will, after checking against Continuwuity, answer with a `jwt` token to create a LiveKit media room: +The lk-jwt-service will, after checking against Continuwuity, answer with a `jwt` token to [create a LiveKit media room](#livekit-cli): ```json {"url":"wss://livekit.example.com","jwt":"a_really_really_long_string"} @@ -375,12 +375,13 @@ Specifications: - [MSC4195: MatrixRTC Transport using LiveKit Backend][MSC4195] - [MSC3401: Native Group VoIP Signalling][MSC3401] - state events for legacy calls - [MSC4075: MatrixRTC invites and notifications][MSC4075] - for ringing users -- [MSC4354: Sticky Events] - for MatrixRTC 2.0 calls +- [MSC4354: Sticky Events][MSC4354] - for MatrixRTC 2.0 calls [MSC4143]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143 [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195 [MSC3401]: https://github.com/matrix-org/matrix-spec-proposals/pull/3401 [MSC4075]: https://github.com/matrix-org/matrix-spec-proposals/pull/4075 +[MSC4354]: https://github.com/matrix-org/matrix-spec-proposals/pull/4354 Source code: @@ -412,6 +413,35 @@ To support Legacy and Compatibility mode, ensure that the user is allowed to sen To support MatrixRTC 2.0 mode, sticky events has to be enabled on the Matrix server. In Continuwuity, this is as easy as setting `enable_sticky_events = true` in the config file. +### Creating LiveKit tokens via `livekit-cli` {#livekit-cli} + +To create room tokens directly without going through `lk-jwt-service`, use the [Livekit CLI tool][livekit-cli]. + + + + +First, download the [release tarball][livekit-cli-releases] and extract it. Then: + +```sh +./lk --url https://livekit.example.com \ + --api-key APIUxUnMnSkuFWV \ + --api-secret t93ZVjPeoEdyx7Wbet3kG4L3NGZIZVEFvqe0UuiVc22A \ + token create --create --join +``` + + +```sh +docker run --rm docker.io/livekit/livekit-cli --url https://livekit.example.com \ + --api-key APIUxUnMnSkuFWV \ + --api-secret t93ZVjPeoEdyx7Wbet3kG4L3NGZIZVEFvqe0UuiVc22A \ + token create --create --join +``` + + + +[livekit-cli]: https://github.com/livekit/livekit-cli +[livekit-cli-releases]: https://github.com/livekit/livekit-cli + ### Additional TURN-over-TLS on 443 configuration Most of the time, LiveKit [**does not need TURN**][sspaeth-matrix-voip-turn] to function. However, there are situations where clients may be unable to use nonstandard ports or UDP connections, such as in highly restrictive networks. In such cases, a TURN-over-TLS server on port 443 could relay traffic for the clients. From 0375643adecbb4905863d8a150207df9c056ae49 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 4 Nov 2026 18:05:16 +0000 Subject: [PATCH 168/342] docs(livekit): Add `stun_servers` to TURN instructions too --- docs/calls/livekit.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index 35438cf8a..7a89efc10 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -548,6 +548,8 @@ Then configure LiveKit, making sure to replace `COTURN_SECRET` with the one you ### in your livekit.yaml ### rtc: # ... other configs here ... + stun_servers: + - coturn.example.com turn_servers: - host: coturn.example.com port: 443 From 0bc55cb59011c05b5c563fcb5ed7962c35d7585e Mon Sep 17 00:00:00 2001 From: stratself Date: Thu, 5 Nov 2026 17:19:24 +0000 Subject: [PATCH 169/342] docs(livekit): Use "MatrixRTC" phrasing in lieu of "Element Call" The calling protocol matters not the client product --- docs/calls.mdx | 9 +++++---- docs/calls/livekit.mdx | 4 ++-- docs/calls/turn.mdx | 4 ++-- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/calls.mdx b/docs/calls.mdx index a4bba12d6..28b83f05d 100644 --- a/docs/calls.mdx +++ b/docs/calls.mdx @@ -2,15 +2,16 @@ Matrix supports two types of calls: -- Element Call powered by [MatrixRTC][MSC4143] and [LiveKit][livekit-server-github] -- Legacy calls, supported by a STUN/TURN server. +- [MatrixRTC][MSC4143] calls, powered by [LiveKit][livekit-server-github] and frontends such as [Element Call][element-call]. +- Legacy 1-to-1 calls, supported by a STUN/TURN server. [MSC4143]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143 +[element-call-github]: https://github.com/element-hq/element-call/ [livekit-server-github]: https://github.com/livekit/livekit -Both types of calls are supported by different sets of clients, but most clients are moving towards MatrixRTC / Element Call. +Both types of calls are supported by different sets of clients, but most clients are moving towards MatrixRTC. For either one to work correctly, you have to do some additional setup: - For legacy calls to work, you need to set up a TURN/STUN server. [Read the TURN guide for instructions on how to set up coturn](./calls/turn.mdx) -- For MatrixRTC / Element Call to work, you have to set up the LiveKit backend, and optionally configure a TURN server for increased reliability. [Read the LiveKit guide](./calls/livekit.mdx) +- For MatrixRTC calls to work, you have to set up the LiveKit backend, and optionally configure a TURN server for increased reliability. [Read the LiveKit guide](./calls/livekit.mdx) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index 7a89efc10..e48322cb9 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -1,6 +1,6 @@ -import { Tab, Tabs} from '@rspress/core/theme'; +import { Tab, Tabs } from '@rspress/core/theme'; -# MatrixRTC/Element Call Setup +# MatrixRTC/LiveKit Setup This guide assumes that you are using `docker compose` for deployment. diff --git a/docs/calls/turn.mdx b/docs/calls/turn.mdx index 1e65813b5..a3be0cd97 100644 --- a/docs/calls/turn.mdx +++ b/docs/calls/turn.mdx @@ -1,8 +1,8 @@ # Setting up TURN/STUN -[TURN][turn] and [STUN][stun] are used as components in many calling systems. Matrix uses them directly for legacy calls and indirectly for MatrixRTC via Livekit. +[TURN][turn] and [STUN][stun] are used as components in many calling systems. Matrix uses them directly for legacy 1-to-1 calls and indirectly to assist MatrixRTC calls via Livekit. -Continuwuity recommends using [coturn][coturn] as your TURN/STUN server, which is available as a Docker image or a distro package. This guide assumes that you are using docker compose for deployment. +Continuwuity recommends using [coturn][coturn] as your TURN/STUN server, which is available as a Docker image or a distro package. This guide assumes that you are using `docker compose` for deployment. :::tip You can find help setting up TURN/STUN in our support room - [`#continuwuity:continuwuity.org`][support-room] From 94270e732c0c2c836240f0f6ca729aa6c8fba7b8 Mon Sep 17 00:00:00 2001 From: stratself Date: Thu, 5 Nov 2026 17:28:19 +0000 Subject: [PATCH 170/342] docs(livekit): Address review comments, add note for EC's dev mode --- docs/calls/livekit.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index e48322cb9..9931b2c9e 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -62,7 +62,7 @@ services: # Make sure port 7880 is blocked by your firewall to prevent access bypassing your reverse proxy # Alternatively, uncomment the lines below and comment out `network_mode: "host"` - # above to specify port mappings. + # above to use bridge networking and manually specify port mappings. # ports: # - "127.0.0.1:7880:7880/tcp" # - "7881:7881/tcp" @@ -312,7 +312,7 @@ Before debugging, ensure the following prerequisites: - Calls fail to start with `ServerUnreachable` error: a LiveKit URL has been properly configured and exposed in Continuwuity, but the client cannot connect to it for some reason. -For browser-based clients, you can also inspect connections using DevTools' Networking tab, to see which requests are erroring out. +For browser-based clients, you can inspect connections using DevTools' Networking tab, to see which requests are erroring out. You may also want to toggle on Element Call's Developer tab via _Settings > Preferences > Developer mode_ \- various call details and advanced settings can be further tweaked there. ### Docker loopback networking issues From 77bc7476f309ebcb0eabc34fb56762979c462e07 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 14 Oct 2026 05:18:27 +0000 Subject: [PATCH 171/342] docs(auth): Reword registration defaults --- docs/authentication/internal.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/authentication/internal.mdx b/docs/authentication/internal.mdx index 05542b573..0aa566843 100644 --- a/docs/authentication/internal.mdx +++ b/docs/authentication/internal.mdx @@ -4,7 +4,7 @@ Continuwuity comes with an internal database for user authentication, which it u ## Registration -Registration is disabled by default. To enable it, set `allow_registration = true` in your config file and use at least one of the registration methods below. +The following registration methods are available for Continuwuity: | Method | Description | Additional configuration needed | | ------ | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | @@ -19,6 +19,8 @@ Admin-issued tokens are the recommended registration method. These tokens are we Other registration methods are meant for **untrusted, public registration**. Care must be taken when allowing these modes of operation. +If you wish to disable registration entirely, set `allow_registration = false` in your config file. + ## Email configuration Continuwuity can be configured to send emails via an SMTP relay of your choice. These are used for verifying user email addresses and sending password reset links to them. From 6dbe40238d8cefcaff90b04acc1a90900b0b58e5 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 14 Oct 2026 05:39:30 +0000 Subject: [PATCH 172/342] docs(nixos): Beautify nix a bit * Add well-known config example to nixfile * Add postinstall redirect section --- docs/deploying/nixos.mdx | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/docs/deploying/nixos.mdx b/docs/deploying/nixos.mdx index 0d193b4a2..7af9f8755 100644 --- a/docs/deploying/nixos.mdx +++ b/docs/deploying/nixos.mdx @@ -31,7 +31,14 @@ services.matrix-continuwuity = { # address and port are handled automatically # You can add any further configuration here, e.g. - # trusted_servers = [ "matrix.org" ]; + # trusted_servers = [ "matrix.org" ]; + + ## (if using well-known delegation) + # well_known = { + # client = "https://matrix.example.com"; + # server = "matrix.example.com:443"; + # } + }; }; }; @@ -79,3 +86,9 @@ client = "https://matrix.example.com" You'll need to set up a reverse proxy (like NGINX or Caddy) to expose Continuwuity to the internet. You can configure your reverse proxy using NixOS options (e.g. `services.caddy`). See the [reverse proxy setup guide](./generic.mdx#setting-up-the-reverse-proxy) for information on correct reverse proxy configuration. + +Then, test that your setup works by following these [instructions](./generic.mdx#how-do-i-know-it-works). + +## What's next? + +Navigate to [Post-installation](../deploying.mdx#post-installation) for next steps. From c66a863bb2bcfd8bd89584c695763d079e26d398 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 14 Oct 2026 05:56:03 +0000 Subject: [PATCH 173/342] docs(kubernetes): Small wording improvements and postinstall section --- docs/deploying/kubernetes.mdx | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/deploying/kubernetes.mdx b/docs/deploying/kubernetes.mdx index 0293465c6..6e231afb9 100644 --- a/docs/deploying/kubernetes.mdx +++ b/docs/deploying/kubernetes.mdx @@ -1,11 +1,11 @@ # Continuwuity for Kubernetes Continuwuity doesn't support horizontal scalability or distributed loading -natively. However, a deployment in Kubernetes is very similar to the docker -setup. This is because Continuwuity can be fully configured using environment -variables. A sample StatefulSet is shared below. The only thing missing is +natively. However, a deployment in Kubernetes is very similar to the [docker setup](./docker.mdx). +This is because Continuwuity can be fully configured using environment +variables. A sample `StatefulSet` is shared below. The only thing missing is a PVC definition (named `continuwuity-data`) for the volume mounted to -the StatefulSet, an Ingress resources to point your webserver to the +the `StatefulSet`, an Ingress resources to point your webserver to the Continuwuity Pods, and a Service resource (targeting `app.kubernetes.io/name: continuwuity`) to glue the Ingress and Pod together. @@ -103,10 +103,18 @@ spec: --- -Apart from manually configuring the containers, -[a community-maintained Helm Chart is available here to run -conduwuit on Kubernetes](https://gitlab.cronce.io/charts/conduwuit) +## Community maintained Helm Chart -This should be compatible with Continuwuity, but you will need to change the image reference. +Apart from manually configuring the containers, you can consult +a community-maintained Helm Chart for the former `conduwuit` project, +which is available [here][community-helm-chart]. -If changes need to be made, please reach out to the maintainer, as this is not maintained or controlled by the Continuwuity maintainers. +[community-helm-chart]: https://gitlab.cronce.io/charts/conduwuit + +This should be compatible with Continuwuity, but you will need to switch the image reference. + +If changes are needed to be made, please reach out to the maintainer of that repository, as it is not maintained nor controlled by the Continuwuity maintainers. + +## Post-installation + +After successfully setting up your Continuwuity, navigate to [Post-installation](../deploying.mdx#post-installation) for next steps. From 72411502049454be52b8c1d7245840817b62bcb6 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 14 Oct 2026 06:07:13 +0000 Subject: [PATCH 174/342] docs(arch-linux): Add some wordings Ideally want the installation commands here, but will leave for a future commit --- docs/deploying/arch-linux.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/deploying/arch-linux.mdx b/docs/deploying/arch-linux.mdx index 928d1c8e5..e6888e7fd 100644 --- a/docs/deploying/arch-linux.mdx +++ b/docs/deploying/arch-linux.mdx @@ -8,4 +8,6 @@ The development version is available on the AUR as [`continuwuity-git`][aur-cont [aur-continuwuity]: https://aur.archlinux.org/packages/continuwuity [aur-continuwuity-git]: https://aur.archlinux.org/packages/continuwuity-git -Simply install the `continuwuity` package. Configure the service in `/etc/conduwuit/conduwuit.toml`, then enable and start the `continuwuity.service`. +Simply install the `continuwuity` package. Consult the [generic deployment instructions](./generic.mdx) for detailed installation steps, which involves editing `/etc/conduwuit/conduwuit.toml` and setting up a reverse proxy. Finally, enable and start the `continuwuity.service`. + +After successfully setting up Continuwuity, navigate to [Post-installation](../deploying.mdx#post-installation) for next steps. From 49ebbcc63e3950e66661e083f1fc090c5bcaa4a5 Mon Sep 17 00:00:00 2001 From: stratself Date: Thu, 15 Oct 2026 11:22:40 +0000 Subject: [PATCH 175/342] fix(docs): Don't say "check Maintenance for Maintenance" --- docs/deploying.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/deploying.mdx b/docs/deploying.mdx index 3a33819fe..267050c04 100644 --- a/docs/deploying.mdx +++ b/docs/deploying.mdx @@ -101,7 +101,7 @@ After Continuwuity is up and running, consider the following: - See the [**Authentication chapter**](./authentication.mdx) for various ways to access to your homeserver, such as logging in with an external OIDC provider. -- Consult the [**Maintenance**](./maintenance.mdx) page for guidance on maintaining your homeserver. +- Consult the [**Maintenance**](./maintenance.mdx) page for guidance on backups, moderation, and other topics for homeserver management. - If you want to set up an appservice, take a look at the [**Appservice Guide**](./appservices.mdx). From 596f269a90a32ee5841c9086d0a816f0f86026a3 Mon Sep 17 00:00:00 2001 From: stratself Date: Tue, 3 Nov 2026 21:18:55 +0000 Subject: [PATCH 176/342] docs(performance): Update trusted servers tuning info --- docs/guides/performance.mdx | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/docs/guides/performance.mdx b/docs/guides/performance.mdx index 4756b0af2..ff69329fb 100644 --- a/docs/guides/performance.mdx +++ b/docs/guides/performance.mdx @@ -82,6 +82,21 @@ Consult these documents for more information on compression tuning and levels: ## Other tweaks +### Tuning your trusted servers + +:::important Important: Vet your trusted servers! +Trusted servers are your first point of contact when obtaining public keys from the wider federated network. They could theoretically impersonate other servers and cause significant harm to your deployment. Please thoroughly verify your trusted servers' credibility before adding them to your configuration. + +If you need suggestions for trusted servers, ask in the Continuwuity support room. +::: + +For performance and reliability, it is recommended to set up 3 to 5 trusted servers for your deployment. Currently, these must all be Synapse servers. + +```toml +# Example config, using maintainers' recommended homeservers +trusted_servers = ["codestorm.net","starstruck.systems","unredacted.org","matrix.org"] +``` + ### Using UNIX sockets If your homeserver and reverse proxy live on the same machine, you may wish to expose Continuwuity on a UNIX socket instead of a port. This removes TCP overhead between the two programs. @@ -111,25 +126,6 @@ https://matrix.example.com {
-### Tuning your trusted servers - -:::important Important: Vet your trusted servers! -Trusted servers are your first point of contact when obtaining public keys from other servers, and they could theoretically impersonate other servers and cause significant harm to your deployment. Please thoroughly verify your trusted servers' credibility before adding them to your configuration. - -If you need suggestions for trusted servers, ask in the Continuwuity main room. -::: - -Trusted servers are queried sequentially in the order they are listed. If you have multiple trusted servers configured, put the faster ones first: - -```toml -# Example config, using maintainers' recommended homeservers -trusted_servers = ["codestorm.net","starstruck.systems","unredacted.org","matrix.org"] -``` - -Avoid prioritising `matrix.org` as your primary trusted server, as it tends to be quite slow. - -Some users have also reported that increasing `trusted_server_batch_size` helps with faster joins for huge rooms. Start with doubling the default to `2048` until you find a suitable value. - ### Enable HTTP/3 on your reverse proxy Consider enabling the newer **HTTP/3** protocol for inbound connections to Continuwuity. In Caddy HTTP/3 is allowed by default, but you must expose port :443/**udp** on your firewall. From c65eb6de91be9e545b1945bfa7e3b2f9b96e4c66 Mon Sep 17 00:00:00 2001 From: stratself Date: Tue, 3 Nov 2026 22:16:57 +0000 Subject: [PATCH 177/342] docs(push): Update some things (see commit comments) * Make "gateway discovery" test from both client and server * Add docker caveat to locally-hosted push components * Edit a name to match author --- docs/guides/push.mdx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/guides/push.mdx b/docs/guides/push.mdx index 00a6c8e88..041296218 100644 --- a/docs/guides/push.mdx +++ b/docs/guides/push.mdx @@ -78,9 +78,9 @@ To debug and test your UnifiedPush installation, use the [UP-Example] app for An ### UnifiedPush and push gateways -The push gateway URL is usually pre-configured by the client app. However, some clients (such as Element X) implement UnifiedPush's [Gateway Discovery] mechanism, and attempt to detect a push gateway _on the same domain as the push provider_, before falling back to a hardcoded one. +Normally, the push gateway URL is pre-configured by the client app. However, some clients (such as Element X) implement UnifiedPush's [Gateway Discovery] mechanism, and attempt to detect a push gateway _on the same domain as the push provider_ to use before falling back to a hardcoded one. Users of these clients can therefore self-host their own push gateway. -Per the [spec][spec-push-gateway-api], these push gateways must be available on the `/_matrix/push/v1/notify` path of said domain. To test that a push gateway is accessible to the homeserver, make a request for it from the homeserver's IP: +Per the [spec][spec-push-gateway-api], these push gateways must be available on the `/_matrix/push/v1/notify` path of said domain. To test that a push gateway is usable, make a request to it from both the homeserver and the client. The returned response should look like the following: ```txt curl https://push.example.com/_matrix/push/v1/notify @@ -122,7 +122,7 @@ Community tutorials for selfhosting some of these stacks are listed below. Unles - Push gateway: [common-proxies] - Push server: [ejabberd's mod_unified_push] - Push app: [Conversations] (and forks) -- [Element X push notifications via Conversations][alfredolin-xmpp], by Alfredo Lin. +- [Element X push notifications via Conversations][alfredolin-xmpp], by Alfredolin. - Push gateway: [common-proxies] - Push server: [Prosody's mod_unified_push] - Push app: [Conversations] @@ -156,6 +156,8 @@ WARN conduwuit_service::pusher: Pusher URL is a forbidden remote address url=htt To fix this, remove your push gateway or push server's address from `ip_range_denylist`, and restart Continuwuity to apply the changes. +Docker deployments with the push server/gateway on the same host as Continuwuity may run into some further network issues. In this case, consult the [Docker loopback networking issues] section and its workarounds. + ### Push notifications not audible/not displaying This is likely an issue with your account's _push rules_, which determines which events are shown to to the user as notifications. Check these push rules in the client's notifications settings and tweak accordingly. Continuwuity also provides an [`!admin users reset-push-rules`](../reference/admin/users#admin-users-reset-push-rules) command, which restores the rules to the default of notifying for every message. @@ -175,7 +177,7 @@ If you find spurious log entries like this in your Continuwuity deployment: WARN push{user_id="@user:example.com" pushkey="very-long-string-of-letters" events=1}:send_push_notice:send_notice:send_request: conduwuit_service::pusher: Could not send request to pusher https//push.example.com: error sending request for url (https://push.example.com/_matrix/push/v1/notify) ``` -Then, your server is most likely sending push requests to too many invalid targets. This could be due to one of the following reasons: +Then, your server is sending push requests to too many invalid targets. This could be due to one of the following reasons: #### Connection issues between the server and the push gateway From c7c54f880a65bd353005cf14eb89355631cfa045 Mon Sep 17 00:00:00 2001 From: stratself Date: Wed, 4 Nov 2026 08:42:55 +0000 Subject: [PATCH 178/342] docs(arch): Link to AUR/archlinuxcn instructions --- docs/deploying/arch-linux.mdx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/deploying/arch-linux.mdx b/docs/deploying/arch-linux.mdx index e6888e7fd..90adad030 100644 --- a/docs/deploying/arch-linux.mdx +++ b/docs/deploying/arch-linux.mdx @@ -2,12 +2,16 @@ Continuwuity is available in the [`archlinuxcn`][archlinuxcn] repository and AUR with the same package name, [`continuwuity`][aur-continuwuity]. -The development version is available on the AUR as [`continuwuity-git`][aur-continuwuity-git]. +For instructions on adding the archlinuxcn repo to your machine, see the [archlinuxcn README][archlinuxcn-readme] page. For AUR instructions, consult its [entry][aur-archwiki] on the Arch Wiki. + +The development version, which tracks latest commits to the main branch, is also available on the AUR as [`continuwuity-git`][aur-continuwuity-git]. [archlinuxcn]: https://www.archlinuxcn.org/ +[archlinuxcn-readme]: https://github.com/archlinuxcn/repo#usage +[aur-archwiki]: https://wiki.archlinux.org/title/Arch_User_Repository [aur-continuwuity]: https://aur.archlinux.org/packages/continuwuity [aur-continuwuity-git]: https://aur.archlinux.org/packages/continuwuity-git -Simply install the `continuwuity` package. Consult the [generic deployment instructions](./generic.mdx) for detailed installation steps, which involves editing `/etc/conduwuit/conduwuit.toml` and setting up a reverse proxy. Finally, enable and start the `continuwuity.service`. +Once you're done configuring your repos, simply install the `continuwuity` package with `pacman -S continuwuity`. Consult the [generic deployment instructions](./generic.mdx) for detailed steps, which involves editing `/etc/conduwuit/conduwuit.toml` and setting up a reverse proxy. Finally, enable and start the `continuwuity.service`. After successfully setting up Continuwuity, navigate to [Post-installation](../deploying.mdx#post-installation) for next steps. From ba0ea752a97f25fc06aa530be4d60ab06054849c Mon Sep 17 00:00:00 2001 From: stratself Date: Mon, 9 Nov 2026 18:41:29 +0000 Subject: [PATCH 179/342] docs(generic): Recommend the MTRNord tester --- docs/deploying/generic.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/deploying/generic.mdx b/docs/deploying/generic.mdx index 0dafb150a..6be4eac29 100644 --- a/docs/deploying/generic.mdx +++ b/docs/deploying/generic.mdx @@ -246,8 +246,8 @@ to the `#admin:example.com` room and be able to [issue admin commands](../refere To check if your server can communicate with other homeservers, use an external testing tool: -- [Matrix Connectivity Tester](https://federationtester.mtrnord.blog/) -- [Matrix Federation Tester](https://federationtester.matrix.org/) +- [Matrix Connectivity Tester](https://federationtester.mtrnord.blog/) by MTRNord (recommended, with more tests). +- [Matrix Federation Tester](https://federationtester.matrix.org/) by f0x. If you can register your account but cannot join federated rooms, check your configuration and verify that your federation endpoints are opened and forwarded correctly. From 38fb7897bb53805414f09e5262e297d1e800f01c Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Tue, 10 Nov 2026 23:23:41 +0000 Subject: [PATCH 180/342] chore: Release --- CHANGELOG.md | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ Cargo.lock | 24 +++++++++--------- Cargo.toml | 2 +- 3 files changed, 83 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53645d5df..e39a88dcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,73 @@ +# Continuwuity v26.11.0-alpha.1 (2026-11-10) + +## Features + +- Added opt-in OpenTelemetry metrics, exported over OTLP or scraped by Prometheus from `/_continuwuity/metrics`, and a Grafana dashboard. Contributed by @eleboucher. (prometheus-metrics) +- Add support for using custom DNS servers instead of using /etc/resolv.conf. Contributed by @s1lv3r. ([#2056](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2056)) +- Continuwuity now supports configuring additional trusted audience values for deployments using OIDC with an IDP that sends them. Contributed by @ginger ([#2226](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2226)) +- "!admin users list" now hides deactivated users by default, but can display them with the optional "--show-deactivated" flag. "--hide-suspended" and "--hide-locked" have been added as well, which stop suspended and locked users from being displayed respectively. Contributed by @Clubs. ([#2292](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2292)) +- Added support for [MSC4494: Membership-based invite blocking](https://github.com/matrix-org/matrix-spec-proposals/pull/4494) ([#2297](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2297)) +- Appservices now receive typing indicators and read receipts. Contributed by @Jade ([#2327](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2327)) +- Added support for [MSC4363](https://github.com/matrix-org/matrix-spec-proposals/pull/4363) (OAuth step-up authentication). Contributed by @ginger. +- Added support for [MSC4484](https://github.com/matrix-org/matrix-spec-proposals/pull/4484). Clients which use the built-in Matrix server administration APIs will need to ask for the appropriate scope when signing in with OAuth. Contributed by @ginger. +- Implemented unstable support for [MSC4560] (Stripped state requests over federation). Contributed by @ginger. + + [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +- Profile banners are now treated as images when imported from OIDC claims, like avatars already were. +- The first-run version of the web UI now includes a link to the registration page. Contributed by @ginger + +## Bugfixes + +- Invitees are now added as room creators when creating a v12+ trusted private chat. Contributed by @ginger. ([#2162](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2162)) +- Fixed push gateway URLs containing the configured notification path outside of their suffix. Contributed by @eleboucher. ([#2261](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2261)) +- "!admin users change-email" now verifies a user exists before attempting to change their email. Contributed by @Clubs. ([#2298](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2298)) +- Fixed URL preview image MIME types and rejected failed downloads. Contributed by @eleboucher. ([#2308](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2308)) +- Correctly set RocksDB column options, including enabling block caches. Contributed by @Jade ([#2345](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2345)) +- Fix some possible deadlocks/freezes and reduce lock contention (improving performance). Contributed by @Jade ([#2351](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2351)) +- Once again fixed how room extremities are handled, fixing a problem that made continuwuity gradually make rooms needlessly complex, which also caused more frequent state resets. ([#2356](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2356)) +- The OAuth identity reset page is no longer linked from the account management UI to reduce confusion. Contributed by @ginger. ([#2383](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2383)) +- Fixed a worker panic when knocking on a room over federation. Contributed by @eleboucher. ([#2387](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2387)) +- Perform more validation on events received during atomic gapfill from remote servers, fixing a panic if bad data was persisted by another server and later lazily fetched by us. ([#2400](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2400)) +- Redirect URIs in OAuth clients' metadata are now properly validated to be on a subdomain of the OAuth issuer URL domain. Contributed by @ginger. ([#2421](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2421)) +- Fix v12 rooms created by the same user in the same millisecond ending up as the same room. Contributed by @eleboucher. ([#2424](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2424)) +- Client-server API endpoints are now properly ratelimited for unauthenticated requests. Contributed by @ginger. ([#2444](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2444)) +- Setting a profile key longer than 255 bytes now returns 400 `M_KEY_TOO_LARGE` as required by the spec, instead of 413 `M_TOO_LARGE`. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Setting `m.fully_read` via the account data endpoints now returns 405 `M_BAD_JSON` as required by the spec, instead of 400. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Appservices masquerading as a device that does not exist now receive 400 `M_UNKNOWN_DEVICE` as required by the spec, instead of 403 `M_FORBIDDEN`. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Setting profile data that would make the profile exceed 64 KiB now returns 400 `M_PROFILE_TOO_LARGE` as required by the spec, instead of a 500 error. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- The `m.forget_forced_upon_leave` capability now reflects the `forget_forced_upon_leave` config option instead of always being advertised as enabled. ([#2452](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2452)) +- Fixed push notifications for membership events setting `user_is_target` based on the sender rather than the user being notified. ([#2454](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2454)) +- Ensure HTTP clients actually follow the `dns_servers` config option. Contributed by @silversys ([#2460](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2460)) +- Reworked event relations to follow the spec more closely. Pagination of `/relations` now returns the correct pages and `next_batch` tokens, recursive relations are returned in the right order without duplicates, and bundled `m.reference` aggregations now include every reference. Contributed by @Henry-Hiles (QuadRadical). ([#2465](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2465)) +- Read receipts are now more spec compliant, will work better in threads and are less likely to end up causing loops with other software. Contributed by @Jade ([#2481](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2481)) +- Fix gap filling skipping outlier events that are missing their previous events. Contributed by @eleboucher. +- Fix incoming federation events losing state changes when predecessors share the same state-before snapshot. Contributed by @eleboucher. +- Fix new devices sometimes never reaching other users' device lists. Contributed by @eleboucher. +- Fix state resolution applying events out of order, which could undo room joins. Contributed by @eleboucher. +- Fix to-device messages, including room keys, sometimes being lost before delivery. Contributed by @eleboucher. +- For deployments using OIDC with `profile_key_import_mode` set to `on_login`, users' avatars will no longer be clobbered if they didn't change their avatar since their last login. +- Room summary visibility checks are no longer incorrectly applied for remote rooms. Contributed by @ginger. +- The userinfo endpoint is now accessible even if federation is disabled, allowing LiveKit to be used on servers with federation disabled without using the server name whitelist. +- `!admin token issue` can no longer issue registration tokens when `allow_registration` is false. Contributed by @Clubs. + +## Improved Documentation + +- Add the Authentication section to document available auth methods for Continuwuity. The "delegated authentication" guide has also been migrated to here. Contributed by @stratself. ([#2234](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2234)) +- Add a guide for push notifications, detailing how it works, push gateway specifics, troubleshooting common issues, and pointing to external guides for UnifiedPush backends. Contributed by @stratself ([#2244](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2244)) +- The deploying page now includes vital general information about installing Continuwuity: release tracks, update steps, and post-installation recommendations. Contributed by @stratself ([#2252](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2252)) +- Add some missing instructions on configuring Continuwuity on the RPM page. Users are encouraged to use the [generic deploying docs](https://continuwuity.org/deploying/generic) for the bulk of guidance anyhow. Contributed by @stratself ([#2275](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2275)) +- Better, more succinct [introduction page](https://continuwuity.org/introduction.html). Contributed by @stratself ([#2279](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2279)) +- Add a section on [troubleshooting Docker issues](https://continuwuity.org/troubleshooting#docker-issues). Contributed by @stratself. ([#2324](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2324)) +- Instructions for Authelia added to the [OIDC guide](https://continuwuity.org/authentication/oidc.html). Contributed by @fhoekstra ([#2341](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2341)) +- Docker compose examples now use bind mounts by default, instead of Docker volumes, as they are easier to work with esp. for backup/restore. Contributed by @stratself. ([#2353](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2353)) +- The documentation now refers to the Continuwuity Docker service as `continuwuity` instead of `homeserver`. + +## Misc + +- Updated internal Sentry integration setup to the new pattern required by the SDK. #2423 +- Upgraded rocksdb from 11.1.1 to 11.12.0 and jemalloc to 5.4.0. + + # Continuwuity v26.9.1 (2026-09-28) ## Features diff --git a/Cargo.lock b/Cargo.lock index 5e9fc7351..1e88e7434 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -865,7 +865,7 @@ dependencies = [ [[package]] name = "conduwuit" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "clap", "conduwuit_build_metadata", @@ -897,7 +897,7 @@ dependencies = [ [[package]] name = "conduwuit_admin" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "clap", "conduwuit_api", @@ -921,7 +921,7 @@ dependencies = [ [[package]] name = "conduwuit_api" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "axum", "base64 0.23.1", @@ -953,7 +953,7 @@ dependencies = [ [[package]] name = "conduwuit_build_metadata" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "built", "cargo_metadata", @@ -961,7 +961,7 @@ dependencies = [ [[package]] name = "conduwuit_core" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "argon2", "arrayvec", @@ -1031,7 +1031,7 @@ dependencies = [ [[package]] name = "conduwuit_database" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "async-channel", "conduwuit_core", @@ -1051,7 +1051,7 @@ dependencies = [ [[package]] name = "conduwuit_macros" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "itertools 0.15.0", "proc-macro2", @@ -1061,7 +1061,7 @@ dependencies = [ [[package]] name = "conduwuit_router" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "axum", "axum-server", @@ -1094,7 +1094,7 @@ dependencies = [ [[package]] name = "conduwuit_service" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "askama", "assign", @@ -1150,7 +1150,7 @@ dependencies = [ [[package]] name = "conduwuit_web" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "askama", "async-trait", @@ -5167,7 +5167,7 @@ dependencies = [ [[package]] name = "ruminuwuity" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "assign", "http", @@ -7351,7 +7351,7 @@ dependencies = [ [[package]] name = "xtask" -version = "26.9.1" +version = "26.11.0-alpha.1" dependencies = [ "askama", "cargo_metadata", diff --git a/Cargo.toml b/Cargo.toml index 43a9efa85..05831568a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ license = "Apache-2.0" # See also `rust-toolchain.toml` readme = "README.md" repository = "https://forgejo.ellis.link/continuwuation/continuwuity" -version = "26.9.1" +version = "26.11.0-alpha.1" [workspace.metadata.crane] name = "conduwuit" From 93173313ea96e88516902ec64fdc7a4f1d6a5bb4 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 11 Nov 2026 05:08:21 +0000 Subject: [PATCH 181/342] chore(deps): update pre-commit hook crate-ci/typos to v1.52.2 --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cc4bdf6c7..76c5ef022 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,7 +24,7 @@ repos: - id: check-added-large-files - repo: https://github.com/crate-ci/typos - rev: v1.51.1 + rev: v1.52.2 hooks: - id: typos - id: typos From 7b927196a2be3adb5ca881b3377b925bde42b884 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 10 Nov 2026 12:29:18 -0500 Subject: [PATCH 182/342] chore: Use up-to-date Ruma Some changes to sticky events were needed for this also. --- Cargo.lock | 24 +-- Cargo.toml | 2 +- src/api/client/dehydrated_device.rs | 8 +- src/api/client/media.rs | 4 +- src/api/client/media_legacy.rs | 4 +- src/api/client/mutual_rooms.rs | 6 +- src/api/client/room/stripped_state.rs | 8 +- src/api/client/sync/v5.rs | 253 ++++++++++++------------- src/api/client/well_known.rs | 6 +- src/api/server/stripped_state.rs | 6 +- src/service/rooms/summary/mod.rs | 2 +- src/service/sync/mod.rs | 108 +++++++---- src/service/users/dehydrated_device.rs | 2 +- 13 files changed, 234 insertions(+), 199 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1e88e7434..733a76301 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4969,7 +4969,7 @@ dependencies = [ [[package]] name = "ruma" version = "0.17.2" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "assign", "js_int", @@ -4988,7 +4988,7 @@ dependencies = [ [[package]] name = "ruma-appservice-api" version = "0.17.1" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "http", "js_int", @@ -5001,7 +5001,7 @@ dependencies = [ [[package]] name = "ruma-client-api" version = "0.25.2" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "as_variant", "assign", @@ -5023,7 +5023,7 @@ dependencies = [ [[package]] name = "ruma-common" version = "0.20.2" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "as_variant", "base64 0.23.1", @@ -5056,7 +5056,7 @@ dependencies = [ [[package]] name = "ruma-events" version = "0.35.2" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "as_variant", "indexmap 2.14.2", @@ -5077,7 +5077,7 @@ dependencies = [ [[package]] name = "ruma-federation-api" version = "0.16.1" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "bytes", "http", @@ -5099,7 +5099,7 @@ dependencies = [ [[package]] name = "ruma-identifiers-validation" version = "0.14.0" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "js_int", "thiserror 2.0.21", @@ -5108,7 +5108,7 @@ dependencies = [ [[package]] name = "ruma-macros" version = "0.20.2" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "as_variant", "cfg-if", @@ -5124,7 +5124,7 @@ dependencies = [ [[package]] name = "ruma-push-gateway-api" version = "0.16.0" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "js_int", "ruma-common", @@ -5136,7 +5136,7 @@ dependencies = [ [[package]] name = "ruma-signatures" version = "0.22.1" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "base64 0.23.1", "ed25519-dalek", @@ -5153,7 +5153,7 @@ dependencies = [ [[package]] name = "ruma-state-res" version = "0.18.0" -source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "js_int", "ruma-common", @@ -5625,7 +5625,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe" dependencies = [ "annotate-snippets", - "base64 0.23.1", + "base64 0.22.1", "encoding_rs_io", "granit-parser", "nohash-hasher", diff --git a/Cargo.toml b/Cargo.toml index 05831568a..a683d2058 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -357,7 +357,7 @@ version = "1.1.1" # Used for matrix spec type definitions and helpers [workspace.dependencies.ruma] git = "https://github.com/ruma/ruma.git" -rev = "0ed7fba34213f18a628a56f527c6cc795cd7eef5" +rev = "472a23ef86bc0bb40a22d856fc0af539eb9d71b7" features = [ "appservice-api-c", "client-api", diff --git a/src/api/client/dehydrated_device.rs b/src/api/client/dehydrated_device.rs index 72ae2b955..124b90f19 100644 --- a/src/api/client/dehydrated_device.rs +++ b/src/api/client/dehydrated_device.rs @@ -3,10 +3,10 @@ use conduwuit::{Err, Result, at}; use futures::StreamExt; use ruma::{ api::client::dehydrated_device::{ - delete_dehydrated_device::unstable as delete_dehydrated_device, - get_dehydrated_device::unstable as get_dehydrated_device, - get_events::unstable as get_events, - put_dehydrated_device::unstable as put_dehydrated_device, + delete_dehydrated_device::msc3814 as delete_dehydrated_device, + get_dehydrated_device::msc3814 as get_dehydrated_device, + get_events::msc3814 as get_events, + put_dehydrated_device::msc3814 as put_dehydrated_device, }, assign, }; diff --git a/src/api/client/media.rs b/src/api/client/media.rs index 824d98541..669cda35d 100644 --- a/src/api/client/media.rs +++ b/src/api/client/media.rs @@ -30,9 +30,9 @@ pub(crate) async fn get_media_config_route( State(services): State, _body: Ruma, ) -> Result { - Ok(get_media_config::v1::Response::new(ruma_from_usize( + Ok(get_media_config::v1::Response::new(Some(ruma_from_usize( services.server.config.max_request_size, - ))) + )))) } /// # `POST /_matrix/media/v3/upload` diff --git a/src/api/client/media_legacy.rs b/src/api/client/media_legacy.rs index ddc7e9c92..85eaabec9 100644 --- a/src/api/client/media_legacy.rs +++ b/src/api/client/media_legacy.rs @@ -25,9 +25,9 @@ pub(crate) async fn get_media_config_legacy_route( State(services): State, _body: Ruma, ) -> Result { - Ok(get_media_config::v3::Response::new(ruma_from_usize( + Ok(get_media_config::v3::Response::new(Some(ruma_from_usize( services.server.config.max_request_size, - ))) + )))) } /// # `GET /_matrix/media/v1/config` diff --git a/src/api/client/mutual_rooms.rs b/src/api/client/mutual_rooms.rs index 532a5cc79..265238545 100644 --- a/src/api/client/mutual_rooms.rs +++ b/src/api/client/mutual_rooms.rs @@ -13,8 +13,8 @@ use crate::Ruma; #[tracing::instrument(skip_all, name = "mutual_rooms", level = "info")] pub(crate) async fn get_mutual_rooms_unstable_route( State(services): State, - body: Ruma, -) -> Result { + body: Ruma, +) -> Result { let sender_user = body.identity.expect_sender_user()?; if sender_user == body.user_id { @@ -28,7 +28,7 @@ pub(crate) async fn get_mutual_rooms_unstable_route( .collect() .await; - Ok(get_mutual_rooms::unstable::Response::new(mutual_rooms)) + Ok(get_mutual_rooms::msc2666::Response::new(mutual_rooms)) } /// # `GET /_matrix/client/v1/mutual_rooms` diff --git a/src/api/client/room/stripped_state.rs b/src/api/client/room/stripped_state.rs index d30655721..cf686ef2f 100644 --- a/src/api/client/room/stripped_state.rs +++ b/src/api/client/room/stripped_state.rs @@ -15,11 +15,11 @@ use crate::{Ruma, router::ClientIdentity}; #[tracing::instrument(skip_all, name = "stripped_state", level = "info")] pub(crate) async fn get_stripped_state_route( State(services): State, - body: Ruma, -) -> Result { + body: Ruma, +) -> Result { let user_id = body.identity.as_ref().and_then(ClientIdentity::sender_user); - if body.via.len() > get_stripped_state::unstable::MAX_VIAS { + if body.via.len() > get_stripped_state::msc4560::MAX_VIAS { return Err!(Request(TooLarge("Too many vias, please be less indecisive."))); } @@ -59,7 +59,7 @@ pub(crate) async fn get_stripped_state_route( via, RoomStrippedState { state, num_joined_members, .. }, )) => Ok( - assign!(get_stripped_state::unstable::Response::new(via), { state, num_joined_members }), + assign!(get_stripped_state::msc4560::Response::new(via), { state, num_joined_members }), ), | Accessibility::Inaccessible => { Err!(Request(Forbidden("You may not request this room's stripped state."))) diff --git a/src/api/client/sync/v5.rs b/src/api/client/sync/v5.rs index 4f21c1930..4ce7d9c1c 100644 --- a/src/api/client/sync/v5.rs +++ b/src/api/client/sync/v5.rs @@ -24,7 +24,7 @@ use conduwuit::{ use conduwuit_service::{ Services, rooms::read_receipt::pack_receipts, - sync::{SnakeConnectionsKey, into_snake_key}, + sync::{SnakeConnectionsKey, StickyDelivered, into_snake_key}, }; use futures::{ FutureExt, StreamExt, TryFutureExt, @@ -34,7 +34,7 @@ use futures::{ use ruma::{ DeviceId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, UInt, UserId, api::client::sync::sync_events::{ - self, DeviceLists, UnreadNotificationsCount, v5::request::ExtensionRoomConfig, + self, DeviceLists, UnreadNotificationsCount, msc4186::request::ExtensionRoomConfig, }, assign, directory::RoomTypeFilter, @@ -63,7 +63,7 @@ use crate::{ client_ip::ClientIp, }; -type SyncInfo<'a> = (&'a UserId, &'a DeviceId, u64, &'a sync_events::v5::Request); +type SyncInfo<'a> = (&'a UserId, &'a DeviceId, u64, &'a sync_events::msc4186::Request); type TodoRooms = BTreeMap, usize, u64)>; type KnownRooms = BTreeMap>; type KnownRoomUpdates = BTreeMap>; @@ -86,8 +86,9 @@ fn num_live_events<'a>( } struct SyncCollection { - response: sync_events::v5::Response, + response: sync_events::msc4186::Response, known_room_updates: KnownRoomUpdates, + sticky_delivered: StickyDelivered, } /// `POST /_matrix/client/unstable/org.matrix.simplified_msc3575/sync` @@ -103,8 +104,8 @@ struct SyncCollection { pub(crate) async fn sync_events_v5_route( State(ref services): State, ClientIp(client_ip): ClientIp, // NOTE: Required for updating device metadata - body: Ruma, -) -> Result { + body: Ruma, +) -> Result { let sender_user = body.identity.expect_sender_user()?; let sender_device = body.identity.expect_sender_device()?; @@ -142,7 +143,7 @@ pub(crate) async fn sync_events_v5_route( } // Get sticky parameters from cache - let known_rooms = + let (known_rooms, sticky_delivered) = services .sync .update_snake_sync_request_with_cache(&snake_key, globalsince, &mut body); @@ -155,6 +156,7 @@ pub(crate) async fn sync_events_v5_route( &body, globalsince, &known_rooms, + &sticky_delivered, ) .await?; @@ -173,6 +175,7 @@ pub(crate) async fn sync_events_v5_route( &body, globalsince, &known_rooms, + &sticky_delivered, ) .await?; } @@ -202,9 +205,10 @@ async fn collect_sync_response( services: &Services, sender_user: &UserId, sender_device: &DeviceId, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, globalsince: u64, known_rooms: &KnownRooms, + sticky_delivered: &StickyDelivered, ) -> Result { // Bounds every read below and becomes the `pos` returned to the client. // Zero would be echoed back as a request for an initial sync. @@ -262,7 +266,6 @@ async fn collect_sync_response( let pos = next_batch.to_string(); let mut todo_rooms: TodoRooms = BTreeMap::new(); - let mut sticky_rooms = BTreeSet::new(); let sync_info: SyncInfo<'_> = (sender_user, sender_device, globalsince, body); @@ -277,16 +280,16 @@ async fn collect_sync_response( let (account_data, e2ee, to_device, receipts) = try_join4(account_data, e2ee, to_device, receipts).await?; - let extensions = assign!(sync_events::v5::response::Extensions::default(), { + let extensions = assign!(sync_events::msc4186::response::Extensions::default(), { account_data, e2ee, to_device, receipts, - typing: sync_events::v5::response::Typing::default(), - sticky_events: sync_events::v5::response::StickyEvents::default(), + typing: sync_events::msc4186::response::Typing::default(), + sticky_events: sync_events::msc4186::response::StickyEvents::default(), }); - let mut response = assign!(sync_events::v5::Response::new(pos), { + let mut response = assign!(sync_events::msc4186::Response::new(pos), { txn_id: body.txn_id.clone(), lists: BTreeMap::new(), rooms: BTreeMap::new(), @@ -319,7 +322,6 @@ async fn collect_sync_response( all_rooms, &direct_rooms, &mut todo_rooms, - &mut sticky_rooms, known_rooms, &mut response, ) @@ -329,7 +331,6 @@ async fn collect_sync_response( "subscriptions".to_owned(), fetch_subscriptions(services, body, known_rooms, &allowed_rooms, &mut todo_rooms).await, ); - sticky_rooms.extend(body.room_subscriptions.keys().cloned()); let mut timeline_event_ids = BTreeSet::new(); response.rooms = process_rooms( @@ -346,25 +347,31 @@ async fn collect_sync_response( ) .await?; - response.extensions.sticky_events = collect_sticky_events( + let (sticky_events, sticky_delivered) = collect_sticky_events( services, sender_user, body, - &sticky_rooms, + next_batch, + sticky_delivered, + &known_room_updates, &joined_room_ids, - &todo_rooms, &timeline_event_ids, ) - .await?; + .await; + response.extensions.sticky_events = sticky_events; response.extensions.typing = collect_typing_events(services, sender_user, body, &todo_rooms, &known_room_updates) .await?; - Ok(SyncCollection { response, known_room_updates }) + Ok(SyncCollection { + response, + known_room_updates, + sticky_delivered, + }) } -fn response_is_empty(response: &sync_events::v5::Response) -> bool { +fn response_is_empty(response: &sync_events::msc4186::Response) -> bool { let no_account_data = response.extensions.account_data.global.is_empty() && response .extensions @@ -395,7 +402,7 @@ async fn commit_sync_collection( services: &Services, sender_user: &UserId, sender_device: &DeviceId, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, globalsince: u64, snake_key: &SnakeConnectionsKey, collection: &SyncCollection, @@ -408,9 +415,10 @@ async fn commit_sync_collection( .parse() .expect("generated sync position"), collection.known_room_updates.clone(), + collection.sticky_delivered.clone(), ); - if body.extensions.to_device.enabled.unwrap_or(false) { + if body.extensions.to_device.enabled { services .users .remove_to_device_events(sender_user, sender_device, globalsince) @@ -420,7 +428,7 @@ async fn commit_sync_collection( async fn fetch_subscriptions( services: &Services, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, known_rooms: &KnownRooms, allowed_rooms: &BTreeSet, todo_rooms: &mut TodoRooms, @@ -480,15 +488,14 @@ async fn fetch_subscriptions( async fn handle_lists<'a, Rooms, AllRooms>( services: &Services, sender_user: &UserId, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, all_invited_rooms: Rooms, all_joined_rooms: Rooms, all_rooms: AllRooms, direct_rooms: &HashSet, todo_rooms: &'a mut TodoRooms, - sticky_rooms: &mut BTreeSet, known_rooms: &'a KnownRooms, - response: &'_ mut sync_events::v5::Response, + response: &'_ mut sync_events::msc4186::Response, ) -> KnownRoomUpdates where Rooms: Iterator + Clone + Send + 'a, @@ -579,7 +586,6 @@ where .await; sort_rooms_by_activity(&mut active_rooms); let active_rooms: Vec<_> = active_rooms.into_iter().map(at!(0)).collect(); - sticky_rooms.extend(active_rooms.iter().map(|room_id| (*room_id).to_owned())); let mut new_known_rooms: BTreeSet = BTreeSet::new(); @@ -631,7 +637,7 @@ where } response.lists.insert( list_id.clone(), - assign!(sync_events::v5::response::List::default(), { + assign!(sync_events::msc4186::response::List::default(), { count: ruma_from_usize(active_rooms.len()), }), ); @@ -749,10 +755,10 @@ async fn process_rooms<'a, Rooms>( all_invited_rooms: Rooms, all_knocked_rooms: Rooms, todo_rooms: &TodoRooms, - response: &mut sync_events::v5::Response, - body: &sync_events::v5::Request, + response: &mut sync_events::msc4186::Response, + body: &sync_events::msc4186::Request, timeline_event_ids: &mut BTreeSet, -) -> Result> +) -> Result> where Rooms: Iterator + Clone + Send + 'a, { @@ -787,7 +793,7 @@ where rooms.insert( room_id.clone(), - assign!(sync_events::v5::response::Room::new(), { + assign!(sync_events::msc4186::response::Room::new(), { initial: Some(roomsince == &0), invite_state, limited: true, @@ -821,7 +827,7 @@ where rooms.insert( room_id.clone(), - assign!(sync_events::v5::response::Room::new(), { + assign!(sync_events::msc4186::response::Room::new(), { initial: Some(roomsince == &0), invite_state: Some(knock_state), limited: true, @@ -988,7 +994,7 @@ where .state_accessor .get_member(room_id, &user_id) .map_ok(|member_event| { - assign!(sync_events::v5::response::Hero::new(user_id.clone()), { + assign!(sync_events::msc4186::response::Hero::new(user_id.clone()), { name: member_event.displayname, avatar: member_event.avatar_url, }) @@ -1032,7 +1038,7 @@ where rooms.insert( room_id.clone(), - assign!(sync_events::v5::response::Room::new(), { + assign!(sync_events::msc4186::response::Room::new(), { name: services .rooms .state_accessor @@ -1103,64 +1109,61 @@ where Ok(rooms) } +#[expect(clippy::too_many_arguments)] async fn collect_sticky_events( services: &Services, sender_user: &UserId, - body: &sync_events::v5::Request, - sticky_rooms: &BTreeSet, + body: &sync_events::msc4186::Request, + next_batch: u64, + sticky_delivered: &StickyDelivered, + known_room_updates: &KnownRoomUpdates, joined_room_ids: &BTreeSet, - todo_rooms: &TodoRooms, timeline_event_ids: &BTreeSet, -) -> Result { - if !services.config.allow_sticky_events - || !body.extensions.sticky_events.enabled.unwrap_or(false) - { - return Ok(sync_events::v5::response::StickyEvents::default()); +) -> (sync_events::msc4186::response::StickyEvents, StickyDelivered) { + let mut response = sync_events::msc4186::response::StickyEvents::default(); + let mut delivered = StickyDelivered::new(); + + let sticky_events = &body.extensions.sticky_events; + if !services.config.allow_sticky_events || !sticky_events.enabled.unwrap_or(false) { + return (response, delivered); } - let since = body - .extensions - .sticky_events - .since - .as_deref() - .and_then(|token| token.parse::().ok()) - .unwrap_or(0); - let limit = body - .extensions - .sticky_events + let scope = extension_scope( + sticky_events.lists.as_deref(), + sticky_events.rooms.as_deref(), + body.lists.keys().map(String::as_str), + known_room_updates, + ); + let limit = sticky_events .limit .map_or(DEFAULT_STICKY_LIMIT, usize_from_ruma) .clamp(1, DEFAULT_STICKY_LIMIT); let now = u64::from(MilliSecondsSinceUnixEpoch::now().get()); let oldest_sticky_ts = now.saturating_sub(sticky::MAX_DURATION_MS); - let mut backlog = Vec::new(); - let mut stream = Vec::new(); - for room_id in sticky_rooms - .iter() - .filter(|room_id| joined_room_ids.contains(*room_id)) - { - // a room the client has not seen before needs its whole backlog, which - // a single stream position cannot express - let initial = todo_rooms - .get(room_id) - .is_some_and(|&(_, _, roomsince)| roomsince == 0); + for room_id in scope.intersection(joined_room_ids) { + let since = sticky_delivered.get(room_id).copied(); + let mut pending = Vec::new(); let pdus = services.rooms.timeline.pdus_rev(room_id, None).ignore_err(); pin_mut!(pdus); while let Some((count, pdu)) = pdus.next().await { - // nothing older than this can still be sticky, and on the stream we - // have already delivered everything up to `since` - if u64::from(pdu.origin_server_ts) < oldest_sticky_ts - || (!initial && count <= PduCount::Normal(since)) - { - break; - } - let PduCount::Normal(count) = count else { continue; }; + if count > next_batch { + continue; + } + + // Nothing older than this can still be sticky, and everything up to + // `since` has already been delivered + if u64::from(pdu.origin_server_ts) < oldest_sticky_ts + || since.is_some_and(|since| count <= since) + { + break; + } + let is_sticky = pdu .sticky .as_deref() @@ -1177,38 +1180,26 @@ async fn collect_sticky_events( continue; } - if count > since { - stream.push((count, room_id.clone(), pdu)); - } else { - backlog.push((room_id.clone(), pdu)); - } + pending.push((count, pdu)); } - } - stream.sort_by_key(|(count, ..)| *count); - let mut response = sync_events::v5::response::StickyEvents::default(); + pending.reverse(); + let truncated = pending.len() > limit; + let mut last_count = next_batch; + for (count, pdu) in pending.into_iter().take(limit) { + push_sticky_event(services, &mut response, sender_user, room_id.clone(), pdu).await; + last_count = count; + } - // MSC4480 lets us ignore the limit for a newly visible room's backlog - for (room_id, pdu) in backlog { - push_sticky_event(services, &mut response, sender_user, room_id, pdu).await; + delivered.insert(room_id.clone(), if truncated { last_count } else { next_batch }); } - let mut next_batch = None; - for (count, room_id, pdu) in stream.into_iter().take(limit) { - push_sticky_event(services, &mut response, sender_user, room_id, pdu).await; - next_batch = Some(count); - } - - if !response.rooms.is_empty() { - response.next_batch = Some(next_batch.unwrap_or(since).to_string()); - } - - Ok(response) + (response, delivered) } async fn push_sticky_event( services: &Services, - response: &mut sync_events::v5::response::StickyEvents, + response: &mut sync_events::msc4186::response::StickyEvents, sender_user: &UserId, room_id: OwnedRoomId, mut pdu: PduEvent, @@ -1275,12 +1266,12 @@ async fn collect_required_state( async fn collect_typing_events( services: &Services, sender_user: &UserId, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, todo_rooms: &TodoRooms, known_room_updates: &KnownRoomUpdates, -) -> Result { +) -> Result { if !body.extensions.typing.enabled.unwrap_or(false) { - return Ok(sync_events::v5::response::Typing::default()); + return Ok(sync_events::msc4186::response::Typing::default()); } let typing = &body.extensions.typing; let scope = extension_scope( @@ -1290,10 +1281,10 @@ async fn collect_typing_events( known_room_updates, ); if scope.is_empty() { - return Ok(sync_events::v5::response::Typing::default()); + return Ok(sync_events::msc4186::response::Typing::default()); } - let mut typing_response = sync_events::v5::response::Typing::default(); + let mut typing_response = sync_events::msc4186::response::Typing::default(); for (room_id, (_, _, roomsince)) in todo_rooms { if !scope.contains(room_id) { continue; @@ -1373,12 +1364,17 @@ fn extension_scope<'a>( async fn collect_account_data( services: &Services, - (sender_user, _, globalsince, body): (&UserId, &DeviceId, u64, &sync_events::v5::Request), -) -> sync_events::v5::response::AccountData { - let mut account_data = sync_events::v5::response::AccountData::default(); + (sender_user, _, globalsince, body): ( + &UserId, + &DeviceId, + u64, + &sync_events::msc4186::Request, + ), +) -> sync_events::msc4186::response::AccountData { + let mut account_data = sync_events::msc4186::response::AccountData::default(); if !body.extensions.account_data.enabled.unwrap_or(false) { - return sync_events::v5::response::AccountData::default(); + return sync_events::msc4186::response::AccountData::default(); } account_data.global = services @@ -1413,15 +1409,15 @@ async fn collect_e2ee<'a, Rooms>( &UserId, &DeviceId, u64, - &sync_events::v5::Request, + &sync_events::msc4186::Request, ), all_joined_rooms: Rooms, -) -> Result +) -> Result where Rooms: Iterator + Send + 'a, { - if !body.extensions.e2ee.enabled.unwrap_or(false) { - return Ok(sync_events::v5::response::E2EE::default()); + if !body.extensions.e2ee.enabled { + return Ok(sync_events::msc4186::response::E2EE::default()); } let mut left_encrypted_users = HashSet::new(); // Users that have left any encrypted rooms the sender was in let mut device_list_changes = HashSet::new(); @@ -1608,7 +1604,7 @@ where } } - Ok(assign!(sync_events::v5::response::E2EE::default(), { + Ok(assign!(sync_events::msc4186::response::E2EE::default(), { device_unused_fallback_key_types: None, device_one_time_keys_count: services @@ -1627,12 +1623,12 @@ async fn collect_to_device( services: &Services, (sender_user, sender_device, globalsince, body): SyncInfo<'_>, next_batch: u64, -) -> Option { - if !body.extensions.to_device.enabled.unwrap_or(false) { +) -> Option { + if !body.extensions.to_device.enabled { return None; } - Some(assign!(sync_events::v5::response::ToDevice::default(), { + Some(assign!(sync_events::msc4186::response::ToDevice::default(), { next_batch: next_batch.to_string(), events: services .users @@ -1643,9 +1639,9 @@ async fn collect_to_device( })) } -async fn collect_receipts(_services: &Services) -> sync_events::v5::response::Receipts { +async fn collect_receipts(_services: &Services) -> sync_events::msc4186::response::Receipts { // TODO: get explicitly requested read receipts - sync_events::v5::response::Receipts::default() + sync_events::msc4186::response::Receipts::default() } #[cfg(test)] @@ -1658,23 +1654,25 @@ mod tests { fn custom_room_type() -> RoomTypeFilter { RoomTypeFilter::from(Some("com.example")) } - fn response() -> sync_events::v5::Response { sync_events::v5::Response::new("1".to_owned()) } + fn response() -> sync_events::msc4186::Response { + sync_events::msc4186::Response::new("1".to_owned()) + } - fn typing_scope_request() -> sync_events::v5::Request { - let mut request = sync_events::v5::Request::new(); + fn typing_scope_request() -> sync_events::msc4186::Request { + let mut request = sync_events::msc4186::Request::new(); request .lists - .insert("first".to_owned(), sync_events::v5::request::List::default()); + .insert("first".to_owned(), sync_events::msc4186::request::List::default()); request .lists - .insert("second".to_owned(), sync_events::v5::request::List::default()); + .insert("second".to_owned(), sync_events::msc4186::request::List::default()); request.room_subscriptions.insert( owned_room_id!("!subscription-a:example.com"), - sync_events::v5::request::RoomSubscription::default(), + sync_events::msc4186::request::RoomSubscription::default(), ); request.room_subscriptions.insert( owned_room_id!("!subscription-b:example.com"), - sync_events::v5::request::RoomSubscription::default(), + sync_events::msc4186::request::RoomSubscription::default(), ); request } @@ -1768,9 +1766,10 @@ mod tests { #[test] fn a_room_with_no_events_is_still_empty() { let mut response = response(); - response - .rooms - .insert(owned_room_id!("!a:example.com"), sync_events::v5::response::Room::default()); + response.rooms.insert( + owned_room_id!("!a:example.com"), + sync_events::msc4186::response::Room::default(), + ); assert!(response_is_empty(&response)); } @@ -1781,7 +1780,7 @@ mod tests { let mut response = response(); response .rooms - .insert(room_id.to_owned(), sync_events::v5::response::Room::default()); + .insert(room_id.to_owned(), sync_events::msc4186::response::Room::default()); response .extensions .receipts @@ -1846,7 +1845,7 @@ mod tests { #[test] fn to_device_without_events_is_empty() { let mut response = response(); - response.extensions.to_device = Some(sync_events::v5::response::ToDevice::default()); + response.extensions.to_device = Some(sync_events::msc4186::response::ToDevice::default()); assert!(response_is_empty(&response)); } diff --git a/src/api/client/well_known.rs b/src/api/client/well_known.rs index 749571f99..9e2552307 100644 --- a/src/api/client/well_known.rs +++ b/src/api/client/well_known.rs @@ -43,9 +43,9 @@ pub(crate) async fn well_known_client( /// homeserver, implementing MSC4143. pub(crate) async fn get_rtc_transports( State(services): State, - _body: Ruma, -) -> Result { - Ok(ruma::api::client::rtc::transports::v1::Response::new( + _body: Ruma, +) -> Result { + Ok(ruma::api::client::rtc::transports::msc4143::Response::new( services.config.matrix_rtc.foci.clone(), )) } diff --git a/src/api/server/stripped_state.rs b/src/api/server/stripped_state.rs index 9680583ce..8fb0dc83d 100644 --- a/src/api/server/stripped_state.rs +++ b/src/api/server/stripped_state.rs @@ -14,8 +14,8 @@ use crate::Ruma; /// [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 pub(crate) async fn get_stripped_state_route( State(services): State, - body: Ruma, -) -> Result { + body: Ruma, +) -> Result { if let Some(forbidden_type) = body .state .iter() @@ -42,7 +42,7 @@ pub(crate) async fn get_stripped_state_route( .await { | Accessibility::Accessible(RoomStrippedState { state, num_joined_members, .. }) => Ok( - assign!(get_stripped_state::unstable::Response::default(), { state, num_joined_members }), + assign!(get_stripped_state::msc4560::Response::default(), { state, num_joined_members }), ), | Accessibility::Inaccessible => { Err!(Request(Forbidden("You may not access this room's stripped state."))) diff --git a/src/service/rooms/summary/mod.rs b/src/service/rooms/summary/mod.rs index 42a277c17..ee643b6a6 100644 --- a/src/service/rooms/summary/mod.rs +++ b/src/service/rooms/summary/mod.rs @@ -666,7 +666,7 @@ impl Service { return Accessibility::NotFound; } - let request = assign!(get_stripped_state::unstable::Request::new(room_id.to_owned()), { + let request = assign!(get_stripped_state::msc4560::Request::new(room_id.to_owned()), { state: state.to_owned(), num_joined_members }); diff --git a/src/service/sync/mod.rs b/src/service/sync/mod.rs index e3a07c40d..46e56894b 100644 --- a/src/service/sync/mod.rs +++ b/src/service/sync/mod.rs @@ -6,7 +6,8 @@ use std::{ use conduwuit::{Result, SyncMutex, trace}; use futures::StreamExt; use ruma::{ - OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId, api::client::sync::sync_events::v5, + OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId, + api::client::sync::sync_events::msc4186, }; use tokio::sync::watch; @@ -24,21 +25,32 @@ struct Services { #[allow(unused, reason = "TODO refactor")] struct SlidingSyncCache { - lists: BTreeMap, - subscriptions: BTreeMap, + lists: BTreeMap, + subscriptions: BTreeMap, // For every room, the roomsince number known_rooms: BTreeMap>, - extensions: v5::request::Extensions, + extensions: msc4186::request::Extensions, } +/// For every in-scope room, the stream position up to which sticky events +/// have been delivered on this connection. +pub type StickyDelivered = BTreeMap; + #[derive(Default)] struct SnakeSyncCache { - lists: BTreeMap, - subscriptions: BTreeMap, + lists: BTreeMap, + subscriptions: BTreeMap, known_rooms: BTreeMap>, + sticky_delivered: StickyDelivered, acknowledged_pos: u64, - pending: BTreeMap>>, - extensions: v5::request::Extensions, + pending: BTreeMap, + extensions: msc4186::request::Extensions, +} + +#[derive(Default)] +struct PendingState { + known_rooms: BTreeMap>, + sticky_delivered: StickyDelivered, } impl SnakeSyncCache { @@ -47,13 +59,19 @@ impl SnakeSyncCache { } fn acknowledge(&mut self, pos: u64) { - if let Some(known_rooms) = self.pending.remove(&pos) { - self.known_rooms = known_rooms; + if let Some(pending) = self.pending.remove(&pos) { + self.known_rooms = pending.known_rooms; + self.sticky_delivered = pending.sticky_delivered; self.acknowledged_pos = pos; } } - fn stage_pending(&mut self, pos: u64, known_rooms: BTreeMap>) { + fn stage_pending( + &mut self, + pos: u64, + known_rooms: BTreeMap>, + sticky_delivered: StickyDelivered, + ) { let mut pending_rooms = self.known_rooms.clone(); for (list_id, rooms) in known_rooms { let list = pending_rooms.entry(list_id).or_default(); @@ -61,7 +79,10 @@ impl SnakeSyncCache { list.insert(room_id, pos); } } - self.pending.insert(pos, pending_rooms); + self.pending.insert(pos, PendingState { + known_rooms: pending_rooms, + sticky_delivered, + }); } } @@ -177,8 +198,8 @@ impl Service { &self, snake_key: &SnakeConnectionsKey, pos: u64, - request: &mut v5::Request, - ) -> BTreeMap> { + request: &mut msc4186::Request, + ) -> (BTreeMap>, StickyDelivered) { let mut cache = self.snake_connections.lock(); let cached = Arc::clone( cache @@ -190,7 +211,7 @@ impl Service { cached.acknowledge(pos); - //v5::Request::try_from_http_request(req, path_args); + //msc4186::Request::try_from_http_request(req, path_args); for (list_id, list) in &mut request.lists { if let Some(cached_list) = cached.lists.get(list_id) { list_or_sticky( @@ -224,18 +245,6 @@ impl Service { .room_subscriptions .extend(cached.subscriptions.clone()); - request.extensions.e2ee.enabled = request - .extensions - .e2ee - .enabled - .or(cached.extensions.e2ee.enabled); - - request.extensions.to_device.enabled = request - .extensions - .to_device - .enabled - .or(cached.extensions.to_device.enabled); - request.extensions.account_data.enabled = request .extensions .account_data @@ -275,9 +284,25 @@ impl Service { &mut request.extensions.receipts.lists, cached.extensions.receipts.lists.clone(), ); + some_or_sticky( + &mut request.extensions.sticky_events.enabled, + cached.extensions.sticky_events.enabled, + ); + some_or_sticky( + &mut request.extensions.sticky_events.limit, + cached.extensions.sticky_events.limit, + ); + some_or_sticky( + &mut request.extensions.sticky_events.rooms, + cached.extensions.sticky_events.rooms.clone(), + ); + some_or_sticky( + &mut request.extensions.sticky_events.lists, + cached.extensions.sticky_events.lists.clone(), + ); cached.extensions = request.extensions.clone(); - cached.known_rooms.clone() + (cached.known_rooms.clone(), cached.sticky_delivered.clone()) } pub fn store_snake_sync_pending( @@ -285,6 +310,7 @@ impl Service { key: &SnakeConnectionsKey, pos: u64, known_rooms: BTreeMap>, + sticky_delivered: StickyDelivered, ) { let mut cache = self.snake_connections.lock(); let cached = Arc::clone( @@ -295,13 +321,13 @@ impl Service { let cached = &mut cached.lock(); drop(cache); - cached.stage_pending(pos, known_rooms); + cached.stage_pending(pos, known_rooms, sticky_delivered); } pub fn update_snake_sync_subscriptions( &self, key: &SnakeConnectionsKey, - subscriptions: BTreeMap, + subscriptions: BTreeMap, ) { let mut cache = self.snake_connections.lock(); let cached = Arc::clone( @@ -412,10 +438,13 @@ mod tests { fn pending_rooms_are_committed_only_when_the_response_pos_is_acknowledged() { let room_id = OwnedRoomId::try_from("!room:example.com").unwrap(); let mut cache = SnakeSyncCache { - pending: BTreeMap::from([( - 42, - BTreeMap::from([("list".to_owned(), BTreeMap::from([(room_id, 42)]))]), - )]), + pending: BTreeMap::from([(42, PendingState { + known_rooms: BTreeMap::from([( + "list".to_owned(), + BTreeMap::from([(room_id, 42)]), + )]), + sticky_delivered: StickyDelivered::new(), + })]), ..Default::default() }; @@ -438,7 +467,11 @@ mod tests { let dropped = OwnedRoomId::try_from("!dropped:example.com").unwrap(); let mut cache = SnakeSyncCache::default(); let stage = |cache: &mut SnakeSyncCache, pos, rooms: BTreeSet| { - cache.stage_pending(pos, BTreeMap::from([("all_rooms".to_owned(), rooms)])); + cache.stage_pending( + pos, + BTreeMap::from([("all_rooms".to_owned(), rooms)]), + StickyDelivered::new(), + ); cache.acknowledge(pos); }; @@ -458,7 +491,10 @@ mod tests { fn overlapping_responses_accept_either_response_position() { let mut cache = SnakeSyncCache { acknowledged_pos: 100, - pending: BTreeMap::from([(200, BTreeMap::new()), (201, BTreeMap::new())]), + pending: BTreeMap::from([ + (200, PendingState::default()), + (201, PendingState::default()), + ]), ..Default::default() }; diff --git a/src/service/users/dehydrated_device.rs b/src/service/users/dehydrated_device.rs index 83ab1b343..065d9013e 100644 --- a/src/service/users/dehydrated_device.rs +++ b/src/service/users/dehydrated_device.rs @@ -3,7 +3,7 @@ use conduwuit_database::{Deserialized, Json}; use ruma::{ DeviceId, OwnedDeviceId, UserId, api::client::dehydrated_device::{ - DehydratedDeviceData, put_dehydrated_device::unstable::Request, + DehydratedDeviceData, put_dehydrated_device::msc3814::Request, }, serde::Raw, }; From aef031c9d7b98773c89a6acc49132cdb072c3ddb Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 10 Nov 2026 13:28:01 -0500 Subject: [PATCH 183/342] fix(sync): Give each sliding sync response its own pos --- src/api/client/sync/v5.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/api/client/sync/v5.rs b/src/api/client/sync/v5.rs index 4ce7d9c1c..e97319e46 100644 --- a/src/api/client/sync/v5.rs +++ b/src/api/client/sync/v5.rs @@ -211,8 +211,7 @@ async fn collect_sync_response( sticky_delivered: &StickyDelivered, ) -> Result { // Bounds every read below and becomes the `pos` returned to the client. - // Zero would be echoed back as a request for an initial sync. - let next_batch = services.globals.current_count()?.max(1); + let next_batch = services.globals.next_count()?; let all_joined_rooms = services .rooms From cacf6ff912d90786f89a80e75e32c536a6bb46eb Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 11 Nov 2026 05:03:56 +0000 Subject: [PATCH 184/342] chore(deps): update rust crate syn to v3.0.10 --- Cargo.lock | 50 +++++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 733a76301..4aab0148e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -193,7 +193,7 @@ dependencies = [ "rustc-hash", "serde", "serde_derive", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -255,7 +255,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -497,7 +497,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 3.0.9", + "syn 2.0.119", ] [[package]] @@ -785,7 +785,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1056,7 +1056,7 @@ dependencies = [ "itertools 0.15.0", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1379,7 +1379,7 @@ dependencies = [ "proc-macro2", "quote", "strict", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1621,7 +1621,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1643,7 +1643,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core 0.24.1", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1763,7 +1763,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2169,7 +2169,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -3174,7 +3174,7 @@ dependencies = [ "proc-macro2", "quote", "regex", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4478,7 +4478,7 @@ dependencies = [ "proc-macro-error-attr3", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4775,7 +4775,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -5117,7 +5117,7 @@ dependencies = [ "quote", "ruma-identifiers-validation", "serde", - "syn 3.0.9", + "syn 3.0.10", "toml 1.2.1+spec-1.1.0", ] @@ -5662,7 +5662,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -5781,7 +5781,7 @@ dependencies = [ "darling 0.24.1", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -6077,9 +6077,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -6103,7 +6103,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -6205,7 +6205,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -6315,7 +6315,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -7003,7 +7003,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] @@ -7384,7 +7384,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -7425,7 +7425,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -7465,7 +7465,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] From 4ebf44412c9cd07819ee721dce301d8cabdb2600 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 11 Nov 2026 05:04:03 +0000 Subject: [PATCH 185/342] chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.227.4 --- .forgejo/workflows/renovate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/renovate.yml b/.forgejo/workflows/renovate.yml index 57a6c3048..8e3c04e51 100644 --- a/.forgejo/workflows/renovate.yml +++ b/.forgejo/workflows/renovate.yml @@ -43,7 +43,7 @@ jobs: name: Renovate runs-on: ubuntu-latest container: - image: ghcr.io/renovatebot/renovate:44.210.1@sha256:45cc73346c44a9afe037f2d19766f2b545b59b2ed31b937b5b09017d2958e45f + image: ghcr.io/renovatebot/renovate:44.227.4@sha256:e09d40686f73d43b2c1e4667cb47d3c1d24a6ac730b74ce7aced9c84f68594f1 options: --tmpfs /tmp:exec steps: - name: Checkout From fca19a983dda123121f50e8d1364db43c2622c2c Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Wed, 11 Nov 2026 18:26:25 +0100 Subject: [PATCH 186/342] chore: Update resolvematrix to 1.4.1 Also includes other updates cuz thats what cargo does --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4aab0148e..71b6cc3f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -497,7 +497,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] @@ -4897,9 +4897,9 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" [[package]] name = "resolvematrix" -version = "1.4.0" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e7767f4eb1d58880d6b33135a6c098cc8fbccecb259a833b44448c0de144dac" +checksum = "565260441c783e26272b2d879525e80e97552e851fffa723cb0cfe0a3c46df92" dependencies = [ "hickory-resolver", "num-traits", @@ -5625,7 +5625,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe" dependencies = [ "annotate-snippets", - "base64 0.22.1", + "base64 0.23.1", "encoding_rs_io", "granit-parser", "nohash-hasher", diff --git a/Cargo.toml b/Cargo.toml index a683d2058..214b9b984 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -600,7 +600,7 @@ features = ["std"] version = "0.3.0" [workspace.dependencies.resolvematrix] -version = "1.4.0" +version = "1.4.1" [workspace.dependencies.serde_urlencoded] version = "0.7.1" From 9be45212f1520d73bf19094f89d295cc9d955478 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 11 Nov 2026 11:14:20 +0100 Subject: [PATCH 187/342] fix: Don't require resolv.conf when dns_servers is configured --- changelog.d/2495.bugfix.md | 1 + src/service/client/mod.rs | 12 ++++++++++-- .../rooms/event_handler/state_at_incoming/tests.rs | 3 ++- 3 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 changelog.d/2495.bugfix.md diff --git a/changelog.d/2495.bugfix.md b/changelog.d/2495.bugfix.md new file mode 100644 index 000000000..178437bc9 --- /dev/null +++ b/changelog.d/2495.bugfix.md @@ -0,0 +1 @@ +Fix the DNS resolver failing to start without `/etc/resolv.conf` when `dns_servers` is configured. Contributed by @eleboucher. diff --git a/src/service/client/mod.rs b/src/service/client/mod.rs index f258f5195..39f00b40c 100644 --- a/src/service/client/mod.rs +++ b/src/service/client/mod.rs @@ -338,8 +338,16 @@ fn builder_interface( fn get_dns_resolver(server: &Arc) -> Result> { let config = &server.config; - let (system_resolver_config, mut opts) = hickory_resolver::system_conf::read_system_conf() - .map_err(|e| err!(error!("Failed to configure DNS resolver from system: {e}")))?; + let (system_resolver_config, mut opts) = + match hickory_resolver::system_conf::read_system_conf() { + | Ok(system_conf) => system_conf, + | Err(e) if config.dns_servers.is_empty() => + return Err(err!(error!("Failed to configure DNS resolver from system: {e}"))), + | Err(e) => { + warn!("Failed to read system DNS configuration, using dns_servers: {e}"); + Default::default() + }, + }; let mut conf = ResolverConfig::from_name_servers(vec![]); diff --git a/src/service/rooms/event_handler/state_at_incoming/tests.rs b/src/service/rooms/event_handler/state_at_incoming/tests.rs index bf7e0035b..c1d4c0ef9 100644 --- a/src/service/rooms/event_handler/state_at_incoming/tests.rs +++ b/src/service/rooms/event_handler/state_at_incoming/tests.rs @@ -222,7 +222,8 @@ async fn test_services() -> (Arc, std::path::PathBuf) { "database_path": path, "db_cache_capacity_mb": 16.0, "rocksdb_write_buffer_capacity_mb": 4.0, - "allow_local_presence": false + "allow_local_presence": false, + "dns_servers": ["127.0.0.1"] })) .unwrap(); let runtime = tokio::runtime::Handle::current(); From aefededfc89de8b03b6ca7ccf7f37d28c61268a3 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 11 Nov 2026 12:24:15 +0100 Subject: [PATCH 188/342] test: Skip system CA roots in state_at_incoming test services --- src/service/rooms/event_handler/state_at_incoming/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/service/rooms/event_handler/state_at_incoming/tests.rs b/src/service/rooms/event_handler/state_at_incoming/tests.rs index c1d4c0ef9..d46395cee 100644 --- a/src/service/rooms/event_handler/state_at_incoming/tests.rs +++ b/src/service/rooms/event_handler/state_at_incoming/tests.rs @@ -223,7 +223,8 @@ async fn test_services() -> (Arc, std::path::PathBuf) { "db_cache_capacity_mb": 16.0, "rocksdb_write_buffer_capacity_mb": 4.0, "allow_local_presence": false, - "dns_servers": ["127.0.0.1"] + "dns_servers": ["127.0.0.1"], + "allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true })) .unwrap(); let runtime = tokio::runtime::Handle::current(); From cb37a9cf0b7c41b0363c62be6f197cb0d94c4f35 Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 8 Nov 2026 19:31:05 +0000 Subject: [PATCH 189/342] feat: Assert content type on federation responses --- changelog.d/+74cd7995.feature.md | 1 + src/service/federation/execute.rs | 45 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 changelog.d/+74cd7995.feature.md diff --git a/changelog.d/+74cd7995.feature.md b/changelog.d/+74cd7995.feature.md new file mode 100644 index 000000000..da20c50ae --- /dev/null +++ b/changelog.d/+74cd7995.feature.md @@ -0,0 +1 @@ +Check content-type header on federation responses, ignoring any that don't match (spec compliance) diff --git a/src/service/federation/execute.rs b/src/service/federation/execute.rs index 78f3ee723..54fe61e81 100644 --- a/src/service/federation/execute.rs +++ b/src/service/federation/execute.rs @@ -300,6 +300,23 @@ async fn into_http_response( actual.base_url(), ); + if url.path() != "/.well-known/matrix/server" { + // For some reason, the spec starts off saying federation responses MUST + // include a `Content-Type` header of `application/json` on all + // responses. Then, the definition for the well-known server endpoint + // says that it's a SHOULD and that servers SHOULD just assume that the + // response is JSON regardless... And then there's media wayyyy down in + // the spec doc that just throws a `multipart/mixed` in there. + enforce_content_type( + &response, + if url.path().starts_with("/_matrix/federation/v1/media/") { + "multipart/mixed" + } else { + "application/json" + }, + )?; + } + let mut http_response_builder = http::Response::builder() .status(status) .version(response.version()); @@ -353,6 +370,34 @@ fn handle_error( Err(e.into()) } +/// Enforces that the `Content-Type` response header is present, and that the +/// first part matches the expected header. This does not enforce that multipart +/// responses have a boundary as only the text left of a semicolon, if present, +/// is compared. +/// +/// Returns `M_UNKNOWN` with HTTP 415 (Unsupported Media Type) if the response +/// header is missing or mismatched. +fn enforce_content_type(response: &Response, expected: &str) -> Result<()> { + match response + .headers() + .get(&http::header::CONTENT_TYPE) + .and_then(|h| h.to_str().ok()) + .map(|h| h.split_once(';').unwrap_or((h, "")).0) + { + | Some(ct) if ct == expected => Ok(()), + | Some(ct) => Err!(Request( + Unknown( + "Remote server returned the wrong Content-Type: expected {expected}, got {ct:?}" + ), + UNSUPPORTED_MEDIA_TYPE + )), + | None => Err!(Request( + Unknown("Remote server did not return a Content-Type header"), + UNSUPPORTED_MEDIA_TYPE + )), + } +} + /// A trait for the input types of acceptable path builders for outgoing /// federation requests. /// From 4bd09a6d88fff57f8a0b76959433769bf8b39616 Mon Sep 17 00:00:00 2001 From: timedout Date: Wed, 11 Nov 2026 07:47:36 +0000 Subject: [PATCH 190/342] fix: Find some zen Non-successful media responses get the `application/json` treatment, and the content-type is lowercased for case-insensitive matching, per RFC something or other I forgot already --- src/service/federation/execute.rs | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/service/federation/execute.rs b/src/service/federation/execute.rs index 54fe61e81..b32174c22 100644 --- a/src/service/federation/execute.rs +++ b/src/service/federation/execute.rs @@ -307,14 +307,17 @@ async fn into_http_response( // says that it's a SHOULD and that servers SHOULD just assume that the // response is JSON regardless... And then there's media wayyyy down in // the spec doc that just throws a `multipart/mixed` in there. - enforce_content_type( - &response, - if url.path().starts_with("/_matrix/federation/v1/media/") { - "multipart/mixed" - } else { - "application/json" - }, - )?; + // + // Media has a special case regarding status codes. Only 200 OK + // responses should have the multipart assertion, as errors are JSON. + let ct = if url.path().starts_with("/_matrix/federation/v1/media/") + && response.status().is_success() + { + "multipart/mixed" + } else { + "application/json" + }; + enforce_content_type(&response, ct)?; } let mut http_response_builder = http::Response::builder() @@ -378,11 +381,19 @@ fn handle_error( /// Returns `M_UNKNOWN` with HTTP 415 (Unsupported Media Type) if the response /// header is missing or mismatched. fn enforce_content_type(response: &Response, expected: &str) -> Result<()> { + // N.B. Content type's value is case-insensitive per RFC 9110. The Matrix + // spec explicitly prescribes `application/json` and `multipart/mixed` etc, + // but it's assumed they're intended to be case-insensitive. + debug_assert_eq!( + expected, + expected.to_lowercase(), + "Content type checks should use the lowercase content type" + ); // ^ Saves us double-folding match response .headers() .get(&http::header::CONTENT_TYPE) .and_then(|h| h.to_str().ok()) - .map(|h| h.split_once(';').unwrap_or((h, "")).0) + .map(|h| h.split_once(';').unwrap_or((h, "")).0.to_lowercase()) { | Some(ct) if ct == expected => Ok(()), | Some(ct) => Err!(Request( From 2c605151eb3f196ee6b3096b9eb7cb588e9f8a8e Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 11 Nov 2026 17:19:04 +0100 Subject: [PATCH 191/342] fix: Don't apply get_missing_events limit to earliest_events --- changelog.d/get-missing-events-earliest-limit.bugfix.md | 1 + src/api/server/get_missing_events.rs | 3 --- 2 files changed, 1 insertion(+), 3 deletions(-) create mode 100644 changelog.d/get-missing-events-earliest-limit.bugfix.md diff --git a/changelog.d/get-missing-events-earliest-limit.bugfix.md b/changelog.d/get-missing-events-earliest-limit.bugfix.md new file mode 100644 index 000000000..2e5d51f8c --- /dev/null +++ b/changelog.d/get-missing-events-earliest-limit.bugfix.md @@ -0,0 +1 @@ +Fixed `/get_missing_events` rejecting requests with more `earliest_events` than the `limit`. Contributed by @eleboucher. diff --git a/src/api/server/get_missing_events.rs b/src/api/server/get_missing_events.rs index 335e8fc09..2842912db 100644 --- a/src/api/server/get_missing_events.rs +++ b/src/api/server/get_missing_events.rs @@ -47,9 +47,6 @@ pub(crate) async fn get_missing_events_route( if body.latest_events.len() > limit { return Err!(Request(InvalidParam("Too many latest_events"))); } - if body.earliest_events.len() > limit { - return Err!(Request(InvalidParam("Too many earliest_events"))); - } let room_version = services.rooms.state.get_room_version(&body.room_id).await?; From 98fe280de42edcd63104c4a54747f2f9ab870d09 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 13 Sep 2026 19:19:16 +0200 Subject: [PATCH 192/342] feat: Allow room moderators to view redacted event content (MSC2815) --- .../+msc2815-unredacted-content.feature.md | 1 + conduwuit-example.toml | 9 +++ src/api/client/room/event.rs | 73 ++++++++++++++++++- src/api/client/unversioned.rs | 5 ++ src/core/config/mod.rs | 11 +++ src/database/maps.rs | 5 ++ src/service/rooms/timeline/data.rs | 17 +++++ src/service/rooms/timeline/mod.rs | 6 ++ src/service/rooms/timeline/redact.rs | 9 +++ 9 files changed, 133 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+msc2815-unredacted-content.feature.md diff --git a/changelog.d/+msc2815-unredacted-content.feature.md b/changelog.d/+msc2815-unredacted-content.feature.md new file mode 100644 index 000000000..09cb3f3ea --- /dev/null +++ b/changelog.d/+msc2815-unredacted-content.feature.md @@ -0,0 +1 @@ +Added [MSC2815](https://github.com/matrix-org/matrix-spec-proposals/pull/2815), letting room moderators fetch the content of redacted events, behind the `allow_moderators_to_view_redacted_content` config option. Contributed by @eleboucher. diff --git a/conduwuit-example.toml b/conduwuit-example.toml index e52fb7463..cc2ac8d75 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -1664,6 +1664,15 @@ # env: CONTINUWUITY_ALLOW_STICKY_EVENTS #allow_sticky_events = false +# Allow room moderators to view redacted event content ([MSC2815]). +# +# Redacted content is kept in the database indefinitely, and readable by +# users at or above the room's `redact` power level, and server admins. +# +# MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 +# +#allow_moderators_to_view_redacted_content = false + # Maximum time federation user can indicate typing. # # env: CONTINUWUITY_TYPING_FEDERATION_TIMEOUT_S diff --git a/src/api/client/room/event.rs b/src/api/client/room/event.rs index c316a7813..91626d636 100644 --- a/src/api/client/room/event.rs +++ b/src/api/client/room/event.rs @@ -1,14 +1,28 @@ -use axum::extract::State; -use conduwuit::{Err, Event, Result, debug_warn, err}; -use ruma::api::client::room::get_room_event; +use axum::extract::{Query, State}; +use conduwuit::{Err, Error, Event, PduEvent, Result, debug_warn, err}; +use futures::{FutureExt, TryFutureExt, future::try_join}; +use http::StatusCode; +use ruma::{ + UserId, + api::{client::room::get_room_event, error::ErrorKind}, +}; +use serde::Deserialize; +use serde_json::json; use crate::{Ruma, client::is_ignored_pdu}; +#[derive(Deserialize)] +pub(crate) struct Msc2815Params { + #[serde(rename = "fi.mau.msc2815.include_unredacted_content", default)] + include_unredacted_content: Option, +} + /// # `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}` /// /// Gets a single event. pub(crate) async fn get_room_event_route( State(ref services): State, + Query(params): Query, ref body: Ruma, ) -> Result { let sender_user = body.identity.expect_sender_user()?; @@ -54,6 +68,13 @@ pub(crate) async fn get_room_event_route( return Err!(Request(Forbidden("You don't have permission to view this event."))); } + if services.config.allow_moderators_to_view_redacted_content + && params.include_unredacted_content.as_deref() == Some("true") + && event.is_redacted() + { + unredact(services, sender_user, &mut event).await?; + } + if let Err(e) = services .rooms .pdu_metadata @@ -72,3 +93,49 @@ pub(crate) async fn get_room_event_route( Ok(get_room_event::v3::Response::new(event.into_format())) } + +async fn unredact(services: &crate::State, sender_user: &UserId, event: &mut PduEvent) -> Result { + let power_levels = services + .rooms + .state_accessor + .get_room_power_levels(&event.room_id_or_hash()) + .await; + + if power_levels.for_user(sender_user) < power_levels.redact + && !services.users.is_admin(sender_user).await + { + return Err!(Request(Forbidden( + "You don't have permission to view redacted content in this room." + ))); + } + + let Ok(pdu_id) = services.rooms.timeline.get_pdu_id(event.event_id()).await else { + return Err(content_unavailable()); + }; + + let Ok(content) = services + .rooms + .timeline + .get_unredacted_content(&pdu_id) + .await + else { + return Err(content_unavailable()); + }; + + event.content = content; + + Ok(()) +} + +fn content_unavailable() -> Error { + let kind = serde_json::from_value::( + json!({ "errcode": "FI.MAU.MSC2815_UNREDACTED_CONTENT_DELETED" }), + ) + .expect("errcode is a valid custom error kind"); + + Error::Request( + kind, + "The unredacted content of this event is not available.".into(), + StatusCode::NOT_FOUND, + ) +} diff --git a/src/api/client/unversioned.rs b/src/api/client/unversioned.rs index 207bcb620..f35a074ac 100644 --- a/src/api/client/unversioned.rs +++ b/src/api/client/unversioned.rs @@ -34,6 +34,11 @@ pub(crate) async fn get_supported_versions_route( unstable_features.insert("org.matrix.msc4354".to_owned(), true); } + if services.config.allow_moderators_to_view_redacted_content { + // moderators can view redacted content (https://github.com/matrix-org/matrix-spec-proposals/pull/2815) + unstable_features.insert("fi.mau.msc2815".to_owned(), true); + } + Ok(assign!(get_supported_versions::Response::new(versions()), { unstable_features })) diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 2c58cd14f..2935da3e7 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -1776,6 +1776,17 @@ pub struct Config { #[serde(default)] pub allow_sticky_events: bool, + /// Allow room moderators to view redacted event content ([MSC2815]). + /// + /// Redacted content is kept in the database indefinitely, and readable by + /// users at or above the room's `redact` power level, and server admins. + /// + /// MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 + /// + /// default: false + #[serde(default)] + pub allow_moderators_to_view_redacted_content: bool, + /// Maximum time federation user can indicate typing. /// /// default: 30 diff --git a/src/database/maps.rs b/src/database/maps.rs index 013fc9270..183355d06 100644 --- a/src/database/maps.rs +++ b/src/database/maps.rs @@ -153,6 +153,11 @@ pub(super) static MAPS: &[Descriptor] = &[ index_size: 512, ..descriptor::SEQUENTIAL }, + Descriptor { + name: "pduid_unredactedcontent", + key_size_hint: Some(16), + ..descriptor::SEQUENTIAL + }, Descriptor { name: "publicroomids", ..descriptor::RANDOM_SMALL diff --git a/src/service/rooms/timeline/data.rs b/src/service/rooms/timeline/data.rs index 560bbae84..853465044 100644 --- a/src/service/rooms/timeline/data.rs +++ b/src/service/rooms/timeline/data.rs @@ -8,6 +8,7 @@ use conduwuit::{ use database::{Database, Deserialized, Json, KeyVal, Map}; use futures::{FutureExt, Stream, TryFutureExt, TryStreamExt, future::select_ok, pin_mut}; use ruma::{CanonicalJsonObject, EventId, OwnedUserId, RoomId, api::Direction}; +use serde_json::value::RawValue as RawJsonValue; use super::{PduId, RawPduId}; use crate::{Dep, rooms, rooms::short::ShortRoomId}; @@ -16,6 +17,7 @@ pub(super) struct Data { eventid_outlierpdu: Arc, eventid_pduid: Arc, pduid_pdu: Arc, + pduid_unredactedcontent: Arc, roomid_lasttimelinecount: Arc, userroomid_highlightcount: Arc, userroomid_notificationcount: Arc, @@ -36,6 +38,7 @@ impl Data { eventid_outlierpdu: db["eventid_outlierpdu"].clone(), eventid_pduid: db["eventid_pduid"].clone(), pduid_pdu: db["pduid_pdu"].clone(), + pduid_unredactedcontent: db["pduid_unredactedcontent"].clone(), roomid_lasttimelinecount: db["roomid_lasttimelinecount"].clone(), userroomid_highlightcount: db["userroomid_highlightcount"].clone(), userroomid_notificationcount: db["userroomid_notificationcount"].clone(), @@ -234,6 +237,20 @@ impl Data { Ok(()) } + pub(super) fn save_unredacted_content(&self, pdu_id: &RawPduId, content: &RawJsonValue) { + self.pduid_unredactedcontent.raw_put(pdu_id, Json(content)); + } + + pub(super) async fn get_unredacted_content( + &self, + pdu_id: &RawPduId, + ) -> Result> { + self.pduid_unredactedcontent + .get(pdu_id) + .await + .deserialized() + } + /// Returns an iterator over all events and their tokens in a room that /// happened before the event with id `until` in reverse-chronological /// order. diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 715d52855..1e68f21ad 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -25,6 +25,7 @@ use ruma::{ events::room::encrypted::Relation, }; use serde::Deserialize; +use serde_json::value::RawValue as RawJsonValue; use self::data::Data; pub use self::{create::pdu_fits, data::PdusIterItem}; @@ -242,6 +243,11 @@ impl Service { self.db.replace_pdu(pdu_id, pdu_json).await } + #[inline] + pub async fn get_unredacted_content(&self, pdu_id: &RawPduId) -> Result> { + self.db.get_unredacted_content(pdu_id).await + } + /// Returns an iterator over all PDUs in a room. Unknown rooms produce no /// items. #[inline] diff --git a/src/service/rooms/timeline/redact.rs b/src/service/rooms/timeline/redact.rs index 92e91cffb..6fa9fb020 100644 --- a/src/service/rooms/timeline/redact.rs +++ b/src/service/rooms/timeline/redact.rs @@ -52,6 +52,15 @@ impl super::Service { .get_room_version(&pdu.room_id_or_hash()) .await?; + if !pdu.is_redacted() + && self + .services + .config + .allow_moderators_to_view_redacted_content + { + self.db.save_unredacted_content(&pdu_id, &pdu.content); + } + pdu.redact(&room_version_id, Some(reason.event_id()))?; let obj = utils::to_canonical_object(&pdu).map_err(|e| { From f154ecb5428b0ab866dc3781798c02400377e0cb Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 13 Sep 2026 20:44:03 +0200 Subject: [PATCH 193/342] feat: Expire retained unredacted content and address review --- .../+msc2815-unredacted-content.feature.md | 2 +- conduwuit-example.toml | 12 +++- src/api/client/room/event.rs | 57 +++++++++++-------- src/core/config/mod.rs | 16 +++++- src/service/rooms/timeline/data.rs | 44 ++++++++++++-- src/service/rooms/timeline/mod.rs | 54 ++++++++++++++++-- 6 files changed, 146 insertions(+), 39 deletions(-) diff --git a/changelog.d/+msc2815-unredacted-content.feature.md b/changelog.d/+msc2815-unredacted-content.feature.md index 09cb3f3ea..f38ba7d91 100644 --- a/changelog.d/+msc2815-unredacted-content.feature.md +++ b/changelog.d/+msc2815-unredacted-content.feature.md @@ -1 +1 @@ -Added [MSC2815](https://github.com/matrix-org/matrix-spec-proposals/pull/2815), letting room moderators fetch the content of redacted events, behind the `allow_moderators_to_view_redacted_content` config option. Contributed by @eleboucher. +Added support for [MSC2815](https://github.com/matrix-org/matrix-spec-proposals/pull/2815), allowing room moderators to fetch the original content of redacted events, behind the `allow_moderators_to_view_redacted_content` config option. Contributed by @eleboucher. diff --git a/conduwuit-example.toml b/conduwuit-example.toml index cc2ac8d75..ec955ba76 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -1666,13 +1666,21 @@ # Allow room moderators to view redacted event content ([MSC2815]). # -# Redacted content is kept in the database indefinitely, and readable by -# users at or above the room's `redact` power level, and server admins. +# Redacted content is readable by users at or above the room's `redact` +# power level, and by server admins, until it expires. # # MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 # #allow_moderators_to_view_redacted_content = false +# How long to retain the content of redacted events, in seconds. Expired +# content is deleted by a periodic purge and is no longer served. +# +# Only has an effect when allow_moderators_to_view_redacted_content is +# enabled. +# +#unredacted_content_max_age_secs = 7776000 (90 days) + # Maximum time federation user can indicate typing. # # env: CONTINUWUITY_TYPING_FEDERATION_TIMEOUT_S diff --git a/src/api/client/room/event.rs b/src/api/client/room/event.rs index 91626d636..b66f8bcaf 100644 --- a/src/api/client/room/event.rs +++ b/src/api/client/room/event.rs @@ -1,6 +1,6 @@ use axum::extract::{Query, State}; use conduwuit::{Err, Error, Event, PduEvent, Result, debug_warn, err}; -use futures::{FutureExt, TryFutureExt, future::try_join}; +use futures::TryFutureExt; use http::StatusCode; use ruma::{ UserId, @@ -14,7 +14,7 @@ use crate::{Ruma, client::is_ignored_pdu}; #[derive(Deserialize)] pub(crate) struct Msc2815Params { #[serde(rename = "fi.mau.msc2815.include_unredacted_content", default)] - include_unredacted_content: Option, + include_unredacted_content: Option, } /// # `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}` @@ -69,7 +69,7 @@ pub(crate) async fn get_room_event_route( } if services.config.allow_moderators_to_view_redacted_content - && params.include_unredacted_content.as_deref() == Some("true") + && params.include_unredacted_content.unwrap_or(false) && event.is_redacted() { unredact(services, sender_user, &mut event).await?; @@ -109,33 +109,40 @@ async fn unredact(services: &crate::State, sender_user: &UserId, event: &mut Pdu ))); } - let Ok(pdu_id) = services.rooms.timeline.get_pdu_id(event.event_id()).await else { - return Err(content_unavailable()); - }; - - let Ok(content) = services + let content = services .rooms .timeline - .get_unredacted_content(&pdu_id) - .await - else { - return Err(content_unavailable()); + .get_pdu_id(event.event_id()) + .and_then(async |pdu_id| { + services + .rooms + .timeline + .get_unredacted_content(&pdu_id) + .await + }) + .await; + + let Ok(content) = content else { + // CustomErrorKind has private fields; only serde can build one. + let keep_ms = services + .config + .unredacted_content_max_age_secs + .saturating_mul(1000); + + let kind = serde_json::from_value::(json!({ + "errcode": "FI.MAU.MSC2815_UNREDACTED_CONTENT_DELETED", + "fi.mau.msc2815.content_keep_ms": keep_ms, + })) + .expect("errcode is a valid custom error kind"); + + return Err(Error::Request( + kind, + "The unredacted content of this event is not available.".into(), + StatusCode::NOT_FOUND, + )); }; event.content = content; Ok(()) } - -fn content_unavailable() -> Error { - let kind = serde_json::from_value::( - json!({ "errcode": "FI.MAU.MSC2815_UNREDACTED_CONTENT_DELETED" }), - ) - .expect("errcode is a valid custom error kind"); - - Error::Request( - kind, - "The unredacted content of this event is not available.".into(), - StatusCode::NOT_FOUND, - ) -} diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 2935da3e7..548963e4c 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -1778,8 +1778,8 @@ pub struct Config { /// Allow room moderators to view redacted event content ([MSC2815]). /// - /// Redacted content is kept in the database indefinitely, and readable by - /// users at or above the room's `redact` power level, and server admins. + /// Redacted content is readable by users at or above the room's `redact` + /// power level, and by server admins, until it expires. /// /// MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 /// @@ -1787,6 +1787,16 @@ pub struct Config { #[serde(default)] pub allow_moderators_to_view_redacted_content: bool, + /// How long to retain the content of redacted events, in seconds. Expired + /// content is deleted by a periodic purge and is no longer served. + /// + /// Only has an effect when allow_moderators_to_view_redacted_content is + /// enabled. + /// + /// default: 7776000 (90 days) + #[serde(default = "default_unredacted_content_max_age_secs")] + pub unredacted_content_max_age_secs: u64, + /// Maximum time federation user can indicate typing. /// /// default: 30 @@ -3254,6 +3264,8 @@ fn default_remote_join_pdu_queue_capacity() -> usize { 50 } fn default_transaction_id_cache_max_age_secs() -> u64 { 60 * 60 * 2 } +fn default_unredacted_content_max_age_secs() -> u64 { 60 * 60 * 24 * 90 } + fn default_transaction_id_cache_max_entries() -> usize { 8192 } fn default_tracing_flame_filter() -> String { diff --git a/src/service/rooms/timeline/data.rs b/src/service/rooms/timeline/data.rs index 853465044..f416582fc 100644 --- a/src/service/rooms/timeline/data.rs +++ b/src/service/rooms/timeline/data.rs @@ -3,11 +3,17 @@ use std::sync::Arc; use conduwuit::{ Err, PduCount, PduEvent, Result, at, err, result::NotFound, - utils::{self, stream::TryReadyExt}, + utils::{ + self, + stream::{ReadyExt, TryReadyExt}, + }, }; use database::{Database, Deserialized, Json, KeyVal, Map}; -use futures::{FutureExt, Stream, TryFutureExt, TryStreamExt, future::select_ok, pin_mut}; +use futures::{ + FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::select_ok, pin_mut, +}; use ruma::{CanonicalJsonObject, EventId, OwnedUserId, RoomId, api::Direction}; +use serde::{Deserialize, Serialize}; use serde_json::value::RawValue as RawJsonValue; use super::{PduId, RawPduId}; @@ -31,6 +37,12 @@ struct Services { pub type PdusIterItem = (PduCount, PduEvent); +#[derive(Deserialize, Serialize)] +pub(super) struct UnredactedContent { + pub(super) created: u64, + pub(super) content: Box, +} + impl Data { pub(super) fn new(args: &crate::Args<'_>) -> Self { let db = &args.db; @@ -238,19 +250,43 @@ impl Data { } pub(super) fn save_unredacted_content(&self, pdu_id: &RawPduId, content: &RawJsonValue) { - self.pduid_unredactedcontent.raw_put(pdu_id, Json(content)); + let entry = UnredactedContent { + created: utils::millis_since_unix_epoch(), + content: content.to_owned(), + }; + + self.pduid_unredactedcontent.raw_put(pdu_id, Json(&entry)); } pub(super) async fn get_unredacted_content( &self, pdu_id: &RawPduId, - ) -> Result> { + ) -> Result { self.pduid_unredactedcontent .get(pdu_id) .await .deserialized() } + pub(super) async fn purge_unredacted_content(&self, cutoff: u64) -> usize { + let expired: Vec<_> = self + .pduid_unredactedcontent + .raw_stream() + .ready_filter_map(Result::ok) + .ready_filter_map(|(key, val)| { + let entry: UnredactedContent = serde_json::from_slice(val).ok()?; + (entry.created < cutoff).then(|| key.to_vec()) + }) + .collect() + .await; + + for key in &expired { + self.pduid_unredactedcontent.remove(key); + } + + expired.len() + } + /// Returns an iterator over all events and their tokens in a room that /// happened before the event with id `until` in reverse-chronological /// order. diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 1e68f21ad..d603757c6 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -6,17 +6,17 @@ mod data; mod helpers; mod redact; -use std::{fmt::Write, sync::Arc}; +use std::{fmt::Write, sync::Arc, time::Duration}; use async_trait::async_trait; pub use conduwuit_core::matrix::pdu::{PduId, RawPduId}; use conduwuit_core::{ - Result, Server, at, err, + Err, Result, Server, at, debug, err, matrix::{ event::Event, pdu::{PduCount, PduEvent}, }, - utils::{MutexMap, MutexMapGuard, future::TryExtExt, stream::TryIgnore}, + utils::{self, MutexMap, MutexMapGuard, future::TryExtExt, stream::TryIgnore}, warn, }; use futures::{Future, Stream, TryStreamExt, pin_mut}; @@ -26,6 +26,10 @@ use ruma::{ }; use serde::Deserialize; use serde_json::value::RawValue as RawJsonValue; +use tokio::{ + sync::Notify, + time::{MissedTickBehavior, interval}, +}; use self::data::Data; pub use self::{create::pdu_fits, data::PdusIterItem}; @@ -57,6 +61,7 @@ struct ExtractBody { } pub struct Service { + interrupt: Notify, services: Services, db: Data, pub mutex_insert: RoomMutexMap, @@ -88,6 +93,8 @@ struct Services { users: Dep, } +const PURGE_INTERVAL_SECS: u64 = 60 * 60; + type RoomMutexMap = MutexMap; pub type RoomMutexGuard = MutexMapGuard; @@ -125,9 +132,35 @@ impl crate::Service for Service { }, db: Data::new(&args), mutex_insert: RoomMutexMap::new(), + interrupt: Notify::new(), })) } + #[tracing::instrument(skip_all, name = "unredacted_content_purge", level = "debug")] + async fn worker(self: Arc) -> Result<()> { + // Runs while disabled too, so old retained content still ages out. + let mut i = interval(Duration::from_secs(PURGE_INTERVAL_SECS)); + i.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + tokio::select! { + () = self.interrupt.notified() => break, + _ = i.tick() => (), + } + + let purged = self + .db + .purge_unredacted_content(self.unredacted_content_cutoff()) + .await; + if purged > 0 { + debug!("Purged {purged} expired unredacted event contents"); + } + } + + Ok(()) + } + + fn interrupt(&self) { self.interrupt.notify_waiters(); } + async fn memory_usage(&self, out: &mut (dyn Write + Send)) -> Result { let mutex_insert = self.mutex_insert.len(); writeln!(out, "insert_mutex: {mutex_insert}")?; @@ -243,9 +276,20 @@ impl Service { self.db.replace_pdu(pdu_id, pdu_json).await } - #[inline] pub async fn get_unredacted_content(&self, pdu_id: &RawPduId) -> Result> { - self.db.get_unredacted_content(pdu_id).await + let entry = self.db.get_unredacted_content(pdu_id).await?; + + if entry.created < self.unredacted_content_cutoff() { + return Err!(Request(NotFound("Unredacted content has expired."))); + } + + Ok(entry.content) + } + + fn unredacted_content_cutoff(&self) -> u64 { + let max_age = self.services.config.unredacted_content_max_age_secs; + + utils::millis_since_unix_epoch().saturating_sub(max_age.saturating_mul(1000)) } /// Returns an iterator over all PDUs in a room. Unknown rooms produce no From 8603ae21cc5750d87bdf306aa4e8a848548cd5ec Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Thu, 1 Oct 2026 20:53:33 +0200 Subject: [PATCH 194/342] fix: Address redacted content review nitpicks --- src/api/client/room/event.rs | 22 +++++++++++----------- src/service/rooms/timeline/mod.rs | 2 +- src/service/rooms/timeline/redact.rs | 19 ++++++++++++------- 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/src/api/client/room/event.rs b/src/api/client/room/event.rs index b66f8bcaf..379cc2dd6 100644 --- a/src/api/client/room/event.rs +++ b/src/api/client/room/event.rs @@ -95,18 +95,18 @@ pub(crate) async fn get_room_event_route( } async fn unredact(services: &crate::State, sender_user: &UserId, event: &mut PduEvent) -> Result { - let power_levels = services - .rooms - .state_accessor - .get_room_power_levels(&event.room_id_or_hash()) - .await; + if !services.users.is_admin(sender_user).await { + let power_levels = services + .rooms + .state_accessor + .get_room_power_levels(&event.room_id_or_hash()) + .await; - if power_levels.for_user(sender_user) < power_levels.redact - && !services.users.is_admin(sender_user).await - { - return Err!(Request(Forbidden( - "You don't have permission to view redacted content in this room." - ))); + if power_levels.for_user(sender_user) < power_levels.redact { + return Err!(Request(Forbidden( + "You don't have permission to view redacted content in this room." + ))); + } } let content = services diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index d603757c6..69c7faa70 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -93,7 +93,7 @@ struct Services { users: Dep, } -const PURGE_INTERVAL_SECS: u64 = 60 * 60; +const PURGE_INTERVAL_SECS: u64 = 3600; type RoomMutexMap = MutexMap; pub type RoomMutexGuard = MutexMapGuard; diff --git a/src/service/rooms/timeline/redact.rs b/src/service/rooms/timeline/redact.rs index 6fa9fb020..d6a67be63 100644 --- a/src/service/rooms/timeline/redact.rs +++ b/src/service/rooms/timeline/redact.rs @@ -4,7 +4,7 @@ use conduwuit_core::{ utils::{self}, warn, }; -use ruma::{EventId, events::room::encrypted::Relation}; +use ruma::{EventId, events::room::encrypted::Relation, signatures::content_hash}; use super::{ExtractBody, ExtractRelatesTo}; use crate::rooms::short::ShortRoomId; @@ -52,13 +52,18 @@ impl super::Service { .get_room_version(&pdu.room_id_or_hash()) .await?; - if !pdu.is_redacted() - && self - .services - .config - .allow_moderators_to_view_redacted_content + if self + .services + .config + .allow_moderators_to_view_redacted_content { - self.db.save_unredacted_content(&pdu_id, &pdu.content); + let mut pdu_json = self.get_pdu_json_from_id(&pdu_id).await?; + pdu_json.remove("event_id"); + if content_hash(&pdu_json) + .is_ok_and(|hash| hash.encode() == pdu.hashes.sha256.trim_end_matches('=')) + { + self.db.save_unredacted_content(&pdu_id, &pdu.content); + } } pdu.redact(&room_version_id, Some(reason.event_id()))?; From ea3beb628a3cab6fbc4142b725c9edb043846eb6 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Thu, 1 Oct 2026 20:53:33 +0200 Subject: [PATCH 195/342] chore: regenerate env --- conduwuit-example.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index ec955ba76..44b0aba4e 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -1671,6 +1671,7 @@ # # MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 # +# env: CONTINUWUITY_ALLOW_MODERATORS_TO_VIEW_REDACTED_CONTENT #allow_moderators_to_view_redacted_content = false # How long to retain the content of redacted events, in seconds. Expired @@ -1679,6 +1680,7 @@ # Only has an effect when allow_moderators_to_view_redacted_content is # enabled. # +# env: CONTINUWUITY_UNREDACTED_CONTENT_MAX_AGE_SECS #unredacted_content_max_age_secs = 7776000 (90 days) # Maximum time federation user can indicate typing. From 49171ec1edcc21af00542e79cd7b274aa95ed2f7 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Thu, 12 Nov 2026 05:03:29 +0000 Subject: [PATCH 196/342] chore(deps): update node-patch-updates to v2.1.2 --- package-lock.json | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/package-lock.json b/package-lock.json index 4e72790f8..696d96791 100644 --- a/package-lock.json +++ b/package-lock.json @@ -431,9 +431,9 @@ } }, "node_modules/@rspress/core": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.1.tgz", - "integrity": "sha512-GArybZxyifQ/wC8N2SzVyFi5JCJpUXgajITV4if8ylOImjZr8j9Cgy+6o55tXEtq85r6XYYE5fbcEz2nxxCpnA==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.2.tgz", + "integrity": "sha512-3ghPRkZFwbuO3tr2Rb5cxi6QfSFWOcxoZ5p4pv21lbN5DxAzMduITFlfgBMTArIQbehXrfXw3OUXe1l422b0RA==", "dev": true, "license": "MIT", "dependencies": { @@ -441,7 +441,7 @@ "@mdx-js/react": "^3.1.1", "@rsbuild/core": "^2.2.14", "@rsbuild/plugin-react": "~2.1.1", - "@rspress/shared": "2.1.1", + "@rspress/shared": "2.1.2", "@shikijs/rehype": "^4.2.0", "@shikijs/transformers": "^4.2.0", "@types/mdast": "^4.0.4", @@ -464,8 +464,8 @@ "react-router-dom": "^7.18.5", "rehype-external-links": "^3.0.0", "rehype-raw": "^7.0.0", - "remark-cjk-friendly": "^2.3.3", - "remark-cjk-friendly-gfm-strikethrough": "^2.3.2", + "remark-cjk-friendly": "^2.3.4", + "remark-cjk-friendly-gfm-strikethrough": "^2.3.3", "remark-gfm": "^4.0.1", "remark-mdx": "^3.1.1", "remark-parse": "^11.0.0", @@ -485,9 +485,9 @@ } }, "node_modules/@rspress/plugin-client-redirects": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.1.tgz", - "integrity": "sha512-jrnh0UTczcTAk+xeJH6b2/LFLF2W7UzPYP992GxnW0mWJxPnvKQIk9v051bezD3gDuiGGRv8puFU7PMmwLOaHg==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.2.tgz", + "integrity": "sha512-kNCC7fffXA277TzTDfKpP+QuCI1X218lJ5JH/2iqYR8PHnLw0Y6ZIwoFmJlE0eKaBdniYyBRGn9zgvT93mCWdg==", "dev": true, "license": "MIT", "engines": { @@ -498,9 +498,9 @@ } }, "node_modules/@rspress/plugin-sitemap": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.1.tgz", - "integrity": "sha512-3Zk+dmitcx5QxiSPi1Wh4exexRnKa09Yyj3710x6UM4sW2cl72SctMZapO7X9ETNrgVt9fW52eQsFzW1y38gSg==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.2.tgz", + "integrity": "sha512-qF9NDLLJORa7MM8QY/etgMlrXM8hlArNaK5ntiFimqtKRoF1YTJQSKPsAfMq2PvYrpQJyEqsSg6wJ+r+lyjNlw==", "dev": true, "license": "MIT", "engines": { @@ -511,16 +511,16 @@ } }, "node_modules/@rspress/shared": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.1.tgz", - "integrity": "sha512-U+OEPt/Ze+ryJdLHvpJJv9hxiRp03rknn5pvhh6v0enjib9SuUrsku/cPzneal3EsNyDZB5kncghpH1iwVKxnA==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.2.tgz", + "integrity": "sha512-W34tT1fdP3PrdbXpZNKqOGZMOw+RYL70Z9vnkbT1HTTbtX4uMIDE+SU7ByihG0S0LYBsT3kPxA2cXj696253Uw==", "dev": true, "license": "MIT", "dependencies": { "@rsbuild/core": "^2.2.14", "@shikijs/rehype": "^4.2.0", "@types/react": "^19.3.0", - "mdast-util-mdx-jsx": "^3.2.0", + "mdast-util-mdx-jsx": "^3.2.1", "unified": "^11.0.5" } }, From c8d87b3a0d0615bcda329c65e613883c670e79fb Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 11 Nov 2026 14:39:19 +0000 Subject: [PATCH 197/342] chore(deps): update dependency cargo-bins/cargo-binstall to v1.27.0 --- docker/Dockerfile | 2 +- docker/musl.Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 6b581749c..e59ecac67 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -50,7 +50,7 @@ EOF # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.26.2 +ENV BINSTALL_VERSION=1.27.0 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree diff --git a/docker/musl.Dockerfile b/docker/musl.Dockerfile index 143857898..278a559d1 100644 --- a/docker/musl.Dockerfile +++ b/docker/musl.Dockerfile @@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \ # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.26.2 +ENV BINSTALL_VERSION=1.27.0 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree From 79a2cbc7be9f9b0be93b75c709cbce12af099018 Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Tue, 13 Oct 2026 00:32:22 +0200 Subject: [PATCH 198/342] chore: Enable unstable-msc4188 in resolvematrix --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index 214b9b984..530250644 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -601,6 +601,7 @@ version = "0.3.0" [workspace.dependencies.resolvematrix] version = "1.4.1" +features = ["unstable-msc4188"] [workspace.dependencies.serde_urlencoded] version = "0.7.1" From 4f63edac332ed828c0d005422bf267640fd0e614 Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Tue, 13 Oct 2026 21:42:23 +0200 Subject: [PATCH 199/342] feat: Support marking servers as unhealthy+stale during resolution For when the server resolution process returns an error or Gone --- src/service/federation/execute.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/service/federation/execute.rs b/src/service/federation/execute.rs index b32174c22..2363cca40 100644 --- a/src/service/federation/execute.rs +++ b/src/service/federation/execute.rs @@ -138,7 +138,11 @@ impl super::Service { .client .matrix_resolver .resolve_server(dest.as_str()) - .await?; + .await + .inspect_err(|_| { + self.hit_unhealthy(dest.to_owned()); + self.mark_destination_stale(dest); + })?; let request = Request::try_from(request.try_into_http_request::>( actual.base_url().as_str(), From 326348ec1a576147069a37a50a28a3d19496237a Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Tue, 13 Oct 2026 21:47:57 +0200 Subject: [PATCH 200/342] chore: Changelog --- changelog.d/2355.feature.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2355.feature.md diff --git a/changelog.d/2355.feature.md b/changelog.d/2355.feature.md new file mode 100644 index 000000000..f76ef7211 --- /dev/null +++ b/changelog.d/2355.feature.md @@ -0,0 +1 @@ +Added support for servers returning 410 gone to indicate they are no longer serving a Matrix server (MSC4188). Contributed by @nex and @silversys From 23a51bcf96c2a93a2a233e9e086197a4c66dffa2 Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Wed, 14 Oct 2026 19:33:40 +0200 Subject: [PATCH 201/342] fix: Set initial backoff time to 90 days immediately As per the MSC: > This MSC recommends homeservers should wait a minimum of 24 hours > and should wait no longer than 90 days, balancing the need to respect > the server's intent to be offline whilst allowing for potential future > changes in server operation or domain ownership. And as per nex: > Technically the MSC said it should be up to 90 days, but they'll never > make me parse cache-control! --- src/service/federation/execute.rs | 15 ++++++++++++--- src/service/federation/mod.rs | 22 ++++++++++++---------- src/service/sending/sender.rs | 4 ++-- 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/src/service/federation/execute.rs b/src/service/federation/execute.rs index 2363cca40..152433cb7 100644 --- a/src/service/federation/execute.rs +++ b/src/service/federation/execute.rs @@ -1,4 +1,9 @@ -use std::{borrow::Cow, fmt::Debug, mem, time::Instant}; +use std::{ + borrow::Cow, + fmt::Debug, + mem, + time::{Duration, Instant}, +}; use conduwuit::{ Err, Error, Result, debug, debug_error, debug_info, debug_warn, err, metrics::KeyValue, @@ -133,6 +138,10 @@ impl super::Service { self.ensure_remote_is_healthy(dest)?; + /// How long to mark a server as unhealthy before attempting + /// re-resolution + const UNHEALTHY_TIMEOUT: Duration = Duration::from_hours(24 * 90); + let actual = self .services .client @@ -140,7 +149,7 @@ impl super::Service { .resolve_server(dest.as_str()) .await .inspect_err(|_| { - self.hit_unhealthy(dest.to_owned()); + self.hit_unhealthy(dest.to_owned(), Some(UNHEALTHY_TIMEOUT)); self.mark_destination_stale(dest); })?; @@ -214,7 +223,7 @@ impl super::Service { if self.should_mark_stale(&wrapped) { debug_info!("{dest} is unhealthy & stale due to a connect error"); self.mark_destination_stale(dest); - self.hit_unhealthy(dest.to_owned()); + self.hit_unhealthy(dest.to_owned(), None); } let Error::Reqwest(unwrapped) = wrapped else { unreachable!("wrapped reqwest error must unwrap to a reqwest error"); diff --git a/src/service/federation/mod.rs b/src/service/federation/mod.rs index 76d0e124a..17a5d2d32 100644 --- a/src/service/federation/mod.rs +++ b/src/service/federation/mod.rs @@ -18,6 +18,7 @@ use ruma::{ OwnedServerName, ServerName, api::error::{ErrorKind, LimitExceededErrorData, RetryAfter}, }; +use yansi::Paint; use crate::{Dep, client, moderation, server_keys}; @@ -92,7 +93,7 @@ impl Service { /// retry count is incremented and next retry window is updated. /// /// Does not update the marker if the backoff period is already in effect. - pub fn hit_unhealthy(&self, server_name: OwnedServerName) { + pub fn hit_unhealthy(&self, server_name: OwnedServerName, next_attempt: Option) { if server_name == self.services.server.name { return; } @@ -109,7 +110,8 @@ impl Service { } *retries = retries.saturating_add(1); - let next_interval = self.services.server.config.sender_retry_backoff(*retries); + let next_interval = next_attempt + .unwrap_or_else(|| self.services.server.config.sender_retry_backoff(*retries)); *next_retry = millis_from_now(next_interval); debug!( "{} is (now) unhealthy ({} retries, blocked until: {})", @@ -200,14 +202,14 @@ impl Service { } match error.status_code() { - // Some special servers account for this specifically - | StatusCode::MISDIRECTED_REQUEST - // Common error codes observed for misdirected requests - // | StatusCode::NOT_FOUND This one can be encountered naturally - | StatusCode::METHOD_NOT_ALLOWED - | StatusCode::IM_A_TEAPOT => true, - _ => false, - } + // Some special servers account for this specifically + | StatusCode::MISDIRECTED_REQUEST + // Common error codes observed for misdirected requests + // | StatusCode::NOT_FOUND This one can be encountered naturally + | StatusCode::METHOD_NOT_ALLOWED + | StatusCode::IM_A_TEAPOT => true, + _ => false, + } } /// Returns a clone of the internal remote health tracking map. diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index 5467b36f4..03be9e2ce 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -149,10 +149,10 @@ impl Service { { debug!("{dest} is now unhealthy & stale due to a connect error: {e:?}"); self.services.federation.mark_destination_stale(dest); - self.services.federation.hit_unhealthy(dest.clone()); + self.services.federation.hit_unhealthy(dest.clone(), None); } else if e.status_code() != StatusCode::OK { debug!("{dest} is now unhealthy due to error response: {e:?}"); - self.services.federation.hit_unhealthy(dest.clone()); + self.services.federation.hit_unhealthy(dest.clone(), None); } } Self::handle_response_err(dest, statuses, &e); From 4d271a56210a9e18ef5abad160e841f2ee342cda Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Mon, 9 Nov 2026 19:16:28 +0100 Subject: [PATCH 202/342] chore: stupid fucking rustrover --- src/service/federation/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/service/federation/mod.rs b/src/service/federation/mod.rs index 17a5d2d32..0b09c56bf 100644 --- a/src/service/federation/mod.rs +++ b/src/service/federation/mod.rs @@ -18,7 +18,6 @@ use ruma::{ OwnedServerName, ServerName, api::error::{ErrorKind, LimitExceededErrorData, RetryAfter}, }; -use yansi::Paint; use crate::{Dep, client, moderation, server_keys}; From 5d0dc8b13708ba78ba84714f1e92323ce7a8a1ed Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Thu, 12 Nov 2026 13:52:35 +0100 Subject: [PATCH 203/342] chore: Update variable name, improve doc comment --- src/service/federation/execute.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/service/federation/execute.rs b/src/service/federation/execute.rs index 152433cb7..594b84a10 100644 --- a/src/service/federation/execute.rs +++ b/src/service/federation/execute.rs @@ -138,9 +138,8 @@ impl super::Service { self.ensure_remote_is_healthy(dest)?; - /// How long to mark a server as unhealthy before attempting - /// re-resolution - const UNHEALTHY_TIMEOUT: Duration = Duration::from_hours(24 * 90); + /// How long to wait with re-resolution if a server fails to resolve + const UNRESOLVABLE_RETRY_AFTER: Duration = Duration::from_hours(24 * 90); let actual = self .services @@ -149,7 +148,7 @@ impl super::Service { .resolve_server(dest.as_str()) .await .inspect_err(|_| { - self.hit_unhealthy(dest.to_owned(), Some(UNHEALTHY_TIMEOUT)); + self.hit_unhealthy(dest.to_owned(), Some(UNRESOLVABLE_RETRY_AFTER)); self.mark_destination_stale(dest); })?; From ae0a2d1797d6c37d99d28673baa94d874427c12a Mon Sep 17 00:00:00 2001 From: ginger Date: Fri, 13 Nov 2026 03:32:50 +0000 Subject: [PATCH 204/342] Return 404 instead of 403 for summaries of missing rooms --- src/api/client/room/summary.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/client/room/summary.rs b/src/api/client/room/summary.rs index 836dba890..e6f200a95 100644 --- a/src/api/client/room/summary.rs +++ b/src/api/client/room/summary.rs @@ -39,7 +39,7 @@ pub(crate) async fn get_room_summary( Err!(Request(Forbidden("You may not preview this room."), FORBIDDEN)) }, | Accessibility::NotFound => { - Err!(Request(Forbidden("This room does not exist."), FORBIDDEN)) + Err!(Request(NotFound("This room does not exist."), FORBIDDEN)) }, } } From b5594c3061f3be9e301063d9b4226a03575702fe Mon Sep 17 00:00:00 2001 From: ginger Date: Fri, 13 Nov 2026 03:35:10 +0000 Subject: [PATCH 205/342] fix: I am god's most intelligent catgirl --- src/api/client/room/summary.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/client/room/summary.rs b/src/api/client/room/summary.rs index e6f200a95..6c60cd88b 100644 --- a/src/api/client/room/summary.rs +++ b/src/api/client/room/summary.rs @@ -39,7 +39,7 @@ pub(crate) async fn get_room_summary( Err!(Request(Forbidden("You may not preview this room."), FORBIDDEN)) }, | Accessibility::NotFound => { - Err!(Request(NotFound("This room does not exist."), FORBIDDEN)) + Err!(Request(NotFound("This room does not exist."))) }, } } From c72156cb04538159f2715ffbda715533470c1678 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 11 Nov 2026 22:38:10 +0100 Subject: [PATCH 206/342] fix: Keep one account data entry per type when updates race Signed-off-by: Erwan Leboucher --- .../+account-data-replaced-entries.bugfix.md | 1 + src/service/account_data/mod.rs | 8 ++++- src/service/migrations.rs | 34 ++++++++++++++++++- 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+account-data-replaced-entries.bugfix.md diff --git a/changelog.d/+account-data-replaced-entries.bugfix.md b/changelog.d/+account-data-replaced-entries.bugfix.md new file mode 100644 index 000000000..c3751d5a9 --- /dev/null +++ b/changelog.d/+account-data-replaced-entries.bugfix.md @@ -0,0 +1 @@ +Fix account data updates sent at the same time leaving old copies behind, which every initial sync then returned. Existing copies are removed on startup. Contributed by @eleboucher. diff --git a/src/service/account_data/mod.rs b/src/service/account_data/mod.rs index 52e9cb9b2..14301ee91 100644 --- a/src/service/account_data/mod.rs +++ b/src/service/account_data/mod.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use conduwuit::{ Err, Result, err, - utils::{ReadyExt, result::LogErr, stream::TryIgnore}, + utils::{MutexMap, ReadyExt, result::LogErr, stream::TryIgnore}, }; use database::{Deserialized, Handle, Ignore, Json, Map}; use futures::{Stream, StreamExt, TryFutureExt}; @@ -27,6 +27,7 @@ pub enum AnyRawAccountDataEvent { pub struct Service { services: Services, db: Data, + update_mutex: MutexMap, } struct Data { @@ -50,6 +51,7 @@ impl crate::Service for Service { roomuserdataid_accountdata: args.db["roomuserdataid_accountdata"].clone(), roomusertype_roomuserdataid: args.db["roomusertype_roomuserdataid"].clone(), }, + update_mutex: MutexMap::new(), })) } @@ -71,6 +73,10 @@ impl Service { return Err!(Request(InvalidParam("Account data doesn't have all required fields."))); } + // Two updates reading the same previous entry would both remove it, + // and the entry of the one that lost the index would stay forever. + let _lock = self.update_mutex.lock(user_id).await; + let count = self.services.globals.next_count().unwrap(); let roomuserdataid = (room_id, user_id, count, &event_type); self.db diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 727bcce17..666994d9e 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -18,7 +18,7 @@ use conduwuit::{ }, warn, }; -use database::Json; +use database::{Deserialized, Ignore, Json}; use futures::{FutureExt, StreamExt, TryStreamExt}; use itertools::Itertools; use ruma::{ @@ -173,6 +173,9 @@ migration!(stringify!($name) => $name) // Re-calculates extremities for any rooms that actually lack any // extremities at all. migration!(consistency_check_extremity_tracker), + // This is backwards compatible because old versions never read the + // account data entries it removes. + migration!(remove_replaced_account_data), ] }; @@ -1018,6 +1021,35 @@ async fn remove_unknown_extremities(services: &Services) -> Result { Ok(()) } +async fn remove_replaced_account_data(services: &Services) -> Result { + type Key = (Option, OwnedUserId, u64, String); + type Latest = (Ignore, Ignore, u64, Ignore); + + let entries = services.db["roomuserdataid_accountdata"].clone(); + let latest_of_type = services.db["roomusertype_roomuserdataid"].clone(); + + let keys: Vec = entries.keys().ignore_err().collect().await; + let mut removed: usize = 0; + for (room_id, user_id, count, event_type) in &keys { + let latest = latest_of_type + .qry(&(room_id, user_id, event_type)) + .await + .deserialized::(); + + if latest.is_ok_and(|(_, _, latest, _)| latest != *count) { + entries.del((room_id, user_id, count, event_type)); + removed = removed.saturating_add(1); + } + } + + info!( + total = keys.len(), + ?removed, + "Removed replaced entries in 'roomuserdataid_accountdata'." + ); + Ok(()) +} + #[tracing::instrument(skip_all)] async fn consistency_check_extremity_tracker(services: &Services) -> Result { let mut rooms = services.rooms.metadata.iter_ids(); From 4ebcf299e22e3f19a86e9c16d51c443009a9959d Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 11 Nov 2026 11:22:02 +0100 Subject: [PATCH 207/342] fix: Refetch OIDC signing keys on unknown key id --- changelog.d/2497.bugfix.md | 1 + src/service/oidc/mod.rs | 118 +++++++++++++++++++++++-------------- 2 files changed, 74 insertions(+), 45 deletions(-) create mode 100644 changelog.d/2497.bugfix.md diff --git a/changelog.d/2497.bugfix.md b/changelog.d/2497.bugfix.md new file mode 100644 index 000000000..11412dbfc --- /dev/null +++ b/changelog.d/2497.bugfix.md @@ -0,0 +1 @@ +Fixed OIDC logins failing after the identity provider rotates its signing keys. Contributed by @eleboucher. diff --git a/src/service/oidc/mod.rs b/src/service/oidc/mod.rs index 220b29891..a05168b75 100644 --- a/src/service/oidc/mod.rs +++ b/src/service/oidc/mod.rs @@ -2,17 +2,17 @@ use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration}; use async_trait::async_trait; use conduwuit::{ - Result, + Result, SyncRwLock, config::{OidcConfig, OidcProfileKeyImportMode}, debug, err, error, info, warn, }; use database::{Deserialized, Map}; use lettre::Address; use openidconnect::{ - AdditionalClaims, AuthorizationCode, ClientSecret, CsrfToken, EmptyExtraTokenFields, - EndpointMaybeSet, EndpointNotSet, EndpointSet, IdTokenClaims, IdTokenFields, IssuerUrl, - Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, StandardErrorResponse, - StandardTokenResponse, TokenResponse, + AdditionalClaims, AuthorizationCode, ClaimsVerificationError, ClientSecret, CsrfToken, + EmptyExtraTokenFields, EndpointMaybeSet, EndpointNotSet, EndpointSet, IdTokenClaims, + IdTokenFields, IssuerUrl, Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, + SignatureVerificationError, StandardErrorResponse, StandardTokenResponse, TokenResponse, core::{ CoreAuthDisplay, CoreAuthPrompt, CoreAuthenticationFlow, CoreErrorResponseType, CoreGenderClaim, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm, @@ -60,7 +60,7 @@ struct Services { struct OidcClient { config: OidcConfig, client_secret: ClientSecret, - machine: SetOnce, + machine: SetOnce>>, client: reqwest::Client, } @@ -180,31 +180,10 @@ impl crate::Service for Service { } async fn worker(self: Arc) -> Result { - if let Some(OidcClient { config, client_secret, machine, client }) = &self.client { - let redirect_url = self - .services - .config - .get_client_domain() - .join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX)) - .expect("redirect url should be valid"); - - let provider_metadata = CoreProviderMetadata::discover_async( - IssuerUrl::new(config.discovery_url.clone()) - .map_err(|err| err!("Failed to parse OIDC discovery URL: {err}"))?, - client, - ) - .await - .map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))?; - + if let Some(OidcClient { machine, .. }) = &self.client { + let discovered = self.discover().await?; machine - .set( - OidcClientMachine::from_provider_metadata( - provider_metadata, - config.client_id.clone(), - Some(client_secret.clone()), - ) - .set_redirect_uri(RedirectUrl::from_url(redirect_url)), - ) + .set(SyncRwLock::new(Arc::new(discovered))) .expect("machine should be empty"); } @@ -224,6 +203,33 @@ impl Service { pub fn enabled(&self) -> bool { self.client.is_some() } + async fn discover(&self) -> Result { + let OidcClient { config, client_secret, client, .. } = + self.client.as_ref().expect("oidc should be configured"); + + let redirect_url = self + .services + .config + .get_client_domain() + .join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX)) + .expect("redirect url should be valid"); + + let provider_metadata = CoreProviderMetadata::discover_async( + IssuerUrl::new(config.discovery_url.clone()) + .map_err(|err| err!("Failed to parse OIDC discovery URL: {err}"))?, + client, + ) + .await + .map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))?; + + Ok(OidcClientMachine::from_provider_metadata( + provider_metadata, + config.client_id.clone(), + Some(client_secret.clone()), + ) + .set_redirect_uri(RedirectUrl::from_url(redirect_url))) + } + pub fn provider_name(&self) -> Option { let OidcClient { config, .. } = self.client.as_ref().expect("oidc should be configured"); @@ -253,7 +259,7 @@ impl Service { pub async fn begin_session(&self, prompt: Option) -> (PendingSession, Url) { let OidcClient { machine, config, .. } = self.client.as_ref().expect("oidc should be configured"); - let machine = machine.wait().await; + let machine = machine.wait().await.read().clone(); let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256(); @@ -284,13 +290,13 @@ impl Service { return Err("Delegated authentication is not enabled on this server."); }; - let machine = machine.wait().await; + let current = machine.wait().await.read().clone(); if session.csrf_token.into_secret() != response.state { return Err("State mismatch."); } - let token_response = machine + let token_response = current .exchange_code(AuthorizationCode::new(response.code)) .expect("machine should be configured correctly") .set_pkce_verifier(session.pkce_verifier) @@ -307,19 +313,41 @@ impl Service { return Err(Self::SERVER_MISCONFIGURED); }; - let verifier = machine - .id_token_verifier() - .set_other_audience_verifier_fn(|audience| { - config.additional_trusted_audiences.contains(audience) - }); + let verify = |machine: &OidcClientMachine| { + let verifier = + machine + .id_token_verifier() + .set_other_audience_verifier_fn(|audience| { + config.additional_trusted_audiences.contains(audience) + }); - let claims = id_token - .claims(&verifier, &session.nonce) - .map_err(|err| { - error!("Failed to verify id token claims: {err}"); - Self::SERVER_MISCONFIGURED - })? - .to_owned(); + id_token + .claims(&verifier, &session.nonce) + .map(ToOwned::to_owned) + }; + + let mut result = verify(¤t); + + if matches!( + result, + Err(ClaimsVerificationError::SignatureVerification( + SignatureVerificationError::NoMatchingKey + )) + ) { + match self.discover().await { + | Ok(discovered) => { + info!("Refreshed OIDC provider metadata after an unknown signing key"); + result = verify(&discovered); + *machine.wait().await.write() = Arc::new(discovered); + }, + | Err(err) => warn!("Failed to refresh OIDC provider metadata: {err}"), + } + } + + let claims = result.map_err(|err| { + error!("Failed to verify id token claims: {err}"); + Self::SERVER_MISCONFIGURED + })?; info!(subject = claims.subject().as_str(), "Authenticated subject"); From 77e8a6b41b7702ddf21112e646619f03e884b231 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 13 Nov 2026 16:57:29 +0100 Subject: [PATCH 208/342] fix(membership): Return the local join error when there are no remote servers to try --- changelog.d/+local-join-forbidden.bugfix.md | 1 + src/service/rooms/membership/mod.rs | 3 +++ 2 files changed, 4 insertions(+) create mode 100644 changelog.d/+local-join-forbidden.bugfix.md diff --git a/changelog.d/+local-join-forbidden.bugfix.md b/changelog.d/+local-join-forbidden.bugfix.md new file mode 100644 index 000000000..3e5b62d94 --- /dev/null +++ b/changelog.d/+local-join-forbidden.bugfix.md @@ -0,0 +1 @@ +Joining a local room the user is not allowed to join now returns `403 M_FORBIDDEN` instead of `500 M_UNKNOWN` when there are no other servers to try. diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index e7bd6037d..b5bfa10d2 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -221,6 +221,9 @@ impl Service { // We couldn't authorize a local join, probably because it's // restricted and we couldn't satisfy // the join rules ourselves. + if servers.is_empty() { + return Err(err); + } info!(?err, "Failed to join room locally, trying over federation instead"); }, } From 7afe5885e9c6a41c198d36f063acf6aa138c767f Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 13 Nov 2026 17:16:05 +0100 Subject: [PATCH 209/342] feat(media): Remove legacy unauthenticated media support --- changelog.d/+remove-legacy-media.feature.md | 1 + complement/complement.config.toml | 1 - conduwuit-example.toml | 23 -- src/api/client/media_legacy.rs | 398 -------------------- src/api/client/mod.rs | 2 - src/api/router.rs | 51 +-- src/core/config/mod.rs | 25 -- src/service/media/remote.rs | 202 +--------- src/service/sending/mod.rs | 26 +- 9 files changed, 19 insertions(+), 710 deletions(-) create mode 100644 changelog.d/+remove-legacy-media.feature.md delete mode 100644 src/api/client/media_legacy.rs diff --git a/changelog.d/+remove-legacy-media.feature.md b/changelog.d/+remove-legacy-media.feature.md new file mode 100644 index 000000000..59ed76bc0 --- /dev/null +++ b/changelog.d/+remove-legacy-media.feature.md @@ -0,0 +1 @@ +Remove support for legacy, unauthenticated media, including the `allow_legacy_media` and `freeze_legacy_media` options. diff --git a/complement/complement.config.toml b/complement/complement.config.toml index dc7e66d6c..2f2172f05 100644 --- a/complement/complement.config.toml +++ b/complement/complement.config.toml @@ -31,7 +31,6 @@ rocksdb_log_level = "info" rocksdb_max_log_files = 1 rocksdb_recovery_mode = 0 rocksdb_paranoid_file_checks = true -allow_legacy_media = true startup_netburst = true startup_netburst_keep = -1 allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure = true diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 44b0aba4e..5bf234f89 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -1733,29 +1733,6 @@ # env: CONTINUWUITY_BROTLI_COMPRESSION #brotli_compression = false -# Enable the legacy unauthenticated Matrix media repository endpoints. -# These endpoints consist of: -# - /_matrix/media/*/config -# - /_matrix/media/*/upload -# - /_matrix/media/*/preview_url -# - /_matrix/media/*/download/* -# - /_matrix/media/*/thumbnail/* -# -# The authenticated equivalent endpoints are always enabled. -# -# Defaults to false, as unauthenticated media has been sunsetted. -# -# env: CONTINUWUITY_ALLOW_LEGACY_MEDIA -#allow_legacy_media = false - -# If set to true, prevents fetching new legacy remote media. -# -# Legacy media may still be accessible if it was already fetched -# previously and allow_legacy_media is true. -# -# env: CONTINUWUITY_FREEZE_LEGACY_MEDIA -#freeze_legacy_media = true - # Check consistency of the media directory at startup: # 1. When `media_compat_file_link` is enabled, this check will upgrade # media when switching back and forth between Conduit and conduwuit. diff --git a/src/api/client/media_legacy.rs b/src/api/client/media_legacy.rs deleted file mode 100644 index 85eaabec9..000000000 --- a/src/api/client/media_legacy.rs +++ /dev/null @@ -1,398 +0,0 @@ -#![allow(deprecated)] - -use axum::extract::State; -use conduwuit::{ - Err, Result, err, - utils::{content_disposition::make_content_disposition, math::ruma_from_usize}, -}; -use conduwuit_service::media::{CORP_CROSS_ORIGIN, Dim, FileMeta}; -use reqwest::Url; -use ruma::{ - api::client::media::{ - create_content, get_content, get_content_as_filename, get_content_thumbnail, - get_media_config, get_media_preview, - }, - assign, -}; -use service::media::mxc::Mxc; - -use crate::{Ruma, RumaResponse, client::create_content_route}; - -/// # `GET /_matrix/media/v3/config` -/// -/// Returns max upload size. -pub(crate) async fn get_media_config_legacy_route( - State(services): State, - _body: Ruma, -) -> Result { - Ok(get_media_config::v3::Response::new(Some(ruma_from_usize( - services.server.config.max_request_size, - )))) -} - -/// # `GET /_matrix/media/v1/config` -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// Returns max upload size. -pub(crate) async fn get_media_config_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_media_config_legacy_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `GET /_matrix/media/v3/preview_url` -/// -/// Returns URL preview. -pub(crate) async fn get_media_preview_legacy_route( - State(services): State, - body: Ruma, -) -> Result { - let sender_user = body.identity.expect_sender_user()?; - - let url = &body.url; - let url = Url::parse(&body.url).map_err(|e| { - err!(Request(InvalidParam( - debug_warn!(%sender_user, %url, "Requested URL is not valid: {e}") - ))) - })?; - - if !services.media.url_preview_allowed(&url) { - return Err!(Request(Forbidden( - debug_warn!(%sender_user, %url, "URL is not allowed to be previewed") - ))); - } - - let preview = services.media.get_url_preview(&url).await.map_err(|e| { - err!(Request(Unknown( - debug_error!(%sender_user, %url, "Failed to fetch a URL preview: {e}") - ))) - })?; - - serde_json::value::to_raw_value(&preview) - .map(get_media_preview::v3::Response::from_raw_value) - .map_err(|error| { - err!(Request(Unknown( - debug_error!(%sender_user, %url, "Failed to parse URL preview: {error}") - ))) - }) -} - -/// # `GET /_matrix/media/v1/preview_url` -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// Returns URL preview. -pub(crate) async fn get_media_preview_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_media_preview_legacy_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `POST /_matrix/media/v1/upload` -/// -/// Permanently save media in the server. -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// - Some metadata will be saved in the database -/// - Media will be saved in the media/ directory -pub(crate) async fn create_content_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - create_content_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}` -/// -/// Load media from our server or over federation. -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_legacy_route( - State(services): State, - body: Ruma, -) -> Result { - let mxc = Mxc { - server_name: &body.server_name, - media_id: &body.media_id, - }; - - match services.media.get(&mxc).await? { - | Some(FileMeta { - content, - content_type, - content_disposition, - }) => { - let content_disposition = make_content_disposition( - content_disposition.as_ref(), - content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content::v3::Response::new( - content.expect("entire file contents"), - content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), - } - )) - }, - | _ => - if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { - let response = services - .media - .fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms) - .await - .map_err(|e| { - err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) - })?; - - let content_disposition = make_content_disposition( - response.content_disposition.as_ref(), - response.content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content::v3::Response::new( - response.file, - response.content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), - } - )) - } else { - Err!(Request(NotFound("Media not found."))) - }, - } -} - -/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}` -/// -/// Load media from our server or over federation. -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_content_legacy_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}/{fileName}` -/// -/// Load media from our server or over federation, permitting desired filename. -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_as_filename_legacy_route( - State(services): State, - body: Ruma, -) -> Result { - let mxc = Mxc { - server_name: &body.server_name, - media_id: &body.media_id, - }; - - match services.media.get(&mxc).await? { - | Some(FileMeta { - content, - content_type, - content_disposition, - }) => { - let content_disposition = make_content_disposition( - content_disposition.as_ref(), - content_type.as_deref(), - Some(&body.filename), - ); - - Ok(assign!(get_content_as_filename::v3::Response::new( - content.expect("entire file contents"), - content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), - } - )) - }, - | _ => - if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { - let response = services - .media - .fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms) - .await - .map_err(|e| { - err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) - })?; - - let content_disposition = make_content_disposition( - response.content_disposition.as_ref(), - response.content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content_as_filename::v3::Response::new( - response.file, - response.content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), - } - )) - } else { - Err!(Request(NotFound("Media not found."))) - }, - } -} - -/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}/{fileName}` -/// -/// Load media from our server or over federation, permitting desired filename. -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_as_filename_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_content_as_filename_legacy_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `GET /_matrix/media/v3/thumbnail/{serverName}/{mediaId}` -/// -/// Load media thumbnail from our server or over federation. -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_thumbnail_legacy_route( - State(services): State, - body: Ruma, -) -> Result { - let mxc = Mxc { - server_name: &body.server_name, - media_id: &body.media_id, - }; - - let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?; - match services.media.get_thumbnail(&mxc, &dim).await? { - | Some(FileMeta { - content, - content_type, - content_disposition, - }) => { - let content_disposition = make_content_disposition( - content_disposition.as_ref(), - content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content_thumbnail::v3::Response::new( - content.expect("entire file contents"), - content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()), - } - )) - }, - | _ => - if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { - let response = services - .media - .fetch_remote_thumbnail_legacy(&body) - .await - .map_err(|e| { - err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) - })?; - - let content_disposition = make_content_disposition( - response.content_disposition.as_ref(), - response.content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content_thumbnail::v3::Response::new( - response.file, - response.content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()), - } - )) - } else { - Err!(Request(NotFound("Media not found."))) - }, - } -} - -/// # `GET /_matrix/media/v1/thumbnail/{serverName}/{mediaId}` -/// -/// Load media thumbnail from our server or over federation. -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_thumbnail_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_content_thumbnail_legacy_route(State(services), body) - .await - .map(RumaResponse) -} diff --git a/src/api/client/mod.rs b/src/api/client/mod.rs index c0bb2dc98..6c26f6748 100644 --- a/src/api/client/mod.rs +++ b/src/api/client/mod.rs @@ -12,7 +12,6 @@ pub(super) mod directory; pub(super) mod filter; pub(super) mod keys; pub(super) mod media; -pub(super) mod media_legacy; pub(super) mod membership; pub(super) mod message; pub(super) mod mutual_rooms; @@ -57,7 +56,6 @@ pub(super) use directory::*; pub(super) use filter::*; pub(super) use keys::*; pub(super) use media::*; -pub(super) use media_legacy::*; pub(super) use membership::*; pub use membership::{leave_all_rooms, leave_room, remote_leave_room}; pub(super) use message::*; diff --git a/src/api/router.rs b/src/api/router.rs index 09681c0b1..f2e8f9730 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -8,7 +8,7 @@ use std::str::FromStr; use axum::{ Router, response::{IntoResponse, Redirect}, - routing::{any, get, post}, + routing::{any, get}, }; use conduwuit::err; pub(super) use conduwuit_service::state::State; @@ -247,45 +247,16 @@ pub fn build(router: Router, state: State) -> Router { // and other functionality will continue to work router = router.ruma_route(&server::get_openid_userinfo_route); - if config.allow_legacy_media { - router = router - .ruma_route(&client::get_media_config_legacy_route) - .ruma_route(&client::get_media_preview_legacy_route) - .ruma_route(&client::get_content_legacy_route) - .ruma_route(&client::get_content_as_filename_legacy_route) - .ruma_route(&client::get_content_thumbnail_legacy_route) - .route("/_matrix/media/v1/config", get(client::get_media_config_legacy_legacy_route)) - .route("/_matrix/media/v1/upload", post(client::create_content_legacy_route)) - .route( - "/_matrix/media/v1/preview_url", - get(client::get_media_preview_legacy_legacy_route), - ) - .route( - "/_matrix/media/v1/download/{server_name}/{media_id}", - get(client::get_content_legacy_legacy_route), - ) - .route( - "/_matrix/media/v1/download/{server_name}/{media_id}/{file_name}", - get(client::get_content_as_filename_legacy_legacy_route), - ) - .route( - "/_matrix/media/v1/thumbnail/{server_name}/{media_id}", - get(client::get_content_thumbnail_legacy_legacy_route), - ); - } else { - router = router - .route("/_matrix/media/v1/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/v3/config", any(legacy_media_disabled)) - .route("/_matrix/media/v3/download/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/v3/thumbnail/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/v3/preview_url", any(redirect_legacy_preview)) - .route("/_matrix/media/r0/config", any(legacy_media_disabled)) - .route("/_matrix/media/r0/download/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/r0/thumbnail/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/r0/preview_url", any(redirect_legacy_preview)); - } - router + .route("/_matrix/media/v1/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/v3/config", any(legacy_media_disabled)) + .route("/_matrix/media/v3/download/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/v3/thumbnail/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/v3/preview_url", any(redirect_legacy_preview)) + .route("/_matrix/media/r0/config", any(legacy_media_disabled)) + .route("/_matrix/media/r0/download/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/r0/thumbnail/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/r0/preview_url", any(redirect_legacy_preview)) } async fn redirect_legacy_preview(uri: Uri) -> impl IntoResponse { @@ -306,7 +277,7 @@ async fn redirect_legacy_preview(uri: Uri) -> impl IntoResponse { } async fn legacy_media_disabled() -> impl IntoResponse { - err!(Request(Forbidden("Unauthenticated media is disabled."))) + err!(Request(NotFound("Unauthenticated media is disabled."))) } async fn federation_disabled() -> impl IntoResponse { diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 548963e4c..831a052a6 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -1847,31 +1847,6 @@ pub struct Config { #[serde(default)] pub brotli_compression: bool, - /// Enable the legacy unauthenticated Matrix media repository endpoints. - /// These endpoints consist of: - /// - /_matrix/media/*/config - /// - /_matrix/media/*/upload - /// - /_matrix/media/*/preview_url - /// - /_matrix/media/*/download/* - /// - /_matrix/media/*/thumbnail/* - /// - /// The authenticated equivalent endpoints are always enabled. - /// - /// Defaults to false, as unauthenticated media has been sunsetted. - /// - /// default: false - #[serde(default)] - pub allow_legacy_media: bool, - - /// If set to true, prevents fetching new legacy remote media. - /// - /// Legacy media may still be accessible if it was already fetched - /// previously and allow_legacy_media is true. - /// - /// default: true - #[serde(default = "true_fn")] - pub freeze_legacy_media: bool, - /// Check consistency of the media directory at startup: /// 1. When `media_compat_file_link` is enabled, this check will upgrade /// media when switching back and forth between Conduit and conduwuit. diff --git a/src/service/media/remote.rs b/src/service/media/remote.rs index 2be895a6e..15aa4f672 100644 --- a/src/service/media/remote.rs +++ b/src/service/media/remote.rs @@ -1,7 +1,7 @@ use std::{fmt::Debug, time::Duration}; use conduwuit::{ - Err, Error, Result, debug_warn, err, + Err, Result, debug_warn, err, utils::{content_disposition::make_content_disposition, response::LimitReadExt}, }; use http::header::{CONTENT_DISPOSITION, CONTENT_TYPE, HeaderValue}; @@ -9,9 +9,6 @@ use ruma::{ ServerName, UserId, api::{ OutgoingRequest, - auth_scheme::NoAccessToken, - client::media, - error::ErrorKind::{NotFound, Unrecognized}, federation::{ self, authenticated_media::{Content, FileOrLocation}, @@ -35,17 +32,8 @@ impl super::Service { ) -> Result { self.check_fetch_authorized(mxc)?; - let result = self - .fetch_thumbnail_authenticated(mxc, user, server, timeout_ms, dim) - .await; - - if let Err(Error::Request(NotFound, ..)) = &result { - return self - .fetch_thumbnail_unauthenticated(mxc, user, server, timeout_ms, dim) - .await; - } - - result + self.fetch_thumbnail_authenticated(mxc, user, server, timeout_ms, dim) + .await } pub async fn fetch_remote_content( @@ -57,8 +45,7 @@ impl super::Service { ) -> Result { self.check_fetch_authorized(mxc)?; - let result = self - .fetch_content_authenticated(mxc, user, server, timeout_ms) + self.fetch_content_authenticated(mxc, user, server, timeout_ms) .await .inspect_err(|error| { debug_warn!( @@ -68,15 +55,7 @@ impl super::Service { ?error, "Authenticated fetch of remote content failed" ); - }); - - if let Err(Error::Request(Unrecognized, ..)) = &result { - return self - .fetch_content_unauthenticated(mxc, user, server, timeout_ms) - .await; - } - - result + }) } async fn fetch_thumbnail_authenticated( @@ -127,66 +106,6 @@ impl super::Service { } } - #[allow(deprecated)] - async fn fetch_thumbnail_unauthenticated( - &self, - mxc: &Mxc<'_>, - user: Option<&UserId>, - server: Option<&ServerName>, - timeout_ms: Duration, - dim: &Dim, - ) -> Result { - use media::get_content_thumbnail::v3::{Request, Response}; - - let mut request = Request::new( - mxc.media_id.into(), - mxc.server_name.into(), - dim.width.into(), - dim.height.into(), - ); - request.allow_redirect = true; - request.allow_remote = true; - request.animated = Some(true); - request.method = Some(dim.method.clone()); - request.timeout_ms = timeout_ms; - - let Response { - file, content_type, content_disposition, .. - } = self - .federation_request_legacy_media(mxc, server, request) - .await?; - - let content = Content::new(file, content_type.unwrap(), content_disposition.unwrap()); - - self.handle_thumbnail_file(mxc, user, dim, content).await - } - - #[allow(deprecated)] - async fn fetch_content_unauthenticated( - &self, - mxc: &Mxc<'_>, - user: Option<&UserId>, - server: Option<&ServerName>, - timeout_ms: Duration, - ) -> Result { - use media::get_content::v3::{Request, Response}; - - let mut request = Request::new(mxc.media_id.into(), mxc.server_name.into()); - request.allow_remote = true; - request.allow_redirect = true; - request.timeout_ms = timeout_ms; - - let Response { - file, content_type, content_disposition, .. - } = self - .federation_request_legacy_media(mxc, server, request) - .await?; - - let content = Content::new(file, content_type.unwrap(), content_disposition.unwrap()); - - self.handle_content_file(mxc, user, content).await - } - async fn handle_thumbnail_file( &self, mxc: &Mxc<'_>, @@ -319,108 +238,6 @@ impl super::Service { .await } - async fn federation_request_legacy_media<'i, Request>( - &self, - mxc: &Mxc<'_>, - server: Option<&ServerName>, - request: Request, - ) -> Result - where - Request: OutgoingRequest< - Authentication = NoAccessToken, - PathBuilder: PathBuilder: FederationPathBuilderInput>, - > + Debug - + Send, - { - self.services - .sending - .send_legacy_media_request(server.unwrap_or(mxc.server_name), request) - .await - } - - #[allow(deprecated)] - pub async fn fetch_remote_thumbnail_legacy( - &self, - body: &media::get_content_thumbnail::v3::Request, - ) -> Result { - let mxc = Mxc { - server_name: &body.server_name, - media_id: &body.media_id, - }; - - let mut request = media::get_content_thumbnail::v3::Request::new( - body.media_id.clone(), - body.server_name.clone(), - body.width, - body.height, - ); - request.method.clone_from(&body.method); - request.allow_remote = body.allow_remote; - request.allow_redirect = body.allow_redirect; - request.animated = body.animated; - request.timeout_ms = body.timeout_ms; - - self.check_legacy_freeze()?; - self.check_fetch_authorized(&mxc)?; - let response = self - .services - .sending - .send_legacy_media_request(mxc.server_name, request) - .await?; - - let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?; - self.upload_thumbnail( - &mxc, - None, - None, - response.content_type.as_deref(), - &dim, - &response.file, - ) - .await?; - - Ok(response) - } - - #[allow(deprecated)] - pub async fn fetch_remote_content_legacy( - &self, - mxc: &Mxc<'_>, - allow_redirect: bool, - timeout_ms: Duration, - ) -> Result { - let mut request = - media::get_content::v3::Request::new(mxc.media_id.into(), mxc.server_name.into()); - request.allow_remote = true; - request.allow_redirect = allow_redirect; - request.timeout_ms = timeout_ms; - - self.check_legacy_freeze()?; - self.check_fetch_authorized(mxc)?; - let response = self - .services - .sending - .send_legacy_media_request(mxc.server_name, request) - .await?; - - let content_disposition = make_content_disposition( - response.content_disposition.as_ref(), - response.content_type.as_deref(), - None, - ); - - self.create( - mxc, - None, - Some(&content_disposition), - response.content_type.as_deref(), - &response.file, - ) - .await?; - - Ok(response) - } - fn check_fetch_authorized(&self, mxc: &Mxc<'_>) -> Result<()> { if self .services @@ -436,13 +253,4 @@ impl super::Service { Ok(()) } - - fn check_legacy_freeze(&self) -> Result<()> { - self.services - .server - .config - .freeze_legacy_media - .then_some(()) - .ok_or(err!(Request(NotFound("Remote media is frozen.")))) - } } diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index cc518f5a5..4bd1f76a1 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -23,10 +23,8 @@ use futures::{FutureExt, Stream, StreamExt}; use ruma::{ OwnedServerName, RoomId, ServerName, UserId, api::{ - OutgoingRequest, - auth_scheme::{NoAccessToken, NoAuthentication, SendAccessToken}, - federation::authentication::ServerSignatures, - path_builder::PathBuilder, + OutgoingRequest, auth_scheme::NoAuthentication, + federation::authentication::ServerSignatures, path_builder::PathBuilder, }, }; use tokio::{task, task::JoinSet}; @@ -420,26 +418,6 @@ impl Service { .await } - /// Send an unauthenticated federation request with no X-Matrix header. - #[inline] - pub async fn send_legacy_media_request<'i, T>( - &self, - dest: &ServerName, - request: T, - ) -> Result - where - T: OutgoingRequest< - Authentication = NoAccessToken, - PathBuilder: PathBuilder: FederationPathBuilderInput>, - > + Debug - + Send, - { - self.services - .federation - .execute_on(&self.services.client.federation, dest, request, SendAccessToken::None) - .await - } - /// Clean up queued sending event data /// /// Used after we remove an appservice registration or a user deletes a push From 26ec038418d0d06915c507fb51a65b9904bd2a7f Mon Sep 17 00:00:00 2001 From: Niklas Wojtkowiak Date: Sat, 14 Nov 2026 00:20:01 -0900 Subject: [PATCH 210/342] fix(client): Return 400, not 500, for non-canonical createRoom --- src/api/client/room/create.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/api/client/room/create.rs b/src/api/client/room/create.rs index 279b267c5..c4e5ed917 100644 --- a/src/api/client/room/create.rs +++ b/src/api/client/room/create.rs @@ -121,7 +121,10 @@ pub(crate) async fn create_room_route( // ID exactly matches this, and abort if it doesn't. Otherwise, we use it // as the room ID itself. let expect_room_id = { - let body_ref = body.json_body.as_ref().unwrap(); + let body_ref = body + .json_body + .as_ref() + .ok_or_else(|| err!(Request(BadJson("Invalid JSON body"))))?; if let Some(CanonicalJsonValue::String(room_id)) = body_ref .get("fi.mau.room_id") .or_else(|| body_ref.get("room_id")) @@ -302,7 +305,10 @@ pub(crate) async fn create_room_route( // Allow requesters to override the `origin_server_ts` to customize room ids // from v12 onwards let custom_origin_server_ts = { - let body_ref = body.json_body.as_ref().unwrap(); + let body_ref = body + .json_body + .as_ref() + .ok_or_else(|| err!(Request(BadJson("Invalid JSON body"))))?; body_ref .get("origin_server_ts") .or_else(|| body_ref.get("fi.mau.origin_server_ts")) From b34dfe343a7460e172a297333b53c73bc9bd9f90 Mon Sep 17 00:00:00 2001 From: Niklas Wojtkowiak Date: Sat, 14 Nov 2026 00:22:45 -0900 Subject: [PATCH 211/342] docs(changelog): Add fragment for createRoom bad JSON fix --- changelog.d/+create-room-bad-json.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/+create-room-bad-json.bugfix.md diff --git a/changelog.d/+create-room-bad-json.bugfix.md b/changelog.d/+create-room-bad-json.bugfix.md new file mode 100644 index 000000000..7bba2bd13 --- /dev/null +++ b/changelog.d/+create-room-bad-json.bugfix.md @@ -0,0 +1 @@ +Creating a room with valid but non-canonical JSON now returns `400 M_BAD_JSON` instead of panicking the worker and returning `500 M_UNKNOWN`. From 39035d735ef055266e05e1949ce5797e967eff90 Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 13 Nov 2026 18:13:16 +0000 Subject: [PATCH 212/342] refactor: Configuration-gate experiments --- docs/development/unstable_features.mdx | 75 ++++++++++++++++ src/api/client/room/event.rs | 9 +- src/api/client/send.rs | 7 +- src/api/client/sync/v3/joined.rs | 4 - src/api/client/sync/v5.rs | 2 +- src/api/client/unversioned.rs | 12 +-- src/core/config/experiments.rs | 115 +++++++++++++++++++++++++ src/core/config/mod.rs | 42 +++------ src/core/matrix/versions.rs | 28 +++--- src/service/mod.rs | 6 +- src/service/rooms/timeline/append.rs | 4 +- src/service/rooms/timeline/helpers.rs | 8 +- src/service/rooms/timeline/mod.rs | 7 +- src/service/rooms/timeline/redact.rs | 7 +- src/service/sending/sender.rs | 2 +- 15 files changed, 238 insertions(+), 90 deletions(-) create mode 100644 docs/development/unstable_features.mdx create mode 100644 src/core/config/experiments.rs diff --git a/docs/development/unstable_features.mdx b/docs/development/unstable_features.mdx new file mode 100644 index 000000000..eb1daf7fd --- /dev/null +++ b/docs/development/unstable_features.mdx @@ -0,0 +1,75 @@ +# Unstable features policy + +Like several other homeservers in the Matrix ecosystem, Continuwuity adopts a "disable by default" +approach to experimental features. This ensures every deployment gets the same baseline stability, +allowing users to opt in to potentially unstable features. + +Historically, Continuwuity used maintainer discretion to decide whether an unstable feature should +be enabled by default. However, as the project has grown, and the pace of spec development has +increased, keeping up with unstable proposals becomes less and less feasible by the day, and this +causes the implementation of unstable proposals to gradually drift. This can lead to implementations +becoming so stale they're incompatible, with no bandwidth to get them fixed up. + +Continuwuity is already selective about which unstable features it implements: the maintainer team +typically only accept implementations of proposals that seem like they are a net positive for a +large portion of the Matrix ecosystem, rather than aiming to "implement everything". As such, the +unstable feature list should typically be small and manageable. + +## Adding an unstable feature + +First, navigate to `src/core/config/experiments.rs`. There, you have two options for adding an +experiment to the `Experiments` struct: + +1. Use `SimpleExperiment` if the experiment only requires enabling with no further configuration. +2. Define a new struct that implements the `ToggledExperiment` trait. + +All experiments must be optional and default to off (i.e. `is_enabled()` returns `false`). +`SimpleExperiment` is actually a wrapper around `Option`, and the omission of the +configuration OR setting it to `false` disables the experiment. `ToggledExperiment` impls should +copy similar behaviour. + +Then, add a public field to the `Experiments` struct that is named the MSC's ID in lowercase. +Add a docstring to it, starting with the proposal title (including ID), then a brief paragraph or +so explaining what the proposal does in simple terms, and then finally end the docstring with a link +to the proposal. + +### Advertising support for unstable features + +If the proposal requires advertising an unstable feature flag, that flag must be added to +`unstable_features` in `src/core/matrix/versions.rs`. For example: + +```diff +pub fn unstable_features(experiments: &Experiments) -> BTreeMap { + BTreeMap::from_iter([ + // Always enabled feature (https://github.com/matrix-org/matrix-spec-proposals/pull/0000) + // Expected for spec v1.20 + ("org.matrix.msc0000".to_owned(), true), ++ // MSC9999: My Cool Feature (https://github.com/matrix-org/matrix-spec-proposals/pull/9999) ++ ("example.matrix.msc9999".to_owned(), experiments.msc9999.is_enabled()) + ]) +} +``` + +This will allow the `/_matrix/client/versions` endpoint to dynamically advertise whether the unstable +feature is enabled on the current server. + +## Removing unstable features + +If a proposal is abandoned, becomes obsolete, or is accepted into the specification, the unstable +configuration should be removed (and possibly migrated) as soon as possible. + +After removing a field from `experiments`, the key should be added to the `DEPRECATED_KEYS` slice in +`src/core/config/mod.rs` (really far down). This will ensure that a warning is printed on startup +when a configuration is using a now-removed config key. For example: + +```diff +pub struct Experiments { +- pub msc9999: SimpleExperiment, +} +``` +```diff +const DEPRECATED_KEYS: &[&str] = [ + "foo", ++ "experiments.msc9999", +]; +``` diff --git a/src/api/client/room/event.rs b/src/api/client/room/event.rs index 379cc2dd6..d4917f73a 100644 --- a/src/api/client/room/event.rs +++ b/src/api/client/room/event.rs @@ -1,5 +1,7 @@ use axum::extract::{Query, State}; -use conduwuit::{Err, Error, Event, PduEvent, Result, debug_warn, err}; +use conduwuit::{ + Err, Error, Event, PduEvent, Result, config::experiments::ToggledExperiment, debug_warn, err, +}; use futures::TryFutureExt; use http::StatusCode; use ruma::{ @@ -68,7 +70,7 @@ pub(crate) async fn get_room_event_route( return Err!(Request(Forbidden("You don't have permission to view this event."))); } - if services.config.allow_moderators_to_view_redacted_content + if services.config.experiments.msc2815.is_enabled() && params.include_unredacted_content.unwrap_or(false) && event.is_redacted() { @@ -126,6 +128,9 @@ async fn unredact(services: &crate::State, sender_user: &UserId, event: &mut Pdu // CustomErrorKind has private fields; only serde can build one. let keep_ms = services .config + .experiments + .msc2815 + .expect("msc2815 config is disabled but unredact() attempted to access it anyway") .unredacted_content_max_age_secs .saturating_mul(1000); diff --git a/src/api/client/send.rs b/src/api/client/send.rs index b87f7eb2e..41e3804b0 100644 --- a/src/api/client/send.rs +++ b/src/api/client/send.rs @@ -95,12 +95,7 @@ pub(crate) async fn send_message_event_route( PartialPdu { event_type: body.event_type.clone().into(), content, - sticky: services - .config - .allow_sticky_events - .then_some(body.sticky_duration_ms) - .flatten() - .map(sticky::object), + sticky: body.sticky_duration_ms.map(sticky::object), unsigned: Some(unsigned), timestamp: if body.identity.is_appservice() || services.admin.user_is_admin(sender_user).await diff --git a/src/api/client/sync/v3/joined.rs b/src/api/client/sync/v3/joined.rs index b47753518..7eee0d1d5 100644 --- a/src/api/client/sync/v3/joined.rs +++ b/src/api/client/sync/v3/joined.rs @@ -273,10 +273,6 @@ async fn build_sticky_events( timeline: &TimelinePdus, joined_since_last_sync: bool, ) -> Sticky { - if !services.config.allow_sticky_events { - return Sticky::new(); - } - let SyncContext { syncing_user, last_sync_end_count, diff --git a/src/api/client/sync/v5.rs b/src/api/client/sync/v5.rs index e97319e46..0285c8359 100644 --- a/src/api/client/sync/v5.rs +++ b/src/api/client/sync/v5.rs @@ -1123,7 +1123,7 @@ async fn collect_sticky_events( let mut delivered = StickyDelivered::new(); let sticky_events = &body.extensions.sticky_events; - if !services.config.allow_sticky_events || !sticky_events.enabled.unwrap_or(false) { + if !sticky_events.enabled.unwrap_or(false) { return (response, delivered); } diff --git a/src/api/client/unversioned.rs b/src/api/client/unversioned.rs index f35a074ac..39862673b 100644 --- a/src/api/client/unversioned.rs +++ b/src/api/client/unversioned.rs @@ -27,17 +27,7 @@ pub(crate) async fn get_supported_versions_route( State(services): State, _body: Ruma, ) -> Result { - let mut unstable_features = unstable_features(); - - if services.config.allow_sticky_events { - // sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354) - unstable_features.insert("org.matrix.msc4354".to_owned(), true); - } - - if services.config.allow_moderators_to_view_redacted_content { - // moderators can view redacted content (https://github.com/matrix-org/matrix-spec-proposals/pull/2815) - unstable_features.insert("fi.mau.msc2815".to_owned(), true); - } + let unstable_features = unstable_features(&services.config.experiments); Ok(assign!(get_supported_versions::Response::new(versions()), { unstable_features diff --git a/src/core/config/experiments.rs b/src/core/config/experiments.rs new file mode 100644 index 000000000..82a49e0c5 --- /dev/null +++ b/src/core/config/experiments.rs @@ -0,0 +1,115 @@ +use serde::Deserialize; + +/// Configuration for experimental features. +#[derive(Debug, Deserialize, Default, Clone)] +pub struct Experiments { + /// MSC2815: Proposal to allow room moderators to view redacted event + /// content + /// + /// Allows the server to retain unredacted copies of events that have been + /// redacted for a limited period of time, which allows room moderators and + /// server administrators to reveal redacted contents. Useful for moderation + /// and investigating reports. + /// + /// Requires a supporting client to use. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/2815 + #[serde(default)] + pub msc2815: Option, + /// MSC4155: Invite filtering + /// + /// Provides advanced invite filtering rules for users, allowing complex + /// configurations that can allow, ignore, and reject invites from users and + /// servers broadly. + /// + /// Requires a supporting client to set up on an account. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4155 + #[serde(default)] + pub msc4155: SimpleExperiment, + /// MSC4174: Web push + /// + /// Adds server-side support for web push, allowing web clients to receive + /// push notifications directly without the need for an intermediary push + /// gateway like Sygnal. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4174 + #[serde(default)] + pub msc4174: SimpleExperiment, + /// MSC4484: Server Administration OAuth Scope + /// + /// Adds a new OAuth2 scope that explicitly grants a token temporary + /// homeserver administrator privileges, granting temporary token access + /// to administrator endpoints like locking & suspension. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4484 + #[serde(default)] + pub msc4484: SimpleExperiment, + /// MSC4494: Membership-based invite blocking + /// + /// Adds a new invite blocking action that will reject all invites coming + /// from users who do not share a room with the invitee that is not `public` + /// (the join rule). + /// + /// This is not related to MSC4155, this proposal instead builds on the + /// "invite blocking" proposal that landed in the specification in v1.17, + /// which simply allows enabling or disabling invites altogether. + /// + /// MSC4494 is a good middle-ground between the allowlisting possible with + /// MSC4155, and the general desire to block invites from users you may not + /// know. + /// + /// Requires a supporting client to enable on an account. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4494 + #[serde(default)] + pub msc4494: SimpleExperiment, + /// MSC4560: Stripped state requests over federation + /// + /// Implements a more efficient way for servers to acquire and serve + /// "stripped state" to clients, which is typically only used for displaying + /// rooms. The display of space hierarchies and room summaries is + /// significantly faster when this proposal is enabled and used. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4560 + #[serde(default)] + pub msc4560: SimpleExperiment, +} + +/// Represents a "simple" experiment, which is either disabled or enabled. +/// +/// More complex experiments that require configuration should define their own +/// type and implement `ToggledExperiment` instead. +#[derive(Debug, Deserialize, Default, Clone, Copy)] +pub struct SimpleExperiment(Option); + +pub trait ToggledExperiment { + /// Returns true if this experiment is explicitly enabled. + #[must_use] + fn is_enabled(&self) -> bool; +} + +impl ToggledExperiment for SimpleExperiment { + #[inline] + fn is_enabled(&self) -> bool { self.0.is_some_and(crate::is_true!()) } +} + +/// Configuration for [MSC2815]: Proposal to allow room moderators to view +/// redacted event content +/// +/// MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 +#[derive(Debug, Deserialize, Default, Clone, Copy)] +pub struct MSC2815 { + #[serde(default)] + pub enabled: bool, + #[serde(default = "default_unredacted_content_max_age_secs")] + pub unredacted_content_max_age_secs: u64, +} + +#[inline] +fn default_unredacted_content_max_age_secs() -> u64 { 7_776_000 } + +impl ToggledExperiment for Option { + #[inline] + fn is_enabled(&self) -> bool { self.is_some_and(|config| config.enabled) } +} diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 831a052a6..be2461f50 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -1,5 +1,6 @@ #![allow(clippy::doc_link_with_quotes)] pub mod check; +pub mod experiments; pub mod manager; pub mod proxy; @@ -18,6 +19,7 @@ use either::{ Either, Either::{Left, Right}, }; +pub use experiments::Experiments; use figment::providers::{Env, Format, Toml}; pub use figment::{Figment, value::Value as FigmentValue}; use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter}; @@ -1768,35 +1770,6 @@ pub struct Config { #[serde(default = "true_fn")] pub allow_incoming_typing: bool, - /// Allow the use of unstable persistent "sticky events" ([MSC4354]) - /// - /// MSC4354: https://c10y.cc/MSC4354 - /// - /// default: false - #[serde(default)] - pub allow_sticky_events: bool, - - /// Allow room moderators to view redacted event content ([MSC2815]). - /// - /// Redacted content is readable by users at or above the room's `redact` - /// power level, and by server admins, until it expires. - /// - /// MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 - /// - /// default: false - #[serde(default)] - pub allow_moderators_to_view_redacted_content: bool, - - /// How long to retain the content of redacted events, in seconds. Expired - /// content is deleted by a periodic purge and is no longer served. - /// - /// Only has an effect when allow_moderators_to_view_redacted_content is - /// enabled. - /// - /// default: 7776000 (90 days) - #[serde(default = "default_unredacted_content_max_age_secs")] - pub unredacted_content_max_age_secs: u64, - /// Maximum time federation user can indicate typing. /// /// default: 30 @@ -2474,6 +2447,12 @@ pub struct Config { #[serde(default)] pub matrix_rtc: MatrixRtcConfig, + /// Configuration for unstable features. + /// + /// display: none + #[serde(default)] + pub experiments: Experiments, + #[serde(flatten)] #[allow(clippy::zero_sized_map_values)] // this is a catchall, the map shouldn't be zero at runtime @@ -3007,6 +2986,9 @@ const DEPRECATED_KEYS: &[&str] = &[ "well_known_support_email", "well_known_support_mxid", "well_known.rtc_focus_server_urls", + "allow_sticky_events", + "allow_moderators_to_view_redacted_content", + "unredacted_content_max_age_secs", ]; impl Config { @@ -3239,8 +3221,6 @@ fn default_remote_join_pdu_queue_capacity() -> usize { 50 } fn default_transaction_id_cache_max_age_secs() -> u64 { 60 * 60 * 2 } -fn default_unredacted_content_max_age_secs() -> u64 { 60 * 60 * 24 * 90 } - fn default_transaction_id_cache_max_entries() -> usize { 8192 } fn default_tracing_flame_filter() -> String { diff --git a/src/core/matrix/versions.rs b/src/core/matrix/versions.rs index 3ea538b62..160efe085 100644 --- a/src/core/matrix/versions.rs +++ b/src/core/matrix/versions.rs @@ -1,5 +1,7 @@ use std::collections::BTreeMap; +use crate::config::{Experiments, experiments::ToggledExperiment}; + #[must_use] pub fn versions() -> Vec { vec![ @@ -25,32 +27,26 @@ pub fn versions() -> Vec { "v1.16".to_owned(), "v1.17".to_owned(), "v1.18".to_owned(), + "v1.19".to_owned(), ] } #[must_use] -pub fn unstable_features() -> BTreeMap { +pub fn unstable_features(experiments: &Experiments) -> BTreeMap { BTreeMap::from_iter([ // MatrixRTC (https://github.com/matrix-org/matrix-spec-proposals/pull/4143) + // Expected for spec v1.20 ("org.matrix.msc4143".to_owned(), true), - // query mutual rooms (https://github.com/matrix-org/matrix-spec-proposals/pull/2666) - // Expected for spec v1.19 - ("uk.half-shot.msc2666.query_mutual_rooms".to_owned(), true), - ("uk.half-shot.msc2666.query_mutual_rooms.stable".to_owned(), true), // Simplified Sliding sync (https://github.com/matrix-org/matrix-spec-proposals/pull/4186) - // Expected for spec v1.19 + // Expected for spec v1.20 ("org.matrix.simplified_msc3575".to_owned(), true), - // invite filtering (https://github.com/matrix-org/matrix-spec-proposals/pull/4155) - ("org.matrix.msc4155".to_owned(), true), + ("org.matrix.msc4155".to_owned(), experiments.msc4155.is_enabled()), // profile change propagation (https://github.com/matrix-org/matrix-spec-proposals/pull/4466) ("computer.gingershaped.msc4466".to_owned(), true), - // web push (https://github.com/matrix-org/matrix-spec-proposals/pull/4174) - ("org.matrix.msc4174".to_owned(), true), - // Membership-based invite blocking (https://github.com/matrix-org/matrix-spec-proposals/pull/4494) - ("uk.timedout.msc4494".to_owned(), true), - // server administration OAuth scope (https://github.com/matrix-org/matrix-spec-proposals/pull/4484) - ("org.continuwuity.msc4484.unstable".to_owned(), true), - // stripped state over federation (https://github.com/matrix-org/matrix-spec-proposals/pull/4560) - ("org.continuwuity.msc4560".to_owned(), true), + ("org.matrix.msc4174".to_owned(), experiments.msc4174.is_enabled()), + ("uk.timedout.msc4494".to_owned(), experiments.msc4494.is_enabled()), + ("org.continuwuity.msc4484.unstable".to_owned(), experiments.msc4484.is_enabled()), + ("org.continuwuity.msc4560".to_owned(), experiments.msc4560.is_enabled()), + ("fi.mau.msc2815".to_owned(), experiments.msc2815.is_enabled()), ]) } diff --git a/src/service/mod.rs b/src/service/mod.rs index 1a5505583..9a8722cff 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -42,6 +42,8 @@ pub mod transactions; pub mod uiaa; pub mod users; +use std::collections::BTreeMap; + pub(crate) use service::{Args, Dep, Service}; pub use crate::services::Services; @@ -51,8 +53,8 @@ conduwuit::mod_dtor! {} use std::sync::LazyLock; -use conduwuit::matrix::versions::{unstable_features, versions}; +use conduwuit::matrix::versions::versions; use ruma::api::SupportedVersions; pub static SUPPORTED_VERSIONS: LazyLock = - LazyLock::new(|| SupportedVersions::from_parts(&versions(), &unstable_features())); + LazyLock::new(|| SupportedVersions::from_parts(&versions(), &BTreeMap::new())); diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index d0cfd058e..c4b66e866 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -591,9 +591,7 @@ impl super::Service { room_id: &RoomId, ) -> Option { let server = target_user_id.server_name(); - if !self.services.config.allow_sticky_events - || self.services.globals.server_is_ours(server) - { + if self.services.globals.server_is_ours(server) { return None; } diff --git a/src/service/rooms/timeline/helpers.rs b/src/service/rooms/timeline/helpers.rs index 170b35889..dc5db990e 100644 --- a/src/service/rooms/timeline/helpers.rs +++ b/src/service/rooms/timeline/helpers.rs @@ -48,13 +48,7 @@ impl super::Service { PartialPdu { event_type: event_type.to_string().into(), content, - sticky: self - .services - .config - .allow_sticky_events - .then_some(sticky_duration_ms) - .flatten() - .map(sticky::object), + sticky: sticky_duration_ms.map(sticky::object), state_key: Some(state_key.into()), timestamp, ..Default::default() diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 69c7faa70..6c206d9bf 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -287,7 +287,12 @@ impl Service { } fn unredacted_content_cutoff(&self) -> u64 { - let max_age = self.services.config.unredacted_content_max_age_secs; + let max_age = self + .services + .config + .experiments + .msc2815 + .map_or_default(|c| c.unredacted_content_max_age_secs); utils::millis_since_unix_epoch().saturating_sub(max_age.saturating_mul(1000)) } diff --git a/src/service/rooms/timeline/redact.rs b/src/service/rooms/timeline/redact.rs index d6a67be63..af69fcb36 100644 --- a/src/service/rooms/timeline/redact.rs +++ b/src/service/rooms/timeline/redact.rs @@ -1,3 +1,4 @@ +use conduwuit::config::experiments::ToggledExperiment; use conduwuit_core::{ Result, err, matrix::event::Event, @@ -52,11 +53,7 @@ impl super::Service { .get_room_version(&pdu.room_id_or_hash()) .await?; - if self - .services - .config - .allow_moderators_to_view_redacted_content - { + if self.services.config.experiments.msc2815.is_enabled() { let mut pdu_json = self.get_pdu_json_from_id(&pdu_id).await?; pdu_json.remove("event_id"); if content_hash(&pdu_json) diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index 03be9e2ce..26cb371b1 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -327,7 +327,7 @@ impl Service { /// still-sticky events. Only netburst delivers this queue, so with it /// disabled there is nothing to keep the event for. async fn survives_netburst_trim(&self, event: &SendingEvent) -> bool { - if !self.server.config.allow_sticky_events || !self.server.config.startup_netburst { + if !self.server.config.startup_netburst { return false; } From f6c9b53e17c38c1307b2f2f3767fa3dde558fea9 Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 13 Nov 2026 18:18:08 +0000 Subject: [PATCH 213/342] chore: Update reference config file --- conduwuit-example.toml | 31 +++++-------------------------- 1 file changed, 5 insertions(+), 26 deletions(-) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 5bf234f89..3babc66d0 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -1657,32 +1657,6 @@ # env: CONTINUWUITY_ALLOW_INCOMING_TYPING #allow_incoming_typing = true -# Allow the use of unstable persistent "sticky events" ([MSC4354]) -# -# MSC4354: https://c10y.cc/MSC4354 -# -# env: CONTINUWUITY_ALLOW_STICKY_EVENTS -#allow_sticky_events = false - -# Allow room moderators to view redacted event content ([MSC2815]). -# -# Redacted content is readable by users at or above the room's `redact` -# power level, and by server admins, until it expires. -# -# MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 -# -# env: CONTINUWUITY_ALLOW_MODERATORS_TO_VIEW_REDACTED_CONTENT -#allow_moderators_to_view_redacted_content = false - -# How long to retain the content of redacted events, in seconds. Expired -# content is deleted by a periodic purge and is no longer served. -# -# Only has an effect when allow_moderators_to_view_redacted_content is -# enabled. -# -# env: CONTINUWUITY_UNREDACTED_CONTENT_MAX_AGE_SECS -#unredacted_content_max_age_secs = 7776000 (90 days) - # Maximum time federation user can indicate typing. # # env: CONTINUWUITY_TYPING_FEDERATION_TIMEOUT_S @@ -2312,6 +2286,11 @@ # env: CONTINUWUITY_ALLOW_WEB_INDEXING #allow_web_indexing = false +# Configuration for unstable features. +# +# env: CONTINUWUITY_EXPERIMENTS +#experiments = false + [global.tls] # Path to a valid TLS certificate file. From 82e42696aa93355962152836df1db5b483aaea1c Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 13 Nov 2026 18:18:51 +0000 Subject: [PATCH 214/342] chore: Fix display for experiments --- conduwuit-example.toml | 5 ----- src/core/config/mod.rs | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 3babc66d0..d13bd50a4 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -2286,11 +2286,6 @@ # env: CONTINUWUITY_ALLOW_WEB_INDEXING #allow_web_indexing = false -# Configuration for unstable features. -# -# env: CONTINUWUITY_EXPERIMENTS -#experiments = false - [global.tls] # Path to a valid TLS certificate file. diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index be2461f50..d826d82e8 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -2449,7 +2449,7 @@ pub struct Config { /// Configuration for unstable features. /// - /// display: none + /// display: hidden #[serde(default)] pub experiments: Experiments, From d4c6decdd66c9ed3301f793da2e3849d6c28aba4 Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 13 Nov 2026 21:19:05 +0000 Subject: [PATCH 215/342] feat: Theoretically add experiments to the config reference For some reason it doesn't *actually* embed. I'm not too sure how the config generator works, so maybe im just missing something. --- changelog.d/2517.feature.md | 1 + src/core/config/experiments.rs | 14 ++++++++++++++ src/core/config/mod.rs | 2 +- 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 changelog.d/2517.feature.md diff --git a/changelog.d/2517.feature.md b/changelog.d/2517.feature.md new file mode 100644 index 000000000..ab8a89b1c --- /dev/null +++ b/changelog.d/2517.feature.md @@ -0,0 +1 @@ +Changed the policy on unstable features, disabling most by default and making them configurable in a tidy little `experiments` configuration. See also: #1884. diff --git a/src/core/config/experiments.rs b/src/core/config/experiments.rs index 82a49e0c5..e140a695c 100644 --- a/src/core/config/experiments.rs +++ b/src/core/config/experiments.rs @@ -1,7 +1,9 @@ +use conduwuit_macros::config_example_generator; use serde::Deserialize; /// Configuration for experimental features. #[derive(Debug, Deserialize, Default, Clone)] +#[config_example_generator(filename = "conduwuit-example.toml", section = "global.experiments")] pub struct Experiments { /// MSC2815: Proposal to allow room moderators to view redacted event /// content @@ -14,6 +16,8 @@ pub struct Experiments { /// Requires a supporting client to use. /// /// https://github.com/matrix-org/matrix-spec-proposals/pull/2815 + /// + /// default: false #[serde(default)] pub msc2815: Option, /// MSC4155: Invite filtering @@ -25,6 +29,8 @@ pub struct Experiments { /// Requires a supporting client to set up on an account. /// /// https://github.com/matrix-org/matrix-spec-proposals/pull/4155 + /// + /// default: false #[serde(default)] pub msc4155: SimpleExperiment, /// MSC4174: Web push @@ -34,6 +40,8 @@ pub struct Experiments { /// gateway like Sygnal. /// /// https://github.com/matrix-org/matrix-spec-proposals/pull/4174 + /// + /// default: false #[serde(default)] pub msc4174: SimpleExperiment, /// MSC4484: Server Administration OAuth Scope @@ -43,6 +51,8 @@ pub struct Experiments { /// to administrator endpoints like locking & suspension. /// /// https://github.com/matrix-org/matrix-spec-proposals/pull/4484 + /// + /// default: false #[serde(default)] pub msc4484: SimpleExperiment, /// MSC4494: Membership-based invite blocking @@ -62,6 +72,8 @@ pub struct Experiments { /// Requires a supporting client to enable on an account. /// /// https://github.com/matrix-org/matrix-spec-proposals/pull/4494 + /// + /// default: false #[serde(default)] pub msc4494: SimpleExperiment, /// MSC4560: Stripped state requests over federation @@ -72,6 +84,8 @@ pub struct Experiments { /// significantly faster when this proposal is enabled and used. /// /// https://github.com/matrix-org/matrix-spec-proposals/pull/4560 + /// + /// default: false #[serde(default)] pub msc4560: SimpleExperiment, } diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index d826d82e8..078e2558f 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -2449,7 +2449,7 @@ pub struct Config { /// Configuration for unstable features. /// - /// display: hidden + /// display: nested #[serde(default)] pub experiments: Experiments, From bfb611d9e4344412bbeb82dcf5dabec4c696a8cc Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Fri, 13 Nov 2026 16:28:32 -0500 Subject: [PATCH 216/342] fix(config): Include experiments in the generated example config --- conduwuit-example.toml | 94 ++++++++++++++++++++++++++++++++++ src/core/config/experiments.rs | 34 ++++++++---- src/core/config/mod.rs | 7 ++- 3 files changed, 125 insertions(+), 10 deletions(-) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index d13bd50a4..7cc920932 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -2657,3 +2657,97 @@ # # env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE #profile_key_import_mode = "on_registration" + +[global.experiments] + +# MSC4155: Invite filtering +# +# Provides advanced invite filtering rules for users, allowing complex +# configurations that can allow, ignore, and reject invites from users and +# servers broadly. +# +# Requires a supporting client to set up on an account. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4155 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4155 +#msc4155 = false + +# MSC4174: Web push +# +# Adds server-side support for web push, allowing web clients to receive +# push notifications directly without the need for an intermediary push +# gateway like Sygnal. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4174 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4174 +#msc4174 = false + +# MSC4484: Server Administration OAuth Scope +# +# Adds a new OAuth2 scope that explicitly grants a token temporary +# homeserver administrator privileges, granting temporary token access +# to administrator endpoints like locking & suspension. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4484 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4484 +#msc4484 = false + +# MSC4494: Membership-based invite blocking +# +# Adds a new invite blocking action that will reject all invites coming +# from users who do not share a room with the invitee that is not `public` +# (the join rule). +# +# This is not related to MSC4155, this proposal instead builds on the +# "invite blocking" proposal that landed in the specification in v1.17, +# which simply allows enabling or disabling invites altogether. +# +# MSC4494 is a good middle-ground between the allowlisting possible with +# MSC4155, and the general desire to block invites from users you may not +# know. +# +# Requires a supporting client to enable on an account. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4494 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4494 +#msc4494 = false + +# MSC4560: Stripped state requests over federation +# +# Implements a more efficient way for servers to acquire and serve +# "stripped state" to clients, which is typically only used for displaying +# rooms. The display of space hierarchies and room summaries is +# significantly faster when this proposal is enabled and used. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4560 +#msc4560 = false + +#[global.experiments.msc2815] +# MSC2815: Proposal to allow room moderators to view redacted event content +# +# Allows the server to retain unredacted copies of events that have been +# redacted for a limited period of time, which allows room moderators and +# server administrators to reveal redacted contents. Useful for moderation +# and investigating reports. +# +# Requires a supporting client to use. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/2815 + + +# Whether to enable MSC2815. +# +# env: CONTINUWUITY_EXPERIMENTS__MSC2815__ENABLED +#enabled = false + +# How long, in seconds, to retain the original content of redacted +# events before it is permanently erased. Defaults to 90 days. +# +# env: CONTINUWUITY_EXPERIMENTS__MSC2815__UNREDACTED_CONTENT_MAX_AGE_SECS +#unredacted_content_max_age_secs = 7776000 diff --git a/src/core/config/experiments.rs b/src/core/config/experiments.rs index e140a695c..14d5d556f 100644 --- a/src/core/config/experiments.rs +++ b/src/core/config/experiments.rs @@ -8,16 +8,9 @@ pub struct Experiments { /// MSC2815: Proposal to allow room moderators to view redacted event /// content /// - /// Allows the server to retain unredacted copies of events that have been - /// redacted for a limited period of time, which allows room moderators and - /// server administrators to reveal redacted contents. Useful for moderation - /// and investigating reports. + /// See [`MSC2815`] for details. /// - /// Requires a supporting client to use. - /// - /// https://github.com/matrix-org/matrix-spec-proposals/pull/2815 - /// - /// default: false + /// display: nested #[serde(default)] pub msc2815: Option, /// MSC4155: Invite filtering @@ -113,9 +106,32 @@ impl ToggledExperiment for SimpleExperiment { /// /// MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 #[derive(Debug, Deserialize, Default, Clone, Copy)] +#[config_example_generator( + filename = "conduwuit-example.toml", + section = "global.experiments.msc2815", + optional = "true", + subheader = r#"# MSC2815: Proposal to allow room moderators to view redacted event content +# +# Allows the server to retain unredacted copies of events that have been +# redacted for a limited period of time, which allows room moderators and +# server administrators to reveal redacted contents. Useful for moderation +# and investigating reports. +# +# Requires a supporting client to use. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/2815"# +)] pub struct MSC2815 { + /// Whether to enable MSC2815. + /// + /// default: false #[serde(default)] pub enabled: bool, + + /// How long, in seconds, to retain the original content of redacted + /// events before it is permanently erased. Defaults to 90 days. + /// + /// default: 7776000 #[serde(default = "default_unredacted_content_max_age_secs")] pub unredacted_content_max_age_secs: u64, } diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 078e2558f..b720756ee 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -1,6 +1,5 @@ #![allow(clippy::doc_link_with_quotes)] pub mod check; -pub mod experiments; pub mod manager; pub mod proxy; @@ -3423,3 +3422,9 @@ fn default_profile_key_map() -> HashMap { fn default_unauthenticated_request_ratelimit() -> PerMinuteRatelimiter { PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap())) } + +// NOTE: This must be declared *after* every config struct in this file. The +// example config generator writes sections in macro expansion order, and the +// `global` section truncates the file, so declaring this module any earlier +// causes its sections to be wiped from the generated example config. +pub mod experiments; From 4811ad831dd4e39ae8bce6d5eebebdb5f4658905 Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 13 Nov 2026 21:40:30 +0000 Subject: [PATCH 217/342] feat: Call out experiments and staleness in the config reference --- conduwuit-example.toml | 9 +++++++++ src/core/config/experiments.rs | 13 ++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 7cc920932..1f9bb0b5e 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -2659,6 +2659,15 @@ #profile_key_import_mode = "on_registration" [global.experiments] +# Continuwuity's experimental features are frequently updated. +# If you got this configuration via a package manager, chances are it's outdated. +# Check out the configuration reference online to see a fresh version: +# https://continuwuity.org/reference/config.html#:~:text=global.experiments +# +# Please keep in mind that experiments are used to enable unstable features. +# You probably don't need to enable any of these unless you know what they are, +# and consequently know why you should enable them. + # MSC4155: Invite filtering # diff --git a/src/core/config/experiments.rs b/src/core/config/experiments.rs index 14d5d556f..c19b19ad0 100644 --- a/src/core/config/experiments.rs +++ b/src/core/config/experiments.rs @@ -3,7 +3,18 @@ use serde::Deserialize; /// Configuration for experimental features. #[derive(Debug, Deserialize, Default, Clone)] -#[config_example_generator(filename = "conduwuit-example.toml", section = "global.experiments")] +#[config_example_generator( + filename = "conduwuit-example.toml", + section = "global.experiments", + subheader = r##"# Continuwuity's experimental features are frequently updated. +# If you got this configuration via a package manager, chances are it's outdated. +# Check out the configuration reference online to see a fresh version: +# https://continuwuity.org/reference/config.html#:~:text=global.experiments +# +# Please keep in mind that experiments are used to enable unstable features. +# You probably don't need to enable any of these unless you know what they are, +# and consequently know why you should enable them."## +)] pub struct Experiments { /// MSC2815: Proposal to allow room moderators to view redacted event /// content From 20943c6210611334f782d092e3b8956c7fb4f8f0 Mon Sep 17 00:00:00 2001 From: timedout Date: Fri, 13 Nov 2026 21:56:07 +0000 Subject: [PATCH 218/342] docs: Explain everything that was mentioned in 1884 --- docs/development/unstable_features.mdx | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/development/unstable_features.mdx b/docs/development/unstable_features.mdx index eb1daf7fd..3b421fb97 100644 --- a/docs/development/unstable_features.mdx +++ b/docs/development/unstable_features.mdx @@ -15,6 +15,15 @@ typically only accept implementations of proposals that seem like they are a net large portion of the Matrix ecosystem, rather than aiming to "implement everything". As such, the unstable feature list should typically be small and manageable. +**All** unstable proposals require an experiment before their implementation can be accepted. +Likewise, all experiments should default to being disabled, requiring explicit configuration to +enable. + +**Draft proposals** will not be merged until their proposal is undrafted. Likewise, the pull request +that implements the draft proposal should itself be marked "WIP", to avoid being merged or +prioritised for review. Review is still possible for WIP PRs, so feel free to request a round of +feedback. + ## Adding an unstable feature First, navigate to `src/core/config/experiments.rs`. There, you have two options for adding an @@ -73,3 +82,24 @@ const DEPRECATED_KEYS: &[&str] = [ + "experiments.msc9999", ]; ``` + +## Always-on experiments + +Some experiments can be forcefully enabled (i.e. always-on), or enabled by default. This should only +be the case in exceptional circumstances, and must be adequately well documented. Some examples of +situations that may warrant an experiment being always-enabled: + +* A proposal was implemented AFTER it was merged, but BEFORE it had a merged spec PR. +These proposals are typically as stable as they'll get, as major changes post-factum of an MSC +merge requires another MSC, so only minor changes can be made in the spec PR phase. +* The daily experience of users would be at a great detriment without the experiment being enabled. +* A proposal is so simple that making it opt-in would be pointless. This is *incredibly* rare. + +The latter two require explicit maintainer approval, so discuss those with the maintainer team +first. You can exercise your own judgement for the first. + +Always-on or enabled-by-default experiments must explain in detail why they're exempt from the +standard experiments policy via comments in surrounding areas, like +`src/core/config/experiments.rs` and `src/core/matrix/versions.rs`. Ideally, these features are not +unstable for too long, so explaining a timescale for how long before the feature is stabilised is +also helpful. From 7ade8c4899e48bec31759f1eabcd89c6844a9a70 Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Sat, 14 Nov 2026 14:22:11 +0100 Subject: [PATCH 219/342] docs: Disable LLM buttons in documentation ew --- rspress.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/rspress.config.ts b/rspress.config.ts index 9f4931069..beaca2bd4 100644 --- a/rspress.config.ts +++ b/rspress.config.ts @@ -41,6 +41,7 @@ export default defineConfig({ }, }, themeConfig: { + llmsUI: false, socialLinks: [ { icon: { From 559f76908e963b83f6b985af255886a4ed251ce6 Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Sat, 14 Nov 2026 14:28:16 +0100 Subject: [PATCH 220/342] docs: Disable webMcp ew x2 --- rspress.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/rspress.config.ts b/rspress.config.ts index beaca2bd4..a2584ac5f 100644 --- a/rspress.config.ts +++ b/rspress.config.ts @@ -40,6 +40,7 @@ export default defineConfig({ }, }, }, + webMcp: false, themeConfig: { llmsUI: false, socialLinks: [ From 700c11d75852136f584a96608bbee540c2936777 Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Sat, 14 Nov 2026 14:36:46 +0100 Subject: [PATCH 221/342] docs: Disable even more llm stuff fuck off LLM bullshit ew x3 --- rspress.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/rspress.config.ts b/rspress.config.ts index a2584ac5f..de38b38eb 100644 --- a/rspress.config.ts +++ b/rspress.config.ts @@ -11,6 +11,7 @@ export default defineConfig({ light: '/assets/logo.svg', dark: '/assets/logo.svg', }, + llms: false, // Use `.no-zoom` class to disable image zooms mediumZoom: { selector: '.rspress-doc :not(.no-zoom *) > img', From add66bd0b7e2af8ed6011aae092c5ac0715b4c25 Mon Sep 17 00:00:00 2001 From: theS1LV3R Date: Fri, 13 Nov 2026 13:50:09 +0100 Subject: [PATCH 222/342] chore: Update resolvematrix to 1.4.2 --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 71b6cc3f9..50f031c2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4897,9 +4897,9 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" [[package]] name = "resolvematrix" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "565260441c783e26272b2d879525e80e97552e851fffa723cb0cfe0a3c46df92" +checksum = "d6e659fe17ed82acfac43641d00d1bbfd0a9d53ec4d2f901b01f792f0e2c9e3c" dependencies = [ "hickory-resolver", "num-traits", diff --git a/Cargo.toml b/Cargo.toml index 530250644..c59b353af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -600,7 +600,7 @@ features = ["std"] version = "0.3.0" [workspace.dependencies.resolvematrix] -version = "1.4.1" +version = "1.4.2" features = ["unstable-msc4188"] [workspace.dependencies.serde_urlencoded] From c5cd82a6a3c004b9651dc3e86eef30e172053119 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 14 Nov 2026 20:12:45 +0000 Subject: [PATCH 223/342] fix: SEC45 Co-authored-by: Henry-Hiles --- src/service/rooms/state_accessor/user_can.rs | 10 ++++++++++ src/service/rooms/timeline/redact.rs | 8 +++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/service/rooms/state_accessor/user_can.rs b/src/service/rooms/state_accessor/user_can.rs index 7e7340bc6..2a6d52515 100644 --- a/src/service/rooms/state_accessor/user_can.rs +++ b/src/service/rooms/state_accessor/user_can.rs @@ -33,6 +33,16 @@ impl super::Service { return Err!(Request(Forbidden("Redacting m.room.create is not safe, forbidding."))); } + // Defense in depth, shouldn't be reachable + if redacting_event + .as_ref() + .is_ok_and(|pdu| pdu.room_id() != Some(room_id)) + { + return Err!(Request(Forbidden( + "Cannot redact an event that belongs to a different room." + ))); + } + if redacting_event .as_ref() .is_ok_and(|pdu| *pdu.kind() == TimelineEventType::RoomServerAcl) diff --git a/src/service/rooms/timeline/redact.rs b/src/service/rooms/timeline/redact.rs index af69fcb36..905cd40c7 100644 --- a/src/service/rooms/timeline/redact.rs +++ b/src/service/rooms/timeline/redact.rs @@ -1,6 +1,6 @@ use conduwuit::config::experiments::ToggledExperiment; use conduwuit_core::{ - Result, err, + Err, Result, err, matrix::event::Event, utils::{self}, warn, @@ -33,6 +33,12 @@ impl super::Service { err!(Database(error!(?pdu_id, %event_id, ?e, "PDU ID points to invalid PDU."))) })?; + if pdu.room_id() != reason.room_id() { + return Err!(Request(Forbidden( + "Cannot redact an event that belongs to a different room." + ))); + } + let thread_root = match pdu.get_content::() { | Ok(ExtractRelatesTo { relates_to: Relation::Thread(thread) }) => Some(thread.event_id), From 24e962a656b1aae6c4f4b41a9873409897857d8e Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 14 Nov 2026 21:14:00 +0000 Subject: [PATCH 224/342] chore: Release --- CHANGELOG.md | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ Cargo.lock | 24 ++++++++-------- Cargo.toml | 2 +- 3 files changed, 93 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e39a88dcf..4a0d2be35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,83 @@ +# Continuwuity v26.11.0-alpha.2 (2026-11-14) + +## Features + +- Added opt-in OpenTelemetry metrics, exported over OTLP or scraped by Prometheus from `/_continuwuity/metrics`, and a Grafana dashboard. Contributed by @eleboucher. (prometheus-metrics) +- Add support for using custom DNS servers instead of using /etc/resolv.conf. Contributed by @s1lv3r. ([#2056](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2056)) +- Continuwuity now supports configuring additional trusted audience values for deployments using OIDC with an IDP that sends them. Contributed by @ginger ([#2226](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2226)) +- "!admin users list" now hides deactivated users by default, but can display them with the optional "--show-deactivated" flag. "--hide-suspended" and "--hide-locked" have been added as well, which stop suspended and locked users from being displayed respectively. Contributed by @Clubs. ([#2292](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2292)) +- Added support for [MSC4494: Membership-based invite blocking](https://github.com/matrix-org/matrix-spec-proposals/pull/4494) ([#2297](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2297)) +- Appservices now receive typing indicators and read receipts. Contributed by @Jade ([#2327](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2327)) +- Added support for servers returning 410 gone to indicate they are no longer serving a Matrix server ([MSC4188](https://github.com/matrix-org/matrix-spec-proposals/pull/4188)). Contributed by @nex and @silversys ([#2355](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2355)) +- Changed the policy on unstable features, disabling most by default and making them configurable in a tidy little `experiments` configuration. See also: #1884. ([#2517](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2517)) +- Added support for [MSC4363](https://github.com/matrix-org/matrix-spec-proposals/pull/4363) (OAuth step-up authentication). Contributed by @ginger. +- Added support for [MSC2815](https://github.com/matrix-org/matrix-spec-proposals/pull/2815), allowing room moderators to fetch the original content of redacted events, behind the `allow_moderators_to_view_redacted_content` config option. Contributed by @eleboucher. +- Added support for [MSC4484](https://github.com/matrix-org/matrix-spec-proposals/pull/4484). Clients which use the built-in Matrix server administration APIs will need to ask for the appropriate scope when signing in with OAuth. Contributed by @ginger. +- Check content-type header on federation responses, ignoring any that don't match (spec compliance) +- Implemented unstable support for [MSC4560] (Stripped state requests over federation). Contributed by @ginger. + + [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +- Profile banners are now treated as images when imported from OIDC claims, like avatars already were. +- Remove support for legacy, unauthenticated media, including the `allow_legacy_media` and `freeze_legacy_media` options. +- The first-run version of the web UI now includes a link to the registration page. Contributed by @ginger + +## Bugfixes + +- Fixed `/get_missing_events` rejecting requests with more `earliest_events` than the `limit`. Contributed by @eleboucher. (get-missing-events-earliest-limit) +- Invitees are now added as room creators when creating a v12+ trusted private chat. Contributed by @ginger. ([#2162](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2162)) +- Fixed push gateway URLs containing the configured notification path outside of their suffix. Contributed by @eleboucher. ([#2261](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2261)) +- "!admin users change-email" now verifies a user exists before attempting to change their email. Contributed by @Clubs. ([#2298](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2298)) +- Fixed URL preview image MIME types and rejected failed downloads. Contributed by @eleboucher. ([#2308](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2308)) +- Correctly set RocksDB column options, including enabling block caches. Contributed by @Jade ([#2345](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2345)) +- Fix some possible deadlocks/freezes and reduce lock contention (improving performance). Contributed by @Jade ([#2351](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2351)) +- Once again fixed how room extremities are handled, fixing a problem that made continuwuity gradually make rooms needlessly complex, which also caused more frequent state resets. ([#2356](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2356)) +- The OAuth identity reset page is no longer linked from the account management UI to reduce confusion. Contributed by @ginger. ([#2383](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2383)) +- Fixed a worker panic when knocking on a room over federation. Contributed by @eleboucher. ([#2387](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2387)) +- Perform more validation on events received during atomic gapfill from remote servers, fixing a panic if bad data was persisted by another server and later lazily fetched by us. ([#2400](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2400)) +- Redirect URIs in OAuth clients' metadata are now properly validated to be on a subdomain of the OAuth issuer URL domain. Contributed by @ginger. ([#2421](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2421)) +- Fix v12 rooms created by the same user in the same millisecond ending up as the same room. Contributed by @eleboucher. ([#2424](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2424)) +- Client-server API endpoints are now properly ratelimited for unauthenticated requests. Contributed by @ginger. ([#2444](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2444)) +- Setting a profile key longer than 255 bytes now returns 400 `M_KEY_TOO_LARGE` as required by the spec, instead of 413 `M_TOO_LARGE`. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Setting `m.fully_read` via the account data endpoints now returns 405 `M_BAD_JSON` as required by the spec, instead of 400. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Appservices masquerading as a device that does not exist now receive 400 `M_UNKNOWN_DEVICE` as required by the spec, instead of 403 `M_FORBIDDEN`. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Setting profile data that would make the profile exceed 64 KiB now returns 400 `M_PROFILE_TOO_LARGE` as required by the spec, instead of a 500 error. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- The `m.forget_forced_upon_leave` capability now reflects the `forget_forced_upon_leave` config option instead of always being advertised as enabled. ([#2452](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2452)) +- Fixed push notifications for membership events setting `user_is_target` based on the sender rather than the user being notified. ([#2454](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2454)) +- Ensure HTTP clients actually follow the `dns_servers` config option. Contributed by @silversys ([#2460](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2460)) +- Reworked event relations to follow the spec more closely. Pagination of `/relations` now returns the correct pages and `next_batch` tokens, recursive relations are returned in the right order without duplicates, and bundled `m.reference` aggregations now include every reference. Contributed by @Henry-Hiles (QuadRadical). ([#2465](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2465)) +- Read receipts are now more spec compliant, will work better in threads and are less likely to end up causing loops with other software. Contributed by @Jade ([#2481](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2481)) +- Fix the DNS resolver failing to start without `/etc/resolv.conf` when `dns_servers` is configured. Contributed by @eleboucher. ([#2495](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2495)) +- Fixed OIDC logins failing after the identity provider rotates its signing keys. Contributed by @eleboucher. ([#2497](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2497)) +- Creating a room with valid but non-canonical JSON now returns `400 M_BAD_JSON` instead of panicking the worker and returning `500 M_UNKNOWN`. +- Fix account data updates sent at the same time leaving old copies behind, which every initial sync then returned. Existing copies are removed on startup. Contributed by @eleboucher. +- Fix gap filling skipping outlier events that are missing their previous events. Contributed by @eleboucher. +- Fix incoming federation events losing state changes when predecessors share the same state-before snapshot. Contributed by @eleboucher. +- Fix new devices sometimes never reaching other users' device lists. Contributed by @eleboucher. +- Fix state resolution applying events out of order, which could undo room joins. Contributed by @eleboucher. +- Fix to-device messages, including room keys, sometimes being lost before delivery. Contributed by @eleboucher. +- For deployments using OIDC with `profile_key_import_mode` set to `on_login`, users' avatars will no longer be clobbered if they didn't change their avatar since their last login. +- Joining a local room the user is not allowed to join now returns `403 M_FORBIDDEN` instead of `500 M_UNKNOWN` when there are no other servers to try. +- Room summary visibility checks are no longer incorrectly applied for remote rooms. Contributed by @ginger. +- The userinfo endpoint is now accessible even if federation is disabled, allowing LiveKit to be used on servers with federation disabled without using the server name whitelist. + +## Improved Documentation + +- Add the Authentication section to document available auth methods for Continuwuity. The "delegated authentication" guide has also been migrated to here. Contributed by @stratself. ([#2234](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2234)) +- Add a guide for push notifications, detailing how it works, push gateway specifics, troubleshooting common issues, and pointing to external guides for UnifiedPush backends. Contributed by @stratself ([#2244](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2244)) +- The deploying page now includes vital general information about installing Continuwuity: release tracks, update steps, and post-installation recommendations. Contributed by @stratself ([#2252](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2252)) +- Add some missing instructions on configuring Continuwuity on the RPM page. Users are encouraged to use the [generic deploying docs](https://continuwuity.org/deploying/generic) for the bulk of guidance anyhow. Contributed by @stratself ([#2275](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2275)) +- Better, more succinct [introduction page](https://continuwuity.org/introduction.html). Contributed by @stratself ([#2279](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2279)) +- Add a section on [troubleshooting Docker issues](https://continuwuity.org/troubleshooting#docker-issues). Contributed by @stratself. ([#2324](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2324)) +- Instructions for Authelia added to the [OIDC guide](https://continuwuity.org/authentication/oidc.html). Contributed by @fhoekstra ([#2341](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2341)) +- Docker compose examples now use bind mounts by default, instead of Docker volumes, as they are easier to work with esp. for backup/restore. Contributed by @stratself. ([#2353](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2353)) +- The documentation now refers to the Continuwuity Docker service as `continuwuity` instead of `homeserver`. + +## Misc + +- #2423 +- Upgraded rocksdb from 11.1.1 to 11.12.0 and jemalloc to 5.4.0. + + # Continuwuity v26.11.0-alpha.1 (2026-11-10) ## Features diff --git a/Cargo.lock b/Cargo.lock index 50f031c2a..aabcd620f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -865,7 +865,7 @@ dependencies = [ [[package]] name = "conduwuit" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "clap", "conduwuit_build_metadata", @@ -897,7 +897,7 @@ dependencies = [ [[package]] name = "conduwuit_admin" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "clap", "conduwuit_api", @@ -921,7 +921,7 @@ dependencies = [ [[package]] name = "conduwuit_api" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "axum", "base64 0.23.1", @@ -953,7 +953,7 @@ dependencies = [ [[package]] name = "conduwuit_build_metadata" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "built", "cargo_metadata", @@ -961,7 +961,7 @@ dependencies = [ [[package]] name = "conduwuit_core" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "argon2", "arrayvec", @@ -1031,7 +1031,7 @@ dependencies = [ [[package]] name = "conduwuit_database" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "async-channel", "conduwuit_core", @@ -1051,7 +1051,7 @@ dependencies = [ [[package]] name = "conduwuit_macros" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "itertools 0.15.0", "proc-macro2", @@ -1061,7 +1061,7 @@ dependencies = [ [[package]] name = "conduwuit_router" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "axum", "axum-server", @@ -1094,7 +1094,7 @@ dependencies = [ [[package]] name = "conduwuit_service" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "askama", "assign", @@ -1150,7 +1150,7 @@ dependencies = [ [[package]] name = "conduwuit_web" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "askama", "async-trait", @@ -5167,7 +5167,7 @@ dependencies = [ [[package]] name = "ruminuwuity" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "assign", "http", @@ -7351,7 +7351,7 @@ dependencies = [ [[package]] name = "xtask" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" dependencies = [ "askama", "cargo_metadata", diff --git a/Cargo.toml b/Cargo.toml index c59b353af..034231d04 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ license = "Apache-2.0" # See also `rust-toolchain.toml` readme = "README.md" repository = "https://forgejo.ellis.link/continuwuation/continuwuity" -version = "26.11.0-alpha.1" +version = "26.11.0-alpha.2" [workspace.metadata.crane] name = "conduwuit" From 6e7ebe66c98049abfe0be80ca56f4fec055e4c49 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 14 Nov 2026 23:09:44 +0000 Subject: [PATCH 225/342] docs: Fix changelog --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a0d2be35..05fe334da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,7 @@ - Joining a local room the user is not allowed to join now returns `403 M_FORBIDDEN` instead of `500 M_UNKNOWN` when there are no other servers to try. - Room summary visibility checks are no longer incorrectly applied for remote rooms. Contributed by @ginger. - The userinfo endpoint is now accessible even if federation is disabled, allowing LiveKit to be used on servers with federation disabled without using the server name whitelist. +- `!admin token issue` can no longer issue registration tokens when `allow_registration` is false. Contributed by @Clubs. ## Improved Documentation @@ -74,7 +75,7 @@ ## Misc -- #2423 +- Updated internal Sentry integration setup to the new pattern required by the SDK. #2423 - Upgraded rocksdb from 11.1.1 to 11.12.0 and jemalloc to 5.4.0. From df5e03f3b466eca864b4d5ec1e3a53c87b96d047 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 11 Nov 2026 22:46:26 +0100 Subject: [PATCH 226/342] fix(sync): Apply the room and account data filters in legacy sync --- Cargo.lock | 1 + changelog.d/+sync-v3-filter.bugfix.md | 1 + src/api/Cargo.toml | 1 + src/api/client/sync/v3/mod.rs | 91 ++++++++++++++++++++++++++- 4 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+sync-v3-filter.bugfix.md diff --git a/Cargo.lock b/Cargo.lock index aabcd620f..6cab04b2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -949,6 +949,7 @@ dependencies = [ "sha1 0.11.0", "tokio", "tracing", + "wildmatch", ] [[package]] diff --git a/changelog.d/+sync-v3-filter.bugfix.md b/changelog.d/+sync-v3-filter.bugfix.md new file mode 100644 index 000000000..14d6d1d2a --- /dev/null +++ b/changelog.d/+sync-v3-filter.bugfix.md @@ -0,0 +1 @@ +Legacy `/sync` now honours the `room.rooms`, `room.not_rooms`, `account_data.types` and `account_data.not_types` filter fields instead of returning every room and all account data. Contributed by @eleboucher. diff --git a/src/api/Cargo.toml b/src/api/Cargo.toml index 329d934c4..ac70cb37d 100644 --- a/src/api/Cargo.toml +++ b/src/api/Cargo.toml @@ -87,6 +87,7 @@ serde.workspace = true sha1.workspace = true tokio.workspace = true tracing.workspace = true +wildmatch = "2.7.0" [lints] workspace = true diff --git a/src/api/client/sync/v3/mod.rs b/src/api/client/sync/v3/mod.rs index e6ac768f0..1363a1e0e 100644 --- a/src/api/client/sync/v3/mod.rs +++ b/src/api/client/sync/v3/mod.rs @@ -21,7 +21,7 @@ use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture}; use ruma::{ DeviceId, OwnedUserId, RoomId, UserId, api::client::{ - filter::FilterDefinition, + filter::{self, FilterDefinition, RoomFilter}, sync::sync_events::{ self, DeviceLists, v3::{ @@ -39,6 +39,7 @@ use service::{ account_data::AnyRawAccountDataEvent, rooms::lazy_loading::{self, MemberSet, Options as _}, }; +use wildmatch::WildMatch; use super::{load_timeline, share_encrypted_room}; use crate::{ @@ -267,15 +268,27 @@ pub(crate) async fn build_sync_events( use_state_after: body.use_state_after, }; + let unfiltered = Box::new(FilterDefinition::default()); + let unfiltered_context = SyncContext { filter: &unfiltered, ..context }; + let joined_rooms = services .rooms .state_cache .rooms_joined(syncing_user) + // a filtered out room still contributes its device list updates, which + // an initial sync does not have + .ready_filter(|room_id| { + last_sync_end_count.is_some() || room_selected(&filter.room, room_id) + }) .broad_filter_map(|room_id| async { + let selected = room_selected(&filter.room, &room_id); + // the client is not sent this room, so its lazy loading state must + // not change + let context = if selected { context } else { unfiltered_context }; let joined_room = load_joined_room(services, context, room_id.clone()).await; match joined_room { - | Ok((room, updates)) => Some((room_id, room, updates)), + | Ok((room, updates)) => Some((room_id, selected.then_some(room), updates)), | Err(err) => { error!(?err, %room_id, "error loading joined room"); None @@ -287,7 +300,9 @@ pub(crate) async fn build_sync_events( |(mut joined_rooms, mut all_updates), (room_id, joined_room, updates)| { all_updates.merge(updates); - if !joined_room.is_empty() { + if let Some(joined_room) = joined_room + && !joined_room.is_empty() + { joined_rooms.insert(room_id, joined_room); } @@ -299,6 +314,7 @@ pub(crate) async fn build_sync_events( .rooms .state_cache .rooms_left(syncing_user) + .ready_filter(|(room_id, _)| room_selected(&filter.room, room_id)) .broad_filter_map(|(room_id, leave_pdu)| async { let left_room = load_left_room(services, context, room_id.clone(), leave_pdu).await; @@ -317,6 +333,7 @@ pub(crate) async fn build_sync_events( .rooms .state_cache .rooms_invited(syncing_user) + .ready_filter(|(room_id, _)| room_selected(&filter.room, room_id)) .wide_filter_map(async |(room_id, invite_state)| { if is_ignored_invite(services, syncing_user, &room_id).await { None @@ -347,6 +364,7 @@ pub(crate) async fn build_sync_events( .rooms .state_cache .rooms_knocked(syncing_user) + .ready_filter(|(room_id, _)| room_selected(&filter.room, room_id)) .fold_default(|mut knocked_rooms: BTreeMap<_, _>, (room_id, knock_state)| async move { let knock_count = services .rooms @@ -376,6 +394,13 @@ pub(crate) async fn build_sync_events( .account_data .changes_since(None, syncing_user, last_sync_end_count, Some(current_count)) .ready_filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Global)) + .ready_filter(|event| { + event + .get_field::("type") + .ok() + .flatten() + .is_some_and(|event_type| type_selected(&filter.account_data, &event_type)) + }) .collect(); let to_device_events = services @@ -465,6 +490,24 @@ pub(crate) async fn build_sync_events( Ok(response) } +fn room_selected(filter: &RoomFilter, room_id: &RoomId) -> bool { + !filter.not_rooms.iter().any(|not_room| not_room == room_id) + && filter + .rooms + .as_ref() + .is_none_or(|rooms| rooms.iter().any(|room| room == room_id)) +} + +fn type_selected(filter: &filter::Filter, event_type: &str) -> bool { + let matches = |pattern: &String| WildMatch::new(pattern).matches(event_type); + + !filter.not_types.iter().any(matches) + && filter + .types + .as_ref() + .is_none_or(|types| types.iter().any(matches)) +} + #[tracing::instrument(name = "presence", level = "debug", skip_all)] async fn process_presence_updates( services: &Services, @@ -528,3 +571,45 @@ async fn prepare_lazily_loaded_members( lazily_loaded_members } + +#[cfg(test)] +mod tests { + use ruma::{owned_room_id, room_id}; + + use super::*; + + #[test] + fn rooms_filter_selects_rooms() { + let room_id = room_id!("!a:example.com"); + let mut filter = RoomFilter::default(); + assert!(room_selected(&filter, room_id)); + + filter.rooms = Some(Vec::new()); + assert!(!room_selected(&filter, room_id)); + + filter.rooms = Some(vec![room_id.to_owned()]); + assert!(room_selected(&filter, room_id)); + + filter.not_rooms = vec![owned_room_id!("!a:example.com")]; + assert!(!room_selected(&filter, room_id)); + } + + #[test] + fn types_filter_selects_account_data() { + let mut filter = filter::Filter::default(); + assert!(type_selected(&filter, "m.direct")); + + filter.types = Some(Vec::new()); + assert!(!type_selected(&filter, "m.direct")); + + filter.types = Some(vec!["m.direct".to_owned()]); + assert!(type_selected(&filter, "m.direct")); + + filter.types = Some(vec!["m.*".to_owned()]); + assert!(type_selected(&filter, "m.direct")); + assert!(!type_selected(&filter, "im.ponies.user_emotes")); + + filter.not_types = vec!["m.direct".to_owned()]; + assert!(!type_selected(&filter, "m.direct")); + } +} From 055c430e77748f71ff1bf9c2f41a2b6cfb3b8e7c Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Thu, 12 Nov 2026 15:38:42 +0100 Subject: [PATCH 227/342] refactor(sync): Build device list updates separately from joined rooms --- Cargo.toml | 3 + src/api/Cargo.toml | 2 +- src/api/client/sync/v3/joined.rs | 127 ++++++++++++++++++------------- src/api/client/sync/v3/mod.rs | 57 +++++++------- src/ruminuwuity/Cargo.toml | 2 +- 5 files changed, 110 insertions(+), 81 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 034231d04..83d70b227 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -272,6 +272,9 @@ version = "0.5.2" [workspace.dependencies.libloading] version = "0.9.0" +[workspace.dependencies.wildmatch] +version = "2.7.0" + # Validating urls in config, was already a transitive dependency [workspace.dependencies.url] version = "2.5.8" diff --git a/src/api/Cargo.toml b/src/api/Cargo.toml index ac70cb37d..689902717 100644 --- a/src/api/Cargo.toml +++ b/src/api/Cargo.toml @@ -87,7 +87,7 @@ serde.workspace = true sha1.workspace = true tokio.workspace = true tracing.workspace = true -wildmatch = "2.7.0" +wildmatch.workspace = true [lints] workspace = true diff --git a/src/api/client/sync/v3/joined.rs b/src/api/client/sync/v3/joined.rs index 7eee0d1d5..3a2828e69 100644 --- a/src/api/client/sync/v3/joined.rs +++ b/src/api/client/sync/v3/joined.rs @@ -64,7 +64,7 @@ pub(super) async fn load_joined_room( services: &Services, sync_context: SyncContext<'_>, ref room_id: OwnedRoomId, -) -> Result<(JoinedRoom, DeviceListUpdates)> { +) -> Result { /* Building a sync response involves many steps which all depend on each other. To parallelize the process as much as possible, each step is divided into its own function, @@ -80,7 +80,6 @@ pub(super) async fn load_joined_room( sticky, summary, notification_counts, - device_list_updates, }, ) = try_join3( build_account_data(services, sync_context, room_id), @@ -117,7 +116,7 @@ pub(super) async fn load_joined_room( unread_thread_notifications: BTreeMap::new(), }); - Ok((joined_room, device_list_updates)) + Ok(joined_room) } /// Collect changes to the syncing user's account data events. @@ -263,7 +262,6 @@ struct StateAndTimeline { sticky: Sticky, summary: Option, notification_counts: Option, - device_list_updates: DeviceListUpdates, } async fn build_sticky_events( @@ -377,24 +375,14 @@ async fn build_state_and_timeline( debug_warn!("timeline for newly joined room is empty"); } - let (summary, device_list_updates) = try_join( - build_room_summary( - services, - sync_context, - room_id, - shortstatehashes, - &timeline, - &state_events, - joined_since_last_sync, - ), - build_device_list_updates( - services, - sync_context, - room_id, - shortstatehashes, - &state_events, - joined_since_last_sync, - ), + let summary = build_room_summary( + services, + sync_context, + room_id, + shortstatehashes, + &timeline, + &state_events, + joined_since_last_sync, ) .await?; @@ -430,7 +418,6 @@ async fn build_state_and_timeline( sticky, summary, notification_counts, - device_list_updates, }) } @@ -854,35 +841,34 @@ async fn build_heroes( .await } -/// Collect updates to users' device lists for E2EE. -#[tracing::instrument(level = "debug", skip_all)] -async fn build_device_list_updates( +/// Collect updates to users' device lists for E2EE in a joined room. +#[tracing::instrument(level = "debug", skip_all, fields(%room_id))] +pub(super) async fn load_device_list_updates( services: &Services, - SyncContext { + sync_context: SyncContext<'_>, + room_id: &RoomId, +) -> Result { + let SyncContext { syncing_user, last_sync_end_count, current_count, .. - }: SyncContext<'_>, - room_id: &RoomId, - ShortStateHashes { current_shortstatehash, .. }: ShortStateHashes, - state_events: &Vec, - joined_since_last_sync: bool, -) -> Result { - let is_encrypted_room = services - .rooms - .state_accessor - .state_get(current_shortstatehash, &StateEventType::RoomEncryption, "") - .is_ok(); + } = sync_context; + + let mut device_list_updates = DeviceListUpdates::new(); // initial syncs don't include device updates, and rooms which aren't // encrypted don't affect them, so return early in either of those cases - if last_sync_end_count.is_none() || !(is_encrypted_room.await) { - return Ok(DeviceListUpdates::new()); + if last_sync_end_count.is_none() + || !services + .rooms + .state_accessor + .is_encrypted_room(room_id) + .await + { + return Ok(device_list_updates); } - let mut device_list_updates = DeviceListUpdates::new(); - // add users with changed keys to the `changed` list services .users @@ -893,19 +879,56 @@ async fn build_device_list_updates( }) .await; - // add users who now share encrypted rooms to `changed` and - // users who no longer share encrypted rooms to `left` - for state_event in state_events { - if state_event.kind == RoomMember { - let Some(content): Option = state_event.get_content().ok() + let shortstatehashes = fetch_shortstatehashes(services, sync_context, room_id).await?; + let ShortStateHashes { + current_shortstatehash, + last_sync_end_shortstatehash, + } = shortstatehashes; + + if check_joined_since_last_sync(services, shortstatehashes, sync_context).await? { + // the syncing user now shares an encrypted room with every member + services + .rooms + .state_cache + .room_members(room_id) + .ready_for_each(|user_id| { + device_list_updates.changed.insert(user_id); + }) + .await; + } else if let Some(last_sync_end_shortstatehash) = last_sync_end_shortstatehash + && last_sync_end_shortstatehash != current_shortstatehash + { + // add users who now share encrypted rooms to `changed` and + // users who no longer share encrypted rooms to `left` + let state_added = services + .rooms + .state_accessor + .state_added((last_sync_end_shortstatehash, current_shortstatehash)) + .await?; + + for (shortstatekey, _) in state_added { + let Ok((StateEventType::RoomMember, state_key)) = services + .rooms + .short + .get_statekey_from_short(shortstatekey) + .await else { continue; }; - let Some(user_id): Option = state_event - .state_key - .as_ref() - .and_then(|key| key.parse().ok()) + let Ok(user_id) = OwnedUserId::try_from(state_key.as_str()) else { + continue; + }; + + let Ok(content): Result = services + .rooms + .state_accessor + .state_get_content( + current_shortstatehash, + &StateEventType::RoomMember, + user_id.as_str(), + ) + .await else { continue; }; @@ -921,7 +944,7 @@ async fn build_device_list_updates( | Leave if !shares_encrypted_room => { device_list_updates.left.insert(user_id); }, - | Join if joined_since_last_sync || shares_encrypted_room => { + | Join if shares_encrypted_room => { device_list_updates.changed.insert(user_id); }, | _ => (), diff --git a/src/api/client/sync/v3/mod.rs b/src/api/client/sync/v3/mod.rs index 1363a1e0e..a2ef6ae00 100644 --- a/src/api/client/sync/v3/mod.rs +++ b/src/api/client/sync/v3/mod.rs @@ -46,7 +46,10 @@ use crate::{ Ruma, client::{ is_ignored_invite, - sync::v3::{joined::load_joined_room, left::load_left_room}, + sync::v3::{ + joined::{load_device_list_updates, load_joined_room}, + left::load_left_room, + }, }, client_ip::ClientIp, }; @@ -268,47 +271,45 @@ pub(crate) async fn build_sync_events( use_state_after: body.use_state_after, }; - let unfiltered = Box::new(FilterDefinition::default()); - let unfiltered_context = SyncContext { filter: &unfiltered, ..context }; - let joined_rooms = services .rooms .state_cache .rooms_joined(syncing_user) - // a filtered out room still contributes its device list updates, which - // an initial sync does not have - .ready_filter(|room_id| { - last_sync_end_count.is_some() || room_selected(&filter.room, room_id) - }) + .ready_filter(|room_id| room_selected(&filter.room, room_id)) .broad_filter_map(|room_id| async { - let selected = room_selected(&filter.room, &room_id); - // the client is not sent this room, so its lazy loading state must - // not change - let context = if selected { context } else { unfiltered_context }; let joined_room = load_joined_room(services, context, room_id.clone()).await; match joined_room { - | Ok((room, updates)) => Some((room_id, selected.then_some(room), updates)), + | Ok(room) => Some((room_id, room)), | Err(err) => { error!(?err, %room_id, "error loading joined room"); None }, } }) - .ready_fold( - (BTreeMap::new(), DeviceListUpdates::new()), - |(mut joined_rooms, mut all_updates), (room_id, joined_room, updates)| { - all_updates.merge(updates); + .ready_fold(BTreeMap::new(), |mut joined_rooms, (room_id, joined_room)| { + if !joined_room.is_empty() { + joined_rooms.insert(room_id, joined_room); + } - if let Some(joined_room) = joined_room - && !joined_room.is_empty() - { - joined_rooms.insert(room_id, joined_room); - } + joined_rooms + }); - (joined_rooms, all_updates) - }, - ); + // a filtered out room still contributes its device list updates + let device_list_updates = services + .rooms + .state_cache + .rooms_joined(syncing_user) + .broad_filter_map(|room_id| async move { + load_device_list_updates(services, context, &room_id) + .await + .inspect_err(|err| error!(?err, %room_id, "error loading device list updates")) + .ok() + }) + .ready_fold(DeviceListUpdates::new(), |mut all_updates, updates| { + all_updates.merge(updates); + all_updates + }); let left_rooms = services .rooms @@ -429,7 +430,8 @@ pub(crate) async fn build_sync_events( .list_unused_fallback_key_types(syncing_user, syncing_device); let ( - (joined_rooms, mut device_list_updates), + joined_rooms, + mut device_list_updates, left_rooms, invited_rooms, knocked_rooms, @@ -442,6 +444,7 @@ pub(crate) async fn build_sync_events( ) = async { futures::join!( joined_rooms, + device_list_updates, left_rooms, invited_rooms, knocked_rooms, diff --git a/src/ruminuwuity/Cargo.toml b/src/ruminuwuity/Cargo.toml index 19818776a..d523ce8a6 100644 --- a/src/ruminuwuity/Cargo.toml +++ b/src/ruminuwuity/Cargo.toml @@ -25,7 +25,7 @@ http.workspace = true ruma.workspace = true serde = { workspace = true } serde_json = { workspace = true } -wildmatch = "2.7.0" +wildmatch.workspace = true [dev-dependencies] From a3d23c371897ec61b79dbddbd86e967cdb668e9f Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 16 Nov 2026 05:05:23 +0000 Subject: [PATCH 228/342] chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.241.0 --- .forgejo/workflows/renovate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/renovate.yml b/.forgejo/workflows/renovate.yml index 8e3c04e51..b05933c09 100644 --- a/.forgejo/workflows/renovate.yml +++ b/.forgejo/workflows/renovate.yml @@ -43,7 +43,7 @@ jobs: name: Renovate runs-on: ubuntu-latest container: - image: ghcr.io/renovatebot/renovate:44.227.4@sha256:e09d40686f73d43b2c1e4667cb47d3c1d24a6ac730b74ce7aced9c84f68594f1 + image: ghcr.io/renovatebot/renovate:44.241.0@sha256:22d22b4ca7d768b5b469309d34379783bf91cd94a58faecf1cd0f4528a65d21c options: --tmpfs /tmp:exec steps: - name: Checkout From 92f9531defd7ef7e6b58966682a01728891c62d5 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 17 Nov 2026 05:01:16 +0000 Subject: [PATCH 229/342] chore(deps): update https://github.com/taiki-e/install-action digest to ab49d3c --- .forgejo/actions/timelord/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/actions/timelord/action.yml b/.forgejo/actions/timelord/action.yml index 5a5db6721..ab1746a57 100644 --- a/.forgejo/actions/timelord/action.yml +++ b/.forgejo/actions/timelord/action.yml @@ -71,7 +71,7 @@ runs: - name: Install timelord-cli and git-warp-time if: steps.check-binaries.outputs.need-install == 'true' - uses: https://github.com/taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2 + uses: https://github.com/taiki-e/install-action@ab49d3c64680143e184118bed66a46419fc15519 # v2 with: tool: git-warp-time,timelord-cli@3.0.1 From b3d099a52aa9b018edf25f7a13901f350568df1b Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 17 Nov 2026 09:07:42 +0000 Subject: [PATCH 230/342] fix: Always advertise unstable feature for MSC4354 Fixes #2542 --- src/core/matrix/versions.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/matrix/versions.rs b/src/core/matrix/versions.rs index 160efe085..8db196e1f 100644 --- a/src/core/matrix/versions.rs +++ b/src/core/matrix/versions.rs @@ -35,10 +35,10 @@ pub fn versions() -> Vec { pub fn unstable_features(experiments: &Experiments) -> BTreeMap { BTreeMap::from_iter([ // MatrixRTC (https://github.com/matrix-org/matrix-spec-proposals/pull/4143) - // Expected for spec v1.20 + // Expected for spec v1.20/v2.0 ("org.matrix.msc4143".to_owned(), true), // Simplified Sliding sync (https://github.com/matrix-org/matrix-spec-proposals/pull/4186) - // Expected for spec v1.20 + // Expected for spec v1.20/v2.0 ("org.matrix.simplified_msc3575".to_owned(), true), ("org.matrix.msc4155".to_owned(), experiments.msc4155.is_enabled()), // profile change propagation (https://github.com/matrix-org/matrix-spec-proposals/pull/4466) @@ -48,5 +48,8 @@ pub fn unstable_features(experiments: &Experiments) -> BTreeMap { ("org.continuwuity.msc4484.unstable".to_owned(), experiments.msc4484.is_enabled()), ("org.continuwuity.msc4560".to_owned(), experiments.msc4560.is_enabled()), ("fi.mau.msc2815".to_owned(), experiments.msc2815.is_enabled()), + // Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354) + // Proposal merged, expected for spec v1.20/v2.0 + ("org.matrix.msc4354".to_owned(), true), ]) } From 07d4c6f304191918b70c4e48307d791d8badf52a Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 17 Nov 2026 09:14:37 +0000 Subject: [PATCH 231/342] fix: Don't default to a 30-second sync timeout Fixes #2462 --- src/api/client/sync/v3/mod.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/api/client/sync/v3/mod.rs b/src/api/client/sync/v3/mod.rs index a2ef6ae00..f970c6541 100644 --- a/src/api/client/sync/v3/mod.rs +++ b/src/api/client/sync/v3/mod.rs @@ -3,7 +3,6 @@ mod left; mod state; use std::{ - cmp::{self}, collections::{BTreeMap, HashMap, HashSet}, time::Duration, }; @@ -207,7 +206,12 @@ pub(crate) async fn sync_events_route( let mut wake_receiver = services.sync.subscribe_to_wake(sender_user); let response = build_sync_events(&services, &body).await?; - if body.body.full_state + + let timeout_duration = body.body.timeout.unwrap_or_default(); + // If the timeout is zero, request has full_state=true, or there's + // meaningful data to return, do so immediately. + if timeout_duration.is_zero() + || body.body.full_state || !(response.rooms.is_empty() && response.presence.is_empty() && response.account_data.is_empty() @@ -217,10 +221,10 @@ pub(crate) async fn sync_events_route( return Ok(response); } - // Hang a few seconds so requests are not spammed - // Stop hanging if new info arrives - let default = Duration::from_secs(30); - let duration = cmp::min(body.body.timeout.unwrap_or(default), default); + // Otherwise, wait for a wake signal to rebuild changes. Cap timeout at 30 + // seconds (this isn't specced, but a reasonable cap since most clients have + // a 30-second polling interval). + let duration = timeout_duration.min(Duration::from_secs(30)); _ = tokio::time::timeout(duration, wake_receiver.changed()).await; // Retry returning data From 32bfe5f129117315fb8650a11847837cc462165b Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 17 Nov 2026 09:26:22 +0000 Subject: [PATCH 232/342] fix: Allow sync v2 to be interrupted by server shutdown Fixes #2361 --- src/api/client/sync/v3/mod.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/api/client/sync/v3/mod.rs b/src/api/client/sync/v3/mod.rs index f970c6541..e004ec08d 100644 --- a/src/api/client/sync/v3/mod.rs +++ b/src/api/client/sync/v3/mod.rs @@ -225,7 +225,11 @@ pub(crate) async fn sync_events_route( // seconds (this isn't specced, but a reasonable cap since most clients have // a 30-second polling interval). let duration = timeout_duration.min(Duration::from_secs(30)); - _ = tokio::time::timeout(duration, wake_receiver.changed()).await; + let mut shutdown_signal = services.server.signal.subscribe(); + tokio::select! { + _ = tokio::time::timeout(duration, wake_receiver.changed()) => {}, + _ = shutdown_signal.recv() => return Err!(Request(Unknown("Server is shutting down"), SERVICE_UNAVAILABLE)), + }; // Retry returning data build_sync_events(&services, &body).await From 4ef487f40e577ec546bc547048e0e2140d41caf7 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 17 Nov 2026 09:30:49 +0000 Subject: [PATCH 233/342] chore: Add changelog frags for quickfixes --- changelog.d/2361.bugfix.md | 1 + changelog.d/2462.bugfix.md | 1 + changelog.d/2542.bugfix.md | 1 + 3 files changed, 3 insertions(+) create mode 100644 changelog.d/2361.bugfix.md create mode 100644 changelog.d/2462.bugfix.md create mode 100644 changelog.d/2542.bugfix.md diff --git a/changelog.d/2361.bugfix.md b/changelog.d/2361.bugfix.md new file mode 100644 index 000000000..a0bc00bfc --- /dev/null +++ b/changelog.d/2361.bugfix.md @@ -0,0 +1 @@ +Requests waiting on `/_matrix/client/v3/sync` can now be interrupted by the server shutdown, unblocking the 30-second shutdown delay imposed on a quiet server. diff --git a/changelog.d/2462.bugfix.md b/changelog.d/2462.bugfix.md new file mode 100644 index 000000000..8ae8ab125 --- /dev/null +++ b/changelog.d/2462.bugfix.md @@ -0,0 +1 @@ +`/_matrix/client/v3/sync` no longer waits 30 seconds if the `timeout` parameter is omitted or set to zero, correctly reflecting the specification's rule that such requests should return immediately, even if they are empty. diff --git a/changelog.d/2542.bugfix.md b/changelog.d/2542.bugfix.md new file mode 100644 index 000000000..fa6324d5e --- /dev/null +++ b/changelog.d/2542.bugfix.md @@ -0,0 +1 @@ +The sticky events feature flag is correctly advertised in `/_matrix/client/versions` again after it was accidentally removed in #2517. From 902e54b525638a1b939373beeb33e98e7d5c1802 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 17 Nov 2026 10:14:32 +0000 Subject: [PATCH 234/342] fix: Off-by-one on PDU size check Related: https://github.com/ruma/ruma/pull/2677 --- src/service/rooms/timeline/create.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/service/rooms/timeline/create.rs b/src/service/rooms/timeline/create.rs index d53bb14fd..f1ea0484c 100644 --- a/src/service/rooms/timeline/create.rs +++ b/src/service/rooms/timeline/create.rs @@ -54,7 +54,7 @@ pub fn pdu_fits(owned_obj: &CanonicalJsonObject) -> bool { } // Now check the full PDU size match serde_json::to_string(owned_obj) { - | Ok(s) => s.len() <= 65535, + | Ok(s) => s.len() <= 65536, | Err(_) => false, } } @@ -305,7 +305,7 @@ impl super::Service { { return match e { | Error::SignatureJson(ruma::signatures::JsonError::PduTooLarge) => { - Err!(Request(TooLarge("Message/PDU is too long (exceeds 65535 bytes)"))) + Err!(Request(TooLarge("Message/PDU is too long (exceeds 65536 bytes)"))) }, | _ => Err!(Request(Unknown(warn!("Signing event failed: {e}")))), }; @@ -332,7 +332,7 @@ impl super::Service { // Verify that the *full* PDU isn't over 64KiB. if !pdu_fits(&pdu_json.clone()) { // feckin huge PDU mate - return Err!(Request(TooLarge("Message/PDU is too long (exceeds 65535 bytes)"))); + return Err!(Request(TooLarge("Message/PDU is too long (exceeds 65536 bytes)"))); } // Check with the policy server From 467e335c908f2b00fb7b37d9f169694a92d95a2d Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 17 Nov 2026 10:17:15 +0000 Subject: [PATCH 235/342] perf: Remove unnecessary clones for PDU size check --- src/service/rooms/membership/mod.rs | 2 +- src/service/rooms/timeline/create.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index b5bfa10d2..93246d8c2 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -534,7 +534,7 @@ impl Service { return state; }, }; - if !pdu_fits(&value.clone()) { + if !pdu_fits(&value) { warn!( "dropping incoming PDU {event_id} in room {room_id} from room join \ because it exceeds 65535 bytes or is otherwise too large." diff --git a/src/service/rooms/timeline/create.rs b/src/service/rooms/timeline/create.rs index f1ea0484c..daf99fac0 100644 --- a/src/service/rooms/timeline/create.rs +++ b/src/service/rooms/timeline/create.rs @@ -330,7 +330,7 @@ impl super::Service { pdu_json .insert("event_id".into(), CanonicalJsonValue::String(pdu.event_id.clone().into())); // Verify that the *full* PDU isn't over 64KiB. - if !pdu_fits(&pdu_json.clone()) { + if !pdu_fits(&pdu_json) { // feckin huge PDU mate return Err!(Request(TooLarge("Message/PDU is too long (exceeds 65536 bytes)"))); } From ceafc6f58d6f852e71cc8c9218760a2761ac1ab8 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 17 Nov 2026 23:57:45 +0000 Subject: [PATCH 236/342] chore: Update SECURITY.md (#2549) Reviewed-on: https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2549 Reviewed-by: Ginger Reviewed-by: Jade Ellis --- SECURITY.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index b386a571f..913992235 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -23,12 +23,15 @@ to encourage users to stay up-to-date with the latest release, and we have no co We appreciate the efforts of security researchers and the community in identifying and reporting vulnerabilities. To ensure that potential vulnerabilities are addressed properly, please follow these guidelines: -1. **Contact members of the team directly** over E2EE private message. +1. **Contact _all_ members of the team** over E2EE private message on Matrix. + Add each contact to the same encrypted room. **Do not message maintainers individually**. + If you cannot reach us from matrix.org, please try [another server][sl] (e.g. continuwuity.rocks). - [@jade:ellis.link](https://matrix.to/#/@jade:ellis.link) - [@nex:nexy7574.co.uk](https://matrix.to/#/@nex:nexy7574.co.uk) - [@ginger:gingershaped.computer](https://matrix.to/#/@ginger:gingershaped.computer) 2. **Email the security team** at [security@continuwuity.org](mailto:security@continuwuity.org). This is not E2EE, so - don't include sensitive details. + don't include sensitive details. Do not ask where to send sensitive details either; that + information is included in this security policy. We may not respond to emails that do this. 3. **Do not disclose the vulnerability publicly** until a fix has been pushed to the main branch. 4. **Provide detailed information** about the vulnerability, including: - A clear description of the issue @@ -42,6 +45,8 @@ ensure that potential vulnerabilities are addressed properly, please follow thes If you have any doubts about a potential security vulnerability, contact us via private channels first! We'd prefer that you bother us, instead of having a vulnerability disclosed without a fix. +[sl]: https://servers.joinmatrix.org + ### Terms for credit Before reporting a vulnerability, please remember that we are a small team maintaining a large codebase depended upon by @@ -105,4 +110,4 @@ When security vulnerabilities are identified: --- -This security policy was last updated on May 25, 2025. +This security policy was last updated on November 17th, 2026. From ad50b9a3b3824776f35590e13edd5553dec69cec Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 18 Nov 2026 12:37:15 +0000 Subject: [PATCH 237/342] fix(complement): Enable using container builds as a base --- bin/complement | 20 +++++++++++++++++--- docker/complement.Dockerfile | 24 +++++++++++++++++++++--- docs/development/testing.mdx | 14 ++++++++++++++ 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/bin/complement b/bin/complement index 1c4281987..0d5a56e98 100755 --- a/bin/complement +++ b/bin/complement @@ -52,8 +52,10 @@ else fi # The base docker image to use for complement tests -# You can build the default with `docker build -t continuwuity:complement -f ./docker/complement.Dockerfile .` -# after running `cargo build -p conduwuit --features openreg`. Only the debug binary is used. +# On Linux, you can build the default with `docker build -t continuwuity:complement -f ./docker/complement.Dockerfile .` +# after running `cargo build -p conduwuit --features openreg`. +# On non-Linux platforms (or to use a container build), build `docker/Dockerfile` with debuginfo and openreg `--build-arg RUST_PROFILE=dev --build-arg CARGO_FEATURES=default,openreg` +# and then run `docker build -t continuwuity:complement --target container -f ./docker/complement.Dockerfile .`. COMPLEMENT_BASE_IMAGE="${COMPLEMENT_BASE_IMAGE:-continuwuity:complement}" # Complement tests that are skipped due to flakiness/reliability issues or we don't implement such features and won't for a long time @@ -83,6 +85,13 @@ for command in docker go jq; do fi done +if [ -z "${DOCKER_HOST:-}" ]; then + DOCKER_HOST="$(docker context inspect --format '{{.Endpoints.docker.Host}}' 2>/dev/null || true)" + if [ -n "$DOCKER_HOST" ]; then + export DOCKER_HOST + fi +fi + if [ -n "$IMAGE_ARCHIVE" ]; then if [ ! -f "$IMAGE_ARCHIVE" ]; then echo "Docker image archive not found: $IMAGE_ARCHIVE" @@ -99,7 +108,12 @@ fi if ! docker image inspect "$COMPLEMENT_BASE_IMAGE" > /dev/null 2>&1; then echo "Complement base image not found: $COMPLEMENT_BASE_IMAGE" - echo "Build it with: cargo build -p conduwuit --features openreg && docker build -t $COMPLEMENT_BASE_IMAGE -f docker/complement.Dockerfile ." + if [ "$(uname -s)" != "Linux" ]; then + echo "Build it with: docker buildx build --load -t continuwuity:latest-openreg --build-arg RUST_PROFILE=dev --build-arg CARGO_FEATURES=default,openreg -f docker/Dockerfile . && docker build -t $COMPLEMENT_BASE_IMAGE --target container -f docker/complement.Dockerfile ." + else + echo "Build it with: cargo build -p conduwuit --features openreg && docker build -t $COMPLEMENT_BASE_IMAGE -f docker/complement.Dockerfile ." + echo "Or from a container build: docker buildx build --load -t continuwuity:latest-openreg --build-arg RUST_PROFILE=dev --build-arg CARGO_FEATURES=default,openreg -f docker/Dockerfile . && docker build -t $COMPLEMENT_BASE_IMAGE --target container -f docker/complement.Dockerfile ." + fi exit 1 fi diff --git a/docker/complement.Dockerfile b/docker/complement.Dockerfile index 1cef3527d..82dd1a970 100644 --- a/docker/complement.Dockerfile +++ b/docker/complement.Dockerfile @@ -1,11 +1,29 @@ -FROM ubuntu:latest +ARG CONTINUWUITY_IMAGE=continuwuity:latest-openreg +ARG BINARY_SOURCE=host + +FROM ${CONTINUWUITY_IMAGE} AS container-binary + +FROM scratch AS host-binary +ARG BINARY_PATH=target/debug/conduwuit +COPY ${BINARY_PATH} /sbin/conduwuit + +FROM ubuntu:latest AS base EXPOSE 8008 EXPOSE 8448 RUN apt-get update && apt-get install -y ca-certificates liburing2 && rm -rf /var/lib/apt/lists/* RUN mkdir -p /etc/continuwuity /var/lib/continuwuity /usr/local/bin/ COPY complement/complement-entrypoint.sh /usr/local/bin/complement-entrypoint.sh COPY complement/complement.config.toml /etc/continuwuity/config.toml -COPY target/debug/conduwuit /usr/local/bin/conduwuit -RUN chmod +x /usr/local/bin/conduwuit /usr/local/bin/complement-entrypoint.sh +RUN chmod +x /usr/local/bin/complement-entrypoint.sh #HEALTHCHECK --interval=30s --timeout=5s CMD curl --fail http://localhost:8008/_continuwuity/server_version || exit 1 ENTRYPOINT ["/usr/local/bin/complement-entrypoint.sh"] + +FROM base AS container +COPY --from=container-binary /sbin/conduwuit /usr/local/bin/conduwuit +RUN chmod +x /usr/local/bin/conduwuit + +FROM base AS host +COPY --from=host-binary /sbin/conduwuit /usr/local/bin/conduwuit +RUN chmod +x /usr/local/bin/conduwuit + +FROM ${BINARY_SOURCE} diff --git a/docs/development/testing.mdx b/docs/development/testing.mdx index 3e6aa0201..62e9eb1fe 100644 --- a/docs/development/testing.mdx +++ b/docs/development/testing.mdx @@ -20,6 +20,20 @@ docker build -t continuwuity:complement -f docker/complement.Dockerfile . The `openreg` feature is required: without it the server refuses the open registrations Complement uses to create test users, and almost every test fails. +On non-Linux (or to build inside a container instead of on the host), build the Continuwuity image with the `openreg` feature and `RUST_PROFILE=dev` first (open +registration is only enabled when `debug_assertions` are active), then build +the Complement image using the `container` target: + +```bash +docker buildx build --load -t continuwuity:latest-openreg --build-arg RUST_PROFILE=dev --build-arg CARGO_FEATURES=default,openreg -f docker/Dockerfile . +docker build -t continuwuity:complement --target container -f docker/complement.Dockerfile . +./bin/complement +``` + +Pass `--build-arg CONTINUWUITY_IMAGE=your-image:tag` when building +`docker/complement.Dockerfile` if your Continuwuity container image uses a +different tag. + The run can take up to an hour. The runner writes the full Go test stream to `tests/test_results/complement/test_logs.jsonl` and a sorted pass/fail/skip summary to `tests/test_results/complement/test_results.jsonl`. It exits nonzero From cec1f85f8896834546a9a41cfe2d546aad2fe9c7 Mon Sep 17 00:00:00 2001 From: hexchen Date: Mon, 26 Oct 2026 04:11:03 +0000 Subject: [PATCH 238/342] fix: verify_server_keys_response fails on non-standard json fields Previously `verify_server_keys_response` would work with re-serialized ServerSigningKeys, which drops any extra, non-standard fields from the origin server response. The signature is made over the whole response though, meaning that any response including extra fields will not pass signature verification. --- changelog.d/2415.bugfix | 1 + src/api/server/key.rs | 6 ++ src/service/server_keys/request.rs | 37 ++++++---- src/service/server_keys/verify.rs | 111 ++++++++++++++++++++++++----- 4 files changed, 125 insertions(+), 30 deletions(-) create mode 100644 changelog.d/2415.bugfix diff --git a/changelog.d/2415.bugfix b/changelog.d/2415.bugfix new file mode 100644 index 000000000..75fbffad8 --- /dev/null +++ b/changelog.d/2415.bugfix @@ -0,0 +1 @@ +Fix remote server key signature verification when extra fields exist. Contributed by @hexchen diff --git a/src/api/server/key.rs b/src/api/server/key.rs index b547ea15c..757b94111 100644 --- a/src/api/server/key.rs +++ b/src/api/server/key.rs @@ -37,9 +37,15 @@ pub(crate) async fn get_server_keys_route( if resp.valid_until_ts > in_one_week() { continue; } + let raw_resp = Raw::new(&resp)?; let trusted = services.config.trusted_servers.iter().any(|notary| { + // Re-verifying here rejects any key that passes extra, + // non-standard json keys as a part of the ServerSigningKeys + // object. Since these extra json keys are stripped, the + // signature won't validate. server_keys::Service::verify_server_keys_response( &resp, + &raw_resp, Some((notary.server_name(), notary.verify_keys())), ) .is_ok() diff --git a/src/service/server_keys/request.rs b/src/service/server_keys/request.rs index 5a4ce6a10..8eec4448b 100644 --- a/src/service/server_keys/request.rs +++ b/src/service/server_keys/request.rs @@ -11,7 +11,7 @@ use ruma::{ }, get_server_keys, }, - serde::Base64, + serde::{Base64, Raw}, uint, }; @@ -30,13 +30,14 @@ impl super::Service { ) -> Result { use get_server_keys::v2::Request; - let server_signing_key = self + let raw_server_key = self .services .sending .send_unauthenticated_request(&target, Request::new()) .await - .map(|response| response.server_key) - .and_then(|key| key.deserialize().map_err(Into::into))?; + .map(|response| response.server_key)?; + + let server_signing_key = raw_server_key.deserialize()?; if server_signing_key.server_name != target { return Err!(BadServerResponse(debug_warn!( @@ -57,7 +58,9 @@ impl super::Service { ))); } - if let Err(e) = Self::verify_server_keys_response(&server_signing_key, None) { + if let Err(e) = + Self::verify_server_keys_response(&server_signing_key, &raw_server_key, None) + { return Err!(BadServerResponse(debug_warn!( ?target, "Origin server failed to self-sign key response: {e}" @@ -108,20 +111,29 @@ impl super::Service { .await .map(|response| Self::parse_notary_response(&response))? .into_iter() - .filter(|keys| { - Self::validate_notary_chunk(&batch, keys, notary, notary_keys.as_slice()) + .filter(|(keys, raw_keys)| { + Self::validate_notary_chunk( + &batch, + keys, + raw_keys, + notary, + notary_keys.as_slice(), + ) }) + .map(|(keys, _)| keys) .collect(); Ok(keys) } /// Parses a notary response, returning a vec of server signing key - /// responses. Drops any chunks that cannot be deserialized. - fn parse_notary_response(raw: &NotaryResponse) -> Vec { + /// responses, each paired with its raw JSON (which is what the signatures + /// were made over). Drops any chunks that cannot be deserialized. + fn parse_notary_response( + raw: &NotaryResponse, + ) -> Vec<(ServerSigningKeys, Raw)> { raw.server_keys .iter() - .map(ruma::serde::Raw::deserialize) - .filter_map(Result::ok) + .filter_map(|chunk| chunk.deserialize().ok().map(|keys| (keys, chunk.clone()))) .collect() } @@ -130,6 +142,7 @@ impl super::Service { fn validate_notary_chunk( batch: &ServerKeysQuery, keys: &ServerSigningKeys, + raw_keys: &Raw, notary_name: &ServerName, notary_keys: &[Base64], ) -> bool { @@ -182,7 +195,7 @@ impl super::Service { return false; } - Self::verify_server_keys_response(keys, Some((notary_name, notary_keys))) + Self::verify_server_keys_response(keys, raw_keys, Some((notary_name, notary_keys))) .inspect_err(|e| { trace!( ?e, diff --git a/src/service/server_keys/verify.rs b/src/service/server_keys/verify.rs index a9c0c24e4..6432c4351 100644 --- a/src/service/server_keys/verify.rs +++ b/src/service/server_keys/verify.rs @@ -5,7 +5,7 @@ use ruma::{ CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, ServerName, SigningKeyAlgorithm, api::federation::discovery::ServerSigningKeys, room_version_rules::RoomVersionRules, - serde::{Base64, base64::Standard}, + serde::{Base64, Raw, base64::Standard}, signatures::Verified, }; use serde_json::value::RawValue as RawJsonValue; @@ -57,13 +57,23 @@ impl super::Service { /// /// `notary` must either be empty or have ONE entry. Extraneous notaries /// will be ignored. + /// + /// `raw_server_keys` must be the response exactly as received. Signatures + /// cover every field the origin sent, including ones `ServerSigningKeys` + /// does not include, so verifying a re-serialised response would fail. pub fn verify_server_keys_response( server_keys: &ServerSigningKeys, + raw_server_keys: &Raw, notary: Option<(&ServerName, &[Base64])>, ) -> Result<()> { if let Some((notary_name, notary_keys)) = notary { if !notary_keys.is_empty() { - Self::verify_notary_signature(server_keys, notary_name, notary_keys)?; + Self::verify_notary_signature( + server_keys, + raw_server_keys, + notary_name, + notary_keys, + )?; } } @@ -77,7 +87,7 @@ impl super::Service { let mut pubkey_map = ruma::signatures::PublicKeyMap::new(); pubkey_map.insert(server_keys.server_name.to_string(), set); - let mut canonical = to_canonical_object(server_keys)?; + let mut canonical = to_canonical_object(raw_server_keys)?; Self::strip_extraneous_signatures(&mut canonical, &server_keys.server_name, &[]); ruma::signatures::verify_json(&pubkey_map, &canonical).map_err(Into::into) } @@ -86,6 +96,7 @@ impl super::Service { /// the provided signing keys. fn verify_notary_signature( server_keys: &ServerSigningKeys, + raw_server_keys: &Raw, notary_name: &ServerName, notary_keys: &[Base64], ) -> Result<()> { @@ -99,14 +110,11 @@ impl super::Service { "Missing notary server signature from {notary_name}" ))); }; - let mut canonical_object = to_canonical_object(notary_signatures)?; - Self::strip_extraneous_signatures(&mut canonical_object, &server_keys.server_name, &[ - notary_name, - ]); + // The notary signed the response as the origin served it, so verify + // over the raw JSON, not a re-serialised `ServerSigningKeys`. let for_verify = ruma::signatures::to_canonical_json_string_for_signing( - &to_canonical_object(server_keys).expect("server keys object must be canonical json"), - ) - .expect("canonical JSON must be stringable"); + &to_canonical_object(raw_server_keys)?, + )?; let raw_notary_keys = notary_keys.iter().map(Base64::as_bytes).collect::>(); let raw_notary_signatures = notary_signatures @@ -183,8 +191,12 @@ mod tests { } )).map(Raw::from_json).unwrap(); - Service::verify_server_keys_response(&response_data.deserialize().unwrap(), None) - .expect("Self-signature of real key response is valid"); + Service::verify_server_keys_response( + &response_data.deserialize().unwrap(), + &response_data, + None, + ) + .expect("Self-signature of real key response is valid"); } #[test] @@ -210,8 +222,12 @@ mod tests { } )).map(Raw::from_json).unwrap(); - Service::verify_server_keys_response(&response_data.deserialize().unwrap(), None) - .expect("Self-signature of real key response is valid"); + Service::verify_server_keys_response( + &response_data.deserialize().unwrap(), + &response_data, + None, + ) + .expect("Self-signature of real key response is valid"); } #[test] @@ -240,6 +256,7 @@ mod tests { Base64::::parse("Z4oHuEjdUbtC5W/z/gzc5B8raxNk+8gGwbNwgxHqW8Y").unwrap(); Service::verify_server_keys_response( &response_data.deserialize().unwrap(), + &response_data, Some((server_name!("starstruck.systems"), &[starstruck_pubkey])), ) .expect("Server keys from notary are valid"); @@ -266,8 +283,12 @@ mod tests { } } )).map(Raw::from_json).unwrap(); - Service::verify_server_keys_response(&response_data.deserialize().unwrap(), None) - .expect_err("Tampered response should fail self-signature check"); + Service::verify_server_keys_response( + &response_data.deserialize().unwrap(), + &response_data, + None, + ) + .expect_err("Tampered response should fail self-signature check"); } #[test] @@ -304,7 +325,61 @@ mod tests { } } )).map(Raw::from_json).unwrap(); - Service::verify_server_keys_response(&response_data.deserialize().unwrap(), None) - .expect_err("Intercepted notary response should fail strict validation"); + Service::verify_server_keys_response( + &response_data.deserialize().unwrap(), + &response_data, + None, + ) + .expect_err("Intercepted notary response should fail strict validation"); + } + + #[test] + fn verify_response_with_extra_fields() { + let response_data = serde_json::from_value(serde_json::json!( + { + "old_verify_keys": {}, + "server_name": "origin.example", + "signatures": { + "notary.example": { + "ed25519:a_RBdc": "ozlc2T5TlUa9XAsmeam+ESr20573vqFJvYHonj3nG8x+m6v7K5TSlEKTAlTRrJYiC6T/aWB+yxMae6FYR6nqCA" + }, + "origin.example": { + "ed25519:a_jUhC": "+8xKspAfqI8SfrioOVliQ/jCPRDZEuag6JfkN5dXx9gsCX2rSnbvVTJlTJXFiDYUSyIJZg8ilq1QaPsT85ltBA" + } + }, + "tls_fingerprints": [], + "valid_until_ts": 1900000000000_i64, + "verify_keys": { + "ed25519:a_jUhC": { + "key": "idcPtcSpRB5Chnlv1azhL3rMlcTawgQhoGNZWKaNFGI" + } + } + } + )).map(Raw::from_json).unwrap(); + + let notary_pubkey = + Base64::::parse("0ocHGigwa/ap6gSZzzspDQhhOkVkloaf9apolOvwqo8").unwrap(); + + Service::verify_server_keys_response( + &response_data.deserialize().unwrap(), + &response_data, + None, + ) + .expect("Self-signature must verify over the raw response"); + + Service::verify_server_keys_response( + &response_data.deserialize().unwrap(), + &response_data, + Some((server_name!("notary.example"), &[notary_pubkey])), + ) + .expect("Notary signature must verify over the raw response"); + + let reserialised = Raw::new(&response_data.deserialize().unwrap()).unwrap(); + Service::verify_server_keys_response( + &response_data.deserialize().unwrap(), + &reserialised, + None, + ) + .expect_err("Re-serialisation must not verify"); } } From 8ffa3e53672726d1637d672a42d6172b32afb4c4 Mon Sep 17 00:00:00 2001 From: timedout Date: Wed, 11 Nov 2026 08:25:24 +0000 Subject: [PATCH 239/342] fix: Wrap parsed & raw values Rather than passing them around separately everywhere, just unify them into a single struct that is primarily fetched via a raw. Also stores raw data directly into the database so that signatures can be verified later rather than only at receive time. --- src/admin/federation/commands.rs | 4 +- src/api/server/key.rs | 12 +-- src/service/server_keys/get.rs | 18 ++--- src/service/server_keys/mod.rs | 20 +++-- src/service/server_keys/request.rs | 75 ++++++++--------- src/service/server_keys/verify.rs | 126 +++++++++++++---------------- 6 files changed, 119 insertions(+), 136 deletions(-) diff --git a/src/admin/federation/commands.rs b/src/admin/federation/commands.rs index 966c7bdcf..a4fbbabe0 100644 --- a/src/admin/federation/commands.rs +++ b/src/admin/federation/commands.rs @@ -142,11 +142,11 @@ impl crate::Context<'_> { .await?; self.write_str("| ------ | ---------- | --------------------------- |\n") .await?; - for (key_id, key) in &response.verify_keys { + for (key_id, key) in &response.parsed.verify_keys { self.write_str(&format!("| {key_id} | {} | |\n", key.key)) .await?; } - for (key_id, old_key) in &response.old_verify_keys { + for (key_id, old_key) in &response.parsed.old_verify_keys { self.write_str(&format!( "| {key_id} | {} | {:0<13} |\n", old_key.key, diff --git a/src/api/server/key.rs b/src/api/server/key.rs index 757b94111..aa24d8926 100644 --- a/src/api/server/key.rs +++ b/src/api/server/key.rs @@ -34,18 +34,12 @@ pub(crate) async fn get_server_keys_route( // We need to verify that this response is still trusted based on // the current configuration. It's possible we got this response // from a notary who we no longer trust. - if resp.valid_until_ts > in_one_week() { + if resp.parsed.valid_until_ts > in_one_week() { continue; } - let raw_resp = Raw::new(&resp)?; let trusted = services.config.trusted_servers.iter().any(|notary| { - // Re-verifying here rejects any key that passes extra, - // non-standard json keys as a part of the ServerSigningKeys - // object. Since these extra json keys are stripped, the - // signature won't validate. server_keys::Service::verify_server_keys_response( &resp, - &raw_resp, Some((notary.server_name(), notary.verify_keys())), ) .is_ok() @@ -53,8 +47,8 @@ pub(crate) async fn get_server_keys_route( if !trusted { continue; } - for (old_key_id, old_key) in resp.old_verify_keys { - if old_key.expired_ts > resp.valid_until_ts { + for (old_key_id, old_key) in resp.parsed.old_verify_keys { + if old_key.expired_ts > resp.parsed.valid_until_ts { // This key expired in the future which is probably illegal continue; } diff --git a/src/service/server_keys/get.rs b/src/service/server_keys/get.rs index 5011171c4..a94213c44 100644 --- a/src/service/server_keys/get.rs +++ b/src/service/server_keys/get.rs @@ -241,9 +241,9 @@ impl super::Service { continue; } }; - trace!(?origin_response, "Got signing key response from origin"); + trace!(?origin_response.raw, "Got signing key response from origin"); self.add_signing_keys(&origin_response); - Self::track_result(&mut result, &mut still_missing, &origin_response); + Self::track_result(&mut result, &mut still_missing, &origin_response.parsed); if still_missing.is_empty() { break; } @@ -262,9 +262,9 @@ impl super::Service { "Got signing keys response from a notary" ); for server_keys in notary_response { - trace!(?server_keys, "Adding response from notary"); + trace!(?server_keys.raw, "Adding response from notary"); self.add_signing_keys(&server_keys); - Self::track_result(&mut result, &mut still_missing, &server_keys); + Self::track_result(&mut result, &mut still_missing, &server_keys.parsed); if still_missing.is_empty() { break; } @@ -285,9 +285,9 @@ impl super::Service { continue; }; for server_keys in res { - trace!(?server_keys, "Adding response from notary"); + trace!(?server_keys.raw, "Adding response from notary"); self.add_signing_keys(&server_keys); - Self::track_result(&mut result, &mut still_missing, &server_keys); + Self::track_result(&mut result, &mut still_missing, &server_keys.parsed); } if still_missing.is_empty() { break; @@ -300,9 +300,9 @@ impl super::Service { debug_warn!(err=?res.err(), "Got error response from origin"); continue; }; - trace!(response=?res, "Got signing key response from origin"); + trace!(response=?res.raw, "Got signing key response from origin"); self.add_signing_keys(&res); - Self::track_result(&mut result, &mut still_missing, &res); + Self::track_result(&mut result, &mut still_missing, &res.parsed); if still_missing.is_empty() { break; } @@ -400,7 +400,7 @@ impl super::Service { .inspect_err(|e| info!("Could not acquire signing key from origin server: {e:?}")) .ok()?; - verify_key_from_response(key_id, &response, min_valid_ts) + verify_key_from_response(key_id, &response.parsed, min_valid_ts) .inspect(|_| self.add_signing_keys(&response)) } } diff --git a/src/service/server_keys/mod.rs b/src/service/server_keys/mod.rs index ae1352d2b..9b6cc53d8 100644 --- a/src/service/server_keys/mod.rs +++ b/src/service/server_keys/mod.rs @@ -19,8 +19,10 @@ use ruma::{ ServerSigningKeyId, api::federation::discovery::{ServerSigningKeys, VerifyKey}, room_version_rules::RoomVersionRules, + serde::Raw, signatures::{Ed25519KeyPair, PublicKeyMap, PublicKeySet}, }; +use verify::IncomingServerKeys; use crate::{Dep, globals, sending, server_keys::util::required_keys}; @@ -83,19 +85,22 @@ impl Service { } /// Adds a signing key response to the database. - fn add_signing_keys(&self, new_keys: &ServerSigningKeys) { + fn add_signing_keys(&self, new_keys: &IncomingServerKeys) { // TODO(nex): this results in massive amounts of data duplication. // Perhaps a sliding approach would be better? where we just update the // last known response if the only thing that changed was the // valid_until_ts. This would require a more complex data structure // though. For now, just storing the duplicated data is fine. for key in new_keys + .parsed .verify_keys .keys() - .chain(new_keys.old_verify_keys.keys()) + .chain(new_keys.parsed.old_verify_keys.keys()) { - let db_key = (new_keys.server_name.as_str(), key.as_str()); - self.db.servernamekeyid_response.put(db_key, Json(new_keys)); + let db_key = (new_keys.parsed.server_name.as_str(), key.as_str()); + self.db + .servernamekeyid_response + .put(db_key, Json(&new_keys.raw)); } } @@ -170,7 +175,7 @@ impl Service { let mut keys = self .signing_keys_for(origin) .ready_fold(BTreeMap::new(), |mut base, keys| { - base.extend(keys.verify_keys); + base.extend(keys.parsed.verify_keys); base }) .await; @@ -186,11 +191,12 @@ impl Service { pub fn signing_keys_for<'a>( &'a self, origin: &'a ServerName, - ) -> impl Stream + Send + 'a { + ) -> impl Stream + Send + 'a { self.db .servernamekeyid_response .stream_prefix(&(origin, Interfix)) .ignore_err() - .map(|(_, v): (Ignore, ServerSigningKeys)| v) + .map(|(_, v): (Ignore, Raw)| v.try_into().map_err(Into::into)) + .ignore_err() } } diff --git a/src/service/server_keys/request.rs b/src/service/server_keys/request.rs index 8eec4448b..e3f03562a 100644 --- a/src/service/server_keys/request.rs +++ b/src/service/server_keys/request.rs @@ -4,17 +4,18 @@ use conduwuit::{Err, Result, trace, utils::millis_since_unix_epoch, warn}; use ruma::{ MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId, ServerName, UInt, api::federation::discovery::{ - ServerSigningKeys, get_remote_server_keys_batch::{ self, v2::{QueryCriteria, Response as NotaryResponse}, }, get_server_keys, }, - serde::{Base64, Raw}, + serde::Base64, uint, }; +use crate::server_keys::verify::IncomingServerKeys; + pub(crate) type ServerKeysQuery = BTreeMap; pub(crate) type ServerKeysQuerySet = BTreeMap; @@ -27,7 +28,7 @@ impl super::Service { &self, target: OwnedServerName, min_valid_ts: MilliSecondsSinceUnixEpoch, - ) -> Result { + ) -> Result { use get_server_keys::v2::Request; let raw_server_key = self @@ -37,30 +38,28 @@ impl super::Service { .await .map(|response| response.server_key)?; - let server_signing_key = raw_server_key.deserialize()?; + let server_signing_key: IncomingServerKeys = raw_server_key.try_into()?; - if server_signing_key.server_name != target { + if server_signing_key.parsed.server_name != target { return Err!(BadServerResponse(debug_warn!( requested = ?target, - response = ?server_signing_key.server_name, + response = ?server_signing_key.parsed.server_name, "Origin server responded with bogus server_name" ))); } - if server_signing_key.valid_until_ts < min_valid_ts - || server_signing_key.valid_until_ts > in_one_week() + if server_signing_key.parsed.valid_until_ts < min_valid_ts + || server_signing_key.parsed.valid_until_ts > in_one_week() { return Err!(BadServerResponse(debug_warn!( ?target, ?min_valid_ts, - ?server_signing_key.valid_until_ts, + ?server_signing_key.parsed.valid_until_ts, "Origin server responded with server keys that are not in-date" ))); } - if let Err(e) = - Self::verify_server_keys_response(&server_signing_key, &raw_server_key, None) - { + if let Err(e) = Self::verify_server_keys_response(&server_signing_key, None) { return Err!(BadServerResponse(debug_warn!( ?target, "Origin server failed to self-sign key response: {e}" @@ -86,7 +85,7 @@ impl super::Service { &self, notary: &ServerName, batch: ServerKeysQuery, - ) -> Result> { + ) -> Result> { use get_remote_server_keys_batch::v2::Request; let is_empty = batch.is_empty() || batch.values().all(BTreeMap::is_empty); @@ -111,16 +110,9 @@ impl super::Service { .await .map(|response| Self::parse_notary_response(&response))? .into_iter() - .filter(|(keys, raw_keys)| { - Self::validate_notary_chunk( - &batch, - keys, - raw_keys, - notary, - notary_keys.as_slice(), - ) + .filter(|keys| { + Self::validate_notary_chunk(&batch, keys, notary, notary_keys.as_slice()) }) - .map(|(keys, _)| keys) .collect(); Ok(keys) } @@ -128,12 +120,10 @@ impl super::Service { /// Parses a notary response, returning a vec of server signing key /// responses, each paired with its raw JSON (which is what the signatures /// were made over). Drops any chunks that cannot be deserialized. - fn parse_notary_response( - raw: &NotaryResponse, - ) -> Vec<(ServerSigningKeys, Raw)> { + fn parse_notary_response(raw: &NotaryResponse) -> Vec { raw.server_keys .iter() - .filter_map(|chunk| chunk.deserialize().ok().map(|keys| (keys, chunk.clone()))) + .filter_map(|chunk| chunk.try_into().ok()) .collect() } @@ -141,13 +131,15 @@ impl super::Service { /// if the response should be dropped, true if it should be kept. fn validate_notary_chunk( batch: &ServerKeysQuery, - keys: &ServerSigningKeys, - raw_keys: &Raw, + incoming: &IncomingServerKeys, notary_name: &ServerName, notary_keys: &[Base64], ) -> bool { - let Some(expected_keys) = batch.get(&keys.server_name) else { - trace!("Dropping signing keys chunk for unrequested server: {}", keys.server_name); + let Some(expected_keys) = batch.get(&incoming.parsed.server_name) else { + trace!( + "Dropping signing keys chunk for unrequested server: {}", + incoming.parsed.server_name + ); return false; }; let min_valid_ts = expected_keys @@ -161,13 +153,15 @@ impl super::Service { // If this notary response is older than any of the min_valid_ts we // requested, then we should drop it. - if keys.valid_until_ts < min_valid_ts || keys.valid_until_ts > in_one_week() { + if incoming.parsed.valid_until_ts < min_valid_ts + || incoming.parsed.valid_until_ts > in_one_week() + { trace!( ?min_valid_ts, - ?keys.valid_until_ts, + ?incoming.parsed.valid_until_ts, "Dropping signing keys chunk for server {} because it is older than the minimum \ valid timestamp we requested", - keys.server_name + incoming.parsed.server_name ); return false; } @@ -175,38 +169,39 @@ impl super::Service { // Does this chunk even contain any keys we asked for? // Note that this enforces min_valid_ts per-key, instead of using the // lowest denominator. - let all_key_ids = keys + let all_key_ids = incoming + .parsed .verify_keys .keys() - .chain(keys.old_verify_keys.keys()) + .chain(incoming.parsed.old_verify_keys.keys()) .map(ToOwned::to_owned) .collect::>(); let interesting = expected_keys.iter().any(|(k, q)| { all_key_ids.contains(k) && q.minimum_valid_until_ts - .is_none_or(|m| m <= keys.valid_until_ts) + .is_none_or(|m| m <= incoming.parsed.valid_until_ts) }); if !interesting { trace!( "Dropping signing keys chunk for server {} because it does not contain any keys \ we requested", - keys.server_name + incoming.parsed.server_name ); return false; } - Self::verify_server_keys_response(keys, raw_keys, Some((notary_name, notary_keys))) + Self::verify_server_keys_response(incoming, Some((notary_name, notary_keys))) .inspect_err(|e| { trace!( ?e, - ?keys, + ?incoming.raw, ?notary_name, ?notary_keys, "Dropping illegal server signing keys response chunk" ); warn!( %notary_name, - server_name=%keys.server_name, + server_name=%incoming.parsed.server_name, "Dropping illegal server signing keys response chunk: {e:?}" ); }) diff --git a/src/service/server_keys/verify.rs b/src/service/server_keys/verify.rs index 6432c4351..963715c55 100644 --- a/src/service/server_keys/verify.rs +++ b/src/service/server_keys/verify.rs @@ -10,6 +10,31 @@ use ruma::{ }; use serde_json::value::RawValue as RawJsonValue; +pub struct IncomingServerKeys { + pub raw: Raw, + pub parsed: ServerSigningKeys, +} + +impl TryFrom> for IncomingServerKeys { + type Error = serde_json::Error; + + fn try_from(value: Raw) -> std::result::Result { + value + .deserialize() + .map(|parsed| Self { raw: value, parsed }) + } +} + +impl TryFrom<&Raw> for IncomingServerKeys { + type Error = serde_json::Error; + + fn try_from(value: &Raw) -> std::result::Result { + value + .deserialize() + .map(|parsed| Self { raw: value.to_owned(), parsed }) + } +} + impl super::Service { /// Validates the incoming event only using locally known verification keys. /// Inserts the calculated event ID into the event_id field upon success. @@ -57,46 +82,39 @@ impl super::Service { /// /// `notary` must either be empty or have ONE entry. Extraneous notaries /// will be ignored. - /// - /// `raw_server_keys` must be the response exactly as received. Signatures - /// cover every field the origin sent, including ones `ServerSigningKeys` - /// does not include, so verifying a re-serialised response would fail. pub fn verify_server_keys_response( - server_keys: &ServerSigningKeys, - raw_server_keys: &Raw, + incoming: &IncomingServerKeys, notary: Option<(&ServerName, &[Base64])>, ) -> Result<()> { if let Some((notary_name, notary_keys)) = notary { if !notary_keys.is_empty() { - Self::verify_notary_signature( - server_keys, - raw_server_keys, - notary_name, - notary_keys, - )?; + Self::verify_notary_signature(incoming, notary_name, notary_keys)?; } } // NOTE: old_verify_keys aren't considered here because old keys can't // be used to sign key responses. let mut set = ruma::signatures::PublicKeySet::new(); - server_keys.verify_keys.iter().for_each(|(key_id, key)| { - set.insert(key_id.to_string(), key.key.clone()); - }); + incoming + .parsed + .verify_keys + .iter() + .for_each(|(key_id, key)| { + set.insert(key_id.to_string(), key.key.clone()); + }); let mut pubkey_map = ruma::signatures::PublicKeyMap::new(); - pubkey_map.insert(server_keys.server_name.to_string(), set); + pubkey_map.insert(incoming.parsed.server_name.to_string(), set); - let mut canonical = to_canonical_object(raw_server_keys)?; - Self::strip_extraneous_signatures(&mut canonical, &server_keys.server_name, &[]); + let mut canonical = to_canonical_object(&incoming.raw)?; + Self::strip_extraneous_signatures(&mut canonical, &incoming.parsed.server_name, &[]); ruma::signatures::verify_json(&pubkey_map, &canonical).map_err(Into::into) } /// Verifies that the notary has at least one valid signature present with /// the provided signing keys. fn verify_notary_signature( - server_keys: &ServerSigningKeys, - raw_server_keys: &Raw, + incoming: &IncomingServerKeys, notary_name: &ServerName, notary_keys: &[Base64], ) -> Result<()> { @@ -105,7 +123,7 @@ impl super::Service { // certificate has been compromised, which would otherwise allow // them to produce attacker-controlled signing keys with valid // self-signatures. - let Some(notary_signatures) = server_keys.signatures.get(notary_name) else { + let Some(notary_signatures) = incoming.parsed.signatures.get(notary_name) else { return Err!(Request(Forbidden( "Missing notary server signature from {notary_name}" ))); @@ -113,7 +131,7 @@ impl super::Service { // The notary signed the response as the origin served it, so verify // over the raw JSON, not a re-serialised `ServerSigningKeys`. let for_verify = ruma::signatures::to_canonical_json_string_for_signing( - &to_canonical_object(raw_server_keys)?, + &to_canonical_object(&incoming.raw)?, )?; let raw_notary_keys = notary_keys.iter().map(Base64::as_bytes).collect::>(); @@ -134,7 +152,7 @@ impl super::Service { trace!( "Valid signature from {notary_name} present on signing keys response \ for {}", - server_keys.server_name + incoming.parsed.server_name ); return Ok(()); } @@ -189,14 +207,10 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); + )).map(Raw::from_json).unwrap().try_into().unwrap(); - Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), - &response_data, - None, - ) - .expect("Self-signature of real key response is valid"); + Service::verify_server_keys_response(&response_data, None) + .expect("Self-signature of real key response is valid"); } #[test] @@ -220,14 +234,10 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); + )).map(Raw::from_json).unwrap().try_into().unwrap(); - Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), - &response_data, - None, - ) - .expect("Self-signature of real key response is valid"); + Service::verify_server_keys_response(&response_data, None) + .expect("Self-signature of real key response is valid"); } #[test] @@ -251,11 +261,10 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); + )).map(Raw::from_json).unwrap().try_into().unwrap(); let starstruck_pubkey = Base64::::parse("Z4oHuEjdUbtC5W/z/gzc5B8raxNk+8gGwbNwgxHqW8Y").unwrap(); Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), &response_data, Some((server_name!("starstruck.systems"), &[starstruck_pubkey])), ) @@ -282,13 +291,9 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); - Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), - &response_data, - None, - ) - .expect_err("Tampered response should fail self-signature check"); + )).map(Raw::from_json).unwrap().try_into().unwrap(); + Service::verify_server_keys_response(&response_data, None) + .expect_err("Tampered response should fail self-signature check"); } #[test] @@ -324,13 +329,9 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); - Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), - &response_data, - None, - ) - .expect_err("Intercepted notary response should fail strict validation"); + )).map(Raw::from_json).unwrap().try_into().unwrap(); + Service::verify_server_keys_response(&response_data, None) + .expect_err("Intercepted notary response should fail strict validation"); } #[test] @@ -355,31 +356,18 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); + )).map(Raw::from_json).unwrap().try_into().unwrap(); let notary_pubkey = Base64::::parse("0ocHGigwa/ap6gSZzzspDQhhOkVkloaf9apolOvwqo8").unwrap(); - Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), - &response_data, - None, - ) - .expect("Self-signature must verify over the raw response"); + Service::verify_server_keys_response(&response_data, None) + .expect("Self-signature must verify over the raw response"); Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), &response_data, Some((server_name!("notary.example"), &[notary_pubkey])), ) .expect("Notary signature must verify over the raw response"); - - let reserialised = Raw::new(&response_data.deserialize().unwrap()).unwrap(); - Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), - &reserialised, - None, - ) - .expect_err("Re-serialisation must not verify"); } } From 06c63e8de3cd2d7a9c1ca2a02716e3c0a908fb24 Mon Sep 17 00:00:00 2001 From: Silversys Date: Wed, 18 Nov 2026 20:03:21 +0100 Subject: [PATCH 240/342] chore: Update resolvematrix to 1.5.0 --- Cargo.lock | 11 +++++++++-- Cargo.toml | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6cab04b2c..e39a51a8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -624,6 +624,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "cache_control" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf2a5fb3207c12b5d208ebc145f967fea5cac41a021c37417ccc31ba40f39ee" + [[package]] name = "camino" version = "1.2.6" @@ -4898,10 +4904,11 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" [[package]] name = "resolvematrix" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6e659fe17ed82acfac43641d00d1bbfd0a9d53ec4d2f901b01f792f0e2c9e3c" +checksum = "39a1efc3c55274528f8b1a916eb0edf5c40a8364b4899fbc1283a57c8d0024db" dependencies = [ + "cache_control", "hickory-resolver", "num-traits", "parking_lot", diff --git a/Cargo.toml b/Cargo.toml index 83d70b227..e730e8cdd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -603,7 +603,7 @@ features = ["std"] version = "0.3.0" [workspace.dependencies.resolvematrix] -version = "1.4.2" +version = "1.5.0" features = ["unstable-msc4188"] [workspace.dependencies.serde_urlencoded] From 9bdbaf3300d469a20eac50407330e54e0f5647c3 Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 12:23:05 +0000 Subject: [PATCH 241/342] fix: Actually config-gate MSC4155 support --- src/service/users/account.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/service/users/account.rs b/src/service/users/account.rs index 9fc78d339..3c5f1486c 100644 --- a/src/service/users/account.rs +++ b/src/service/users/account.rs @@ -4,7 +4,9 @@ use std::{ }; use conduwuit::{ - Err, Result, debug, debug_error, debug_warn, err, error, info, trace, + Err, Result, + config::experiments::ToggledExperiment, + debug, debug_error, debug_warn, err, error, info, trace, utils::{self, stream::TryIgnore}, warn, }; @@ -107,6 +109,27 @@ impl super::Service { if stable.is_err() && unstable.is_err() { return FilterLevel::Default; } + let msc4494_enabled = self.services.config.experiments.msc4494.is_enabled(); + if !self.services.config.experiments.msc4155.is_enabled() { + // Only MSC4380 should be checked here, since it's in spec. + let Some(action) = stable.ok().and_then(|c| c.content.default_action) else { + return FilterLevel::Default; + }; + return match action { + | InvitePermissionAction::Block => FilterLevel::Block, + | InvitePermissionAction::DenyPublic if msc4494_enabled => { + if !self + .check_msc4494_mutual_room(sender_user, recipient_user) + .await + { + FilterLevel::Block + } else { + FilterLevel::Default + } + }, + | _ => FilterLevel::Allow, + }; + } let content = stable.unwrap_or_else(|_| unstable.unwrap()).content; let verdict = content.user_filter_level(sender_user); if verdict != FilterLevel::Default { @@ -114,7 +137,8 @@ impl super::Service { } // Apply other layers of invite blocking first, so that user/server // denies take priority over implicit allows. - if content.default_action == Some(InvitePermissionAction::DenyPublic) + if msc4494_enabled + && content.default_action == Some(InvitePermissionAction::DenyPublic) && !self .check_msc4494_mutual_room(sender_user, recipient_user) .await From f3cbfed7214c484e715eaf41701dd9293d90bfe4 Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 12:48:05 +0000 Subject: [PATCH 242/342] fix: Actually config-gate MSC4174 support --- src/service/pusher/mod.rs | 14 +++++++++----- src/service/pusher/webpush/mod.rs | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/service/pusher/mod.rs b/src/service/pusher/mod.rs index 778457f42..a7af1364c 100644 --- a/src/service/pusher/mod.rs +++ b/src/service/pusher/mod.rs @@ -3,7 +3,7 @@ mod webpush; use std::{fmt::Debug, mem, net::IpAddr, sync::Arc}; use bytes::BytesMut; -use conduwuit::utils::response::LimitReadExt; +use conduwuit::{config::experiments::ToggledExperiment, utils::response::LimitReadExt}; use conduwuit_core::{ Err, Event, Result, Server, debug_warn, err, trace, utils::{stream::TryIgnore, string_from_bytes}, @@ -133,7 +133,9 @@ impl Service { self.validate_push_url(&http.url, PUSH_GATEWAY_SCHEMES) .await?; }, - | PusherKind::WebPush(data) => { + | PusherKind::WebPush(data) + if self.services.config.experiments.msc4174.is_enabled() => + { self.validate_push_url(&data.url, WEBPUSH_SCHEMES).await?; webpush::decode_pushkey(pushkey)?; webpush::decode_auth(&data.auth)?; @@ -147,7 +149,7 @@ impl Service { } } }, - | PusherKind::Email(_) | PusherKind::Custom { .. } => (), + | _ => (), } let key = (sender, pushkey); @@ -547,7 +549,9 @@ impl Service { Ok(()) }, - | PusherKind::WebPush(data) => { + | PusherKind::WebPush(data) + if self.services.config.experiments.msc4174.is_enabled() => + { let notify = self .build_notification( user, @@ -562,7 +566,7 @@ impl Service { self.send_webpush_notice(user, pusher, data, notify).await }, - | PusherKind::Email(_) | PusherKind::Custom { .. } => Ok(()), + | _ => Ok(()), } } diff --git a/src/service/pusher/webpush/mod.rs b/src/service/pusher/webpush/mod.rs index 2a428d539..e8f9572ae 100644 --- a/src/service/pusher/webpush/mod.rs +++ b/src/service/pusher/webpush/mod.rs @@ -3,6 +3,7 @@ mod vapid; use std::time::{Duration, SystemTime}; +use conduwuit::config::experiments::ToggledExperiment; use conduwuit_core::{ Err, Result, debug, debug_warn, err, utils::{self, string::constant_time_eq}, @@ -85,6 +86,9 @@ impl Service { /// Reports whether a Web Push pusher has completed its activation /// handshake. pub async fn is_webpush_activated(&self, sender: &UserId, pushkey: &str) -> bool { + if !self.services.config.experiments.msc4174.is_enabled() { + return false; + } self.webpush_state(sender, pushkey).await.activated } @@ -109,6 +113,9 @@ impl Service { pusher: &Pusher, previous: Option<&Pusher>, ) -> bool { + if !self.services.config.experiments.msc4174.is_enabled() { + return false; + } let Some(data) = pusher.kind.as_webpush() else { return false; }; @@ -126,6 +133,13 @@ impl Service { } pub(super) fn begin_webpush_activation(&self, sender: &UserId, pusher: &Pusher) { + debug_assert!( + self.services.config.experiments.msc4174.is_enabled(), + "begin_webpush_activation should not be called with MSC4174 disabled" + ); + if !self.services.config.experiments.msc4174.is_enabled() { + return; + } // Send a one-time encrypted token before allowing notification // delivery. let token = utils::rand::string(ACK_TOKEN_LENGTH); From cebeee6baeda7a629b42664bfbf35228a95de332 Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 13:16:21 +0000 Subject: [PATCH 243/342] fix: Actually config-gate MSC4484 support --- src/api/client/capabilities.rs | 9 ++++++--- src/api/router/auth.rs | 8 ++++++-- src/service/oauth/grant.rs | 4 ++-- src/service/oauth/mod.rs | 11 ++++++++--- src/web/pages/oauth/grant.rs | 7 +++++-- 5 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/api/client/capabilities.rs b/src/api/client/capabilities.rs index d5d6e9f56..1c7d6f512 100644 --- a/src/api/client/capabilities.rs +++ b/src/api/client/capabilities.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, BTreeSet}; use axum::extract::State; -use conduwuit::{Result, Server}; +use conduwuit::{Result, Server, config::experiments::ToggledExperiment}; use ruma::{ RoomVersionId, api::{ @@ -53,8 +53,11 @@ pub(crate) async fn get_capabilities_route( capabilities.account_moderation.lock = true; capabilities.account_moderation.suspend = true; - capabilities.admin = - AdminCapability::new(BTreeSet::from_iter([OAuthClientScope::ServerAdministration])); + if services.config.experiments.msc4484.is_enabled() { + capabilities.admin = AdminCapability::new(BTreeSet::from_iter([ + OAuthClientScope::ServerAdministration, + ])); + } } capabilities.profile_fields = Some( diff --git a/src/api/router/auth.rs b/src/api/router/auth.rs index 543910cba..6d666bebb 100644 --- a/src/api/router/auth.rs +++ b/src/api/router/auth.rs @@ -5,7 +5,9 @@ use std::{ }; use conduwuit::{ - Err, Error, Result, err, + Err, Error, Result, + config::experiments::ToggledExperiment, + err, utils::{IterStream, millis_since_unix_epoch}, }; use http::StatusCode; @@ -343,7 +345,9 @@ async fn check_access_token( } else { let mut scopes = BTreeSet::from_iter([OAuthClientScope::ApiFullAccess]); - if services.admin.user_is_admin(&sender_user).await { + if services.config.experiments.msc4484.is_enabled() + && services.admin.user_is_admin(&sender_user).await + { scopes.insert(OAuthClientScope::ServerAdministration); } diff --git a/src/service/oauth/grant.rs b/src/service/oauth/grant.rs index 1eccc8f98..806409213 100644 --- a/src/service/oauth/grant.rs +++ b/src/service/oauth/grant.rs @@ -107,7 +107,7 @@ pub struct RawScopes(String); impl RawScopes { #[allow(clippy::trivial_regex)] - pub fn to_scopes(&self) -> Result { + pub fn to_scopes(&self, msc4484: bool) -> Result { let client_api_token_regex = regex!(r"urn:matrix:(client|org.matrix.msc2967.client):api:\*"); let device_token_regex = @@ -121,7 +121,7 @@ impl RawScopes { let scope_was_new = { if client_api_token_regex.is_match(token) { scopes.scopes.insert(OAuthClientScope::ApiFullAccess) - } else if server_administration_regex.is_match(token) { + } else if msc4484 && server_administration_regex.is_match(token) { scopes.scopes.insert(OAuthClientScope::ServerAdministration) } else if let Some(captures) = device_token_regex.captures(token) { scopes diff --git a/src/service/oauth/mod.rs b/src/service/oauth/mod.rs index bddad5f76..adf7111a9 100644 --- a/src/service/oauth/mod.rs +++ b/src/service/oauth/mod.rs @@ -6,7 +6,9 @@ use std::{ use base64::Engine; use conduwuit::{ - Result, SyncMutex, info, + Result, SyncMutex, + config::experiments::ToggledExperiment, + info, utils::{self, hash::sha256}, }; use database::{Deserialized, Json, Map}; @@ -284,7 +286,9 @@ impl Service { } } - let requested_scopes = query.scope.to_scopes()?; + let requested_scopes = query + .scope + .to_scopes(self.services.config.experiments.msc4484.is_enabled())?; let redirect_uri_query_separator = match query.response_mode { | ResponseMode::Fragment => '#', @@ -343,7 +347,7 @@ impl Service { let requested_scopes = query .scope - .to_scopes() + .to_scopes(self.services.config.experiments.msc4484.is_enabled()) .map_err(|err| OAuthError::new(ErrorCode::InvalidGrant, err))?; let device_code = Self::generate_token(); @@ -762,6 +766,7 @@ impl Service { scopes: &BTreeSet, ) -> Result<(), OAuthError> { if scopes.contains(&OAuthClientScope::ServerAdministration) + && self.services.config.experiments.msc4484.is_enabled() && !self.services.admin.user_is_admin(authorizing_user).await { return Err(OAuthError::new( diff --git a/src/web/pages/oauth/grant.rs b/src/web/pages/oauth/grant.rs index 1cb268102..c815cda6e 100644 --- a/src/web/pages/oauth/grant.rs +++ b/src/web/pages/oauth/grant.rs @@ -4,6 +4,7 @@ use axum::{ response::Redirect, routing::on, }; +use conduwuit_core::config::experiments::ToggledExperiment; use conduwuit_service::oauth::{ SessionInfo, client_metadata::ClientMetadata, @@ -104,8 +105,10 @@ async fn route_authorization_code( return Err(WebError::BadRequest("Invalid client ID".to_owned())); }; - let RequestedScopes { device_id, mut scopes } = - query.scope.to_scopes().map_err(WebError::BadRequest)?; + let RequestedScopes { device_id, mut scopes } = query + .scope + .to_scopes(services.config.experiments.msc4484.is_enabled()) + .map_err(WebError::BadRequest)?; let existing_session_info = if let Some(device_id) = &device_id { services From 4e7493604aacd41159fae19918c79d40b2516183 Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 13:46:25 +0000 Subject: [PATCH 244/342] fix: Actually config-gate MSC4560 support --- src/api/router.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/api/router.rs b/src/api/router.rs index f2e8f9730..e8b24cfca 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -10,7 +10,7 @@ use axum::{ response::{IntoResponse, Redirect}, routing::{any, get}, }; -use conduwuit::err; +use conduwuit::{config::experiments::ToggledExperiment, err}; pub(super) use conduwuit_service::state::State; use http::{Uri, uri}; @@ -184,7 +184,6 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&client::get_mutual_rooms_unstable_route) .ruma_route(&client::get_mutual_rooms_route) .ruma_route(&client::get_room_summary) - .ruma_route(&client::get_stripped_state_route) .ruma_route(&client::get_suspended_status) .ruma_route(&client::put_suspended_status) .ruma_route(&client::get_lock_status) @@ -199,6 +198,9 @@ pub fn build(router: Router, state: State) -> Router { .route("/_continuwuity/server_version", get(client::continuwuity_server_version)) .ruma_route(&admin::rooms::ban::ban_room) .ruma_route(&admin::rooms::list::list_rooms); + if config.experiments.msc4560.is_enabled() { + router = router.ruma_route(&client::get_stripped_state_route); + } if config.allow_prometheus_metrics { router = router.route("/_continuwuity/metrics", get(client::continuwuity_metrics)); @@ -230,11 +232,13 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&server::get_keys_route) .ruma_route(&server::claim_keys_route) .ruma_route(&server::get_hierarchy_route) - .ruma_route(&server::get_stripped_state_route) .ruma_route(&server::well_known_server) .ruma_route(&server::get_content_route) .ruma_route(&server::get_content_thumbnail_route) .route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count)); + if config.experiments.msc4560.is_enabled() { + router = router.ruma_route(&server::get_stripped_state_route); + } } else { router = router .route("/_matrix/federation/{*path}", any(federation_disabled)) From 94ba3b2b836d23f0389e042aca4a679b6b85ef1d Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 14:00:09 +0000 Subject: [PATCH 245/342] fix: Add an experiment for MSC3814 This proposal is still itself a draft, not even ready for review, so we definitely shouldn't enable it by default per the policy. --- src/api/router.rs | 11 +++++++---- src/core/config/experiments.rs | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/api/router.rs b/src/api/router.rs index e8b24cfca..36469eb46 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -162,10 +162,6 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&client::update_device_route) .ruma_route(&client::delete_device_route) .ruma_route(&client::delete_devices_route) - .ruma_route(&client::put_dehydrated_device_route) - .ruma_route(&client::delete_dehydrated_device_route) - .ruma_route(&client::get_dehydrated_device_route) - .ruma_route(&client::get_dehydrated_events_route) .ruma_route(&client::get_tags_route) .ruma_route(&client::update_tag_route) .ruma_route(&client::delete_tag_route) @@ -198,6 +194,13 @@ pub fn build(router: Router, state: State) -> Router { .route("/_continuwuity/server_version", get(client::continuwuity_server_version)) .ruma_route(&admin::rooms::ban::ban_room) .ruma_route(&admin::rooms::list::list_rooms); + if config.experiments.msc3814.is_enabled() { + router = router + .ruma_route(&client::put_dehydrated_device_route) + .ruma_route(&client::delete_dehydrated_device_route) + .ruma_route(&client::get_dehydrated_device_route) + .ruma_route(&client::get_dehydrated_events_route); + } if config.experiments.msc4560.is_enabled() { router = router.ruma_route(&client::get_stripped_state_route); } diff --git a/src/core/config/experiments.rs b/src/core/config/experiments.rs index c19b19ad0..f647ed889 100644 --- a/src/core/config/experiments.rs +++ b/src/core/config/experiments.rs @@ -24,6 +24,26 @@ pub struct Experiments { /// display: nested #[serde(default)] pub msc2815: Option, + /// MSC3814: Dehydrated devices with SSSS + /// + /// Enables server-side support for "dehydrated devices", which are + /// server-side devices (created by supporting clients) that can collect + /// encryption keys when there are no online devices, which supporting + /// clients can then "hydrate" to download any encryption keys that were + /// sent while they were offline. + /// + /// Important: this is NOT required to receive encrypted messages while you + /// are offline. Devices can still receive encrypted messages while they are + /// offline, but to share those keys with new devices, they have to be + /// online. Dehydrated devices work around this by providing a "shared" + /// device new sessions can bootstrap from, to receive keys from before they + /// logged in that haven't been uploaded to the server-side key backup yet. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/3814 + /// + /// default: false + #[serde(default)] + pub msc3814: SimpleExperiment, /// MSC4155: Invite filtering /// /// Provides advanced invite filtering rules for users, allowing complex From fcddfb5f35c4046ac65160b6af24225a3d1cb2eb Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 14:11:22 +0000 Subject: [PATCH 246/342] fix: Gate MSC4406 behind an experiment --- src/api/client/message.rs | 32 +++++++++++++++++++++----------- src/core/config/experiments.rs | 18 ++++++++++++++++++ 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/src/api/client/message.rs b/src/api/client/message.rs index bcaf7cfe9..2bb3cbbc0 100644 --- a/src/api/client/message.rs +++ b/src/api/client/message.rs @@ -1,6 +1,8 @@ use axum::extract::State; use conduwuit::{ - Err, Error, Result, at, debug_warn, + Err, Error, Result, at, + config::experiments::ToggledExperiment, + debug_warn, matrix::{ event::{Event, Matches}, pdu::PduCount, @@ -315,21 +317,29 @@ where if server_ignored { // the sender's server is ignored, so ignore this event - return Err(Error::BadRequest( - ErrorKind::SenderIgnored(SenderIgnoredErrorData::new()), - "The sender's server is ignored by this server.", - )); + return if services.config.experiments.msc4406.is_enabled() { + Err(Error::BadRequest( + ErrorKind::SenderIgnored(SenderIgnoredErrorData::new()), + "The sender's server is ignored by this server.", + )) + } else { + Err!(Request(NotFound("This event's sender's homeserver is ignored by this server."))) + }; } if user_ignored && !services.config.send_messages_from_ignored_users_to_client { // the recipient of this PDU has the sender ignored, and we're not // configured to send ignored messages to clients - return Err(Error::BadRequest( - ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender( - event.sender().to_owned(), - )), - "You have ignored this sender.", - )); + return if services.config.experiments.msc4406.is_enabled() { + Err(Error::BadRequest( + ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender( + event.sender().to_owned(), + )), + "You have ignored this sender.", + )) + } else { + Err!(Request(NotFound("You have ignored the sender of this event."))) + }; } Ok(false) diff --git a/src/core/config/experiments.rs b/src/core/config/experiments.rs index f647ed889..5d67ef994 100644 --- a/src/core/config/experiments.rs +++ b/src/core/config/experiments.rs @@ -68,6 +68,24 @@ pub struct Experiments { /// default: false #[serde(default)] pub msc4174: SimpleExperiment, + /// MSC4406: `M_SENDER_IGNORED` error code + /// + /// Introduces a new error code that explicitly informs clients the reason + /// they cannot access an event if it is sent by an ignored user. Without + /// this proposal, clients will simply get a "not found" or "forbidden" + /// error when requesting events sent by users that have been ignored, which + /// leads to replies being shown as "this message could not be found". + /// The new error code allows clients to distinguish unknown/forbidden + /// events from ignored senders, allowing them to display an error message + /// like "you have blocked this sender" instead. + /// + /// Requires a supporting client to be useful. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4406 + /// + /// default: false + #[serde(default)] + pub msc4406: SimpleExperiment, /// MSC4484: Server Administration OAuth Scope /// /// Adds a new OAuth2 scope that explicitly grants a token temporary From 52a6bf0003668cf8fd946024eac2e666d34d81b1 Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 14:13:30 +0000 Subject: [PATCH 247/342] fix: Don't unconditionally advertise MSC4174 as enabled in capabilities --- src/api/client/capabilities.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/api/client/capabilities.rs b/src/api/client/capabilities.rs index 1c7d6f512..5851fb9bc 100644 --- a/src/api/client/capabilities.rs +++ b/src/api/client/capabilities.rs @@ -66,7 +66,10 @@ pub(crate) async fn get_capabilities_route( capabilities.set( "org.matrix.msc4174.webpush", - json!({ "enabled": true, "vapid": services.pusher.webpush_vapid_public_key() }), + json!({ + "enabled": services.config.experiments.msc4174.is_enabled(), + "vapid": services.pusher.webpush_vapid_public_key() + }), )?; Ok(get_capabilities::v3::Response::new(capabilities)) From 8f10378bffa871a7b2157daa1c3ae5741ce5c82e Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 14:15:24 +0000 Subject: [PATCH 248/342] chore: Regenerate config reference --- conduwuit-example.toml | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 1f9bb0b5e..bc9534e39 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -2669,6 +2669,26 @@ # and consequently know why you should enable them. +# MSC3814: Dehydrated devices with SSSS +# +# Enables server-side support for "dehydrated devices", which are +# server-side devices (created by supporting clients) that can collect +# encryption keys when there are no online devices, which supporting +# clients can then "hydrate" to download any encryption keys that were +# sent while they were offline. +# +# Important: this is NOT required to receive encrypted messages while you +# are offline. Devices can still receive encrypted messages while they are +# offline, but to share those keys with new devices, they have to be +# online. Dehydrated devices work around this by providing a "shared" +# device new sessions can bootstrap from, to receive keys from before they +# logged in that haven't been uploaded to the server-side key backup yet. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/3814 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC3814 +#msc3814 = false + # MSC4155: Invite filtering # # Provides advanced invite filtering rules for users, allowing complex @@ -2693,6 +2713,24 @@ # env: CONTINUWUITY_EXPERIMENTS__MSC4174 #msc4174 = false +# MSC4406: `M_SENDER_IGNORED` error code +# +# Introduces a new error code that explicitly informs clients the reason +# they cannot access an event if it is sent by an ignored user. Without +# this proposal, clients will simply get a "not found" or "forbidden" +# error when requesting events sent by users that have been ignored, which +# leads to replies being shown as "this message could not be found". +# The new error code allows clients to distinguish unknown/forbidden +# events from ignored senders, allowing them to display an error message +# like "you have blocked this sender" instead. +# +# Requires a supporting client to be useful. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4406 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4406 +#msc4406 = false + # MSC4484: Server Administration OAuth Scope # # Adds a new OAuth2 scope that explicitly grants a token temporary From 62fc507798bc00e0c8ccc1fab94d5d975ed18fb8 Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 14:18:47 +0000 Subject: [PATCH 249/342] chore: Add changelog --- changelog.d/2533.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2533.bugfix.md diff --git a/changelog.d/2533.bugfix.md b/changelog.d/2533.bugfix.md new file mode 100644 index 000000000..39b0092fb --- /dev/null +++ b/changelog.d/2533.bugfix.md @@ -0,0 +1 @@ +Fixed the experiments implementation in #2517 not properly disabling some functionality when associated experiments weren't enabled. From 49207a42f8b18a03250fc0caa64308ec589dfdca Mon Sep 17 00:00:00 2001 From: timedout Date: Sun, 15 Nov 2026 15:44:13 +0000 Subject: [PATCH 250/342] fix: Work around MSC4484 lockout when disabled --- src/api/router/auth.rs | 20 ++++++++++---------- src/service/oauth/grant.rs | 4 ++-- src/service/oauth/mod.rs | 6 ++---- src/web/pages/oauth/grant.rs | 7 ++----- 4 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/api/router/auth.rs b/src/api/router/auth.rs index 6d666bebb..0569ebfbf 100644 --- a/src/api/router/auth.rs +++ b/src/api/router/auth.rs @@ -340,19 +340,19 @@ async fn check_access_token( .map(Box::new); // Make sure the user has the right scopes to use the route - let user_scopes = if let Some(session_info) = &session_info { + let mut user_scopes = if let Some(session_info) = &session_info { session_info.scopes() } else { - let mut scopes = BTreeSet::from_iter([OAuthClientScope::ApiFullAccess]); - - if services.config.experiments.msc4484.is_enabled() - && services.admin.user_is_admin(&sender_user).await - { - scopes.insert(OAuthClientScope::ServerAdministration); - } - - scopes + BTreeSet::from_iter([OAuthClientScope::ApiFullAccess]) }; + if (!services.config.experiments.msc4484.is_enabled() || session_info.is_none()) + && services.admin.user_is_admin(&sender_user).await + { + // This is required to make sure admin APIs still work when msc4484 + // is disabled. + // https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2533#issuecomment-40042 + user_scopes.insert(OAuthClientScope::ServerAdministration); + } if !required_scopes .iter() diff --git a/src/service/oauth/grant.rs b/src/service/oauth/grant.rs index 806409213..1eccc8f98 100644 --- a/src/service/oauth/grant.rs +++ b/src/service/oauth/grant.rs @@ -107,7 +107,7 @@ pub struct RawScopes(String); impl RawScopes { #[allow(clippy::trivial_regex)] - pub fn to_scopes(&self, msc4484: bool) -> Result { + pub fn to_scopes(&self) -> Result { let client_api_token_regex = regex!(r"urn:matrix:(client|org.matrix.msc2967.client):api:\*"); let device_token_regex = @@ -121,7 +121,7 @@ impl RawScopes { let scope_was_new = { if client_api_token_regex.is_match(token) { scopes.scopes.insert(OAuthClientScope::ApiFullAccess) - } else if msc4484 && server_administration_regex.is_match(token) { + } else if server_administration_regex.is_match(token) { scopes.scopes.insert(OAuthClientScope::ServerAdministration) } else if let Some(captures) = device_token_regex.captures(token) { scopes diff --git a/src/service/oauth/mod.rs b/src/service/oauth/mod.rs index adf7111a9..e0d118b2a 100644 --- a/src/service/oauth/mod.rs +++ b/src/service/oauth/mod.rs @@ -286,9 +286,7 @@ impl Service { } } - let requested_scopes = query - .scope - .to_scopes(self.services.config.experiments.msc4484.is_enabled())?; + let requested_scopes = query.scope.to_scopes()?; let redirect_uri_query_separator = match query.response_mode { | ResponseMode::Fragment => '#', @@ -347,7 +345,7 @@ impl Service { let requested_scopes = query .scope - .to_scopes(self.services.config.experiments.msc4484.is_enabled()) + .to_scopes() .map_err(|err| OAuthError::new(ErrorCode::InvalidGrant, err))?; let device_code = Self::generate_token(); diff --git a/src/web/pages/oauth/grant.rs b/src/web/pages/oauth/grant.rs index c815cda6e..1cb268102 100644 --- a/src/web/pages/oauth/grant.rs +++ b/src/web/pages/oauth/grant.rs @@ -4,7 +4,6 @@ use axum::{ response::Redirect, routing::on, }; -use conduwuit_core::config::experiments::ToggledExperiment; use conduwuit_service::oauth::{ SessionInfo, client_metadata::ClientMetadata, @@ -105,10 +104,8 @@ async fn route_authorization_code( return Err(WebError::BadRequest("Invalid client ID".to_owned())); }; - let RequestedScopes { device_id, mut scopes } = query - .scope - .to_scopes(services.config.experiments.msc4484.is_enabled()) - .map_err(WebError::BadRequest)?; + let RequestedScopes { device_id, mut scopes } = + query.scope.to_scopes().map_err(WebError::BadRequest)?; let existing_session_info = if let Some(device_id) = &device_id { services From a9728fab80a2114298c00b6ed5b604d1406c76b4 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sat, 14 Nov 2026 05:04:54 +0000 Subject: [PATCH 251/342] chore(deps): update rust to v1.100.0 --- rust-toolchain.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain.toml b/rust-toolchain.toml index c84026107..cb88237df 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -10,7 +10,7 @@ [toolchain] profile = "minimal" -channel = "1.99.1" +channel = "1.100.0" components = [ # For rust-analyzer "rust-src", From 50665f4726b0408c10a93bdcb11230f0be9b150b Mon Sep 17 00:00:00 2001 From: renovate Date: Sat, 14 Nov 2026 05:14:39 +0000 Subject: [PATCH 252/342] chore(Nix): Updated flake hashes --- nix/rust.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nix/rust.nix b/nix/rust.nix index 53800cbe0..5af1e067d 100644 --- a/nix/rust.nix +++ b/nix/rust.nix @@ -12,7 +12,7 @@ target: target.fromToolchainName { name = (lib.importTOML "${inputs.self}/rust-toolchain.toml").toolchain.channel; - sha256 = "sha256-+xUr6Al1wZSqX8aEsq7DpuFOK4Ve/i+qTl+K5uWQ9GM="; + sha256 = "sha256-MFHoWVcPZKjFrLnQnodCXbUsfZcofGfo9tV9fTTvklg="; }; in { From 67c41110463db3ba6dbaf03982a73a78cb27ac8b Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Thu, 19 Nov 2026 05:03:11 +0000 Subject: [PATCH 253/342] chore(deps): update rust-non-major --- Cargo.lock | 53 +++++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e39a51a8b..367e4ff24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -497,7 +497,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 3.0.10", + "syn 2.0.119", ] [[package]] @@ -604,9 +604,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" [[package]] name = "bytes" -version = "1.12.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" [[package]] name = "bytesize" @@ -764,9 +764,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.7" +version = "4.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" dependencies = [ "clap_builder", "clap_derive", @@ -784,9 +784,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.7" +version = "4.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" dependencies = [ "heck", "proc-macro2", @@ -1525,9 +1525,9 @@ dependencies = [ [[package]] name = "ctor" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +checksum = "ea691ed9f36489d087419b8b2ba3ef27d89621380b4178c73e2445a379e4e0f4" dependencies = [ "link-section", "linktime-proc-macro", @@ -1784,10 +1784,11 @@ dependencies = [ [[package]] name = "dtor" -version = "1.0.6" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd3f6c362b2bbd7063090886afd78978f5dbf1f11da7efcc40f81d32c943fac1" +checksum = "915e80ae7aca23bef767ded8e4a763d0c912c2faaa8bfec1e66d505ebaceb254" dependencies = [ + "link-section", "linktime-proc-macro", ] @@ -2317,9 +2318,9 @@ dependencies = [ [[package]] name = "granit-parser" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f05586d4d4df3d47123207826c40b252728b438a1a07bad3c01ee6bea401df" +checksum = "9bd04d0d9c7079b416b458d2317aea4aa964c81938cb7c20f559758c4f422dc8" dependencies = [ "arraydeque", "smallvec", @@ -3268,9 +3269,9 @@ dependencies = [ [[package]] name = "link-section" -version = "0.19.3" +version = "0.19.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39c29a617ce3df32c08497bdc1ab6e2376e0b17948ac166a2fbe5977c5954cd9" +checksum = "4d9aae57673c1a235149777a74d152f3210ebd3e3b13346d2cdb6809e566bd3c" [[package]] name = "linked-hash-map" @@ -4787,9 +4788,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ "aho-corasick", "memchr", @@ -4799,9 +4800,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" dependencies = [ "aho-corasick", "memchr", @@ -4810,9 +4811,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "reqwest" @@ -5628,12 +5629,12 @@ dependencies = [ [[package]] name = "serde-saphyr" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe" +checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" dependencies = [ "annotate-snippets", - "base64 0.23.1", + "base64 0.22.1", "encoding_rs_io", "granit-parser", "nohash-hasher", @@ -5971,9 +5972,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.5" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" dependencies = [ "serde", ] From 38433deba7783ba0b187b467c44769edd2b39f9d Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 18 Nov 2026 05:06:44 +0000 Subject: [PATCH 254/342] chore(deps): update rust-zerover-patch-updates --- Cargo.lock | 87 +++++++++++++++++++++++++++--------------------------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 367e4ff24..861055021 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -946,7 +946,7 @@ dependencies = [ "hyper", "itertools 0.15.0", "lettre", - "rand 0.10.3", + "rand 0.10.4", "reqwest 0.13.5", "ruma", "ruminuwuity", @@ -998,7 +998,7 @@ dependencies = [ "ipaddress", "lettre", "libc", - "libloading 0.9.0", + "libloading 0.9.1", "lock_api 0.5.0", "maplit", "nix", @@ -1010,7 +1010,7 @@ dependencies = [ "opentelemetry_sdk", "parking_lot", "prometheus", - "rand 0.10.3", + "rand 0.10.4", "regex", "reqwest 0.13.5", "resolvematrix", @@ -1131,7 +1131,7 @@ dependencies = [ "openidconnect", "opentelemetry", "p256 0.14.0", - "rand 0.10.3", + "rand 0.10.4", "regex", "reqwest 0.12.28", "reqwest 0.13.5", @@ -1922,9 +1922,9 @@ dependencies = [ [[package]] name = "email-encoding" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd" +checksum = "9f690ae2169f2ceb3f45b28b6fcd8fa16839f2f5c8818546774b9425f5f71004" dependencies = [ "base64 0.23.1", "memchr", @@ -2495,7 +2495,7 @@ dependencies = [ "idna", "ipnet", "jni", - "rand 0.10.3", + "rand 0.10.4", "thiserror 2.0.21", "tinyvec", "tokio", @@ -2515,7 +2515,7 @@ dependencies = [ "jni", "once_cell", "prefix-trie", - "rand 0.10.3", + "rand 0.10.4", "ring", "serde", "thiserror 2.0.21", @@ -2541,7 +2541,7 @@ dependencies = [ "ndk-context", "once_cell", "parking_lot", - "rand 0.10.3", + "rand 0.10.4", "resolv-conf", "serde", "smallvec", @@ -2954,9 +2954,9 @@ dependencies = [ [[package]] name = "ipaddress" -version = "0.2.11" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a97d7409c3ade4304acbff6b33b915af4564c42bf6e383651ced09bd6a2bce" +checksum = "e0ae5a9c049476ef23026df39fe92a8d83c1d8b670b975f095cb4d5a3b13d43e" dependencies = [ "lazy_static", "libc", @@ -3196,9 +3196,9 @@ dependencies = [ [[package]] name = "lettre" -version = "0.11.23" +version = "0.11.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae" +checksum = "f294f3d7cdb313e578acef7d7727d4e8d897e0fcd0d6d58c19959cec95073f19" dependencies = [ "async-trait", "base64 0.23.1", @@ -3242,9 +3242,9 @@ dependencies = [ [[package]] name = "libloading" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" +checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10" dependencies = [ "cfg-if", "windows-link", @@ -4618,7 +4618,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand 0.10.3", + "rand 0.10.4", "rand_pcg", "ring", "rustc-hash", @@ -4695,9 +4695,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -5045,7 +5045,7 @@ dependencies = [ "js_int", "konst", "percent-encoding", - "rand 0.10.3", + "rand 0.10.4", "regex", "ruma-identifiers-validation", "ruma-macros", @@ -5095,7 +5095,7 @@ dependencies = [ "js_int", "memchr", "mime", - "rand 0.10.3", + "rand 0.10.4", "ruma-common", "ruma-events", "ruma-signatures", @@ -5151,7 +5151,7 @@ dependencies = [ "ed25519-dalek", "memchr", "pkcs8 0.11.0", - "rand 0.10.3", + "rand 0.10.4", "ruma-common", "ruma-events", "serde_json", @@ -5486,9 +5486,9 @@ dependencies = [ [[package]] name = "sentry" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c2c887f17023c9462a4202176efc33ca7228f9c30c0141c765ab534ab2d36b" +checksum = "d7bc7fb14982f395d53924f4feebd48c6cc136399c49ac2160dcf2b260e74b75" dependencies = [ "cfg_aliases", "httpdate", @@ -5506,9 +5506,9 @@ dependencies = [ [[package]] name = "sentry-backtrace" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c391d4330f3b37fdddf2b928151244e8c2dc0cfea1740e455cc8942af436f919" +checksum = "f68328b53eb7defc20f993ed7cd1f4ce10d06feecefdf914db062ce2523e4b77" dependencies = [ "backtrace", "regex", @@ -5517,9 +5517,9 @@ dependencies = [ [[package]] name = "sentry-contexts" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "654dacb94135c713e1dcbff01314a83d333f0e62f76b91fed5ab87415075530c" +checksum = "1d57fb52d1e5d76cc5a7415428004699d9e6d498859a7acc8e05becc57dad81f" dependencies = [ "hostname", "libc", @@ -5531,22 +5531,21 @@ dependencies = [ [[package]] name = "sentry-core" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edcb294ca821e5c5624edaf33535eb18b06ef4f8675201d3e4d81ce325741692" +checksum = "8367f7f31654b35453e20c8aca06e0ecf5a4d4793e33be139c1581e475a94e6a" dependencies = [ - "rand 0.10.3", + "rand 0.10.4", "sentry-types", - "serde", "serde_json", "url", ] [[package]] name = "sentry-debug-images" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74835055f6a57b78c0e13f941b460e39edc1899b05fe31dd47cd02367f70888f" +checksum = "386f4ce2364e58f2ca811f388a0427fa13784bbe7aee85f302e901ef4b00fab9" dependencies = [ "findshlibs", "sentry-core", @@ -5554,9 +5553,9 @@ dependencies = [ [[package]] name = "sentry-log" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f24141aaeb20c731719b33077f1063a79e07eef63a4954530559c067ba046aad" +checksum = "c938358d54c65a79fea165a447ae0eabc5717f23ba482ceee279c5645f0ccad3" dependencies = [ "bitflags", "log", @@ -5565,9 +5564,9 @@ dependencies = [ [[package]] name = "sentry-panic" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5d28522f81ed90510ec43ed01cb1873a393b329dc719f93335b4c75fbef05d1" +checksum = "2ab095af8f107e893941f857d8e204f5d25404247c34af131c7d199e3021679f" dependencies = [ "sentry-backtrace", "sentry-core", @@ -5575,9 +5574,9 @@ dependencies = [ [[package]] name = "sentry-tower" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "057730796d82b72f35f57e66fc41c2b9e334eb3edf5030dd18d3b1f88d062c78" +checksum = "18f29b19179ae36e6318c71f6ee18d1e0db8bbe8e7b7f213c2aba9e721b650fb" dependencies = [ "http", "pin-project", @@ -5589,9 +5588,9 @@ dependencies = [ [[package]] name = "sentry-tracing" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec67c296aadc41d4d41b64738908c51cacddf99edebe7a2b476f9bf40de93ff5" +checksum = "a7cae82b121a812e69a1cfaaacb800112f5f261f362fbf5a08e13d1c11ef349e" dependencies = [ "bitflags", "sentry-backtrace", @@ -5602,13 +5601,13 @@ dependencies = [ [[package]] name = "sentry-types" -version = "0.49.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83d84a36b6bdeeb7813976fb899fca45d94540d2e2b80eac91ba66b4c654d8f0" +checksum = "03da7c1f79d001b4f18e277f8207470efb262fb94c761baa195873d2ace8eb8a" dependencies = [ "debugid", "hex", - "rand 0.10.3", + "rand 0.10.4", "serde", "serde_json", "thiserror 2.0.21", From 6f6e8c4eb5d90d45b01a376e6d265751e4e52d97 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 18 Nov 2026 05:05:41 +0000 Subject: [PATCH 255/342] chore(deps): update node-patch-updates to v2.1.3 --- package-lock.json | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/package-lock.json b/package-lock.json index 696d96791..5908fcd3c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -431,9 +431,9 @@ } }, "node_modules/@rspress/core": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.2.tgz", - "integrity": "sha512-3ghPRkZFwbuO3tr2Rb5cxi6QfSFWOcxoZ5p4pv21lbN5DxAzMduITFlfgBMTArIQbehXrfXw3OUXe1l422b0RA==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.3.tgz", + "integrity": "sha512-qKa5c7zHO8cmhxkReURd3dN/ZRfHYnEztdIQ9hMuolaNzhSYo2A36XErUvLvbMf2EUM2AxfPYRQv+4Crfeq6pw==", "dev": true, "license": "MIT", "dependencies": { @@ -441,7 +441,7 @@ "@mdx-js/react": "^3.1.1", "@rsbuild/core": "^2.2.14", "@rsbuild/plugin-react": "~2.1.1", - "@rspress/shared": "2.1.2", + "@rspress/shared": "2.1.3", "@shikijs/rehype": "^4.2.0", "@shikijs/transformers": "^4.2.0", "@types/mdast": "^4.0.4", @@ -485,9 +485,9 @@ } }, "node_modules/@rspress/plugin-client-redirects": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.2.tgz", - "integrity": "sha512-kNCC7fffXA277TzTDfKpP+QuCI1X218lJ5JH/2iqYR8PHnLw0Y6ZIwoFmJlE0eKaBdniYyBRGn9zgvT93mCWdg==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.3.tgz", + "integrity": "sha512-iEqJ8qEFuUxGKRVaS/WMyFi8FiJlogdcEHbGK/UjY8+8Hg8r8aSv4YihmNh3Ev/uIW21hrC8aXMEgVo0H51Q+g==", "dev": true, "license": "MIT", "engines": { @@ -498,9 +498,9 @@ } }, "node_modules/@rspress/plugin-sitemap": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.2.tgz", - "integrity": "sha512-qF9NDLLJORa7MM8QY/etgMlrXM8hlArNaK5ntiFimqtKRoF1YTJQSKPsAfMq2PvYrpQJyEqsSg6wJ+r+lyjNlw==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.3.tgz", + "integrity": "sha512-Fqo7/4PfQK1ecHUFoUDMrR/E+Hcu+kIohxSs8QabflMy3dqk+M3ZqzJDOHpVYB+HLLGwKiqkPLT4BK+W93clkw==", "dev": true, "license": "MIT", "engines": { @@ -511,9 +511,9 @@ } }, "node_modules/@rspress/shared": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.2.tgz", - "integrity": "sha512-W34tT1fdP3PrdbXpZNKqOGZMOw+RYL70Z9vnkbT1HTTbtX4uMIDE+SU7ByihG0S0LYBsT3kPxA2cXj696253Uw==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.3.tgz", + "integrity": "sha512-VwJ7kgsTWVqHzSXQVHIUCsdMparmq9b/IDmTa3a6jMPl1zmm5Qg9M0eP4j8JXWoIS9n19XtCkQcZmMTFOPRy3A==", "dev": true, "license": "MIT", "dependencies": { From a4ef1ecfa2af2cb14a63cf96fa2baf64eb2e7667 Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 20 Nov 2026 10:48:04 -0500 Subject: [PATCH 256/342] chore: Clippy fixes --- src/admin/mod.rs | 1 + src/api/client/keys.rs | 3 +-- src/api/client/membership/knock.rs | 5 +--- src/api/client/membership/leave.rs | 5 +--- src/api/client/membership/members.rs | 2 +- src/api/client/room/create.rs | 2 +- src/api/client/room/initial_sync.rs | 3 +-- src/api/client/sync/v3/joined.rs | 3 +-- src/api/client/user_directory.rs | 4 +--- src/api/server/make_join.rs | 2 +- src/database/engine/backup.rs | 3 +-- src/router/serve/unix.rs | 2 +- src/service/client/mod.rs | 2 +- src/service/media/data.rs | 35 ++++------------------------ src/service/media/migrations.rs | 2 +- src/service/mod.rs | 1 + src/service/rooms/membership/mod.rs | 2 +- src/service/rooms/short/mod.rs | 5 +--- src/service/rooms/state/mod.rs | 13 ++++------- src/service/rooms/summary/mod.rs | 2 +- src/service/rooms/timeline/redact.rs | 7 +----- src/service/server_keys/request.rs | 3 +-- src/service/transactions/mod.rs | 2 +- src/service/users/mod.rs | 5 +--- 24 files changed, 32 insertions(+), 82 deletions(-) diff --git a/src/admin/mod.rs b/src/admin/mod.rs index 6c4a421cc..079aa0185 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -2,6 +2,7 @@ #![allow(clippy::wildcard_imports)] #![allow(clippy::enum_glob_use)] #![allow(clippy::too_many_arguments)] +#![allow(clippy::large_unopt_stack_frames, reason = "very large Subcommand macro expansions")] conduwuit_macros::introspect_crate! {} diff --git a/src/api/client/keys.rs b/src/api/client/keys.rs index d48bfdb3e..271e6b836 100644 --- a/src/api/client/keys.rs +++ b/src/api/client/keys.rs @@ -15,8 +15,7 @@ use ruma::{ OneTimeKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId, api::{ client::keys::{ - claim_keys, get_key_changes, get_keys, upload_keys, - upload_signatures::{self}, + claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures, upload_signing_keys, }, federation, diff --git a/src/api/client/membership/knock.rs b/src/api/client/membership/knock.rs index a29d80929..d7ef2458a 100644 --- a/src/api/client/membership/knock.rs +++ b/src/api/client/membership/knock.rs @@ -16,10 +16,7 @@ use futures::{FutureExt, StreamExt}; use ruma::{ CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, UserId, - api::{ - client::knock::knock_room, - federation::{self}, - }, + api::{client::knock::knock_room, federation}, canonical_json::to_canonical_value, events::{ StateEventType, diff --git a/src/api/client/membership/leave.rs b/src/api/client/membership/leave.rs index 1ef0b21fa..a10aff0f9 100644 --- a/src/api/client/membership/leave.rs +++ b/src/api/client/membership/leave.rs @@ -10,10 +10,7 @@ use conduwuit::{ use futures::{FutureExt, StreamExt, pin_mut}; use ruma::{ CanonicalJsonObject, CanonicalJsonValue, OwnedServerName, RoomId, UserId, - api::{ - client::membership::leave_room, - federation::{self}, - }, + api::{client::membership::leave_room, federation}, events::{ StateEventType, room::member::{MembershipState, RoomMemberEventContent}, diff --git a/src/api/client/membership/members.rs b/src/api/client/membership/members.rs index 5c8d00829..e2695bd3a 100644 --- a/src/api/client/membership/members.rs +++ b/src/api/client/membership/members.rs @@ -9,7 +9,7 @@ use conduwuit::{ use futures::{FutureExt, StreamExt, future::join}; use ruma::{ api::client::membership::{ - get_member_events::{self}, + get_member_events, joined_members::{self, v3::RoomMember}, }, events::{ diff --git a/src/api/client/room/create.rs b/src/api/client/room/create.rs index c4e5ed917..74f0653db 100644 --- a/src/api/client/room/create.rs +++ b/src/api/client/room/create.rs @@ -77,7 +77,7 @@ struct FullCreationContent { /// - Send events listed in initial state /// - Send events implied by `name` and `topic` /// - Send invite events -#[allow(clippy::large_stack_frames)] +#[allow(clippy::large_unopt_stack_frames)] #[allow(clippy::cognitive_complexity)] pub(crate) async fn create_room_route( State(services): State, diff --git a/src/api/client/room/initial_sync.rs b/src/api/client/room/initial_sync.rs index 9ae8dd73f..70b50f961 100644 --- a/src/api/client/room/initial_sync.rs +++ b/src/api/client/room/initial_sync.rs @@ -94,8 +94,7 @@ pub(crate) async fn room_initial_sync_route( .first() .map(at!(0)) .as_ref() - .map(ToString::to_string) - .unwrap_or_default(); + .map_or_default(ToString::to_string); let start = events.last().map(at!(0)).as_ref().map(ToString::to_string); let chunk = events diff --git a/src/api/client/sync/v3/joined.rs b/src/api/client/sync/v3/joined.rs index 3a2828e69..536dc2a9d 100644 --- a/src/api/client/sync/v3/joined.rs +++ b/src/api/client/sync/v3/joined.rs @@ -787,8 +787,7 @@ async fn build_room_summary( Ok(Some(assign!(RoomSummary::new(), { heroes: heroes - .map(|heroes| heroes.into_iter().collect()) - .unwrap_or_default(), + .map_or_default(|heroes| heroes.into_iter().collect()), joined_member_count: Some(ruma_from_u64(joined_member_count)), invited_member_count: Some(ruma_from_u64(invited_member_count)), }))) diff --git a/src/api/client/user_directory.rs b/src/api/client/user_directory.rs index 7d8a9a9c4..a8eb613d6 100644 --- a/src/api/client/user_directory.rs +++ b/src/api/client/user_directory.rs @@ -5,9 +5,7 @@ use conduwuit::{ }; use futures::{FutureExt, StreamExt, pin_mut}; use ruma::{ - api::client::user_directory::search_users::{self}, - assign, - events::room::join_rules::JoinRule, + api::client::user_directory::search_users, assign, events::room::join_rules::JoinRule, }; use crate::Ruma; diff --git a/src/api/server/make_join.rs b/src/api/server/make_join.rs index dcb74d433..aa0e99e37 100644 --- a/src/api/server/make_join.rs +++ b/src/api/server/make_join.rs @@ -69,7 +69,7 @@ pub(crate) async fn create_join_event_template_route( .get_member(&body.room_id, &body.user_id) .await .ok() - .map_or_else(|| MembershipState::Leave, |content| content.membership); + .map_or(MembershipState::Leave, |content| content.membership); let join_authorized_via_users_server: Option = { if matches!( diff --git a/src/database/engine/backup.rs b/src/database/engine/backup.rs index 9c6d899c7..ca874e7e9 100644 --- a/src/database/engine/backup.rs +++ b/src/database/engine/backup.rs @@ -76,8 +76,7 @@ impl super::Engine { .config .database_backup_path .clone() - .map(PathBuf::into_os_string) - .unwrap_or_default(); + .map_or_default(PathBuf::into_os_string); if path.is_empty() { return Err!(Config("database_backup_path", "Configure path to enable backups")); diff --git a/src/router/serve/unix.rs b/src/router/serve/unix.rs index 9bb3dd6e0..ceba1c1b9 100644 --- a/src/router/serve/unix.rs +++ b/src/router/serve/unix.rs @@ -22,7 +22,7 @@ use hyper_util::{ use tokio::{ fs, net::{UnixListener, UnixStream, unix::SocketAddr}, - sync::broadcast::{self}, + sync::broadcast, task::JoinSet, time::{Duration, sleep}, }; diff --git a/src/service/client/mod.rs b/src/service/client/mod.rs index 39f00b40c..2cd157f84 100644 --- a/src/service/client/mod.rs +++ b/src/service/client/mod.rs @@ -379,7 +379,7 @@ fn get_dns_resolver(server: &Arc) -> Result> { info!(?nameservers, "Resolved nameservers for DNS client"); for sys_conf in nameservers { - let mut ns = sys_conf.clone(); + let mut ns = sys_conf; if config.query_over_tcp_only { ns.connections = vec![ConnectionConfig::tcp()]; diff --git a/src/service/media/data.rs b/src/service/media/data.rs index 7416464f8..d4a1c15cd 100644 --- a/src/service/media/data.rs +++ b/src/service/media/data.rs @@ -182,26 +182,11 @@ impl Data { let mut value = Vec::::new(); value.extend_from_slice(×tamp.as_secs().to_be_bytes()); value.push(0xFF); - value.extend_from_slice( - data.title - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.title.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); - value.extend_from_slice( - data.description - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.description.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); - value.extend_from_slice( - data.image - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.image.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); value.extend_from_slice(&data.image_size.unwrap_or(0).to_be_bytes()); value.push(0xFF); @@ -209,12 +194,7 @@ impl Data { value.push(0xFF); value.extend_from_slice(&data.image_height.unwrap_or(0).to_be_bytes()); value.push(0xFF); - value.extend_from_slice( - data.video - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.video.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); value.extend_from_slice(&data.video_size.unwrap_or(0).to_be_bytes()); value.push(0xFF); @@ -222,12 +202,7 @@ impl Data { value.push(0xFF); value.extend_from_slice(&data.video_height.unwrap_or(0).to_be_bytes()); value.push(0xFF); - value.extend_from_slice( - data.audio - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.audio.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); value.extend_from_slice(&data.audio_size.unwrap_or(0).to_be_bytes()); diff --git a/src/service/media/migrations.rs b/src/service/media/migrations.rs index 5fd628cd9..0cb91ea13 100644 --- a/src/service/media/migrations.rs +++ b/src/service/media/migrations.rs @@ -1,7 +1,7 @@ use std::{ collections::HashSet, ffi::{OsStr, OsString}, - fs::{self}, + fs, path::PathBuf, sync::Arc, time::Instant, diff --git a/src/service/mod.rs b/src/service/mod.rs index 9a8722cff..0560e135c 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -1,4 +1,5 @@ #![type_length_limit = "8192"] +#![recursion_limit = "256"] #![allow(refining_impl_trait)] extern crate conduwuit_core as conduwuit; diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index 93246d8c2..0659db2be 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -153,7 +153,7 @@ impl Service { .get_member(room_id, sender_user) .await .ok() - .map_or_else(|| MembershipState::Leave, |content| content.membership) + .map_or(MembershipState::Leave, |content| content.membership) } else { MembershipState::Leave }; diff --git a/src/service/rooms/short/mod.rs b/src/service/rooms/short/mod.rs index 53d70fe85..2287eea2d 100644 --- a/src/service/rooms/short/mod.rs +++ b/src/service/rooms/short/mod.rs @@ -8,10 +8,7 @@ use conduwuit::{ utils::{self, IterStream, ReadyExt}, }; use database::{Deserialized, Get, Map, Qry}; -use futures::{ - Stream, StreamExt, - stream::{self}, -}; +use futures::{Stream, StreamExt, stream}; use ruma::{EventId, OwnedEventId, RoomId, events::StateEventType}; use serde::Deserialize; diff --git a/src/service/rooms/state/mod.rs b/src/service/rooms/state/mod.rs index 147e944a7..c61d9349d 100644 --- a/src/service/rooms/state/mod.rs +++ b/src/service/rooms/state/mod.rs @@ -264,14 +264,11 @@ impl Service { .compress_state_event(shortstatekey, &new_pdu.event_id) .await; - let replaces = states_parents - .last() - .map(|info| { - info.full_state - .iter() - .find(|bytes| bytes.starts_with(&shortstatekey.to_be_bytes())) - }) - .unwrap_or_default(); + let replaces = states_parents.last().map_or_default(|info| { + info.full_state + .iter() + .find(|bytes| bytes.starts_with(&shortstatekey.to_be_bytes())) + }); if Some(&new) == replaces { return Ok(previous_shortstatehash.expect("must exist")); diff --git a/src/service/rooms/summary/mod.rs b/src/service/rooms/summary/mod.rs index ee643b6a6..d8d8d96fb 100644 --- a/src/service/rooms/summary/mod.rs +++ b/src/service/rooms/summary/mod.rs @@ -745,7 +745,7 @@ impl Service { .get_member(room_id, querying_user) .await .ok() - .map_or_else(|| MembershipState::Leave, |content| content.membership); + .map_or(MembershipState::Leave, |content| content.membership); if matches!(membership, MembershipState::Join | MembershipState::Invite) { return true; diff --git a/src/service/rooms/timeline/redact.rs b/src/service/rooms/timeline/redact.rs index 905cd40c7..0fbe4aba0 100644 --- a/src/service/rooms/timeline/redact.rs +++ b/src/service/rooms/timeline/redact.rs @@ -1,10 +1,5 @@ use conduwuit::config::experiments::ToggledExperiment; -use conduwuit_core::{ - Err, Result, err, - matrix::event::Event, - utils::{self}, - warn, -}; +use conduwuit_core::{Err, Result, err, matrix::event::Event, utils, warn}; use ruma::{EventId, events::room::encrypted::Relation, signatures::content_hash}; use super::{ExtractBody, ExtractRelatesTo}; diff --git a/src/service/server_keys/request.rs b/src/service/server_keys/request.rs index e3f03562a..f7b2ead17 100644 --- a/src/service/server_keys/request.rs +++ b/src/service/server_keys/request.rs @@ -101,8 +101,7 @@ impl super::Service { .trusted_servers .iter() .find(|n| n.server_name() == notary) - .map(|nk| nk.verify_keys().to_owned()) - .unwrap_or_default(); + .map_or_default(|nk| nk.verify_keys().to_owned()); let keys = self .services .sending diff --git a/src/service/transactions/mod.rs b/src/service/transactions/mod.rs index 094317c8b..9664abd00 100644 --- a/src/service/transactions/mod.rs +++ b/src/service/transactions/mod.rs @@ -143,7 +143,7 @@ impl Service { ) { let mut key = user_id.as_bytes().to_vec(); key.push(0xFF); - key.extend_from_slice(device_id.map(DeviceId::as_bytes).unwrap_or_default()); + key.extend_from_slice(device_id.map_or_default(DeviceId::as_bytes)); key.push(0xFF); key.extend_from_slice(txn_id.as_bytes()); diff --git a/src/service/users/mod.rs b/src/service/users/mod.rs index 09ade8a97..c02ff8647 100644 --- a/src/service/users/mod.rs +++ b/src/service/users/mod.rs @@ -9,10 +9,7 @@ pub(super) mod remote; use std::{mem, sync::Arc}; pub use account::{AccessTokenStatus, AccountStatus}; -use conduwuit::{ - Err, Error, Result, err, - utils::{self}, -}; +use conduwuit::{Err, Error, Result, err, utils}; use database::Map; pub use device::DeviceToken; pub use profile::ProfileFieldChange; From 8004e962c3dd8b84f366129850e743eb33e26818 Mon Sep 17 00:00:00 2001 From: Ginger Date: Thu, 29 Oct 2026 17:23:10 -0400 Subject: [PATCH 257/342] feat: Add support for MSC4388 --- Cargo.toml | 1 + conduwuit-example.toml | 23 ++++- src/api/client/mod.rs | 2 + src/api/client/rendezvous.rs | 76 ++++++++++++++++ src/api/router.rs | 5 ++ src/core/config/mod.rs | 25 +++++- src/core/mod.rs | 3 +- src/service/mod.rs | 1 + src/service/rendezvous/mod.rs | 158 ++++++++++++++++++++++++++++++++++ src/service/services.rs | 6 +- 10 files changed, 289 insertions(+), 11 deletions(-) create mode 100644 src/api/client/rendezvous.rs create mode 100644 src/service/rendezvous/mod.rs diff --git a/Cargo.toml b/Cargo.toml index e730e8cdd..4dbc03622 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -395,6 +395,7 @@ features = [ "unstable-msc4406", "unstable-msc4439", "unstable-msc4354", + "unstable-msc4388", "unstable-msc4480", "unstable-msc4466", "unstable-msc4494", diff --git a/conduwuit-example.toml b/conduwuit-example.toml index bc9534e39..aeadec88e 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -812,15 +812,30 @@ # env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE #forget_forced_upon_leave = false -# Set this to true to require authentication on the normally -# unauthenticated profile retrieval endpoints (GET) -# "/_matrix/client/v3/profile/{userId}". +# Set this to true to require authentication when looking up user profiles +# through this server. # -# This can prevent profile scraping. +# By default this is false, allowing tools such as matrix.to to access +# profiles of users on this server and on other servers. +# Setting this to true will block those tools, and may block automated +# crawlers from scraping users' profiles, although it will not block +# other homeservers from accessing users' profiles. # # env: CONTINUWUITY_REQUIRE_AUTH_FOR_PROFILE_REQUESTS #require_auth_for_profile_requests = false +# Set this to false to allow rendezvous sessions to be created without +# authentication. Rendezvous sessions are used for QR code sign-in. +# +# By default this is true, meaning that a user must use their signed-in +# device to generate a QR code when signing in. Setting this to false will +# allow signed-out devices to generate QR codes using this homeserver, +# which may be desirable for public-registration homeservers. +#a user +# +# env: CONTINUWUITY_REQUIRE_AUTH_FOR_RENDEZVOUS +#require_auth_for_rendezvous = true + # Set this to true to allow your server's public room directory to be # federated. Set this to false to protect against /publicRooms spiders, # but will forbid external users from viewing your server's public room diff --git a/src/api/client/mod.rs b/src/api/client/mod.rs index 6c26f6748..fa372a67c 100644 --- a/src/api/client/mod.rs +++ b/src/api/client/mod.rs @@ -23,6 +23,7 @@ pub(super) mod push; pub(super) mod read_marker; pub(super) mod redact; pub(super) mod relations; +pub(super) mod rendezvous; pub(super) mod report; pub(super) mod room; pub(super) mod search; @@ -69,6 +70,7 @@ pub(super) use push::*; pub(super) use read_marker::*; pub(super) use redact::*; pub(super) use relations::*; +pub(super) use rendezvous::*; pub(super) use report::*; pub(super) use room::*; pub(super) use search::*; diff --git a/src/api/client/rendezvous.rs b/src/api/client/rendezvous.rs new file mode 100644 index 000000000..d779b74a3 --- /dev/null +++ b/src/api/client/rendezvous.rs @@ -0,0 +1,76 @@ +use axum::extract::State; +use conduwuit::{Err, Result}; +use http::HeaderMap; +use ruma::api::client::rendezvous::{ + create_rendezvous_session, delete_rendezvous_session, discover_rendezvous, + get_rendezvous_session, update_rendezvous_session, +}; +use service::Services; + +use crate::{Ruma, router::ClientIdentity}; + +/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous` +pub(crate) async fn discover_rendezvous_route( + State(services): State, + body: Ruma, +) -> Result { + Ok(discover_rendezvous::msc4388::Response::new(rendezvous_available( + &services, + body.identity.as_ref(), + ))) +} + +/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/` +pub(crate) async fn create_rendezvous_session_route( + State(services): State, + body: Ruma, +) -> Result { + if !rendezvous_available(&services, body.identity.as_ref()) { + return Err!(Request(Forbidden("You are not authorized to create a rendezvous session"))); + } + + services.rendezvous.create_session(body.data.clone()) +} + +/// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}` +pub(crate) async fn update_rendezvous_session_route( + State(services): State, + body: Ruma, +) -> Result { + services.rendezvous.update_session( + &body.id, + body.txn_id.clone(), + body.sequence_token.clone(), + body.data.clone(), + ) +} + +/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}` +pub(crate) async fn get_rendezvous_session_route( + State(services): State, + headers: HeaderMap, + body: Ruma, +) -> Result { + if let Some(mode) = headers.get("Sec-Fetch-Mode") + && let Ok(mode) = mode.to_str() + && mode == "navigate" + { + return Err!(Request(Forbidden( + "Rendezvous sessions do not accept browser navigation requests." + ))); + } + + services.rendezvous.get_session(&body.id) +} + +/// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}` +pub(crate) async fn delete_rendezvous_session_route( + State(services): State, + body: Ruma, +) -> Result { + services.rendezvous.delete_session(&body.id) +} + +fn rendezvous_available(services: &Services, identity: Option<&ClientIdentity>) -> bool { + !services.config.require_auth_for_rendezvous || identity.is_some() +} diff --git a/src/api/router.rs b/src/api/router.rs index 36469eb46..0e8481d35 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -189,6 +189,11 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&client::well_known_policy_server) .ruma_route(&client::get_rtc_transports) .ruma_route(&client::room_initial_sync_route) + .ruma_route(&client::discover_rendezvous_route) + .ruma_route(&client::create_rendezvous_session_route) + .ruma_route(&client::update_rendezvous_session_route) + .ruma_route(&client::get_rendezvous_session_route) + .ruma_route(&client::delete_rendezvous_session_route) .ruma_route(&client::get_authorization_server_metadata_route) .merge(client::oauth::router(state)) .route("/_continuwuity/server_version", get(client::continuwuity_server_version)) diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index b720756ee..ec0c7aa40 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -919,14 +919,31 @@ pub struct Config { #[serde(default)] pub forget_forced_upon_leave: bool, - /// Set this to true to require authentication on the normally - /// unauthenticated profile retrieval endpoints (GET) - /// "/_matrix/client/v3/profile/{userId}". + /// Set this to true to require authentication when looking up user profiles + /// through this server. /// - /// This can prevent profile scraping. + /// By default this is false, allowing tools such as matrix.to to access + /// profiles of users on this server and on other servers. + /// Setting this to true will block those tools, and may block automated + /// crawlers from scraping users' profiles, although it will not block + /// other homeservers from accessing users' profiles. + /// + /// default: false #[serde(default)] pub require_auth_for_profile_requests: bool, + /// Set this to false to allow rendezvous sessions to be created without + /// authentication. Rendezvous sessions are used for QR code sign-in. + /// + /// By default this is true, meaning that a user must use their signed-in + /// device to generate a QR code when signing in. Setting this to false will + /// allow signed-out devices to generate QR codes using this homeserver, + /// which may be desirable for public-registration homeservers. + /// + /// default: true + #[serde(default = "true_fn")] + pub require_auth_for_rendezvous: bool, + /// Set this to true to allow your server's public room directory to be /// federated. Set this to false to protect against /publicRooms spiders, /// but will forbid external users from viewing your server's public room diff --git a/src/core/mod.rs b/src/core/mod.rs index f176593c4..d815bc545 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -37,7 +37,8 @@ pub use error::Error; pub use info::version::*; pub use matrix::{Event, EventTypeExt, Pdu, PduCount, PduEvent, PduId, pdu, state_res}; pub use parking_lot::{ - Mutex as SyncMutex, RwLock as SyncRwLock, RwLockReadGuard as SyncRwLockReadGuard, + MappedMutexGuard as SyncMappedMutexGuard, Mutex as SyncMutex, MutexGuard as SyncMutexGuard, + RwLock as SyncRwLock, RwLockReadGuard as SyncRwLockReadGuard, RwLockWriteGuard as SyncRwLockWriteGuard, }; pub use server::Server; diff --git a/src/service/mod.rs b/src/service/mod.rs index 0560e135c..0cb476cb0 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -34,6 +34,7 @@ pub mod oidc; pub mod presence; pub mod pusher; pub mod registration_tokens; +pub mod rendezvous; pub mod rooms; pub mod sending; pub mod server_keys; diff --git a/src/service/rendezvous/mod.rs b/src/service/rendezvous/mod.rs new file mode 100644 index 000000000..e877b1ef8 --- /dev/null +++ b/src/service/rendezvous/mod.rs @@ -0,0 +1,158 @@ +use std::{ + sync::Arc, + time::{Duration, SystemTime}, +}; + +use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils}; +use lru_cache::LruCache; +use ruma::{ + OwnedTransactionId, + api::client::rendezvous::{ + create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session, + update_rendezvous_session, + }, +}; + +pub struct Service { + sessions: SyncMutex>, +} + +struct Session { + data: String, + created_at: SystemTime, + last_sequence_token: String, + transaction_sequences: LruCache, +} + +impl Session { + const SAVED_TRANSACTION_SEQUENCES: usize = 256; + + fn new(data: String, sequence_token: String) -> Self { + Self { + data, + created_at: SystemTime::now(), + last_sequence_token: sequence_token, + transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES), + } + } +} + +impl crate::Service for Service { + fn build(_: crate::Args<'_>) -> Result> { + Ok(Arc::new(Self { + sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)), + })) + } + + fn name(&self) -> &str { crate::service::make_name(std::module_path!()) } +} + +impl Service { + const MAX_DATA_SIZE_BYTES: usize = 4096; + const MAX_SESSIONS: usize = 256; + const SESSION_MAX_AGE: Duration = Duration::from_secs(300); + const TOKEN_LENGTH: usize = 32; + + fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) } + + fn lock_session(&self, id: &str) -> Result> { + SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| { + sessions + .get_mut(id) + .filter(|session| { + SystemTime::now() + .duration_since(session.created_at) + .is_ok_and(|duration| duration < Self::SESSION_MAX_AGE) + }) + .ok_or_else(|| err!(Request(NotFound("Unknown session")))) + }) + .map_err(at!(1)) + } + + pub fn create_session( + &self, + data: String, + ) -> Result { + if data.len() > Self::MAX_DATA_SIZE_BYTES { + return Err!(Request(TooLarge("Data too large"))); + } + + let id = Self::create_token(); + let sequence_token = Self::create_token(); + + self.sessions + .lock() + .insert(id.clone(), Session::new(data, sequence_token.clone())); + + Ok(create_rendezvous_session::msc4388::Response::new( + id, + sequence_token, + Self::SESSION_MAX_AGE, + )) + } + + pub fn update_session( + &self, + id: &str, + transaction: OwnedTransactionId, + sequence_token: String, + data: String, + ) -> Result { + let mut session = self.lock_session(id)?; + + if data.len() > Self::MAX_DATA_SIZE_BYTES { + return Err!(Request(TooLarge("Data too large"))); + } + + let mut session = self.lock_session(id)?; + + if let Some(sequence_token) = session.transaction_sequences.get_mut(&transaction) { + return Ok(update_rendezvous_session::msc4388::Response::new( + sequence_token.to_owned(), + )); + } + + if session.last_sequence_token != sequence_token { + return Err!(Request(ConcurrentWrite("Sequence token mismatch"))); + } + + let new_sequence_token = Self::create_token(); + + session.data = data; + session.last_sequence_token.clone_from(&new_sequence_token); + session + .transaction_sequences + .insert(transaction, sequence_token); + + Ok(update_rendezvous_session::msc4388::Response::new(new_sequence_token)) + } + + pub fn get_session(&self, id: &str) -> Result { + let session = self.lock_session(id)?; + + let session_age = SystemTime::now() + .duration_since(session.created_at) + .unwrap_or(Duration::MAX); + + let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age); + + Ok(get_rendezvous_session::msc4388::Response::new( + session.last_sequence_token.clone(), + session.data.clone(), + session_time_remaining, + )) + } + + pub fn delete_session( + &self, + id: &str, + ) -> Result { + let mut sessions = self.sessions.lock(); + + if sessions.remove(id).is_some() { + Ok(delete_rendezvous_session::msc4388::Response::new()) + } else { + Err!(Request(NotFound("Unknown session"))) + } + } +} diff --git a/src/service/services.rs b/src/service/services.rs index 96df263f7..79a1ced78 100644 --- a/src/service/services.rs +++ b/src/service/services.rs @@ -11,8 +11,8 @@ use crate::{ account_data, admin, announcements, antispam, appservice, client, config, emergency, federation, firstrun, globals, key_backups, mailer, manager::Manager, - media, moderation, oauth, oidc, presence, pusher, registration_tokens, rooms, sending, - server_keys, + media, moderation, oauth, oidc, presence, pusher, registration_tokens, rendezvous, rooms, + sending, server_keys, service::{self, Args, Map, Service}, sync, threepid, transactions, uiaa, users, }; @@ -33,6 +33,7 @@ pub struct Services { pub presence: Arc, pub pusher: Arc, pub registration_tokens: Arc, + pub rendezvous: Arc, pub rooms: rooms::Service, pub federation: Arc, pub firstrun: Arc, @@ -89,6 +90,7 @@ impl Services { presence: build!(presence::Service), pusher: build!(pusher::Service), registration_tokens: build!(registration_tokens::Service), + rendezvous: build!(rendezvous::Service), rooms: rooms::Service { alias: build!(rooms::alias::Service), auth_chain: build!(rooms::auth_chain::Service), From 2944026572f77323fd7fc2764046f18e83e13826 Mon Sep 17 00:00:00 2001 From: Ginger Date: Thu, 29 Oct 2026 17:35:01 -0400 Subject: [PATCH 258/342] fix: Be more lenient with allowed characters in device ID scopes --- src/service/oauth/grant.rs | 42 +++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/src/service/oauth/grant.rs b/src/service/oauth/grant.rs index 1eccc8f98..b42506f1b 100644 --- a/src/service/oauth/grant.rs +++ b/src/service/oauth/grant.rs @@ -106,12 +106,14 @@ impl Display for RequestedScopes { pub struct RawScopes(String); impl RawScopes { + const MIN_DEVICE_ID_LENGTH: usize = 5; + #[allow(clippy::trivial_regex)] pub fn to_scopes(&self) -> Result { let client_api_token_regex = regex!(r"urn:matrix:(client|org.matrix.msc2967.client):api:\*"); let device_token_regex = - regex!(r"urn:matrix:(client|org.matrix.msc2967.client):device:([a-zA-Z0-9-._~]{5,})"); + regex!(r"urn:matrix:(client|org.matrix.msc2967.client):device:(.+)"); let server_administration_regex = regex!(r"urn:matrix:client:cc.c10y.msc4484.server_administration"); @@ -124,10 +126,40 @@ impl RawScopes { } else if server_administration_regex.is_match(token) { scopes.scopes.insert(OAuthClientScope::ServerAdministration) } else if let Some(captures) = device_token_regex.captures(token) { - scopes - .device_id - .replace(captures.get(2).unwrap().as_str().into()) - .is_none() + let device_id = captures.get(2).unwrap().as_str(); + + if device_id.len() < Self::MIN_DEVICE_ID_LENGTH { + return Err(format!( + "Device ID is too short, it must be at least {} characters", + Self::MIN_DEVICE_ID_LENGTH + )); + } + + // The Matrix specification has a "suggested" set of + // characters to be used in the device + // ID scope. In the past we checked against this set, but we + // no longer do that; instead we check + // against the _required_ set of + // characters defined by the OAuth specification. + // We do this because we have observed SDKs in the wild + // (*cough* matrix-rust-sdk) that will provide device IDs + // that are just unpadded base64, which they're allowed to + // do, since the spec just says that + // clients "SHOULD" only use the suggested character set and + // servers "MAY" choose to require that they do. + // Of course this actually means that clients will do + // whatever the hell they want and + // servers can never ever be stricter + // than they absolutely have to be. What + // a stupid provision. + if device_id + .chars() + .any(|char| !matches!(char, '\x21' | '\x23'..='\x5b' | '\x5d'..='\x7e')) + { + return Err("Device ID contains disallowed characters".to_owned()); + } + + scopes.device_id.replace(device_id.into()).is_none() } else { continue; } From 3d2975209ed4d4db06c339be156a37b92bf81107 Mon Sep 17 00:00:00 2001 From: Ginger Date: Thu, 29 Oct 2026 18:04:01 -0400 Subject: [PATCH 259/342] chore: News fragment --- changelog.d/2429.feature.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2429.feature.md diff --git a/changelog.d/2429.feature.md b/changelog.d/2429.feature.md new file mode 100644 index 000000000..a2b595fb5 --- /dev/null +++ b/changelog.d/2429.feature.md @@ -0,0 +1 @@ +Added support for MSC4388, allowing compatible Matrix clients to log in to Continuwuity by scanning a QR code on an already logged-in client. Contributed by @ginger. From 580fcf236585a19c234ae9fa6a86a90e471c27c0 Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 30 Oct 2026 13:40:41 -0400 Subject: [PATCH 260/342] chore: Add doc comments --- src/service/rendezvous/mod.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/service/rendezvous/mod.rs b/src/service/rendezvous/mod.rs index e877b1ef8..a56ee7d5c 100644 --- a/src/service/rendezvous/mod.rs +++ b/src/service/rendezvous/mod.rs @@ -55,7 +55,10 @@ impl Service { fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) } + /// Lock and fetch an unexpired rendezvous session. fn lock_session(&self, id: &str) -> Result> { + // We don't clear out expired sessions manually, the LRU cache will + // evict them over time SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| { sessions .get_mut(id) @@ -69,6 +72,7 @@ impl Service { .map_err(at!(1)) } + /// Create a fresh rendezvous session. pub fn create_session( &self, data: String, @@ -91,6 +95,7 @@ impl Service { )) } + /// Update a rendezvous session with new data. pub fn update_session( &self, id: &str, @@ -104,8 +109,9 @@ impl Service { return Err!(Request(TooLarge("Data too large"))); } - let mut session = self.lock_session(id)?; - + // If the provided transaction ID was used already, we have to return + // the sequence token that we returned last time it was used. + // This makes session updates with the same transaction ID idempotent. if let Some(sequence_token) = session.transaction_sequences.get_mut(&transaction) { return Ok(update_rendezvous_session::msc4388::Response::new( sequence_token.to_owned(), @@ -127,7 +133,8 @@ impl Service { Ok(update_rendezvous_session::msc4388::Response::new(new_sequence_token)) } - pub fn get_session(&self, id: &str) -> Result { + /// Look up a rendezvous session by ID. + pub fn get_session(&self, id: &str) -> Result { let session = self.lock_session(id)?; let session_age = SystemTime::now() @@ -143,6 +150,7 @@ impl Service { )) } + /// Delete a rendezvous session. pub fn delete_session( &self, id: &str, From 330797f4fbe42904993a4d30e6d9bc4322d6f382 Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 30 Oct 2026 18:00:50 -0400 Subject: [PATCH 261/342] fix: Properly save rendezvous sequence token --- src/service/rendezvous/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/service/rendezvous/mod.rs b/src/service/rendezvous/mod.rs index a56ee7d5c..d5cca1352 100644 --- a/src/service/rendezvous/mod.rs +++ b/src/service/rendezvous/mod.rs @@ -122,13 +122,15 @@ impl Service { return Err!(Request(ConcurrentWrite("Sequence token mismatch"))); } + drop(sequence_token); + let new_sequence_token = Self::create_token(); session.data = data; session.last_sequence_token.clone_from(&new_sequence_token); session .transaction_sequences - .insert(transaction, sequence_token); + .insert(transaction, new_sequence_token.clone()); Ok(update_rendezvous_session::msc4388::Response::new(new_sequence_token)) } From 4c49a20255f163774d978f447eb36174d88904b4 Mon Sep 17 00:00:00 2001 From: Ginger Date: Wed, 11 Nov 2026 10:02:52 -0500 Subject: [PATCH 262/342] feat: Enable unauthenticated rendezvous by default --- conduwuit-example.toml | 16 +++++++++------- src/core/config/mod.rs | 19 +++++++++++-------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index aeadec88e..b0230fcae 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -824,14 +824,16 @@ # env: CONTINUWUITY_REQUIRE_AUTH_FOR_PROFILE_REQUESTS #require_auth_for_profile_requests = false -# Set this to false to allow rendezvous sessions to be created without -# authentication. Rendezvous sessions are used for QR code sign-in. +# Set this to true to require authentication to create a rendezvous +# session. Rendezvous sessions are used for QR code login. # -# By default this is true, meaning that a user must use their signed-in -# device to generate a QR code when signing in. Setting this to false will -# allow signed-out devices to generate QR codes using this homeserver, -# which may be desirable for public-registration homeservers. -#a user +# For QR code login, the device that shows the QR code is the one that +# creates the rendezvous session. Therefore, this must be false to let +# a logged-out device show a QR code. +# +# By default this is false, allowing logged-out desktop devices (which may +# not have a camera) to show a QR code. Setting this to true will +# require logged-out devices to scan the QR code instead. # # env: CONTINUWUITY_REQUIRE_AUTH_FOR_RENDEZVOUS #require_auth_for_rendezvous = true diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index ec0c7aa40..af5ef5cca 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -932,16 +932,19 @@ pub struct Config { #[serde(default)] pub require_auth_for_profile_requests: bool, - /// Set this to false to allow rendezvous sessions to be created without - /// authentication. Rendezvous sessions are used for QR code sign-in. + /// Set this to true to require authentication to create a rendezvous + /// session. Rendezvous sessions are used for QR code login. + /// + /// For QR code login, the device that shows the QR code is the one that + /// creates the rendezvous session. Therefore, this must be false to let + /// a logged-out device show a QR code. + /// + /// By default this is false, allowing logged-out desktop devices (which may + /// not have a camera) to show a QR code. Setting this to true will + /// require logged-out devices to scan the QR code instead. /// - /// By default this is true, meaning that a user must use their signed-in - /// device to generate a QR code when signing in. Setting this to false will - /// allow signed-out devices to generate QR codes using this homeserver, - /// which may be desirable for public-registration homeservers. - /// /// default: true - #[serde(default = "true_fn")] + #[serde(default)] pub require_auth_for_rendezvous: bool, /// Set this to true to allow your server's public room directory to be From 48e83f6dfa3aa9ef9dbd4bce0dda0a94b9e51619 Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 20 Nov 2026 10:10:03 -0500 Subject: [PATCH 263/342] fix: Check max rendezvous data size at the correct time --- src/service/rendezvous/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/service/rendezvous/mod.rs b/src/service/rendezvous/mod.rs index d5cca1352..09cceafbc 100644 --- a/src/service/rendezvous/mod.rs +++ b/src/service/rendezvous/mod.rs @@ -105,10 +105,6 @@ impl Service { ) -> Result { let mut session = self.lock_session(id)?; - if data.len() > Self::MAX_DATA_SIZE_BYTES { - return Err!(Request(TooLarge("Data too large"))); - } - // If the provided transaction ID was used already, we have to return // the sequence token that we returned last time it was used. // This makes session updates with the same transaction ID idempotent. @@ -126,6 +122,10 @@ impl Service { let new_sequence_token = Self::create_token(); + if data.len() > Self::MAX_DATA_SIZE_BYTES { + return Err!(Request(TooLarge("Data too large"))); + } + session.data = data; session.last_sequence_token.clone_from(&new_sequence_token); session From 6d96936d3a452881e24f6680f90bffc1c3a627b1 Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 20 Nov 2026 10:30:26 -0500 Subject: [PATCH 264/342] fix: Correct config defaults --- conduwuit-example.toml | 2 +- src/core/config/mod.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index b0230fcae..9d22e4a51 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -836,7 +836,7 @@ # require logged-out devices to scan the QR code instead. # # env: CONTINUWUITY_REQUIRE_AUTH_FOR_RENDEZVOUS -#require_auth_for_rendezvous = true +#require_auth_for_rendezvous = false # Set this to true to allow your server's public room directory to be # federated. Set this to false to protect against /publicRooms spiders, diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index af5ef5cca..f5869deaf 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -943,7 +943,7 @@ pub struct Config { /// not have a camera) to show a QR code. Setting this to true will /// require logged-out devices to scan the QR code instead. /// - /// default: true + /// default: false #[serde(default)] pub require_auth_for_rendezvous: bool, From 9d2e53af99eb28240701a52699f48e95b8f65736 Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 20 Nov 2026 11:22:14 -0500 Subject: [PATCH 265/342] fix: Config wording improvement --- conduwuit-example.toml | 2 +- src/core/config/mod.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 9d22e4a51..c5a3edce6 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -831,7 +831,7 @@ # creates the rendezvous session. Therefore, this must be false to let # a logged-out device show a QR code. # -# By default this is false, allowing logged-out desktop devices (which may +# By default this is false to allow logged-out desktop devices (which may # not have a camera) to show a QR code. Setting this to true will # require logged-out devices to scan the QR code instead. # diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index f5869deaf..43d991215 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -939,7 +939,7 @@ pub struct Config { /// creates the rendezvous session. Therefore, this must be false to let /// a logged-out device show a QR code. /// - /// By default this is false, allowing logged-out desktop devices (which may + /// By default this is false to allow logged-out desktop devices (which may /// not have a camera) to show a QR code. Setting this to true will /// require logged-out devices to scan the QR code instead. /// From 58026816f2b7dcebf032d65c58d2bccf855f136d Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 20 Nov 2026 13:02:47 -0500 Subject: [PATCH 266/342] fix: URL-escape device IDs in the web UI --- src/web/pages/templates/_components/device_card.html.j2 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/pages/templates/_components/device_card.html.j2 b/src/web/pages/templates/_components/device_card.html.j2 index b145f6635..7a4272c57 100644 --- a/src/web/pages/templates/_components/device_card.html.j2 +++ b/src/web/pages/templates/_components/device_card.html.j2 @@ -23,7 +23,7 @@
{% if style != DeviceCardStyle::Detailed %} - Details + Details {% endif %}
{% endif %} From aa077b4bece6e65b01de36f71ec92d82f4c7630f Mon Sep 17 00:00:00 2001 From: Julian Anderson Date: Thu, 19 Nov 2026 21:23:41 -0500 Subject: [PATCH 267/342] chore(config): Deprecate allow_check_for_updates Fixes #2555 --- changelog.d/2556.misc.md | 1 + src/core/config/mod.rs | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 changelog.d/2556.misc.md diff --git a/changelog.d/2556.misc.md b/changelog.d/2556.misc.md new file mode 100644 index 000000000..6869942de --- /dev/null +++ b/changelog.d/2556.misc.md @@ -0,0 +1 @@ +The former configuration alias `allow_check_for_updates` is now explicitly deprecated in favor of `allow_announcements_check`. diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 43d991215..48fcb3d18 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -195,7 +195,7 @@ pub struct Config { /// announcements or major updates. This is not an update check endpoint. /// /// default: true - #[serde(alias = "allow_check_for_updates", default = "true_fn")] + #[serde(default = "true_fn")] pub allow_announcements_check: bool, /// Set this to any float value to multiply continuwuity's in-memory LRU @@ -2994,6 +2994,7 @@ impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter { const DEPRECATED_KEYS: &[&str] = &[ "cache_capacity", + "allow_check_for_updates", "conduit_cache_capacity_modifier", "max_concurrent_requests", "otlp_protocol", From 6cd38e4278f89cfc6e2bc4670019b1d25c3f8db7 Mon Sep 17 00:00:00 2001 From: Julian Anderson Date: Thu, 19 Nov 2026 21:46:24 -0500 Subject: [PATCH 268/342] chore(config): Alphabetize deprecated keys --- src/core/config/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 48fcb3d18..536193e10 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -2993,12 +2993,15 @@ impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter { } const DEPRECATED_KEYS: &[&str] = &[ - "cache_capacity", "allow_check_for_updates", + "allow_moderators_to_view_redacted_content", + "allow_sticky_events", + "cache_capacity", "conduit_cache_capacity_modifier", "max_concurrent_requests", "otlp_protocol", "roomid_spacehierarchy_cache_capacity", + "unredacted_content_max_age_secs", "well_known_client", "well_known_server", "well_known_support_page", @@ -3006,9 +3009,6 @@ const DEPRECATED_KEYS: &[&str] = &[ "well_known_support_email", "well_known_support_mxid", "well_known.rtc_focus_server_urls", - "allow_sticky_events", - "allow_moderators_to_view_redacted_content", - "unredacted_content_max_age_secs", ]; impl Config { From bd26b2d59659387f7d2fde7e98cb3947554313cb Mon Sep 17 00:00:00 2001 From: Julian Anderson Date: Fri, 20 Nov 2026 10:27:03 -0500 Subject: [PATCH 269/342] chore(config): Deprecate request_ip_source --- changelog.d/2556.misc.md | 2 +- conduwuit-example.toml | 7 ++++--- src/core/config/mod.rs | 8 +++++--- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/changelog.d/2556.misc.md b/changelog.d/2556.misc.md index 6869942de..8840924f8 100644 --- a/changelog.d/2556.misc.md +++ b/changelog.d/2556.misc.md @@ -1 +1 @@ -The former configuration alias `allow_check_for_updates` is now explicitly deprecated in favor of `allow_announcements_check`. +The former configuration alias `allow_check_for_updates` is now explicitly deprecated in favor of `allow_announcements_check`. Additionally, `request_ip_source` is now deprecated in favor of `accepted_ip_sources`. diff --git a/conduwuit-example.toml b/conduwuit-example.toml index c5a3edce6..e860a971c 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -412,7 +412,7 @@ # env: CONTINUWUITY_IP_LOOKUP_STRATEGY #ip_lookup_strategy = 5 -# The preferred source to use for getting the real client IP. +# DEPRECATED: The preferred source to use for getting the real client IP. # # Takes any of the following options: # @@ -431,9 +431,10 @@ # to set this header" check; if the header selected is present, it is # used. # -# Ignored if `accepted_ip_sources` is set. +# Ignored if `accepted_ip_sources` is set. `accepted_ip_sources` is +# the preferred alternative. # -# If not set set, `direct` is used. Additionally, `direct` is used +# If not set, `direct` is used. Additionally, `direct` is used # as a fallback if the chosen header is not found. # # env: CONTINUWUITY_REQUEST_IP_SOURCE diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 536193e10..56b0db526 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -490,7 +490,7 @@ pub struct Config { #[serde(default = "default_ip_lookup_strategy")] pub ip_lookup_strategy: u8, - /// The preferred source to use for getting the real client IP. + /// DEPRECATED: The preferred source to use for getting the real client IP. /// /// Takes any of the following options: /// @@ -509,9 +509,10 @@ pub struct Config { /// to set this header" check; if the header selected is present, it is /// used. /// - /// Ignored if `accepted_ip_sources` is set. + /// Ignored if `accepted_ip_sources` is set. `accepted_ip_sources` is + /// the preferred alternative. /// - /// If not set set, `direct` is used. Additionally, `direct` is used + /// If not set, `direct` is used. Additionally, `direct` is used /// as a fallback if the chosen header is not found. #[serde(default)] pub request_ip_source: Option, @@ -3000,6 +3001,7 @@ const DEPRECATED_KEYS: &[&str] = &[ "conduit_cache_capacity_modifier", "max_concurrent_requests", "otlp_protocol", + "request_ip_source", "roomid_spacehierarchy_cache_capacity", "unredacted_content_max_age_secs", "well_known_client", From c1b3c150342b6fee38c2d876f5b37c3253ea8bb6 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:19:42 +0000 Subject: [PATCH 270/342] fix(alloc): export malloc_conf as thin pointer and fix options --- src/core/alloc/je.rs | 46 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 584cda823..4420e62e4 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -17,21 +17,55 @@ use crate::{ }; #[cfg(feature = "jemalloc_conf")] -#[unsafe(no_mangle)] -pub static malloc_conf: &[u8] = const_str::concat_bytes!( +#[repr(transparent)] +struct MallocConf(*const c_char); + +// SAFETY: MallocConf points to static immutable NUL-terminated bytes. +#[cfg(feature = "jemalloc_conf")] +unsafe impl Sync for MallocConf {} + +#[cfg(feature = "jemalloc_conf")] +const MALLOC_CONF_BYTES: &[u8] = const_str::concat_bytes!( "lg_extent_max_active_fit:4", ",oversize_threshold:16777216", ",tcache_max:2097152", ",dirty_decay_ms:16000", ",muzzy_decay_ms:144000", - ",percpu_arena:percpu", - ",metadata_thp:always", - ",background_thread:true", - ",max_background_threads:-1", + MALLOC_CONF_PLATFORM, MALLOC_CONF_PROF, 0 ); +#[cfg(all(feature = "jemalloc_conf", target_os = "linux"))] +const MALLOC_CONF_PLATFORM: &str = ",percpu_arena:percpu,metadata_thp:always,background_thread:true"; +#[cfg(all(feature = "jemalloc_conf", not(target_os = "linux")))] +const MALLOC_CONF_PLATFORM: &str = ""; + +// Targets match `NO_UNPREFIXED_MALLOC_TARGETS` in `tikv-jemalloc-sys` when +// `unprefixed_malloc_on_supported_platforms` is enabled. +#[cfg(feature = "jemalloc_conf")] +#[used] +#[allow(non_upper_case_globals)] +#[cfg_attr( + any( + target_vendor = "apple", + target_env = "musl", + target_os = "android", + target_os = "dragonfly", + ), + unsafe(export_name = "_rjem_malloc_conf") +)] +#[cfg_attr( + not(any( + target_vendor = "apple", + target_env = "musl", + target_os = "android", + target_os = "dragonfly", + )), + unsafe(no_mangle) +)] +static malloc_conf: MallocConf = MallocConf(MALLOC_CONF_BYTES.as_ptr().cast()); + #[cfg(all(feature = "jemalloc_conf", feature = "jemalloc_prof"))] const MALLOC_CONF_PROF: &str = ",prof_active:false"; #[cfg(all(feature = "jemalloc_conf", not(feature = "jemalloc_prof")))] From 5169496cb603966304fa4913aa6be48027aea4fb Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:20:05 +0000 Subject: [PATCH 271/342] fix(alloc): avoid TLS and panics in jemalloc ctor and key lookup --- src/core/alloc/je.rs | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 4420e62e4..c6bc93294 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -4,6 +4,8 @@ use std::{ cell::OnceCell, ffi::{CStr, c_char, c_void}, fmt::Debug, + ptr, + sync::OnceLock, }; use arrayvec::ArrayVec; @@ -83,8 +85,19 @@ const KEY_SEGS: usize = 8; #[ctor::ctor(unsafe)] fn _static_initialization() { - acq_epoch().expect("pre-initialization of jemalloc failed"); - acq_epoch().expect("pre-initialization of jemalloc failed"); + let mut epoch: u64 = 0; + let mut len = size_of::(); + // SAFETY: Pre-initialize jemalloc before main() without touching Rust TLS + // or unwinding across the constructor boundary. + unsafe { + ffi::mallctl( + c"epoch".as_ptr(), + ptr::from_mut(&mut epoch).cast::(), + &raw mut len, + ptr::null_mut(), + 0, + ); + } } #[must_use] @@ -172,19 +185,15 @@ unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) { macro_rules! mallctl { ($name:expr_2021) => {{ - thread_local! { - static KEY: OnceCell = OnceCell::default(); - }; + static KEY: OnceLock = OnceLock::new(); - KEY.with(|once| { - once.get_or_init(move || key($name).expect("failed to translate name into mib key")) - .clone() - }) + KEY.get_or_init(|| key($name).expect("failed to translate name into mib key")) + .clone() }}; } pub mod this_thread { - use super::{Debug, Key, OnceCell, Result, is_nonzero, key, math}; + use super::{Debug, Key, OnceCell, OnceLock, Result, is_nonzero, key, math}; thread_local! { static ALLOCATED_BYTES: OnceCell<&'static u64> = const { OnceCell::new() }; @@ -397,7 +406,6 @@ where T: Copy + Debug, { acq_epoch()?; - acq_epoch()?; // SAFETY: T must be perfectly valid to receive value. unsafe { mallctl::raw::read_mib(key.as_slice()) }.map_err(map_err) @@ -421,6 +429,9 @@ fn key(name: &str) -> Result { // tikv asserts the output buffer length is tight to the number of required // mibs so we slice that down here. let segs = name.chars().filter(is_equal_to!(&'.')).count().try_add(1)?; + if segs > KEY_SEGS { + return Err(err!("mallctl: key has too many segments ({segs} > {KEY_SEGS})")); + } let name = self::name(name)?; let mut buf = [0_usize; KEY_SEGS]; @@ -430,6 +441,10 @@ fn key(name: &str) -> Result { } fn name(name: &str) -> Result { + if name.as_bytes().contains(&0) { + return Err(err!("mallctl: key contains interior NUL byte")); + } + let mut buf = Name::new(); buf.try_extend_from_slice(name.as_bytes())?; buf.try_extend_from_slice(b"\0")?; From 45b0a30155780abf7d467d0b6daf79c040fe65b5 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:20:27 +0000 Subject: [PATCH 272/342] fix(alloc): prevent leak, panic, and FFI unwind in memory_stats --- src/core/alloc/je.rs | 74 +++++++++++++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 25 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index c6bc93294..8bd0878cf 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -1,9 +1,11 @@ //! jemalloc allocator use std::{ + any::Any, cell::OnceCell, - ffi::{CStr, c_char, c_void}, + ffi::{CStr, CString, c_char, c_void}, fmt::Debug, + panic::{self, AssertUnwindSafe}, ptr, sync::OnceLock, }; @@ -104,10 +106,9 @@ fn _static_initialization() { #[cfg(feature = "jemalloc_stats")] pub fn memory_usage() -> Option { let mibs = |input: usize| { - let kibs = input / 1024; - let kibs = u32::try_from(kibs).unwrap_or_default(); - let kibs = f64::from(kibs); - kibs / 1024.0 + let whole = u32::try_from(input / (1024 * 1024)).unwrap_or(u32::MAX); + let rem_kibs = u32::try_from((input / 1024) % 1024).unwrap_or_default(); + f64::from(whole) + f64::from(rem_kibs) / 1024.0 }; let [allocated, active, mapped, metadata, resident, retained] = @@ -145,42 +146,65 @@ pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { #[cfg(not(feature = "jemalloc_stats"))] pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } +struct StatsPrintState { + buf: String, + max_len: usize, + panic: Option>, +} + pub fn memory_stats(opts: &str) -> Option { const MAX_LENGTH: usize = 1_048_576; - let mut str = String::new(); - let opaque = std::ptr::from_mut(&mut str).cast::(); - let opts_p: *const c_char = std::ffi::CString::new(opts) - .expect("cstring") - .into_raw() - .cast_const(); + let opts = CString::new(opts).ok()?; // Acquire the epoch; ensure latest stats are pulled in acq_epoch().ok()?; - // SAFETY: calls malloc_stats_print() with our string instance which must - // remain in this frame. https://docs.rs/tikv-jemalloc-sys/latest/tikv_jemalloc_sys/fn.malloc_stats_print.html - unsafe { ffi::malloc_stats_print(Some(malloc_stats_cb), opaque, opts_p) }; + let mut state = StatsPrintState { + buf: String::new(), + max_len: MAX_LENGTH, + panic: None, + }; + let opaque = ptr::from_mut(&mut state).cast::(); - str.truncate(MAX_LENGTH); + // SAFETY: `state` and `opts` remain live in this frame for the duration of + // `malloc_stats_print()`, which invokes `malloc_stats_cb` synchronously. + unsafe { ffi::malloc_stats_print(Some(malloc_stats_cb), opaque, opts.as_ptr()) }; - Some(str) + if let Some(payload) = state.panic { + panic::resume_unwind(payload); + } + + Some(state.buf) } unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) { - // SAFETY: we have to trust the opaque points to our String - let res: &mut String = unsafe { - opaque - .cast::() - .as_mut() - .expect("failed to cast void* to &mut String") + // SAFETY: `opaque` points to `StatsPrintState` on the caller's stack. + let Some(state) = (unsafe { opaque.cast::().as_mut() }) else { + return; }; - // SAFETY: we have to trust the string is null terminated. + if state.panic.is_some() || msg.is_null() || state.buf.len() >= state.max_len { + return; + } + + // SAFETY: jemalloc guarantees `msg` is a valid NUL-terminated C string. let msg = unsafe { CStr::from_ptr(msg) }; - let msg = String::from_utf8_lossy(msg.to_bytes()); - res.push_str(msg.as_ref()); + if let Err(err) = panic::catch_unwind(AssertUnwindSafe(|| { + let msg = String::from_utf8_lossy(msg.to_bytes()); + let remaining = state.max_len.saturating_sub(state.buf.len()); + if msg.len() <= remaining { + state.buf.push_str(msg.as_ref()); + } else { + if let Some(prefix) = msg.get(..msg.floor_char_boundary(remaining)) { + state.buf.push_str(prefix); + } + state.max_len = state.buf.len(); + } + })) { + state.panic = Some(err); + } } macro_rules! mallctl { From 3118183bd8f26a4835012a0af77d7b1b88d7977b Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:20:46 +0000 Subject: [PATCH 273/342] fix(alloc): fix UB and MIB aliasing in thread::allocated/deallocated --- src/core/alloc/je.rs | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 8bd0878cf..1aeb5257e 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -2,7 +2,6 @@ use std::{ any::Any, - cell::OnceCell, ffi::{CStr, CString, c_char, c_void}, fmt::Debug, panic::{self, AssertUnwindSafe}, @@ -208,7 +207,7 @@ unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) { } macro_rules! mallctl { - ($name:expr_2021) => {{ + ($name:literal) => {{ static KEY: OnceLock = OnceLock::new(); KEY.get_or_init(|| key($name).expect("failed to translate name into mib key")) @@ -217,12 +216,7 @@ macro_rules! mallctl { } pub mod this_thread { - use super::{Debug, Key, OnceCell, OnceLock, Result, is_nonzero, key, math}; - - thread_local! { - static ALLOCATED_BYTES: OnceCell<&'static u64> = const { OnceCell::new() }; - static DEALLOCATED_BYTES: OnceCell<&'static u64> = const { OnceCell::new() }; - } + use super::{Debug, Key, OnceLock, Result, is_nonzero, key, math}; pub fn trim() -> Result { decay().and_then(|()| purge()) } @@ -277,13 +271,13 @@ pub mod this_thread { #[inline] #[must_use] pub fn allocated() -> u64 { - *ALLOCATED_BYTES.with(|once| init_tls_cell(once, "thread.allocatedp")) + super::get(&mallctl!("thread.allocated")).unwrap_or_default() } #[inline] #[must_use] pub fn deallocated() -> u64 { - *DEALLOCATED_BYTES.with(|once| init_tls_cell(once, "thread.deallocatedp")) + super::get(&mallctl!("thread.deallocated")).unwrap_or_default() } fn notify(key: Key) -> Result { super::notify_by_arena(Some(arena_id()?), key) } @@ -301,16 +295,6 @@ pub mod this_thread { { super::get_by_arena(Some(arena_id()?), key) } - - fn init_tls_cell(cell: &OnceCell<&'static u64>, name: &str) -> &'static u64 { - cell.get_or_init(|| { - let ptr: *const u64 = super::get(&mallctl!(name)).expect("failed to obtain pointer"); - - // SAFETY: ptr points directly to the internal state of jemalloc for - // this thread - unsafe { ptr.as_ref() }.expect("pointer must not be null") - }) - } } pub fn stats_reset() -> Result { notify(&mallctl!("stats.mutexes.reset")) } From b9ceb008ba9461a3afc10228b2a2dd6f655de973 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:21:06 +0000 Subject: [PATCH 274/342] fix(alloc): pass NULL pointers in jemalloc notify ctls --- src/core/alloc/je.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 1aeb5257e..867bdef51 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -390,7 +390,25 @@ where get(&key) } -fn notify(key: &Key) -> Result { xchg(key, ()) } +fn notify(key: &Key) -> Result { + // SAFETY: jemalloc notification ctls require `oldp`, `oldlenp`, and `newp` + // to be NULL and `newlen` to be 0 (otherwise `EPERM` is returned). + let ret = unsafe { + ffi::mallctlbymib( + key.as_ptr(), + key.len(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + 0, + ) + }; + if ret == 0 { + Ok(()) + } else { + Err(err!("mallctl: {}", std::io::Error::from_raw_os_error(ret))) + } +} fn set(key: &Key, val: T) -> Result where From 180869ecff34eaccbf335505c391e59f84dcbf32 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:28:09 +0000 Subject: [PATCH 275/342] fix(alloc): validate arena index bounds before arena..* mallctls --- src/core/alloc/je.rs | 66 ++++++++++++++++++++++++++++---------------- 1 file changed, 42 insertions(+), 24 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 867bdef51..cb83b0bf6 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -83,6 +83,8 @@ type Key = ArrayVec; const NAME_MAX: usize = 128; const KEY_SEGS: usize = 8; +const ARENA_LIMIT: usize = 4095; +const ARENAS_ALL: usize = 4096; #[ctor::ctor(unsafe)] fn _static_initialization() { @@ -280,20 +282,30 @@ pub mod this_thread { super::get(&mallctl!("thread.deallocated")).unwrap_or_default() } - fn notify(key: Key) -> Result { super::notify_by_arena(Some(arena_id()?), key) } - - fn set(key: Key, val: T) -> Result - where - T: Copy + Debug, - { - super::set_by_arena(Some(arena_id()?), key, val) + // `key` must be an `arena..*` MIB (`key.len() >= 2`). `arena_id()` returns + // this thread's own valid arena (< narenas < ARENA_LIMIT), so we skip + // `validate_arena_id()` to avoid locking `ctl_mtx` on hot paths like `decay()`. + fn notify(mut key: Key) -> Result { + key[1] = arena_id()?; + super::notify(&key) } - fn get(key: Key) -> Result + fn set(mut key: Key, val: T) -> Result where T: Copy + Debug, { - super::get_by_arena(Some(arena_id()?), key) + // `arena_id()` is already a valid arena index; skip `validate_arena_id()`. + key[1] = arena_id()?; + super::set(&key, val) + } + + fn get(mut key: Key) -> Result + where + T: Copy + Debug, + { + // `arena_id()` is already a valid arena index; skip `validate_arena_id()`. + key[1] = arena_id()?; + super::get(&key) } } @@ -323,16 +335,14 @@ pub fn decay>>(arena: I) -> Result { pub fn set_muzzy_decay>>(arena: I, decay_ms: isize) -> Result { match arena.into() { - | Some(arena) => - set_by_arena(Some(arena), mallctl!("arena.4096.muzzy_decay_ms"), decay_ms), + | Some(arena) => set_by_arena(arena, mallctl!("arena.0.muzzy_decay_ms"), decay_ms), | _ => set(&mallctl!("arenas.muzzy_decay_ms"), decay_ms), } } pub fn set_dirty_decay>>(arena: I, decay_ms: isize) -> Result { match arena.into() { - | Some(arena) => - set_by_arena(Some(arena), mallctl!("arena.4096.dirty_decay_ms"), decay_ms), + | Some(arena) => set_by_arena(arena, mallctl!("arena.0.dirty_decay_ms"), decay_ms), | _ => set(&mallctl!("arenas.dirty_decay_ms"), decay_ms), } } @@ -369,27 +379,35 @@ pub fn inc_epoch() -> Result { xchg(&mallctl!("epoch"), 1_u64) } pub fn acq_epoch() -> Result { xchg(&mallctl!("epoch"), 0_u64) } +fn validate_arena_id(id: usize, allow_all: bool) -> Result { + if allow_all && id == ARENAS_ALL { + return Ok(id); + } + + let narenas = arenas()?.min(ARENA_LIMIT); + if id < narenas { + Ok(id) + } else { + Err(err!("mallctl: invalid arena index {id} (narenas: {narenas})")) + } +} + fn notify_by_arena(id: Option, mut key: Key) -> Result { - key[1] = id.unwrap_or(4096); + key[1] = match id { + | Some(id) => validate_arena_id(id, true)?, + | None => ARENAS_ALL, + }; notify(&key) } -fn set_by_arena(id: Option, mut key: Key, val: T) -> Result +fn set_by_arena(id: usize, mut key: Key, val: T) -> Result where T: Copy + Debug, { - key[1] = id.unwrap_or(4096); + key[1] = validate_arena_id(id, false)?; set(&key, val) } -fn get_by_arena(id: Option, mut key: Key) -> Result -where - T: Copy + Debug, -{ - key[1] = id.unwrap_or(4096); - get(&key) -} - fn notify(key: &Key) -> Result { // SAFETY: jemalloc notification ctls require `oldp`, `oldlenp`, and `newp` // to be NULL and `newlen` to be 0 (otherwise `EPERM` is returned). From e0b9bfdb73efd8b6224fa46dd295c15c4886b8e2 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:29:10 +0000 Subject: [PATCH 276/342] fix(alloc): mark raw mallctl helpers unsafe and check null in percpu_arenas --- src/core/alloc/je.rs | 214 +++++++++++++++++++++++++++++++------------ 1 file changed, 157 insertions(+), 57 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index cb83b0bf6..2ee2fba46 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -2,7 +2,7 @@ use std::{ any::Any, - ffi::{CStr, CString, c_char, c_void}, + ffi::{CStr, CString, c_char, c_uint, c_void}, fmt::Debug, panic::{self, AssertUnwindSafe}, ptr, @@ -218,107 +218,165 @@ macro_rules! mallctl { } pub mod this_thread { - use super::{Debug, Key, OnceLock, Result, is_nonzero, key, math}; + use super::{Debug, Key, OnceLock, Result, c_uint, is_nonzero, key, math}; pub fn trim() -> Result { decay().and_then(|()| purge()) } - pub fn purge() -> Result { notify(mallctl!("arena.0.purge")) } + pub fn purge() -> Result { + // SAFETY: `arena..purge` is an `arena..*` notification ctl. + unsafe { notify(mallctl!("arena.0.purge")) } + } - pub fn decay() -> Result { notify(mallctl!("arena.0.decay")) } + pub fn decay() -> Result { + // SAFETY: `arena..decay` is an `arena..*` notification ctl. + unsafe { notify(mallctl!("arena.0.decay")) } + } - pub fn idle() -> Result { super::notify(&mallctl!("thread.idle")) } + pub fn idle() -> Result { + // SAFETY: `thread.idle` is a non-indexed notification ctl. + unsafe { super::notify(&mallctl!("thread.idle")) } + } - pub fn flush() -> Result { super::notify(&mallctl!("thread.tcache.flush")) } + pub fn flush() -> Result { + // SAFETY: `thread.tcache.flush` is a non-indexed notification ctl. + unsafe { super::notify(&mallctl!("thread.tcache.flush")) } + } pub fn set_muzzy_decay(decay_ms: isize) -> Result { - set(mallctl!("arena.0.muzzy_decay_ms"), decay_ms) + // SAFETY: `arena..muzzy_decay_ms` has C type `ssize_t`. + unsafe { set(mallctl!("arena.0.muzzy_decay_ms"), decay_ms) } } - pub fn get_muzzy_decay() -> Result { get(mallctl!("arena.0.muzzy_decay_ms")) } + pub fn get_muzzy_decay() -> Result { + // SAFETY: `arena..muzzy_decay_ms` has C type `ssize_t`. + unsafe { get(mallctl!("arena.0.muzzy_decay_ms")) } + } pub fn set_dirty_decay(decay_ms: isize) -> Result { - set(mallctl!("arena.0.dirty_decay_ms"), decay_ms) + // SAFETY: `arena..dirty_decay_ms` has C type `ssize_t`. + unsafe { set(mallctl!("arena.0.dirty_decay_ms"), decay_ms) } } - pub fn get_dirty_decay() -> Result { get(mallctl!("arena.0.dirty_decay_ms")) } + pub fn get_dirty_decay() -> Result { + // SAFETY: `arena..dirty_decay_ms` has C type `ssize_t`. + unsafe { get(mallctl!("arena.0.dirty_decay_ms")) } + } pub fn cache_enable(enable: bool) -> Result { - super::set::(&mallctl!("thread.tcache.enabled"), enable.into()).map(is_nonzero!()) + // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on non-MSVC). + unsafe { super::set::(&mallctl!("thread.tcache.enabled"), enable.into()) } + .map(is_nonzero!()) } pub fn is_cache_enabled() -> Result { - super::get::(&mallctl!("thread.tcache.enabled")).map(is_nonzero!()) + // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on non-MSVC). + unsafe { super::get::(&mallctl!("thread.tcache.enabled")) }.map(is_nonzero!()) } pub fn set_arena(id: usize) -> Result { - super::set::(&mallctl!("thread.arena"), id.try_into()?).and_then(math::try_into) + // SAFETY: `thread.arena` has C type `unsigned`. + unsafe { super::set::(&mallctl!("thread.arena"), id.try_into()?) } + .and_then(math::try_into) } pub fn arena_id() -> Result { - super::get::(&mallctl!("thread.arena")).and_then(math::try_into) + // SAFETY: `thread.arena` has C type `unsigned`. + unsafe { super::get::(&mallctl!("thread.arena")) }.and_then(math::try_into) } pub fn prof_enable(enable: bool) -> Result { - super::set::(&mallctl!("thread.prof.active"), enable.into()).map(is_nonzero!()) + // SAFETY: `thread.prof.active` has C type `bool` (1 byte on non-MSVC). + unsafe { super::set::(&mallctl!("thread.prof.active"), enable.into()) } + .map(is_nonzero!()) } pub fn is_prof_enabled() -> Result { - super::get::(&mallctl!("thread.prof.active")).map(is_nonzero!()) + // SAFETY: `thread.prof.active` has C type `bool` (1 byte on non-MSVC). + unsafe { super::get::(&mallctl!("thread.prof.active")) }.map(is_nonzero!()) } - pub fn reset_peak() -> Result { super::notify(&mallctl!("thread.peak.reset")) } + pub fn reset_peak() -> Result { + // SAFETY: `thread.peak.reset` is a non-indexed notification ctl. + unsafe { super::notify(&mallctl!("thread.peak.reset")) } + } - pub fn peak() -> Result { super::get(&mallctl!("thread.peak.read")) } + pub fn peak() -> Result { + // SAFETY: `thread.peak.read` has C type `uint64_t`. + unsafe { super::get(&mallctl!("thread.peak.read")) } + } #[inline] #[must_use] pub fn allocated() -> u64 { - super::get(&mallctl!("thread.allocated")).unwrap_or_default() + // SAFETY: `thread.allocated` has C type `uint64_t`. + unsafe { super::get(&mallctl!("thread.allocated")) }.unwrap_or_default() } #[inline] #[must_use] pub fn deallocated() -> u64 { - super::get(&mallctl!("thread.deallocated")).unwrap_or_default() + // SAFETY: `thread.deallocated` has C type `uint64_t`. + unsafe { super::get(&mallctl!("thread.deallocated")) }.unwrap_or_default() } - // `key` must be an `arena..*` MIB (`key.len() >= 2`). `arena_id()` returns - // this thread's own valid arena (< narenas < ARENA_LIMIT), so we skip - // `validate_arena_id()` to avoid locking `ctl_mtx` on hot paths like `decay()`. - fn notify(mut key: Key) -> Result { + /// # Safety + /// Caller must ensure `key` is an `arena..*` notification MIB + /// (`key.len() >= 2`). + // `arena_id()` returns this thread's own valid arena (< narenas < ARENA_LIMIT), + // so we skip `validate_arena_id()` to avoid locking `ctl_mtx` on hot paths like + // `decay()`. + unsafe fn notify(mut key: Key) -> Result { key[1] = arena_id()?; - super::notify(&key) + // SAFETY: Caller guarantees `key` is an `arena..*` notification MIB + // and `arena_id()` returns a valid arena index. + unsafe { super::notify(&key) } } - fn set(mut key: Key, val: T) -> Result + /// # Safety + /// Caller must ensure `key` is an `arena..*` MIB and `T` matches its + /// exact C type. + unsafe fn set(mut key: Key, val: T) -> Result where T: Copy + Debug, { // `arena_id()` is already a valid arena index; skip `validate_arena_id()`. key[1] = arena_id()?; - super::set(&key, val) + // SAFETY: Caller guarantees `T` matches `key`. + unsafe { super::set(&key, val) } } - fn get(mut key: Key) -> Result + /// # Safety + /// Caller must ensure `key` is an `arena..*` MIB and `T` matches its + /// exact C type. + unsafe fn get(mut key: Key) -> Result where T: Copy + Debug, { // `arena_id()` is already a valid arena index; skip `validate_arena_id()`. key[1] = arena_id()?; - super::get(&key) + // SAFETY: Caller guarantees `T` matches `key`. + unsafe { super::get(&key) } } } -pub fn stats_reset() -> Result { notify(&mallctl!("stats.mutexes.reset")) } +pub fn stats_reset() -> Result { + // SAFETY: `stats.mutexes.reset` is a non-indexed notification ctl. + unsafe { notify(&mallctl!("stats.mutexes.reset")) } +} -pub fn prof_reset() -> Result { notify(&mallctl!("prof.reset")) } +pub fn prof_reset() -> Result { + // SAFETY: `prof.reset` is a non-indexed notification ctl. + unsafe { notify(&mallctl!("prof.reset")) } +} pub fn prof_enable(enable: bool) -> Result { - set::(&mallctl!("prof.active"), enable.into()).map(is_nonzero!()) + // SAFETY: `prof.active` has C type `bool` (1 byte on non-MSVC). + unsafe { set::(&mallctl!("prof.active"), enable.into()) }.map(is_nonzero!()) } pub fn is_prof_enabled() -> Result { - get::(&mallctl!("prof.active")).map(is_nonzero!()) + // SAFETY: `prof.active` has C type `bool` (1 byte on non-MSVC). + unsafe { get::(&mallctl!("prof.active")) }.map(is_nonzero!()) } pub fn trim> + Copy>(arena: I) -> Result { @@ -326,29 +384,40 @@ pub fn trim> + Copy>(arena: I) -> Result { } pub fn purge>>(arena: I) -> Result { - notify_by_arena(arena.into(), mallctl!("arena.4096.purge")) + // SAFETY: `arena..purge` is an `arena..*` notification ctl. + unsafe { notify_by_arena(arena.into(), mallctl!("arena.4096.purge")) } } pub fn decay>>(arena: I) -> Result { - notify_by_arena(arena.into(), mallctl!("arena.4096.decay")) + // SAFETY: `arena..decay` is an `arena..*` notification ctl. + unsafe { notify_by_arena(arena.into(), mallctl!("arena.4096.decay")) } } pub fn set_muzzy_decay>>(arena: I, decay_ms: isize) -> Result { match arena.into() { - | Some(arena) => set_by_arena(arena, mallctl!("arena.0.muzzy_decay_ms"), decay_ms), - | _ => set(&mallctl!("arenas.muzzy_decay_ms"), decay_ms), + // SAFETY: `arena..muzzy_decay_ms` has C type `ssize_t`. + | Some(arena) => unsafe { + set_by_arena(arena, mallctl!("arena.0.muzzy_decay_ms"), decay_ms) + }, + // SAFETY: `arenas.muzzy_decay_ms` has C type `ssize_t`. + | _ => unsafe { set(&mallctl!("arenas.muzzy_decay_ms"), decay_ms) }, } } pub fn set_dirty_decay>>(arena: I, decay_ms: isize) -> Result { match arena.into() { - | Some(arena) => set_by_arena(arena, mallctl!("arena.0.dirty_decay_ms"), decay_ms), - | _ => set(&mallctl!("arenas.dirty_decay_ms"), decay_ms), + // SAFETY: `arena..dirty_decay_ms` has C type `ssize_t`. + | Some(arena) => unsafe { + set_by_arena(arena, mallctl!("arena.0.dirty_decay_ms"), decay_ms) + }, + // SAFETY: `arenas.dirty_decay_ms` has C type `ssize_t`. + | _ => unsafe { set(&mallctl!("arenas.dirty_decay_ms"), decay_ms) }, } } pub fn background_thread_enable(enable: bool) -> Result { - set::(&mallctl!("background_thread"), enable.into()).map(is_nonzero!()) + // SAFETY: `background_thread` has C type `bool` (1 byte on non-MSVC). + unsafe { set::(&mallctl!("background_thread"), enable.into()) }.map(is_nonzero!()) } #[inline] @@ -364,20 +433,32 @@ pub fn is_percpu_arena() -> bool { percpu_arenas().is_ok_and(is_equal_to!("percp pub fn is_phycpu_arena() -> bool { percpu_arenas().is_ok_and(is_equal_to!("phycpu")) } pub fn percpu_arenas() -> Result<&'static str> { - let ptr = get::<*const c_char>(&mallctl!("opt.percpu_arena"))?; - //SAFETY: ptr points to a null-terminated string returned for - // opt.percpu_arena. + // SAFETY: `opt.percpu_arena` has C type `const char *`. + let ptr = unsafe { get::<*const c_char>(&mallctl!("opt.percpu_arena")) }?; + if ptr.is_null() { + return Err(err!("mallctl: opt.percpu_arena returned NULL")); + } + + // SAFETY: `ptr` is non-null and points to a static NUL-terminated string + // returned by jemalloc for `opt.percpu_arena`. let cstr = unsafe { CStr::from_ptr(ptr) }; cstr.to_str().map_err(Into::into) } pub fn arenas() -> Result { - get::(&mallctl!("arenas.narenas")).and_then(math::try_into) + // SAFETY: `arenas.narenas` has C type `unsigned`. + unsafe { get::(&mallctl!("arenas.narenas")) }.and_then(math::try_into) } -pub fn inc_epoch() -> Result { xchg(&mallctl!("epoch"), 1_u64) } +pub fn inc_epoch() -> Result { + // SAFETY: `epoch` has C type `uint64_t`. + unsafe { xchg(&mallctl!("epoch"), 1_u64) } +} -pub fn acq_epoch() -> Result { xchg(&mallctl!("epoch"), 0_u64) } +pub fn acq_epoch() -> Result { + // SAFETY: `epoch` has C type `uint64_t`. + unsafe { xchg(&mallctl!("epoch"), 0_u64) } +} fn validate_arena_id(id: usize, allow_all: bool) -> Result { if allow_all && id == ARENAS_ALL { @@ -392,23 +473,35 @@ fn validate_arena_id(id: usize, allow_all: bool) -> Result { } } -fn notify_by_arena(id: Option, mut key: Key) -> Result { +/// # Safety +/// Caller must ensure `key` is an `arena..*` notification MIB +/// (`key.len() >= 2`). +unsafe fn notify_by_arena(id: Option, mut key: Key) -> Result { key[1] = match id { | Some(id) => validate_arena_id(id, true)?, | None => ARENAS_ALL, }; - notify(&key) + // SAFETY: Caller guarantees `key` is an `arena..*` notification MIB and + // `key[1]` has been validated above. + unsafe { notify(&key) } } -fn set_by_arena(id: usize, mut key: Key, val: T) -> Result +/// # Safety +/// Caller must ensure `key` is an `arena..*` MIB (`key.len() >= 2`) and `T` +/// matches its exact C type. +unsafe fn set_by_arena(id: usize, mut key: Key, val: T) -> Result where T: Copy + Debug, { key[1] = validate_arena_id(id, false)?; - set(&key, val) + // SAFETY: Caller guarantees `T` matches `key`. + unsafe { set(&key, val) } } -fn notify(key: &Key) -> Result { +/// # Safety +/// Caller must ensure `key` is a valid notification MIB and any indexed arena +/// component is within bounds. +unsafe fn notify(key: &Key) -> Result { // SAFETY: jemalloc notification ctls require `oldp`, `oldlenp`, and `newp` // to be NULL and `newlen` to be 0 (otherwise `EPERM` is returned). let ret = unsafe { @@ -428,44 +521,51 @@ fn notify(key: &Key) -> Result { } } -fn set(key: &Key, val: T) -> Result +/// # Safety +/// Caller must ensure `T` matches the exact C type expected by `key`. +unsafe fn set(key: &Key, val: T) -> Result where T: Copy + Debug, { let _lock = CONTROL.write(); - let res = xchg(key, val)?; + // SAFETY: Caller guarantees `T` matches `key`. + let res = unsafe { xchg(key, val) }?; inc_epoch()?; Ok(res) } +/// # Safety +/// Caller must ensure `T` matches the exact C type expected by `key`. #[tracing::instrument( name = "get", level = "trace", skip_all, fields(?key) )] -fn get(key: &Key) -> Result +unsafe fn get(key: &Key) -> Result where T: Copy + Debug, { acq_epoch()?; - // SAFETY: T must be perfectly valid to receive value. + // SAFETY: Caller guarantees `T` matches the C type returned for `key`. unsafe { mallctl::raw::read_mib(key.as_slice()) }.map_err(map_err) } +/// # Safety +/// Caller must ensure `T` matches the exact C type expected by `key`. #[tracing::instrument( name = "xchg", level = "trace", skip_all, fields(?key, ?val) )] -fn xchg(key: &Key, val: T) -> Result +unsafe fn xchg(key: &Key, val: T) -> Result where T: Copy + Debug, { - // SAFETY: T must be the exact expected type. + // SAFETY: Caller guarantees `T` matches the C type expected by `key`. unsafe { mallctl::raw::update_mib(key.as_slice(), val) }.map_err(map_err) } From f46c87a40d40d50018a06ba6e2f65dcd3ec06882 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:30:05 +0000 Subject: [PATCH 277/342] fix(alloc): avoid unnecessary global epoch refreshes in mallctl get and memory_stats --- src/core/alloc/je.rs | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 2ee2fba46..98241aad4 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -15,7 +15,7 @@ use tikv_jemalloc_sys as ffi; use tikv_jemallocator as jemalloc; use crate::{ - Result, SyncRwLock, err, is_equal_to, is_nonzero, + Result, err, is_equal_to, is_nonzero, utils::{math, math::Tried}, }; @@ -76,7 +76,6 @@ const MALLOC_CONF_PROF: &str = ""; #[global_allocator] static JEMALLOC: jemalloc::Jemalloc = jemalloc::Jemalloc; -static CONTROL: SyncRwLock<()> = SyncRwLock::new(()); type Name = ArrayVec; type Key = ArrayVec; @@ -130,8 +129,8 @@ pub fn memory_usage() -> Option { None } pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { use mallctl::stats; - // Acquire the epoch; ensure latest stats are pulled in - acq_epoch().ok()?; + // Advance the epoch; ensure latest stats are pulled in + inc_epoch().ok()?; Some([ ("allocated", stats::allocated::read().unwrap_or_default()), @@ -158,9 +157,6 @@ pub fn memory_stats(opts: &str) -> Option { let opts = CString::new(opts).ok()?; - // Acquire the epoch; ensure latest stats are pulled in - acq_epoch().ok()?; - let mut state = StatsPrintState { buf: String::new(), max_len: MAX_LENGTH, @@ -457,7 +453,7 @@ pub fn inc_epoch() -> Result { pub fn acq_epoch() -> Result { // SAFETY: `epoch` has C type `uint64_t`. - unsafe { xchg(&mallctl!("epoch"), 0_u64) } + unsafe { get(&mallctl!("epoch")) } } fn validate_arena_id(id: usize, allow_all: bool) -> Result { @@ -523,16 +519,14 @@ unsafe fn notify(key: &Key) -> Result { /// # Safety /// Caller must ensure `T` matches the exact C type expected by `key`. +// Does not advance `epoch`; callers reading cached `stats.*` must call +// `inc_epoch()` explicitly. unsafe fn set(key: &Key, val: T) -> Result where T: Copy + Debug, { - let _lock = CONTROL.write(); // SAFETY: Caller guarantees `T` matches `key`. - let res = unsafe { xchg(key, val) }?; - inc_epoch()?; - - Ok(res) + unsafe { xchg(key, val) } } /// # Safety @@ -547,8 +541,6 @@ unsafe fn get(key: &Key) -> Result where T: Copy + Debug, { - acq_epoch()?; - // SAFETY: Caller guarantees `T` matches the C type returned for `key`. unsafe { mallctl::raw::read_mib(key.as_slice()) }.map_err(map_err) } From 318a0205b0cda55fba5c17596c50935523cf0815 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 01:36:59 +0000 Subject: [PATCH 278/342] perf(alloc): return &'static Key from mallctl! macro --- src/core/alloc/je.rs | 62 +++++++++++++++++++++++--------------------- 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 98241aad4..e9da2d721 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -209,7 +209,6 @@ macro_rules! mallctl { static KEY: OnceLock = OnceLock::new(); KEY.get_or_init(|| key($name).expect("failed to translate name into mib key")) - .clone() }}; } @@ -230,12 +229,12 @@ pub mod this_thread { pub fn idle() -> Result { // SAFETY: `thread.idle` is a non-indexed notification ctl. - unsafe { super::notify(&mallctl!("thread.idle")) } + unsafe { super::notify(mallctl!("thread.idle")) } } pub fn flush() -> Result { // SAFETY: `thread.tcache.flush` is a non-indexed notification ctl. - unsafe { super::notify(&mallctl!("thread.tcache.flush")) } + unsafe { super::notify(mallctl!("thread.tcache.flush")) } } pub fn set_muzzy_decay(decay_ms: isize) -> Result { @@ -260,59 +259,59 @@ pub mod this_thread { pub fn cache_enable(enable: bool) -> Result { // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on non-MSVC). - unsafe { super::set::(&mallctl!("thread.tcache.enabled"), enable.into()) } + unsafe { super::set::(mallctl!("thread.tcache.enabled"), enable.into()) } .map(is_nonzero!()) } pub fn is_cache_enabled() -> Result { // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on non-MSVC). - unsafe { super::get::(&mallctl!("thread.tcache.enabled")) }.map(is_nonzero!()) + unsafe { super::get::(mallctl!("thread.tcache.enabled")) }.map(is_nonzero!()) } pub fn set_arena(id: usize) -> Result { // SAFETY: `thread.arena` has C type `unsigned`. - unsafe { super::set::(&mallctl!("thread.arena"), id.try_into()?) } + unsafe { super::set::(mallctl!("thread.arena"), id.try_into()?) } .and_then(math::try_into) } pub fn arena_id() -> Result { // SAFETY: `thread.arena` has C type `unsigned`. - unsafe { super::get::(&mallctl!("thread.arena")) }.and_then(math::try_into) + unsafe { super::get::(mallctl!("thread.arena")) }.and_then(math::try_into) } pub fn prof_enable(enable: bool) -> Result { // SAFETY: `thread.prof.active` has C type `bool` (1 byte on non-MSVC). - unsafe { super::set::(&mallctl!("thread.prof.active"), enable.into()) } + unsafe { super::set::(mallctl!("thread.prof.active"), enable.into()) } .map(is_nonzero!()) } pub fn is_prof_enabled() -> Result { // SAFETY: `thread.prof.active` has C type `bool` (1 byte on non-MSVC). - unsafe { super::get::(&mallctl!("thread.prof.active")) }.map(is_nonzero!()) + unsafe { super::get::(mallctl!("thread.prof.active")) }.map(is_nonzero!()) } pub fn reset_peak() -> Result { // SAFETY: `thread.peak.reset` is a non-indexed notification ctl. - unsafe { super::notify(&mallctl!("thread.peak.reset")) } + unsafe { super::notify(mallctl!("thread.peak.reset")) } } pub fn peak() -> Result { // SAFETY: `thread.peak.read` has C type `uint64_t`. - unsafe { super::get(&mallctl!("thread.peak.read")) } + unsafe { super::get(mallctl!("thread.peak.read")) } } #[inline] #[must_use] pub fn allocated() -> u64 { // SAFETY: `thread.allocated` has C type `uint64_t`. - unsafe { super::get(&mallctl!("thread.allocated")) }.unwrap_or_default() + unsafe { super::get(mallctl!("thread.allocated")) }.unwrap_or_default() } #[inline] #[must_use] pub fn deallocated() -> u64 { // SAFETY: `thread.deallocated` has C type `uint64_t`. - unsafe { super::get(&mallctl!("thread.deallocated")) }.unwrap_or_default() + unsafe { super::get(mallctl!("thread.deallocated")) }.unwrap_or_default() } /// # Safety @@ -321,7 +320,8 @@ pub mod this_thread { // `arena_id()` returns this thread's own valid arena (< narenas < ARENA_LIMIT), // so we skip `validate_arena_id()` to avoid locking `ctl_mtx` on hot paths like // `decay()`. - unsafe fn notify(mut key: Key) -> Result { + unsafe fn notify(key: &Key) -> Result { + let mut key = key.clone(); key[1] = arena_id()?; // SAFETY: Caller guarantees `key` is an `arena..*` notification MIB // and `arena_id()` returns a valid arena index. @@ -331,10 +331,11 @@ pub mod this_thread { /// # Safety /// Caller must ensure `key` is an `arena..*` MIB and `T` matches its /// exact C type. - unsafe fn set(mut key: Key, val: T) -> Result + unsafe fn set(key: &Key, val: T) -> Result where T: Copy + Debug, { + let mut key = key.clone(); // `arena_id()` is already a valid arena index; skip `validate_arena_id()`. key[1] = arena_id()?; // SAFETY: Caller guarantees `T` matches `key`. @@ -344,10 +345,11 @@ pub mod this_thread { /// # Safety /// Caller must ensure `key` is an `arena..*` MIB and `T` matches its /// exact C type. - unsafe fn get(mut key: Key) -> Result + unsafe fn get(key: &Key) -> Result where T: Copy + Debug, { + let mut key = key.clone(); // `arena_id()` is already a valid arena index; skip `validate_arena_id()`. key[1] = arena_id()?; // SAFETY: Caller guarantees `T` matches `key`. @@ -357,22 +359,22 @@ pub mod this_thread { pub fn stats_reset() -> Result { // SAFETY: `stats.mutexes.reset` is a non-indexed notification ctl. - unsafe { notify(&mallctl!("stats.mutexes.reset")) } + unsafe { notify(mallctl!("stats.mutexes.reset")) } } pub fn prof_reset() -> Result { // SAFETY: `prof.reset` is a non-indexed notification ctl. - unsafe { notify(&mallctl!("prof.reset")) } + unsafe { notify(mallctl!("prof.reset")) } } pub fn prof_enable(enable: bool) -> Result { // SAFETY: `prof.active` has C type `bool` (1 byte on non-MSVC). - unsafe { set::(&mallctl!("prof.active"), enable.into()) }.map(is_nonzero!()) + unsafe { set::(mallctl!("prof.active"), enable.into()) }.map(is_nonzero!()) } pub fn is_prof_enabled() -> Result { // SAFETY: `prof.active` has C type `bool` (1 byte on non-MSVC). - unsafe { get::(&mallctl!("prof.active")) }.map(is_nonzero!()) + unsafe { get::(mallctl!("prof.active")) }.map(is_nonzero!()) } pub fn trim> + Copy>(arena: I) -> Result { @@ -396,7 +398,7 @@ pub fn set_muzzy_decay>>(arena: I, decay_ms: isize) -> Res set_by_arena(arena, mallctl!("arena.0.muzzy_decay_ms"), decay_ms) }, // SAFETY: `arenas.muzzy_decay_ms` has C type `ssize_t`. - | _ => unsafe { set(&mallctl!("arenas.muzzy_decay_ms"), decay_ms) }, + | _ => unsafe { set(mallctl!("arenas.muzzy_decay_ms"), decay_ms) }, } } @@ -407,13 +409,13 @@ pub fn set_dirty_decay>>(arena: I, decay_ms: isize) -> Res set_by_arena(arena, mallctl!("arena.0.dirty_decay_ms"), decay_ms) }, // SAFETY: `arenas.dirty_decay_ms` has C type `ssize_t`. - | _ => unsafe { set(&mallctl!("arenas.dirty_decay_ms"), decay_ms) }, + | _ => unsafe { set(mallctl!("arenas.dirty_decay_ms"), decay_ms) }, } } pub fn background_thread_enable(enable: bool) -> Result { // SAFETY: `background_thread` has C type `bool` (1 byte on non-MSVC). - unsafe { set::(&mallctl!("background_thread"), enable.into()) }.map(is_nonzero!()) + unsafe { set::(mallctl!("background_thread"), enable.into()) }.map(is_nonzero!()) } #[inline] @@ -430,7 +432,7 @@ pub fn is_phycpu_arena() -> bool { percpu_arenas().is_ok_and(is_equal_to!("phycp pub fn percpu_arenas() -> Result<&'static str> { // SAFETY: `opt.percpu_arena` has C type `const char *`. - let ptr = unsafe { get::<*const c_char>(&mallctl!("opt.percpu_arena")) }?; + let ptr = unsafe { get::<*const c_char>(mallctl!("opt.percpu_arena")) }?; if ptr.is_null() { return Err(err!("mallctl: opt.percpu_arena returned NULL")); } @@ -443,17 +445,17 @@ pub fn percpu_arenas() -> Result<&'static str> { pub fn arenas() -> Result { // SAFETY: `arenas.narenas` has C type `unsigned`. - unsafe { get::(&mallctl!("arenas.narenas")) }.and_then(math::try_into) + unsafe { get::(mallctl!("arenas.narenas")) }.and_then(math::try_into) } pub fn inc_epoch() -> Result { // SAFETY: `epoch` has C type `uint64_t`. - unsafe { xchg(&mallctl!("epoch"), 1_u64) } + unsafe { xchg(mallctl!("epoch"), 1_u64) } } pub fn acq_epoch() -> Result { // SAFETY: `epoch` has C type `uint64_t`. - unsafe { get(&mallctl!("epoch")) } + unsafe { get(mallctl!("epoch")) } } fn validate_arena_id(id: usize, allow_all: bool) -> Result { @@ -472,7 +474,8 @@ fn validate_arena_id(id: usize, allow_all: bool) -> Result { /// # Safety /// Caller must ensure `key` is an `arena..*` notification MIB /// (`key.len() >= 2`). -unsafe fn notify_by_arena(id: Option, mut key: Key) -> Result { +unsafe fn notify_by_arena(id: Option, key: &Key) -> Result { + let mut key = key.clone(); key[1] = match id { | Some(id) => validate_arena_id(id, true)?, | None => ARENAS_ALL, @@ -485,10 +488,11 @@ unsafe fn notify_by_arena(id: Option, mut key: Key) -> Result { /// # Safety /// Caller must ensure `key` is an `arena..*` MIB (`key.len() >= 2`) and `T` /// matches its exact C type. -unsafe fn set_by_arena(id: usize, mut key: Key, val: T) -> Result +unsafe fn set_by_arena(id: usize, key: &Key, val: T) -> Result where T: Copy + Debug, { + let mut key = key.clone(); key[1] = validate_arena_id(id, false)?; // SAFETY: Caller guarantees `T` matches `key`. unsafe { set(&key, val) } From f2a9e1f9931c7b07b0920dc0d01f1e93ddad56b8 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 00:21:26 +0000 Subject: [PATCH 279/342] test(alloc): add unit tests for jemalloc wrapper fixes --- src/core/alloc/je.rs | 99 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index e9da2d721..3b199adf5 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -595,3 +595,102 @@ fn name(name: &str) -> Result { fn map_err(error: tikv_jemalloc_ctl::Error) -> crate::Error { err!("mallctl: {}", error.to_string()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn notify_ctls_succeed() { + this_thread::flush().expect("thread.tcache.flush"); + this_thread::decay().expect("arena..decay"); + this_thread::purge().expect("arena..purge"); + this_thread::trim().expect("this_thread::trim"); + trim(None).expect("trim(None)"); + } + + #[test] + #[cfg(feature = "jemalloc_stats")] + fn allocated_and_deallocated_do_not_alias() { + let a0 = this_thread::allocated(); + let d0 = this_thread::deallocated(); + + let buf = std::hint::black_box(vec![0_u8; 64 * 1024]); + let a1 = this_thread::allocated(); + assert!(a1 > a0, "expected allocated to increase: {a0} -> {a1}"); + + drop(buf); + let d1 = this_thread::deallocated(); + assert!(d1 > d0, "expected deallocated to increase: {d0} -> {d1}"); + } + + #[test] + fn memory_stats_handles_valid_and_nul_opts() { + assert!(memory_stats("invalid\0opts").is_none()); + let stats = memory_stats("gmal").expect("memory_stats"); + assert!(!stats.is_empty()); + } + + #[test] + fn key_too_many_segments_returns_err() { + key("a.b.c.d.e.f.g.h.i").unwrap_err(); + } + + #[test] + fn key_interior_nul_returns_err() { + key("a.b\0.c").unwrap_err(); + } + + #[test] + fn arena_index_bounds_rejected() { + purge(Some(ARENAS_ALL)).expect("purge(MALLCTL_ARENAS_ALL)"); + decay(Some(ARENAS_ALL)).expect("decay(MALLCTL_ARENAS_ALL)"); + + let narenas = arenas().expect("arenas.narenas"); + purge(Some(narenas)).unwrap_err(); + decay(Some(narenas)).unwrap_err(); + set_dirty_decay(Some(narenas), -1).unwrap_err(); + set_muzzy_decay(Some(narenas), -1).unwrap_err(); + + purge(Some(4097)).unwrap_err(); + decay(Some(4097)).unwrap_err(); + trim(Some(4097)).unwrap_err(); + purge(Some(usize::MAX)).unwrap_err(); + + set_dirty_decay(Some(ARENAS_ALL), -1).unwrap_err(); + set_muzzy_decay(Some(ARENAS_ALL), -1).unwrap_err(); + set_dirty_decay(Some(4097), -1).unwrap_err(); + set_muzzy_decay(Some(4097), -1).unwrap_err(); + } + + #[test] + #[cfg(feature = "jemalloc_conf")] + fn malloc_conf_is_applied() { + if std::env::var_os("MALLOC_CONF").is_some() + || std::env::var_os("_RJEM_MALLOC_CONF").is_some() + { + return; + } + + // SAFETY: `opt.dirty_decay_ms` and `opt.muzzy_decay_ms` have C type `ssize_t`. + let dirty = unsafe { get::(mallctl!("opt.dirty_decay_ms")) } + .expect("opt.dirty_decay_ms"); + let muzzy = unsafe { get::(mallctl!("opt.muzzy_decay_ms")) } + .expect("opt.muzzy_decay_ms"); + assert_eq!(dirty, 16_000, "expected malloc_conf dirty_decay_ms:16000"); + assert_eq!(muzzy, 144_000, "expected malloc_conf muzzy_decay_ms:144000"); + } + + #[test] + fn percpu_arenas_returns_valid_mode() { + let mode = percpu_arenas().expect("opt.percpu_arena"); + assert!(matches!(mode, "disabled" | "percpu" | "phycpu"), "unexpected mode: {mode}"); + } + + #[test] + fn epoch_read_and_advance() { + let e0 = acq_epoch().expect("acq_epoch"); + let e1 = inc_epoch().expect("inc_epoch"); + assert!(e1 > e0, "expected inc_epoch to advance epoch: {e0} -> {e1}"); + } +} From 8375eb5a36607b880c99cf84352d745412bba0b1 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 01:18:52 +0000 Subject: [PATCH 280/342] chore(deps): Upgrade jemalloc with soundness fixes --- Cargo.lock | 12 ++++++------ Cargo.toml | 8 ++++---- docs/development/index.mdx | 5 +++-- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 861055021..67ee39a64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -497,7 +497,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] @@ -5189,7 +5189,7 @@ dependencies = [ [[package]] name = "rust-librocksdb-sys" version = "0.49.0+11.12.0" -source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=6021299f3e0e9455dc3f2e39c65e1dc217be8903#6021299f3e0e9455dc3f2e39c65e1dc217be8903" +source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b" dependencies = [ "bindgen", "bzip2-sys", @@ -5207,7 +5207,7 @@ dependencies = [ [[package]] name = "rust-rocksdb" version = "0.54.0" -source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=6021299f3e0e9455dc3f2e39c65e1dc217be8903#6021299f3e0e9455dc3f2e39c65e1dc217be8903" +source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b" dependencies = [ "libc", "parking_lot", @@ -6228,7 +6228,7 @@ dependencies = [ [[package]] name = "tikv-jemalloc-ctl" version = "0.7.0" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=ac4d4861b335b199f812807996e8c9166961041a#ac4d4861b335b199f812807996e8c9166961041a" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92" dependencies = [ "libc", "tikv-jemalloc-sys", @@ -6237,7 +6237,7 @@ dependencies = [ [[package]] name = "tikv-jemalloc-sys" version = "0.7.0+5.4.0-0-g7a34f18502e7b222724097cdcd499b437d189acc" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=ac4d4861b335b199f812807996e8c9166961041a#ac4d4861b335b199f812807996e8c9166961041a" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92" dependencies = [ "cc", "libc", @@ -6246,7 +6246,7 @@ dependencies = [ [[package]] name = "tikv-jemallocator" version = "0.7.0" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=ac4d4861b335b199f812807996e8c9166961041a#ac4d4861b335b199f812807996e8c9166961041a" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92" dependencies = [ "libc", "tikv-jemalloc-sys", diff --git a/Cargo.toml b/Cargo.toml index 4dbc03622..df89a71f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -407,7 +407,7 @@ features = [ [workspace.dependencies.rust-rocksdb] git = "https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1" -rev = "6021299f3e0e9455dc3f2e39c65e1dc217be8903" +rev = "85ded20348e3dab902c239967075795e9c6d101b" default-features = false features = [ "multi-threaded-cf", @@ -490,7 +490,7 @@ version = "0.49.5" # jemalloc usage [workspace.dependencies.tikv-jemalloc-sys] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "ac4d4861b335b199f812807996e8c9166961041a" +rev = "46e7821917b06636cdb5b203d312799970eaea92" default-features = false features = [ "background_threads_runtime_support", @@ -498,7 +498,7 @@ features = [ ] [workspace.dependencies.tikv-jemallocator] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "ac4d4861b335b199f812807996e8c9166961041a" +rev = "46e7821917b06636cdb5b203d312799970eaea92" default-features = false features = [ "background_threads_runtime_support", @@ -506,7 +506,7 @@ features = [ ] [workspace.dependencies.tikv-jemalloc-ctl] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "ac4d4861b335b199f812807996e8c9166961041a" +rev = "46e7821917b06636cdb5b203d312799970eaea92" default-features = false features = ["use_std"] diff --git a/docs/development/index.mdx b/docs/development/index.mdx index c1ff50026..280c25c64 100644 --- a/docs/development/index.mdx +++ b/docs/development/index.mdx @@ -84,8 +84,9 @@ All forked dependencies are maintained under the - [rocksdb][continuwuation-rocksdb] - Fork of [facebook/rocksdb][rocksdb] via [`@zaidoon1`][8] with liburing build fixes and GCC debug build fixes - [jemallocator][continuwuation-jemallocator] - Fork of - [tikv/jemallocator][jemallocator] fixing musl builds, suspicious code, and - adding support for redzones in Valgrind + [tikv/jemallocator][jemallocator] fixing musl builds and using jemalloc's + `*x` APIs consistently in `GlobalAlloc` to avoid interposer/Valgrind + mismatches - [rustyline-async][continuwuation-rustyline-async] - Fork of [zyansheep/rustyline-async][rustyline-async] with tab completion callback and `CTRL+\` signal quit event for Continuwuity console CLI From 094d24f82ed1fea2e2496013ea5083c4da78e585 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 13:33:55 +0000 Subject: [PATCH 281/342] docs(alloc): Fix interrupted doc comments in je.rs --- src/core/alloc/je.rs | 46 ++++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 3b199adf5..cad356f8e 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -40,7 +40,8 @@ const MALLOC_CONF_BYTES: &[u8] = const_str::concat_bytes!( ); #[cfg(all(feature = "jemalloc_conf", target_os = "linux"))] -const MALLOC_CONF_PLATFORM: &str = ",percpu_arena:percpu,metadata_thp:always,background_thread:true"; +const MALLOC_CONF_PLATFORM: &str = + ",percpu_arena:percpu,metadata_thp:always,background_thread:true"; #[cfg(all(feature = "jemalloc_conf", not(target_os = "linux")))] const MALLOC_CONF_PLATFORM: &str = ""; @@ -258,13 +259,15 @@ pub mod this_thread { } pub fn cache_enable(enable: bool) -> Result { - // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on non-MSVC). + // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on + // non-MSVC). unsafe { super::set::(mallctl!("thread.tcache.enabled"), enable.into()) } .map(is_nonzero!()) } pub fn is_cache_enabled() -> Result { - // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on non-MSVC). + // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on + // non-MSVC). unsafe { super::get::(mallctl!("thread.tcache.enabled")) }.map(is_nonzero!()) } @@ -317,11 +320,11 @@ pub mod this_thread { /// # Safety /// Caller must ensure `key` is an `arena..*` notification MIB /// (`key.len() >= 2`). - // `arena_id()` returns this thread's own valid arena (< narenas < ARENA_LIMIT), - // so we skip `validate_arena_id()` to avoid locking `ctl_mtx` on hot paths like - // `decay()`. unsafe fn notify(key: &Key) -> Result { let mut key = key.clone(); + // `arena_id()` returns this thread's own valid arena (< narenas < + // ARENA_LIMIT), so we skip `validate_arena_id()` to avoid locking + // `ctl_mtx` on hot paths like `decay()`. key[1] = arena_id()?; // SAFETY: Caller guarantees `key` is an `arena..*` notification MIB // and `arena_id()` returns a valid arena index. @@ -336,7 +339,8 @@ pub mod this_thread { T: Copy + Debug, { let mut key = key.clone(); - // `arena_id()` is already a valid arena index; skip `validate_arena_id()`. + // `arena_id()` is already a valid arena index; skip + // `validate_arena_id()`. key[1] = arena_id()?; // SAFETY: Caller guarantees `T` matches `key`. unsafe { super::set(&key, val) } @@ -350,7 +354,8 @@ pub mod this_thread { T: Copy + Debug, { let mut key = key.clone(); - // `arena_id()` is already a valid arena index; skip `validate_arena_id()`. + // `arena_id()` is already a valid arena index; skip + // `validate_arena_id()`. key[1] = arena_id()?; // SAFETY: Caller guarantees `T` matches `key`. unsafe { super::get(&key) } @@ -521,10 +526,11 @@ unsafe fn notify(key: &Key) -> Result { } } +/// Does not advance `epoch`; callers reading cached `stats.*` must call +/// `inc_epoch()` explicitly. +/// /// # Safety /// Caller must ensure `T` matches the exact C type expected by `key`. -// Does not advance `epoch`; callers reading cached `stats.*` must call -// `inc_epoch()` explicitly. unsafe fn set(key: &Key, val: T) -> Result where T: Copy + Debug, @@ -632,14 +638,10 @@ mod tests { } #[test] - fn key_too_many_segments_returns_err() { - key("a.b.c.d.e.f.g.h.i").unwrap_err(); - } + fn key_too_many_segments_returns_err() { key("a.b.c.d.e.f.g.h.i").unwrap_err(); } #[test] - fn key_interior_nul_returns_err() { - key("a.b\0.c").unwrap_err(); - } + fn key_interior_nul_returns_err() { key("a.b\0.c").unwrap_err(); } #[test] fn arena_index_bounds_rejected() { @@ -672,11 +674,13 @@ mod tests { return; } - // SAFETY: `opt.dirty_decay_ms` and `opt.muzzy_decay_ms` have C type `ssize_t`. - let dirty = unsafe { get::(mallctl!("opt.dirty_decay_ms")) } - .expect("opt.dirty_decay_ms"); - let muzzy = unsafe { get::(mallctl!("opt.muzzy_decay_ms")) } - .expect("opt.muzzy_decay_ms"); + // SAFETY: `opt.dirty_decay_ms` and `opt.muzzy_decay_ms` have C type + // `ssize_t`. + let dirty = + unsafe { get::(mallctl!("opt.dirty_decay_ms")) }.expect("opt.dirty_decay_ms"); + // SAFETY: Same as above + let muzzy = + unsafe { get::(mallctl!("opt.muzzy_decay_ms")) }.expect("opt.muzzy_decay_ms"); assert_eq!(dirty, 16_000, "expected malloc_conf dirty_decay_ms:16000"); assert_eq!(muzzy, 144_000, "expected malloc_conf muzzy_decay_ms:144000"); } From 61d77278f6d38380480240857585c5cfa155d674 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 13:36:35 +0000 Subject: [PATCH 282/342] chore: Add changelog --- changelog.d/2565.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2565.bugfix.md diff --git a/changelog.d/2565.bugfix.md b/changelog.d/2565.bugfix.md new file mode 100644 index 000000000..e47a8dc25 --- /dev/null +++ b/changelog.d/2565.bugfix.md @@ -0,0 +1 @@ +Fix soundness and correctness issues in the jemalloc interface, improving performance. Contributed by @Jade From 68068574d3a550191f332c2b74007ead4ac4553b Mon Sep 17 00:00:00 2001 From: timedout Date: Sat, 21 Nov 2026 01:52:39 +0000 Subject: [PATCH 283/342] fix(service/admin): Gate IsTerminal and warn imports on console feature --- src/service/admin/execute.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/service/admin/execute.rs b/src/service/admin/execute.rs index 3ab282740..0a6f64ff5 100644 --- a/src/service/admin/execute.rs +++ b/src/service/admin/execute.rs @@ -1,6 +1,7 @@ +#[cfg(feature = "console")] use std::io::IsTerminal; -use conduwuit::{Err, Result, debug, debug_info, error, info, warn}; +use conduwuit::{Err, Result, debug, debug_info, error, info}; use ruma::events::room::message::RoomMessageEventContent; use tokio::time::{Duration, sleep}; @@ -15,7 +16,7 @@ impl super::Service { #[cfg(feature = "console")] if self.services.server.config.admin_console_automatic { if !std::io::stdin().is_terminal() { - warn!("Console enabled without a tty available; Not enabling console"); + conduwuit::warn!("Console enabled without a tty available; Not enabling console"); return; } From d4ac77a023871edb83fe459f91fbd1197902e4cd Mon Sep 17 00:00:00 2001 From: timedout Date: Sat, 21 Nov 2026 01:52:39 +0000 Subject: [PATCH 284/342] feat: Add mimalloc support, drop hardened_malloc --- Cargo.lock | 26 +++++++++++++++++++------- Cargo.toml | 12 +++--------- src/core/Cargo.toml | 12 +++++------- src/core/alloc/hardened.rs | 18 ------------------ src/core/alloc/mimalloc.rs | 4 ++++ src/core/alloc/mod.rs | 27 +++++++-------------------- src/core/config/check.rs | 6 +++--- src/main/Cargo.toml | 7 +++---- 8 files changed, 44 insertions(+), 68 deletions(-) delete mode 100644 src/core/alloc/hardened.rs create mode 100644 src/core/alloc/mimalloc.rs diff --git a/Cargo.lock b/Cargo.lock index 67ee39a64..891a1c340 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -991,7 +991,6 @@ dependencies = [ "figment", "futures", "governor", - "hardened_malloc-rs", "http", "http-body-util", "hyper-util", @@ -1001,6 +1000,7 @@ dependencies = [ "libloading 0.9.1", "lock_api 0.5.0", "maplit", + "mimalloc", "nix", "num-traits", "openidconnect", @@ -2395,12 +2395,6 @@ dependencies = [ "tokio-util", ] -[[package]] -name = "hardened_malloc-rs" -version = "0.1.2+12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "647deb1583b14d160f85f3ff626f20b6edd366e3852c9843b06077388f794cb6" - [[package]] name = "hashbrown" version = "0.12.3" @@ -3256,6 +3250,15 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + [[package]] name = "libz-sys" version = "1.1.32" @@ -3429,6 +3432,15 @@ dependencies = [ "walkdir", ] +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + [[package]] name = "mime" version = "0.3.18" diff --git a/Cargo.toml b/Cargo.toml index df89a71f0..57ca88ac6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -522,15 +522,6 @@ features = ["resource"] version = "0.5.0" default-features = false -[workspace.dependencies.hardened_malloc-rs] -version = "0.1.2" -default-features = false -features = [ - "static", - "gcc", - "light", -] - [workspace.dependencies.rustyline-async] version = "0.4.9" default-features = false @@ -610,6 +601,9 @@ features = ["unstable-msc4188"] [workspace.dependencies.serde_urlencoded] version = "0.7.1" +[workspace.dependencies.mimalloc] +version = "0.1.52" + # # Patches # diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 335ba023a..00f59a9e0 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -26,14 +26,14 @@ conduwuit_mods = [ gzip_compression = [ "reqwest/gzip", ] -hardened_malloc = [ - "dep:hardened_malloc-rs" -] jemalloc = [ "dep:tikv-jemalloc-sys", "dep:tikv-jemalloc-ctl", "dep:tikv-jemallocator", ] +mimalloc = [ + "dep:mimalloc", +] jemalloc_conf = [] jemalloc_prof = [ "tikv-jemalloc-sys/profiling", @@ -118,14 +118,12 @@ lock_api.workspace = true hyper-util.workspace = true resolvematrix.workspace = true openidconnect.workspace = true +mimalloc.optional = true +mimalloc.workspace = true [target.'cfg(unix)'.dependencies] nix.workspace = true -[target.'cfg(all(not(target_env = "msvc"), target_os = "linux"))'.dependencies] -hardened_malloc-rs.workspace = true -hardened_malloc-rs.optional = true - [dev-dependencies] maplit.workspace = true opentelemetry_sdk.workspace = true diff --git a/src/core/alloc/hardened.rs b/src/core/alloc/hardened.rs deleted file mode 100644 index 69628ba7d..000000000 --- a/src/core/alloc/hardened.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! hmalloc allocator - -#[global_allocator] -static HMALLOC: hardened_malloc_rs::HardenedMalloc = hardened_malloc_rs::HardenedMalloc; - -pub fn trim>>(_: I) -> crate::Result { Ok(()) } - -#[must_use] -//TODO: get usage -pub fn memory_usage() -> Option { None } - -#[must_use] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } - -#[must_use] -pub fn memory_stats(_opts: &str) -> Option { - Some("Extended statistics are not available from hardened_malloc.".to_owned()) -} diff --git a/src/core/alloc/mimalloc.rs b/src/core/alloc/mimalloc.rs new file mode 100644 index 000000000..272a4081a --- /dev/null +++ b/src/core/alloc/mimalloc.rs @@ -0,0 +1,4 @@ +use mimalloc::MiMalloc; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; diff --git a/src/core/alloc/mod.rs b/src/core/alloc/mod.rs index a34809412..f137771e7 100644 --- a/src/core/alloc/mod.rs +++ b/src/core/alloc/mod.rs @@ -1,27 +1,14 @@ //! Integration with allocators -// jemalloc -#[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] +pub mod default; + +#[cfg(feature = "jemalloc")] pub mod je; -#[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] +#[cfg(feature = "jemalloc")] pub use je::{memory_stats, memory_usage, memory_usage_stats, trim}; -#[cfg(all(not(target_env = "msvc"), feature = "hardened_malloc", not(feature = "jemalloc")))] -pub mod hardened; -#[cfg(all( - not(target_env = "msvc"), - feature = "hardened_malloc", - not(feature = "jemalloc") -))] -pub use hardened::{memory_stats, memory_usage, memory_usage_stats, trim}; +#[cfg(all(feature = "mimalloc", not(feature = "jemalloc")))] +pub mod mimalloc; -#[cfg(any( - target_env = "msvc", - all(not(feature = "hardened_malloc"), not(feature = "jemalloc")) -))] -pub mod default; -#[cfg(any( - target_env = "msvc", - all(not(feature = "hardened_malloc"), not(feature = "jemalloc")) -))] +#[cfg(not(feature = "jemalloc"))] pub use default::{memory_stats, memory_usage, memory_usage_stats, trim}; diff --git a/src/core/config/check.rs b/src/core/config/check.rs index 1e3efdb5e..e7aa6649b 100644 --- a/src/core/config/check.rs +++ b/src/core/config/check.rs @@ -43,10 +43,10 @@ pub fn check(config: &Config) -> Result { )); } - if cfg!(all(feature = "hardened_malloc", feature = "jemalloc", not(target_env = "msvc"))) { + if cfg!(all(feature = "mimalloc", feature = "jemalloc")) { debug_warn!( - "hardened_malloc and jemalloc compile-time features are both enabled, this causes \ - jemalloc to be used." + "mimalloc and jemalloc compile-time features are both enabled, this causes jemalloc \ + to be used." ); } diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index 18cc054a7..db155c5bd 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -70,7 +70,6 @@ standard = [ ] full = [ "standard", - # "hardened_malloc", # Conflicts with jemalloc "jemalloc_prof", "perf_measurements", "tokio_console", @@ -96,9 +95,6 @@ gzip_compression = [ "conduwuit-router/gzip_compression", "conduwuit-service/gzip_compression", ] -hardened_malloc = [ - "conduwuit-core/hardened_malloc", -] http3 = [ "conduwuit-service/http3" ] @@ -116,6 +112,9 @@ jemalloc = [ "conduwuit-core/jemalloc", "conduwuit-service/jemalloc", ] +mimalloc = [ + "conduwuit-core/mimalloc" +] jemalloc_prof = [ "conduwuit-core/jemalloc_prof", ] From a27a5bed294127363a34fb7fab5438719f7567ab Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:10:36 +0000 Subject: [PATCH 285/342] fix(alloc): Restore not(target_env = "msvc") cfg gates and gate default module --- src/core/alloc/mod.rs | 15 +++++++++------ src/core/config/check.rs | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/core/alloc/mod.rs b/src/core/alloc/mod.rs index f137771e7..16b7bfe5e 100644 --- a/src/core/alloc/mod.rs +++ b/src/core/alloc/mod.rs @@ -1,14 +1,17 @@ //! Integration with allocators -pub mod default; - -#[cfg(feature = "jemalloc")] +// jemalloc +#[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] pub mod je; -#[cfg(feature = "jemalloc")] +#[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] pub use je::{memory_stats, memory_usage, memory_usage_stats, trim}; -#[cfg(all(feature = "mimalloc", not(feature = "jemalloc")))] +// mimalloc +#[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] pub mod mimalloc; -#[cfg(not(feature = "jemalloc"))] +// default +#[cfg(any(target_env = "msvc", not(feature = "jemalloc")))] +pub mod default; +#[cfg(any(target_env = "msvc", not(feature = "jemalloc")))] pub use default::{memory_stats, memory_usage, memory_usage_stats, trim}; diff --git a/src/core/config/check.rs b/src/core/config/check.rs index e7aa6649b..2c6f98912 100644 --- a/src/core/config/check.rs +++ b/src/core/config/check.rs @@ -43,7 +43,7 @@ pub fn check(config: &Config) -> Result { )); } - if cfg!(all(feature = "mimalloc", feature = "jemalloc")) { + if cfg!(all(feature = "mimalloc", feature = "jemalloc", not(target_env = "msvc"))) { debug_warn!( "mimalloc and jemalloc compile-time features are both enabled, this causes jemalloc \ to be used." From 8a20a5c3498b0462479f52e5a90c9254a2bc5ad7 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:13:13 +0000 Subject: [PATCH 286/342] fix(config): Warn in release builds when both mimalloc and jemalloc are enabled --- src/core/config/check.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/config/check.rs b/src/core/config/check.rs index 2c6f98912..70a403d06 100644 --- a/src/core/config/check.rs +++ b/src/core/config/check.rs @@ -5,7 +5,7 @@ use figment::Figment; use ruma::{OwnedServerName, events::room::server_acl::RoomServerAclEventContent}; use super::DEPRECATED_KEYS; -use crate::{Config, Err, Result, Server, debug, debug_info, debug_warn, error, warn}; +use crate::{Config, Err, Result, Server, debug, debug_info, error, warn}; /// Performs check() with additional checks specific to reloading old config /// with new config. @@ -44,7 +44,7 @@ pub fn check(config: &Config) -> Result { } if cfg!(all(feature = "mimalloc", feature = "jemalloc", not(target_env = "msvc"))) { - debug_warn!( + warn!( "mimalloc and jemalloc compile-time features are both enabled, this causes jemalloc \ to be used." ); From 6df7dda32909040798f255e5dbdea0383f56b372 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:24:59 +0000 Subject: [PATCH 287/342] feat(alloc): Implement trim, memory_usage, and memory_stats for mimalloc --- Cargo.lock | 8 ++++ Cargo.toml | 5 +++ src/core/Cargo.toml | 3 ++ src/core/alloc/mimalloc.rs | 85 +++++++++++++++++++++++++++++++++++++- src/core/alloc/mod.rs | 6 ++- 5 files changed, 104 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 891a1c340..8f8d5fbd4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -998,6 +998,7 @@ dependencies = [ "lettre", "libc", "libloading 0.9.1", + "libmimalloc-sys", "lock_api 0.5.0", "maplit", "mimalloc", @@ -1552,6 +1553,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "cty" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b365fabc795046672053e29c954733ec3b05e4be654ab130fe8f1f94d7051f35" + [[package]] name = "curve25519-dalek" version = "5.0.0" @@ -3257,6 +3264,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" dependencies = [ "cc", + "cty", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 57ca88ac6..7870336b4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -603,6 +603,11 @@ version = "0.7.1" [workspace.dependencies.mimalloc] version = "0.1.52" +features = ["extended"] + +[workspace.dependencies.libmimalloc-sys] +version = "0.1.49" +features = ["extended"] # # Patches diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 00f59a9e0..b4aa779a8 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -32,6 +32,7 @@ jemalloc = [ "dep:tikv-jemallocator", ] mimalloc = [ + "dep:libmimalloc-sys", "dep:mimalloc", ] jemalloc_conf = [] @@ -118,6 +119,8 @@ lock_api.workspace = true hyper-util.workspace = true resolvematrix.workspace = true openidconnect.workspace = true +libmimalloc-sys.optional = true +libmimalloc-sys.workspace = true mimalloc.optional = true mimalloc.workspace = true diff --git a/src/core/alloc/mimalloc.rs b/src/core/alloc/mimalloc.rs index 272a4081a..c12c0f843 100644 --- a/src/core/alloc/mimalloc.rs +++ b/src/core/alloc/mimalloc.rs @@ -1,4 +1,87 @@ +//! mimalloc allocator + +use std::ptr; + +use libmimalloc_sys as ffi; use mimalloc::MiMalloc; #[global_allocator] -static GLOBAL: MiMalloc = MiMalloc; +static MIMALLOC: MiMalloc = MiMalloc; + +pub fn trim>>(_: I) -> crate::Result { + // SAFETY: `mi_collect` is thread-safe and takes a single boolean flag. + unsafe { + ffi::mi_collect(true); + } + + Ok(()) +} + +#[must_use] +pub fn memory_usage() -> Option { + let mut current_rss = 0; + let mut peak_rss = 0; + let mut current_commit = 0; + let mut peak_commit = 0; + + // SAFETY: All non-null out-pointers are valid writable `usize` stack slots; + // null pointers are explicitly permitted by `mi_process_info`. + unsafe { + ffi::mi_process_info( + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + &raw mut current_rss, + &raw mut peak_rss, + &raw mut current_commit, + &raw mut peak_commit, + ptr::null_mut(), + ); + } + + let mibs = |input: usize| { + let whole = u32::try_from(input / (1024 * 1024)).unwrap_or(u32::MAX); + let rem_kibs = u32::try_from((input / 1024) % 1024).unwrap_or_default(); + f64::from(whole) + f64::from(rem_kibs) / 1024.0 + }; + + Some(format!( + "current_rss: {:.2} MiB\npeak_rss: {:.2} MiB\ncurrent_commit: {:.2} MiB\npeak_commit: \ + {:.2} MiB\n", + mibs(current_rss), + mibs(peak_rss), + mibs(current_commit), + mibs(peak_commit), + )) +} + +#[must_use] +pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } + +#[must_use] +pub fn memory_stats(_opts: &str) -> Option { + MiMalloc::stats_json() + .ok() + .and_then(|stats| stats.to_str().ok().map(str::to_owned)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trim_succeeds() { trim(None).expect("trim(None)"); } + + #[test] + fn memory_usage_returns_rss_and_commit() { + let usage = memory_usage().expect("memory_usage"); + assert!(usage.contains("current_rss:"), "unexpected usage: {usage}"); + assert!(usage.contains("current_commit:"), "unexpected usage: {usage}"); + } + + #[test] + fn memory_stats_returns_json() { + let stats = memory_stats("").expect("memory_stats"); + assert!(stats.starts_with('{'), "expected JSON object, got: {stats}"); + } +} diff --git a/src/core/alloc/mod.rs b/src/core/alloc/mod.rs index 16b7bfe5e..fe3441b74 100644 --- a/src/core/alloc/mod.rs +++ b/src/core/alloc/mod.rs @@ -9,9 +9,11 @@ pub use je::{memory_stats, memory_usage, memory_usage_stats, trim}; // mimalloc #[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] pub mod mimalloc; +#[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] +pub use mimalloc::{memory_stats, memory_usage, memory_usage_stats, trim}; // default -#[cfg(any(target_env = "msvc", not(feature = "jemalloc")))] +#[cfg(all(not(feature = "mimalloc"), any(target_env = "msvc", not(feature = "jemalloc"))))] pub mod default; -#[cfg(any(target_env = "msvc", not(feature = "jemalloc")))] +#[cfg(all(not(feature = "mimalloc"), any(target_env = "msvc", not(feature = "jemalloc"))))] pub use default::{memory_stats, memory_usage, memory_usage_stats, trim}; From c6b9854c494d570bfefa4a5660ca4338bd39b7fa Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:27:14 +0000 Subject: [PATCH 288/342] docs(main): Clarify mimalloc feature scope and jemalloc precedence --- src/main/Cargo.toml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index db155c5bd..6c403f3b6 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -112,8 +112,12 @@ jemalloc = [ "conduwuit-core/jemalloc", "conduwuit-service/jemalloc", ] +# Sets Rust's #[global_allocator] to mimalloc (C/C++ libraries such as RocksDB +# still use system libc malloc). On non-MSVC targets, `jemalloc` takes +# precedence if both are enabled, so build with `--no-default-features` and +# omit `jemalloc`/`standard` to use mimalloc. mimalloc = [ - "conduwuit-core/mimalloc" + "conduwuit-core/mimalloc", ] jemalloc_prof = [ "conduwuit-core/jemalloc_prof", From 43cf8cccdf55ab13a7c7a855bbb0d341946d92d2 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 14:12:45 +0000 Subject: [PATCH 289/342] refactor: Unify memory stats and create feature parity --- docs/guides/metrics.mdx | 1 + src/admin/debug/commands.rs | 8 +- src/admin/debug/mod.rs | 3 +- src/core/alloc/default.rs | 6 +- src/core/alloc/je.rs | 30 ++-- src/core/alloc/mimalloc.rs | 241 +++++++++++++++++++++++++------- src/core/alloc/mod.rs | 6 + src/core/metrics/instruments.rs | 8 +- src/core/metrics/tests.rs | 20 +++ 9 files changed, 259 insertions(+), 64 deletions(-) diff --git a/docs/guides/metrics.mdx b/docs/guides/metrics.mdx index cb5df8c70..de01db04a 100644 --- a/docs/guides/metrics.mdx +++ b/docs/guides/metrics.mdx @@ -82,6 +82,7 @@ Names below are as they appear in Prometheus. OTLP uses the dotted OpenTelemetry | `continuwuity_database_block_cache_bytes` | gauge | `column` | RocksDB block cache usage | | `continuwuity_cache_entries` | gauge | `name` | Entries in the auth chain and state info caches | | `continuwuity_jemalloc_memory_bytes` | gauge | `kind` | jemalloc statistics, only with the `jemalloc_stats` feature | +| `continuwuity_mimalloc_memory_bytes` | gauge | `kind` | mimalloc statistics, only with the `mimalloc` feature | | `process_uptime_seconds` | gauge | | Time since the server started | | `process_cpu_time_seconds_total` | counter | `cpu_mode` | CPU time used by the process | | `process_memory_usage_bytes` | gauge | | Resident memory (Linux) | diff --git a/src/admin/debug/commands.rs b/src/admin/debug/commands.rs index 3109730cb..8846ffbaa 100644 --- a/src/admin/debug/commands.rs +++ b/src/admin/debug/commands.rs @@ -1007,7 +1007,7 @@ impl crate::Context<'_> { pub(super) async fn memory_stats(&self, opts: Option) -> Result { const OPTS: &str = "abcdefghijklmnopqrstuvwxyz"; - let opts: String = OPTS + let mut mapped_opts: String = OPTS .chars() .filter(|&c| { let allow_any = opts.as_ref().is_some_and(|opts| opts == "*"); @@ -1018,7 +1018,11 @@ impl crate::Context<'_> { }) .collect(); - let stats = conduwuit::alloc::memory_stats(&opts).unwrap_or_default(); + if opts.as_ref().is_some_and(|opts| opts.contains('J')) { + mapped_opts.push('J'); + } + + let stats = conduwuit::alloc::memory_stats(&mapped_opts).unwrap_or_default(); self.write_str("```\n").await?; self.write_str(&stats).await?; diff --git a/src/admin/debug/mod.rs b/src/admin/debug/mod.rs index 9bf3647b3..85a1c3a77 100644 --- a/src/admin/debug/mod.rs +++ b/src/admin/debug/mod.rs @@ -192,7 +192,8 @@ pub enum DebugCommand { /// /// Optional argument is a character mask (a sequence of characters in any /// order) which enable additional extended statistics. Known characters are - /// "abdeglmx". For convenience, a '*' will enable everything. + /// "abdeglmx" and 'J' for JSON output. For convenience, a '*' will enable + /// everything. MemoryStats { opts: Option, }, diff --git a/src/core/alloc/default.rs b/src/core/alloc/default.rs index 7d6f94e34..23d56e5b2 100644 --- a/src/core/alloc/default.rs +++ b/src/core/alloc/default.rs @@ -1,5 +1,9 @@ //! Default allocator with no special features +use arrayvec::ArrayVec; + +pub(crate) fn metric() -> Option<(&'static str, &'static str)> { None } + /// Always returns Ok pub fn trim>>(_: I) -> crate::Result { Ok(()) } @@ -12,4 +16,4 @@ pub fn memory_stats(_opts: &str) -> Option { None } pub fn memory_usage() -> Option { None } #[must_use] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } +pub fn memory_usage_stats() -> Option> { None } diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index cad356f8e..dc92c1a1e 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -103,22 +103,30 @@ fn _static_initialization() { } } +pub(crate) fn metric() -> Option<(&'static str, &'static str)> { + Some(( + "continuwuity.jemalloc.memory", + "jemalloc memory statistics, when built with jemalloc_stats", + )) +} + #[must_use] #[cfg(feature = "jemalloc_stats")] pub fn memory_usage() -> Option { + use std::fmt::Write; + let mibs = |input: usize| { let whole = u32::try_from(input / (1024 * 1024)).unwrap_or(u32::MAX); let rem_kibs = u32::try_from((input / 1024) % 1024).unwrap_or_default(); f64::from(whole) + f64::from(rem_kibs) / 1024.0 }; - let [allocated, active, mapped, metadata, resident, retained] = - memory_usage_stats()?.map(|(_, bytes)| mibs(bytes)); - Some(format!( - "allocated: {allocated:.2} MiB\nactive: {active:.2} MiB\nmapped: {mapped:.2} \ - MiB\nmetadata: {metadata:.2} MiB\nresident: {resident:.2} MiB\nretained: {retained:.2} \ - MiB\n" - )) + let mut out = String::new(); + for (name, bytes) in memory_usage_stats()? { + writeln!(out, "{name}: {:.2} MiB", mibs(bytes)).ok()?; + } + + Some(out) } #[must_use] @@ -127,25 +135,25 @@ pub fn memory_usage() -> Option { None } #[must_use] #[cfg(feature = "jemalloc_stats")] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { +pub fn memory_usage_stats() -> Option> { use mallctl::stats; // Advance the epoch; ensure latest stats are pulled in inc_epoch().ok()?; - Some([ + Some(ArrayVec::from([ ("allocated", stats::allocated::read().unwrap_or_default()), ("active", stats::active::read().unwrap_or_default()), ("mapped", stats::mapped::read().unwrap_or_default()), ("metadata", stats::metadata::read().unwrap_or_default()), ("resident", stats::resident::read().unwrap_or_default()), ("retained", stats::retained::read().unwrap_or_default()), - ]) + ])) } #[must_use] #[cfg(not(feature = "jemalloc_stats"))] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } +pub fn memory_usage_stats() -> Option> { None } struct StatsPrintState { buf: String, diff --git a/src/core/alloc/mimalloc.rs b/src/core/alloc/mimalloc.rs index c12c0f843..495fc0879 100644 --- a/src/core/alloc/mimalloc.rs +++ b/src/core/alloc/mimalloc.rs @@ -1,68 +1,165 @@ //! mimalloc allocator -use std::ptr; +use std::{ + any::Any, + ffi::{CStr, c_void}, + panic::{self, AssertUnwindSafe}, + ptr, +}; +use arrayvec::ArrayVec; use libmimalloc_sys as ffi; use mimalloc::MiMalloc; +use serde::Deserialize; #[global_allocator] static MIMALLOC: MiMalloc = MiMalloc; +#[derive(Deserialize)] +struct StatCount { + current: i64, + peak: i64, +} + +#[derive(Deserialize)] +struct Stats { + reserved: StatCount, + committed: StatCount, + purged: i64, + reset: i64, +} + +trait OutputFnChar { + type Char; +} + +impl OutputFnChar for Option { + type Char = C; +} + +type MiChar = ::Char; + +struct StatsPrintState { + buf: String, + max_len: usize, + panic: Option>, +} + +pub(crate) fn metric() -> Option<(&'static str, &'static str)> { + Some(("continuwuity.mimalloc.memory", "mimalloc memory statistics")) +} + pub fn trim>>(_: I) -> crate::Result { // SAFETY: `mi_collect` is thread-safe and takes a single boolean flag. - unsafe { - ffi::mi_collect(true); - } + unsafe { ffi::mi_collect(true) }; Ok(()) } +fn read_stats() -> Option { + let stats = MiMalloc::stats_json().ok()?; + let json = stats.to_str().ok()?; + serde_json::from_str(json).ok() +} + +fn non_neg_usize(value: i64) -> usize { usize::try_from(value.max(0)).unwrap_or(usize::MAX) } + +fn mibs(input: usize) -> f64 { + let whole = u32::try_from(input / (1024 * 1024)).unwrap_or(u32::MAX); + let rem_kibs = u32::try_from((input / 1024) % 1024).unwrap_or_default(); + f64::from(whole) + f64::from(rem_kibs) / 1024.0 +} + #[must_use] pub fn memory_usage() -> Option { - let mut current_rss = 0; - let mut peak_rss = 0; - let mut current_commit = 0; - let mut peak_commit = 0; - - // SAFETY: All non-null out-pointers are valid writable `usize` stack slots; - // null pointers are explicitly permitted by `mi_process_info`. - unsafe { - ffi::mi_process_info( - ptr::null_mut(), - ptr::null_mut(), - ptr::null_mut(), - &raw mut current_rss, - &raw mut peak_rss, - &raw mut current_commit, - &raw mut peak_commit, - ptr::null_mut(), - ); - } - - let mibs = |input: usize| { - let whole = u32::try_from(input / (1024 * 1024)).unwrap_or(u32::MAX); - let rem_kibs = u32::try_from((input / 1024) % 1024).unwrap_or_default(); - f64::from(whole) + f64::from(rem_kibs) / 1024.0 - }; + let stats = read_stats()?; Some(format!( - "current_rss: {:.2} MiB\npeak_rss: {:.2} MiB\ncurrent_commit: {:.2} MiB\npeak_commit: \ - {:.2} MiB\n", - mibs(current_rss), - mibs(peak_rss), - mibs(current_commit), - mibs(peak_commit), + "reserved: {:.2} MiB\nreserved_peak: {:.2} MiB\ncommitted: {:.2} MiB\ncommitted_peak: \ + {:.2} MiB\npurged_total: {:.2} MiB\nreset_total: {:.2} MiB\n", + mibs(non_neg_usize(stats.reserved.current)), + mibs(non_neg_usize(stats.reserved.peak)), + mibs(non_neg_usize(stats.committed.current)), + mibs(non_neg_usize(stats.committed.peak)), + mibs(non_neg_usize(stats.purged)), + mibs(non_neg_usize(stats.reset)), )) } #[must_use] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } +pub fn memory_usage_stats() -> Option> { + let stats = read_stats()?; + let mut out = ArrayVec::new(); + out.extend([ + ("reserved", non_neg_usize(stats.reserved.current)), + ("reserved_peak", non_neg_usize(stats.reserved.peak)), + ("committed", non_neg_usize(stats.committed.current)), + ("committed_peak", non_neg_usize(stats.committed.peak)), + ]); + + Some(out) +} #[must_use] -pub fn memory_stats(_opts: &str) -> Option { - MiMalloc::stats_json() - .ok() - .and_then(|stats| stats.to_str().ok().map(str::to_owned)) +pub fn memory_stats(opts: &str) -> Option { + const MAX_LENGTH: usize = 1_048_576; + + if opts.contains('\0') { + return None; + } + + if opts.contains('J') { + let stats = MiMalloc::stats_json().ok()?; + let json = String::from_utf8_lossy(stats.to_bytes()); + let end = json.floor_char_boundary(json.len().min(MAX_LENGTH)); + return json.get(..end).map(str::to_owned); + } + + let mut state = StatsPrintState { + buf: String::new(), + max_len: MAX_LENGTH, + panic: None, + }; + let opaque = ptr::from_mut(&mut state).cast::(); + + // SAFETY: `state` remains live in this frame for the duration of + // `mi_stats_print_out()`, which invokes `mi_stats_cb` synchronously. + unsafe { ffi::mi_stats_print_out(Some(mi_stats_cb), opaque) }; + + if let Some(payload) = state.panic { + panic::resume_unwind(payload); + } + + Some(state.buf) +} + +unsafe extern "C" fn mi_stats_cb(msg: *const MiChar, arg: *mut c_void) { + // SAFETY: `arg` points to `StatsPrintState` on the caller's stack. + let Some(state) = (unsafe { arg.cast::().as_mut() }) else { + return; + }; + + if state.panic.is_some() || msg.is_null() || state.buf.len() >= state.max_len { + return; + } + + // SAFETY: mimalloc guarantees `msg` is a valid NUL-terminated C string. + let msg = unsafe { CStr::from_ptr(msg.cast()) }; + + if let Err(err) = panic::catch_unwind(AssertUnwindSafe(|| { + let msg = String::from_utf8_lossy(msg.to_bytes()); + let remaining = state.max_len.saturating_sub(state.buf.len()); + if msg.len() <= remaining { + state.buf.push_str(msg.as_ref()); + } else { + if let Some(prefix) = msg.get(..msg.floor_char_boundary(remaining)) { + state.buf.push_str(prefix); + } + state.max_len = state.buf.len(); + } + })) { + state.panic = Some(err); + } } #[cfg(test)] @@ -73,15 +170,65 @@ mod tests { fn trim_succeeds() { trim(None).expect("trim(None)"); } #[test] - fn memory_usage_returns_rss_and_commit() { - let usage = memory_usage().expect("memory_usage"); - assert!(usage.contains("current_rss:"), "unexpected usage: {usage}"); - assert!(usage.contains("current_commit:"), "unexpected usage: {usage}"); + fn non_neg_usize_clamps_negative_values() { + assert_eq!(non_neg_usize(-1), 0, "expected -1 to clamp to 0"); + assert_eq!(non_neg_usize(i64::MIN), 0, "expected i64::MIN to clamp to 0"); + assert_eq!(non_neg_usize(0), 0, "expected 0 to remain 0"); + assert_eq!(non_neg_usize(4096), 4096, "expected positive value unchanged"); } #[test] - fn memory_stats_returns_json() { - let stats = memory_stats("").expect("memory_stats"); - assert!(stats.starts_with('{'), "expected JSON object, got: {stats}"); + fn memory_usage_stats_reports_allocator_bytes() { + let buf = std::hint::black_box(vec![0_u8; 64 * 1024]); + let stats = memory_usage_stats().expect("memory_usage_stats"); + drop(buf); + + let keys: Vec<_> = stats.iter().map(|&(key, _)| key).collect(); + assert_eq!( + keys, + ["reserved", "reserved_peak", "committed", "committed_peak"], + "unexpected stat keys" + ); + + for (key, bytes) in stats { + assert!(bytes > 0, "expected {key} > 0, got {bytes}"); + } + } + + #[test] + fn memory_usage_returns_allocator_summary() { + let usage = memory_usage().expect("memory_usage"); + for expected in [ + "reserved:", + "reserved_peak:", + "committed:", + "committed_peak:", + "purged_total:", + "reset_total:", + "MiB", + ] { + assert!(usage.contains(expected), "missing {expected:?} in usage:\n{usage}"); + } + assert!(!usage.contains("current_rss:"), "unexpected current_rss in usage:\n{usage}"); + assert!(!usage.contains("peak_rss:"), "unexpected peak_rss in usage:\n{usage}"); + } + + #[test] + fn memory_stats_supports_text_json_and_rejects_nul() { + assert!(memory_stats("invalid\0opts").is_none(), "expected NUL opts to return None"); + + for opts in ["", "abcdefghijklmnopqrstuvwxyz"] { + let stats = memory_stats(opts).expect("memory_stats text"); + assert!(!stats.is_empty(), "expected non-empty stats for opts={opts:?}"); + assert!(!stats.starts_with('{'), "expected formatted text, got JSON:\n{stats}"); + assert!(stats.contains("reserved"), "missing reserved in stats:\n{stats}"); + assert!(stats.contains("committed"), "missing committed in stats:\n{stats}"); + } + + let json = memory_stats("J").expect("memory_stats JSON"); + assert!(json.starts_with('{'), "expected JSON object, got:\n{json}"); + let parsed: serde_json::Value = + serde_json::from_str(&json).expect("expected valid JSON from memory_stats(\"J\")"); + assert!(parsed.get("committed").is_some(), "expected committed field in JSON"); } } diff --git a/src/core/alloc/mod.rs b/src/core/alloc/mod.rs index fe3441b74..3acfb43a0 100644 --- a/src/core/alloc/mod.rs +++ b/src/core/alloc/mod.rs @@ -4,16 +4,22 @@ #[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] pub mod je; #[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] +pub(crate) use je::metric; +#[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] pub use je::{memory_stats, memory_usage, memory_usage_stats, trim}; // mimalloc #[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] pub mod mimalloc; #[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] +pub(crate) use mimalloc::metric; +#[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] pub use mimalloc::{memory_stats, memory_usage, memory_usage_stats, trim}; // default #[cfg(all(not(feature = "mimalloc"), any(target_env = "msvc", not(feature = "jemalloc"))))] pub mod default; #[cfg(all(not(feature = "mimalloc"), any(target_env = "msvc", not(feature = "jemalloc"))))] +pub(crate) use default::metric; +#[cfg(all(not(feature = "mimalloc"), any(target_env = "msvc", not(feature = "jemalloc"))))] pub use default::{memory_stats, memory_usage, memory_usage_stats, trim}; diff --git a/src/core/metrics/instruments.rs b/src/core/metrics/instruments.rs index b9ba973b2..10bff549a 100644 --- a/src/core/metrics/instruments.rs +++ b/src/core/metrics/instruments.rs @@ -196,9 +196,13 @@ fn register_process(meter: &Meter) { } fn register_allocator(meter: &Meter) { + let Some((name, description)) = crate::alloc::metric() else { + return; + }; + meter - .u64_observable_gauge("continuwuity.jemalloc.memory") - .with_description("jemalloc memory statistics, when built with jemalloc_stats") + .u64_observable_gauge(name) + .with_description(description) .with_unit("By") .with_callback(|observer| { for (kind, bytes) in crate::alloc::memory_usage_stats().into_iter().flatten() { diff --git a/src/core/metrics/tests.rs b/src/core/metrics/tests.rs index fdbe52c9d..3f13d8bd5 100644 --- a/src/core/metrics/tests.rs +++ b/src/core/metrics/tests.rs @@ -38,3 +38,23 @@ async fn renders_prometheus_names() { } assert!(!body.contains("otel_scope_name")); } + +#[tokio::test] +#[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] +async fn renders_mimalloc_memory_metric() { + let (metrics, _provider) = metrics(); + let body = metrics.render().unwrap(); + + for expected in [ + "continuwuity_mimalloc_memory_bytes{kind=\"reserved\"}", + "continuwuity_mimalloc_memory_bytes{kind=\"reserved_peak\"}", + "continuwuity_mimalloc_memory_bytes{kind=\"committed\"}", + "continuwuity_mimalloc_memory_bytes{kind=\"committed_peak\"}", + ] { + assert!(body.contains(expected), "missing {expected:?} in:\n{body}"); + } + assert!( + !body.contains("continuwuity_jemalloc_memory_bytes"), + "unexpected jemalloc metric in mimalloc build:\n{body}" + ); +} From d4aec6ca5cb3a6753443d0d0eed6ebded5f91152 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 14:54:10 +0000 Subject: [PATCH 290/342] fix: Use mimalloc for c/c++ code by default --- src/core/Cargo.toml | 4 ++++ src/core/alloc/mod.rs | 2 ++ src/core/config/check.rs | 7 ------- src/main/Cargo.toml | 4 ---- 4 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index b4aa779a8..48a0f2e9e 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -31,9 +31,13 @@ jemalloc = [ "dep:tikv-jemalloc-ctl", "dep:tikv-jemallocator", ] +# Uses mimalloc for Rust allocations and, via `override`, exports +# malloc/free/etc. so C/C++ dependencies (RocksDB, zstd, lz4, ...) use it too. +# Mutually exclusive with `jemalloc` on non-MSVC targets. mimalloc = [ "dep:libmimalloc-sys", "dep:mimalloc", + "libmimalloc-sys/override", ] jemalloc_conf = [] jemalloc_prof = [ diff --git a/src/core/alloc/mod.rs b/src/core/alloc/mod.rs index 3acfb43a0..c7e8dd49d 100644 --- a/src/core/alloc/mod.rs +++ b/src/core/alloc/mod.rs @@ -9,6 +9,8 @@ pub(crate) use je::metric; pub use je::{memory_stats, memory_usage, memory_usage_stats, trim}; // mimalloc +#[cfg(all(feature = "mimalloc", feature = "jemalloc", not(target_env = "msvc")))] +compile_error!("the `mimalloc` and `jemalloc` features are mutually exclusive"); #[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] pub mod mimalloc; #[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] diff --git a/src/core/config/check.rs b/src/core/config/check.rs index 70a403d06..146e149e7 100644 --- a/src/core/config/check.rs +++ b/src/core/config/check.rs @@ -43,13 +43,6 @@ pub fn check(config: &Config) -> Result { )); } - if cfg!(all(feature = "mimalloc", feature = "jemalloc", not(target_env = "msvc"))) { - warn!( - "mimalloc and jemalloc compile-time features are both enabled, this causes jemalloc \ - to be used." - ); - } - if cfg!(not(unix)) && config.unix_socket_path.is_some() { return Err!(Config( "unix_socket_path", diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index 6c403f3b6..c4477721f 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -112,10 +112,6 @@ jemalloc = [ "conduwuit-core/jemalloc", "conduwuit-service/jemalloc", ] -# Sets Rust's #[global_allocator] to mimalloc (C/C++ libraries such as RocksDB -# still use system libc malloc). On non-MSVC targets, `jemalloc` takes -# precedence if both are enabled, so build with `--no-default-features` and -# omit `jemalloc`/`standard` to use mimalloc. mimalloc = [ "conduwuit-core/mimalloc", ] From cb9b3e65d0341f8f1f07847a026568ed6f35b17c Mon Sep 17 00:00:00 2001 From: timedout Date: Sat, 21 Nov 2026 15:15:28 +0000 Subject: [PATCH 291/342] chore: Add newsfrag --- changelog.d/2564.feature.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2564.feature.md diff --git a/changelog.d/2564.feature.md b/changelog.d/2564.feature.md new file mode 100644 index 000000000..ad2f99eb2 --- /dev/null +++ b/changelog.d/2564.feature.md @@ -0,0 +1 @@ +Dropped support for `hardened_malloc` and add support for `mimalloc` instead. Contributed by @nex and @jade. From 973cfd57467035bac7f8c3b0b5a3d7f34c6b453f Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 20 Nov 2026 12:48:12 -0500 Subject: [PATCH 292/342] fix: Log OIDC registrations in the admin room --- src/service/oidc/mod.rs | 5 +++-- src/web/pages/oidc/complete.rs | 9 +++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/service/oidc/mod.rs b/src/service/oidc/mod.rs index a05168b75..a1632baf9 100644 --- a/src/service/oidc/mod.rs +++ b/src/service/oidc/mod.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration}; +use std::{collections::HashMap, net::IpAddr, str::FromStr, sync::Arc, time::Duration}; use async_trait::async_trait; use conduwuit::{ @@ -359,6 +359,7 @@ impl Service { &self, claims: &Claims, supplied_user_id: Option, + client_ip: &IpAddr, ) -> Result { let Some(OidcClient { config, .. }) = self.client.as_ref() else { return Err("Delegated authentication is not enabled on this server."); @@ -419,7 +420,7 @@ impl Service { // Create a new shadow user self.services .users - .create_local_account(&user_id, None, None, None, None) + .create_local_account(&user_id, None, None, Some(client_ip), None) .await .map_err(|err| { error!("Failed to create a shadow user for {user_id}: {err}"); diff --git a/src/web/pages/oidc/complete.rs b/src/web/pages/oidc/complete.rs index 32a0d342d..f2e116eb8 100644 --- a/src/web/pages/oidc/complete.rs +++ b/src/web/pages/oidc/complete.rs @@ -6,6 +6,7 @@ use axum::{ response::Redirect, routing::on, }; +use conduwuit_api::client_ip::ClientIp; use conduwuit_service::{ oauth::grant::AuthorizationCodeResponse, oidc::{ClaimedLocalUser, SessionCompletionStatus}, @@ -63,6 +64,7 @@ async fn route_complete( Expect(Query(query)): Expect>, session_store: Session, user: User, + ClientIp(client_ip): ClientIp, PostForm(form): PostForm, ) -> Result { let user_id = user.into_session().map(|session| session.user_id); @@ -104,7 +106,10 @@ async fn route_complete( .await .expect("should be able to serialize oidc session"); - services.oidc.complete_session(&claims, None).await + services + .oidc + .complete_session(&claims, None, &client_ip) + .await }, | OidcSessionState::Authorized { claims } => { let supplied_user_id = if let Some(form) = form { @@ -163,7 +168,7 @@ async fn route_complete( services .oidc - .complete_session(&claims, supplied_user_id) + .complete_session(&claims, supplied_user_id, &client_ip) .await }, } From 7408d539776780e11d60206ddfca200cbf2ed1db Mon Sep 17 00:00:00 2001 From: Ginger Date: Fri, 20 Nov 2026 12:52:40 -0500 Subject: [PATCH 293/342] chore: News fragment --- changelog.d/2561.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2561.bugfix.md diff --git a/changelog.d/2561.bugfix.md b/changelog.d/2561.bugfix.md new file mode 100644 index 000000000..783bb173a --- /dev/null +++ b/changelog.d/2561.bugfix.md @@ -0,0 +1 @@ +A message is now sent to the admin room when a user logs in for the first time through an OIDC provider, if admin room notices are enabled. Contributed by @ginger. From 798bef5bc7df9f578045beafae096815eb55cf15 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sat, 21 Nov 2026 05:02:37 +0000 Subject: [PATCH 294/342] chore(deps): update node-patch-updates to v2.1.4 --- package-lock.json | 235 ++++++++++++++++++++++++++-------------------- 1 file changed, 131 insertions(+), 104 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5908fcd3c..7802c4951 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,21 +16,21 @@ } }, "node_modules/@emnapi/core": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", - "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", + "version": "2.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.3.tgz", + "integrity": "sha512-KA+gOBtbifRATmUa/Gpf5C2B2EJ0r4brHUT3XSgACeHREcuiObXH56xd+B3fFsEFbUT04VBEe6MuZiCtMp0tQg==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/wasi-threads": "1.2.3", + "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" } }, "node_modules/@emnapi/runtime": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", - "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "version": "2.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.3.tgz", + "integrity": "sha512-ayb/PyyLzpwRyFVxeC0uoEHu59QlB1iWGcGsOpXQcaB/Dc+uGfBmNmpCHp3HmTT0t8lSsMmg3j7+tdJW/TlHjQ==", "dev": true, "license": "MIT", "optional": true, @@ -39,9 +39,9 @@ } }, "node_modules/@emnapi/wasi-threads": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", - "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", "dev": true, "license": "MIT", "optional": true, @@ -106,33 +106,36 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", - "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", + "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", "dev": true, "license": "MIT", "optional": true, "dependencies": { "@tybys/wasm-util": "^0.10.3" }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, "funding": { "type": "github", "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" } }, "node_modules/@rsbuild/core": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.1.tgz", - "integrity": "sha512-dv5tL7djb8ex5z4sqnDmUbd5PnGNr/CXuFfiMD4RkUsF1JEZZkGH8lc+QW4fqYQIHM7RTvcMUakgvwVU/O9WMw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.3.tgz", + "integrity": "sha512-IdbBXZrIY16RxnQduXRrsRBQtJ/X7JkYESrk6D46WA918wrckYTBxE09vHvDxR+3JoCLE02vOm2NPBNxqaUw5A==", "dev": true, "license": "MIT", "dependencies": { - "@rspack/core": "~2.3.1", - "@swc/helpers": "^0.5.23" + "@rspack/core": "~2.3.3", + "@swc/helpers": "^0.5.24" }, "bin": { "rsbuild": "bin/rsbuild.js" @@ -169,32 +172,32 @@ } }, "node_modules/@rspack/binding": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.1.tgz", - "integrity": "sha512-pfCJGBFNK2tnNnoDP6ZoTbOjxbKr1U2eGFDJ8bIuZQai4FBNhWQlKFmNup+X5K935XYRulZBomIBAL6GL6W2YQ==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.3.tgz", + "integrity": "sha512-wwF++36a3rqYi0G9zj+rUavn/GIMzbzXehelGS1jkYeKPHyPXrVYwRHqwEKNKMD9z+FdW4YJKQcfFkPlHEiwUg==", "dev": true, "license": "MIT", "optionalDependencies": { - "@rspack/binding-darwin-arm64": "2.3.1", - "@rspack/binding-darwin-x64": "2.3.1", - "@rspack/binding-linux-arm64-gnu": "2.3.1", - "@rspack/binding-linux-arm64-musl": "2.3.1", - "@rspack/binding-linux-ppc64-gnu": "2.3.1", - "@rspack/binding-linux-riscv64-gnu": "2.3.1", - "@rspack/binding-linux-riscv64-musl": "2.3.1", - "@rspack/binding-linux-s390x-gnu": "2.3.1", - "@rspack/binding-linux-x64-gnu": "2.3.1", - "@rspack/binding-linux-x64-musl": "2.3.1", - "@rspack/binding-wasm32-wasi": "2.3.1", - "@rspack/binding-win32-arm64-msvc": "2.3.1", - "@rspack/binding-win32-ia32-msvc": "2.3.1", - "@rspack/binding-win32-x64-msvc": "2.3.1" + "@rspack/binding-darwin-arm64": "2.3.3", + "@rspack/binding-darwin-x64": "2.3.3", + "@rspack/binding-linux-arm64-gnu": "2.3.3", + "@rspack/binding-linux-arm64-musl": "2.3.3", + "@rspack/binding-linux-ppc64-gnu": "2.3.3", + "@rspack/binding-linux-riscv64-gnu": "2.3.3", + "@rspack/binding-linux-riscv64-musl": "2.3.3", + "@rspack/binding-linux-s390x-gnu": "2.3.3", + "@rspack/binding-linux-x64-gnu": "2.3.3", + "@rspack/binding-linux-x64-musl": "2.3.3", + "@rspack/binding-wasm32-wasi": "2.3.3", + "@rspack/binding-win32-arm64-msvc": "2.3.3", + "@rspack/binding-win32-ia32-msvc": "2.3.3", + "@rspack/binding-win32-x64-msvc": "2.3.3" } }, "node_modules/@rspack/binding-darwin-arm64": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.1.tgz", - "integrity": "sha512-koLyL2r8PUcLD0StjuZ/n5XM6GJ0C8dzJN0IuIV9d7nQcibJxwjjSAWEPGVz6bm8WuzypvuVKNoa1+GGAHeMQA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.3.tgz", + "integrity": "sha512-G9WcBOP/6ZWeqTM/G0/rkJRY4DWmYQvk2untzcpj92uO12tqjZ9BSMgtBFvwElwagfQBkX8PPutkAZgtnlAoWA==", "cpu": [ "arm64" ], @@ -206,9 +209,9 @@ ] }, "node_modules/@rspack/binding-darwin-x64": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.1.tgz", - "integrity": "sha512-YK39JLiu1YC6+3BMxkP7e848pHD7e2T/0OSNogDi7whfiZNg95wa9Ncd7I5ppAf0nhmV+FNew/sCBIFp5h67Jw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.3.tgz", + "integrity": "sha512-6agI5XDoihay+84vzZgIwwpQQ3xBWbe2HTWBRc0n42LzynIj9h7Qv8CJzf1gSDV1Ts0jzDgAJCYUFJ6Ya5F6MA==", "cpu": [ "x64" ], @@ -220,13 +223,16 @@ ] }, "node_modules/@rspack/binding-linux-arm64-gnu": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.1.tgz", - "integrity": "sha512-Q+RCA/KM2tn6m6R5U4lktXDs5cCRm3SyleQk86iqqUFX7wKzVRUvr5BTsreg6K9of3gpYmQ6+g1PGT5cwo0rLA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.3.tgz", + "integrity": "sha512-VdjK1mDq+GBexd041lmWBFmAvcWIZy7kepTJbJgxLeHYYOnI3KmBG15kemhlK0pBySa+bePX7p2w8uYtl1HsCA==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -234,13 +240,16 @@ ] }, "node_modules/@rspack/binding-linux-arm64-musl": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.1.tgz", - "integrity": "sha512-He+muVDON1fohGtdYamh3zHVwf6/E6fZu/+iEAkxjclE0P94bsCfYVcZW/a4/l1tJ2zvLZtB4jD7Qr6r4vG/WA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.3.tgz", + "integrity": "sha512-xF4Wy4XwGjC3m13tFm1q9p9Qpm31qrk6f5zEMPZC31UVabb+2jrgTI1pfZ8IRuo9x/Qw9s+Zq3hyDbtJvvD8Pg==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -248,13 +257,16 @@ ] }, "node_modules/@rspack/binding-linux-ppc64-gnu": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.1.tgz", - "integrity": "sha512-blIZUgyPt4FcSHkZL6sJ2xbzc7ACgDeU49An4mXLSebwdgnlhTzxeSFnh2VeJDlGza8CUaZYB/zS/6oZ2kCDcw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.3.tgz", + "integrity": "sha512-jVmn+LpF44D4FdZyT91rlT/tPMdHIfPfQTgVzwPB5nDICp4b57SFjVBApuAPIxnLT1pKLkv/LIcdvGSdAeX12w==", "cpu": [ "ppc64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -262,13 +274,16 @@ ] }, "node_modules/@rspack/binding-linux-riscv64-gnu": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.1.tgz", - "integrity": "sha512-3FtW2DUFmXxhBORUA3zSc+ot4d6R/1/U6z/48TDN4jeIYDUG9VqYBF6LUohX4vBY6IP0DCyXb2N9WayD/9QXoA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.3.tgz", + "integrity": "sha512-JcQJm8M634jkbG6zJ3TfziKYsCINEAh3FwKuxLljvBgGDEupBxPuB0n2bXBIUeI8P9C33B45IYX6BwWYXll/zw==", "cpu": [ "riscv64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -276,13 +291,16 @@ ] }, "node_modules/@rspack/binding-linux-riscv64-musl": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.1.tgz", - "integrity": "sha512-+5qNgdNdXzp/K8f8BjgJ3m7tcbBKPENN7WPDfBcSHvWb5GF4+o/pbrX26c0+LEugo0bYUOAoitBNd94AwcNvpA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.3.tgz", + "integrity": "sha512-YMIOS7rFvCDnpeyxoVEVbM7U/TwcC2VDtN3Oiq9BenRsNTEvk0imINhuVRFanh15+wkiQHk9h0b+pzcggYLAsA==", "cpu": [ "riscv64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -290,13 +308,16 @@ ] }, "node_modules/@rspack/binding-linux-s390x-gnu": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.1.tgz", - "integrity": "sha512-yNcg/y1+MV0wZ984CVU4d1HAYYwMcDPXoQO0xynU+K5YuBxPWALHOxuRRCKCcykBdL1GIEshAIewEFrsW/cmJg==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.3.tgz", + "integrity": "sha512-tHGtIG6GGHsk2KvSleQp/BrVqiGdjDsLJuMKR7hE7W1uJW6WDJ+a+Z23Rk5kHXh5BjeFLjXxcufGuokvmLmTag==", "cpu": [ "s390x" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -304,13 +325,16 @@ ] }, "node_modules/@rspack/binding-linux-x64-gnu": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.1.tgz", - "integrity": "sha512-ffclKBuH8wwimOBd6xGUxrBfVKKY5Ow4E7OFdHZeg4xffm2O8auGszmOgvFu1eoDoOYHaVJn+cEV6UD0KwZk8A==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.3.tgz", + "integrity": "sha512-spe8SjywfO+dD7Sk+vIpPaOXf56wstrgeuztfJdiI9zTeQmf/lhdaNUUSUAXlGIaLjrN/PhV8i5kbQ7VaAkenw==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -318,13 +342,16 @@ ] }, "node_modules/@rspack/binding-linux-x64-musl": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.1.tgz", - "integrity": "sha512-qcDwwuyxR7TMtrW+r5Y9RIW25boXd1Ip/9jz04jhdq/OiU/Am7rCP2X90CH8sWdzovIF9UNmsGjY4KklR0F2Mg==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.3.tgz", + "integrity": "sha512-4E4OJodrmsS52zkSAWShG/F07etr0OG4oSrIN+/2BBgc0qR2wwu2T+rAs308IL3lbywlS+J+cynrRcsSFMD+Kg==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -332,9 +359,9 @@ ] }, "node_modules/@rspack/binding-wasm32-wasi": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.1.tgz", - "integrity": "sha512-3dr6zjFaCK3A920ftCriSJkiRhEfhHtat7LtBdj6g0mcV5Rt+iealmli0vjeAvD0UdpE1u8EKWlfw82JLgFLSQ==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.3.tgz", + "integrity": "sha512-AhlsPjW31TGP8N+J7OmbCPaamARUl+OQNiT3xo0PL5Dz5oMm+bEfYLostpehKyy8MNDrmJcY97M9pDb5MDMA0w==", "cpu": [ "wasm32" ], @@ -342,15 +369,15 @@ "license": "MIT", "optional": true, "dependencies": { - "@emnapi/core": "1.11.3", - "@emnapi/runtime": "1.11.3", - "@napi-rs/wasm-runtime": "1.1.6" + "@emnapi/core": "2.0.0-beta.3", + "@emnapi/runtime": "2.0.0-beta.3", + "@napi-rs/wasm-runtime": "1.2.7" } }, "node_modules/@rspack/binding-win32-arm64-msvc": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.1.tgz", - "integrity": "sha512-AZbuLPylt1xvWssN93AsirbYs3WgfcrA8tMsqHmVJIHahLu9E+JPKZ3Gmsw6IYEZk3EfnV3ujQzeQ1/VfF0Vsw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.3.tgz", + "integrity": "sha512-Zqbj7GBPtkJ8GlUKAjFgvmOxKkQwjfS3XfjwGBcmoIAUb4IxUsmMqvi+gfKrvI45SjYVFZaJnTpOJw6GL79K+Q==", "cpu": [ "arm64" ], @@ -362,9 +389,9 @@ ] }, "node_modules/@rspack/binding-win32-ia32-msvc": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.1.tgz", - "integrity": "sha512-R5NVU68TePZcgRdYUzrQX9YFNxmcyXZEPwaPv40AAgsqNyacG3iRaYVmV79jt3rWYfa0QJaqvRLUchDe2SZ6zQ==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.3.tgz", + "integrity": "sha512-sJJmbrdzH6kI48mCsUu5a2+BzEktLmHrHUmWGkAPAi0zhi4anA7sOdS1+uERbkkd/XAzs0bdn3JXyT2djY+3IA==", "cpu": [ "ia32" ], @@ -376,9 +403,9 @@ ] }, "node_modules/@rspack/binding-win32-x64-msvc": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.1.tgz", - "integrity": "sha512-5T9DYjNPQpLbrNXjCssGd2B6xMQPlc3LxVOKHGUA1O0GV+88vBkTXAcryJ+Fo+yVEMPCzp4VvwBMGAVDpCjcSA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.3.tgz", + "integrity": "sha512-1r3wxV1pBNykqpbEbZWqcrZd13PKLq0e7Ku6qv8IGKKeftuf3RUxTkeM5AzppGMGEIA9sw8mRdN7NvEXxqLLxw==", "cpu": [ "x64" ], @@ -390,13 +417,13 @@ ] }, "node_modules/@rspack/core": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.1.tgz", - "integrity": "sha512-9BWfaiEJLgLK9U53Q4WVruBZ19Mu/XWHXHEu0UFla4lUtH8Z+/ET2m044tiqbtyIgqQyG58fMrxHeVIAiXMXHg==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.3.tgz", + "integrity": "sha512-stAYr0SXf+ZFXFsWTv+Ljxoj/nQs2p7gX9V1kBwlO2IXlRAAhabLONYibT3ZeEGybx3kowrs7uJkcOQsuHgghw==", "dev": true, "license": "MIT", "dependencies": { - "@rspack/binding": "2.3.1" + "@rspack/binding": "2.3.3" }, "engines": { "node": "^20.19.0 || >=22.12.0" @@ -431,17 +458,17 @@ } }, "node_modules/@rspress/core": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.3.tgz", - "integrity": "sha512-qKa5c7zHO8cmhxkReURd3dN/ZRfHYnEztdIQ9hMuolaNzhSYo2A36XErUvLvbMf2EUM2AxfPYRQv+4Crfeq6pw==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.4.tgz", + "integrity": "sha512-7OmP7ABDgQLSpVfpBHfpjqu4H3PGBGMyhLxF1crPQ48Q6MIWAVu77nw7cONn8AZa9GoVq0N/DoE3GEtgZzlu6w==", "dev": true, "license": "MIT", "dependencies": { "@mdx-js/mdx": "^3.1.1", "@mdx-js/react": "^3.1.1", - "@rsbuild/core": "^2.2.14", + "@rsbuild/core": "^2.3.3", "@rsbuild/plugin-react": "~2.1.1", - "@rspress/shared": "2.1.3", + "@rspress/shared": "2.1.4", "@shikijs/rehype": "^4.2.0", "@shikijs/transformers": "^4.2.0", "@types/mdast": "^4.0.4", @@ -485,9 +512,9 @@ } }, "node_modules/@rspress/plugin-client-redirects": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.3.tgz", - "integrity": "sha512-iEqJ8qEFuUxGKRVaS/WMyFi8FiJlogdcEHbGK/UjY8+8Hg8r8aSv4YihmNh3Ev/uIW21hrC8aXMEgVo0H51Q+g==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.4.tgz", + "integrity": "sha512-6/g+Mr8lslqiFzlMBouex8TLm6PlQK6cmZ71Yfv82+Uxcrb+LaFAFiPbq2G7gToXBQUoECM4D/7nSLAfeOhnEQ==", "dev": true, "license": "MIT", "engines": { @@ -498,9 +525,9 @@ } }, "node_modules/@rspress/plugin-sitemap": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.3.tgz", - "integrity": "sha512-Fqo7/4PfQK1ecHUFoUDMrR/E+Hcu+kIohxSs8QabflMy3dqk+M3ZqzJDOHpVYB+HLLGwKiqkPLT4BK+W93clkw==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.4.tgz", + "integrity": "sha512-TObDTXgBKFAHEWEth47aehQSYtFfpIkqM4w14a0hUbPLkbu2AZ2cKnMzFTKK+W6I/3LN54scvfGYTL5CPQsDXw==", "dev": true, "license": "MIT", "engines": { @@ -511,13 +538,13 @@ } }, "node_modules/@rspress/shared": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.3.tgz", - "integrity": "sha512-VwJ7kgsTWVqHzSXQVHIUCsdMparmq9b/IDmTa3a6jMPl1zmm5Qg9M0eP4j8JXWoIS9n19XtCkQcZmMTFOPRy3A==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.4.tgz", + "integrity": "sha512-SuQyVKn9xcQwkzfl+4bPBzX10gxbhCs9UupqSoPtxvyr9pMgSbXnlo3gxTPZXLzk5HUqZZ6tlIju25PVCEtYWA==", "dev": true, "license": "MIT", "dependencies": { - "@rsbuild/core": "^2.2.14", + "@rsbuild/core": "^2.3.3", "@shikijs/rehype": "^4.2.0", "@types/react": "^19.3.0", "mdast-util-mdx-jsx": "^3.2.1", @@ -672,9 +699,9 @@ "license": "Apache-2.0" }, "node_modules/@tybys/wasm-util": { - "version": "0.10.4", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", - "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", "dev": true, "license": "MIT", "optional": true, From 5d6647612604938debee6600ca8138fba3104e0c Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 20 Nov 2026 17:05:16 +0100 Subject: [PATCH 295/342] fix(metrics): Fix in-flight requests, PDU lag, latency buckets and thumbnail accounting --- Cargo.lock | 3 +-- Cargo.toml | 3 ++- changelog.d/2354.bugfix.md | 1 + docs/public/guides/grafana-dashboard.json | 10 +++++----- src/api/server/send.rs | 3 ++- src/core/metrics/instruments.rs | 24 +++++++++++++++++++---- src/main/metrics.rs | 19 ++++++++---------- src/router/request.rs | 8 ++++++-- src/service/media/mod.rs | 24 +++++++++++++++-------- src/service/media/thumbnail.rs | 10 +++++++++- 10 files changed, 70 insertions(+), 35 deletions(-) create mode 100644 changelog.d/2354.bugfix.md diff --git a/Cargo.lock b/Cargo.lock index 8f8d5fbd4..50af5a466 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4002,8 +4002,7 @@ dependencies = [ [[package]] name = "opentelemetry-instrumentation-tower" version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7006f3b1853d315462a7237c81eec3d7adfa5b70975a02b19e92d045bc22d7" +source = "git+https://github.com/open-telemetry/opentelemetry-rust-contrib?rev=6bbbc337aab0bcf10d7799c3e5b5ced75920491a#6bbbc337aab0bcf10d7799c3e5b5ced75920491a" dependencies = [ "axum", "http", diff --git a/Cargo.toml b/Cargo.toml index 7870336b4..18558e4db 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -435,7 +435,8 @@ features = ["reqwest"] version = "0.33.1" [workspace.dependencies.opentelemetry-instrumentation-tower] -version = "0.19.0" +git = "https://github.com/open-telemetry/opentelemetry-rust-contrib" +rev = "6bbbc337aab0bcf10d7799c3e5b5ced75920491a" default-features = false features = ["axum"] diff --git a/changelog.d/2354.bugfix.md b/changelog.d/2354.bugfix.md new file mode 100644 index 000000000..45670f1bb --- /dev/null +++ b/changelog.d/2354.bugfix.md @@ -0,0 +1 @@ +Fixed Prometheus accounting for in-flight requests, federation PDU lag, latency buckets, and thumbnail sizes. Contributed by @eleboucher. diff --git a/docs/public/guides/grafana-dashboard.json b/docs/public/guides/grafana-dashboard.json index e7922d37b..4f1b73520 100644 --- a/docs/public/guides/grafana-dashboard.json +++ b/docs/public/guides/grafana-dashboard.json @@ -302,7 +302,7 @@ "type": "prometheus", "uid": "${datasource}" }, - "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))", "legendFormat": "", "refId": "A", "range": true @@ -496,7 +496,7 @@ "type": "prometheus", "uid": "${datasource}" }, - "expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))", "legendFormat": "p50", "refId": "A", "range": true @@ -506,7 +506,7 @@ "type": "prometheus", "uid": "${datasource}" }, - "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))", "legendFormat": "p95", "refId": "B", "range": true @@ -516,7 +516,7 @@ "type": "prometheus", "uid": "${datasource}" }, - "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))", "legendFormat": "p99", "refId": "C", "range": true @@ -1228,7 +1228,7 @@ { "type": "timeseries", "title": "PDU lag", - "description": "Time between an accepted PDU's origin_server_ts and its arrival; affected by clock skew", + "description": "Time between an accepted PDU's origin_server_ts and its transaction arriving; affected by clock skew", "id": 21, "datasource": { "type": "prometheus", diff --git a/src/api/server/send.rs b/src/api/server/send.rs index 20da3572c..979fada62 100644 --- a/src/api/server/send.rs +++ b/src/api/server/send.rs @@ -332,6 +332,7 @@ async fn handle_room( room_id: OwnedRoomId, pdus: impl Iterator + Send, ) -> std::result::Result, TransactionError> { + let arrived = millis_since_unix_epoch(); let _room_lock = services .rooms .event_handler @@ -392,7 +393,7 @@ async fn handle_room( .federation_incoming_pdu_duration .record(start.elapsed().as_secs_f64(), std::slice::from_ref(&outcome)); if let (Ok(()), Some(ts)) = (&result, origin_server_ts) { - let lag = millis_since_unix_epoch().saturating_sub(ts); + let lag = arrived.saturating_sub(ts); instruments .federation_incoming_pdu_lag .record(Duration::from_millis(lag).as_secs_f64(), &[]); diff --git a/src/core/metrics/instruments.rs b/src/core/metrics/instruments.rs index 10bff549a..7c922188d 100644 --- a/src/core/metrics/instruments.rs +++ b/src/core/metrics/instruments.rs @@ -45,6 +45,14 @@ impl Instruments { .with_boundaries(duration_buckets()) .build() }; + let long_duration = |name: &'static str, description: &'static str| { + meter + .f64_histogram(name) + .with_description(description) + .with_unit("s") + .with_boundaries(long_duration_buckets()) + .build() + }; let size = |name: &'static str, description: &'static str| { meter .u64_histogram(name) @@ -55,11 +63,11 @@ impl Instruments { }; Self { - federation_outgoing_request_duration: duration( + federation_outgoing_request_duration: long_duration( "continuwuity.federation.outgoing.request.duration", "Duration of outgoing federation requests", ), - federation_incoming_transaction_duration: duration( + federation_incoming_transaction_duration: long_duration( "continuwuity.federation.incoming.transaction.duration", "Time taken to process incoming federation transactions", ), @@ -75,11 +83,13 @@ impl Instruments { federation_incoming_pdu_lag: meter .f64_histogram("continuwuity.federation.incoming.pdu.lag") .with_description( - "Time between an accepted incoming PDU's origin_server_ts and its arrival", + "Time between an accepted incoming PDU's origin_server_ts and its \ + transaction arriving", ) .with_unit("s") .with_boundaries(vec![ 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 300.0, 900.0, 3600.0, + 21600.0, 86400.0, ]) .build(), federation_incoming_edus: meter @@ -92,7 +102,7 @@ impl Instruments { "Time taken to handle an incoming federation EDU", ), - sender_transaction_duration: duration( + sender_transaction_duration: long_duration( "continuwuity.sender.transaction.duration", "Duration of outgoing transactions by destination type and outcome", ), @@ -130,6 +140,12 @@ impl Instruments { #[must_use] pub fn duration_buckets() -> Vec { (0..16).map(|i| 0.001 * f64::from(1_u32 << i)).collect() } +/// Federation requests and transactions can run past the 60s default +/// `federation_timeout`. +fn long_duration_buckets() -> Vec { + (0..18).map(|i| 0.001 * f64::from(1_u32 << i)).collect() +} + fn size_buckets() -> Vec { (0..11).map(|i| 1024.0 * f64::from(4_u32.pow(i))).collect() } fn register_process(meter: &Meter) { diff --git a/src/main/metrics.rs b/src/main/metrics.rs index 0e818c32c..370b790a8 100644 --- a/src/main/metrics.rs +++ b/src/main/metrics.rs @@ -26,18 +26,15 @@ pub(crate) fn init( let mut builder = SdkMeterProvider::builder() .with_resource(resource) - .with_view(|instrument: &Instrument| { - (instrument.name() == metric::HTTP_SERVER_REQUEST_DURATION) - .then(|| { - Stream::builder() - .with_aggregation(Aggregation::ExplicitBucketHistogram { - boundaries: duration_buckets(), - record_min_max: true, - }) - .build() - .ok() + .with_view(|instrument: &Instrument| match instrument.name() { + | metric::HTTP_SERVER_REQUEST_DURATION => Stream::builder() + .with_aggregation(Aggregation::ExplicitBucketHistogram { + boundaries: duration_buckets(), + record_min_max: true, }) - .flatten() + .build() + .ok(), + | _ => None, }); let registry = config diff --git a/src/router/request.rs b/src/router/request.rs index d6a962727..2f0d7d7d2 100644 --- a/src/router/request.rs +++ b/src/router/request.rs @@ -64,7 +64,7 @@ pub(crate) async fn handle( .server .metrics .requests_handle_active - .fetch_add(1, Ordering::Relaxed), + .load(Ordering::Relaxed), handled = %services .server .metrics @@ -81,7 +81,11 @@ async fn execute( next: axum::middleware::Next, parent: &Span, ) -> Response { - #[cfg(debug_assertions)] + services + .server + .metrics + .requests_handle_active + .fetch_add(1, Ordering::Relaxed); conduwuit::defer! {{ _ = services.server .metrics diff --git a/src/service/media/mod.rs b/src/service/media/mod.rs index 7e229d9cf..d7021be01 100644 --- a/src/service/media/mod.rs +++ b/src/service/media/mod.rs @@ -112,14 +112,27 @@ impl Service { err!(Database(error!("Failed to write media file for MXC {mxc} at key {key:?}: {e}"))) })?; + self.record_write(mxc, file.len()); + + Ok(()) + } + + fn record_write(&self, mxc: &Mxc<'_>, len: usize) { self.services .server .metrics .instruments .media_write_size - .record(file.len().try_into().unwrap_or(u64::MAX), &[self.origin(mxc)]); + .record(len.try_into().unwrap_or(u64::MAX), &[self.origin(mxc)]); + } - Ok(()) + fn record_read(&self, mxc: &Mxc<'_>, len: usize) { + self.services + .server + .metrics + .instruments + .media_read_size + .record(len.try_into().unwrap_or(u64::MAX), &[self.origin(mxc)]); } fn origin(&self, mxc: &Mxc<'_>) -> KeyValue { @@ -196,12 +209,7 @@ impl Service { .read_to_end(&mut content) .await?; - self.services - .server - .metrics - .instruments - .media_read_size - .record(content.len().try_into().unwrap_or(u64::MAX), &[self.origin(mxc)]); + self.record_read(mxc, content.len()); Ok(Some(FileMeta { content: Some(content), diff --git a/src/service/media/thumbnail.rs b/src/service/media/thumbnail.rs index 139516653..8b67dbe2a 100644 --- a/src/service/media/thumbnail.rs +++ b/src/service/media/thumbnail.rs @@ -44,6 +44,7 @@ impl super::Service { //TODO: Dangling metadata in database if creation fails let mut f = self.create_media_file(&key).await?; f.write_all(file).await?; + self.record_write(mxc, file.len()); Ok(()) } @@ -66,13 +67,19 @@ impl super::Service { // 0, 0 because that's the original file let dim = dim.normalized(); - match self.db.search_file_metadata(mxc, &dim).await { + let thumbnail = match self.db.search_file_metadata(mxc, &dim).await { | Ok(metadata) => self.get_thumbnail_saved(metadata).await, | _ => match self.db.search_file_metadata(mxc, &Dim::default()).await { | Ok(metadata) => self.get_thumbnail_generate(mxc, &dim, metadata).await, | _ => Ok(None), }, + }; + + if let Ok(Some(FileMeta { content: Some(content), .. })) = &thumbnail { + self.record_read(mxc, content.len()); } + + thumbnail } /// Using saved thumbnail @@ -132,6 +139,7 @@ impl super::Service { let mut f = self.create_media_file(&thumbnail_key).await?; f.write_all(&thumbnail_bytes).await?; + self.record_write(mxc, thumbnail_bytes.len()); Ok(Some(into_filemeta(data, thumbnail_bytes))) } From fda99bcda25dce7c8ce849e1ba9d386a191ade18 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sat, 21 Nov 2026 16:02:12 +0000 Subject: [PATCH 296/342] chore(deps): update dependency cargo-bins/cargo-binstall to v1.28.0 --- docker/Dockerfile | 2 +- docker/musl.Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index e59ecac67..3af00fb98 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -50,7 +50,7 @@ EOF # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.27.0 +ENV BINSTALL_VERSION=1.28.0 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree diff --git a/docker/musl.Dockerfile b/docker/musl.Dockerfile index 278a559d1..8e37b6d57 100644 --- a/docker/musl.Dockerfile +++ b/docker/musl.Dockerfile @@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \ # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.27.0 +ENV BINSTALL_VERSION=1.28.0 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree From ece207286acd505cfe67b6e5686fed51093f03bb Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 01:58:19 +0000 Subject: [PATCH 297/342] fix(core): Fix UB in usize_from_f64 on non-finite and out-of-range floats --- src/core/utils/math.rs | 50 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/src/core/utils/math.rs b/src/core/utils/math.rs index 9316731c5..e11d0302a 100644 --- a/src/core/utils/math.rs +++ b/src/core/utils/math.rs @@ -62,14 +62,28 @@ macro_rules! validated { } #[inline] -#[allow(clippy::as_conversions)] +#[allow(clippy::as_conversions, clippy::cast_possible_truncation, clippy::cast_sign_loss)] pub fn usize_from_f64(val: f64) -> Result { + // Exclusive upper bound for values whose truncation fits in `usize`. + // Note that `usize::MAX as f64` rounds up to 2^64 on 64-bit targets, so a + // strict `<` check against 2^(usize::BITS) rejects all out-of-range values + // on both 32-bit and 64-bit targets. + #[allow(clippy::cast_precision_loss)] + const MAX_USIZE_EXCLUSIVE: f64 = (1_u128 << usize::BITS) as f64; + + if !val.is_finite() { + return Err!(Arithmetic("Converting non-finite float to unsigned integer")); + } + if val < 0.0 { return Err!(Arithmetic("Converting negative float to unsigned integer")); } - //SAFETY: - Ok(unsafe { val.to_int_unchecked::() }) + if val >= MAX_USIZE_EXCLUSIVE { + return Err!(Arithmetic("Converting out-of-range float to unsigned integer")); + } + + Ok(val as usize) } #[inline] @@ -111,3 +125,33 @@ fn try_into_err, Src>(e: >::Error) -> Erro #[inline] pub fn clamp(val: T, min: T, max: T) -> T { cmp::min(cmp::max(val, min), max) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn usize_from_f64_valid() { + assert_eq!(usize_from_f64(0.0).unwrap(), 0); + assert_eq!(usize_from_f64(-0.0).unwrap(), 0); + assert_eq!(usize_from_f64(42.9).unwrap(), 42); + assert_eq!(usize_from_f64(1_048_576.0).unwrap(), 1_048_576); + } + + #[test] + fn usize_from_f64_rejects_invalid() { + usize_from_f64(-1.0).unwrap_err(); + usize_from_f64(-0.5).unwrap_err(); + usize_from_f64(f64::NAN).unwrap_err(); + usize_from_f64(f64::INFINITY).unwrap_err(); + usize_from_f64(f64::NEG_INFINITY).unwrap_err(); + usize_from_f64(1e30).unwrap_err(); + #[cfg(target_pointer_width = "64")] + { + // `usize::MAX as f64` rounds up to 2^64, which is out of range. + #[allow(clippy::as_conversions, clippy::cast_precision_loss)] + let rounded_max = usize::MAX as f64; + usize_from_f64(rounded_max).unwrap_err(); + } + } +} From b617e9fd5c6f349b2a495713553b7d5191308d77 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 01:59:40 +0000 Subject: [PATCH 298/342] fix(core): Remove unsound assert_unchecked in compute::getcpu --- src/core/utils/sys/compute.rs | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/src/core/utils/sys/compute.rs b/src/core/utils/sys/compute.rs index 91abddc28..76795be04 100644 --- a/src/core/utils/sys/compute.rs +++ b/src/core/utils/sys/compute.rs @@ -120,21 +120,13 @@ pub fn cores_available() -> impl Iterator { from_mask(*CORES_AVAILABL pub fn getcpu() -> Result { use crate::{Error, utils::math}; - // SAFETY: This is part of an interface with many low-level calls taking - // many raw params, but it's unclear why this specific call is unsafe. - // Nevertheless the value obtained here is semantically unsafe because it - // can change on the instruction boundary trailing its own acquisition and - // also any other time. + // SAFETY: `sched_getcpu(2)` takes no pointers and has no preconditions. + // Note that it may still return -1 with errno set (e.g. under seccomp + // filters or kernels without getcpu support), so the error branch below + // must remain live. let ret: i32 = unsafe { libc::sched_getcpu() }; - #[cfg(target_os = "linux")] - // SAFETY: On modern linux systems with a vdso if we can optimize away the branch checking - // for error (see getcpu(2)) then this system call becomes a memory access. - unsafe { - std::hint::assert_unchecked(ret >= 0); - }; - - if ret == -1 { + if ret < 0 { return Err(Error::from_errno()); } From becfc2454f4bbc1f87922fca97746d2a0d7d38dc Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:01:57 +0000 Subject: [PATCH 299/342] fix(core): Fix UAF race and aliasing UB in config::Manager --- src/core/config/manager.rs | 227 +++++++++++++++++++++++-------------- 1 file changed, 142 insertions(+), 85 deletions(-) diff --git a/src/core/config/manager.rs b/src/core/config/manager.rs index b7bbf0f3e..a44388e7a 100644 --- a/src/core/config/manager.rs +++ b/src/core/config/manager.rs @@ -1,8 +1,6 @@ use std::{ - cell::{Cell, RefCell}, ops::Deref, - ptr, - ptr::null_mut, + ptr::NonNull, sync::{ Arc, atomic::{AtomicPtr, Ordering}, @@ -10,119 +8,178 @@ use std::{ }; use super::Config; -use crate::Result; +use crate::{Result, SyncMutex}; /// The configuration manager is an indirection to reload the configuration for /// the server while it is running. In order to not burden or clutter the many /// callsites which query for configuration items, this object implements Deref /// for the actively loaded configuration. +/// +/// Every installed `Arc` is kept at a stable heap address in `retired` +/// for the entire lifetime of `Manager` (intentionally retaining prior configs +/// across the rare, admin-triggered reloads until shutdown). Because +/// `Deref::deref(&self)` ties the returned `&Arc` lifetime to `&self`, +/// readers can perform a single `Acquire` load with no locking, no TLS, and no +/// risk of dangling or aliasing UB across reloads. pub struct Manager { - active: AtomicPtr, + active: AtomicPtr>, + /// Append-only owner of every `Box>` ever published to + /// `active` (including the currently active config). Entries are only + /// freed when `Manager` itself is dropped (`&mut self`), guaranteeing that + /// any `&Arc` returned by `Deref::deref` remains valid and + /// immutable for the lifetime of `self`. + retired: SyncMutex>, } -thread_local! { - static INDEX: Cell = 0.into(); - static HANDLE: RefCell = const { - RefCell::new([const { None }; HISTORY]) - }; +/// Heap-pinned `Arc` stored as a raw `NonNull` rather than `Box` so +/// moving it (e.g., when `Vec` reallocates) never retags or invalidates raw +/// pointers previously published to `Manager::active`. +struct PinnedConfig(NonNull>); + +// SAFETY: `Arc` is `Send + Sync`, and `PinnedConfig` uniquely owns the +// `Box>` allocation until it is dropped in `Manager::drop`. +unsafe impl Send for PinnedConfig {} + +impl PinnedConfig { + fn new(config: Config) -> Self { + let ptr = Box::into_raw(Box::new(Arc::new(config))); + Self(NonNull::new(ptr).expect("Box::into_raw returned null")) + } + + #[inline] + const fn as_ptr(&self) -> *mut Arc { self.0.as_ptr() } } -type Handle = Option>; -type Handles = [Handle; HISTORY]; - -const HISTORY: usize = 8; +impl Drop for PinnedConfig { + fn drop(&mut self) { + // SAFETY: `self.0` was created via `Box::into_raw` in + // `PinnedConfig::new` and is only dropped when `Manager` itself is + // dropped (`&mut self`), after all borrows derived from `Deref::deref` + // have ended. + unsafe { + drop(Box::from_raw(self.0.as_ptr())); + } + } +} impl Manager { pub(crate) fn new(config: Config) -> Self { - let config = Arc::new(config); + let pinned = PinnedConfig::new(config); + let ptr = pinned.as_ptr(); Self { - active: AtomicPtr::new(Arc::into_raw(config).cast_mut()), + active: AtomicPtr::new(ptr), + retired: SyncMutex::new(vec![pinned]), } } /// Update the active configuration, returning prior configuration. #[tracing::instrument(skip_all, level = "info")] pub fn update(&self, config: Config) -> Result> { - let config = Arc::new(config); - let new = Arc::into_raw(config); - let old = self.active.swap(new.cast_mut(), Ordering::AcqRel); + let pinned = PinnedConfig::new(config); + let new_ptr = pinned.as_ptr(); - // SAFETY: The old active pointer was set using an Arc::into_raw(). - // We're obliged to reconstitute that into Arc otherwise it will leak. - Ok(unsafe { Arc::from_raw(old) }) - } + let mut retired = self.retired.lock(); + // Push before publishing to `active` so ownership is recorded even if + // `Vec::push` were to unwind. + retired.push(pinned); - fn load(&self, handle: &mut [Option>]) -> &'static Arc { - let config = self.active.load(Ordering::Acquire); + // `Release` publishes the initialized `Box>` to readers + // performing `Acquire` loads in `Deref::deref`. + let old_ptr = self.active.swap(new_ptr, Ordering::AcqRel); - // Branch taken after config reload or first access by this thread. - if handle[INDEX.get()] - .as_ref() - .is_none_or(|handle| !ptr::eq(config, Arc::as_ptr(handle))) - { - INDEX.set(INDEX.get().wrapping_add(1).wrapping_rem(HISTORY)); - return load_miss(handle, INDEX.get(), config); - } + // SAFETY: `old_ptr` points to a `PinnedConfig` still owned by `retired` + // and cannot be freed until `Manager` is dropped. + let old = unsafe { Arc::clone(&*old_ptr) }; - let config: &Arc = handle[INDEX.get()] - .as_ref() - .expect("handle was already cached for this thread"); - - // SAFETY: The caller should not hold multiple references at a time - // directly into Config, as a subsequent reference might invalidate - // the thread's cache causing another reference to dangle. - // - // This is a highly unusual pattern as most config values are copied by - // value or used immediately without running overlap with another - // value. Even if it does actually occur somewhere, the window of - // danger is limited to the config being reloaded while the reference - // is held and another access is made by the same thread into a - // different config value. This is mitigated by creating a buffer - // of old configs rather than discarding at the earliest opportunity; - // the odds of this scenario are thus astronomical. - unsafe { std::mem::transmute(config) } - } -} - -impl Drop for Manager { - fn drop(&mut self) { - let config = self.active.swap(null_mut(), Ordering::AcqRel); - - // SAFETY: The active pointer was set using an Arc::into_raw(). We're - // obliged to reconstitute that into Arc otherwise it will leak. - unsafe { Arc::from_raw(config) }; + Ok(old) } } impl Deref for Manager { type Target = Arc; - fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) } + #[inline] + fn deref(&self) -> &Self::Target { + let ptr = self.active.load(Ordering::Acquire); + + // SAFETY: `ptr` was initialized in `Manager::new` or published via + // `Ordering::AcqRel` in `Manager::update` and points to a + // `PinnedConfig` in `self.retired`. Entries in `self.retired` are never + // removed or mutated until `Manager` is dropped (`&mut self`), so the + // returned `&'self Arc` remains valid and immutable for the + // entire borrow of `self`. + unsafe { &*ptr } + } } -#[tracing::instrument( - name = "miss", - level = "trace", - skip_all, - fields(%index, ?config) -)] -#[allow(clippy::transmute_ptr_to_ptr)] -fn load_miss( - handle: &mut [Option>], - index: usize, - config: *const Config, -) -> &'static Arc { - // SAFETY: The active pointer was set prior and always remains valid. We're - // reconstituting the Arc here but as a new reference, so the count is - // incremented. This instance will be cached in the thread-local. - let config = unsafe { - Arc::increment_strong_count(config); - Arc::from_raw(config) - }; +#[cfg(test)] +mod tests { + use std::thread; - // SAFETY: See the note on the transmute above. The caller should not hold - // more than one reference at a time directly into Config, as the second - // access might invalidate the thread's cache, dangling the reference to - // the first. - unsafe { std::mem::transmute(handle[index].insert(config)) } + use super::*; + + fn test_config(server_name: &str) -> Config { + use figment::{ + Figment, + providers::{Format, Toml}, + }; + + let raw = format!("server_name = \"{server_name}\"\ndatabase_path = \"/tmp\"\n"); + Figment::new() + .merge(Toml::string(&raw)) + .extract() + .expect("valid test config") + } + + #[test] + fn deref_survives_many_reloads() { + let manager = Manager::new(test_config("initial.example")); + let first: &Arc = &manager; + let first_name: &str = first.server_name.as_str(); + + for i in 0..32 { + let prev = manager + .update(test_config(&format!("reload-{i}.example"))) + .expect("update succeeds"); + if i == 0 { + assert_eq!(prev.server_name.as_str(), "initial.example"); + } + } + + // Original reference remains valid and unchanged after > HISTORY + // reloads. + assert_eq!(first_name, "initial.example"); + assert_eq!(manager.server_name.as_str(), "reload-31.example"); + } + + #[test] + fn concurrent_reads_and_updates() { + let manager = Manager::new(test_config("start.example")); + + thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + for _ in 0..200 { + let cfg: &Arc = &manager; + assert!(cfg.server_name.as_str().ends_with(".example")); + } + }); + } + + s.spawn(|| { + for i in 0..32 { + let _ = manager + .update(test_config(&format!("iter-{i}.example"))) + .expect("update succeeds"); + } + }); + }); + } + + #[test] + fn reference_outlives_scoped_thread() { + let manager = Manager::new(test_config("scoped.example")); + let cfg_ref: &Arc = thread::scope(|s| s.spawn(|| &*manager).join().unwrap()); + assert_eq!(cfg_ref.server_name.as_str(), "scoped.example"); + } } From 95f925eaee9ebf8263cd2afb505cf5bf67732618 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:04:30 +0000 Subject: [PATCH 300/342] fix(database): Fix Seek drop order and remove no-op transmute in pool --- src/database/pool.rs | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/src/database/pool.rs b/src/database/pool.rs index f13de6272..87859c859 100644 --- a/src/database/pool.rs +++ b/src/database/pool.rs @@ -54,8 +54,14 @@ pub(crate) struct Get { /// Note: only initial seek is supported at this time on the assumption rocksdb /// prefetching prevents mid-iteration polls from blocking on I/O. pub(crate) struct Seek { - pub(crate) map: Arc, + /// SAFETY / DROP ORDER: `state` wraps a RocksDB + /// `DBRawIteratorWithThreadMode` referencing `map.db.db` whose lifetime has + /// been erased to `'static`. `state` MUST be declared before `map` so the + /// iterator is destroyed before `map` (and potentially the last + /// `Arc`) can be dropped if `Seek` is dropped early (e.g. on + /// cancellation or queue closure). pub(crate) state: stream::State<'static>, + pub(crate) map: Arc, pub(crate) dir: Direction, pub(crate) key: Option, pub(crate) res: Option>>, @@ -416,24 +422,30 @@ impl Drop for Pool { } fn into_send_get(result: BatchResult<'_>) -> BatchResult<'static> { - // SAFETY: Necessary to send the Handle (rust_rocksdb::PinnableSlice) - // through the channel. The lifetime on the handle is a device by - // rust-rocksdb to associate a database lifetime with its assets. The - // Handle must be dropped before the database is dropped. + // SAFETY: Necessary to send `Handle` (which wraps + // `rocksdb::DBPinnableSlice`) through the oneshot channel. The lifetime on + // `Handle` ties it to the RocksDB `DB` instance; callers of `execute_get` + // borrow `&self.db.pool` (which is owned by `Engine`), ensuring the + // received `BatchResult<'_>` cannot outlive the database. unsafe { std::mem::transmute(result) } } fn into_recv_get<'a>(result: BatchResult<'static>) -> BatchResult<'a> { - // SAFETY: This is to receive the Handle from the channel. + // SAFETY: Shrinking the erased `'static` lifetime back to `'a` (borrowed + // from `&self.db.pool`). `SmallVec` is invariant over `A`, so this + // cannot be done via implicit covariance. unsafe { std::mem::transmute(result) } } pub(crate) fn into_send_seek(result: stream::State<'_>) -> stream::State<'static> { - // SAFETY: Necessary to send the State through the channel; see above. + // SAFETY: Necessary to send `stream::State` through the pool channel. + // While in flight on the queue, `Seek` owns an `Arc` (declared after + // `state` so `state` drops first on early cancellation); once received back + // from `execute_iter`, the lifetime is shrunk via `into_recv_seek` to the + // caller's borrow of `&self.db.pool` (and `&'a Arc`), ensuring the + // returned `stream::State<'_>` cannot outlive the database. unsafe { std::mem::transmute(result) } } -fn into_recv_seek(result: stream::State<'static>) -> stream::State<'static> { - // SAFETY: This is to receive the State from the channel; see above. - unsafe { std::mem::transmute(result) } -} +#[inline] +const fn into_recv_seek<'a>(result: stream::State<'static>) -> stream::State<'a> { result } From 65d25c77e85977ea858478db505d9658238cd164 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:05:38 +0000 Subject: [PATCH 301/342] fix(database): Assert ColumnFamily layout and document Map drop order --- src/database/map.rs | 4 ++++ src/database/map/open.rs | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/database/map.rs b/src/database/map.rs index ed38e1fc3..067e3c263 100644 --- a/src/database/map.rs +++ b/src/database/map.rs @@ -46,6 +46,10 @@ use crate::{Engine, watchers::Watchers}; pub struct Map { name: &'static str, watchers: Watchers, + /// SAFETY / DROP ORDER: `cf` holds a lifetime-erased RocksDB column family + /// handle (see `open::open`) and MUST be declared before `db` so that the + /// handle is destroyed before `Engine` (and the underlying RocksDB `DB`) + /// can be dropped. cf: Arc, db: Arc, read_options: ReadOptions, diff --git a/src/database/map/open.rs b/src/database/map/open.rs index 97c505159..a81e501c2 100644 --- a/src/database/map/open.rs +++ b/src/database/map/open.rs @@ -1,10 +1,24 @@ use std::sync::Arc; -use rocksdb::ColumnFamily; +use rocksdb::{BoundColumnFamily, ColumnFamily}; use crate::Engine; pub(super) fn open(db: &Arc, name: &str) -> Arc { + // Compile-time guard: `BoundColumnFamily` and `ColumnFamily` are both + // `#[repr(Rust)]` in `rust-rocksdb`, so fail compilation if their size or + // alignment ever diverge. + const { + assert!( + size_of::>() == size_of::(), + "BoundColumnFamily and ColumnFamily must have identical size" + ); + assert!( + align_of::>() == align_of::(), + "BoundColumnFamily and ColumnFamily must have identical alignment" + ); + } + let bounded_arc = db.cf(name); let bounded_ptr = Arc::into_raw(bounded_arc); let cf_ptr = bounded_ptr.cast::(); From d74275bda1e20ac432ec0f971dc45fc7685baa0f Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:05:58 +0000 Subject: [PATCH 302/342] refactor(database): Remove disabled unsound cfg(disable) blocks --- src/database/de.rs | 12 ------------ src/database/util.rs | 16 ---------------- 2 files changed, 28 deletions(-) diff --git a/src/database/de.rs b/src/database/de.rs index 9ff209f0f..0e9d5f5bb 100644 --- a/src/database/de.rs +++ b/src/database/de.rs @@ -472,17 +472,5 @@ impl<'a, 'de: 'a> de::MapAccess<'de> for &'a mut Deserializer<'de> { } } -// activate when stable; too soon now -//#[cfg(debug_assertions)] #[inline] fn deserialize_str(input: &[u8]) -> Result<&str> { string::str_from_bytes(input) } - -//#[cfg(not(debug_assertions))] -#[cfg(disable)] -#[inline] -fn deserialize_str(input: &[u8]) -> Result<&str> { - // SAFETY: Strings were written by the serializer to the database. Assuming - // no database corruption, the string will be valid. Database corruption is - // detected via rocksdb checksums. - unsafe { std::str::from_utf8_unchecked(input) } -} diff --git a/src/database/util.rs b/src/database/util.rs index bcefa2867..a04f0b0af 100644 --- a/src/database/util.rs +++ b/src/database/util.rs @@ -1,28 +1,12 @@ use conduwuit::Result; use rocksdb::{Direction, ErrorKind, IteratorMode}; -//#[cfg(debug_assertions)] macro_rules! unhandled { ($msg:literal) => { unimplemented!($msg) }; } -// activate when stable; we're not ready for this yet -#[cfg(disable)] // #[cfg(not(debug_assertions))] -macro_rules! unhandled { - ($msg:literal) => { - // SAFETY: Eliminates branches for serializing and deserializing types never - // encountered in the codebase. This can promote optimization and reduce - // codegen. The developer must verify for every invoking callsite that the - // unhandled type is in no way involved and could not possibly be - // encountered. - unsafe { - std::hint::unreachable_unchecked(); - } - }; -} - pub(crate) use unhandled; #[inline] From 1dd572416b871dfacd955ac5d90dd6832d8166db Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:06:31 +0000 Subject: [PATCH 303/342] docs(database): Document borrowed-item soundness flaw on iterator streams --- src/database/map/stream.rs | 11 +++++++++++ src/database/stream.rs | 30 ++++++++++++++---------------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/database/map/stream.rs b/src/database/map/stream.rs index b2da4743e..bf82f489c 100644 --- a/src/database/map/stream.rs +++ b/src/database/map/stream.rs @@ -12,6 +12,17 @@ impl super::Map { /// Iterate key-value entries in the map from the beginning. /// /// - Result is deserialized + /// + /// # Unsoundness + /// Because Rust's `Stream` trait does not support lending items tied to + /// `&mut self`, `stream::slice_longevity` unsafely extends the lifetime of + /// raw RocksDB iterator slices to `'a` (the borrow of `Arc`). As a + /// consequence, borrowed deserialized types (e.g. `&str`, `&UserId`, + /// `&[u8]`) reference the underlying RocksDB cursor buffer and are + /// invalidated on the next poll of the stream. Do not hold borrowed items + /// across polls (e.g. via `collect()`, `ready_chunks()`, `peekable()`, + /// `buffered()`, `buffer_unordered()`, `broadband`, or `wideband`) without + /// converting them to owned values first. pub fn stream<'a, K, V>( self: &'a Arc, ) -> impl Stream>> + Send diff --git a/src/database/stream.rs b/src/database/stream.rs index ddcaa32c8..1cf690000 100644 --- a/src/database/stream.rs +++ b/src/database/stream.rs @@ -133,22 +133,20 @@ fn keyval_longevity<'a, 'b: 'a>(item: KeyVal<'a>) -> KeyVal<'b> { } fn slice_longevity<'a, 'b: 'a>(item: &'a Slice) -> &'b Slice { - // SAFETY: The lifetime of the data returned by the rocksdb cursor is only - // valid between each movement of the cursor. It is hereby unsafely - // extended to match the lifetime of the cursor itself. This is due to the - // limitation of the Stream trait where the Item is incapable of conveying - // a lifetime; this is due to GAT's being unstable during its development. - // This unsafety can be removed as soon as this limitation is addressed by - // an upcoming version. + // SAFETY: the lifetime of the data returned by + // the RocksDB cursor is only valid until the next movement of the cursor, + // but is unsafely extended here to match the lifetime `'b` of the `Map` + // borrow because `futures::Stream` is not a lending stream. // - // We have done our best to mitigate the implications of this in conjunction - // with the deserialization API such that borrows being held across - // movements of the cursor do not happen accidentally. The compiler will - // still error when values herein produced try to leave a closure passed to - // a StreamExt API. But escapes can happen if you explicitly and - // intentionally attempt it, and there will be no compiler error or - // warning. This is primarily the case with calling collect() without a - // preceding map(ToOwned::to_owned). A collection of references here is - // illegal, but this will not be enforced by the compiler. + // Callers MUST NOT hold borrowed items (or borrowed deserialized views such + // as `&str`, `&UserId`, or `&[u8]`) across subsequent polls of the stream — + // in particular, never call `collect()`, `ready_chunks()`, `peekable()`, + // `buffered()`, `buffer_unordered()`, `broadband`, or `wideband` on a + // stream yielding borrowed references without first converting items to + // owned values (e.g. `map(ToOwned::to_owned)`). The compiler does NOT + // reject such escapes when items borrow from `'b`. + // + // TODO: Fix this, it is old code and language changes may have made it + // unnecessary unsafe { std::mem::transmute(item) } } From 66dd3e8e3e11eb93863964e110fb9b55011b72b0 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:09:33 +0000 Subject: [PATCH 304/342] fix(service): Mark state::create unsafe and document lifetime invariants --- src/router/router.rs | 6 +++++- src/service/state.rs | 10 +++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/router/router.rs b/src/router/router.rs index c482bfb79..9267a6ce0 100644 --- a/src/router/router.rs +++ b/src/router/router.rs @@ -8,7 +8,11 @@ use ruma::api::error::ErrorKind; pub(crate) fn build(services: &Arc) -> (Router, Guard) { let router = Router::::new(); - let (state, guard) = state::create(services.clone()); + // SAFETY: `guard` is returned alongside `router` and held in `serve()` + // until the HTTP server has finished serving all requests and dropped + // `router`, ensuring no `State` copy can be dereferenced after `Services` + // is dropped. + let (state, guard) = unsafe { state::create(services.clone()) }; let router = conduwuit_api::router::build(router, state) .merge(conduwuit_web::build(services)) .fallback(not_found) diff --git a/src/service/state.rs b/src/service/state.rs index 9f18ad73a..61234a4e6 100644 --- a/src/service/state.rs +++ b/src/service/state.rs @@ -11,7 +11,15 @@ pub struct Guard { services: Arc, } -pub fn create(services: Arc) -> (State, Guard) { +/// Create a raw-pointer `State` handle paired with a `Guard` that keeps +/// `Services` alive. +/// +/// # Safety +/// `State` is `Copy` and dereferences its raw pointer without reference +/// counting. The caller must ensure that no `State` (nor any copy of it) is +/// dereferenced after `Guard` and all other `Arc` clones have been +/// dropped. +pub unsafe fn create(services: Arc) -> (State, Guard) { let state = State { services: Arc::into_raw(services.clone()), }; From 306be392ba17e8879cdc5966f3666b7b23ccc4a9 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:10:38 +0000 Subject: [PATCH 305/342] fix(core): Mark dlopen/dlsym wrappers unsafe in core::mods --- src/core/mods/module.rs | 32 +++++++++++++++++++++++++------- src/core/mods/new.rs | 18 +++++++++++++----- src/main/mods.rs | 19 +++++++++++++++---- 3 files changed, 53 insertions(+), 16 deletions(-) diff --git a/src/core/mods/module.rs b/src/core/mods/module.rs index 3c8183962..0cd49cb28 100644 --- a/src/core/mods/module.rs +++ b/src/core/mods/module.rs @@ -13,11 +13,21 @@ pub struct Module { } impl Module { - pub fn from_name(name: &str) -> Result { Self::from_path(path::from_name(name)?) } + /// # Safety + /// See [`new::from_name`]: loads a shared library via `dlopen(3)` and runs + /// its initialization routines. + pub unsafe fn from_name(name: &str) -> Result { + // SAFETY: Upheld by caller. + unsafe { Self::from_path(path::from_name(name)?) } + } - pub fn from_path(path: OsString) -> Result { + /// # Safety + /// See [`new::from_path`]: loads a shared library via `dlopen(3)` and runs + /// its initialization routines. + pub unsafe fn from_path(path: OsString) -> Result { Ok(Self { - handle: Some(new::from_path(&path)?), + // SAFETY: Upheld by caller. + handle: Some(unsafe { new::from_path(&path)? }), loaded: SystemTime::now(), path, }) @@ -38,16 +48,24 @@ impl Module { } } - pub fn get(&self, name: &str) -> Result> { + /// Look up a symbol in this module via `dlsym(3)`. + /// + /// # Safety + /// `Prototype` is not checked against the symbol's actual type or ABI in + /// the loaded shared library. The caller must ensure `name` refers to a + /// symbol whose type, calling convention, and ABI exactly match + /// `Prototype`. + pub unsafe fn get(&self, name: &str) -> Result> { let cname = CString::new(name.to_owned()).expect("terminated string from provided name"); let handle = self .handle .as_ref() .expect("backing library loaded by this instance"); - // SAFETY: Calls dlsym(3) on unix platforms. This might not have to be - // unsafe if wrapped in libloading with_dlerror(). - let sym = unsafe { handle.get::(cname.as_bytes()) }; + // SAFETY: Caller guarantees `Prototype` matches the symbol's actual + // type and ABI. Passing `as_bytes_with_nul()` avoids a redundant copy + // inside `libloading`. + let sym = unsafe { handle.get::(cname.as_bytes_with_nul()) }; let sym = sym.expect("symbol found; binding successful"); Ok(sym) diff --git a/src/core/mods/new.rs b/src/core/mods/new.rs index 41eec89ef..e138b2046 100644 --- a/src/core/mods/new.rs +++ b/src/core/mods/new.rs @@ -5,14 +5,22 @@ use crate::{Err, Result}; const OPEN_FLAGS: i32 = libloading::os::unix::RTLD_LAZY | libloading::os::unix::RTLD_GLOBAL; -pub fn from_name(name: &str) -> Result { +/// # Safety +/// Loads a shared library via `dlopen(3)`, which executes the library's +/// initialization routines (`.init_array` / constructors). The caller must +/// ensure the resolved module is trusted and ABI-compatible with this binary. +pub unsafe fn from_name(name: &str) -> Result { let path = path::from_name(name)?; - from_path(&path) + // SAFETY: Upheld by caller. + unsafe { from_path(&path) } } -pub fn from_path(path: &OsStr) -> Result { - //SAFETY: Calls dlopen(3) on unix platforms. This might not have to be - // unsafe if wrapped in with_dlerror. +/// # Safety +/// Loads a shared library via `dlopen(3)`, which executes the library's +/// initialization routines (`.init_array` / constructors). The caller must +/// ensure `path` points to a trusted, ABI-compatible shared library. +pub unsafe fn from_path(path: &OsStr) -> Result { + // SAFETY: Caller guarantees `path` is a trusted, ABI-compatible library. let lib = unsafe { Library::open(Some(path), OPEN_FLAGS) }; if let Err(e) = lib { let name = path::to_name(path)?; diff --git a/src/main/mods.rs b/src/main/mods.rs index c0a945497..c00c30f70 100644 --- a/src/main/mods.rs +++ b/src/main/mods.rs @@ -42,7 +42,10 @@ pub(crate) async fn run(server: &Arc, starts: bool) -> Result<(bool, boo let main_lock = server.mods.read().await; let main_mod = (*main_lock).last().expect("main module loaded"); if starts { - let start = main_mod.get::("start")?; + // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern + // "Rust" fn start` with signature matching `StartFuncProto`, compiled + // with the same toolchain and flags. + let start = unsafe { main_mod.get::("start")? }; match start(&server.server).await { | Ok(services) => server.services.lock().await.insert(services), | Err(error) => { @@ -54,7 +57,10 @@ pub(crate) async fn run(server: &Arc, starts: bool) -> Result<(bool, boo server.server.stopping.store(false, Ordering::Release); - let run = main_mod.get::("run")?; + // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern + // "Rust" fn run` with signature matching `RunFuncProto`, compiled with the + // same toolchain and flags. + let run = unsafe { main_mod.get::("run")? }; if let Err(error) = run(server .services .lock() @@ -72,7 +78,10 @@ pub(crate) async fn run(server: &Arc, starts: bool) -> Result<(bool, boo let stops = !reloads || stale_from_mods(&main_lock)? <= restart_thresh(); let starts = reloads && stops; if stops { - let stop = main_mod.get::("stop")?; + // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern + // "Rust" fn stop` with signature matching `StopFuncProto`, compiled + // with the same toolchain and flags. + let stop = unsafe { main_mod.get::("stop")? }; if let Err(error) = stop( server .services @@ -102,7 +111,9 @@ pub(crate) async fn open(server: &Arc) -> Result { for (i, name) in MODULE_NAMES.iter().enumerate() { if mods.get(i).is_none() { - mods.push(mods::Module::from_name(name)?); + // SAFETY: `MODULE_NAMES` are this workspace's own hot-reloadable + // shared libraries built with the same compiler/ABI. + mods.push(unsafe { mods::Module::from_name(name)? }); } } From 9744a6e3322b35c299841adb988ef021d64fa1ef Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:11:14 +0000 Subject: [PATCH 306/342] fix(core): Reject non-ELF targets in mod_init! and mod_fini! macros --- src/core/mods/macros.rs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/core/mods/macros.rs b/src/core/mods/macros.rs index 1f3b7f5fa..fe434ec94 100644 --- a/src/core/mods/macros.rs +++ b/src/core/mods/macros.rs @@ -22,11 +22,24 @@ macro_rules! mod_dtor { #[macro_export] macro_rules! mod_init { ($body:block) => { + #[cfg(not(all(target_family = "unix", not(target_vendor = "apple"))))] + compile_error!("conduwuit_mods (mod_init!) requires an ELF Unix target"); + #[used] - #[cfg_attr(target_family = "unix", unsafe(link_section = ".init_array"))] + // SAFETY: `.init_array` is the standard ELF constructor pointer table; + // the dynamic loader invokes `_mod_init` before `main()` or on `dlopen`. + #[cfg_attr( + all(target_family = "unix", not(target_vendor = "apple")), + unsafe(link_section = ".init_array") + )] static MOD_INIT: unsafe extern "C" fn() = { _mod_init }; - #[cfg_attr(target_family = "unix", unsafe(link_section = ".text.startup"))] + // SAFETY: `.text.startup` is the standard ELF text subsection for + // initialization functions. + #[cfg_attr( + all(target_family = "unix", not(target_vendor = "apple")), + unsafe(link_section = ".text.startup") + )] unsafe extern "C" fn _mod_init() -> () $body }; } @@ -34,11 +47,24 @@ macro_rules! mod_init { #[macro_export] macro_rules! mod_fini { ($body:block) => { + #[cfg(not(all(target_family = "unix", not(target_vendor = "apple"))))] + compile_error!("conduwuit_mods (mod_fini!) requires an ELF Unix target"); + #[used] - #[cfg_attr(target_family = "unix", unsafe(link_section = ".fini_array"))] + // SAFETY: `.fini_array` is the standard ELF destructor pointer table; + // the dynamic loader invokes `_mod_fini` on `dlclose` or process teardown. + #[cfg_attr( + all(target_family = "unix", not(target_vendor = "apple")), + unsafe(link_section = ".fini_array") + )] static MOD_FINI: unsafe extern "C" fn() = { _mod_fini }; - #[cfg_attr(target_family = "unix", unsafe(link_section = ".text.startup"))] + // SAFETY: `.text.exit` / `.text.startup` is a standard ELF text + // subsection for teardown/initialization functions. + #[cfg_attr( + all(target_family = "unix", not(target_vendor = "apple")), + unsafe(link_section = ".text.startup") + )] unsafe extern "C" fn _mod_fini() -> () $body }; } From 7e678869ec76404f6192ff3aa2a58a5eefecdcca Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 02:14:25 +0000 Subject: [PATCH 307/342] refactor(core): Remove unneeded unsafe in UnwrapInfallible and Unquoted --- src/core/utils/result/unwrap_infallible.rs | 8 +++----- src/core/utils/string/unquoted.rs | 9 +++++---- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/core/utils/result/unwrap_infallible.rs b/src/core/utils/result/unwrap_infallible.rs index 99309e025..0baf87b66 100644 --- a/src/core/utils/result/unwrap_infallible.rs +++ b/src/core/utils/result/unwrap_infallible.rs @@ -1,7 +1,6 @@ use std::convert::Infallible; -use super::{DebugInspect, Result}; -use crate::error; +use super::Result; pub trait UnwrapInfallible { fn unwrap_infallible(self) -> T; @@ -10,8 +9,7 @@ pub trait UnwrapInfallible { impl UnwrapInfallible for Result { #[inline] fn unwrap_infallible(self) -> T { - // SAFETY: Branchless unwrap for errors that can never happen. In debug - // mode this is asserted. - unsafe { self.debug_inspect_err(error::infallible).unwrap_unchecked() } + let Ok(val) = self; + val } } diff --git a/src/core/utils/string/unquoted.rs b/src/core/utils/string/unquoted.rs index abf7bbc16..a23f49539 100644 --- a/src/core/utils/string/unquoted.rs +++ b/src/core/utils/string/unquoted.rs @@ -32,11 +32,12 @@ impl<'a> From<&'a str> for &'a Unquoted { fn from(s: &'a str) -> &'a Unquoted { let s: &'a str = s.unquote_infallible(); - //SAFETY: This is a pattern I lifted from ruma-identifiers for - // strong-type strs by wrapping in a tuple-struct. - #[allow(clippy::transmute_ptr_to_ptr)] + // SAFETY: `Unquoted` is `#[repr(transparent)]` over `str`, so + // `*const str` and `*const Unquoted` have identical layout and + // metadata, and the returned reference preserves lifetime `'a`. + #[allow(clippy::as_conversions)] unsafe { - std::mem::transmute(s) + &*(std::ptr::from_ref::(s) as *const Unquoted) } } } From 5ad36c0914e4d714b341f824a7233560cd03f325 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 17:59:19 +0000 Subject: [PATCH 308/342] refactor(core): Drop hot reload support This was unused and a hotbed of potential issues --- Cargo.lock | 15 +-- Cargo.toml | 54 --------- docs/development/_meta.json | 5 - docs/development/hot_reload.mdx | 200 -------------------------------- docs/development/index.mdx | 7 -- docs/reference/admin/server.md | 4 - src/admin/mod.rs | 3 - src/admin/server/commands.rs | 8 -- src/admin/server/mod.rs | 4 - src/api/mod.rs | 3 - src/core/Cargo.toml | 5 - src/core/mod.rs | 13 --- src/core/mods/canary.rs | 28 ----- src/core/mods/macros.rs | 70 ----------- src/core/mods/mod.rs | 11 -- src/core/mods/module.rs | 93 --------------- src/core/mods/new.rs | 31 ----- src/core/mods/path.rs | 41 ------- src/core/server.rs | 27 ----- src/database/mod.rs | 3 - src/main/Cargo.toml | 3 - src/main/mod.rs | 40 +------ src/main/mods.rs | 174 --------------------------- src/main/server.rs | 7 -- src/main/signal.rs | 5 +- src/router/mod.rs | 16 +-- src/service/mod.rs | 12 +- 27 files changed, 11 insertions(+), 871 deletions(-) delete mode 100644 docs/development/hot_reload.mdx delete mode 100644 src/core/mods/canary.rs delete mode 100644 src/core/mods/macros.rs delete mode 100644 src/core/mods/mod.rs delete mode 100644 src/core/mods/module.rs delete mode 100644 src/core/mods/new.rs delete mode 100644 src/core/mods/path.rs delete mode 100644 src/main/mods.rs diff --git a/Cargo.lock b/Cargo.lock index 50af5a466..9a40fe2fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -759,7 +759,7 @@ checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" dependencies = [ "glob", "libc", - "libloading 0.8.9", + "libloading", ] [[package]] @@ -997,7 +997,6 @@ dependencies = [ "ipaddress", "lettre", "libc", - "libloading 0.9.1", "libmimalloc-sys", "lock_api 0.5.0", "maplit", @@ -3241,16 +3240,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "libloading" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10" -dependencies = [ - "cfg-if", - "windows-link", -] - [[package]] name = "libm" version = "0.2.16" @@ -5652,7 +5641,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" dependencies = [ "annotate-snippets", - "base64 0.22.1", + "base64 0.23.1", "encoding_rs_io", "granit-parser", "nohash-hasher", diff --git a/Cargo.toml b/Cargo.toml index 18558e4db..dfd81c967 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -269,9 +269,6 @@ features = [ [workspace.dependencies.tokio-metrics] version = "0.5.2" -[workspace.dependencies.libloading] -version = "0.9.0" - [workspace.dependencies.wildmatch] version = "2.7.0" @@ -753,74 +750,23 @@ inherits = "release" # Developer profile # -# To enable hot-reloading: -# 1. Uncomment all of the rustflags here. -# 2. Uncomment crate-type=dylib in src/*/Cargo.toml -# -# opt-level, mir-opt-level, validate-mir are not known to interfere with reloading -# and can be raised if build times are tolerable. - [profile.dev] debug = "full" opt-level = 0 panic = "unwind" debug-assertions = true incremental = true -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztime-passes', -# '-Zmir-opt-level=0', -# '-Zvalidate-mir=false', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zstaticlib-prefer-dynamic=true', -# '-Zstaticlib-allow-rdylib-deps=true', -# '-Zpacked-bundled-libs=false', -# '-Zplt=true', -# '-Crpath=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,--allow-shlib-undefined', -# '-Clink-arg=-Wl,-z,keep-text-section-prefix', -# '-Clink-arg=-Wl,-z,lazy', -#] [profile.dev.package.conduwuit_core] inherits = "dev" [profile.dev.package.conduwuit] inherits = "dev" -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztime-passes', -# '-Zmir-opt-level=0', -# '-Zvalidate-mir=false', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zexport-executable-symbols=true', -# '-Zplt=true', -# '-Crpath=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,--allow-shlib-undefined', -# '-Clink-arg=-Wl,--export-dynamic', -# '-Clink-arg=-Wl,-z,lazy', -#] [profile.dev.package.'*'] inherits = "dev" debug = 'limited' codegen-units = 1 opt-level = 'z' -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zstaticlib-prefer-dynamic=true', -# '-Zstaticlib-allow-rdylib-deps=true', -# '-Zpacked-bundled-libs=true', -# '-Zplt=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,-z,lazy', -# '-Clink-arg=-Wl,-z,nodelete', -#] # primarily used for CI [profile.test] diff --git a/docs/development/_meta.json b/docs/development/_meta.json index c89720f5b..82db72db5 100644 --- a/docs/development/_meta.json +++ b/docs/development/_meta.json @@ -18,10 +18,5 @@ "type": "file", "name": "testing", "label": "Testing" - }, - { - "type": "file", - "name": "hot_reload", - "label": "Hot Reloading" } ] diff --git a/docs/development/hot_reload.mdx b/docs/development/hot_reload.mdx deleted file mode 100644 index 11cb4253f..000000000 --- a/docs/development/hot_reload.mdx +++ /dev/null @@ -1,200 +0,0 @@ -# Hot Reloading ("Live" Development) - -Note that hot reloading has not been refactored in quite a while and is not -guaranteed to work at this time. - -### Summary - -When developing in debug-builds with the nightly toolchain, Continuwuity is modular -using dynamic libraries and various parts of the application are hot-reloadable -while the server is running: http api handlers, admin commands, services, -database, etc. These are all split up into individual workspace crates as seen -in the `src/` directory. Changes to sourcecode in a crate rebuild that crate and -subsequent crates depending on it. Reloading then occurs for the changed crates. - -Release builds still produce static binaries which are unaffected. Rust's -soundness guarantees are in full force. Thus you cannot hot-reload release -binaries. - -### Requirements - -Currently, this development setup only works on x86_64 and aarch64 Linux glibc. -[musl explicitly does not support hot reloadable libraries, and does not -implement `dlclose`][2]. macOS does not fully support our usage of `RTLD_GLOBAL` -possibly due to some thread-local issues. [This Rust issue][3] may be of -relevance, specifically [this comment][4]. It may be possible to get it working -on only very modern macOS versions such as at least Sonoma, as currently loading -dylibs is supported, but not unloading them in our setup, and the cited comment -mentions an Apple WWDC confirming there have been TLS changes to somewhat make -this possible. - -As mentioned above this requires the nightly toolchain. This is due to reliance -on various Cargo.toml features that are only available on nightly, most -specifically `RUSTFLAGS` in Cargo.toml. Some of the implementation could also be -simpler based on other various nightly features. We hope lots of nightly -features start making it out of nightly sooner as there have been dozens of very -helpful features that have been stuck in nightly ("unstable") for at least 5+ -years that would make this simpler. We encourage greater community consensus to -move these features into stability. - -This currently only works on x86_64/aarch64 Linux with a glibc C library. musl C -library, macOS, and likely other host architectures are not supported (if other -architectures work, feel free to let us know and/or make a PR updating this). -This should work on GNU ld and lld (rust-lld) and gcc/clang, however if you -happen to have linker issues it's recommended to try using `mold` or `gold` -linkers, and please let us know in the [Continuwuity Matrix room][7] the linker -error and what linker solved this issue so we can figure out a solution. Ideally -there should be minimal friction to using this, and in the future a build script -(`build.rs`) may be suitable to making this easier to use if the capabilities -allow us. - -### Usage - -As of 19 May 2024, the instructions for using this are: - -0. Have patience. Don't hesitate to join the [Continuwuity Matrix room][7] to - receive help using this. As indicated by the various rustflags used and some -of the interesting issues linked at the bottom, this is definitely not something -the Rust ecosystem or toolchain is used to doing. - -1. Install the nightly toolchain using rustup. You may need to use `rustup - override set nightly` in your local Continuwuity directory, or use `cargo -+nightly` for all actions. - -2. Uncomment `cargo-features` at the top level / root Cargo.toml - -3. Scroll down to the `# Developer profile` section and uncomment ALL the - rustflags for each dev profile and their respective packages. - -4. In each workspace crate's Cargo.toml (everything under `src/*` AND - `deps/rust-rocksdb/Cargo.toml`), uncomment the `dylib` crate type under -`[lib]`. - -5. Due to [this rpath issue][5], you must export the `LD_LIBRARY_PATH` - environment variable to your nightly Rust toolchain library directory. If -using rustup (hopefully), use this: `export -LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/` - -6. Start the server. You can use `cargo +nightly run` for this along with the - standard. - -7. Make some changes where you need to. - -8. In a separate terminal window in the same directory (or using a terminal - multiplexer like tmux), run the *build* Cargo command `cargo +nightly build`. - Cargo should only rebuild what was changed / what's necessary, so it should - not be rebuilding all the crates. - -9. In your Continuwuity server terminal, hit/send `CTRL+C` signal. This will tell - Continuwuity to find which libraries need to be reloaded, and reloads them as - necessary. - -10. If there were no errors, it will tell you it successfully reloaded `#` - modules, and your changes should now be visible. Repeat 7 - 9 as needed. - -To shutdown Continuwuity in this setup, hit/send `CTRL+\`. Normal builds still -shutdown with `CTRL+C` as usual. - -Steps 1 - 5 are the initial first-time steps for using this. To remove the hot -reload setup, revert/comment all the Cargo.toml changes. - -As mentioned in the requirements section, if you happen to have some linker -issues, try using the `-fuse-ld=` rustflag and specify mold or gold in all the -`rustflags` definitions in the top level Cargo.toml, and please let us know in -the [Continuwuity Matrix room][7] the problem. mold can be installed typically -through your distro, and gold is provided by the binutils package. - -It's possible a helper script can be made to do all of this, or most preferably -a specially made build script (build.rs). `cargo watch` support will be -implemented soon which will eliminate the need to manually run `cargo build` all -together. - -### Addendum - -Conduit was inherited as a single crate without modularity or reloading in its -design. Reasonable partitioning and abstraction allowed a split into several -crates, though many circular dependencies had to be corrected. The resulting -crates now form a directed graph as depicted in figures below. The interfacing -between these crates is still extremely broad which is not mitigable. - -Initially [hot_lib_reload][6] was investigated but found appropriate for a -project designed with modularity through limited interfaces, not a large and -complex existing codebase. Instead a bespoke solution built directly on -[libloading][8] satisfied our constraints. This required relatively minimal -modifications and zero maintenance burden compared to what would be required -otherwise. The technical difference lies with relocation processing: we leverage -global bindings (`RTLD_GLOBAL`) in a very intentional way. Most libraries and -off-the-shelf module systems (such as [hot_lib_reload][6]) restrict themselves -to local bindings (`RTLD_LOCAL`). This allows them to release software to -multiple platforms with much greater consistency, but at the cost of burdening -applications to explicitly manage these bindings. In our case with an optional -feature for developers, we shrug any such requirement to enjoy the cost/benefit -on platforms where global relocations are properly cooperative. - -To make use of `RTLD_GLOBAL` the application has to be oriented as a directed -acyclic graph. The primary rule is simple and illustrated in the figure below: -**no crate is allowed to call a function or use a variable from a crate below -it.** - -![Continuwuity's dynamic library setup diagram - created by Jason -Volk](./assets/libraries.png) - -When a symbol is referenced between crates they become bound: **crates cannot be -unloaded until their calling crates are first unloaded.** Thus we start the -reloading process from the crate which has no callers. There is a small problem -though: the first crate is called by the base executable itself! This is solved -by using an `RTLD_LOCAL` binding for just one link between the main executable -and the first crate, freeing the executable from all modules as no global -binding ever occurs between them. - -![Continuwuity's reload and load order diagram - created by Jason -Volk](./assets/reload_order.png) - -Proper resource management is essential for reliable reloading to occur. This is -a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is -remarkably low, generally stemming from poor patterns and practices. -Unfortunately static analysis doesn't enforce reload-safety programmatically -(though it could one day), for now hazards can be avoided by knowing a few basic -do's and dont's: - -1. Understand that code is memory. Just like one is forbidden from referencing - free'd memory, one must not transfer control to free'd code. Exposure to this -is primarily from two things: - - - Callbacks, which this project makes very little use of. - - Async tasks, which are addressed below. - -2. Tie all resources to a scope or object lifetime with greatest possible -symmetry (locality). For our purposes this applies to code resources, which -means async blocks and tokio tasks. - - - **Never spawn a task without receiving and storing its JoinHandle**. - - **Always wait on join handles** before leaving a scope or in another cleanup - function called by an owning scope. - -3. Know any minor specific quirks documented in code or here: - - - Don't use `tokio::spawn`, instead use our `Handle` in `core/server.rs`, which - is reachable in most of the codebase via `services()` or other state. This is - due to some bugs or assumptions made in tokio, as it happens in `unsafe {}` - blocks, which are mitigated by circumventing some thread-local variables. Using - runtime handles is good practice in any case. - -The initial implementation PR is available [here][1]. - -### Interesting related issues/bugs - -- [DT_RUNPATH produced in binary with rpath = true is wrong (cargo)][5] -- [Disabling MIR Optimization in Rust Compilation -(cargo)](https://internals.rust-lang.org/t/disabling-mir-optimization-in-rust-compilation/19066/5) -- [Workspace-level metadata -(cargo-deb)](https://github.com/kornelski/cargo-deb/issues/68) - -[1]: https://forgejo.ellis.link/continuwuation/continuwuity/pulls/387 -[2]: https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading-libraries -[3]: https://github.com/rust-lang/rust/issues/28794 -[4]: https://github.com/rust-lang/rust/issues/28794#issuecomment-368693049 -[5]: https://github.com/rust-lang/cargo/issues/12746 -[6]: https://crates.io/crates/hot-lib-reloader/ -[7]: https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org -[8]: https://crates.io/crates/libloading diff --git a/docs/development/index.mdx b/docs/development/index.mdx index 280c25c64..d9aef98b3 100644 --- a/docs/development/index.mdx +++ b/docs/development/index.mdx @@ -37,13 +37,6 @@ It is highly unlikely you will ever need to add a new workspace member, but if you truly find yourself needing to, we recommend reaching out to us in the Matrix room for discussions about it beforehand. -The primary inspiration for this design was apart of hot reloadable development, -to support "Continuwuity as a library" where specific parts can simply be -swapped out. There is evidence Conduit wanted to go this route too as `axum` is -technically an optional feature in Conduit, and can be compiled without the -binary or axum library for handling inbound web requests; but it was never -completed or worked. - See the Rust documentation on [Workspaces][workspaces] for general questions and information on Cargo workspaces. diff --git a/docs/reference/admin/server.md b/docs/reference/admin/server.md index 95a0af91d..0a56394fe 100644 --- a/docs/reference/admin/server.md +++ b/docs/reference/admin/server.md @@ -36,10 +36,6 @@ List database backups Send a message to the admin room -## `!admin server reload` - -Hot-reload the server - ## `!admin server restart` Restart the server diff --git a/src/admin/mod.rs b/src/admin/mod.rs index 079aa0185..eab68e4d0 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -34,9 +34,6 @@ pub(crate) use crate::{context::Context, utils::get_room_info}; pub(crate) const PAGE_SIZE: usize = 100; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - pub use crate::admin::AdminCommand; /// Install the admin command processor diff --git a/src/admin/server/commands.rs b/src/admin/server/commands.rs index 1173c5457..51042f89b 100644 --- a/src/admin/server/commands.rs +++ b/src/admin/server/commands.rs @@ -110,14 +110,6 @@ impl crate::Context<'_> { self.write_str("Notice was sent to #admins").await } - pub(super) async fn reload_mods(&self) -> Result { - self.bail_restricted()?; - - self.services.server.reload()?; - - self.write_str("Reloading server...").await - } - #[cfg(unix)] pub(super) async fn restart(&self, force: bool) -> Result { use conduwuit::utils::sys::current_exe_deleted; diff --git a/src/admin/server/mod.rs b/src/admin/server/mod.rs index ff6933ef9..c9fb6d299 100644 --- a/src/admin/server/mod.rs +++ b/src/admin/server/mod.rs @@ -39,10 +39,6 @@ pub enum ServerCommand { message: Vec, }, - /// Hot-reload the server - #[command(name = "reload", alias = "reload-mods")] - ReloadMods, - #[cfg(unix)] /// Restart the server Restart { diff --git a/src/api/mod.rs b/src/api/mod.rs index c2e71ba8c..df050e7be 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -16,6 +16,3 @@ pub mod client_ip; pub mod admin; pub(crate) use self::router::{Ruma, RumaResponse, State}; - -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 48a0f2e9e..72aae4312 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -20,9 +20,6 @@ crate-type = [ brotli_compression = [ "reqwest/brotli", ] -conduwuit_mods = [ - "dep:libloading" -] gzip_compression = [ "reqwest/gzip", ] @@ -85,8 +82,6 @@ http-body-util.workspace = true http.workspace = true ipaddress.workspace = true libc.workspace = true -libloading.workspace = true -libloading.optional = true lettre.workspace = true num-traits.workspace = true rand.workspace = true diff --git a/src/core/mod.rs b/src/core/mod.rs index d815bc545..f0388be62 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -8,19 +8,6 @@ pub mod info; pub mod log; pub mod matrix; pub mod metrics; -pub mod mods; - -#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))] -pub mod mods { - #[macro_export] - macro_rules! mod_ctor { - () => {}; - } - #[macro_export] - macro_rules! mod_dtor { - () => {}; - } -} pub mod server; pub mod utils; diff --git a/src/core/mods/canary.rs b/src/core/mods/canary.rs deleted file mode 100644 index 6095608c6..000000000 --- a/src/core/mods/canary.rs +++ /dev/null @@ -1,28 +0,0 @@ -use std::sync::atomic::{AtomicI32, Ordering}; - -const ORDERING: Ordering = Ordering::Relaxed; -static STATIC_DTORS: AtomicI32 = AtomicI32::new(0); - -/// Called by Module::unload() to indicate module is about to be unloaded and -/// static destruction is intended. This will allow verifying it actually took -/// place. -pub(crate) fn prepare() { - let count = STATIC_DTORS.fetch_sub(1, ORDERING); - debug_assert!(count <= 0, "STATIC_DTORS should not be greater than zero."); -} - -/// Called by static destructor of a module. This call should only be found -/// inside a mod_fini! macro. Do not call from anywhere else. -#[inline(always)] -pub fn report() { let _count = STATIC_DTORS.fetch_add(1, ORDERING); } - -/// Called by Module::unload() (see check()) with action in case a check() -/// failed. This can allow a stuck module to be noted while allowing for other -/// independent modules to be diagnosed. -pub(crate) fn check_and_reset() -> bool { STATIC_DTORS.swap(0, ORDERING) == 0 } - -/// Called by Module::unload() after unload to verify static destruction took -/// place. A call to prepare() must be made prior to Module::unload() and making -/// this call. -#[allow(dead_code)] -pub(crate) fn check() -> bool { STATIC_DTORS.load(ORDERING) == 0 } diff --git a/src/core/mods/macros.rs b/src/core/mods/macros.rs deleted file mode 100644 index fe434ec94..000000000 --- a/src/core/mods/macros.rs +++ /dev/null @@ -1,70 +0,0 @@ -#[macro_export] -macro_rules! mod_ctor { - ( $($body:block)? ) => { - $crate::mod_init! {{ - $crate::debug_info!("Module loaded"); - $($body)? - }} - } -} - -#[macro_export] -macro_rules! mod_dtor { - ( $($body:block)? ) => { - $crate::mod_fini! {{ - $crate::debug_info!("Module unloading"); - $($body)? - $crate::mods::canary::report(); - }} - } -} - -#[macro_export] -macro_rules! mod_init { - ($body:block) => { - #[cfg(not(all(target_family = "unix", not(target_vendor = "apple"))))] - compile_error!("conduwuit_mods (mod_init!) requires an ELF Unix target"); - - #[used] - // SAFETY: `.init_array` is the standard ELF constructor pointer table; - // the dynamic loader invokes `_mod_init` before `main()` or on `dlopen`. - #[cfg_attr( - all(target_family = "unix", not(target_vendor = "apple")), - unsafe(link_section = ".init_array") - )] - static MOD_INIT: unsafe extern "C" fn() = { _mod_init }; - - // SAFETY: `.text.startup` is the standard ELF text subsection for - // initialization functions. - #[cfg_attr( - all(target_family = "unix", not(target_vendor = "apple")), - unsafe(link_section = ".text.startup") - )] - unsafe extern "C" fn _mod_init() -> () $body - }; -} - -#[macro_export] -macro_rules! mod_fini { - ($body:block) => { - #[cfg(not(all(target_family = "unix", not(target_vendor = "apple"))))] - compile_error!("conduwuit_mods (mod_fini!) requires an ELF Unix target"); - - #[used] - // SAFETY: `.fini_array` is the standard ELF destructor pointer table; - // the dynamic loader invokes `_mod_fini` on `dlclose` or process teardown. - #[cfg_attr( - all(target_family = "unix", not(target_vendor = "apple")), - unsafe(link_section = ".fini_array") - )] - static MOD_FINI: unsafe extern "C" fn() = { _mod_fini }; - - // SAFETY: `.text.exit` / `.text.startup` is a standard ELF text - // subsection for teardown/initialization functions. - #[cfg_attr( - all(target_family = "unix", not(target_vendor = "apple")), - unsafe(link_section = ".text.startup") - )] - unsafe extern "C" fn _mod_fini() -> () $body - }; -} diff --git a/src/core/mods/mod.rs b/src/core/mods/mod.rs deleted file mode 100644 index b8f06f29f..000000000 --- a/src/core/mods/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - -pub(crate) use libloading::os::unix::{Library, Symbol}; - -pub mod canary; -pub mod macros; -pub mod module; -pub mod new; -pub mod path; - -pub use module::Module; diff --git a/src/core/mods/module.rs b/src/core/mods/module.rs deleted file mode 100644 index 0cd49cb28..000000000 --- a/src/core/mods/module.rs +++ /dev/null @@ -1,93 +0,0 @@ -use std::{ - ffi::{CString, OsString}, - time::SystemTime, -}; - -use super::{Library, Symbol, canary, new, path}; -use crate::{Result, error}; - -pub struct Module { - handle: Option, - loaded: SystemTime, - path: OsString, -} - -impl Module { - /// # Safety - /// See [`new::from_name`]: loads a shared library via `dlopen(3)` and runs - /// its initialization routines. - pub unsafe fn from_name(name: &str) -> Result { - // SAFETY: Upheld by caller. - unsafe { Self::from_path(path::from_name(name)?) } - } - - /// # Safety - /// See [`new::from_path`]: loads a shared library via `dlopen(3)` and runs - /// its initialization routines. - pub unsafe fn from_path(path: OsString) -> Result { - Ok(Self { - // SAFETY: Upheld by caller. - handle: Some(unsafe { new::from_path(&path)? }), - loaded: SystemTime::now(), - path, - }) - } - - pub fn unload(&mut self) { - canary::prepare(); - self.close(); - if !canary::check_and_reset() { - let name = self.name().expect("Module is named"); - error!("Module {name:?} is stuck and failed to unload."); - } - } - - pub(crate) fn close(&mut self) { - if let Some(handle) = self.handle.take() { - handle.close().expect("Module handle closed"); - } - } - - /// Look up a symbol in this module via `dlsym(3)`. - /// - /// # Safety - /// `Prototype` is not checked against the symbol's actual type or ABI in - /// the loaded shared library. The caller must ensure `name` refers to a - /// symbol whose type, calling convention, and ABI exactly match - /// `Prototype`. - pub unsafe fn get(&self, name: &str) -> Result> { - let cname = CString::new(name.to_owned()).expect("terminated string from provided name"); - let handle = self - .handle - .as_ref() - .expect("backing library loaded by this instance"); - - // SAFETY: Caller guarantees `Prototype` matches the symbol's actual - // type and ABI. Passing `as_bytes_with_nul()` avoids a redundant copy - // inside `libloading`. - let sym = unsafe { handle.get::(cname.as_bytes_with_nul()) }; - let sym = sym.expect("symbol found; binding successful"); - - Ok(sym) - } - - pub fn deleted(&self) -> Result { - let mtime = path::mtime(self.path())?; - let res = mtime > self.loaded; - - Ok(res) - } - - pub fn name(&self) -> Result { path::to_name(self.path()) } - - #[must_use] - pub fn path(&self) -> &OsString { &self.path } -} - -impl Drop for Module { - fn drop(&mut self) { - if self.handle.is_some() { - self.unload(); - } - } -} diff --git a/src/core/mods/new.rs b/src/core/mods/new.rs deleted file mode 100644 index e138b2046..000000000 --- a/src/core/mods/new.rs +++ /dev/null @@ -1,31 +0,0 @@ -use std::ffi::OsStr; - -use super::{Library, path}; -use crate::{Err, Result}; - -const OPEN_FLAGS: i32 = libloading::os::unix::RTLD_LAZY | libloading::os::unix::RTLD_GLOBAL; - -/// # Safety -/// Loads a shared library via `dlopen(3)`, which executes the library's -/// initialization routines (`.init_array` / constructors). The caller must -/// ensure the resolved module is trusted and ABI-compatible with this binary. -pub unsafe fn from_name(name: &str) -> Result { - let path = path::from_name(name)?; - // SAFETY: Upheld by caller. - unsafe { from_path(&path) } -} - -/// # Safety -/// Loads a shared library via `dlopen(3)`, which executes the library's -/// initialization routines (`.init_array` / constructors). The caller must -/// ensure `path` points to a trusted, ABI-compatible shared library. -pub unsafe fn from_path(path: &OsStr) -> Result { - // SAFETY: Caller guarantees `path` is a trusted, ABI-compatible library. - let lib = unsafe { Library::open(Some(path), OPEN_FLAGS) }; - if let Err(e) = lib { - let name = path::to_name(path)?; - return Err!("Loading module {name:?} failed: {e}"); - } - - Ok(lib.expect("module loaded")) -} diff --git a/src/core/mods/path.rs b/src/core/mods/path.rs deleted file mode 100644 index b792890b9..000000000 --- a/src/core/mods/path.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::{ - env::current_exe, - ffi::{OsStr, OsString}, - path::{Path, PathBuf}, - time::SystemTime, -}; - -use libloading::library_filename; - -use crate::Result; - -pub fn from_name(name: &str) -> Result { - let root = PathBuf::new(); - let exe_path = current_exe()?; - let exe_dir = exe_path.parent().unwrap_or(&root); - let mut mod_path = exe_dir.to_path_buf(); - let mod_file = library_filename(name); - mod_path.push(mod_file); - - Ok(mod_path.into_os_string()) -} - -pub fn to_name(path: &OsStr) -> Result { - let path = Path::new(path); - let name = path - .file_stem() - .expect("path file stem") - .to_str() - .expect("name string"); - - let name = name.strip_prefix("lib").unwrap_or(name).to_owned(); - - Ok(name) -} - -pub fn mtime(path: &OsStr) -> Result { - let meta = std::fs::metadata(path)?; - let mtime = meta.modified()?; - - Ok(mtime) -} diff --git a/src/core/server.rs b/src/core/server.rs index c84936478..328eb50ae 100644 --- a/src/core/server.rs +++ b/src/core/server.rs @@ -27,10 +27,6 @@ pub struct Server { /// observable used on shutdown and should not be modified. pub stopping: AtomicBool, - /// Reload/shutdown desired indicator; when false, shutdown is desired. This - /// is an observable used on shutdown and modifying is not recommended. - pub reloading: AtomicBool, - /// Restart desired; when true, restart it desired after shutdown. pub restarting: AtomicBool, @@ -60,7 +56,6 @@ impl Server { config: config::Manager::new(config), started: SystemTime::now(), stopping: AtomicBool::new(false), - reloading: AtomicBool::new(false), restarting: AtomicBool::new(false), runtime, signal: broadcast::channel::<&'static str>(1).0, @@ -69,25 +64,6 @@ impl Server { } } - pub fn reload(&self) -> Result<()> { - if cfg!(any(not(conduwuit_mods), not(feature = "conduwuit_mods"))) { - return Err!("Reloading not enabled"); - } - - if self.reloading.swap(true, Ordering::AcqRel) { - return Err!("Reloading already in progress"); - } - - if self.stopping.swap(true, Ordering::AcqRel) { - return Err!("Shutdown already in progress"); - } - - self.signal("SIGINT").inspect_err(|_| { - self.stopping.store(false, Ordering::Release); - self.reloading.store(false, Ordering::Release); - }) - } - pub fn restart(&self) -> Result { if self.restarting.swap(true, Ordering::AcqRel) { return Err!("Restart already in progress"); @@ -146,9 +122,6 @@ impl Server { #[inline] pub fn is_stopping(&self) -> bool { self.stopping.load(Ordering::Relaxed) } - #[inline] - pub fn is_reloading(&self) -> bool { self.reloading.load(Ordering::Relaxed) } - #[inline] pub fn is_restarting(&self) -> bool { self.restarting.load(Ordering::Relaxed) } diff --git a/src/database/mod.rs b/src/database/mod.rs index fcc4f4df7..020530219 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -5,9 +5,6 @@ extern crate rust_rocksdb as rocksdb; conduwuit_macros::introspect_crate! {} -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - #[cfg(test)] mod benches; mod cork; diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index c4477721f..40162bd5c 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -175,9 +175,6 @@ zstd_compression = [ "conduwuit-router/zstd_compression", "conduwuit-service/zstd_compression", ] -conduwuit_mods = [ - "conduwuit-core/conduwuit_mods", -] bindgen-static = [ # "bindgen/static" # "clang-sys/static" diff --git a/src/main/mod.rs b/src/main/mod.rs index cdc8e27ce..7c5bbe200 100644 --- a/src/main/mod.rs +++ b/src/main/mod.rs @@ -10,7 +10,6 @@ mod clap; mod deadlock; mod logging; mod metrics; -mod mods; mod panic; mod restart; mod runtime; @@ -63,9 +62,8 @@ pub fn run_with_args(args: &Args) -> Result<()> { Ok(()) } -/// Operate the server normally in release-mode static builds. This will start, -/// run and stop the server within the asynchronous runtime. -#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))] +/// Operate the server. This will start, run and stop the server within the +/// asynchronous runtime. #[tracing::instrument( name = "main", parent = None, @@ -114,37 +112,3 @@ async fn async_main(server: &Arc) -> Result<(), Error> { debug_info!("Exit runtime"); Ok(()) } - -/// Operate the server in developer-mode dynamic builds. This will start, run, -/// and hot-reload portions of the server as-needed before returning for an -/// actual shutdown. This is not available in release-mode or static builds. -#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] -async fn async_main(server: &Arc) -> Result<(), Error> { - let mut starts = true; - let mut reloads = true; - while reloads { - if let Err(error) = mods::open(server).await { - error!("Loading router: {error}"); - return Err(error); - } - - let result = mods::run(server, starts).await; - if let Ok(result) = result { - (starts, reloads) = result; - } - - let force = !reloads || result.is_err(); - if let Err(error) = mods::close(server, force).await { - error!("Unloading router: {error}"); - return Err(error); - } - - if let Err(error) = result { - error!("{error}"); - return Err(error); - } - } - - debug_info!("Exit runtime"); - Ok(()) -} diff --git a/src/main/mods.rs b/src/main/mods.rs deleted file mode 100644 index c00c30f70..000000000 --- a/src/main/mods.rs +++ /dev/null @@ -1,174 +0,0 @@ -#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - -#[unsafe(no_link)] -extern crate conduwuit_service; - -use std::{ - future::Future, - pin::Pin, - sync::{Arc, atomic::Ordering}, -}; - -use conduwuit_core::{Error, Result, debug, error, mods}; -use conduwuit_service::Services; - -use crate::Server; - -type StartFuncResult = Pin>> + Send>>; -type StartFuncProto = fn(&Arc) -> StartFuncResult; - -type RunFuncResult = Pin> + Send>>; -type RunFuncProto = fn(&Arc) -> RunFuncResult; - -type StopFuncResult = Pin> + Send>>; -type StopFuncProto = fn(Arc) -> StopFuncResult; - -const RESTART_THRESH: &str = "conduwuit_service"; -const MODULE_NAMES: &[&str] = &[ - //"conduwuit_core", - "conduwuit_database", - "conduwuit_service", - "conduwuit_api", - "conduwuit_admin", - "conduwuit_router", -]; - -#[cfg(panic_trap)] -conduwuit_core::mod_init! {{ - conduwuit_core::debug::set_panic_trap(); -}} - -pub(crate) async fn run(server: &Arc, starts: bool) -> Result<(bool, bool), Error> { - let main_lock = server.mods.read().await; - let main_mod = (*main_lock).last().expect("main module loaded"); - if starts { - // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern - // "Rust" fn start` with signature matching `StartFuncProto`, compiled - // with the same toolchain and flags. - let start = unsafe { main_mod.get::("start")? }; - match start(&server.server).await { - | Ok(services) => server.services.lock().await.insert(services), - | Err(error) => { - error!("Starting server: {error}"); - return Err(error); - }, - }; - } - - server.server.stopping.store(false, Ordering::Release); - - // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern - // "Rust" fn run` with signature matching `RunFuncProto`, compiled with the - // same toolchain and flags. - let run = unsafe { main_mod.get::("run")? }; - if let Err(error) = run(server - .services - .lock() - .await - .as_ref() - .expect("services initialized")) - .await - { - error!("Running server: {error}"); - return Err(error); - } - - let reloads = server.server.reloading.swap(false, Ordering::AcqRel); - - let stops = !reloads || stale_from_mods(&main_lock)? <= restart_thresh(); - let starts = reloads && stops; - if stops { - // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern - // "Rust" fn stop` with signature matching `StopFuncProto`, compiled - // with the same toolchain and flags. - let stop = unsafe { main_mod.get::("stop")? }; - if let Err(error) = stop( - server - .services - .lock() - .await - .take() - .expect("services initialized"), - ) - .await - { - error!("Stopping server: {error}"); - return Err(error); - } - } - - Ok((starts, reloads)) -} - -pub(crate) async fn open(server: &Arc) -> Result { - let mut mods_lock = server.mods.write().await; - let mods: &mut Vec = &mut mods_lock; - debug!( - available = %available(), - loaded = %mods.len(), - "Loading modules", - ); - - for (i, name) in MODULE_NAMES.iter().enumerate() { - if mods.get(i).is_none() { - // SAFETY: `MODULE_NAMES` are this workspace's own hot-reloadable - // shared libraries built with the same compiler/ABI. - mods.push(unsafe { mods::Module::from_name(name)? }); - } - } - - Ok(mods.len()) -} - -pub(crate) async fn close(server: &Arc, force: bool) -> Result { - let stale = stale_count(server).await; - let mut mods_lock = server.mods.write().await; - let mods: &mut Vec = &mut mods_lock; - debug!( - available = %available(), - loaded = %mods.len(), - stale = %stale, - force, - "Unloading modules", - ); - - while mods.last().is_some() { - let module = &mods.last().expect("module"); - if force || module.deleted()? { - mods.pop(); - } else { - break; - } - } - - Ok(mods.len()) -} - -async fn stale_count(server: &Arc) -> usize { - let watermark = stale(server).await.unwrap_or(available()); - available().saturating_sub(watermark) -} - -async fn stale(server: &Arc) -> Result { - let mods_lock = server.mods.read().await; - stale_from_mods(&mods_lock) -} - -fn stale_from_mods(mods: &[mods::Module]) -> Result { - for (i, module) in mods.iter().enumerate() { - if module.deleted()? { - return Ok(i); - } - } - - Ok(mods.len()) -} - -fn restart_thresh() -> usize { - MODULE_NAMES - .iter() - .position(|&name| name.ends_with(RESTART_THRESH)) - .unwrap_or(MODULE_NAMES.len()) -} - -const fn available() -> usize { MODULE_NAMES.len() } diff --git a/src/main/server.rs b/src/main/server.rs index 28b9039ef..e75c9777b 100644 --- a/src/main/server.rs +++ b/src/main/server.rs @@ -27,10 +27,6 @@ pub(crate) struct Server { #[cfg(feature = "sentry_telemetry")] _sentry_guard: Option<::sentry::ClientInitGuard>, - - #[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - // Module instances; TODO: move to mods::loaded mgmt vector - pub(crate) mods: tokio::sync::RwLock>, } impl Server { @@ -87,9 +83,6 @@ impl Server { #[cfg(feature = "sentry_telemetry")] _sentry_guard: sentry_guard, - - #[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - mods: tokio::sync::RwLock::new(Vec::new()), })) } diff --git a/src/main/signal.rs b/src/main/signal.rs index 42cade135..5cd9914fe 100644 --- a/src/main/signal.rs +++ b/src/main/signal.rs @@ -12,7 +12,6 @@ pub(super) async fn signal(server: Arc) { use unix::SignalKind; const CONSOLE: bool = cfg!(feature = "console"); - const RELOADING: bool = cfg!(all(conduwuit_mods, feature = "conduwuit_mods", not(CONSOLE))); let mut quit = unix::signal(SignalKind::quit()).expect("SIGQUIT handler"); let mut term = unix::signal(SignalKind::terminate()).expect("SIGTERM handler"); @@ -30,9 +29,7 @@ pub(super) async fn signal(server: Arc) { } warn!("Received {sig}"); - let result = if RELOADING && sig == "SIGINT" { - server.server.reload() - } else if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") { + let result = if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") { server.server.shutdown() } else { server.server.signal(sig) diff --git a/src/router/mod.rs b/src/router/mod.rs index c6f909d36..d907de7be 100644 --- a/src/router/mod.rs +++ b/src/router/mod.rs @@ -16,11 +16,7 @@ use conduwuit::{Error, Result, Server}; use conduwuit_service::Services; use futures::{Future, FutureExt, TryFutureExt}; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - -#[unsafe(no_mangle)] -pub extern "Rust" fn start( +pub fn start( server: &Arc, ) -> Pin>> + Send>> { AssertUnwindSafe(run::start(server.clone())) @@ -30,10 +26,7 @@ pub extern "Rust" fn start( .boxed() } -#[unsafe(no_mangle)] -pub extern "Rust" fn stop( - services: Arc, -) -> Pin> + Send>> { +pub fn stop(services: Arc) -> Pin> + Send>> { AssertUnwindSafe(run::stop(services)) .catch_unwind() .map_err(Error::from_panic) @@ -41,10 +34,7 @@ pub extern "Rust" fn stop( .boxed() } -#[unsafe(no_mangle)] -pub extern "Rust" fn run( - services: &Arc, -) -> Pin> + Send>> { +pub fn run(services: &Arc) -> Pin> + Send>> { AssertUnwindSafe(run::run(services.clone())) .catch_unwind() .map_err(Error::from_panic) diff --git a/src/service/mod.rs b/src/service/mod.rs index 0cb476cb0..93738ecad 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -44,19 +44,13 @@ pub mod transactions; pub mod uiaa; pub mod users; -use std::collections::BTreeMap; +use std::{collections::BTreeMap, sync::LazyLock}; +use conduwuit::matrix::versions::versions; +use ruma::api::SupportedVersions; pub(crate) use service::{Args, Dep, Service}; pub use crate::services::Services; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - -use std::sync::LazyLock; - -use conduwuit::matrix::versions::versions; -use ruma::api::SupportedVersions; - pub static SUPPORTED_VERSIONS: LazyLock = LazyLock::new(|| SupportedVersions::from_parts(&versions(), &BTreeMap::new())); From 0b738e835b58c84d841948baa08d9e1bd57d6790 Mon Sep 17 00:00:00 2001 From: Julian Anderson Date: Sun, 15 Nov 2026 16:54:41 -0500 Subject: [PATCH 309/342] ci(docs): Replace preview docs workflow with Grebedoc --- .forgejo/workflows/documentation.yml | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/.forgejo/workflows/documentation.yml b/.forgejo/workflows/documentation.yml index 141551007..029cf9f7a 100644 --- a/.forgejo/workflows/documentation.yml +++ b/.forgejo/workflows/documentation.yml @@ -62,10 +62,15 @@ jobs: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} command: pages deploy ./doc_build --branch="main" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}" - - name: Deploy to Cloudflare Pages (Preview) - if: github.ref != 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != '' - uses: https://github.com/cloudflare/wrangler-action@953926a2e2182532811c01a25e53647d93bf07c0 # v4 + - name: Deploy to Grebedoc (Preview) + if: github.ref != 'refs/heads/main' + uses: actions/git-pages@v2 with: - accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} - command: pages deploy ./doc_build --branch="${{ github.head_ref || github.ref_name }}" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}" + site: https://preview.continuwuity.org + path: "pr/${{ forgejo.event.number }}" + server: grebedoc.dev + token: ${{ forgejo.token }} + source: doc_build/ + strict: true + pretty-urls: true + comment: ${{ forgejo.sha }} From cbc089df1bcca7d0e9df8a9d9e56d30768580dc7 Mon Sep 17 00:00:00 2001 From: Julian Anderson Date: Sun, 15 Nov 2026 17:45:55 -0500 Subject: [PATCH 310/342] ci(docs): Expire preview doc deployments after 14 days --- .forgejo/workflows/documentation.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.forgejo/workflows/documentation.yml b/.forgejo/workflows/documentation.yml index 029cf9f7a..32827a412 100644 --- a/.forgejo/workflows/documentation.yml +++ b/.forgejo/workflows/documentation.yml @@ -73,4 +73,5 @@ jobs: source: doc_build/ strict: true pretty-urls: true + expires: 14 comment: ${{ forgejo.sha }} From f3289f150ce786bc29bc6311692eb8d9b8c98b5e Mon Sep 17 00:00:00 2001 From: Julian Anderson Date: Wed, 18 Nov 2026 21:43:52 -0500 Subject: [PATCH 311/342] ci(docs): Set Rspress config values based on prod/preview status --- .forgejo/workflows/documentation.yml | 2 + package-lock.json | 56 +++++++++------------------- package.json | 4 +- rspress.config.ts | 17 ++++----- 4 files changed, 30 insertions(+), 49 deletions(-) diff --git a/.forgejo/workflows/documentation.yml b/.forgejo/workflows/documentation.yml index 32827a412..57cfb3de7 100644 --- a/.forgejo/workflows/documentation.yml +++ b/.forgejo/workflows/documentation.yml @@ -49,6 +49,8 @@ jobs: run: npm ci - name: Build Rspress documentation + env: + SITE_PATH: ${{ github.ref != 'refs/heads/main' && format('/pr/{0}/', '${{ forgejo.event.number }}') || '/' }} run: npm run docs:build - name: Install Wrangler diff --git a/package-lock.json b/package-lock.json index 7802c4951..f8ff7b797 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "devDependencies": { "@rspress/core": "^2.0.0", "@rspress/plugin-client-redirects": "^2.0.0", - "@rspress/plugin-sitemap": "^2.0.0", + "@types/node": "^26.6.6", "typescript": "^7.0.0" } }, @@ -230,9 +230,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -247,9 +244,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -264,9 +258,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -281,9 +272,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -298,9 +286,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -315,9 +300,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -332,9 +314,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -349,9 +328,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -524,19 +500,6 @@ "@rspress/core": "^2.1.0-beta.2" } }, - "node_modules/@rspress/plugin-sitemap": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.4.tgz", - "integrity": "sha512-TObDTXgBKFAHEWEth47aehQSYtFfpIkqM4w14a0hUbPLkbu2AZ2cKnMzFTKK+W6I/3LN54scvfGYTL5CPQsDXw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "peerDependencies": { - "@rspress/core": "^2.1.0-beta.2" - } - }, "node_modules/@rspress/shared": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.4.tgz", @@ -770,6 +733,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, "node_modules/@types/react": { "version": "19.3.0", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", @@ -3842,6 +3815,13 @@ "@typescript/typescript-win32-x64": "7.0.2" } }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, "node_modules/unhead": { "version": "2.1.17", "resolved": "https://registry.npmjs.org/unhead/-/unhead-2.1.17.tgz", diff --git a/package.json b/package.json index 6ae3569a6..aa2e0db2c 100644 --- a/package.json +++ b/package.json @@ -20,11 +20,11 @@ "keywords": [], "author": "", "license": "ISC", - "type": "commonjs", + "type": "module", "devDependencies": { "@rspress/core": "^2.0.0", "@rspress/plugin-client-redirects": "^2.0.0", - "@rspress/plugin-sitemap": "^2.0.0", + "@types/node": "^26.6.6", "typescript": "^7.0.0" } } diff --git a/rspress.config.ts b/rspress.config.ts index de38b38eb..3739a13fe 100644 --- a/rspress.config.ts +++ b/rspress.config.ts @@ -1,10 +1,13 @@ import { defineConfig } from '@rspress/core'; -import { pluginSitemap } from '@rspress/plugin-sitemap'; import { pluginClientRedirects } from '@rspress/plugin-client-redirects'; +const sitePath: string = process.env.SITE_PATH ?? '/'; + export default defineConfig({ root: 'docs', title: 'Continuwuity', + siteOrigin: sitePath != "/" ? "https://preview.continuwuity.org" : "https://continuwuity.org", + base: sitePath, description: 'A community-driven Matrix homeserver', icon: '/assets/logo.svg', logo: { @@ -75,14 +78,10 @@ export default defineConfig({ lastUpdated: true, enableContentAnimation: true, enableAppearanceAnimation: false, - footer: { - }, + footer: {}, }, - plugins: [pluginSitemap({ - siteUrl: 'https://continuwuity.org', // TODO: Set automatically in build pipeline - }), - pluginClientRedirects({ + plugins: [pluginClientRedirects({ redirects: [{ from: '^/config_reference$', to: '/reference/config' @@ -105,8 +104,8 @@ export default defineConfig({ from: "^/source(|_code)$", to: "https://forgejo.ellis.link/continuwuation/continuwuity", }, { - from: "^/(CONTRIBUTING.md|contributing)$", - to: "/development/contributing" + from: "^/(CONTRIBUTING.md|contributing)$", + to: "/development/contributing" } ] })], From 95392ccc467808642ca59c507ba76e8a29064062 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sat, 21 Nov 2026 16:02:04 +0000 Subject: [PATCH 312/342] chore(deps): update rust-non-major --- Cargo.lock | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a40fe2fb..dc8e07eac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -497,7 +497,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 3.0.10", + "syn 2.0.119", ] [[package]] @@ -671,7 +671,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" dependencies = [ "semver", "serde", - "toml 1.2.1+spec-1.1.0", + "toml 1.2.2+spec-1.1.0", ] [[package]] @@ -764,9 +764,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" dependencies = [ "clap_builder", "clap_derive", @@ -784,9 +784,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" dependencies = [ "heck", "proc-macro2", @@ -1029,7 +1029,7 @@ dependencies = [ "tikv-jemallocator", "tokio", "tokio-metrics", - "toml 1.2.1+spec-1.1.0", + "toml 1.2.2+spec-1.1.0", "tracing", "tracing-core", "tracing-subscriber", @@ -2104,9 +2104,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -5135,7 +5135,7 @@ dependencies = [ "ruma-identifiers-validation", "serde", "syn 3.0.10", - "toml 1.2.1+spec-1.1.0", + "toml 1.2.2+spec-1.1.0", ] [[package]] @@ -6395,9 +6395,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.1+spec-1.1.0" +version = "1.2.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" dependencies = [ "indexmap 2.14.2", "serde_core", @@ -6454,9 +6454,9 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.5+spec-1.1.0" +version = "1.1.6+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" dependencies = [ "winnow 1.0.5", ] @@ -6853,9 +6853,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", From cc28a01e49df260da89683e8d720e9cb9766ae2e Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 21:38:55 +0000 Subject: [PATCH 313/342] fix(core): Fix BoolExt::or short-circuiting This would mean that or would return false when one of the inputs was true. Also fix double futures in type signatures --- src/core/utils/future/bool_ext.rs | 94 ++++++++++++++++++++++++++----- 1 file changed, 79 insertions(+), 15 deletions(-) diff --git a/src/core/utils/future/bool_ext.rs b/src/core/utils/future/bool_ext.rs index 24f239ff8..16b4b5678 100644 --- a/src/core/utils/future/bool_ext.rs +++ b/src/core/utils/future/bool_ext.rs @@ -1,10 +1,8 @@ //! Extended external extensions to futures::FutureExt -use std::marker::Unpin; - use futures::{ Future, FutureExt, - future::{select_ok, try_join, try_join_all, try_select}, + future::{try_join, try_join_all}, }; pub trait BoolExt @@ -18,8 +16,8 @@ where fn or(self, b: B) -> impl Future + Send where - B: Future + Send + Unpin, - Self: Sized + Unpin; + B: Future + Send, + Self: Sized; } impl BoolExt for Fut @@ -44,20 +42,20 @@ where #[inline] fn or(self, b: B) -> impl Future + Send where - B: Future + Send + Unpin, - Self: Sized + Unpin, + B: Future + Send, + Self: Sized, { type Result = crate::Result<(), ()>; - let a = self.map(|a| a.then_some(()).ok_or(Result::Err(()))); + let a = self.map(|a| (!a).then_some(()).ok_or(Result::Err(()))); - let b = b.map(|b| b.then_some(()).ok_or(Result::Err(()))); + let b = b.map(|b| (!b).then_some(()).ok_or(Result::Err(()))); - try_select(a, b).map(|result| result.is_ok()) + try_join(a, b).map(|result| result.is_err()) } } -pub async fn and(args: I) -> impl Future + Send +pub fn and(args: I) -> impl Future + Send where I: Iterator + Send, F: Future + Send, @@ -69,14 +67,80 @@ where try_join_all(args).map(|result| result.is_ok()) } -pub async fn or(args: I) -> impl Future + Send +pub fn or(args: I) -> impl Future + Send where I: Iterator + Send, - F: Future + Send + Unpin, + F: Future + Send, { type Result = crate::Result<(), ()>; - let args = args.map(|a| a.map(|a| a.then_some(()).ok_or(Result::Err(())))); + let args = args.map(|a| a.map(|a| (!a).then_some(()).ok_or(Result::Err(())))); - select_ok(args).map(|result| result.is_ok()) + try_join_all(args).map(|result| result.is_err()) +} + +#[cfg(test)] +mod tests { + use std::pin::pin; + + use futures::future; + + use super::{BoolExt, and, or}; + + #[tokio::test] + async fn bool_ext_truth_tables() { + for a in [false, true] { + for b in [false, true] { + assert_eq!(future::ready(a).and(future::ready(b)).await, a && b, "and({a}, {b})"); + assert_eq!(future::ready(a).or(future::ready(b)).await, a || b, "or({a}, {b})"); + } + } + + assert!( + future::ready(false) + .or(future::ready(false)) + .or(future::ready(true)) + .await, + "chained or with trailing true must return true" + ); + assert!( + !future::ready(false) + .or(future::ready(false)) + .or(future::ready(false)) + .await, + "chained or with all false must return false" + ); + } + + #[tokio::test] + async fn bool_ext_short_circuits() { + let pend = pin!(future::pending::()); + assert!( + future::ready(true).or(pend).await, + "or must short-circuit on true without polling pending" + ); + + let pend = pin!(future::pending::()); + assert!( + !future::ready(false).and(pend).await, + "and must short-circuit on false without polling pending" + ); + } + + #[tokio::test] + async fn free_and_or() { + assert!(and(std::iter::empty::>()).await, "empty and is true"); + assert!(!or(std::iter::empty::>()).await, "empty or is false"); + + assert!(and([future::ready(true), future::ready(true)].into_iter()).await, "all true"); + assert!( + !and([future::ready(true), future::ready(false)].into_iter()).await, + "and with false" + ); + assert!( + or([future::ready(false), future::ready(true)].into_iter()).await, + "or with true" + ); + assert!(!or([future::ready(false), future::ready(false)].into_iter()).await, "all false"); + } } From 3379badbd44eadd25bf5324873c0a047f0146d5e Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 23:22:39 +0000 Subject: [PATCH 314/342] fix(service): Prevent potential corruption in state diffs This fixes a non-atomicity issue. Also fixes incorrect calculation of a buffer size that would result in reallocation. --- src/service/rooms/short/mod.rs | 38 +++++------ src/service/rooms/state/mod.rs | 83 ++++++++++++----------- src/service/rooms/state_compressor/mod.rs | 46 +++++++++---- 3 files changed, 93 insertions(+), 74 deletions(-) diff --git a/src/service/rooms/short/mod.rs b/src/service/rooms/short/mod.rs index 2287eea2d..34953228c 100644 --- a/src/service/rooms/short/mod.rs +++ b/src/service/rooms/short/mod.rs @@ -1,4 +1,4 @@ -use std::{borrow::Borrow, fmt::Debug, mem::size_of_val, sync::Arc}; +use std::{borrow::Borrow, collections::HashMap, fmt::Debug, mem::size_of_val, sync::Arc}; pub use conduwuit::matrix::pdu::{ShortEventId, ShortId, ShortRoomId, ShortStateKey}; use conduwuit::{ @@ -72,14 +72,22 @@ impl Service { where I: Iterator + Clone + Debug + Send + 'a, { + let mut created: HashMap = HashMap::new(); event_ids .clone() .stream() .get(&self.db.eventid_shorteventid) .zip(event_ids.into_iter().stream()) - .map(|(result, event_id)| match result { + .map(move |(result, event_id)| match result { | Ok(ref short) => utils::u64_from_u8(short), - | Err(_) => self.create_shorteventid(event_id), + | Err(_) => + if let Some(&short) = created.get(event_id) { + short + } else { + let short = self.create_shorteventid(event_id); + created.insert(event_id.to_owned(), short); + short + }, }) } @@ -217,32 +225,24 @@ impl Service { .map(Deserialized::deserialized) } - /// Gets or creates a short state hash ID. The boolean indicates whether a - /// new short ID was created. - pub async fn get_or_create_shortstatehash( - &self, - state_hash: &[u8], - ) -> (ShortStateHash, bool) { - const BUFSIZE: usize = size_of::(); - - if let Ok(shortstatehash) = self - .db + /// Gets an existing short state hash ID without creating one. + pub async fn get_shortstatehash(&self, state_hash: &[u8]) -> Result { + self.db .statehash_shortstatehash .get(state_hash) .await .deserialized() - { - return (shortstatehash, true); - } + } - let shortstatehash = self.services.globals.next_count().unwrap(); + /// Publishes the mapping from state hash to short state hash after the + /// corresponding state diff has been written. + pub fn set_shortstatehash(&self, state_hash: &[u8], shortstatehash: ShortStateHash) { + const BUFSIZE: usize = size_of::(); debug_assert!(size_of_val(&shortstatehash) == BUFSIZE, "buffer requirement changed"); self.db .statehash_shortstatehash .raw_aput::(state_hash, shortstatehash); - - (shortstatehash, false) } /// Gets a short room ID. diff --git a/src/service/rooms/state/mod.rs b/src/service/rooms/state/mod.rs index c61d9349d..a7c3eacea 100644 --- a/src/service/rooms/state/mod.rs +++ b/src/service/rooms/state/mod.rs @@ -170,47 +170,50 @@ impl Service { let state_hash = calculate_hash(state_ids_compressed.iter().map(|s| &s[..])); - let (shortstatehash, already_existed) = self - .services - .short - .get_or_create_shortstatehash(&state_hash) - .await; - - if !already_existed { - let states_parents = match previous_shortstatehash { - | Ok(p) => - self.services - .state_compressor - .load_shortstatehash_info(p) - .await?, - | _ => Vec::new(), - }; - - let (statediffnew, statediffremoved) = - if let Some(parent_stateinfo) = states_parents.last() { - let statediffnew: CompressedState = state_ids_compressed - .difference(&parent_stateinfo.full_state) - .copied() - .collect(); - - let statediffremoved: CompressedState = parent_stateinfo - .full_state - .difference(&state_ids_compressed) - .copied() - .collect(); - - (Arc::new(statediffnew), Arc::new(statediffremoved)) - } else { - (state_ids_compressed, Arc::new(CompressedState::new())) + let shortstatehash = + if let Ok(existing) = self.services.short.get_shortstatehash(&state_hash).await { + existing + } else { + let states_parents = match previous_shortstatehash { + | Ok(p) => + self.services + .state_compressor + .load_shortstatehash_info(p) + .await?, + | _ => Vec::new(), }; - self.services.state_compressor.save_state_from_diff( - shortstatehash, - statediffnew, - statediffremoved, - 1_000_000, // high number because no state will be based on this one - states_parents, - )?; - } + + let (statediffnew, statediffremoved) = + if let Some(parent_stateinfo) = states_parents.last() { + let statediffnew: CompressedState = state_ids_compressed + .difference(&parent_stateinfo.full_state) + .copied() + .collect(); + + let statediffremoved: CompressedState = parent_stateinfo + .full_state + .difference(&state_ids_compressed) + .copied() + .collect(); + + (Arc::new(statediffnew), Arc::new(statediffremoved)) + } else { + (state_ids_compressed, Arc::new(CompressedState::new())) + }; + + let new_shortstatehash = self.services.globals.next_count()?; + self.services.state_compressor.save_state_from_diff( + new_shortstatehash, + statediffnew, + statediffremoved, + 1_000_000, // high number because no state will be based on this one + states_parents, + )?; + self.services + .short + .set_shortstatehash(&state_hash, new_shortstatehash); + new_shortstatehash + }; self.db .shorteventid_shortstatehash diff --git a/src/service/rooms/state_compressor/mod.rs b/src/service/rooms/state_compressor/mod.rs index ddd25eac1..a65057eea 100644 --- a/src/service/rooms/state_compressor/mod.rs +++ b/src/service/rooms/state_compressor/mod.rs @@ -18,7 +18,7 @@ use lru_cache::LruCache; use ruma::{EventId, RoomId}; use crate::{ - Dep, rooms, + Dep, globals, rooms, rooms::short::{ShortEventId, ShortId, ShortStateHash, ShortStateKey}, }; @@ -29,6 +29,7 @@ pub struct Service { } struct Services { + globals: Dep, short: Dep, state: Dep, } @@ -78,6 +79,7 @@ impl crate::Service for Service { shortstatehash_statediff: args.db["shortstatehash_statediff"].clone(), }, services: Services { + globals: args.depend::("globals"), short: args.depend::("rooms::short"), state: args.depend::("rooms::state"), }, @@ -368,17 +370,17 @@ impl Service { let state_hash = utils::calculate_hash(new_state_ids_compressed.iter().map(|bytes| &bytes[..])); - let (new_shortstatehash, already_existed) = self + let existing = self .services .short - .get_or_create_shortstatehash(&state_hash) - .await; + .get_shortstatehash(&state_hash) + .await + .ok(); - if Some(new_shortstatehash) == previous_shortstatehash { - return Ok(HashSetCompressStateEvent { - shortstatehash: new_shortstatehash, - ..Default::default() - }); + if let Some(shortstatehash) = existing + && Some(shortstatehash) == previous_shortstatehash + { + return Ok(HashSetCompressStateEvent { shortstatehash, ..Default::default() }); } let states_parents = if let Some(p) = previous_shortstatehash { @@ -405,7 +407,10 @@ impl Service { (new_state_ids_compressed, Arc::new(CompressedState::new())) }; - if !already_existed { + let new_shortstatehash = if let Some(existing) = existing { + existing + } else { + let new_shortstatehash = self.services.globals.next_count()?; self.save_state_from_diff( new_shortstatehash, statediffnew.clone(), @@ -413,7 +418,11 @@ impl Service { 2, // every state change is 2 event changes on average states_parents, )?; - } + self.services + .short + .set_shortstatehash(&state_hash, new_shortstatehash); + new_shortstatehash + }; Ok(HashSetCompressStateEvent { shortstatehash: new_shortstatehash, @@ -437,7 +446,10 @@ impl Service { err!(Database("Failed to find StateDiff from short {shortstatehash:?}: {e}")) })?; - let parent = utils::u64_from_bytes(&value[0..size_of::()]) + let parent_bytes = value + .get(0..size_of::()) + .ok_or_else(|| err!(Database("Truncated StateDiff for short {shortstatehash:?}")))?; + let parent = utils::u64_from_bytes(parent_bytes) .ok() .take_if(|parent| *parent != 0); @@ -472,10 +484,14 @@ impl Service { /// Stores a new state diff with a shortstatehash. fn save_statediff(&self, shortstatehash: ShortStateHash, diff: &StateDiff) { + const STRIDE: usize = size_of::(); + let mut value = Vec::::with_capacity( - 2_usize - .saturating_add(diff.added.len()) - .saturating_add(diff.removed.len()), + 1_usize + .saturating_add(usize::from(!diff.removed.is_empty())) + .saturating_add(diff.added.len().saturating_mul(2)) + .saturating_add(diff.removed.len().saturating_mul(2)) + .saturating_mul(STRIDE), ); let parent = diff.parent.unwrap_or(0_u64); From 251086670f4c9cdc4ac82a9f4688d0ba41c9932e Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 6 Oct 2026 20:14:59 +0200 Subject: [PATCH 315/342] feat: Add timestamp to event endpoint backed by a timestamp index --- changelog.d/+timestamp-to-event.feature.md | 1 + src/api/client/room/mod.rs | 4 +- src/api/client/room/timestamp_to_event.rs | 61 ++++++++++++++ src/api/router.rs | 1 + src/database/maps.rs | 4 + src/service/migrations.rs | 71 +++++++++++++++- src/service/rooms/timeline/append.rs | 14 +++- src/service/rooms/timeline/backfill.rs | 3 +- src/service/rooms/timeline/data.rs | 95 +++++++++++++++++++++- src/service/rooms/timeline/mod.rs | 20 ++++- 10 files changed, 262 insertions(+), 12 deletions(-) create mode 100644 changelog.d/+timestamp-to-event.feature.md create mode 100644 src/api/client/room/timestamp_to_event.rs diff --git a/changelog.d/+timestamp-to-event.feature.md b/changelog.d/+timestamp-to-event.feature.md new file mode 100644 index 000000000..c1f903968 --- /dev/null +++ b/changelog.d/+timestamp-to-event.feature.md @@ -0,0 +1 @@ +Added the `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event` endpoint as per MSC3030, letting clients find the event closest to a given timestamp. Contributed by @eleboucher. diff --git a/src/api/client/room/mod.rs b/src/api/client/room/mod.rs index 1d3125d3e..78487f8da 100644 --- a/src/api/client/room/mod.rs +++ b/src/api/client/room/mod.rs @@ -4,10 +4,12 @@ mod event; mod initial_sync; mod stripped_state; mod summary; +mod timestamp_to_event; mod upgrade; pub(crate) use self::{ aliases::get_room_aliases_route, create::create_room_route, event::get_room_event_route, initial_sync::room_initial_sync_route, stripped_state::get_stripped_state_route, - summary::get_room_summary, upgrade::upgrade_room_route, + summary::get_room_summary, timestamp_to_event::get_event_by_timestamp_route, + upgrade::upgrade_room_route, }; diff --git a/src/api/client/room/timestamp_to_event.rs b/src/api/client/room/timestamp_to_event.rs new file mode 100644 index 000000000..0ce077a9b --- /dev/null +++ b/src/api/client/room/timestamp_to_event.rs @@ -0,0 +1,61 @@ +use axum::extract::State; +use conduwuit::{Err, Event, Result, utils::stream::TryIgnore}; +use futures::{StreamExt, pin_mut}; +use ruma::api::client::room::get_event_by_timestamp; + +use crate::Ruma; + +const MAX_CANDIDATES: usize = 20; + +/// # `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event` +/// +/// Gets the ID of the event closest to the given timestamp, in the direction +/// specified by `dir`. +pub(crate) async fn get_event_by_timestamp_route( + State(ref services): State, + body: Ruma, +) -> Result { + let sender_user = body.identity.expect_sender_user()?; + let room_id = &body.room_id; + + if !services + .rooms + .state_accessor + .user_can_see_state_events(sender_user, room_id) + .await + { + return Err!(Request(Forbidden("You don't have permission to view this room."))); + } + + if !services.rooms.timeline.timestamp_index_ready().await { + return Err!(FeatureDisabled("timestamp_to_event")); + } + + let candidates = services + .rooms + .timeline + .pdus_by_timestamp(room_id, body.ts, body.dir) + .ignore_err() + .take(MAX_CANDIDATES); + + pin_mut!(candidates); + while let Some((_, pdu)) = candidates.next().await { + if services + .rooms + .state_accessor + .user_can_see_event(sender_user, room_id, pdu.event_id()) + .await + { + return Ok(get_event_by_timestamp::v1::Response::new( + pdu.event_id().to_owned(), + pdu.origin_server_ts(), + )); + } + } + + Err!(Request(NotFound( + "Unable to find event from {} in direction {:?}", + body.ts.get(), + body.dir + ))) +} diff --git a/src/api/router.rs b/src/api/router.rs index 0e8481d35..511e1e32f 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -52,6 +52,7 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&client::set_pushrule_actions_route) .ruma_route(&client::delete_pushrule_route) .ruma_route(&client::get_room_event_route) + .ruma_route(&client::get_event_by_timestamp_route) .ruma_route(&client::get_room_aliases_route) .ruma_route(&client::get_filter_route) .ruma_route(&client::create_filter_route) diff --git a/src/database/maps.rs b/src/database/maps.rs index 183355d06..35bc75f5e 100644 --- a/src/database/maps.rs +++ b/src/database/maps.rs @@ -232,6 +232,10 @@ pub(super) static MAPS: &[Descriptor] = &[ name: "roomsynctoken_shortstatehash", ..descriptor::DROPPED }, + Descriptor { + name: "roomts_pduid", + ..descriptor::SEQUENTIAL_SMALL + }, Descriptor { name: "roomuserdataid_accountdata", ..descriptor::RANDOM_SMALL diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 666994d9e..b14a74422 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -18,11 +18,11 @@ use conduwuit::{ }, warn, }; -use database::{Deserialized, Ignore, Json}; +use database::{Database, Deserialized, Ignore, Json}; use futures::{FutureExt, StreamExt, TryStreamExt}; use itertools::Itertools; use ruma::{ - OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, UserId, + MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, UserId, api::OAuthClientScope, events::{ AnyStrippedStateEvent, GlobalAccountDataEventType, StateEventType, @@ -32,9 +32,13 @@ use ruma::{ push::Ruleset, serde::{Raw, from_raw_json_value}, }; +use serde::Deserialize; use serde_json::{Value, value::to_raw_value}; -use crate::{Services, media, rooms, rooms::short::ShortStateHash}; +use crate::{ + Services, media, rooms, + rooms::{short::ShortStateHash, timeline::RawPduId}, +}; type MigrationFn = for<'a> fn(&'a Services) -> Pin> + Send + 'a>>; @@ -176,6 +180,35 @@ migration!(stringify!($name) => $name) // This is backwards compatible because old versions never read the // account data entries it removes. migration!(remove_replaced_account_data), + // This is backwards compatible because old versions ignore the `roomts_pduid` keyspace. + Migration(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, |services| { + Box::pin(async { + let global = &services.db["global"]; + if global + .exists(rooms::timeline::TIMESTAMP_INDEX_MIGRATION) + .await + .is_ok() + { + return Ok(()); + } + + let until = match global.get(ROOMTS_UNTIL).await.deserialized::() { + | Ok(until) => until, + | Err(_) => { + let until = services.globals.current_count()?; + global.insert(ROOMTS_UNTIL, until.to_be_bytes()); + until + }, + }; + + services + .server + .runtime() + .spawn(populate_roomts_pduid(services.db.clone(), until)); + + Ok(()) + }) + }), ] }; @@ -953,6 +986,38 @@ async fn unembed_unsigned_info( info!(elapsed=?start.elapsed(), total_migrated_pdus=total_migrated, "Finished migration."); } +const ROOMTS_UNTIL: &str = "populate_roomts_pduid_until"; + +async fn populate_roomts_pduid(db: Arc, until: u64) { + #[derive(Deserialize)] + struct ExtractTs { + origin_server_ts: MilliSecondsSinceUnixEpoch, + } + + info!("Starting background migration to index PDUs by timestamp."); + let start = Instant::now(); + let roomts_pduid = db["roomts_pduid"].clone(); + + db["pduid_pdu"] + .raw_stream() + .ignore_err() + .ready_for_each(|(key, val)| { + let pdu_id = RawPduId::from(key); + if matches!(pdu_id.pdu_count(), PduCount::Normal(count) if count > until) { + return; + } + if let Ok(pdu) = serde_json::from_slice::(val) { + roomts_pduid + .insert(&rooms::timeline::roomts_key(&pdu_id, pdu.origin_server_ts), []); + } + }) + .await; + + db["global"].insert(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, []); + db["global"].remove(ROOMTS_UNTIL); + info!(elapsed = ?start.elapsed(), "Finished indexing PDUs by timestamp."); +} + async fn drop_server_signingkeys(services: &Services) -> Result<()> { services.db.db.drop_column("server_signingkeys")?; diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index c4b66e866..8304ad055 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -23,8 +23,8 @@ use conduwuit_core::{ }; use futures::{FutureExt, StreamExt, TryFutureExt, pin_mut}; use ruma::{ - CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, - RoomVersionId, ServerName, UserId, + CanonicalJsonObject, CanonicalJsonValue, MilliSecondsSinceUnixEpoch, OwnedEventId, + OwnedRoomId, OwnedServerName, RoomId, RoomVersionId, ServerName, UserId, events::{ AnySyncTimelineEvent, GlobalAccountDataEventType, TimelineEventType, push_rules::PushRulesEvent, @@ -347,9 +347,17 @@ impl super::Service { let count2 = PduCount::Normal(self.services.globals.next_count().unwrap()); let pdu_id: RawPduId = PduId { shortroomid, shorteventid: count2 }.into(); + // Remote timestamps are untrusted, so index remote events by when we + // received them + let index_ts = if self.services.globals.user_is_local(pdu.sender()) { + pdu.origin_server_ts() + } else { + MilliSecondsSinceUnixEpoch::now() + }; + // Insert pdu self.db - .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2) + .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2, index_ts) .await; self.progress_extremities(pdu) .await diff --git a/src/service/rooms/timeline/backfill.rs b/src/service/rooms/timeline/backfill.rs index 85efcd5a1..ff78e9ff9 100644 --- a/src/service/rooms/timeline/backfill.rs +++ b/src/service/rooms/timeline/backfill.rs @@ -225,7 +225,8 @@ impl super::Service { .into(); // Insert pdu - self.db.prepend_backfill_pdu(&pdu_id, &event_id, &value); + self.db + .prepend_backfill_pdu(&pdu_id, &event_id, &value, pdu.origin_server_ts()); drop(insert_lock); if pdu.kind == TimelineEventType::RoomMessage { diff --git a/src/service/rooms/timeline/data.rs b/src/service/rooms/timeline/data.rs index f416582fc..a6c68198a 100644 --- a/src/service/rooms/timeline/data.rs +++ b/src/service/rooms/timeline/data.rs @@ -12,7 +12,9 @@ use database::{Database, Deserialized, Json, KeyVal, Map}; use futures::{ FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::select_ok, pin_mut, }; -use ruma::{CanonicalJsonObject, EventId, OwnedUserId, RoomId, api::Direction}; +use ruma::{ + CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedUserId, RoomId, api::Direction, +}; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue as RawJsonValue; @@ -25,6 +27,7 @@ pub(super) struct Data { pduid_pdu: Arc, pduid_unredactedcontent: Arc, roomid_lasttimelinecount: Arc, + roomts_pduid: Arc, userroomid_highlightcount: Arc, userroomid_notificationcount: Arc, pub(super) db: Arc, @@ -52,6 +55,7 @@ impl Data { pduid_pdu: db["pduid_pdu"].clone(), pduid_unredactedcontent: db["pduid_unredactedcontent"].clone(), roomid_lasttimelinecount: db["roomid_lasttimelinecount"].clone(), + roomts_pduid: db["roomts_pduid"].clone(), userroomid_highlightcount: db["userroomid_highlightcount"].clone(), userroomid_notificationcount: db["userroomid_notificationcount"].clone(), db: args.db.clone(), @@ -213,10 +217,12 @@ impl Data { room_id: &RoomId, json: &CanonicalJsonObject, count: PduCount, + index_ts: MilliSecondsSinceUnixEpoch, ) { debug_assert!(matches!(count, PduCount::Normal(_)), "PduCount not Normal"); self.pduid_pdu.raw_put(pdu_id, Json(json)); + self.roomts_pduid.insert(&roomts_key(pdu_id, index_ts), []); self.eventid_pduid.insert(pdu.event_id.as_bytes(), pdu_id); self.eventid_outlierpdu.remove(pdu.event_id.as_bytes()); self.roomid_lasttimelinecount @@ -228,8 +234,10 @@ impl Data { pdu_id: &RawPduId, event_id: &EventId, json: &CanonicalJsonObject, + index_ts: MilliSecondsSinceUnixEpoch, ) { self.pduid_pdu.raw_put(pdu_id, Json(json)); + self.roomts_pduid.insert(&roomts_key(pdu_id, index_ts), []); self.eventid_pduid.insert(event_id, pdu_id); self.eventid_outlierpdu.remove(event_id); } @@ -322,6 +330,48 @@ impl Data { .try_flatten_stream() } + pub(super) fn pdus_by_ts<'a>( + &'a self, + room_id: &'a RoomId, + ts: MilliSecondsSinceUnixEpoch, + dir: Direction, + ) -> impl Stream> + Send + 'a { + self.services + .short + .get_shortroomid(room_id) + .map_err(move |e| err!(Request(NotFound("Room {room_id:?} not found: {e:?}")))) + .map_ok(move |shortroomid| { + let seek = + |shorteventid| roomts_key(&PduId { shortroomid, shorteventid }.into(), ts); + let keys = match dir { + | Direction::Forward => self + .roomts_pduid + .raw_keys_from(&seek(PduCount::min())) + .left_stream(), + | Direction::Backward => self + .roomts_pduid + .rev_raw_keys_from(&seek(PduCount::max())) + .right_stream(), + }; + + keys.ready_try_take_while(move |key| { + Ok(key.starts_with(&shortroomid.to_be_bytes())) + }) + .map_ok(roomts_key_to_pdu_id) + .and_then(async move |pdu_id| { + Ok((pdu_id.pdu_count(), self.get_pdu_from_id(&pdu_id).await?)) + }) + }) + .try_flatten_stream() + } + + pub(super) async fn timestamp_index_ready(&self) -> bool { + self.db["global"] + .exists(TIMESTAMP_INDEX_MIGRATION) + .await + .is_ok() + } + fn from_json_slice((pdu_id, pdu): KeyVal<'_>) -> Result { let pdu_id: RawPduId = pdu_id.into(); @@ -376,9 +426,52 @@ impl Data { } } +pub const TIMESTAMP_INDEX_MIGRATION: &str = "populate_roomts_pduid"; + +#[must_use] +pub fn roomts_key(pdu_id: &RawPduId, ts: MilliSecondsSinceUnixEpoch) -> Vec { + let count = pdu_id.pdu_count().into_signed().cast_unsigned() ^ (1 << 63); + [pdu_id.shortroomid(), u64::from(ts.get()).to_be_bytes(), count.to_be_bytes()].concat() +} + +fn roomts_key_to_pdu_id(key: &[u8]) -> RawPduId { + let shortroomid = u64::from_be_bytes(key[0..8].try_into().expect("roomts key shortroomid")); + let count = u64::from_be_bytes(key[16..24].try_into().expect("roomts key count")) ^ (1 << 63); + + PduId { + shortroomid, + shorteventid: PduCount::from_signed(count.cast_signed()), + } + .into() +} + //TODO: this is an ABA fn increment(db: &Arc, key: &[u8]) { let old = db.get_blocking(key); let new = utils::increment(old.ok().as_deref()); db.insert(key, new); } + +#[cfg(test)] +mod tests { + use ruma::uint; + + use super::*; + + #[test] + fn roomts_key_orders_by_ts_then_count() { + let ids = [ + (PduCount::Normal(9), uint!(1)), + (PduCount::Backfilled(-5), uint!(2)), + (PduCount::Normal(3), uint!(2)), + (PduCount::Normal(1), uint!(3)), + ] + .map(|(count, ts)| (RawPduId::from(PduId { shortroomid: 7, shorteventid: count }), ts)); + let keys = ids.map(|(id, ts)| roomts_key(&id, MilliSecondsSinceUnixEpoch(ts))); + + assert!(keys.is_sorted()); + for ((id, _), key) in ids.iter().zip(&keys) { + assert_eq!(roomts_key_to_pdu_id(key), *id); + } + } +} diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 6c206d9bf..1087dd8c1 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -21,8 +21,8 @@ use conduwuit_core::{ }; use futures::{Future, Stream, TryStreamExt, pin_mut}; use ruma::{ - CanonicalJsonObject, EventId, OwnedEventId, OwnedRoomId, RoomId, - events::room::encrypted::Relation, + CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, + api::Direction, events::room::encrypted::Relation, }; use serde::Deserialize; use serde_json::value::RawValue as RawJsonValue; @@ -32,7 +32,10 @@ use tokio::{ }; use self::data::Data; -pub use self::{create::pdu_fits, data::PdusIterItem}; +pub use self::{ + create::pdu_fits, + data::{PdusIterItem, TIMESTAMP_INDEX_MIGRATION, roomts_key}, +}; use crate::{ Dep, account_data, admin, appservice, config, globals, pusher, rooms, sending, server_keys, sync, users, @@ -307,6 +310,17 @@ impl Service { self.pdus(room_id, None).ignore_err() } + pub fn pdus_by_timestamp<'a>( + &'a self, + room_id: &'a RoomId, + ts: MilliSecondsSinceUnixEpoch, + dir: Direction, + ) -> impl Stream> + Send + 'a { + self.db.pdus_by_ts(room_id, ts, dir) + } + + pub async fn timestamp_index_ready(&self) -> bool { self.db.timestamp_index_ready().await } + /// Reverse iteration starting after `until`. #[tracing::instrument(skip(self), level = "debug")] pub fn pdus_rev<'a>( From 5687847fe315830705efa3f3d75fbc48ab31abbf Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 13 Oct 2026 13:47:53 +0200 Subject: [PATCH 316/342] style: Address review nits on timestamp index --- src/service/migrations.rs | 16 ++++++++-------- src/service/rooms/timeline/data.rs | 9 +++++---- src/service/rooms/timeline/mod.rs | 4 ++-- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/service/migrations.rs b/src/service/migrations.rs index b14a74422..53dc5567e 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -986,6 +986,14 @@ async fn unembed_unsigned_info( info!(elapsed=?start.elapsed(), total_migrated_pdus=total_migrated, "Finished migration."); } +async fn drop_server_signingkeys(services: &Services) -> Result<()> { + services.db.db.drop_column("server_signingkeys")?; + + info!("Cleared server_signingkeys."); + + Ok(()) +} + const ROOMTS_UNTIL: &str = "populate_roomts_pduid_until"; async fn populate_roomts_pduid(db: Arc, until: u64) { @@ -1018,14 +1026,6 @@ async fn populate_roomts_pduid(db: Arc, until: u64) { info!(elapsed = ?start.elapsed(), "Finished indexing PDUs by timestamp."); } -async fn drop_server_signingkeys(services: &Services) -> Result<()> { - services.db.db.drop_column("server_signingkeys")?; - - info!("Cleared server_signingkeys."); - - Ok(()) -} - async fn fix_oauth_scope_names(services: &Services) -> Result { let db = &services.db; let userdeviceid_oauthsessioninfo = db["userdeviceid_oauthsessioninfo"].clone(); diff --git a/src/service/rooms/timeline/data.rs b/src/service/rooms/timeline/data.rs index a6c68198a..f0184533b 100644 --- a/src/service/rooms/timeline/data.rs +++ b/src/service/rooms/timeline/data.rs @@ -330,10 +330,10 @@ impl Data { .try_flatten_stream() } - pub(super) fn pdus_by_ts<'a>( + pub(super) fn pdus_by_timestamp<'a>( &'a self, room_id: &'a RoomId, - ts: MilliSecondsSinceUnixEpoch, + timestamp: MilliSecondsSinceUnixEpoch, dir: Direction, ) -> impl Stream> + Send + 'a { self.services @@ -341,8 +341,9 @@ impl Data { .get_shortroomid(room_id) .map_err(move |e| err!(Request(NotFound("Room {room_id:?} not found: {e:?}")))) .map_ok(move |shortroomid| { - let seek = - |shorteventid| roomts_key(&PduId { shortroomid, shorteventid }.into(), ts); + let seek = |shorteventid| { + roomts_key(&PduId { shortroomid, shorteventid }.into(), timestamp) + }; let keys = match dir { | Direction::Forward => self .roomts_pduid diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 1087dd8c1..15774c2e5 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -313,10 +313,10 @@ impl Service { pub fn pdus_by_timestamp<'a>( &'a self, room_id: &'a RoomId, - ts: MilliSecondsSinceUnixEpoch, + timestamp: MilliSecondsSinceUnixEpoch, dir: Direction, ) -> impl Stream> + Send + 'a { - self.db.pdus_by_ts(room_id, ts, dir) + self.db.pdus_by_timestamp(room_id, timestamp, dir) } pub async fn timestamp_index_ready(&self) -> bool { self.db.timestamp_index_ready().await } From 919fea9b97532e16e416a9e938fdb48c55c2c02e Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 13 Oct 2026 13:48:54 +0200 Subject: [PATCH 317/342] fix: Index remote events by origin_server_ts --- src/service/migrations.rs | 3 ++- src/service/rooms/timeline/append.rs | 14 +++----------- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 53dc5567e..ac4825d8d 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -180,7 +180,8 @@ migration!(stringify!($name) => $name) // This is backwards compatible because old versions never read the // account data entries it removes. migration!(remove_replaced_account_data), - // This is backwards compatible because old versions ignore the `roomts_pduid` keyspace. + // This is backwards compatible because old versions ignore the + // `roomts_pduid` keyspace. Migration(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, |services| { Box::pin(async { let global = &services.db["global"]; diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index 8304ad055..887dca516 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -23,8 +23,8 @@ use conduwuit_core::{ }; use futures::{FutureExt, StreamExt, TryFutureExt, pin_mut}; use ruma::{ - CanonicalJsonObject, CanonicalJsonValue, MilliSecondsSinceUnixEpoch, OwnedEventId, - OwnedRoomId, OwnedServerName, RoomId, RoomVersionId, ServerName, UserId, + CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, + RoomVersionId, ServerName, UserId, events::{ AnySyncTimelineEvent, GlobalAccountDataEventType, TimelineEventType, push_rules::PushRulesEvent, @@ -347,17 +347,9 @@ impl super::Service { let count2 = PduCount::Normal(self.services.globals.next_count().unwrap()); let pdu_id: RawPduId = PduId { shortroomid, shorteventid: count2 }.into(); - // Remote timestamps are untrusted, so index remote events by when we - // received them - let index_ts = if self.services.globals.user_is_local(pdu.sender()) { - pdu.origin_server_ts() - } else { - MilliSecondsSinceUnixEpoch::now() - }; - // Insert pdu self.db - .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2, index_ts) + .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2, pdu.origin_server_ts()) .await; self.progress_extremities(pdu) .await From cf45dcffbb4d0bbf79efec8f0e7f202aaf357b5e Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Mon, 16 Nov 2026 15:44:35 +0100 Subject: [PATCH 318/342] fix(service/sending): Restart crashed sender workers and resend queued backlogs Signed-off-by: Erwan Leboucher --- changelog.d/sender-supervision.bugfix.md | 1 + docs/guides/metrics.mdx | 3 + src/core/metrics/instruments.rs | 6 + src/service/metrics.rs | 22 +++ src/service/mod.rs | 2 + .../event_handler/state_at_incoming/tests.rs | 41 +----- src/service/sending/data.rs | 28 ++++ src/service/sending/mod.rs | 130 ++++++++++++++---- src/service/sending/sender.rs | 91 ++++++++---- src/service/sending/sender/tests.rs | 82 +++++++++++ src/service/sending/tests.rs | 42 ++++++ src/service/test_utils.rs | 52 +++++++ 12 files changed, 415 insertions(+), 85 deletions(-) create mode 100644 changelog.d/sender-supervision.bugfix.md create mode 100644 src/service/sending/sender/tests.rs create mode 100644 src/service/sending/tests.rs create mode 100644 src/service/test_utils.rs diff --git a/changelog.d/sender-supervision.bugfix.md b/changelog.d/sender-supervision.bugfix.md new file mode 100644 index 000000000..bbd9bce83 --- /dev/null +++ b/changelog.d/sender-supervision.bugfix.md @@ -0,0 +1 @@ +Fix outgoing federation stalling after a sender worker panics. Contributed by @eleboucher. diff --git a/docs/guides/metrics.mdx b/docs/guides/metrics.mdx index de01db04a..83ea51bc7 100644 --- a/docs/guides/metrics.mdx +++ b/docs/guides/metrics.mdx @@ -71,6 +71,9 @@ Names below are as they appear in Prometheus. OTLP uses the dotted OpenTelemetry | `continuwuity_sender_events_total` | counter | `destination`, `kind`, `outcome` | PDUs and EDUs sent in outgoing transactions | | `continuwuity_sender_events_queued_total` | counter | `destination`, `kind` | PDUs and EDUs queued for sending | | `continuwuity_sender_queue_depth` | gauge | | Messages waiting for the sender workers | +| `continuwuity_sender_requests` | gauge | `state` | Estimated outgoing requests stored as `queued` or `active` (in flight) | +| `continuwuity_sender_workers` | gauge | | Running sender workers; below the configured count means a worker is restarting | +| `continuwuity_sender_panics_total` | counter | `scope` | Panics caught in a single outgoing `transaction` or a whole sender `worker` | | `continuwuity_users` | gauge | `origin` | Known `local` users, including deactivated, and `remote` users | | `continuwuity_invites_total` | counter | `direction`, `destination`, `outcome` | Invites sent by local users or received over federation | | `continuwuity_media_write_size_bytes` | histogram | `origin` | Media files written, from local uploads or cached remote media | diff --git a/src/core/metrics/instruments.rs b/src/core/metrics/instruments.rs index 7c922188d..e1583d056 100644 --- a/src/core/metrics/instruments.rs +++ b/src/core/metrics/instruments.rs @@ -21,6 +21,7 @@ pub struct Instruments { pub sender_transaction_duration: Histogram, pub sender_events: Counter, pub sender_events_queued: Counter, + pub sender_panics: Counter, pub media_write_size: Histogram, pub media_read_size: Histogram, @@ -116,6 +117,11 @@ impl Instruments { .with_description("PDUs and EDUs queued for sending") .with_unit("{event}") .build(), + sender_panics: meter + .u64_counter("continuwuity.sender.panics") + .with_description("Panics caught in outgoing transactions and sender workers") + .with_unit("{panic}") + .build(), media_write_size: size( "continuwuity.media.write.size", diff --git a/src/service/metrics.rs b/src/service/metrics.rs index a1291de06..80a985f4e 100644 --- a/src/service/metrics.rs +++ b/src/service/metrics.rs @@ -18,6 +18,28 @@ impl Services { }, ); + self.gauge( + "continuwuity.sender.requests", + "Estimated outgoing requests stored as queued or in flight", + "{request}", + |services, observer| { + for (state, count) in services.sending.db.request_counts() { + if let Some(count) = count { + observer.observe(count, &[KeyValue::new("state", state)]); + } + } + }, + ); + + self.gauge( + "continuwuity.sender.workers", + "Running sender workers", + "{worker}", + |services, observer| { + observe(observer, services.sending.workers_alive(), &[]); + }, + ); + self.gauge( "continuwuity.federation.incoming.transactions.active", "Incoming federation transactions currently being processed", diff --git a/src/service/mod.rs b/src/service/mod.rs index 93738ecad..5d7de067f 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -13,6 +13,8 @@ mod migrations; mod service; pub mod services; pub mod state; +#[cfg(test)] +mod test_utils; pub mod account_data; pub mod admin; diff --git a/src/service/rooms/event_handler/state_at_incoming/tests.rs b/src/service/rooms/event_handler/state_at_incoming/tests.rs index d46395cee..fc90905e3 100644 --- a/src/service/rooms/event_handler/state_at_incoming/tests.rs +++ b/src/service/rooms/event_handler/state_at_incoming/tests.rs @@ -1,14 +1,10 @@ -use std::sync::Arc; - -use conduwuit::{ - Config, PduEvent, Server, - log::{Log, LogLevelReloadHandles}, - metrics::Metrics, -}; +use conduwuit::PduEvent; use futures::StreamExt; use ruma::{RoomId, RoomVersionId, events::StateEventType}; use serde_json::json; +use crate::test_utils::test_services; + #[tokio::test] async fn admitted_joins_do_not_disappear_after_a_merge() { use conduwuit::matrix::PartialPdu; @@ -20,7 +16,7 @@ async fn admitted_joins_do_not_disappear_after_a_merge() { }, }; - let (services, path) = test_services().await; + let (services, path, _database) = test_services().await; let alice = UserId::parse("@alice:test.example").unwrap(); let bob = UserId::parse("@bob:bob.example").unwrap(); let charlie = UserId::parse("@charlie:charlie.example").unwrap(); @@ -212,35 +208,6 @@ async fn admitted_joins_do_not_disappear_after_a_merge() { assert_eq!(results, [true, true], "both joined users must be able to send messages"); } -async fn test_services() -> (Arc, std::path::PathBuf) { - let _ = rustls::crypto::ring::default_provider().install_default(); - let path = std::env::temp_dir() - .join(format!("continuwuity-shared-state-{:016x}", rand::random::())); - std::fs::create_dir(&path).unwrap(); - let config: Config = serde_json::from_value(json!({ - "server_name": "test.example", - "database_path": path, - "db_cache_capacity_mb": 16.0, - "rocksdb_write_buffer_capacity_mb": 4.0, - "allow_local_presence": false, - "dns_servers": ["127.0.0.1"], - "allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true - })) - .unwrap(); - let runtime = tokio::runtime::Handle::current(); - let server = Arc::new(Server::new( - config, - Some(runtime.clone()), - Log { - reload: LogLevelReloadHandles::default(), - capture: Arc::default(), - }, - Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None), - )); - let services = crate::Services::build(server).await.unwrap(); - (services, path) -} - fn cache_key( services: &crate::Services, server: &ruma::ServerName, diff --git a/src/service/sending/data.rs b/src/service/sending/data.rs index 59f5c0647..3f34bca91 100644 --- a/src/service/sending/data.rs +++ b/src/service/sending/data.rs @@ -3,6 +3,7 @@ use std::{fmt::Debug, sync::Arc}; use conduwuit::{ Error, Result, at, utils, utils::{ReadyExt, stream::TryIgnore}, + warn, }; use database::{Database, Deserialized, Map}; use futures::{Stream, StreamExt}; @@ -169,6 +170,33 @@ impl Data { }) } + /// The oldest queued request of each destination, not yet in flight. + pub(super) async fn queued_heads(&self) -> Vec<(Destination, QueueItem)> { + let mut heads: Vec<(Destination, QueueItem)> = Vec::new(); + self.servernameevent_data + .raw_stream() + .ignore_err() + .ready_for_each(|(key, val)| match parse_servercurrentevent(key, val) { + | Ok((dest, event)) => + if heads.last().is_none_or(|(last, _)| *last != dest) { + heads.push((dest, (key.to_vec(), event))); + }, + | Err(e) => warn!(?key, "invalid queued request key: {e}"), + }) + .await; + + heads + } + + /// Estimated number of requests waiting to be sent and in flight. + pub(crate) fn request_counts(&self) -> [(&'static str, Option); 2] { + [ + ("queued", &self.servernameevent_data), + ("active", &self.servercurrentevent_data), + ] + .map(|(state, map)| (state, map.property_integer(c"rocksdb.estimate-num-keys").ok())) + } + pub(super) fn set_latest_educount(&self, server_name: &ServerName, last_count: u64) { self.servername_educount.raw_put(server_name, last_count); } diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index 4bd1f76a1..8f971dc7a 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -3,12 +3,19 @@ mod appservice; mod data; mod dest; mod sender; +#[cfg(test)] +mod tests; use std::{ + collections::HashMap, fmt::Debug, hash::{DefaultHasher, Hash, Hasher}, iter::once, - sync::Arc, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, }; use async_trait::async_trait; @@ -19,7 +26,7 @@ use conduwuit::{ utils::{ReadyExt, TryReadyExt, available_parallelism, math::usize_from_u64_truncated}, warn, }; -use futures::{FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, stream::FuturesUnordered}; use ruma::{ OwnedServerName, RoomId, ServerName, UserId, api::{ @@ -27,7 +34,7 @@ use ruma::{ federation::authentication::ServerSignatures, path_builder::PathBuilder, }, }; -use tokio::{task, task::JoinSet}; +use tokio::{task, task::JoinSet, time::sleep}; use self::data::Data; pub use self::{ @@ -49,6 +56,7 @@ pub struct Service { server: Arc, services: Services, channels: Vec<(loole::Sender, loole::Receiver)>, + workers_alive: AtomicUsize, } struct Services { @@ -87,6 +95,8 @@ pub type EduVec = SmallVec<[EduBuf; EDU_VEC_CAP]>; const EDU_BUF_CAP: usize = 128; const EDU_VEC_CAP: usize = 1; +const WORKER_RESTART_DELAY: Duration = Duration::from_millis(2500); +const WORKER_RESTART_DELAY_MAX: Duration = Duration::from_secs(300); #[async_trait] impl crate::Service for Service { @@ -111,36 +121,67 @@ impl crate::Service for Service { federation: args.depend::("federation"), }, channels: (0..num_senders).map(|_| loole::unbounded()).collect(), + workers_alive: AtomicUsize::new(0), })) } async fn worker(self: Arc) -> Result { - let mut senders = - self.channels - .iter() - .enumerate() - .fold(JoinSet::new(), |mut joinset, (id, _)| { - let self_ = self.clone(); - let worker = self_.sender(id); - let worker = if self.unconstrained() { - task::unconstrained(worker).boxed() - } else { - worker.boxed() + if self.server.config.startup_netburst { + self.dispatch_queued(None).await; + } + + let num_senders = self.channels.len(); + let mut senders = JoinSet::new(); + let mut shards = HashMap::new(); + let mut started = vec![Instant::now(); num_senders]; + let mut failures = vec![0_u32; num_senders]; + let mut restarts = FuturesUnordered::new(); + for id in 0..num_senders { + self.spawn_sender(&mut senders, &mut shards, id, false); + } + + loop { + tokio::select! { + Some(ret) = senders.join_next_with_id() => { + self.workers_alive.fetch_sub(1, Ordering::Relaxed); + let (task_id, panicked) = match &ret { + | Ok((task_id, _)) => (*task_id, false), + | Err(error) => (error.id(), error.is_panic()), }; + let shard = shards.remove(&task_id).expect("sender worker has a shard"); - let runtime = self.server.runtime(); - let _abort = joinset.spawn_on(worker, runtime); - joinset - }); + if panicked { + self.server + .metrics + .instruments + .sender_panics + .add(1, &[KeyValue::new("scope", "worker")]); + } - while let Some(ret) = senders.join_next_with_id().await { - match ret { - | Ok((id, error)) => { - debug!(?id, ?error, "sender worker finished"); + if self.channels[shard].1.is_closed() || !self.server.running() { + debug!(shard, ?ret, "sender worker finished"); + continue; + } + + // A worker that ran a while before failing starts over from + // the shortest delay. + failures[shard] = if started[shard].elapsed() > WORKER_RESTART_DELAY_MAX { + 1 + } else { + failures[shard].saturating_add(1) + }; + let delay = restart_delay(failures[shard]); + error!(shard, ?ret, ?delay, "sender worker stopped, restarting"); + restarts.push(sleep(delay).map(move |()| shard)); }, - | Err(error) => { - error!(id = ?error.id(), ?error, "sender worker failed"); + Some(shard) = restarts.next() => { + if !self.channels[shard].1.is_closed() { + started[shard] = Instant::now(); + self.spawn_sender(&mut senders, &mut shards, shard, true); + } }, + () = self.server.until_shutdown(), if !restarts.is_empty() => restarts.clear(), + else => break, } } @@ -161,6 +202,25 @@ impl crate::Service for Service { } impl Service { + fn spawn_sender( + self: &Arc, + senders: &mut JoinSet, + shards: &mut HashMap, + id: usize, + restarted: bool, + ) { + let worker = self.clone().sender(id, restarted); + let worker = if crate::Service::unconstrained(&**self) { + task::unconstrained(worker).boxed() + } else { + worker.boxed() + }; + + let handle = senders.spawn_on(worker, self.server.runtime()); + shards.insert(handle.id(), id); + self.workers_alive.fetch_add(1, Ordering::Relaxed); + } + #[tracing::instrument(skip(self, pdu_id, user, pushkey), level = "debug")] pub fn send_pdu_push(&self, pdu_id: &RawPduId, user: &UserId, pushkey: String) -> Result { let dest = Destination::Push(user.to_owned(), pushkey); @@ -480,10 +540,24 @@ impl Service { sender.send(msg).map_err(|e| err!("{e}")) } + /// Hands the oldest unsent request of each destination to its worker, so + /// a backlog with nothing in flight is sent without waiting for a new + /// event. Bypasses `dispatch` as these requests were already counted. + async fn dispatch_queued(&self, shard: Option) { + for (dest, (queue_id, event)) in self.db.queued_heads().await { + let id = self.shard_id(&dest); + if shard.is_none_or(|shard| shard == id) { + self.channels[id].0.send(Msg { dest, event, queue_id }).ok(); + } + } + } + pub fn queue_depth(&self) -> usize { self.channels.iter().map(|(sender, _)| sender.len()).sum() } + pub fn workers_alive(&self) -> usize { self.workers_alive.load(Ordering::Relaxed) } + pub(super) fn shard_id(&self, dest: &Destination) -> usize { if self.channels.len() <= 1 { return 0; @@ -519,3 +593,11 @@ fn num_senders(args: &crate::Args<'_>) -> usize { worker_count.clamp(MIN_SENDERS, max_senders) } } + +/// Delay before restarting a worker after its `failures`-th consecutive +/// failure, doubling each time. +fn restart_delay(failures: u32) -> Duration { + WORKER_RESTART_DELAY + .saturating_mul(2_u32.saturating_pow(failures.saturating_sub(1))) + .min(WORKER_RESTART_DELAY_MAX) +} diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index 26cb371b1..f7e1c5ed8 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -1,6 +1,7 @@ use std::{ collections::{BTreeMap, HashMap, HashSet}, fmt::Debug, + panic::AssertUnwindSafe, sync::{ Arc, atomic::{AtomicU64, AtomicUsize, Ordering}, @@ -55,6 +56,9 @@ use serde_json::value::{RawValue as RawJsonValue, to_raw_value}; use super::{Destination, EduBuf, EduVec, Msg, SendingEvent, Service, data::QueueItem}; +#[cfg(test)] +mod tests; + #[derive(Debug)] enum TransactionStatus { Running, @@ -78,12 +82,18 @@ pub const EDU_LIMIT: usize = 100; impl Service { #[tracing::instrument(skip(self), level = "debug")] - pub(super) async fn sender(self: Arc, id: usize) -> Result { + pub(super) async fn sender(self: Arc, id: usize, restarted: bool) -> Result { let mut statuses: CurTransactionStatus = CurTransactionStatus::new(); let mut futures: SendingFutures<'_> = FuturesUnordered::new(); + // The previous worker of this shard may have dropped requests it had + // taken from the channel. + if restarted { + self.dispatch_queued(Some(id)).await; + } + info!(shard = id, "Running startup netburst"); - self.startup_netburst(id, &mut futures, &mut statuses) + self.startup_netburst(id, restarted, &mut futures, &mut statuses) .boxed() .await; info!(shard = id, "Finished startup netburst"); @@ -141,7 +151,17 @@ impl Service { statuses: &mut CurTransactionStatus, ) { match response { - | Ok(dest) => self.handle_response_ok(&dest, futures, statuses).await, + | Ok(dest) => { + if let Destination::Federation(server_name) = &dest { + self.services.federation.mark_healthy(server_name); + } + self.handle_response_ok(&dest, futures, statuses).await; + }, + // A bug on our side, not the remote's fault, and resending the same + // events would panic again: drop them and move on. + | Err((dest, e)) if e.is_panic() => { + self.handle_response_ok(&dest, futures, statuses).await; + }, | Err((dest, e)) => { if let Destination::Federation(dest) = &dest { if self.services.federation.should_mark_stale(&e) @@ -188,9 +208,6 @@ impl Service { ) { let _cork = self.db.db.cork(); self.db.delete_all_active_requests_for(dest).await; - if let Destination::Federation(server_name) = dest { - self.services.federation.mark_healthy(server_name); - } // Find events that have been added since starting the last request let new_events = self @@ -274,7 +291,8 @@ impl Service { } /// Performs startup netburst, which sends any previously queued up but not - /// yet sent requests immediately. + /// yet sent requests immediately. A restarted worker always resends its + /// shard's requests in flight, without trimming them. #[tracing::instrument( name = "netburst", level = "debug", @@ -285,6 +303,7 @@ impl Service { async fn startup_netburst<'a>( &'a self, id: usize, + restarted: bool, futures: &mut SendingFutures<'a>, statuses: &mut CurTransactionStatus, ) { @@ -299,8 +318,9 @@ impl Service { } let entry = txns.entry(dest.clone()).or_default(); - let over_budget = - self.server.config.startup_netburst_keep >= 0 && entry.len() >= keep; + let over_budget = !restarted + && self.server.config.startup_netburst_keep >= 0 + && entry.len() >= keep; if over_budget && !self.survives_netburst_trim(&event).await { warn!( @@ -315,8 +335,12 @@ impl Service { } } + if !restarted && !self.server.config.startup_netburst { + return; + } + for (dest, events) in txns { - if self.server.config.startup_netburst && !events.is_empty() { + if !events.is_empty() { statuses.insert(dest.clone(), TransactionStatus::Running); futures.push(self.send_events(dest, events)); } @@ -772,6 +796,7 @@ impl Service { }); let start = Instant::now(); + let panic_dest = dest.clone(); let send = match dest { | Destination::Federation(server) => self.send_events_dest_federation(server, events).boxed(), @@ -780,24 +805,42 @@ impl Service { self.send_events_dest_push(user_id, pushkey, events).boxed(), }; - send.inspect(move |result| { - let instruments = &self.server.metrics.instruments; - let outcome = - KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" }); - instruments - .sender_transaction_duration - .record(start.elapsed().as_secs_f64(), &[destination.clone(), outcome.clone()]); - for (kind, count) in [("pdu", pdus), ("edu", edus)] { - if count > 0 { - instruments.sender_events.add(count, &[ + AssertUnwindSafe(send) + .catch_unwind() + .map(move |result| { + result.unwrap_or_else(|panic| { + let error = Error::from_panic(panic); + error!(dest = ?panic_dest, ?error, "Panicked while sending transaction, dropping it"); + self.server + .metrics + .instruments + .sender_panics + .add(1, &[KeyValue::new("scope", "transaction")]); + + Err((panic_dest, Box::new(error))) + }) + }) + .inspect(move |result| { + let instruments = &self.server.metrics.instruments; + let outcome = + KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" }); + instruments + .sender_transaction_duration + .record(start.elapsed().as_secs_f64(), &[ destination.clone(), - KeyValue::new("kind", kind), outcome.clone(), ]); + for (kind, count) in [("pdu", pdus), ("edu", edus)] { + if count > 0 { + instruments.sender_events.add(count, &[ + destination.clone(), + KeyValue::new("kind", kind), + outcome.clone(), + ]); + } } - } - }) - .boxed() + }) + .boxed() } #[tracing::instrument( diff --git a/src/service/sending/sender/tests.rs b/src/service/sending/sender/tests.rs new file mode 100644 index 000000000..02b4eb005 --- /dev/null +++ b/src/service/sending/sender/tests.rs @@ -0,0 +1,82 @@ +use std::iter::once; + +use conduwuit::Error; +use futures::{StreamExt, stream::FuturesUnordered}; +use ruma::server_name; +use serde_json::json; + +use super::{CurTransactionStatus, TransactionStatus}; +use crate::{ + sending::{Destination, EduBuf, SendingEvent}, + test_utils::{test_services, test_services_with}, +}; + +#[tokio::test] +async fn panicked_transaction_is_dropped_without_blaming_the_remote() { + let (services, path, _database) = test_services().await; + let sending = &services.sending; + let server = server_name!("remote.example"); + let dest = Destination::Federation(server.to_owned()); + let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#)); + + sending.db.queue_requests(once((&event, &dest))); + let in_flight: Vec<_> = sending.db.queued_requests(&dest).collect().await; + sending.db.mark_as_active(in_flight.iter()); + let next = sending.db.queue_requests(once((&event, &dest))); + + let mut futures = FuturesUnordered::new(); + let mut statuses = CurTransactionStatus::from([(dest.clone(), TransactionStatus::Running)]); + let panic = Error::from_panic(Box::new("boom")); + sending + .handle_response(Err((dest.clone(), Box::new(panic))), &mut futures, &mut statuses) + .await; + + let active: Vec<_> = sending + .db + .active_requests_for(&dest) + .map(|(key, _)| key) + .collect() + .await; + let retry_after = sending.services.federation.retry_after(server); + let sending_next = futures.len(); + + drop(futures); + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(active, next); + assert_eq!(sending_next, 1); + assert_eq!(retry_after, None); +} + +#[tokio::test] +async fn restarted_worker_resends_in_flight_requests_without_trimming() { + let (services, path, _database) = + test_services_with(json!({ "startup_netburst_keep": 1 })).await; + let sending = &services.sending; + let dest = Destination::Federation(server_name!("remote.example").to_owned()); + let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#)); + + for _ in 0..3 { + sending.db.queue_requests(once((&event, &dest))); + } + let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await; + sending.db.mark_as_active(queued.iter()); + + let id = sending.shard_id(&dest); + let mut futures = FuturesUnordered::new(); + let mut statuses = CurTransactionStatus::new(); + sending + .startup_netburst(id, true, &mut futures, &mut statuses) + .await; + let after_restart = sending.db.active_requests_for(&dest).count().await; + sending + .startup_netburst(id, false, &mut futures, &mut statuses) + .await; + let after_startup = sending.db.active_requests_for(&dest).count().await; + + drop(futures); + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(after_restart, 3); + assert_eq!(after_startup, 1); +} diff --git a/src/service/sending/tests.rs b/src/service/sending/tests.rs new file mode 100644 index 000000000..74e41d843 --- /dev/null +++ b/src/service/sending/tests.rs @@ -0,0 +1,42 @@ +use std::{iter::once, time::Duration}; + +use futures::StreamExt; +use ruma::server_name; + +use super::{Destination, EduBuf, SendingEvent, restart_delay}; +use crate::test_utils::test_services; + +#[tokio::test] +async fn queued_heads_lists_the_oldest_unsent_request_per_destination() { + let (services, path, _database) = test_services().await; + let db = &services.sending.db; + let queued = Destination::Federation(server_name!("queued.example").to_owned()); + let active = Destination::Federation(server_name!("active.example").to_owned()); + let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#)); + + let first = db.queue_requests(once((&event, &queued))); + db.queue_requests(once((&event, &queued))); + db.queue_requests(once((&event, &active))); + let in_flight: Vec<_> = db.queued_requests(&active).collect().await; + db.mark_as_active(in_flight.iter()); + + let heads: Vec<_> = db + .queued_heads() + .await + .into_iter() + .map(|(dest, (key, _))| (dest, key)) + .collect(); + + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(heads, [(queued, first[0].clone())]); +} + +#[test] +fn restart_delay_doubles_up_to_the_cap() { + assert_eq!(restart_delay(1), Duration::from_millis(2500)); + assert_eq!(restart_delay(2), Duration::from_secs(5)); + assert_eq!(restart_delay(4), Duration::from_secs(20)); + assert_eq!(restart_delay(9), Duration::from_secs(300)); + assert_eq!(restart_delay(u32::MAX), Duration::from_secs(300)); +} diff --git a/src/service/test_utils.rs b/src/service/test_utils.rs new file mode 100644 index 000000000..e71fd2959 --- /dev/null +++ b/src/service/test_utils.rs @@ -0,0 +1,52 @@ +use std::{path::PathBuf, sync::Arc}; + +use conduwuit::{ + Config, Server, + log::{Log, LogLevelReloadHandles}, + metrics::Metrics, +}; +use serde_json::json; +use tokio::sync::{Mutex, MutexGuard}; + +/// RocksDB's default `Env` is shared by the whole process and closing a +/// database stops its background threads, so tests must not keep databases +/// open in parallel. Hold the returned guard until the services are dropped. +static DATABASE: Mutex<()> = Mutex::const_new(()); + +type TestServices = (Arc, PathBuf, MutexGuard<'static, ()>); + +pub(crate) async fn test_services() -> TestServices { test_services_with(json!({})).await } + +pub(crate) async fn test_services_with(overrides: serde_json::Value) -> TestServices { + let guard = DATABASE.lock().await; + let _ = rustls::crypto::ring::default_provider().install_default(); + let path = std::env::temp_dir() + .join(format!("continuwuity-shared-state-{:016x}", rand::random::())); + std::fs::create_dir(&path).unwrap(); + let mut config = json!({ + "server_name": "test.example", + "database_path": path, + "db_cache_capacity_mb": 16.0, + "rocksdb_write_buffer_capacity_mb": 4.0, + "allow_local_presence": false, + "dns_servers": ["127.0.0.1"], + "allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true + }); + config + .as_object_mut() + .unwrap() + .extend(overrides.as_object().unwrap().clone()); + let config: Config = serde_json::from_value(config).unwrap(); + let runtime = tokio::runtime::Handle::current(); + let server = Arc::new(Server::new( + config, + Some(runtime.clone()), + Log { + reload: LogLevelReloadHandles::default(), + capture: Arc::default(), + }, + Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None), + )); + let services = crate::Services::build(server).await.unwrap(); + (services, path, guard) +} From 793c06c17be4cec1bdf9199c6df69bd70f145f92 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 17 Nov 2026 16:46:43 +0100 Subject: [PATCH 319/342] fix(service/sending): Address review feedback on sender supervision Signed-off-by: Erwan Leboucher --- src/service/sending/mod.rs | 4 ++-- src/service/sending/sender.rs | 27 +++++++++++---------------- src/service/sending/sender/tests.rs | 28 ++++++++++++++++------------ src/service/sending/tests.rs | 4 ++-- 4 files changed, 31 insertions(+), 32 deletions(-) diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index 8f971dc7a..180f8da12 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -96,7 +96,7 @@ pub type EduVec = SmallVec<[EduBuf; EDU_VEC_CAP]>; const EDU_BUF_CAP: usize = 128; const EDU_VEC_CAP: usize = 1; const WORKER_RESTART_DELAY: Duration = Duration::from_millis(2500); -const WORKER_RESTART_DELAY_MAX: Duration = Duration::from_secs(300); +const WORKER_RESTART_DELAY_MAX: Duration = Duration::from_secs(30); #[async_trait] impl crate::Service for Service { @@ -171,7 +171,7 @@ impl crate::Service for Service { failures[shard].saturating_add(1) }; let delay = restart_delay(failures[shard]); - error!(shard, ?ret, ?delay, "sender worker stopped, restarting"); + error!(shard, ?ret, ?delay, "sender worker unexpectedly finished, restarting"); restarts.push(sleep(delay).map(move |()| shard)); }, Some(shard) = restarts.next() => { diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index f7e1c5ed8..fe94a8ff7 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -151,17 +151,10 @@ impl Service { statuses: &mut CurTransactionStatus, ) { match response { - | Ok(dest) => { - if let Destination::Federation(server_name) = &dest { - self.services.federation.mark_healthy(server_name); - } - self.handle_response_ok(&dest, futures, statuses).await; - }, - // A bug on our side, not the remote's fault, and resending the same - // events would panic again: drop them and move on. - | Err((dest, e)) if e.is_panic() => { - self.handle_response_ok(&dest, futures, statuses).await; - }, + | Ok(dest) => self.handle_response_ok(&dest, futures, statuses).await, + // A bug on our side, not the remote's fault: retry with backoff + // without marking the remote unhealthy. + | Err((dest, e)) if e.is_panic() => Self::handle_response_err(dest, statuses, &e), | Err((dest, e)) => { if let Destination::Federation(dest) = &dest { if self.services.federation.should_mark_stale(&e) @@ -208,6 +201,9 @@ impl Service { ) { let _cork = self.db.db.cork(); self.db.delete_all_active_requests_for(dest).await; + if let Destination::Federation(server_name) = dest { + self.services.federation.mark_healthy(server_name); + } // Find events that have been added since starting the last request let new_events = self @@ -292,7 +288,7 @@ impl Service { /// Performs startup netburst, which sends any previously queued up but not /// yet sent requests immediately. A restarted worker always resends its - /// shard's requests in flight, without trimming them. + /// shard's requests in flight. #[tracing::instrument( name = "netburst", level = "debug", @@ -318,9 +314,8 @@ impl Service { } let entry = txns.entry(dest.clone()).or_default(); - let over_budget = !restarted - && self.server.config.startup_netburst_keep >= 0 - && entry.len() >= keep; + let over_budget = + self.server.config.startup_netburst_keep >= 0 && entry.len() >= keep; if over_budget && !self.survives_netburst_trim(&event).await { warn!( @@ -810,7 +805,7 @@ impl Service { .map(move |result| { result.unwrap_or_else(|panic| { let error = Error::from_panic(panic); - error!(dest = ?panic_dest, ?error, "Panicked while sending transaction, dropping it"); + error!(dest = ?panic_dest, ?error, "Panicked while sending transaction"); self.server .metrics .instruments diff --git a/src/service/sending/sender/tests.rs b/src/service/sending/sender/tests.rs index 02b4eb005..e5104158d 100644 --- a/src/service/sending/sender/tests.rs +++ b/src/service/sending/sender/tests.rs @@ -12,7 +12,7 @@ use crate::{ }; #[tokio::test] -async fn panicked_transaction_is_dropped_without_blaming_the_remote() { +async fn panicked_transaction_is_kept_for_retry_without_blaming_the_remote() { let (services, path, _database) = test_services().await; let sending = &services.sending; let server = server_name!("remote.example"); @@ -22,7 +22,6 @@ async fn panicked_transaction_is_dropped_without_blaming_the_remote() { sending.db.queue_requests(once((&event, &dest))); let in_flight: Vec<_> = sending.db.queued_requests(&dest).collect().await; sending.db.mark_as_active(in_flight.iter()); - let next = sending.db.queue_requests(once((&event, &dest))); let mut futures = FuturesUnordered::new(); let mut statuses = CurTransactionStatus::from([(dest.clone(), TransactionStatus::Running)]); @@ -39,17 +38,25 @@ async fn panicked_transaction_is_dropped_without_blaming_the_remote() { .await; let retry_after = sending.services.federation.retry_after(server); let sending_next = futures.len(); + let failed = matches!(statuses.get(&dest), Some(TransactionStatus::Failed(1, _))); drop(futures); drop(services); std::fs::remove_dir_all(path).unwrap(); - assert_eq!(active, next); - assert_eq!(sending_next, 1); + assert_eq!( + active, + in_flight + .into_iter() + .map(|(key, _)| key) + .collect::>() + ); + assert_eq!(sending_next, 0); + assert!(failed); assert_eq!(retry_after, None); } #[tokio::test] -async fn restarted_worker_resends_in_flight_requests_without_trimming() { +async fn restarted_worker_resends_trimmed_in_flight_requests() { let (services, path, _database) = test_services_with(json!({ "startup_netburst_keep": 1 })).await; let sending = &services.sending; @@ -68,15 +75,12 @@ async fn restarted_worker_resends_in_flight_requests_without_trimming() { sending .startup_netburst(id, true, &mut futures, &mut statuses) .await; - let after_restart = sending.db.active_requests_for(&dest).count().await; - sending - .startup_netburst(id, false, &mut futures, &mut statuses) - .await; - let after_startup = sending.db.active_requests_for(&dest).count().await; + let active = sending.db.active_requests_for(&dest).count().await; + let sending_now = futures.len(); drop(futures); drop(services); std::fs::remove_dir_all(path).unwrap(); - assert_eq!(after_restart, 3); - assert_eq!(after_startup, 1); + assert_eq!(active, 1); + assert_eq!(sending_now, 1); } diff --git a/src/service/sending/tests.rs b/src/service/sending/tests.rs index 74e41d843..40c1cb957 100644 --- a/src/service/sending/tests.rs +++ b/src/service/sending/tests.rs @@ -37,6 +37,6 @@ fn restart_delay_doubles_up_to_the_cap() { assert_eq!(restart_delay(1), Duration::from_millis(2500)); assert_eq!(restart_delay(2), Duration::from_secs(5)); assert_eq!(restart_delay(4), Duration::from_secs(20)); - assert_eq!(restart_delay(9), Duration::from_secs(300)); - assert_eq!(restart_delay(u32::MAX), Duration::from_secs(300)); + assert_eq!(restart_delay(5), Duration::from_secs(30)); + assert_eq!(restart_delay(u32::MAX), Duration::from_secs(30)); } From cd7910009aac8b75acf263d47cd3a40e26c742a5 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 21:53:08 +0000 Subject: [PATCH 320/342] fix(service/sending): Apply local backoff to panicked federation transactions --- src/service/sending/sender.rs | 44 ++++++++++++++++++++--------- src/service/sending/sender/tests.rs | 4 ++- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index fe94a8ff7..432ad518a 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -62,8 +62,11 @@ mod tests; #[derive(Debug)] enum TransactionStatus { Running, - Failed(u32, Instant), // number of times failed, time of last failure - Retrying(u32), // number of times failed + /// Number of times failed, time of last failure, and whether local backoff + /// applies even for federation destinations (e.g. after a local panic when + /// the remote was not marked unhealthy). + Failed(u32, Instant, bool), + Retrying(u32), // number of times failed } type SendingError = (Destination, Box); @@ -152,10 +155,12 @@ impl Service { ) { match response { | Ok(dest) => self.handle_response_ok(&dest, futures, statuses).await, - // A bug on our side, not the remote's fault: retry with backoff - // without marking the remote unhealthy. - | Err((dest, e)) if e.is_panic() => Self::handle_response_err(dest, statuses, &e), + // A bug on our side, not the remote's fault: retry with local + // backoff without marking the remote unhealthy. + | Err((dest, e)) if e.is_panic() => + Self::handle_response_err(dest, statuses, &e, true), | Err((dest, e)) => { + let mut local_backoff = false; if let Destination::Federation(dest) = &dest { if self.services.federation.should_mark_stale(&e) || e.status_code() == StatusCode::NOT_FOUND @@ -166,22 +171,30 @@ impl Service { } else if e.status_code() != StatusCode::OK { debug!("{dest} is now unhealthy due to error response: {e:?}"); self.services.federation.hit_unhealthy(dest.clone(), None); + } else { + local_backoff = true; } } - Self::handle_response_err(dest, statuses, &e); + Self::handle_response_err(dest, statuses, &e, local_backoff); }, } } /// Handles a response error, incrementing the backoff factor. - fn handle_response_err(dest: Destination, statuses: &mut CurTransactionStatus, er: &Error) { + fn handle_response_err( + dest: Destination, + statuses: &mut CurTransactionStatus, + er: &Error, + local_backoff: bool, + ) { debug!(dest = ?dest, "{er:?}"); let dest2 = dest.clone(); statuses.entry(dest).and_modify(|e| { *e = match e { - | TransactionStatus::Running => TransactionStatus::Failed(1, Instant::now()), + | TransactionStatus::Running => + TransactionStatus::Failed(1, Instant::now(), local_backoff), | &mut TransactionStatus::Retrying(ref n) => - TransactionStatus::Failed(n.saturating_add(1), Instant::now()), + TransactionStatus::Failed(n.saturating_add(1), Instant::now(), local_backoff), | TransactionStatus::Failed(..) => { panic!( "Request to {dest2:?} that was not even running ({e:?}) failed: {er:?}" @@ -444,12 +457,17 @@ impl Service { allow = false; // already running trace!("Transaction is already running for {dest:?}"); }, - | TransactionStatus::Failed(tries, _) => { - if allow { + | TransactionStatus::Failed(tries, time, local_backoff) => { + if *local_backoff + && time.elapsed() < self.server.config.sender_retry_backoff(*tries) + { + allow = false; + trace!("{dest:?} is in local backoff, refusing send"); + } else { *e = TransactionStatus::Retrying(*tries); trace!("Previous transaction failed for {dest:?} ({e:?}), will retry"); + retry = true; } - retry = true; }, }); @@ -468,7 +486,7 @@ impl Service { statuses .entry(dest.clone()) .and_modify(|e| match e { - | TransactionStatus::Failed(tries, time) => { + | TransactionStatus::Failed(tries, time, _) => { let retry_after = self.server.config.sender_retry_backoff(*tries); if time.elapsed() < retry_after { debug_warn!("Not retrying destination for another {retry_after:?}"); diff --git a/src/service/sending/sender/tests.rs b/src/service/sending/sender/tests.rs index e5104158d..89f01ab8f 100644 --- a/src/service/sending/sender/tests.rs +++ b/src/service/sending/sender/tests.rs @@ -38,7 +38,8 @@ async fn panicked_transaction_is_kept_for_retry_without_blaming_the_remote() { .await; let retry_after = sending.services.federation.retry_after(server); let sending_next = futures.len(); - let failed = matches!(statuses.get(&dest), Some(TransactionStatus::Failed(1, _))); + let failed = matches!(statuses.get(&dest), Some(TransactionStatus::Failed(1, _, true))); + let immediate_retry = sending.should_attempt_send(&dest, &mut statuses).unwrap(); drop(futures); drop(services); @@ -52,6 +53,7 @@ async fn panicked_transaction_is_kept_for_retry_without_blaming_the_remote() { ); assert_eq!(sending_next, 0); assert!(failed); + assert_eq!(immediate_retry, (false, false)); assert_eq!(retry_after, None); } From d477417909216b3d89c15d1002af30498cbbe4c8 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 21:53:31 +0000 Subject: [PATCH 321/342] fix(service/sending): Preserve sticky events during restarted worker netburst --- src/service/sending/sender.rs | 13 ++-- src/service/sending/sender/tests.rs | 116 +++++++++++++++++++++++++++- 2 files changed, 120 insertions(+), 9 deletions(-) diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index 432ad518a..bb6be5f2f 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -316,6 +316,7 @@ impl Service { futures: &mut SendingFutures<'a>, statuses: &mut CurTransactionStatus, ) { + let delivering = restarted || self.server.config.startup_netburst; let keep = usize::try_from(self.server.config.startup_netburst_keep).unwrap_or(usize::MAX); let mut txns = HashMap::>::new(); @@ -330,7 +331,7 @@ impl Service { let over_budget = self.server.config.startup_netburst_keep >= 0 && entry.len() >= keep; - if over_budget && !self.survives_netburst_trim(&event).await { + if over_budget && !self.survives_netburst_trim(&event, delivering).await { warn!( startup_netburst_keep = self.server.config.startup_netburst_keep, queue_size = entry.len(), @@ -343,7 +344,7 @@ impl Service { } } - if !restarted && !self.server.config.startup_netburst { + if !delivering { return; } @@ -356,10 +357,10 @@ impl Service { } /// Whether this event skips the netburst budget, which MSC4354 asks of - /// still-sticky events. Only netburst delivers this queue, so with it - /// disabled there is nothing to keep the event for. - async fn survives_netburst_trim(&self, event: &SendingEvent) -> bool { - if !self.server.config.startup_netburst { + /// still-sticky events. Only a delivering netburst drains this queue, so + /// when nothing will deliver it there is nothing to keep the event for. + async fn survives_netburst_trim(&self, event: &SendingEvent, delivering: bool) -> bool { + if !delivering { return false; } diff --git a/src/service/sending/sender/tests.rs b/src/service/sending/sender/tests.rs index 89f01ab8f..1864f318d 100644 --- a/src/service/sending/sender/tests.rs +++ b/src/service/sending/sender/tests.rs @@ -1,9 +1,12 @@ use std::iter::once; -use conduwuit::Error; +use conduwuit::{ + Error, + matrix::{PartialPdu, pdu::sticky}, +}; use futures::{StreamExt, stream::FuturesUnordered}; -use ruma::server_name; -use serde_json::json; +use ruma::{RoomId, UserId, events::sticky::StickyDurationMs, server_name}; +use serde_json::{json, value::to_raw_value}; use super::{CurTransactionStatus, TransactionStatus}; use crate::{ @@ -86,3 +89,110 @@ async fn restarted_worker_resends_trimmed_in_flight_requests() { assert_eq!(active, 1); assert_eq!(sending_now, 1); } + +#[tokio::test] +async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled() { + let (services, path, _database) = + test_services_with(json!({ "startup_netburst": false, "startup_netburst_keep": 0 })) + .await; + let alice = UserId::parse("@alice:test.example").unwrap(); + let bootstrap = services + .rooms + .state + .mutex + .lock("!bootstrap:test.example") + .await; + let create_id = services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu { + event_type: "m.room.create".into(), + content: to_raw_value(&json!({ "room_version": "12" })).unwrap(), + state_key: Some("".into()), + ..Default::default() + }, + &alice, + None, + &bootstrap, + ) + .await + .unwrap(); + drop(bootstrap); + + let room = RoomId::parse(create_id.as_str().replacen('$', "!", 1)).unwrap(); + let lock = services.rooms.state.mutex.lock(&room).await; + services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu { + event_type: "m.room.member".into(), + content: to_raw_value(&json!({ "membership": "join" })).unwrap(), + state_key: Some(alice.as_str().into()), + ..Default::default() + }, + &alice, + Some(&room), + &lock, + ) + .await + .unwrap(); + let sticky_id = services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu { + event_type: "m.room.message".into(), + content: to_raw_value(&json!({ "msgtype": "m.text", "body": "sticky" })).unwrap(), + sticky: Some(sticky::object(StickyDurationMs::new_clamped(600_000_u32))), + ..Default::default() + }, + &alice, + Some(&room), + &lock, + ) + .await + .unwrap(); + drop(lock); + + let raw_pdu_id = services + .rooms + .timeline + .get_pdu_id(&sticky_id) + .await + .unwrap(); + let sending = &services.sending; + let dest = Destination::Federation(server_name!("remote.example").to_owned()); + let event = SendingEvent::Pdu(raw_pdu_id); + + sending.db.queue_requests(once((&event, &dest))); + let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await; + sending.db.mark_as_active(queued.iter()); + + let id = sending.shard_id(&dest); + let mut futures = FuturesUnordered::new(); + let mut statuses = CurTransactionStatus::new(); + sending + .startup_netburst(id, true, &mut futures, &mut statuses) + .await; + let active_after_restart = sending.db.active_requests_for(&dest).count().await; + let sending_after_restart = futures.len(); + + drop(futures); + let mut futures = FuturesUnordered::new(); + let mut statuses = CurTransactionStatus::new(); + sending + .startup_netburst(id, false, &mut futures, &mut statuses) + .await; + let active_after_startup = sending.db.active_requests_for(&dest).count().await; + let sending_after_startup = futures.len(); + + drop(futures); + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(active_after_restart, 1); + assert_eq!(sending_after_restart, 1); + assert_eq!(active_after_startup, 0); + assert_eq!(sending_after_startup, 0); +} From a0d9e71eacb296b34392280c927fd6dfd2cc7d89 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 21:54:14 +0000 Subject: [PATCH 322/342] fix(service/sending): Use Flush to wake queued destinations --- src/service/sending/data.rs | 24 +++++++++++++++--------- src/service/sending/mod.rs | 18 +++++++++++++----- src/service/sending/tests.rs | 13 ++++--------- 3 files changed, 32 insertions(+), 23 deletions(-) diff --git a/src/service/sending/data.rs b/src/service/sending/data.rs index 3f34bca91..fc8bc03a0 100644 --- a/src/service/sending/data.rs +++ b/src/service/sending/data.rs @@ -170,22 +170,28 @@ impl Data { }) } - /// The oldest queued request of each destination, not yet in flight. - pub(super) async fn queued_heads(&self) -> Vec<(Destination, QueueItem)> { - let mut heads: Vec<(Destination, QueueItem)> = Vec::new(); + /// Destinations with at least one queued request not yet in flight. + pub(super) async fn queued_destinations(&self) -> Vec { + let mut dests: Vec = Vec::new(); + let mut last_prefix: Vec = Vec::new(); self.servernameevent_data .raw_stream() .ignore_err() - .ready_for_each(|(key, val)| match parse_servercurrentevent(key, val) { - | Ok((dest, event)) => - if heads.last().is_none_or(|(last, _)| *last != dest) { - heads.push((dest, (key.to_vec(), event))); + .ready_for_each(|(key, val)| { + if !last_prefix.is_empty() && key.starts_with(&last_prefix) { + return; + } + match parse_servercurrentevent(key, val) { + | Ok((dest, _)) => { + last_prefix = dest.get_prefix(); + dests.push(dest); }, - | Err(e) => warn!(?key, "invalid queued request key: {e}"), + | Err(e) => warn!(?key, "invalid queued request key: {e}"), + } }) .await; - heads + dests } /// Estimated number of requests waiting to be sent and in flight. diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index 180f8da12..8cb9b43b6 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -540,14 +540,22 @@ impl Service { sender.send(msg).map_err(|e| err!("{e}")) } - /// Hands the oldest unsent request of each destination to its worker, so - /// a backlog with nothing in flight is sent without waiting for a new - /// event. Bypasses `dispatch` as these requests were already counted. + /// Wakes workers for every destination that has unsent queued requests, so + /// a backlog with nothing in flight is drained without waiting for a new + /// event. Uses `SendingEvent::Flush` so a message racing with already- + /// buffered channel items cannot re-insert and duplicate a sent request. async fn dispatch_queued(&self, shard: Option) { - for (dest, (queue_id, event)) in self.db.queued_heads().await { + for dest in self.db.queued_destinations().await { let id = self.shard_id(&dest); if shard.is_none_or(|shard| shard == id) { - self.channels[id].0.send(Msg { dest, event, queue_id }).ok(); + self.channels[id] + .0 + .send(Msg { + dest, + event: SendingEvent::Flush, + queue_id: Vec::new(), + }) + .ok(); } } } diff --git a/src/service/sending/tests.rs b/src/service/sending/tests.rs index 40c1cb957..be466d65e 100644 --- a/src/service/sending/tests.rs +++ b/src/service/sending/tests.rs @@ -7,29 +7,24 @@ use super::{Destination, EduBuf, SendingEvent, restart_delay}; use crate::test_utils::test_services; #[tokio::test] -async fn queued_heads_lists_the_oldest_unsent_request_per_destination() { +async fn queued_destinations_lists_each_destination_with_unsent_requests() { let (services, path, _database) = test_services().await; let db = &services.sending.db; let queued = Destination::Federation(server_name!("queued.example").to_owned()); let active = Destination::Federation(server_name!("active.example").to_owned()); let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#)); - let first = db.queue_requests(once((&event, &queued))); + db.queue_requests(once((&event, &queued))); db.queue_requests(once((&event, &queued))); db.queue_requests(once((&event, &active))); let in_flight: Vec<_> = db.queued_requests(&active).collect().await; db.mark_as_active(in_flight.iter()); - let heads: Vec<_> = db - .queued_heads() - .await - .into_iter() - .map(|(dest, (key, _))| (dest, key)) - .collect(); + let dests = db.queued_destinations().await; drop(services); std::fs::remove_dir_all(path).unwrap(); - assert_eq!(heads, [(queued, first[0].clone())]); + assert_eq!(dests, [queued]); } #[test] From 613bb1b2a83fe20d216ad355d7381de1def4bac7 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 21:54:34 +0000 Subject: [PATCH 323/342] fix(service/sending): Avoid spawning restarted workers during shutdown --- src/service/sending/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index 8cb9b43b6..21196e91c 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -175,7 +175,7 @@ impl crate::Service for Service { restarts.push(sleep(delay).map(move |()| shard)); }, Some(shard) = restarts.next() => { - if !self.channels[shard].1.is_closed() { + if !self.channels[shard].1.is_closed() && self.server.running() { started[shard] = Instant::now(); self.spawn_sender(&mut senders, &mut shards, shard, true); } From 21f3f0c1ebcfad22e5a3ab497d2139a36bd77d6e Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 21:58:40 +0000 Subject: [PATCH 324/342] perf(service/sending): Seek past destination prefixes in queued_destinations --- src/service/sending/data.rs | 100 ++++++++++++++++++++--------------- src/service/sending/tests.rs | 6 ++- 2 files changed, 61 insertions(+), 45 deletions(-) diff --git a/src/service/sending/data.rs b/src/service/sending/data.rs index fc8bc03a0..afb08439c 100644 --- a/src/service/sending/data.rs +++ b/src/service/sending/data.rs @@ -171,25 +171,37 @@ impl Data { } /// Destinations with at least one queued request not yet in flight. + /// + /// Seeks past each destination's key prefix so large per-destination + /// backlogs are skipped in O(destinations) seeks rather than scanning + /// every queued event. pub(super) async fn queued_destinations(&self) -> Vec { - let mut dests: Vec = Vec::new(); - let mut last_prefix: Vec = Vec::new(); - self.servernameevent_data - .raw_stream() + let mut dests = Vec::new(); + let mut cursor = Vec::new(); + + while let Some(key) = self + .servernameevent_data + .raw_keys_from(&cursor) .ignore_err() - .ready_for_each(|(key, val)| { - if !last_prefix.is_empty() && key.starts_with(&last_prefix) { - return; - } - match parse_servercurrentevent(key, val) { - | Ok((dest, _)) => { - last_prefix = dest.get_prefix(); - dests.push(dest); - }, - | Err(e) => warn!(?key, "invalid queued request key: {e}"), - } - }) - .await; + .next() + .await + { + match parse_destination(key) { + | Ok((dest, _)) => { + let prefix = dest.get_prefix(); + dests.push(dest); + let Some(next) = next_prefix(&prefix) else { + break; + }; + cursor = next; + }, + | Err(e) => { + warn!(?key, "invalid queued request key: {e}"); + cursor = key.to_vec(); + cursor.push(0); + }, + } + } dests } @@ -216,9 +228,17 @@ impl Data { } } -fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> { +/// Smallest byte slice strictly greater than every key starting with `prefix`. +fn next_prefix(prefix: &[u8]) -> Option> { + let pos = prefix.iter().rposition(|&b| b < u8::MAX)?; + let mut next = prefix[..=pos].to_vec(); + next[pos] = next[pos].saturating_add(1); + Some(next) +} + +fn parse_destination(key: &[u8]) -> Result<(Destination, &[u8])> { // Appservices start with a plus - Ok::<_, Error>(if key.starts_with(b"+") { + if key.starts_with(b"+") { let mut parts = key[1..].splitn(2, |&b| b == 0xFF); let server = parts.next().expect("splitn always returns one element"); @@ -230,14 +250,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se Error::bad_database("Invalid server bytes in server_currenttransaction") })?; - ( - Destination::Appservice(server), - if value.is_empty() { - SendingEvent::Pdu(event.into()) - } else { - SendingEvent::Edu(value.into()) - }, - ) + Ok((Destination::Appservice(server), event)) } else if key.starts_with(b"$") { let mut parts = key[1..].splitn(3, |&b| b == 0xFF); @@ -257,15 +270,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se .next() .ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?; - ( - Destination::Push(user_id, pushkey_string), - if value.is_empty() { - SendingEvent::Pdu(event.into()) - } else { - // I'm pretty sure this should never be called - SendingEvent::Edu(value.into()) - }, - ) + Ok((Destination::Push(user_id, pushkey_string), event)) } else { let mut parts = key.splitn(2, |&b| b == 0xFF); @@ -278,15 +283,22 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se Error::bad_database("Invalid server bytes in server_currenttransaction") })?; - ( + Ok(( Destination::Federation(ServerName::parse(&server).map_err(|_| { Error::bad_database("Invalid server string in server_currenttransaction") })?), - if value.is_empty() { - SendingEvent::Pdu(event.into()) - } else { - SendingEvent::Edu(value.into()) - }, - ) - }) + event, + )) + } +} + +fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> { + let (dest, event) = parse_destination(key)?; + let event = if value.is_empty() { + SendingEvent::Pdu(event.into()) + } else { + SendingEvent::Edu(value.into()) + }; + + Ok((dest, event)) } diff --git a/src/service/sending/tests.rs b/src/service/sending/tests.rs index be466d65e..0e59f1921 100644 --- a/src/service/sending/tests.rs +++ b/src/service/sending/tests.rs @@ -10,12 +10,16 @@ use crate::test_utils::test_services; async fn queued_destinations_lists_each_destination_with_unsent_requests() { let (services, path, _database) = test_services().await; let db = &services.sending.db; + let queued_sub = Destination::Federation(server_name!("queued.example.org").to_owned()); let queued = Destination::Federation(server_name!("queued.example").to_owned()); + let appservice = Destination::Appservice("bridge".to_owned()); let active = Destination::Federation(server_name!("active.example").to_owned()); let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#)); db.queue_requests(once((&event, &queued))); db.queue_requests(once((&event, &queued))); + db.queue_requests(once((&event, &queued_sub))); + db.queue_requests(once((&event, &appservice))); db.queue_requests(once((&event, &active))); let in_flight: Vec<_> = db.queued_requests(&active).collect().await; db.mark_as_active(in_flight.iter()); @@ -24,7 +28,7 @@ async fn queued_destinations_lists_each_destination_with_unsent_requests() { drop(services); std::fs::remove_dir_all(path).unwrap(); - assert_eq!(dests, [queued]); + assert_eq!(dests, [appservice, queued_sub, queued]); } #[test] From 9f7fb54bd453f3727962ca97c330435eb3d55b01 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 18:42:48 +0000 Subject: [PATCH 325/342] fix: Don't fail entire preview requests when auxiliary requests fail --- src/api/client/media.rs | 3 +- src/service/client/mod.rs | 2 +- src/service/media/preview.rs | 71 ++++++++++++++++++++---------------- 3 files changed, 42 insertions(+), 34 deletions(-) diff --git a/src/api/client/media.rs b/src/api/client/media.rs index 669cda35d..73ded8f01 100644 --- a/src/api/client/media.rs +++ b/src/api/client/media.rs @@ -2,7 +2,7 @@ use std::time::Duration; use axum::extract::State; use conduwuit::{ - Err, Result, err, + Err, Result, err, info, utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize}, }; use conduwuit_core::error; @@ -219,6 +219,7 @@ pub(crate) async fn get_media_preview_route( ))); } + info!("Fetching a URL preview for {url} on behalf of {sender_user}"); let preview = services .media .get_url_preview(&url) diff --git a/src/service/client/mod.rs b/src/service/client/mod.rs index 2cd157f84..5959c0a8a 100644 --- a/src/service/client/mod.rs +++ b/src/service/client/mod.rs @@ -111,7 +111,7 @@ impl crate::Service for Service { .local_address(url_preview_bind_addr) .timeout(Duration::from_secs(config.url_preview_timeout)) .redirect(redirect::Policy::limited(3)) - .user_agent(url_preview_user_agent) + .user_agent(url_preview_user_agent.replace("", conduwuit::version_ua())) .build()?, external_resource: base(config, reqwest_dns_resolver.clone())? diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index 084aa9a1b..e48df437b 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -7,7 +7,7 @@ use std::time::SystemTime; -use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt}; +use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt, info}; use ipaddress::IPAddress; use ruma::OwnedMxcUri; use serde::Serialize; @@ -100,7 +100,9 @@ impl Service { } let Some(content_type) = response.headers().get(reqwest::header::CONTENT_TYPE) else { - return Err!(Request(Unknown("Unknown or invalid Content-Type header"))); + return Err!(Request(Unknown( + "Response contains unknown, invalid, or missing Content-Type header" + ))); }; let content_type = content_type @@ -109,12 +111,10 @@ impl Service { let data = match content_type { | html if html.starts_with("text/html") => self.download_html(url.as_str()).await?, - | img if img.starts_with("image/") => self.download_image(url.as_str(), None).await?, - | video if video.starts_with("video/") => - self.download_video(url.as_str(), None).await?, - | audio if audio.starts_with("audio/") => - self.download_audio(url.as_str(), None).await?, - | _ => return Err!(Request(Unknown("Unsupported Content-Type"))), + | img if img.starts_with("image/") => self.download_image(url.as_str()).await?, + | video if video.starts_with("video/") => self.download_video(url.as_str()).await?, + | audio if audio.starts_with("audio/") => self.download_audio(url.as_str()).await?, + | other => return Err!(Request(Unknown("Unsupported Content-Type: {other}"))), }; self.set_url_preview(url.as_str(), &data).await?; @@ -123,17 +123,13 @@ impl Service { } #[cfg(feature = "url_preview")] - pub async fn download_image( - &self, - url: &str, - preview_data: Option, - ) -> Result { + pub async fn download_image(&self, url: &str) -> Result { use conduwuit::utils::random_string; use image::ImageReader; use crate::media::mxc::Mxc; - let mut preview_data = preview_data.unwrap_or_default(); + let mut preview_data = UrlPreviewData::default(); let response = self.services.client.url_preview.get(url).send().await?; if !response.status().is_success() { @@ -179,12 +175,8 @@ impl Service { } #[cfg(feature = "url_preview")] - pub async fn download_video( - &self, - url: &str, - preview_data: Option, - ) -> Result { - let mut preview_data = preview_data.unwrap_or_default(); + pub async fn download_video(&self, url: &str) -> Result { + let mut preview_data = UrlPreviewData::default(); if self.services.globals.url_preview_allow_audio_video() { let (url, size) = self.download_media(url).await?; @@ -196,12 +188,8 @@ impl Service { } #[cfg(feature = "url_preview")] - pub async fn download_audio( - &self, - url: &str, - preview_data: Option, - ) -> Result { - let mut preview_data = preview_data.unwrap_or_default(); + pub async fn download_audio(&self, url: &str) -> Result { + let mut preview_data = UrlPreviewData::default(); if self.services.globals.url_preview_allow_audio_video() { let (url, size) = self.download_media(url).await?; @@ -286,24 +274,43 @@ impl Service { .expect("u64 should fit in usize"), ) .await?; - let Ok(html) = HTML::from_string(body.clone(), Some(url.to_owned())) else { + let Ok(html) = HTML::from_string(body.clone(), Some(url.to_owned())) + .inspect_err(|e| debug!(error=?e, "Failed to parse HTML data")) + else { return Err!(Request(Unknown("Failed to parse HTML"))); }; let mut preview_data = UrlPreviewData::default(); if let Some(obj) = html.opengraph.images.first() { - preview_data = self.download_image(&obj.url, Some(preview_data)).await?; + if let Ok(image_data) = self.download_image(&obj.url).await.inspect_err( + |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview image"), + ) { + preview_data.image = image_data.image; + preview_data.image_size = image_data.image_size; + preview_data.image_width = image_data.image_width; + preview_data.image_height = image_data.image_height; + } } if let Some(obj) = html.opengraph.videos.first() { - preview_data = self.download_video(&obj.url, Some(preview_data)).await?; - preview_data.video_width = obj.properties.get("width").and_then(|v| v.parse().ok()); - preview_data.video_height = obj.properties.get("height").and_then(|v| v.parse().ok()); + if let Ok(video_data) = self.download_video(&obj.url).await.inspect_err( + |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview video"), + ) { + preview_data.video = video_data.video; + preview_data.video_width = video_data.video_width; + preview_data.video_height = video_data.video_height; + preview_data.video_size = video_data.video_size; + } } if let Some(obj) = html.opengraph.audios.first() { - preview_data = self.download_audio(&obj.url, Some(preview_data)).await?; + if let Ok(audio_data) = self.download_audio(&obj.url).await.inspect_err( + |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview audio"), + ) { + preview_data.audio = audio_data.audio; + preview_data.audio_size = audio_data.audio_size; + } } let props = html.opengraph.properties; From 17af942cbf09364e2bcae3b213a43b0b2c7eb926 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 19:18:17 +0000 Subject: [PATCH 326/342] feat: Support most other specified opengraph tags --- src/service/media/data.rs | 6 +++ src/service/media/preview.rs | 73 +++++++++++++++++++++++++++++++++++- 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/src/service/media/data.rs b/src/service/media/data.rs index d4a1c15cd..e261984e4 100644 --- a/src/service/media/data.rs +++ b/src/service/media/data.rs @@ -223,6 +223,8 @@ impl Data { x => x, };*/ + // TODO(nex): Oh my god this is awful when can we kill it + let title = match values .next() .and_then(|b| String::from_utf8(b.to_vec()).ok()) @@ -321,6 +323,10 @@ impl Data { video_height, audio, audio_size, + ..Default::default() /* TODO(nex): This weird manual field de/serialisation just + * needs replacing with JSON storage to avoid this mess. + * This is consequently intentionally dropping information + * added later (like image alt text). I'll do it later. */ }) } } diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index e48df437b..83dd3be45 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -9,6 +9,7 @@ use std::time::SystemTime; use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt, info}; use ipaddress::IPAddress; +use lettre::message::header::ContentType; use ruma::OwnedMxcUri; use serde::Serialize; use url::Url; @@ -18,18 +19,52 @@ use crate::media::mxc::Mxc; #[derive(Serialize, Default)] pub struct UrlPreviewData { + // From https://ogp.me/ + /// The title of your object as it should appear within the graph + /// "The Rock". #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:title"))] pub title: Option, + + /// The type of your object, e.g., "video.movie". + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:type"))] + pub site_type: Option, + /// The canonical URL of your object that will be used as its permanent ID + /// in the graph. + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:url"))] + pub url: Option, + /// A one to two sentence description of your object. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:description"))] pub description: Option, + /// The word that appears before this object's title in a sentence. + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:determiner"))] + pub determiner: Option, + /// The locale these tags are marked up in + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:locale"))] + pub locale: Option, + /// If your object is part of a larger web site, the name which should be + /// displayed for the overall site. + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:site_name"))] + pub site_name: Option, + + /// An image URL which should represent your object within the graph. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image"))] pub image: Option, + /// A MIME type for this image. + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:type"))] + pub image_type: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:image:size"))] pub image_size: Option, + /// The number of pixels wide. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:width"))] pub image_width: Option, + /// The number of pixels high. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:height"))] pub image_height: Option, + /// A description of what is in the image (not a caption). + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:alt"))] + pub image_alt: Option, + + /// A URL to a video file that complements this object. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video"))] pub video: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:video:size"))] @@ -38,6 +73,11 @@ pub struct UrlPreviewData { pub video_width: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:height"))] pub video_height: Option, + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:type"))] + pub video_type: Option, + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:alt"))] + pub video_alt: Option, + /// A URL to an audio file to accompany this object. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:audio"))] pub audio: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:audio:size"))] @@ -290,6 +330,19 @@ impl Service { preview_data.image_size = image_data.image_size; preview_data.image_width = image_data.image_width; preview_data.image_height = image_data.image_height; + preview_data.image_type = obj + .properties + .get("image:type") + .cloned() + .map(|s| s.parse()) + .transpose() + .ok() + .flatten(); + preview_data.image_alt = obj + .properties + .get("image:alt") + .cloned() + .or(image_data.image_alt); } } @@ -301,6 +354,19 @@ impl Service { preview_data.video_width = video_data.video_width; preview_data.video_height = video_data.video_height; preview_data.video_size = video_data.video_size; + preview_data.video_type = obj + .properties + .get("video:type") + .cloned() + .map(|s| s.parse()) + .transpose() + .ok() + .flatten(); + preview_data.video_alt = obj + .properties + .get("video:alt") + .cloned() + .or(video_data.video_alt); } } @@ -315,10 +381,13 @@ impl Service { let props = html.opengraph.properties; - /* use OpenGraph title/description, but fall back to HTML if not - * available */ preview_data.title = props.get("title").cloned().or(html.title); preview_data.description = props.get("description").cloned().or(html.description); + preview_data.determiner = props.get("determiner").cloned(); + preview_data.locale = props.get("locale").cloned(); + preview_data.site_name = props.get("site_name").cloned(); + preview_data.site_type = props.get("type").cloned(); + preview_data.url = props.get("url").cloned().or_else(|| Some(url.to_owned())); Ok(preview_data) } From 5ad6c35f0bddc873db43c8bb7af6f780bcb5c58a Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 19:48:18 +0000 Subject: [PATCH 327/342] fix: Default to asset type when not at top-level --- src/service/media/preview.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index 83dd3be45..3e7ff7caf 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -337,7 +337,8 @@ impl Service { .map(|s| s.parse()) .transpose() .ok() - .flatten(); + .flatten() + .or(image_data.image_type); preview_data.image_alt = obj .properties .get("image:alt") @@ -361,7 +362,8 @@ impl Service { .map(|s| s.parse()) .transpose() .ok() - .flatten(); + .flatten() + .or(video_data.video_type); preview_data.video_alt = obj .properties .get("video:alt") From f5bd8d0a7cea1e0c710a7a943103dd71e00c358c Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 19:49:29 +0000 Subject: [PATCH 328/342] chore: Add newsfrag --- changelog.d/2448.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/2448.bugfix.md diff --git a/changelog.d/2448.bugfix.md b/changelog.d/2448.bugfix.md new file mode 100644 index 000000000..557e68c4a --- /dev/null +++ b/changelog.d/2448.bugfix.md @@ -0,0 +1 @@ +URL previews no longer completely fail if downloading auxiliary content (images/videos/audio) fails. Contributed by @nex. From 4710c227db50bd2ee744fa6d6345ad2076d8f0f0 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 19:51:02 +0000 Subject: [PATCH 329/342] chore: Add @silversys to refactor TODO --- src/service/media/data.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/service/media/data.rs b/src/service/media/data.rs index e261984e4..bc20ee0b8 100644 --- a/src/service/media/data.rs +++ b/src/service/media/data.rs @@ -323,10 +323,11 @@ impl Data { video_height, audio, audio_size, - ..Default::default() /* TODO(nex): This weird manual field de/serialisation just - * needs replacing with JSON storage to avoid this mess. - * This is consequently intentionally dropping information - * added later (like image alt text). I'll do it later. */ + ..Default::default() /* TODO(nex,silversys): This weird manual field + * de/serialisation just needs replacing with JSON storage to + * avoid this mess. This is consequently intentionally + * dropping information added later (like image alt text). + * I'll do it later. */ }) } } From 16f18f851642e2b07400638ff262b15ff967a755 Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 19:55:52 +0000 Subject: [PATCH 330/342] feat: Make url preview logs more informative --- src/api/client/media.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/client/media.rs b/src/api/client/media.rs index 73ded8f01..28d1e4bfc 100644 --- a/src/api/client/media.rs +++ b/src/api/client/media.rs @@ -224,6 +224,8 @@ pub(crate) async fn get_media_preview_route( .media .get_url_preview(&url) .await + .inspect(|_| info!(user=%sender_user, "Finished fetching a URL preview for {url}")) + .inspect_err(|e| info!(user=%sender_user, "Failed to fetch a URL preview for {url}: {e}")) .map_err(|error| { err!(Request(Unknown( debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}") From 33ed0a2e75f16e9f22282504556ee06c19db86fa Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 20:42:52 +0000 Subject: [PATCH 331/342] feat: Automatically populate UrlPreviewData, correctly populate media fields --- src/service/media/preview.rs | 172 +++++++++++++++++++++++++---------- 1 file changed, 123 insertions(+), 49 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index 3e7ff7caf..16cce3240 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -193,13 +193,12 @@ impl Service { .ok_or_else(|| err!(Request(Unknown("Downloaded file is not a supported image"))))? .to_mime_type(); - if preview_data.image_height.is_none() || preview_data.image_width.is_none() { - let (width, height) = reader.into_dimensions().map_err(|error| { - err!(Request(Unknown("Failed to read preview image dimensions: {error}"))) - })?; - preview_data.image_width.get_or_insert(width); - preview_data.image_height.get_or_insert(height); - } + let (width, height) = reader.into_dimensions().map_err(|error| { + err!(Request(Unknown("Failed to read preview image dimensions: {error}"))) + })?; + preview_data.image_width.get_or_insert(width); + preview_data.image_height.get_or_insert(height); + preview_data.image_type = content_type.parse().ok(); let mxc = Mxc { server_name: self.services.globals.server_name(), @@ -320,30 +319,20 @@ impl Service { return Err!(Request(Unknown("Failed to parse HTML"))); }; - let mut preview_data = UrlPreviewData::default(); + let mut preview_data = UrlPreviewData::from(&html.opengraph); if let Some(obj) = html.opengraph.images.first() { + info!("Downloading URL preview image from {}", obj.url); if let Ok(image_data) = self.download_image(&obj.url).await.inspect_err( |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview image"), ) { preview_data.image = image_data.image; preview_data.image_size = image_data.image_size; - preview_data.image_width = image_data.image_width; - preview_data.image_height = image_data.image_height; - preview_data.image_type = obj - .properties - .get("image:type") - .cloned() - .map(|s| s.parse()) - .transpose() - .ok() - .flatten() - .or(image_data.image_type); - preview_data.image_alt = obj - .properties - .get("image:alt") - .cloned() - .or(image_data.image_alt); + // Prioritise what the top-level site specified, falling back to + // detected params. + preview_data.image_width = preview_data.image_width.or(image_data.image_width); + preview_data.image_height = preview_data.image_height.or(image_data.image_height); + preview_data.image_type = preview_data.image_type.or(image_data.image_type); } } @@ -352,23 +341,7 @@ impl Service { |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview video"), ) { preview_data.video = video_data.video; - preview_data.video_width = video_data.video_width; - preview_data.video_height = video_data.video_height; preview_data.video_size = video_data.video_size; - preview_data.video_type = obj - .properties - .get("video:type") - .cloned() - .map(|s| s.parse()) - .transpose() - .ok() - .flatten() - .or(video_data.video_type); - preview_data.video_alt = obj - .properties - .get("video:alt") - .cloned() - .or(video_data.video_alt); } } @@ -381,15 +354,13 @@ impl Service { } } - let props = html.opengraph.properties; - - preview_data.title = props.get("title").cloned().or(html.title); - preview_data.description = props.get("description").cloned().or(html.description); - preview_data.determiner = props.get("determiner").cloned(); - preview_data.locale = props.get("locale").cloned(); - preview_data.site_name = props.get("site_name").cloned(); - preview_data.site_type = props.get("type").cloned(); - preview_data.url = props.get("url").cloned().or_else(|| Some(url.to_owned())); + // Provide defaults for some params + preview_data.title = preview_data.title.or(html.title); + preview_data.description = preview_data.description.or(html.description); + preview_data.url = preview_data.url.or_else(|| Some(url.to_owned())); + preview_data.site_type = preview_data + .site_type + .or_else(|| Some("website".to_owned())); Ok(preview_data) } @@ -521,3 +492,106 @@ impl Service { false } } + +impl From<&webpage::Opengraph> for UrlPreviewData { + fn from(og: &webpage::Opengraph) -> Self { + Self { + title: og.properties.get("title").cloned(), + description: og.properties.get("description").cloned(), + site_type: og.properties.get("type").cloned(), + url: og.properties.get("url").cloned(), + determiner: og.properties.get("determiner").cloned(), + locale: og.properties.get("locale").cloned(), + site_name: og.properties.get("site_name").cloned(), + image: og.images.first().map(|img| img.url.clone()), + image_type: og + .images + .first() + .and_then(|img| img.properties.get("type").and_then(|t| t.parse().ok())), + image_width: og + .images + .first() + .and_then(|img| img.properties.get("width").and_then(|w| w.parse().ok())), + image_height: og + .images + .first() + .and_then(|img| img.properties.get("height").and_then(|h| h.parse().ok())), + image_alt: og + .images + .first() + .and_then(|img| img.properties.get("alt").cloned()), + video: og.videos.first().map(|vid| vid.url.clone()), + video_type: og + .videos + .first() + .and_then(|vid| vid.properties.get("type")) + .and_then(|t| t.parse().ok()), + video_width: og + .videos + .first() + .and_then(|vid| vid.properties.get("width")) + .and_then(|w| w.parse().ok()), + video_height: og + .videos + .first() + .and_then(|vid| vid.properties.get("height")) + .and_then(|h| h.parse().ok()), + video_alt: og + .videos + .first() + .and_then(|vid| vid.properties.get("alt").cloned()), + ..Default::default() + } + } +} + +#[cfg(test)] +mod tests { + use webpage::HTML; + + use super::UrlPreviewData; + + #[test] + fn test_urlpreviewdata_parses_correctly() { + let html = r#" + + + + + + + + + + + + + + + + "#; + + let parsed_html = + HTML::from_string(html.to_owned(), Some("https://example.com".to_owned())) + .expect("Failed to parse HTML"); + + let data = UrlPreviewData::from(&parsed_html.opengraph); + + assert_eq!(data.title, Some("Test Title".to_owned())); + assert_eq!(data.description, Some("Test Description".to_owned())); + assert_eq!( + data.image, None, + "UrlPreviewData should not inherit HTTP/S URL from URL preview" + ); + assert_eq!(data.url, Some("https://example.com/index.html".to_owned())); + assert_eq!(data.site_type, Some("org.continuwuity.other".to_owned())); + assert_eq!(data.site_name, Some("Example Site".to_owned())); + assert_eq!(data.image_alt, Some("An example image".to_owned())); + assert_eq!(data.image_type, Some("image/png".parse().unwrap())); + assert_eq!(data.image_height, Some(69)); + assert_eq!(data.image_width, Some(420)); + assert_eq!(data.image_size, None, "*_size must be None when pulling from opengraph"); + assert_eq!(data.video_size, None, "*_size must be None when pulling from opengraph"); + assert_eq!(data.audio_size, None, "*_size must be None when pulling from opengraph"); + } +} From 66be5efeec7300ce6e6372caf44bba4a0ad5d73b Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 21:51:51 +0000 Subject: [PATCH 332/342] fix: Properly select correct properties, fixup unit test --- src/api/client/media.rs | 6 ++++-- src/service/media/preview.rs | 29 +++++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/src/api/client/media.rs b/src/api/client/media.rs index 28d1e4bfc..4f780cd99 100644 --- a/src/api/client/media.rs +++ b/src/api/client/media.rs @@ -224,8 +224,10 @@ pub(crate) async fn get_media_preview_route( .media .get_url_preview(&url) .await - .inspect(|_| info!(user=%sender_user, "Finished fetching a URL preview for {url}")) - .inspect_err(|e| info!(user=%sender_user, "Failed to fetch a URL preview for {url}: {e}")) + .inspect(|_| info!(user=%sender_user, %url, "Finished fetching a URL preview")) + .inspect_err( + |e| info!(user=%sender_user, %url, error=?e, "Failed to fetch a URL preview"), + ) .map_err(|error| { err!(Request(Unknown( debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}") diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index 16cce3240..a90b65a33 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -26,8 +26,8 @@ pub struct UrlPreviewData { pub title: Option, /// The type of your object, e.g., "video.movie". - #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:type"))] - pub site_type: Option, + #[serde(skip_serializing_if = "String::is_empty", rename(serialize = "og:type"))] + pub site_type: String, /// The canonical URL of your object that will be used as its permanent ID /// in the graph. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:url"))] @@ -214,6 +214,7 @@ impl Service { } #[cfg(feature = "url_preview")] + #[tracing::instrument(skip(self))] pub async fn download_video(&self, url: &str) -> Result { let mut preview_data = UrlPreviewData::default(); @@ -227,6 +228,7 @@ impl Service { } #[cfg(feature = "url_preview")] + #[tracing::instrument(skip(self))] pub async fn download_audio(&self, url: &str) -> Result { let mut preview_data = UrlPreviewData::default(); @@ -239,6 +241,7 @@ impl Service { Ok(preview_data) } + #[tracing::instrument(skip(self))] pub async fn download_media(&self, url: &str) -> Result<(OwnedMxcUri, usize)> { use conduwuit::utils::random_string; use http::header::CONTENT_TYPE; @@ -296,6 +299,7 @@ impl Service { } #[cfg(feature = "url_preview")] + #[tracing::instrument(skip(self))] async fn download_html(&self, url: &str) -> Result { use webpage::HTML; @@ -358,9 +362,6 @@ impl Service { preview_data.title = preview_data.title.or(html.title); preview_data.description = preview_data.description.or(html.description); preview_data.url = preview_data.url.or_else(|| Some(url.to_owned())); - preview_data.site_type = preview_data - .site_type - .or_else(|| Some("website".to_owned())); Ok(preview_data) } @@ -498,12 +499,11 @@ impl From<&webpage::Opengraph> for UrlPreviewData { Self { title: og.properties.get("title").cloned(), description: og.properties.get("description").cloned(), - site_type: og.properties.get("type").cloned(), + site_type: og.og_type.clone(), url: og.properties.get("url").cloned(), determiner: og.properties.get("determiner").cloned(), locale: og.properties.get("locale").cloned(), site_name: og.properties.get("site_name").cloned(), - image: og.images.first().map(|img| img.url.clone()), image_type: og .images .first() @@ -520,7 +520,6 @@ impl From<&webpage::Opengraph> for UrlPreviewData { .images .first() .and_then(|img| img.properties.get("alt").cloned()), - video: og.videos.first().map(|vid| vid.url.clone()), video_type: og .videos .first() @@ -561,11 +560,13 @@ mod tests { - + + + @@ -583,8 +584,16 @@ mod tests { data.image, None, "UrlPreviewData should not inherit HTTP/S URL from URL preview" ); + assert_eq!( + data.video, None, + "UrlPreviewData should not inherit HTTP/S URL from URL preview" + ); + assert_eq!( + data.audio, None, + "UrlPreviewData should not inherit HTTP/S URL from URL preview" + ); assert_eq!(data.url, Some("https://example.com/index.html".to_owned())); - assert_eq!(data.site_type, Some("org.continuwuity.other".to_owned())); + assert_eq!(data.site_type, "org.continuwuity.other".to_owned()); assert_eq!(data.site_name, Some("Example Site".to_owned())); assert_eq!(data.image_alt, Some("An example image".to_owned())); assert_eq!(data.image_type, Some("image/png".parse().unwrap())); From bd7450f52a213f669c1ac2c994b3c709e6f507bb Mon Sep 17 00:00:00 2001 From: timedout Date: Tue, 3 Nov 2026 22:27:34 +0000 Subject: [PATCH 333/342] fix: Remove attachment metadata when the attachment has no URL --- src/service/media/preview.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index a90b65a33..9a5d60a50 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -17,7 +17,7 @@ use url::Url; use super::Service; use crate::media::mxc::Mxc; -#[derive(Serialize, Default)] +#[derive(Serialize, Default, Debug)] pub struct UrlPreviewData { // From https://ogp.me/ /// The title of your object as it should appear within the graph @@ -324,9 +324,10 @@ impl Service { }; let mut preview_data = UrlPreviewData::from(&html.opengraph); + debug!(parsed=?preview_data, deserialised=?html.opengraph, "Parsed opengraph data"); if let Some(obj) = html.opengraph.images.first() { - info!("Downloading URL preview image from {}", obj.url); + info!(asset_url=%obj.url, "Downloading preview image"); if let Ok(image_data) = self.download_image(&obj.url).await.inspect_err( |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview image"), ) { @@ -341,6 +342,7 @@ impl Service { } if let Some(obj) = html.opengraph.videos.first() { + info!(asset_url=%obj.url, "Downloading preview video"); if let Ok(video_data) = self.download_video(&obj.url).await.inspect_err( |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview video"), ) { @@ -350,6 +352,7 @@ impl Service { } if let Some(obj) = html.opengraph.audios.first() { + info!(asset_url=%obj.url, "Downloading URL preview audio"); if let Ok(audio_data) = self.download_audio(&obj.url).await.inspect_err( |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview audio"), ) { @@ -363,6 +366,27 @@ impl Service { preview_data.description = preview_data.description.or(html.description); preview_data.url = preview_data.url.or_else(|| Some(url.to_owned())); + // We remove og:image:*, og:video:*, and og:audio:* if their respective + // prior-level properties are not present. + // We do this here instead of in the From<> impl because we can't know + // if we'll be able to fetch the media to convert it to an mxc that + // point. + if preview_data.image.is_none() { + preview_data.image_type = None; + preview_data.image_alt = None; + preview_data.image_height = None; + preview_data.image_width = None; + } + if preview_data.video.is_none() { + preview_data.video_type = None; + preview_data.video_alt = None; + preview_data.video_height = None; + preview_data.video_width = None; + } + if preview_data.audio.is_none() { + preview_data.audio_size = None; + } + Ok(preview_data) } From 137805693efefeb4c4e52c5f72afea500b5e0c95 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 11 Nov 2026 11:23:36 +0000 Subject: [PATCH 334/342] refactor: Use mime::Mime instead of lettre ContentType for URL previews --- Cargo.toml | 3 +++ src/service/Cargo.toml | 1 + src/service/media/preview.rs | 47 +++++++++++++++++++++++++----------- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index dfd81c967..4732335cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -589,6 +589,9 @@ version = "0.10.4" default-features = false features = ["std"] +[workspace.dependencies.mime] +version = "0.3.18" + [workspace.dependencies.nonzero_ext] version = "0.3.0" diff --git a/src/service/Cargo.toml b/src/service/Cargo.toml index 41d1220fd..28c1f78a9 100644 --- a/src/service/Cargo.toml +++ b/src/service/Cargo.toml @@ -105,6 +105,7 @@ itertools.workspace = true log.workspace = true loole.workspace = true lru-cache.workspace = true +mime.workspace = true nonzero_ext.workspace = true p256.workspace = true regex.workspace = true diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index 9a5d60a50..f71f79ba2 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -7,16 +7,25 @@ use std::time::SystemTime; -use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt, info}; +use conduwuit::{Err, Result, debug, err, info, utils::response::LimitReadExt}; use ipaddress::IPAddress; -use lettre::message::header::ContentType; +use mime::Mime; use ruma::OwnedMxcUri; -use serde::Serialize; +use serde::{Serialize, Serializer}; use url::Url; use super::Service; use crate::media::mxc::Mxc; +// serde `serialize_with` passes `&Option` for `Option` fields. +#[allow(clippy::ref_option)] +fn serialize_mime(mime: &Option, serializer: S) -> Result { + match mime { + | Some(m) => serializer.serialize_str(m.as_ref()), + | None => serializer.serialize_none(), + } +} + #[derive(Serialize, Default, Debug)] pub struct UrlPreviewData { // From https://ogp.me/ @@ -50,8 +59,12 @@ pub struct UrlPreviewData { #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image"))] pub image: Option, /// A MIME type for this image. - #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:type"))] - pub image_type: Option, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "serialize_mime", + rename(serialize = "og:image:type") + )] + pub image_type: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:image:size"))] pub image_size: Option, /// The number of pixels wide. @@ -73,8 +86,12 @@ pub struct UrlPreviewData { pub video_width: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:height"))] pub video_height: Option, - #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:type"))] - pub video_type: Option, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "serialize_mime", + rename(serialize = "og:video:type") + )] + pub video_type: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:alt"))] pub video_alt: Option, /// A URL to an audio file to accompany this object. @@ -145,16 +162,18 @@ impl Service { ))); }; - let content_type = content_type + let content_type: Mime = content_type .to_str() + .map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))? + .parse() .map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))?; - let data = match content_type { - | html if html.starts_with("text/html") => self.download_html(url.as_str()).await?, - | img if img.starts_with("image/") => self.download_image(url.as_str()).await?, - | video if video.starts_with("video/") => self.download_video(url.as_str()).await?, - | audio if audio.starts_with("audio/") => self.download_audio(url.as_str()).await?, - | other => return Err!(Request(Unknown("Unsupported Content-Type: {other}"))), + let data = match (content_type.type_(), content_type.subtype()) { + | (mime::TEXT, mime::HTML) => self.download_html(url.as_str()).await?, + | (mime::IMAGE, _) => self.download_image(url.as_str()).await?, + | (mime::VIDEO, _) => self.download_video(url.as_str()).await?, + | (mime::AUDIO, _) => self.download_audio(url.as_str()).await?, + | _ => return Err!(Request(Unknown("Unsupported Content-Type: {content_type}"))), }; self.set_url_preview(url.as_str(), &data).await?; From def987f93558d3bef3875c056fed0cdcc8b510c0 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 11 Nov 2026 11:27:07 +0000 Subject: [PATCH 335/342] fix: Gate webpage usage and update disabled url_preview stubs --- src/service/media/preview.rs | 42 +++++++++++++++--------------------- 1 file changed, 17 insertions(+), 25 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index f71f79ba2..e2f0c0a72 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -7,7 +7,9 @@ use std::time::SystemTime; -use conduwuit::{Err, Result, debug, err, info, utils::response::LimitReadExt}; +#[cfg(feature = "url_preview")] +use conduwuit::info; +use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt}; use ipaddress::IPAddress; use mime::Mime; use ruma::OwnedMxcUri; @@ -291,30 +293,18 @@ impl Service { } #[cfg(not(feature = "url_preview"))] - pub async fn download_image( - &self, - _url: &str, - _preview_data: Option, - ) -> Result { - Err!(FeatureDisabled("url_preview")) + pub fn download_image(&self, _url: &str) -> impl Future> { + std::future::ready(Err!(FeatureDisabled("url_preview"))) } #[cfg(not(feature = "url_preview"))] - pub async fn download_video( - &self, - _url: &str, - _preview_data: Option, - ) -> Result { - Err!(FeatureDisabled("url_preview")) + pub fn download_video(&self, _url: &str) -> impl Future> { + std::future::ready(Err!(FeatureDisabled("url_preview"))) } #[cfg(not(feature = "url_preview"))] - pub async fn download_audio( - &self, - _url: &str, - _preview_data: Option, - ) -> Result { - Err!(FeatureDisabled("url_preview")) + pub fn download_audio(&self, _url: &str) -> impl Future> { + std::future::ready(Err!(FeatureDisabled("url_preview"))) } #[cfg(feature = "url_preview")] @@ -410,8 +400,9 @@ impl Service { } #[cfg(not(feature = "url_preview"))] - async fn download_html(&self, _url: &str) -> Result { - Err!(FeatureDisabled("url_preview")) + #[allow(clippy::unused_self)] + fn download_html(&self, _url: &str) -> impl Future> { + std::future::ready(Err!(FeatureDisabled("url_preview"))) } pub fn url_preview_allowed(&self, url: &Url) -> bool { @@ -537,6 +528,7 @@ impl Service { } } +#[cfg(feature = "url_preview")] impl From<&webpage::Opengraph> for UrlPreviewData { fn from(og: &webpage::Opengraph) -> Self { Self { @@ -589,12 +581,12 @@ impl From<&webpage::Opengraph> for UrlPreviewData { #[cfg(test)] mod tests { - use webpage::HTML; - - use super::UrlPreviewData; - + #[cfg(feature = "url_preview")] #[test] fn test_urlpreviewdata_parses_correctly() { + use webpage::HTML; + + use super::UrlPreviewData; let html = r#" From 635fccf11f658accce4bb591ad4c228995996d07 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 11 Nov 2026 11:29:27 +0000 Subject: [PATCH 336/342] fix: Populate image_size when downloading URL preview images --- src/service/media/preview.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index e2f0c0a72..486449099 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -217,8 +217,9 @@ impl Service { let (width, height) = reader.into_dimensions().map_err(|error| { err!(Request(Unknown("Failed to read preview image dimensions: {error}"))) })?; - preview_data.image_width.get_or_insert(width); - preview_data.image_height.get_or_insert(height); + preview_data.image_width = Some(width); + preview_data.image_height = Some(height); + preview_data.image_size = Some(image.len()); preview_data.image_type = content_type.parse().ok(); let mxc = Mxc { @@ -385,12 +386,14 @@ impl Service { preview_data.image_alt = None; preview_data.image_height = None; preview_data.image_width = None; + preview_data.image_size = None; } if preview_data.video.is_none() { preview_data.video_type = None; preview_data.video_alt = None; preview_data.video_height = None; preview_data.video_width = None; + preview_data.video_size = None; } if preview_data.audio.is_none() { preview_data.audio_size = None; From c6b87fb033718af162d9fa64476c889443ee9091 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 11 Nov 2026 11:31:59 +0000 Subject: [PATCH 337/342] fix: Check CIDR range and HTTP status when downloading preview media --- src/service/media/preview.rs | 66 ++++++++++++++++++++++++++---------- 1 file changed, 49 insertions(+), 17 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index 486449099..4d5dbb9b4 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -137,25 +137,19 @@ impl Service { } async fn request_url_preview(&self, url: &Url) -> Result { - if let Ok(ip) = IPAddress::parse(url.host_str().expect("URL previously validated")) { - if !self.services.client.valid_cidr_range(&ip) { - return Err!(Request(Forbidden("Requesting from this address is forbidden"))); - } - } + self.check_url_ip(url.as_str())?; let client = &self.services.client.url_preview; let response = client.head(url.as_str()).send().await?; debug!(%url, "URL preview response headers: {:?}", response.headers()); - if let Some(remote_addr) = response.remote_addr() { - debug!(%url, "URL preview response remote address: {:?}", remote_addr); - - if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) { - if !self.services.client.valid_cidr_range(&ip) { - return Err!(Request(Forbidden("Requesting from this address is forbidden"))); - } - } + self.check_response_ip(&response)?; + if !response.status().is_success() { + return Err!(Request(Unknown( + "URL preview request returned HTTP {}", + response.status() + ))); } let Some(content_type) = response.headers().get(reqwest::header::CONTENT_TYPE) else { @@ -192,7 +186,10 @@ impl Service { let mut preview_data = UrlPreviewData::default(); + self.check_url_ip(url)?; + let response = self.services.client.url_preview.get(url).send().await?; + self.check_response_ip(&response)?; if !response.status().is_success() { return Err!(Request(Unknown("Image download returned HTTP {}", response.status()))); } @@ -268,7 +265,13 @@ impl Service { use conduwuit::utils::random_string; use http::header::CONTENT_TYPE; + self.check_url_ip(url)?; + let response = self.services.client.url_preview.get(url).send().await?; + self.check_response_ip(&response)?; + if !response.status().is_success() { + return Err!(Request(Unknown("Media download returned HTTP {}", response.status()))); + } let content_type = response.headers().get(CONTENT_TYPE).cloned(); let media = response .limit_read( @@ -314,10 +317,12 @@ impl Service { use webpage::HTML; let client = &self.services.client.url_preview; - let body = client - .get(url) - .send() - .await? + let response = client.get(url).send().await?; + self.check_response_ip(&response)?; + if !response.status().is_success() { + return Err!(Request(Unknown("HTML download returned HTTP {}", response.status()))); + } + let body = response .limit_read_text( self.services .server @@ -408,6 +413,33 @@ impl Service { std::future::ready(Err!(FeatureDisabled("url_preview"))) } + fn check_url_ip(&self, url: &str) -> Result<()> { + let parsed = Url::parse(url) + .map_err(|e| err!(Request(InvalidParam("Requested URL is not valid: {e}"))))?; + let Some(host) = parsed.host_str() else { + return Err!(Request(InvalidParam("Requested URL does not have a host"))); + }; + if let Ok(ip) = IPAddress::parse(host) { + if !self.services.client.valid_cidr_range(&ip) { + return Err!(Request(Forbidden("Requesting from this address is forbidden"))); + } + } + Ok(()) + } + + fn check_response_ip(&self, response: &reqwest::Response) -> Result<()> { + if let Some(remote_addr) = response.remote_addr() { + debug!(url = %response.url(), "URL preview response remote address: {:?}", remote_addr); + + if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) { + if !self.services.client.valid_cidr_range(&ip) { + return Err!(Request(Forbidden("Requesting from this address is forbidden"))); + } + } + } + Ok(()) + } + pub fn url_preview_allowed(&self, url: &Url) -> bool { if ["http", "https"] .iter() From c0f69f23dd9d3a6ed6d71f33ececd0cb409875d7 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 11 Nov 2026 11:33:13 +0000 Subject: [PATCH 338/342] fix: Resolve relative OpenGraph asset URLs and avoid cloning HTML body --- src/service/media/preview.rs | 52 +++++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index 4d5dbb9b4..7cb6a2511 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -332,7 +332,7 @@ impl Service { .expect("u64 should fit in usize"), ) .await?; - let Ok(html) = HTML::from_string(body.clone(), Some(url.to_owned())) + let Ok(html) = HTML::from_string(body, Some(url.to_owned())) .inspect_err(|e| debug!(error=?e, "Failed to parse HTML data")) else { return Err!(Request(Unknown("Failed to parse HTML"))); @@ -341,10 +341,24 @@ impl Service { let mut preview_data = UrlPreviewData::from(&html.opengraph); debug!(parsed=?preview_data, deserialised=?html.opengraph, "Parsed opengraph data"); - if let Some(obj) = html.opengraph.images.first() { - info!(asset_url=%obj.url, "Downloading preview image"); - if let Ok(image_data) = self.download_image(&obj.url).await.inspect_err( - |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview image"), + let base_url = Url::parse(url).ok(); + let resolve_asset_url = |asset_url: &str| -> String { + base_url + .as_ref() + .and_then(|base| base.join(asset_url).ok()) + .map_or_else(|| asset_url.to_owned(), Into::into) + }; + + if let Some(obj) = html + .opengraph + .images + .first() + .filter(|obj| !obj.url.is_empty()) + { + let asset_url = resolve_asset_url(&obj.url); + info!(%asset_url, "Downloading preview image"); + if let Ok(image_data) = self.download_image(&asset_url).await.inspect_err( + |e| info!(error=?e, %asset_url, "Could not download URL preview image"), ) { preview_data.image = image_data.image; preview_data.image_size = image_data.image_size; @@ -356,20 +370,32 @@ impl Service { } } - if let Some(obj) = html.opengraph.videos.first() { - info!(asset_url=%obj.url, "Downloading preview video"); - if let Ok(video_data) = self.download_video(&obj.url).await.inspect_err( - |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview video"), + if let Some(obj) = html + .opengraph + .videos + .first() + .filter(|obj| !obj.url.is_empty()) + { + let asset_url = resolve_asset_url(&obj.url); + info!(%asset_url, "Downloading preview video"); + if let Ok(video_data) = self.download_video(&asset_url).await.inspect_err( + |e| info!(error=?e, %asset_url, "Could not download URL preview video"), ) { preview_data.video = video_data.video; preview_data.video_size = video_data.video_size; } } - if let Some(obj) = html.opengraph.audios.first() { - info!(asset_url=%obj.url, "Downloading URL preview audio"); - if let Ok(audio_data) = self.download_audio(&obj.url).await.inspect_err( - |e| info!(error=?e, asset_url=%obj.url, "Could not download URL preview audio"), + if let Some(obj) = html + .opengraph + .audios + .first() + .filter(|obj| !obj.url.is_empty()) + { + let asset_url = resolve_asset_url(&obj.url); + info!(%asset_url, "Downloading URL preview audio"); + if let Ok(audio_data) = self.download_audio(&asset_url).await.inspect_err( + |e| info!(error=?e, %asset_url, "Could not download URL preview audio"), ) { preview_data.audio = audio_data.audio; preview_data.audio_size = audio_data.audio_size; From 8c4a2d0ce93e4d55525e319fab0bb0e0a6e0ecc1 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 11 Nov 2026 11:34:40 +0000 Subject: [PATCH 339/342] chore: Downgrade per-request URL preview route logs to debug --- src/api/client/media.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/api/client/media.rs b/src/api/client/media.rs index 4f780cd99..a078bb968 100644 --- a/src/api/client/media.rs +++ b/src/api/client/media.rs @@ -2,7 +2,7 @@ use std::time::Duration; use axum::extract::State; use conduwuit::{ - Err, Result, err, info, + Err, Result, debug, err, utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize}, }; use conduwuit_core::error; @@ -219,15 +219,12 @@ pub(crate) async fn get_media_preview_route( ))); } - info!("Fetching a URL preview for {url} on behalf of {sender_user}"); + debug!("Fetching a URL preview for {url} on behalf of {sender_user}"); let preview = services .media .get_url_preview(&url) .await - .inspect(|_| info!(user=%sender_user, %url, "Finished fetching a URL preview")) - .inspect_err( - |e| info!(user=%sender_user, %url, error=?e, "Failed to fetch a URL preview"), - ) + .inspect(|_| debug!(user=%sender_user, %url, "Finished fetching a URL preview")) .map_err(|error| { err!(Request(Unknown( debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}") From 733c25ce5afec11982d67873117ad4a4e2b133ef Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Wed, 11 Nov 2026 11:37:10 +0000 Subject: [PATCH 340/342] chore: Update Cargo.lock --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index dc8e07eac..750117b4f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1127,6 +1127,7 @@ dependencies = [ "log", "loole", "lru-cache", + "mime", "nonzero_ext", "openidconnect", "opentelemetry", From 14739ffaf73b405e65503cd63a823f5ea9bbe74c Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sun, 22 Nov 2026 00:33:32 +0000 Subject: [PATCH 341/342] chore: Remove redundant Mxc import in download_image --- src/service/media/preview.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index 7cb6a2511..de649b709 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -182,8 +182,6 @@ impl Service { use conduwuit::utils::random_string; use image::ImageReader; - use crate::media::mxc::Mxc; - let mut preview_data = UrlPreviewData::default(); self.check_url_ip(url)?; From c82aba6f5a324ac008f7bb2088d99034baced702 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 23 Nov 2026 05:05:22 +0000 Subject: [PATCH 342/342] chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.257.9 --- .forgejo/workflows/renovate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/renovate.yml b/.forgejo/workflows/renovate.yml index b05933c09..b2ba0212b 100644 --- a/.forgejo/workflows/renovate.yml +++ b/.forgejo/workflows/renovate.yml @@ -43,7 +43,7 @@ jobs: name: Renovate runs-on: ubuntu-latest container: - image: ghcr.io/renovatebot/renovate:44.241.0@sha256:22d22b4ca7d768b5b469309d34379783bf91cd94a58faecf1cd0f4528a65d21c + image: ghcr.io/renovatebot/renovate:44.257.9@sha256:578179439fceea89646662dd583b27efdad8d1429e0cbd90681c40dde068589e options: --tmpfs /tmp:exec steps: - name: Checkout