Compare commits

..
Author SHA1 Message Date
timedout 9aacbf2650 feat: Start on PDU builders
ran out of creative juices so this doesn't work but i'll find a way later
2026-07-12 03:51:28 +01:00
timedout b1a3bcfb88 fix: Skip serialization in null fields
feat: Add fallible conversions from common JSON types
2026-07-12 00:25:26 +01:00
timedout 3c2274b9e7 feat: Create versioned PDU types 2026-07-12 00:07:52 +01:00
45 changed files with 1192 additions and 716 deletions

No files matched your search

-24
View File
@@ -1,27 +1,3 @@
# Continuwuity 26.6.2 (2026-07-12)
## Bugfixes
- Fixed the server returning 500 errors if `admin_console_automatic` is enabled and no TTY is available. Contributed by @s1lv3r. (#1975)
- Fixed `global.oauth.compatibility_mode` being required, despite being ignored, when the `[global.oauth.oidc]` config section is provided.
- Fixed an issue with a migration that could cause user accounts imported from an identity provider to be marked as deactivated when the server started. If you have accounts affected by this issue, use `!admin users reset-password --convert-to-local-account` to reactivate them.
# Continuwuity 26.6.1 (2026-07-12)
## Features
- Added enforcement for new federated invite checks and corrected a bunch of related spec compliance issues along the way. Contributed by @nex. (#1952)
## Bugfixes
- Fixed existing accounts failing to link when logging in with OIDC if `prompt_for_localpart` was `false`. (#1942)
- Authentication is no longer required on the `/_matrix/client/v3/account/3pid/email/requestToken` endpoint. (#1953)
- Fixed newly created rooms failing to sync properly in clients using legacy sync.
- Stopped appservice users from being erroneously marked as deactivated during a 26.6 database migration.
- Whitespace will now automatically be trimmed from the start and end of the `global.oauth.oidc.client_secret_file`.
# Continuwuity 26.6.0 (2026-07-10)
## Features
Generated
+14 -14
View File
@@ -826,7 +826,7 @@ dependencies = [
[[package]]
name = "conduwuit"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"aws-lc-rs",
"clap",
@@ -864,7 +864,7 @@ dependencies = [
[[package]]
name = "conduwuit_admin"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"assign",
"clap",
@@ -890,7 +890,7 @@ dependencies = [
[[package]]
name = "conduwuit_api"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"assign",
"async-trait",
@@ -928,7 +928,7 @@ dependencies = [
[[package]]
name = "conduwuit_build_metadata"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"built",
"cargo_metadata",
@@ -936,7 +936,7 @@ dependencies = [
[[package]]
name = "conduwuit_core"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"argon2",
"arrayvec",
@@ -1004,7 +1004,7 @@ dependencies = [
[[package]]
name = "conduwuit_database"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"async-channel",
"conduwuit_core",
@@ -1025,7 +1025,7 @@ dependencies = [
[[package]]
name = "conduwuit_macros"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"cargo_toml",
"itertools 0.15.0",
@@ -1036,7 +1036,7 @@ dependencies = [
[[package]]
name = "conduwuit_router"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"assign",
"axum",
@@ -1074,7 +1074,7 @@ dependencies = [
[[package]]
name = "conduwuit_service"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"askama",
"assign",
@@ -1126,7 +1126,7 @@ dependencies = [
[[package]]
name = "conduwuit_web"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"askama",
"assign",
@@ -4539,9 +4539,9 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7"
[[package]]
name = "resolvematrix"
version = "1.2.0"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a68b9735d8c1096d8152d4dfb5a705c0135dd14d181542fd87301f8d3cb4ed03"
checksum = "a574e37f06e219dcfdb14a4f0abf56e806c4551e030aae53802d2c42b29aea33"
dependencies = [
"futures",
"hickory-resolver",
@@ -4799,7 +4799,7 @@ dependencies = [
[[package]]
name = "ruminuwuity"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"assign",
"ruma",
@@ -6972,7 +6972,7 @@ dependencies = [
[[package]]
name = "xtask"
version = "26.6.2"
version = "26.6.0"
dependencies = [
"askama",
"cargo_metadata",
+8 -2
View File
@@ -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.6.2"
version = "26.6.0"
[workspace.metadata.crane]
name = "conduwuit"
@@ -141,6 +141,12 @@ features = [
version = "0.23.25"
default-features = false
[workspace.dependencies.aws-lc-sys]
version = "0.41.0"
[workspace.dependencies.aws-lc-rs]
version = "1.17.0"
[workspace.dependencies.reqwest]
version = "0.13.2"
default-features = false
@@ -564,7 +570,7 @@ features = ["std"]
version = "0.3.0"
[workspace.dependencies.resolvematrix]
version = "1.2.0"
version = "1.1.0"
[workspace.dependencies.serde_urlencoded]
version = "0.7.1"
+34
View File
@@ -0,0 +1,34 @@
# Roadmap for PDU versioning
Currently, PDUs are one monolithic `PduEvent` struct which applies a one-size-fits-all approach to PDUs, however as we
support a wide range of room versions, this only just about currently works, and will cause more and more problems as
time progresses. This branch will split the `PduEvent` struct into multiple versioned structs that represent the proper
format for appropriate room versions, and will drop the `Event` trait in favour of Ruma's `ruma::state_res::Event`
trait.
This will require a lot of work, and since I forget everything the moment I look out the window, here be a list (waow):
- [x] Split `PduEvent` into multiple versioned structs, implementing `ruma::state_res::Event` for each of them.
- [ ] Refactor out all references to `PduEvent`.
- [ ] Refactor out all references to `conduwuit_core::event::Event` trait in favour of `ruma::state_res::Event`.
- [ ] Centralise PDU struct creation in a way that allows us to greater control the deserialization process.
- Developers can't be trusted to read documentation so we can't store the PDU metadata (things like event ID and
rejection status) in the PDU struct itself, as this may end up being leaked to consumers. Instead, PDU metadata
should be stored seprately from the PDU struct itself, but needs to be strongly associated with it (i.e. fetched
at the same time, always returned together, etc). This may take a form similar to
`StoredPdu<T: Event> { pdu: T, metadata: PduMetadata }`.
- [ ] Stop storing generated data in the `unsigned` field, but instead calculate it on demand(?).
- Storing generated data in the `unsigned` field results in:
- History visibility cannot be enforced on `prev_content` or `redacted_because`.
- `age` is manually calculated but only sometimes.
- `membership` is not provided at all.
- `prev_content` can leak redacted state event content ([#1103]).
- `prev_content` cannot easily be populated for backfilled events, leaving them contextless.
- It is easy to accidentally leak `transaction_id`.
Once `PduEvent` is gone, we can then do the following lovely things:
- Drop our local state resolution logic and event authorisation logic and instead use Ruma's, which naturally receives
more love and attention. Our current `Event` trait and `PduEvent` implementations are incompatible with what Ruma
needs, and do not store the appropriate information required.
- There's something else but I forgot just trust me
+1
View File
@@ -0,0 +1 @@
Fixed newly created rooms failing to sync properly in clients using legacy sync.
+1
View File
@@ -0,0 +1 @@
Stopped appservice users from being erroneously marked as deactivated during a 26.6 database migration.
+1
View File
@@ -0,0 +1 @@
Fixed existing accounts failing to link when logging in with OIDC if `prompt_for_localpart` was `false`.
+1
View File
@@ -0,0 +1 @@
Authentication is no longer required on the `/_matrix/client/v3/account/3pid/email/requestToken` endpoint.
@@ -9,7 +9,7 @@
"id": 15,
"mention_room": true,
"date": "2026-07-10",
"message": "[Continuwuity 26.6.1](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v26.6.1) has just been released! This release contains a bunch of bugfixes for bugs found initially after 26.6.0's release - please read the changelog before updating!"
"message": "[Continuwuity 26.6.0](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v26.6.0) is finally out! This is by far our largest release yet, and it wouldn't have been possible without our community. Thank you so much for all of your patience, support, and/or development time over the last three months <3"
}
]
}
+3 -3
View File
@@ -486,7 +486,7 @@ impl crate::Context<'_> {
.services
.rooms
.event_handler
.parse_incoming_pdu(&response.pdu, None)
.parse_incoming_pdu(&response.pdu)
.boxed()
.await;
@@ -832,7 +832,7 @@ impl crate::Context<'_> {
.services
.rooms
.event_handler
.parse_incoming_pdu(&pdu, Some(&room_version_rules))
.parse_incoming_pdu(&pdu)
.await
{
| Ok(t) => t,
@@ -1014,7 +1014,7 @@ 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.default.clone())
.build()?
} else {
&self.services.client.matrix_resolver
+1 -1
View File
@@ -54,7 +54,7 @@ impl crate::Context<'_> {
let response = self
.services
.client
.external_resource
.default
.get(format!("https://{server_name}/.well-known/matrix/support"))
.send()
.await?;
+2 -3
View File
@@ -3,7 +3,7 @@ use axum_client_ip::ClientIp;
use conduwuit::{
Err, Result, debug_error, err, info,
matrix::{event::gen_event_id_canonical_json, pdu::PartialPdu},
trace, warn,
warn,
};
use futures::FutureExt;
use ruma::{
@@ -166,7 +166,7 @@ pub(crate) async fn invite_helper(
let invite_room_state = services
.rooms
.state
.summary_stripped(&pdu, room_id, recipient_user, true)
.summary_stripped(&pdu, room_id, recipient_user)
.await;
drop(state_lock);
@@ -193,7 +193,6 @@ pub(crate) async fn invite_helper(
.await
.ok();
trace!(?request, "Sending invite");
let response = services
.sending
.send_federation_request(recipient_user.server_name(), request)
+11 -4
View File
@@ -1,9 +1,11 @@
use std::collections::HashSet;
use assign::assign;
use axum::extract::State;
use conduwuit::{
Err, Pdu, Result, debug_info, debug_warn, err,
matrix::{event::gen_event_id, pdu::PartialPdu},
pdu::{AnyPDU, metadata::PduMetadata, new_pdu},
utils::{self, FutureBoolExt, future::ReadyEqExt},
warn,
};
@@ -216,7 +218,7 @@ pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
room_id: &RoomId,
reason: Option<String>,
mut servers: HashSet<OwnedServerName, S>,
) -> Result<Pdu> {
) -> Result<AnyPDU> {
let mut make_leave_response_and_server =
Err!(BadServerResponse("No remote server available to assist in leaving {room_id}."));
@@ -406,9 +408,14 @@ pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
.outlier
.add_pdu_outlier(&event_id, &leave_event);
let leave_pdu = Pdu::from_id_val(&event_id, leave_event).map_err(|e| {
err!(BadServerResponse("Invalid leave PDU received during federated leave: {e:?}"))
})?;
let leave_pdu = new_pdu(
room_version_rules.into(),
PduMetadata::new(event_id),
serde_json::to_value(leave_event)?,
)?;
// let leave_pdu = Pdu::from_id_val(&event_id, leave_event).map_err(|e| {
// err!(BadServerResponse("Invalid leave PDU received during federated leave:
// {e:?}")) })?;
Ok(leave_pdu)
}
+116 -300
View File
@@ -1,29 +1,23 @@
use std::collections::{HashMap, hash_map::Entry};
use axum::extract::State;
use axum_client_ip::ClientIp;
use base64::{Engine as _, engine::general_purpose};
use conduwuit::{
Err, Error, EventTypeExt, PduEvent, Result, debug, err, error,
matrix::{Event, StateKey},
result::FlatOk,
state_res, trace,
utils::hash::sha256,
Err, Error, PduEvent, Result, err, error,
matrix::{Event, event::gen_event_id},
utils::{self, hash::sha256},
warn,
};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedUserId, ServerName,
UserId,
CanonicalJsonValue, UserId,
api::{
error::{ErrorKind, IncompatibleRoomVersionErrorData},
federation::membership::{RawStrippedState, create_invite},
},
events::{StateEventType, room::member::MembershipState},
room_version_rules::RoomVersionRules,
events::room::member::{MembershipState, RoomMemberEventContent},
serde::JsonObject,
};
use serde::Deserialize;
use crate::{Ruma, server::utils::validate_any_membership_event};
use crate::Ruma;
/// # `PUT /_matrix/federation/v2/invite/{roomId}/{eventId}`
///
@@ -34,16 +28,30 @@ pub(crate) async fn create_invite_route(
ClientIp(client): ClientIp,
body: Ruma<create_invite::v2::Request>,
) -> Result<create_invite::v2::Response> {
// ACL check origin
services
.rooms
.event_handler
.acl_check(&body.identity, &body.room_id)
.await?;
if !services.server.supported_room_version(&body.room_version) {
return Err(Error::BadRequest(
ErrorKind::IncompatibleRoomVersion(IncompatibleRoomVersionErrorData::new(
body.room_version.clone(),
)),
"This server does not support that room version",
"Server does not support this room version.",
));
}
let room_version_rules = body.room_version.rules().unwrap();
if let Some(server) = body.room_id.server_name() {
if services.moderation.is_remote_server_forbidden(server) {
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}
}
if services
.moderation
.is_remote_server_forbidden(&body.identity)
@@ -53,61 +61,90 @@ pub(crate) async fn create_invite_route(
body.identity, body.room_id
);
return Err!(Request(Forbidden("Federation denied with {}", body.identity)));
}
// First, validate the invite room state, so we can compare with the create
// event.
debug!(
event_id=%body.event_id,
room_id=%body.room_id,
room_version=?body.room_version,
via=?body.via,
"Validating invite room state for invite request"
);
let (create_event_id, state) = validate_invite_state(
&services,
&body.invite_room_state,
&room_version_rules,
body.room_id.clone(),
)
.await?;
let create_event_json = state
.get(&StateEventType::RoomCreate.with_state_key(""))
.expect("must have create event in invite state by this point");
// We can now perform the banned remote server check with the create event.
// N.B. this checks the sender field, which is technically incorrect for rooms
// v10 and below. This usually isn't the case though so sue me
let creator = create_event_json
.get("sender")
.and_then(|v| v.as_str())
.map(UserId::parse)
.flat_ok()
.expect("must have valid sender in create event");
if services
.moderation
.is_remote_server_forbidden(creator.server_name())
{
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}
// And then we can validate the member event itself
let (mut signed_event, sender_user, recipient_user) = validate_invite_membership_event(
&services,
&body.event,
&room_version_rules,
&body.identity,
create_event_id.clone(),
body.room_id.clone(),
body.event_id.clone(),
let mut signed_event = utils::to_canonical_object(&body.event)
.map_err(|_| err!(Request(InvalidParam("Invite event is invalid."))))?;
// Ensure this is a membership event
if signed_event
.get("type")
.expect("event must have a type")
.as_str()
.expect("type must be a string")
!= "m.room.member"
{
return Err!(Request(BadJson(
"Not allowed to send non-membership event to invite endpoint."
)));
}
let content: RoomMemberEventContent = serde_json::from_value(
signed_event
.get("content")
.ok_or_else(|| err!(Request(BadJson("Event missing content property"))))?
.clone()
.into(),
)
.await?;
.map_err(|e| err!(Request(BadJson(warn!("Event content is empty or invalid: {e}")))))?;
// Ensure this is an invite membership event
if content.membership != MembershipState::Invite {
return Err!(Request(BadJson(
"Not allowed to send a non-invite membership event to invite endpoint."
)));
}
// Ensure the sending user isn't a lying bozo
let sender_user = signed_event
.get("sender")
.and_then(|v| v.as_str())
.map(UserId::parse)
.and_then(Result::ok)
.ok_or_else(|| err!(Request(InvalidParam("Invalid sender property"))))?;
if sender_user.server_name() != body.identity {
return Err!(Request(Forbidden("Sender's server does not match the origin server.",)));
}
// Ensure the target user belongs to this server
let recipient_user = signed_event
.get("state_key")
.and_then(|v| v.as_str())
.map(UserId::parse)
.and_then(Result::ok)
.ok_or_else(|| err!(Request(InvalidParam("Invalid state_key property"))))?;
if !services
.globals
.server_is_ours(recipient_user.server_name())
{
return Err!(Request(InvalidParam("User does not belong to this homeserver.")));
}
// Make sure we're not ACL'ed from their room.
services
.rooms
.event_handler
.acl_check(recipient_user.server_name(), &body.room_id)
.await?;
services
.server_keys
.hash_and_sign_event(&mut signed_event, &room_version_rules)
.map_err(|e| err!(Request(InvalidParam("Failed to sign event: {e}"))))?;
// Generate event id
let event_id = gen_event_id(&signed_event, &room_version_rules)?;
// Add event_id back
signed_event.insert("event_id".to_owned(), CanonicalJsonValue::String(event_id.to_string()));
if services.rooms.metadata.is_banned(&body.room_id).await
&& !services.users.is_admin(&recipient_user).await
{
return Err!(Request(Forbidden("That room is banned on this homeserver.")));
return Err!(Request(Forbidden("This room is banned on this homeserver.")));
}
if services.config.block_non_admin_invites && !services.users.is_admin(&recipient_user).await
@@ -124,57 +161,30 @@ pub(crate) async fn create_invite_route(
return Err!(Request(Forbidden("Invite rejected by antispam service.")));
}
// If we're already in the room, ensure that neither the origin nor ourselves
// are ACL'd.
let resident = services
.rooms
.state_cache
.server_in_room(services.globals.server_name(), &body.room_id)
.await;
if resident {
services
.rooms
.event_handler
.acl_check(&body.identity, &body.room_id)
.await?;
services
.rooms
.event_handler
.acl_check(recipient_user.server_name(), &body.room_id)
.await
.map_err(|_| err!(Request(Forbidden("This server is ACL'd from that room"))))?;
}
services
.server_keys
.hash_and_sign_event(&mut signed_event, &room_version_rules)
.map_err(|e| err!(Request(InvalidParam("Failed to sign event: {e}"))))?;
// Add event_id back
signed_event
.insert("event_id".to_owned(), CanonicalJsonValue::String(body.event_id.to_string()));
let mut invite_state = body.invite_room_state.clone();
let pdu = PduEvent::from_id_val(&body.event_id, signed_event.clone())
.expect("must be able to create PDU object");
invite_state.push(RawStrippedState::Pdu(serde_json::value::to_raw_value(&signed_event)?));
let mut event: JsonObject = serde_json::from_str(body.event.get())
.map_err(|e| err!(Request(BadJson("Invalid invite event PDU: {e}"))))?;
event.insert("event_id".to_owned(), "$placeholder".into());
let pdu: PduEvent = serde_json::from_value(event.into())
.map_err(|e| err!(Request(BadJson("Invalid invite event PDU: {e}"))))?;
invite_state.push(RawStrippedState::Pdu(
serde_json::value::to_raw_value(&pdu).expect("PDU was just created, it must be valid"),
));
// If we are active in the room, the remote server will notify us about the
// join/invite through /send. If we are not in the room, we need to manually
// record the invited state for client /sync through update_membership(), and
// send the invite PDU to the relevant appservices.
if !resident {
// We will start by recording the room's create event as an outlier.
// This will allow us to recognise it later in case the sender revokes the
// invite over federation later. We could store more state from the invite
// request, but we will get that during send_join anyway.
// This is safe to just add directly as an outlier as we already auth checked it
// during validation.
services
.rooms
.outlier
.add_pdu_outlier(&create_event_id, create_event_json);
if !services
.rooms
.state_cache
.server_in_room(services.globals.server_name(), &body.room_id)
.await
{
services
.rooms
.state_cache
@@ -230,197 +240,3 @@ pub(crate) async fn create_invite_route(
.await,
))
}
/// Validates the *membership event* in the invite request, per the steps listed
/// under the invite endpoint's [spec].
///
/// Returns the validated JSON body, sender user ID, and recipient user ID.
///
/// Since this function performs a PDU format check, the create event must be
/// known ahead of time. This implies validating the invite state before the
/// invite event itself.
///
/// [spec]: https://spec.matrix.org/v1.19/server-server-api/#put_matrixfederationv2inviteroomideventid
async fn validate_invite_membership_event(
services: &crate::State,
body: &serde_json::value::RawValue,
room_version_rules: &RoomVersionRules,
origin: &ServerName,
create_event_id: OwnedEventId,
room_id: OwnedRoomId,
event_id: OwnedEventId,
) -> Result<(CanonicalJsonObject, OwnedUserId, OwnedUserId)> {
trace!(?body, "Invite membership event");
let (pdu, target_membership, sender_user, recipient_user) = validate_any_membership_event(
services,
body,
room_version_rules,
create_event_id,
room_id,
event_id,
)
.await?;
// Ensure the sender belongs to the remote that is sending the invite
if sender_user.server_name() != origin {
return Err!(Request(Forbidden("Sender belongs to a different server")));
}
// Ensure the target user belongs to this server
if !services
.globals
.server_is_ours(recipient_user.server_name())
{
return Err!(Request(InvalidParam("Recipient does not belong to this homeserver")));
}
if target_membership != MembershipState::Invite {
return Err!(Request(BadJson("Invalid membership (expected `invite`)")));
}
Ok((pdu, sender_user, recipient_user))
}
/// Validates the *invite state* of an invite request, per the steps listed
/// under the endpoint's [spec].
///
/// Returns the create event's event ID, and the partial state map.
///
/// [spec]: https://spec.matrix.org/v1.19/server-server-api/#put_matrixfederationv2inviteroomideventid
async fn validate_invite_state(
services: &crate::State,
invite_state: &[RawStrippedState],
room_version_rules: &RoomVersionRules,
room_id: OwnedRoomId,
) -> Result<(OwnedEventId, HashMap<(StateEventType, StateKey), CanonicalJsonObject>)> {
trace!(?invite_state, "Raw invite state");
let mut invite_state_map: HashMap<(StateEventType, StateKey), _> =
HashMap::with_capacity(invite_state.len());
let mut create_event_id: Option<OwnedEventId> = None;
for (idx, invite_state_event) in invite_state.iter().cloned().enumerate() {
trace!(%idx, ?invite_state_event, "Invite state event");
// Stripped state hasn't been sent over federation since v1.16.
let RawStrippedState::Pdu(raw_pdu) = invite_state_event else {
debug!(%idx, "Invite state event is not a PDU");
return Err!(Request(InvalidParam(
"PDU in invite state (index {idx}) violates the room event format"
)));
};
let (state_event_room_id, state_event_id, state_event_json) = services
.rooms
.event_handler
.parse_incoming_pdu(&raw_pdu, Some(room_version_rules))
.await
.map_err(|e| {
err!(Request(InvalidParam(debug_warn!("Invalid PDU in invite state: {e}"))))
})?;
if state_event_room_id != room_id {
return Err!(Request(InvalidParam(debug_warn!(
%state_event_room_id,
%room_id,
"PDU in invite state ({state_event_id}) belongs to the wrong room"
))));
}
services
.server_keys
.verify_event(&state_event_json, room_version_rules)
.await
.map_err(|e| {
err!(Request(InvalidParam("Signature verification failed on invite event: {e}")))
})?;
let Some(state_key) = state_event_json.get("state_key").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_info!(
"PDU in invite state ({state_event_id}) is not a state event"
))));
};
let Some(event_type) = state_event_json.get("type").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_warn!(
"PDU in invite state ({state_event_id}) is not an event?"
))));
};
let key = StateEventType::from(event_type).with_state_key(state_key);
match invite_state_map.entry(key) {
| Entry::Occupied(entry) =>
return Err!(Request(InvalidParam(
"Duplicate state events in invite state for state key: {:?}",
entry.key(),
))),
| Entry::Vacant(entry) => {
if entry.key().0 == StateEventType::RoomCreate {
// Ensure this is a legal create event.
let pdu_event =
PduEvent::from_id_val(&state_event_id, state_event_json.clone())
.expect("must be able to create pdu event from event json");
debug!("Validating discovered create event in invite room state");
validate_invite_create_event(&pdu_event, room_version_rules).await?;
create_event_id = Some(state_event_id);
}
entry.insert(state_event_json);
},
}
}
let Some(create_event_id) = create_event_id else {
return Err!(Request(InvalidParam(debug_warn!(
parsed_state=?invite_state_map,
"Invite state does not contain the m.room.create event"
))));
};
invite_state_map.iter().try_for_each(|(key, event_json)| {
service::rooms::event_handler::Service::pdu_format_check_1(
event_json,
room_version_rules,
&create_event_id,
)
.map_err(|e| {
err!(Request(InvalidParam(
"PDU in invite state for {key:?} violates the room event format: {e}"
)))
})
})?;
Ok((create_event_id, invite_state_map))
}
#[derive(Deserialize)]
struct MFederate {
#[serde(rename = "m.federate")]
mfederate: Option<bool>,
}
/// Validates that a create event is suitable for the invite, namely:
///
/// 1. It passes auth checks (aka is valid)
/// 2. The room is federated (there's no point persisting unfederated rooms)
async fn validate_invite_create_event(
pdu: &PduEvent,
room_version_rules: &RoomVersionRules,
) -> Result {
if !state_res::auth_check(
room_version_rules,
pdu,
None,
|_, _| async {
unreachable!("No state should be fetched when processing a lone create event");
},
pdu,
)
.await
.unwrap_or_default()
{
return Err!(Request(InvalidParam("m.room.create event fails auth check")));
}
let can_federate = pdu.get_content::<MFederate>()?.mfederate;
if !can_federate.unwrap_or(true) {
return Err!(Request(InvalidParam(
"Cannot receive invites to a room with m.federate=false"
)));
}
Ok(())
}
+8
View File
@@ -75,6 +75,14 @@ pub(crate) async fn create_join_event_template_route(
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}
if let Some(server) = body.room_id.server_name() {
if services.moderation.is_remote_server_forbidden(server) {
return Err!(Request(Forbidden(warn!(
"Room ID server name {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) {
+6
View File
@@ -58,6 +58,12 @@ pub(crate) async fn create_knock_event_template_route(
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}
if let Some(server) = body.room_id.server_name() {
if services.moderation.is_remote_server_forbidden(server) {
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();
-1
View File
@@ -27,7 +27,6 @@ pub(crate) async fn create_leave_event_template_route(
{
info!(
origin = body.identity.as_str(),
room_id = %body.room_id,
"Refusing to serve make_leave for room we aren't participating in"
);
return Err!(Request(NotFound("This server is not participating in that room.")));
+1 -1
View File
@@ -150,7 +150,7 @@ async fn process_inbound_transaction(
.pdus
.iter()
.stream()
.broad_then(|pdu| services.rooms.event_handler.parse_incoming_pdu(pdu, None))
.broad_then(|pdu| services.rooms.event_handler.parse_incoming_pdu(pdu))
.inspect_err(|e| warn!("Could not parse incoming PDU: {e}"))
.ready_filter_map(Result::ok);
+115 -67
View File
@@ -2,36 +2,34 @@ use std::{borrow::Borrow, time::Instant, vec};
use axum::extract::State;
use conduwuit::{
Err, Event, Result, at, debug, err, info, trace,
Err, Event, Result, at, debug, err, info,
matrix::event::gen_event_id_canonical_json,
trace,
utils::stream::{BroadbandExt, IterStream, TryBroadbandExt},
warn,
};
use conduwuit_service::Services;
use futures::{FutureExt, StreamExt, TryStreamExt};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, RoomId, ServerName, UserId,
CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, ServerName,
api::federation::membership::create_join_event,
assign,
events::{
TimelineEventType,
StateEventType, TimelineEventType,
room::member::{MembershipState, RoomMemberEventContent},
},
room_version_rules::RoomVersionRules,
};
use serde_json::value::to_raw_value;
use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
use crate::{Ruma, server::utils::validate_any_membership_event};
use crate::Ruma;
/// Creates a join membership event for the target, returning a computed
/// response with room state, auth chains, etc.
/// helper method for /send_join v1 and v2
#[tracing::instrument(skip(services, pdu, omit_members), fields(room_id = room_id.as_str(), origin = origin.as_str()), level = "info")]
async fn create_join_event(
services: &Services,
origin: &ServerName,
room_id: &RoomId,
event_id: &EventId,
room_version_rules: &RoomVersionRules,
mut pdu: CanonicalJsonObject,
pdu: &RawJsonValue,
omit_members: bool,
) -> Result<create_join_event::v2::RoomState> {
if !services.rooms.metadata.exists(room_id).await {
@@ -45,7 +43,6 @@ async fn create_join_event(
{
info!(
origin = origin.as_str(),
room_id = %room_id,
"Refusing to serve send_join for room we aren't participating in"
);
return Err!(Request(NotFound("This server is not participating in that room.")));
@@ -67,25 +64,94 @@ async fn create_join_event(
.await
.map_err(|e| err!(Request(NotFound(error!("Room has no state: {e}")))))?;
let sender = pdu
.get("sender")
.and_then(|v| v.as_str())
.map(UserId::parse)
.and_then(Result::ok)
.expect("sender was already validated");
// We do not add the event_id field to the pdu here because of signature and
// hashes checks
trace!("Getting room version");
let room_version = services.rooms.state.get_room_version(room_id).await?;
let room_version_rules = room_version.rules().unwrap();
trace!("Generating event ID and converting to canonical json");
let Ok((event_id, mut value)) = gen_event_id_canonical_json(pdu, &room_version_rules) else {
// Event could not be converted to canonical json
return Err!(Request(BadJson("Could not convert event to canonical json.")));
};
let event_room_id: OwnedRoomId = serde_json::from_value(
value
.get("room_id")
.ok_or_else(|| err!(Request(BadJson("Event missing room_id property."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("room_id field is not a valid room ID: {e}")))))?;
if event_room_id != room_id {
return Err!(Request(BadJson("Event room_id does not match request path room ID.")));
}
let event_type: StateEventType = serde_json::from_value(
value
.get("type")
.ok_or_else(|| err!(Request(BadJson("Event missing type property."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("Event has invalid state event type: {e}")))))?;
if event_type != StateEventType::RoomMember {
return Err!(Request(BadJson(
"Not allowed to send non-membership state event to join endpoint."
)));
}
let content: RoomMemberEventContent = serde_json::from_value(
pdu.get("content")
value
.get("content")
.ok_or_else(|| err!(Request(BadJson("Event missing content property"))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("Event content is empty or invalid: {e}")))))?;
if content.membership != MembershipState::Join {
return Err!(Request(BadJson(
"Not allowed to send a non-join membership event to join endpoint."
)));
}
let sender: OwnedUserId = serde_json::from_value(
value
.get("sender")
.ok_or_else(|| err!(Request(BadJson("Event missing sender property."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("sender property is not a valid user ID: {e}")))))?;
// check if origin server is trying to send for another server
if sender.server_name() != origin {
return Err!(Request(Forbidden("Not allowed to join on behalf of another server.")));
}
let state_key: OwnedUserId = serde_json::from_value(
value
.get("state_key")
.ok_or_else(|| err!(Request(BadJson("Event missing state_key property."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("State key is not a valid user ID: {e}")))))?;
if state_key != sender {
return Err!(Request(BadJson("State key does not match sender user.")));
}
if let Some(authorising_user) = content.join_authorized_via_users_server {
if !room_version_rules.authorization.restricted_join_rule {
use ruma::RoomVersionId::*;
if matches!(room_version, V1 | V2 | V3 | V4 | V5 | V6 | V7) {
return Err!(Request(InvalidParam(
"Room version does not support restricted rooms but \
"Room version {room_version} does not support restricted rooms but \
join_authorised_via_users_server ({authorising_user}) was found in the event."
)));
}
@@ -108,7 +174,8 @@ async fn create_join_event(
they cannot authorise your join."
)));
}
if !super::user_can_perform_restricted_join(services, &sender, room_id).await? {
if !super::user_can_perform_restricted_join(services, &state_key, room_id).await? {
return Err!(Request(UnableToAuthorizeJoin(
"Joining user did not pass restricted room's rules."
)));
@@ -116,7 +183,7 @@ async fn create_join_event(
services
.server_keys
.hash_and_sign_event(&mut pdu, room_version_rules)
.hash_and_sign_event(&mut value, &room_version_rules)
.map_err(|e| {
err!(Request(InvalidParam(warn!("Failed to sign send_join event: {e}"))))
})?;
@@ -133,7 +200,7 @@ async fn create_join_event(
let pdu_id = services
.rooms
.event_handler
.handle_incoming_pdu(sender.server_name(), room_id, event_id, pdu.clone(), false)
.handle_incoming_pdu(sender.server_name(), room_id, &event_id, value.clone(), false)
.boxed()
.await?
.ok_or_else(|| err!(Request(InvalidParam("Could not accept as timeline event."))))?;
@@ -153,12 +220,14 @@ async fn create_join_event(
.iter()
.try_stream()
.broad_filter_map(|event_id| async move {
if omit_members && let Ok(e) = event_id.as_ref() {
let pdu = services.rooms.timeline.get_pdu(e).await;
if pdu.is_ok_and(|p| *p.kind() == TimelineEventType::RoomMember) {
trace!("omitting member event {e:?} from returned state");
// skip members
return None;
if omit_members {
if let Ok(e) = event_id.as_ref() {
let pdu = services.rooms.timeline.get_pdu(e).await;
if pdu.is_ok_and(|p| *p.kind() == TimelineEventType::RoomMember) {
trace!("omitting member event {e:?} from returned state");
// skip members
return None;
}
}
}
Some(event_id)
@@ -220,7 +289,7 @@ async fn create_join_event(
Ok(assign!(create_join_event::v2::RoomState::new(), {
auth_chain,
state,
event: to_raw_value(&CanonicalJsonValue::Object(pdu)).ok(),
event: to_raw_value(&CanonicalJsonValue::Object(value)).ok(),
members_omitted: omit_members,
servers_in_room,
}))
@@ -240,45 +309,24 @@ pub(crate) async fn create_join_event_v2_route(
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
let create_event = services
.rooms
.state_accessor
.get_room_create_event(&body.room_id)
.await;
let room_version_rules = room_version.rules().unwrap();
let (value, membership, sender, target) = validate_any_membership_event(
&services,
&body.pdu,
&room_version_rules,
create_event.event_id.clone(),
body.room_id.clone(),
body.event_id.clone(),
)
.await?;
if membership != MembershipState::Join {
return Err!(Request(InvalidParam("Invalid membership (expected `join`)")));
}
if sender.server_name() != body.identity {
return Err!(Request(InvalidParam("Sender belongs to a different server")));
}
if sender != target {
return Err!(Request(InvalidParam("Sender does not match state key")));
if let Some(server) = body.room_id.server_name() {
if services.moderation.is_remote_server_forbidden(server) {
warn!(
"Server {} tried joining room ID {} through us which has a server name that is \
globally forbidden. Rejecting.",
body.identity, &body.room_id,
);
return Err!(Request(Forbidden(warn!(
"Room ID server name {server} is banned on this homeserver."
))));
}
}
let now = Instant::now();
let room_state = create_join_event(
&services,
&body.identity,
&body.room_id,
&body.event_id,
&room_version_rules,
value,
body.omit_members,
)
.boxed()
.await?;
let room_state =
create_join_event(&services, &body.identity, &body.room_id, &body.pdu, body.omit_members)
.boxed()
.await?;
info!(
"Finished sending a join for {} in {} in {:?}",
body.identity,
+97 -29
View File
@@ -1,11 +1,21 @@
use axum::extract::State;
use conduwuit::{Err, Event, Result, debug_info, err, matrix::pdu::PduEvent, warn};
use conduwuit::{
Err, Result, err, info,
matrix::{event::gen_event_id_canonical_json, pdu::PduEvent},
warn,
};
use futures::FutureExt;
use ruma::{
api::federation::membership::create_knock_event, events::room::member::MembershipState,
OwnedUserId,
api::federation::membership::create_knock_event,
events::{
StateEventType,
room::member::{MembershipState, RoomMemberEventContent},
},
serde::JsonObject,
};
use crate::{Ruma, server::utils::validate_any_membership_event};
use crate::Ruma;
/// # `PUT /_matrix/federation/v1/send_knock/{roomId}/{eventId}`
///
@@ -23,7 +33,18 @@ pub(crate) async fn create_knock_event_v1_route(
forbidden. Rejecting.",
body.identity, &body.room_id,
);
return Err!(Request(Forbidden("Federation denied with {}", body.identity)));
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}
if let Some(server) = body.room_id.server_name() {
if services.moderation.is_remote_server_forbidden(server) {
warn!(
"Server {} tried knocking room ID {} which has a server name that is globally \
forbidden. Rejecting.",
body.identity, &body.room_id,
);
return Err!(Request(Forbidden("Server is banned on this homeserver.")));
}
}
if !services.rooms.metadata.exists(&body.room_id).await {
@@ -36,9 +57,8 @@ pub(crate) async fn create_knock_event_v1_route(
.server_in_room(services.globals.server_name(), &body.room_id)
.await
{
debug_info!(
info!(
origin = body.identity.as_str(),
room_id = %body.room_id,
"Refusing to serve send_knock for room we aren't participating in"
);
return Err!(Request(NotFound("This server is not participating in that room.")));
@@ -52,40 +72,88 @@ pub(crate) async fn create_knock_event_v1_route(
.await?;
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
let create_event = services
.rooms
.state_accessor
.get_room_create_event(&body.room_id)
.await;
let room_version_rules = room_version.rules().unwrap();
if !room_version_rules.authorization.knocking {
return Err!(Request(Forbidden("Room version does not support knocking.")));
}
let (mut event, target_membership, sender, target) = validate_any_membership_event(
&services,
&body.pdu,
&room_version_rules,
create_event.event_id().to_owned(),
body.room_id.clone(),
body.event_id.clone(),
let Ok((event_id, value)) = gen_event_id_canonical_json(&body.pdu, &room_version_rules)
else {
// Event could not be converted to canonical json
return Err!(Request(InvalidParam("Could not convert event to canonical json.")));
};
let event_type: StateEventType = serde_json::from_value(
value
.get("type")
.ok_or_else(|| err!(Request(InvalidParam("Event has no event type."))))?
.clone()
.into(),
)
.await?;
.map_err(|e| err!(Request(InvalidParam("Event has invalid event type: {e}"))))?;
if target_membership != MembershipState::Knock {
return Err!(Request(InvalidParam("Invalid membership (expected `knock`)")));
if event_type != StateEventType::RoomMember {
return Err!(Request(InvalidParam(
"Not allowed to send non-membership state event to knock endpoint.",
)));
}
let content: RoomMemberEventContent = serde_json::from_value(
value
.get("content")
.ok_or_else(|| err!(Request(InvalidParam("Membership event has no content"))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(InvalidParam("Event has invalid membership content: {e}"))))?;
if content.membership != MembershipState::Knock {
return Err!(Request(InvalidParam(
"Not allowed to send a non-knock membership event to knock endpoint."
)));
}
// ACL check sender server name
let sender: OwnedUserId = serde_json::from_value(
value
.get("sender")
.ok_or_else(|| err!(Request(InvalidParam("Event has no sender user ID."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson("Event sender is not a valid user ID: {e}"))))?;
services
.rooms
.event_handler
.acl_check(sender.server_name(), &body.room_id)
.await?;
// check if origin server is trying to send for another server
if sender.server_name() != body.identity {
return Err!(Request(InvalidParam("Sender belongs to a different server")));
}
if sender != target {
return Err!(Request(InvalidParam("Sender does not match state key")));
return Err!(Request(BadJson("Not allowed to knock on behalf of another server/user.")));
}
event.insert("event_id".to_owned(), body.event_id.as_str().into());
let state_key: OwnedUserId = serde_json::from_value(
value
.get("state_key")
.ok_or_else(|| err!(Request(InvalidParam("Event does not have a state_key"))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson("Event does not have a valid state_key: {e}"))))?;
let pdu = PduEvent::from_id_val(&body.event_id, event.clone())
if state_key != sender {
return Err!(Request(InvalidParam("state_key does not match sender user of event.")));
}
let mut event: JsonObject = serde_json::from_str(body.pdu.get())
.map_err(|e| err!(Request(InvalidParam("Invalid knock event PDU: {e}"))))?;
event.insert("event_id".to_owned(), "$placeholder".into());
let pdu: PduEvent = serde_json::from_value(event.into())
.map_err(|e| err!(Request(InvalidParam("Invalid knock event PDU: {e}"))))?;
let mutex_lock = services
@@ -98,7 +166,7 @@ pub(crate) async fn create_knock_event_v1_route(
let pdu_id = services
.rooms
.event_handler
.handle_incoming_pdu(sender.server_name(), &body.room_id, &body.event_id, event, false)
.handle_incoming_pdu(sender.server_name(), &body.room_id, &event_id, value.clone(), false)
.boxed()
.await?
.ok_or_else(|| err!(Request(InvalidParam("Could not accept as timeline event."))))?;
@@ -113,7 +181,7 @@ pub(crate) async fn create_knock_event_v1_route(
let knock_room_state = services
.rooms
.state
.summary_stripped(&pdu, &body.room_id, &sender, true)
.summary_stripped(&pdu, &body.room_id, &sender)
.await;
Ok(create_knock_event::v1::Response::new(knock_room_state))
+104 -31
View File
@@ -1,11 +1,18 @@
use axum::extract::State;
use conduwuit::{Err, Result, debug_info, err};
use conduwuit::{Err, Result, err, info, matrix::event::gen_event_id_canonical_json};
use conduwuit_service::Services;
use futures::FutureExt;
use ruma::{
api::federation::membership::create_leave_event, events::room::member::MembershipState,
OwnedRoomId, OwnedUserId, RoomId, ServerName,
api::federation::membership::create_leave_event,
events::{
StateEventType,
room::member::{MembershipState, RoomMemberEventContent},
},
};
use serde_json::value::RawValue as RawJsonValue;
use crate::{Ruma, server::utils::validate_any_membership_event};
use crate::Ruma;
/// # `PUT /_matrix/federation/v2/send_leave/{roomId}/{eventId}`
///
@@ -14,8 +21,17 @@ pub(crate) async fn create_leave_event_v2_route(
State(services): State<crate::State>,
body: Ruma<create_leave_event::v2::Request>,
) -> Result<create_leave_event::v2::Response> {
let room_id = body.room_id.as_ref();
let origin = &body.identity;
create_leave_event(&services, &body.identity, &body.room_id, &body.pdu).await?;
Ok(create_leave_event::v2::Response::new())
}
async fn create_leave_event(
services: &Services,
origin: &ServerName,
room_id: &RoomId,
pdu: &RawJsonValue,
) -> Result {
if !services.rooms.metadata.exists(room_id).await {
return Err!(Request(NotFound("Room is unknown to this server.")));
}
@@ -26,10 +42,9 @@ pub(crate) async fn create_leave_event_v2_route(
.server_in_room(services.globals.server_name(), room_id)
.await
{
debug_info!(
info!(
origin = origin.as_str(),
room_id = %room_id,
"Refusing to send_leave for room we aren't participating in"
"Refusing to serve backfill for room we aren't participating in"
);
return Err!(Request(NotFound("This server is not participating in that room.")));
}
@@ -41,31 +56,91 @@ pub(crate) async fn create_leave_event_v2_route(
.acl_check(origin, room_id)
.await?;
// We do not add the event_id field to the pdu here because of signature and
// hashes checks
let room_version = services.rooms.state.get_room_version(room_id).await?;
let create_event = services
.rooms
.state_accessor
.get_room_create_event(room_id)
.await;
let room_version_rules = room_version.rules().unwrap();
let (value, membership, sender, target) = validate_any_membership_event(
&services,
&body.pdu,
&room_version_rules,
create_event.event_id.clone(),
body.room_id.clone(),
body.event_id.clone(),
let Ok((event_id, value)) = gen_event_id_canonical_json(pdu, &room_version_rules) else {
// Event could not be converted to canonical json
return Err!(Request(BadJson("Could not convert event to canonical json.")));
};
let event_room_id: OwnedRoomId = serde_json::from_value(
serde_json::to_value(
value
.get("room_id")
.ok_or_else(|| err!(Request(BadJson("Event missing room_id property."))))?,
)
.expect("CanonicalJson is valid json value"),
)
.await?;
if membership != MembershipState::Leave {
return Err!(Request(InvalidParam("Invalid membership (expected `leave`)")));
.map_err(|e| err!(Request(BadJson(warn!("room_id field is not a valid room ID: {e}")))))?;
if event_room_id != room_id {
return Err!(Request(BadJson("Event room_id does not match request path room ID.")));
}
if sender.server_name() != body.identity {
return Err!(Request(InvalidParam("Sender belongs to a different server")));
let content: RoomMemberEventContent = serde_json::from_value(
value
.get("content")
.ok_or_else(|| err!(Request(BadJson("Event missing content property."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("Event content is empty or invalid: {e}")))))?;
if content.membership != MembershipState::Leave {
return Err!(Request(BadJson(
"Not allowed to send a non-leave membership event to leave endpoint."
)));
}
if sender != target {
return Err!(Request(InvalidParam("Sender does not match state key")));
let event_type: StateEventType = serde_json::from_value(
value
.get("type")
.ok_or_else(|| err!(Request(BadJson("Event missing type property."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("Event has invalid state event type: {e}")))))?;
if event_type != StateEventType::RoomMember {
return Err!(Request(BadJson(
"Not allowed to send non-membership state event to leave endpoint."
)));
}
// ACL check sender server name
let sender: OwnedUserId = serde_json::from_value(
value
.get("sender")
.ok_or_else(|| err!(Request(BadJson("Event missing sender property."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("sender property is not a valid user ID: {e}")))))?;
services
.rooms
.event_handler
.acl_check(sender.server_name(), room_id)
.await?;
if sender.server_name() != origin {
return Err!(Request(BadJson("Not allowed to leave on behalf of another server/user.")));
}
let state_key: OwnedUserId = serde_json::from_value(
value
.get("state_key")
.ok_or_else(|| err!(Request(BadJson("Event missing state_key property."))))?
.clone()
.into(),
)
.map_err(|e| err!(Request(BadJson(warn!("State key is not a valid user ID: {e}")))))?;
if state_key != sender {
return Err!(Request(BadJson("State key does not match sender user.")));
}
let mutex_lock = services
@@ -78,7 +153,7 @@ pub(crate) async fn create_leave_event_v2_route(
let pdu_id = services
.rooms
.event_handler
.handle_incoming_pdu(origin, room_id, &body.event_id, value, false)
.handle_incoming_pdu(origin, room_id, &event_id, value, false)
.boxed()
.await?
.ok_or_else(|| err!(Request(InvalidParam("Could not accept as timeline event."))))?;
@@ -89,7 +164,5 @@ pub(crate) async fn create_leave_event_v2_route(
.sending
.send_pdu_room(room_id, &pdu_id)
.boxed()
.await?;
Ok(create_leave_event::v2::Response::new())
.await
}
+2 -105
View File
@@ -1,10 +1,7 @@
use conduwuit::{Err, Result, err, is_false};
use conduwuit::{Err, Result, is_false};
use conduwuit_service::Services;
use futures::{FutureExt, future::OptionFuture, join};
use ruma::{
CanonicalJsonObject, EventId, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, ServerName,
UserId, events::room::member::MembershipState, room_version_rules::RoomVersionRules,
};
use ruma::{EventId, RoomId, ServerName};
pub(super) struct AccessCheck<'a> {
pub(super) services: &'a Services,
@@ -66,103 +63,3 @@ impl AccessCheck<'_> {
Ok(())
}
}
/// Performs validation on a membership event that should be run on any event a
/// remote is trying to send via us.
///
/// ## Checks performed
///
/// 1. PDU room ID matches request path room ID
/// 2. PDU event ID matches request path event ID
/// 3. Signature check
/// 4. Event type check
/// 5. `sender` field presence (and parsing)
/// 6. `state_key` field presence (and parsing)
/// 7. PDU room format check (PDU check 1)
///
/// ## Returns
///
/// A resulting tuple of (PDU JSON, target membership state, sender, recipient).
pub(crate) async fn validate_any_membership_event(
services: &crate::State,
body: &serde_json::value::RawValue,
room_version_rules: &RoomVersionRules,
create_event_id: OwnedEventId,
expected_room_id: OwnedRoomId,
expected_event_id: OwnedEventId,
) -> Result<(CanonicalJsonObject, MembershipState, OwnedUserId, OwnedUserId)> {
let (template_room_id, template_event_id, pdu) = services
.rooms
.event_handler
.parse_incoming_pdu(body, Some(room_version_rules))
.await
.map_err(|e| err!(Request(BadJson("Invalid membership PDU: {e}"))))?;
if template_room_id != expected_room_id {
return Err!(Request(InvalidParam("Membership event does not belong to requested room")));
}
if template_event_id != expected_event_id {
return Err!(Request(InvalidParam(debug_warn!(
%template_event_id,
%expected_event_id,
"Membership event ID does not match provided event ID"
))));
}
services
.server_keys
.verify_event(&pdu, room_version_rules)
.await
.map_err(|e| {
err!(Request(InvalidParam("Signature verification failed on membership event: {e}")))
})?;
// Ensure this is a membership event
if pdu
.get("type")
.expect("event must have a type")
.as_str()
.expect("type must be a string")
!= "m.room.member"
{
return Err!(Request(BadJson(
"Not allowed to send non-membership event to this endpoint"
)));
}
let membership = pdu
.get("content")
.ok_or_else(|| err!(Request(BadJson("Event missing content property"))))?
.as_object()
.ok_or_else(|| err!(Request(BadJson("Event content is not an object"))))?
.get("membership")
.ok_or_else(|| err!(Request(BadJson("Event missing membership property"))))?
.as_str()
.ok_or_else(|| err!(Request(BadJson("Event is not a string"))))?
.to_owned();
let sender_user = pdu
.get("sender")
.and_then(|v| v.as_str())
.map(UserId::parse)
.and_then(Result::ok)
.ok_or_else(|| err!(Request(InvalidParam("Invalid sender property"))))?;
let recipient_user = pdu
.get("state_key")
.and_then(|v| v.as_str())
.map(UserId::parse)
.and_then(Result::ok)
.ok_or_else(|| err!(Request(InvalidParam("Invalid state_key property"))))?;
// Do a quick format check. The spec doesn't suggest this, but it's probably
// a good idea nonetheless.
service::rooms::event_handler::Service::pdu_format_check_1(
&pdu,
room_version_rules,
&create_event_id,
)
.map_err(|e| {
err!(Request(InvalidParam("Membership event violates the room event format: {e}")))
})?;
Ok((pdu, membership.into(), sender_user, recipient_user))
}
-1
View File
@@ -2442,7 +2442,6 @@ pub struct OauthConfig {
/// legacy authentication will be unable to log in.
///
/// default: "hybrid"
#[serde(default)]
compatibility_mode: OAuthMode,
/// display: hidden
+1 -3
View File
@@ -143,8 +143,6 @@ pub trait Event: Clone + Debug {
fn into_pdu(self) -> Pdu;
fn is_owned(&self) -> bool;
//
// Canonical properties
//
@@ -182,12 +180,12 @@ pub trait Event: Clone + Debug {
fn state_key(&self) -> Option<&str>;
/// The event type.
// #[deprecated]
fn kind(&self) -> &TimelineEventType;
/// Metadata container; peer-trusted only.
fn unsigned(&self) -> Option<&RawJsonValue>;
//#[deprecated]
#[inline]
fn event_type(&self) -> &TimelineEventType { self.kind() }
}
+195 -12
View File
@@ -1,19 +1,25 @@
mod count;
pub mod hashes;
mod id;
pub mod metadata;
mod partial;
mod raw_id;
mod redact;
#[cfg(test)]
mod tests;
mod unsigned;
pub mod v2;
pub mod v3;
use std::cmp::Ordering;
use assign::assign;
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId,
OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, UInt, UserId, events::TimelineEventType,
OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, ServerSignatures, UInt, UserId, event_id,
events::TimelineEventType, room_version_rules::RoomVersionRules, state_res::Event,
};
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::value::RawValue as RawJsonValue;
pub use self::{
@@ -23,10 +29,193 @@ pub use self::{
partial::PartialPdu,
raw_id::*,
};
use super::{Event, StateKey};
use crate::Result;
use super::StateKey;
use crate::{
Err, Result,
pdu::{hashes::Hashes, metadata::PduMetadata},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EventFormatVersion {
/// V1 represents the PDU format for rooms v1 and v2.
V1,
/// V2 represents the PDU format for rooms v3-v11.
V2,
/// V3 represents the PDU format for rooms v12+.
V3,
}
impl From<RoomVersionRules> for EventFormatVersion {
fn from(rules: RoomVersionRules) -> Self {
// TODO: this is hacky because ruma doesn't actually define event versions in an
// enum, but does define consts with the appropriate rules.
if rules.event_format.require_event_id {
Self::V1
} else if rules.event_format.require_room_create_room_id {
Self::V2
} else {
Self::V3
}
}
}
/// Trait that allows conversion from a generic PDU to a concrete PDU type.
pub trait ConcretePDU: ruma::state_res::Event<Id = OwnedEventId> {
/// The concrete type for this PDU (`v2::PDU`, `v3::PDU`, etc)
type Concrete;
/// Get a reference to the concrete PDU type.
fn to_concrete(&self) -> &Self::Concrete;
/// Get the value of the concrete PDU type, consuming.
fn into_concrete(self) -> Self::Concrete;
}
pub fn new_pdu<E, C, P, JSON>(
format: EventFormatVersion,
metadata: PduMetadata,
json: serde_json::Value,
) -> Result<E>
where
E: ConcretePDU<Concrete = C>,
JSON: DeserializeOwned,
{
match format {
| EventFormatVersion::V2 =>
Ok(assign!(v2::PDU::try_from(json)?, {internal_metadata: metadata})),
| EventFormatVersion::V3 =>
Ok(assign!(v3::PDU::try_from(json)?, {internal_metadata: metadata})),
| _ => Err!("Unsupported event format: {format:?}"),
}
}
/// A builder type that specifies every field present on any PDU type, allowing
/// it to be used to create any PDU version with the appropriate function.
///
/// See `create_pdu`.
#[derive(Clone, Debug, Default)]
pub struct CommonPDUBuilder {
pub auth_events: Option<Vec<OwnedEventId>>,
pub content: Option<Box<RawJsonValue>>,
pub depth: Option<UInt>,
pub hashes: Option<Hashes>,
pub origin_server_ts: Option<MilliSecondsSinceUnixEpoch>,
pub prev_events: Option<Vec<OwnedEventId>>,
pub redacts: Option<OwnedEventId>,
pub room_id: Option<OwnedRoomId>,
pub sender: Option<OwnedUserId>,
pub signatures: Option<ServerSignatures>,
pub state_key: Option<String>,
pub event_type: Option<TimelineEventType>,
pub unsigned: Option<Box<RawJsonValue>>,
pub internal_metadata: Option<PduMetadata>,
}
/// Creates a new PDU based on the given version and builder.
///
/// ## Example
///
/// ```rust
/// use conduwuit_core::pdu::{CommonPDUBuilder, create_pdu}
///
/// let room_version_rules = RoomVersionRules::V10; // This usually comes dynamically.
/// let builder = CommonPDUBuilder {
/// auth_events: Some(vec![event_id!("$auth_event_id").to_owned()]),
/// content: Some(Box::new(serde_json::json!({"key": "value"}))),
/// depth: Some(1),
/// origin_server_ts: Some(MilliSecondsSinceUnixEpoch(123456789)),
/// prev_events: Some(vec![event_id!("$prev_event_id").to_owned()]),
/// room_id: Some(room_id!("!room_id").to_owned()),
/// sender: Some(user_id!("@sender:example.com").to_owned()),
/// event_type: Some(TimelineEventType::RoomMessage),
/// ..Default::default()
/// };
/// let pdu = create_pdu(
/// room_version_rules.into(),
/// builder,
/// ).expect("PDU creation must succeed");
/// ```
pub fn create_pdu<C>(version: EventFormatVersion, builder: CommonPDUBuilder) -> Result<C> {
match version {
| EventFormatVersion::V2 => Ok(create_v2_pdu(builder)),
| EventFormatVersion::V3 => Ok(create_v3_pdu(builder)),
| _ => Err!("Unsupported event format: {version:?}"),
}
}
fn create_v2_pdu<C>(builder: CommonPDUBuilder) -> v2::PDU {
v2::PDU {
auth_events: builder
.auth_events
.expect("auth_events must be provided for a V2 PDU"),
content: builder
.content
.expect("content must be provided for a V2 PDU"),
depth: builder.depth.expect("depth must be provided for a V2 PDU"),
hashes: builder.hashes.unwrap_or_default(), /* We allow default here since we might not
* have hashed yet */
origin_server_ts: builder
.origin_server_ts
.expect("origin_server_ts must be provided for a V2 PDU"),
prev_events: builder
.prev_events
.expect("prev_events must be provided for a V2 PDU"),
redacts: builder.redacts,
room_id: builder
.room_id
.expect("room_id must be provided for a V2 PDU"),
sender: builder
.sender
.expect("sender must be provided for a V2 PDU"),
signatures: builder.signatures.unwrap_or_default(), /* We allow default here since we
* might not have signed yet */
state_key: builder.state_key,
event_type: builder
.event_type
.expect("event_type must be provided for a V2 PDU"),
unsigned: builder.unsigned,
internal_metadata: builder
.internal_metadata
.unwrap_or_else(|| PduMetadata::new(event_id!("$unknown").to_owned())),
}
}
fn create_v3_pdu(builder: CommonPDUBuilder) -> v3::PDU {
v3::PDU {
auth_events: builder
.auth_events
.expect("auth_events must be provided for a V3 PDU"),
content: builder
.content
.expect("content must be provided for a V3 PDU"),
depth: builder.depth.expect("depth must be provided for a V3 PDU"),
hashes: builder.hashes.unwrap_or_default(), /* We allow default here since we might not
* have hashed yet */
origin_server_ts: builder
.origin_server_ts
.expect("origin_server_ts must be provided for a V3 PDU"),
prev_events: builder
.prev_events
.expect("prev_events must be provided for a V3 PDU"),
room_id: builder.room_id,
sender: builder
.sender
.expect("sender must be provided for a V3 PDU"),
signatures: builder.signatures.unwrap_or_default(), /* We allow default here since we
* might not have signed yet */
state_key: builder.state_key,
event_type: builder
.event_type
.expect("event_type must be provided for a V3 PDU"),
unsigned: builder.unsigned,
internal_metadata: builder
.internal_metadata
.unwrap_or_else(|| PduMetadata::new(event_id!("$unknown").to_owned())),
}
}
/// Persistent Data Unit (Event)
#[deprecated(note = "Use `v2::PDU` or `v3::PDU` or `ruma::state_res::Event` instead")]
#[derive(Clone, Deserialize, Serialize, Debug)]
pub struct Pdu {
pub event_id: OwnedEventId,
@@ -85,7 +274,7 @@ impl Pdu {
}
}
impl Event for Pdu {
impl crate::Event for Pdu {
#[inline]
fn auth_events(&self) -> impl DoubleEndedIterator<Item = &EventId> + Clone + Send + '_ {
self.auth_events.iter().map(AsRef::as_ref)
@@ -151,12 +340,9 @@ impl Event for Pdu {
#[inline]
fn into_pdu(self) -> Pdu { self }
#[inline]
fn is_owned(&self) -> bool { true }
}
impl Event for &Pdu {
impl crate::Event for &Pdu {
#[inline]
fn auth_events(&self) -> impl DoubleEndedIterator<Item = &EventId> + Clone + Send + '_ {
self.auth_events.iter().map(AsRef::as_ref)
@@ -219,9 +405,6 @@ impl Event for &Pdu {
#[inline]
fn into_pdu(self) -> Pdu { self.clone() }
#[inline]
fn is_owned(&self) -> bool { false }
}
/// Prevent derived equality which wouldn't limit itself to event_id
+15
View File
@@ -0,0 +1,15 @@
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
/// The content hash map for a PDU.
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Hashes {
/// The SHA256 content hash.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub sha256: String,
/// Any other hashes present, if any.
#[serde(flatten, default, skip_serializing_if = "HashMap::is_empty")]
pub other: HashMap<String, String>,
}
+16
View File
@@ -0,0 +1,16 @@
use ruma::{EventId, OwnedEventId};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PduMetadata {
/// This event's calculated event ID.
pub event_id: OwnedEventId,
/// Indicates whether the event has been rejected under auth rules.
pub rejected: bool,
}
impl PduMetadata {
/// Creates a new PduMetadata instance with the minimum required fields.
pub fn new(event_id: OwnedEventId) -> Self { Self { event_id, rejected: false } }
}
+174
View File
@@ -0,0 +1,174 @@
use ruma::{
CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId,
OwnedUserId, RoomId, ServerSignatures, UInt, UserId, events::TimelineEventType,
};
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue;
use crate::{
Pdu,
pdu::{hashes::Hashes, metadata::PduMetadata},
};
/// Represents a persistent data unit (PDU) version 2, introduced in room
/// version 3, up until room version 11.
///
/// Spec: https://spec.matrix.org/v1.19/rooms/v3/#event-format
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PDU {
/// The event IDs which authorise this event. Between 0 and 10 entries.
pub auth_events: Vec<OwnedEventId>,
/// This event's content.
pub content: Box<RawJsonValue>,
/// The depth of this event.
pub depth: UInt,
/// The content hashes for this event.
pub hashes: Hashes,
/// Timestamp in milliseconds on origin homeserver when this event was
/// created.
pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The event IDs which immediately precede this event. Between 0 and 20
/// entries.
pub prev_events: Vec<OwnedEventId>,
/// For redaction events, the ID of the event being redacted.
///
/// Not used in v11.
#[serde(skip_serializing_if = "Option::is_none")]
pub redacts: Option<OwnedEventId>,
/// The room in which this event resides.
pub room_id: OwnedRoomId,
/// The user who sent this event.
pub sender: OwnedUserId,
/// The signatures on this event.
pub signatures: ServerSignatures,
/// The state key for this PDU, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub state_key: Option<String>,
/// The type of this PDU.
#[serde(rename = "type")]
pub event_type: TimelineEventType,
/// Additional data added by the origin server but not covered by the
/// signatures.
///
/// This should be `None` when receiving from and transmitting over
/// federation.
#[serde(skip_serializing_if = "Option::is_none")]
pub unsigned: Option<Box<RawJsonValue>>,
/// Internal metadata that is important to the PDU but should not be
/// serialized into the final event.
///
/// This field MUST NOT be sent to clients or federation.
pub internal_metadata: PduMetadata,
}
impl PDU {
#[must_use]
pub fn internal_metadata(&self) -> &PduMetadata { &self.internal_metadata }
}
impl crate::pdu::ConcretePDU for PDU {
type Concrete = PDU;
fn to_concrete(&self) -> &Self::Concrete { &self }
fn into_concrete(self) -> Self::Concrete { self }
}
impl ruma::state_res::Event for PDU {
type Id = OwnedEventId;
fn event_id(&self) -> &Self::Id { &self.internal_metadata.event_id }
fn room_id(&self) -> Option<&RoomId> { Some(&self.room_id) }
fn sender(&self) -> &UserId { &self.sender }
fn origin_server_ts(&self) -> MilliSecondsSinceUnixEpoch { self.origin_server_ts }
fn event_type(&self) -> &TimelineEventType { &self.event_type }
fn content(&self) -> &RawJsonValue { self.content.as_ref() }
fn state_key(&self) -> Option<&str> { self.state_key.as_deref() }
fn prev_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
Box::new(self.prev_events.iter())
}
fn auth_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
Box::new(self.auth_events.iter())
}
fn redacts(&self) -> Option<&Self::Id> { self.redacts.as_ref() }
fn rejected(&self) -> bool { self.internal_metadata().rejected }
}
impl crate::Event for PDU {
fn as_pdu(&self) -> &Pdu { todo!() }
fn into_pdu(self) -> Pdu { todo!() }
fn auth_events(&self) -> impl DoubleEndedIterator<Item = &EventId> + Clone + Send + '_ {
self.auth_events.iter().map(AsRef::as_ref)
}
fn content(&self) -> &RawJsonValue { self.content.as_ref() }
fn event_id(&self) -> &EventId { &self.internal_metadata.event_id }
fn origin_server_ts(&self) -> MilliSecondsSinceUnixEpoch { self.origin_server_ts }
fn prev_events(&self) -> impl DoubleEndedIterator<Item = &EventId> + Clone + Send + '_ {
self.prev_events.iter().map(AsRef::as_ref)
}
fn redacts(&self) -> Option<&EventId> { self.redacts.as_deref() }
fn room_id(&self) -> Option<&RoomId> { Some(&self.room_id) }
fn room_id_or_hash(&self) -> OwnedRoomId { self.room_id.clone() }
fn sender(&self) -> &UserId { &self.sender }
fn state_key(&self) -> Option<&str> { self.state_key.as_deref() }
fn kind(&self) -> &TimelineEventType { self.event_type() }
fn unsigned(&self) -> Option<&RawJsonValue> { self.unsigned.as_deref() }
fn event_type(&self) -> &TimelineEventType { &self.event_type }
}
impl TryFrom<&RawJsonValue> for PDU {
type Error = crate::Error;
fn try_from(value: &RawJsonValue) -> Result<Self, Self::Error> {
serde_json::from_str(value.get()).map_err(Into::into)
}
}
impl TryFrom<Box<RawJsonValue>> for PDU {
type Error = crate::Error;
fn try_from(value: Box<RawJsonValue>) -> Result<Self, Self::Error> {
Self::try_from(value.as_ref())
}
}
impl TryFrom<serde_json::Value> for PDU {
type Error = crate::Error;
fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
serde_json::from_value(value).map_err(Into::into)
}
}
impl TryFrom<CanonicalJsonObject> for PDU {
type Error = crate::Error;
fn try_from(value: CanonicalJsonObject) -> Result<Self, Self::Error> {
serde_json::from_value(serde_json::to_value(value)?).map_err(Into::into)
}
}
+187
View File
@@ -0,0 +1,187 @@
use ruma::{
CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId,
OwnedUserId, RoomId, ServerSignatures, UInt, UserId,
events::{StateEventType, TimelineEventType},
};
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue;
use crate::{
Pdu,
pdu::{hashes::Hashes, metadata::PduMetadata},
};
/// Represents a persistent data unit (PDU) version 3, introduced in room
/// version 12.
///
/// Spec: https://spec.matrix.org/v1.19/rooms/v12/#event-format
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PDU {
/// The event IDs which authorise this event. Between 0 and 10 entries.
pub auth_events: Vec<OwnedEventId>,
/// This event's content.
pub content: Box<RawJsonValue>,
/// The depth of this event.
pub depth: UInt,
/// The content hashes for this event.
pub hashes: Hashes,
/// Timestamp in milliseconds on origin homeserver when this event was
/// created.
pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The event IDs which immediately precede this event. Between 0 and 20
/// entries.
pub prev_events: Vec<OwnedEventId>,
/// The room in which this event resides.
/// May be None if the event is a create event.
#[serde(skip_serializing_if = "Option::is_none")]
pub room_id: Option<OwnedRoomId>,
/// The user who sent this event.
pub sender: OwnedUserId,
/// The signatures on this event.
pub signatures: ServerSignatures,
/// The state key for this PDU, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub state_key: Option<String>,
/// The type of this PDU.
#[serde(rename = "type")]
pub event_type: TimelineEventType,
/// Additional data added by the origin server but not covered by the
/// signatures.
///
/// This should be `None` when receiving from and transmitting over
/// federation.
#[serde(skip_serializing_if = "Option::is_none")]
pub unsigned: Option<Box<RawJsonValue>>,
/// Internal metadata that is important to the PDU but should not be
/// serialized into the final event.
///
/// This field MUST NOT be sent to clients or federation.
pub internal_metadata: PduMetadata,
}
impl PDU {
#[must_use]
pub fn internal_metadata(&self) -> &PduMetadata { &self.internal_metadata }
}
impl crate::pdu::ConcretePDU<PDU> for PDU {
fn to_concrete(&self) -> &PDU { &self }
fn into_concrete(self) -> PDU { self }
}
impl ruma::state_res::Event for PDU {
type Id = OwnedEventId;
fn event_id(&self) -> &Self::Id { &self.internal_metadata.event_id }
fn room_id(&self) -> Option<&RoomId> { self.room_id.as_deref() }
fn sender(&self) -> &UserId { &self.sender }
fn origin_server_ts(&self) -> MilliSecondsSinceUnixEpoch { self.origin_server_ts }
fn event_type(&self) -> &TimelineEventType { &self.event_type }
fn content(&self) -> &RawJsonValue { self.content.as_ref() }
fn state_key(&self) -> Option<&str> { self.state_key.as_deref() }
fn prev_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
Box::new(self.prev_events.iter())
}
fn auth_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
Box::new(self.auth_events.iter())
}
fn redacts(&self) -> Option<&Self::Id> { None }
fn rejected(&self) -> bool { self.internal_metadata().rejected }
}
impl crate::Event for PDU {
fn as_pdu(&self) -> &Pdu { todo!() }
fn into_pdu(self) -> Pdu { todo!() }
fn auth_events(&self) -> impl DoubleEndedIterator<Item = &EventId> + Clone + Send + '_ {
self.auth_events.iter().map(AsRef::as_ref)
}
fn content(&self) -> &RawJsonValue { self.content.as_ref() }
fn event_id(&self) -> &EventId { &self.internal_metadata.event_id }
fn origin_server_ts(&self) -> MilliSecondsSinceUnixEpoch { self.origin_server_ts }
fn prev_events(&self) -> impl DoubleEndedIterator<Item = &EventId> + Clone + Send + '_ {
self.prev_events.iter().map(AsRef::as_ref)
}
fn redacts(&self) -> Option<&EventId> { None }
fn room_id(&self) -> Option<&RoomId> { self.room_id.as_deref() }
fn room_id_or_hash(&self) -> OwnedRoomId {
if self.event_type == StateEventType::RoomCreate.into()
&& self.state_key().is_some_and(str::is_empty)
{
// Calculate the room ID for a create event.
RoomId::new_v2(
self.internal_metadata()
.event_id
.as_str()
.strip_prefix("$")
.expect("event ID must start with $ sigil"),
)
.expect("must be able to create a room ID from create event reference hash")
} else {
// Otherwise, all other events have a room ID field.
self.room_id.clone().unwrap()
}
}
fn sender(&self) -> &UserId { &self.sender }
fn state_key(&self) -> Option<&str> { self.state_key.as_deref() }
fn kind(&self) -> &TimelineEventType { self.event_type() }
fn unsigned(&self) -> Option<&RawJsonValue> { self.unsigned.as_deref() }
fn event_type(&self) -> &TimelineEventType { &self.event_type }
}
impl TryFrom<&RawJsonValue> for PDU {
type Error = crate::Error;
fn try_from(value: &RawJsonValue) -> Result<Self, Self::Error> {
serde_json::from_str(value.get()).map_err(Into::into)
}
}
impl TryFrom<Box<RawJsonValue>> for PDU {
type Error = crate::Error;
fn try_from(value: Box<RawJsonValue>) -> Result<Self, Self::Error> {
Self::try_from(value.as_ref())
}
}
impl TryFrom<serde_json::Value> for PDU {
type Error = crate::Error;
fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
serde_json::from_value(value).map_err(Into::into)
}
}
impl TryFrom<CanonicalJsonObject> for PDU {
type Error = crate::Error;
fn try_from(value: CanonicalJsonObject) -> Result<Self, Self::Error> {
serde_json::from_value(serde_json::to_value(value)?).map_err(Into::into)
}
}
+2 -10
View File
@@ -1,6 +1,4 @@
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};
@@ -9,16 +7,10 @@ use crate::admin::InvocationSource;
pub(super) const SIGNAL: &str = "SIGUSR2";
impl super::Service {
/// Possibly spawn the terminal console at startup if configured and a TTY
/// is available.
/// Possibly spawn the terminal console at startup if configured.
pub(super) async fn console_auto_start(&self) {
#[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");
return;
}
// Allow more of the startup sequence to execute before spawning
tokio::task::yield_now().await;
self.console.start().await;
+1 -1
View File
@@ -134,7 +134,7 @@ impl Service {
let response = self
.services
.client
.external_resource
.default
.get(CHECK_FOR_ANNOUNCEMENTS_URL)
.send()
.await?
+19 -14
View File
@@ -16,9 +16,9 @@ pub struct Service {
pub matrix_resolver: Arc<MatrixResolver>,
pub dns_resolver: Arc<TokioResolver>,
pub dns: reqwest::Client,
pub default: reqwest::Client,
pub url_preview: reqwest::Client,
pub external_resource: reqwest::Client,
pub extern_media: reqwest::Client,
pub federation: reqwest::Client,
pub federation_slow: reqwest::Client,
pub sender: reqwest::Client,
@@ -35,17 +35,17 @@ impl crate::Service for Service {
let dns_resolver = get_dns_resolver(args.server)?;
let dns_client = base(&args.server.config)?
.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))
.pool_max_idle_per_host(0)
.redirect(redirect::Policy::limited(4))
.build()?;
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())
.http_client(
base(&args.server.config)?
.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))
.pool_max_idle_per_host(0)
.redirect(redirect::Policy::limited(4))
.build()?
)
.dns_resolver(dns_resolver.clone())
.build()?);
let matrix_dns_resolver = matrix_resolver.create_dns_resolver();
@@ -69,19 +69,23 @@ impl crate::Service for Service {
matrix_resolver,
dns_resolver,
dns: dns_client,
default: base(config)?
.dns_resolver(matrix_dns_resolver.clone())
.build()?,
url_preview: base(config)
.and_then(|builder| {
builder_interface(builder, url_preview_bind_iface.as_deref())
})?
.local_address(url_preview_bind_addr)
.dns_resolver(matrix_dns_resolver.clone())
.timeout(Duration::from_secs(config.url_preview_timeout))
.redirect(redirect::Policy::limited(3))
.user_agent(url_preview_user_agent)
.build()?,
external_resource: base(config)?
extern_media: base(config)?
.dns_resolver(matrix_dns_resolver.clone())
.redirect(redirect::Policy::limited(3))
.build()?,
@@ -124,7 +128,7 @@ impl crate::Service for Service {
.build()?,
appservice: base(config)?
.dns_resolver(matrix_dns_resolver)
.dns_resolver(matrix_dns_resolver.clone())
.connect_timeout(Duration::from_secs(5))
.read_timeout(Duration::from_secs(config.appservice_timeout))
.timeout(Duration::from_secs(config.appservice_timeout))
@@ -134,6 +138,7 @@ impl crate::Service for Service {
.build()?,
pusher: base(config)?
.dns_resolver(matrix_dns_resolver)
.connect_timeout(Duration::from_secs(config.pusher_conn_timeout))
.timeout(Duration::from_secs(config.pusher_timeout))
.pool_max_idle_per_host(1)
+1 -1
View File
@@ -260,7 +260,7 @@ impl super::Service {
let response = self
.services
.client
.external_resource
.extern_media
.get(location)
.send()
.await?;
+2 -4
View File
@@ -829,7 +829,7 @@ async fn fix_local_invite_state(services: &Services) -> Result {
&& services.globals.user_is_local(&membership_event.sender) {
// build and save stripped state for their invite in the database
let stripped_state = services.rooms.state.summary_stripped(&membership_event, &room_id, &user_id, false).await;
let stripped_state = services.rooms.state.summary_stripped(&membership_event, &room_id, &user_id).await;
userroomid_invitestate.put((&user_id, &room_id), Json(stripped_state));
fixed = fixed.saturating_add(1);
}
@@ -882,7 +882,7 @@ async fn split_userid_password(services: &Services) -> Result {
drop(cork);
info!(?remote_users, "Split userid_password.");
db["global"].insert(SPLIT_USERID_PASSWORD, []);
db["global"].insert(FIXED_LOCAL_INVITE_STATE_MARKER, []);
db.db.sort()?;
Ok(())
}
@@ -895,7 +895,5 @@ async fn obliterate_roomsynctoken_shortstatehash_with_extreme_prejudice(
info!("Cleared roomsynctoken_shortstatehash.");
services.db["global"].insert(DROP_ROOMSYNCTOKEN_SHORTSTATEHASH, []);
Ok(())
}
-1
View File
@@ -151,7 +151,6 @@ impl crate::Service for Service {
config: config.clone(),
client_secret: if let Some(client_secret_file) = &config.client_secret_file {
std::fs::read_to_string(client_secret_file)
.map(|client_secret| client_secret.trim().to_owned())
.map(ClientSecret::new)
.map_err(|err| err!("Failed to read OIDC client secret file: {err}"))?
} else if let Some(client_secret) = &config.client_secret {
@@ -241,7 +241,7 @@ impl super::Service {
latest_events.clear();
for raw_event in response.events {
let (_, event_id, pdu_json) = self.parse_incoming_pdu(&raw_event, None).await?;
let (_, event_id, pdu_json) = self.parse_incoming_pdu(&raw_event).await?;
let pdu = PduEvent::from_id_val(&event_id, pdu_json).map_err(|e| {
err!(Request(BadJson("Failed to parse gapfilled event {event_id}: {e}")))
})?;
@@ -384,9 +384,8 @@ impl super::Service {
.send_federation_request(&remote, get_event::v1::Request::new(event_id.clone()))
.await?;
let (_, calculated_event_id, value) = self
.parse_incoming_pdu(&res.pdu, Some(room_version_rules))
.await?;
let (calculated_event_id, value) =
Self::parse_incoming_pdu_with_known_room(&res.pdu, room_version_rules)?;
if calculated_event_id != event_id {
Err!(Request(BadJson(warn!(
+8 -10
View File
@@ -48,16 +48,14 @@ impl super::Service {
let mut auth_chain_map = HashMap::with_capacity(event_auth.auth_chain.len());
for auth_pdu_json in event_auth.auth_chain {
let (auth_event_room_id, auth_event_id, auth_pdu_json) = match self
.parse_incoming_pdu(&auth_pdu_json, Some(room_version_rules))
.await
{
| Ok(parsed) => parsed,
| Err(e) => {
warn!(error=?e, "Dropping auth chain event as it could not be parsed");
continue;
},
};
let (auth_event_room_id, auth_event_id, auth_pdu_json) =
match self.parse_incoming_pdu(&auth_pdu_json).await {
| Ok(parsed) => parsed,
| Err(e) => {
warn!(error=?e, "Dropping auth chain event as it could not be parsed");
continue;
},
};
if let Err(e) = Self::pdu_format_check_1(
&auth_pdu_json,
room_version_rules,
@@ -314,7 +314,7 @@ impl super::Service {
.iter()
.stream()
.broad_filter_map(|raw_event_json| async {
if let Some(parsed) = self.parse_incoming_pdu(raw_event_json, None).await.ok()
if let Some(parsed) = self.parse_incoming_pdu(raw_event_json).await.ok()
&& parsed.0 == room_id
{
Some(parsed)
@@ -351,7 +351,7 @@ impl super::Service {
.iter()
.stream()
.broad_filter_map(|raw_event_json| async {
if let Some(parsed) = self.parse_incoming_pdu(raw_event_json, None).await.ok()
if let Some(parsed) = self.parse_incoming_pdu(raw_event_json).await.ok()
&& parsed.0 == room_id
{
Some(parsed)
@@ -14,12 +14,10 @@ impl super::Service {
/// This performs steps 1 through 4 of [S-S section 5.1][spec], returning
/// the parsed PDU and modified JSON object.
///
/// **External callers likely want `handle_incoming_pdu` instead.**
///
/// [spec]: https://spec.matrix.org/v1.19/server-server-api/#checks-performed-on-receipt-of-a-pdu
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(name = "handle_outlier", skip_all)]
pub async fn handle_outlier_pdu<'a, Pdu>(
pub(super) async fn handle_outlier_pdu<'a, Pdu>(
&self,
origin: &'a ServerName,
create_event: &'a Pdu,
@@ -56,6 +54,7 @@ impl super::Service {
})?;
value.remove("unsigned");
let room_version_rules = get_room_version_rules(create_event)?;
// 2. Check signatures, otherwise drop.
// 3. Check content hash, redacting the event if it fails.
@@ -82,14 +82,25 @@ pub(super) fn expect_event_id_array(
}
impl super::Service {
/// Parses an incoming PDU JSON object, generating an event ID for it. Does
/// not insert the event ID into the returned object. Does not discover the
/// room ID.
pub(super) fn parse_incoming_pdu_with_known_room(
pdu: &RawJsonValue,
room_version_rules: &RoomVersionRules,
) -> Result<(OwnedEventId, CanonicalJsonObject)> {
let (event_id, value) =
gen_event_id_canonical_json(pdu, room_version_rules).map_err(|e| {
err!(Request(InvalidParam("Could not convert event to canonical json: {e}")))
})?;
// NOTE: validation checks are now performed by `pdu_format_check_1`.
Ok((event_id, value))
}
/// Parses an incoming PDU JSON object, generating an event ID for it and
/// attempts to discover the associated room ID. Does not insert the event
/// ID into the returned object.
pub async fn parse_incoming_pdu(
&self,
pdu: &RawJsonValue,
room_version_rules: Option<&RoomVersionRules>,
) -> Result<Parsed> {
pub async fn parse_incoming_pdu(&self, pdu: &RawJsonValue) -> Result<Parsed> {
let value = serde_json::from_str::<CanonicalJsonObject>(pdu.get()).map_err(|e| {
err!(BadServerResponse(debug_warn!("Error parsing incoming event {e:?}")))
})?;
@@ -100,20 +111,17 @@ impl super::Service {
let room_id = extract_room_id(event_type, &value)?;
let room_version_rules = match room_version_rules {
| Some(r) => r,
| None => &self
.services
.state
.get_room_version(&room_id)
.await
.unwrap_or(RoomVersionId::V1)
.rules()
.expect("room version must be supported"),
};
let room_version_rules = self
.services
.state
.get_room_version(&room_id)
.await
.unwrap_or(RoomVersionId::V1)
.rules()
.unwrap();
let (event_id, value) =
gen_event_id_canonical_json(pdu, room_version_rules).map_err(|e| {
gen_event_id_canonical_json(pdu, &room_version_rules).map_err(|e| {
err!(Request(InvalidParam("Could not convert event to canonical json: {e}")))
})?;
// NOTE: validation checks are now performed by `pdu_format_check_1`.
@@ -18,7 +18,7 @@ impl super::Service {
/// Checks that the PDU conforms to the PDU format (check 1). This is
/// already mostly done during deserialisation, so this function just checks
/// that the PDU isn't a too large.
pub fn pdu_format_check_1(
pub(super) fn pdu_format_check_1(
pdu_json: &CanonicalJsonObject,
room_version_rules: &RoomVersionRules,
create_event_id: &EventId,
@@ -45,8 +45,6 @@ impl super::Service {
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")));
} else if event_format.allow_room_create_in_auth_events && !create_event_in_auth_events {
return Err!(Request(BadJson("PDU does not reference the room create event")));
}
let prev_events = expect_event_id_array(pdu_json, "prev_events")?;
@@ -61,7 +59,7 @@ impl super::Service {
/// the content hash verification fails (check 3), returning the
/// potentially modified JSON. Returns an error if the PDU cannot be
/// redacted, or fails signature verification.
pub async fn signature_hash_check_2_3(
pub(super) async fn signature_hash_check_2_3(
&self,
pdu_json: CanonicalJsonObject,
room_version_rules: &RoomVersionRules,
@@ -94,7 +92,7 @@ impl super::Service {
/// If the auth check fails, false is returned, otherwise true.
///
/// [spec]: https://spec.matrix.org/v1.19/server-server-api/#checks-performed-on-receipt-of-a-pdu
pub async fn auth_state_check_4(
pub(super) async fn auth_state_check_4(
&self,
pdu: &PduEvent,
room_version_rules: &RoomVersionRules,
+3 -18
View File
@@ -1,7 +1,7 @@
use std::{collections::HashMap, fmt::Write, sync::Arc};
use async_trait::async_trait;
use conduwuit::{debug, utils::stream::WidebandExt};
use conduwuit::debug;
use conduwuit_core::{
Event, PduEvent, Result, err,
result::FlatOk,
@@ -30,7 +30,7 @@ use crate::{
short::{ShortEventId, ShortStateHash},
state_compressor::{CompressedState, parse_compressed_state_event},
},
sending, sync,
sync,
};
pub struct Service {
@@ -45,7 +45,6 @@ struct Services {
state_cache: Dep<rooms::state_cache::Service>,
state_accessor: Dep<rooms::state_accessor::Service>,
state_compressor: Dep<rooms::state_compressor::Service>,
sending: Dep<sending::Service>,
sync: Dep<sync::Service>,
timeline: Dep<rooms::timeline::Service>,
}
@@ -72,7 +71,6 @@ impl crate::Service for Service {
.depend::<rooms::state_accessor::Service>("rooms::state_accessor"),
state_compressor: args
.depend::<rooms::state_compressor::Service>("rooms::state_compressor"),
sending: args.depend::<sending::Service>("sending"),
sync: args.depend::<sync::Service>("sync"),
timeline: args.depend::<rooms::timeline::Service>("rooms::timeline"),
},
@@ -309,7 +307,6 @@ impl Service {
event: &PduEvent,
room_id: &RoomId,
target_user: &UserId,
federation: bool,
) -> Vec<RawStrippedState> {
let mut state_events = [
(&StateEventType::RoomCreate, ""),
@@ -346,20 +343,8 @@ impl Service {
.await
.into_iter()
.filter_map(Result::ok)
.stream()
.wide_then(async |pdu| {
let formatted = if federation {
self.services
.sending
.convert_to_outgoing_federation_event(pdu.to_canonical_object())
.await
} else {
serde_json::value::to_raw_value(&pdu).unwrap()
};
RawStrippedState::Pdu(formatted)
})
.map(|pdu| RawStrippedState::Pdu(serde_json::value::to_raw_value(&pdu).unwrap()))
.collect()
.await
}
/// Set the state hash to a new version, but does not update state_cache.
+1 -1
View File
@@ -114,7 +114,7 @@ impl super::Service {
let invite_state = if is_local {
self.services
.state
.summary_stripped(pdu, room_id, user_id, false)
.summary_stripped(pdu, room_id, user_id)
.await
} else {
vec![]
+2 -5
View File
@@ -166,11 +166,8 @@ impl super::Service {
/// Backfills a single PDU.
#[tracing::instrument(skip(self, pdu), level = "debug")]
pub async fn backfill_pdu(&self, origin: &ServerName, pdu: Box<RawJsonValue>) -> Result<()> {
let (room_id, event_id, value) = self
.services
.event_handler
.parse_incoming_pdu(&pdu, None)
.await?;
let (room_id, event_id, value) =
self.services.event_handler.parse_incoming_pdu(&pdu).await?;
// Lock so we cannot backfill the same pdu twice at the same time
let mutex_lock = self
+3 -18
View File
@@ -1,6 +1,6 @@
use std::{cmp, collections::HashMap};
use conduwuit::{smallstr::SmallString, trace};
use conduwuit::{pdu::AnyPDU, smallstr::SmallString, trace};
use conduwuit_core::{
Err, Error, Result, err,
matrix::{
@@ -84,7 +84,7 @@ impl super::Service {
sender: &UserId,
room_id: Option<&RoomId>,
_mutex_lock: &RoomMutexGuard,
) -> Result<(PduEvent, RoomVersionRules)> {
) -> Result<AnyPDU> {
let PartialPdu {
event_type,
content,
@@ -282,7 +282,7 @@ impl super::Service {
sender: &UserId,
room_id: Option<&RoomId>,
mutex_lock: &RoomMutexGuard,
) -> Result<(PduEvent, CanonicalJsonObject)> {
) -> Result<AnyPDU> {
if !self.services.globals.user_is_local(sender) {
return Err!(Request(Forbidden("Sender must be a local user")));
}
@@ -308,21 +308,6 @@ impl super::Service {
| _ => Err!(Request(Unknown(warn!("Signing event failed: {e}")))),
};
}
// Evil hack because only the PDU JSON gets signed
pdu.hashes = serde_json::from_value(serde_json::to_value(
pdu_json
.get("hashes")
.expect("must have hashes after signing")
.clone(),
)?)?;
pdu.signatures = serde_json::from_value(serde_json::to_value(
pdu_json
.get("signatures")
.expect("must have signatures after signing")
.clone(),
)?)?;
// Generate event id
pdu.event_id = gen_event_id(&pdu_json, &room_version_rules)?;
pdu_json