mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-04 22:31:47 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e598a6f71 | ||
|
|
148a025f36 | ||
|
|
4d88bb84f5 | ||
|
|
2d6260792d | ||
|
|
6a1f29cd03 |
No files matched your search
Generated
+564
-108
File diff suppressed because it is too large.
Load diff
+13
-2
@@ -166,6 +166,15 @@ features = [
|
|||||||
"form",
|
"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]
|
[workspace.dependencies.serde]
|
||||||
version = "1.0.229"
|
version = "1.0.229"
|
||||||
default-features = false
|
default-features = false
|
||||||
@@ -376,6 +385,7 @@ features = [
|
|||||||
"unstable-msc4203",
|
"unstable-msc4203",
|
||||||
"unstable-msc4310",
|
"unstable-msc4310",
|
||||||
"unstable-msc4380",
|
"unstable-msc4380",
|
||||||
|
"unstable-msc4140",
|
||||||
"unstable-msc4143",
|
"unstable-msc4143",
|
||||||
"unstable-msc4293",
|
"unstable-msc4293",
|
||||||
"unstable-msc4363",
|
"unstable-msc4363",
|
||||||
@@ -413,9 +423,10 @@ default-features = false
|
|||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
default-features = false
|
default-features = false
|
||||||
|
|
||||||
[workspace.dependencies.openid]
|
[workspace.dependencies.openidconnect]
|
||||||
version = "0.26.0"
|
version = "4.1.0"
|
||||||
default-features = false
|
default-features = false
|
||||||
|
features = ["reqwest"]
|
||||||
|
|
||||||
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
||||||
[workspace.dependencies.opentelemetry]
|
[workspace.dependencies.opentelemetry]
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
Add support for delayed events (MSC4140), including the stable endpoints and the `m.delayed_events` capability. The limits can be configured with `delayed_events_max_delay_ms` and `delayed_events_max_scheduled`. Contributed by @eve and @Henry-Hiles.
|
||||||
@@ -813,6 +813,19 @@
|
|||||||
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
|
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
|
||||||
#forget_forced_upon_leave = false
|
#forget_forced_upon_leave = false
|
||||||
|
|
||||||
|
# The maximum delay in milliseconds for delayed events (MSC4140). Setting
|
||||||
|
# this or `delayed_events_max_scheduled` to 0 disables delayed events.
|
||||||
|
#
|
||||||
|
# env: CONTINUWUITY_DELAYED_EVENTS_MAX_DELAY_MS
|
||||||
|
#delayed_events_max_delay_ms = 604800000
|
||||||
|
|
||||||
|
# The maximum number of delayed events each user can have scheduled at
|
||||||
|
# once. Setting this or `delayed_events_max_delay_ms` to 0 disables
|
||||||
|
# delayed events.
|
||||||
|
#
|
||||||
|
# env: CONTINUWUITY_DELAYED_EVENTS_MAX_SCHEDULED
|
||||||
|
#delayed_events_max_scheduled = 100
|
||||||
|
|
||||||
# Set this to true to require authentication when looking up user profiles
|
# Set this to true to require authentication when looking up user profiles
|
||||||
# through this server.
|
# through this server.
|
||||||
#
|
#
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::{
|
||||||
|
collections::{BTreeMap, BTreeSet},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use conduwuit::{Result, Server, config::experiments::ToggledExperiment};
|
use conduwuit::{Result, Server, config::experiments::ToggledExperiment};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
RoomVersionId,
|
RoomVersionId, UInt,
|
||||||
api::{
|
api::{
|
||||||
OAuthClientScope,
|
OAuthClientScope,
|
||||||
client::discovery::get_capabilities::{
|
client::discovery::get_capabilities::{
|
||||||
self,
|
self,
|
||||||
v3::{
|
v3::{
|
||||||
AdminCapability, Capabilities, GetLoginTokenCapability, ProfileFieldsCapability,
|
AdminCapability, Capabilities, DelayedEventsCapability, GetLoginTokenCapability,
|
||||||
RoomVersionStability, RoomVersionsCapability, ThirdPartyIdChangesCapability,
|
ProfileFieldsCapability, RoomVersionStability, RoomVersionsCapability,
|
||||||
|
ThirdPartyIdChangesCapability,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -64,6 +68,11 @@ pub(crate) async fn get_capabilities_route(
|
|||||||
assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }),
|
assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
capabilities.delayed_events = Some(assign!(DelayedEventsCapability::new(), {
|
||||||
|
max_delay_ms: Some(Duration::from_millis(services.config.delayed_events_max_delay_ms)),
|
||||||
|
max_scheduled: Some(UInt::new_saturating(services.config.delayed_events_max_scheduled)),
|
||||||
|
}));
|
||||||
|
|
||||||
capabilities.set(
|
capabilities.set(
|
||||||
"org.matrix.msc4174.webpush",
|
"org.matrix.msc4174.webpush",
|
||||||
json!({
|
json!({
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
use axum::extract::State;
|
||||||
|
use conduwuit::{Err, Result};
|
||||||
|
use ruma::{
|
||||||
|
api::client::delayed_events::{
|
||||||
|
get_delayed_event, schedule_delayed_event,
|
||||||
|
update_delayed_event::{self, UpdateAction},
|
||||||
|
},
|
||||||
|
events::TimelineEventType,
|
||||||
|
signatures::MAX_PDU_BYTES,
|
||||||
|
};
|
||||||
|
use serde_json::{Map as JsonMap, Value as JsonValue};
|
||||||
|
use service::rooms::delayed_events::NewDelayedEvent;
|
||||||
|
|
||||||
|
use crate::{Ruma, client_ip::ClientIp};
|
||||||
|
|
||||||
|
/// The largest content we accept for a delayed event, leaving 4 KiB of the PDU
|
||||||
|
/// size limit for the rest of the event (IDs, hashes, signatures, etc).
|
||||||
|
const MAX_CONTENT_BYTES: usize = MAX_PDU_BYTES - 4096;
|
||||||
|
|
||||||
|
/// # `PUT /_matrix/client/v3/rooms/{roomId}/delayed_event/{eventType}/{txnId}`
|
||||||
|
///
|
||||||
|
/// Schedules an event to be sent into a room after a delay.
|
||||||
|
pub(crate) async fn schedule_delayed_event_route(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
ClientIp(client_ip): ClientIp,
|
||||||
|
body: Ruma<schedule_delayed_event::v3::Request>,
|
||||||
|
) -> Result<schedule_delayed_event::v3::Response> {
|
||||||
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
|
let sender_device = body.identity.sender_device();
|
||||||
|
|
||||||
|
if services.users.is_suspended(sender_user).await? {
|
||||||
|
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
services
|
||||||
|
.users
|
||||||
|
.update_device_last_seen(sender_user, sender_device, client_ip)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let Some(max_delay) = services.rooms.delayed_events.max_delay() else {
|
||||||
|
return Err!(Request(Forbidden("Delayed events are disabled on this server.")));
|
||||||
|
};
|
||||||
|
|
||||||
|
if body.delay_ms.is_zero() {
|
||||||
|
return Err!(Request(BadJson("delay_ms must be greater than 0.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
if body.delay_ms > max_delay {
|
||||||
|
return Err!(Request(DelayTooLarge(
|
||||||
|
"The requested delay exceeds the maximum of {}ms.",
|
||||||
|
max_delay.as_millis()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if serde_json::from_str::<JsonMap<String, JsonValue>>(body.content.json().get()).is_err() {
|
||||||
|
return Err!(Request(BadJson("The event content must be a JSON object.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The full PDU is size checked again when it is sent.
|
||||||
|
if body.content.json().get().len() > MAX_CONTENT_BYTES {
|
||||||
|
return Err!(Request(TooLarge(
|
||||||
|
"The event content exceeds the maximum of {MAX_CONTENT_BYTES} bytes."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auth is checked again when the event is sent
|
||||||
|
let is_own_membership = body.event_type == TimelineEventType::RoomMember
|
||||||
|
&& body.state_key.as_deref() == Some(sender_user.as_str());
|
||||||
|
if !is_own_membership
|
||||||
|
&& !services
|
||||||
|
.rooms
|
||||||
|
.state_cache
|
||||||
|
.is_joined(sender_user, &body.room_id)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
return Err!(Request(Forbidden("You are not joined to this room.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
let timestamp =
|
||||||
|
if body.identity.is_appservice() || services.admin.user_is_admin(sender_user).await {
|
||||||
|
body.timestamp
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let body = body.body;
|
||||||
|
let delay_id = services
|
||||||
|
.rooms
|
||||||
|
.delayed_events
|
||||||
|
.schedule(sender_user, sender_device, &body.txn_id, NewDelayedEvent {
|
||||||
|
room_id: body.room_id,
|
||||||
|
event_type: body.event_type,
|
||||||
|
state_key: body.state_key,
|
||||||
|
content: body.content,
|
||||||
|
delay: body.delay_ms,
|
||||||
|
timestamp,
|
||||||
|
sticky_duration_ms: body.sticky_duration_ms,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(schedule_delayed_event::v3::Response::new(delay_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # `POST /_matrix/client/v1/delayed_events/{delayId}/{action}`
|
||||||
|
///
|
||||||
|
/// Restarts, sends or cancels a scheduled delayed event.
|
||||||
|
pub(crate) async fn update_delayed_event_route(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
body: Ruma<update_delayed_event::v1::Request>,
|
||||||
|
) -> Result<update_delayed_event::v1::Response> {
|
||||||
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
|
let update_delayed_event::v1::Request { delay_id, action, .. } = body.body;
|
||||||
|
|
||||||
|
// Cancelling is still allowed, since it only stops activity.
|
||||||
|
if action != UpdateAction::Cancel && services.users.is_suspended(sender_user).await? {
|
||||||
|
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
services
|
||||||
|
.rooms
|
||||||
|
.delayed_events
|
||||||
|
.update(sender_user, &delay_id, action)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(update_delayed_event::v1::Response::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # `GET /_matrix/client/v1/delayed_events/{delayId}`
|
||||||
|
///
|
||||||
|
/// Returns a scheduled or finalized delayed event.
|
||||||
|
pub(crate) async fn get_delayed_event_route(
|
||||||
|
State(services): State<crate::State>,
|
||||||
|
body: Ruma<get_delayed_event::v1::Request>,
|
||||||
|
) -> Result<get_delayed_event::v1::Response> {
|
||||||
|
let sender_user = body.identity.expect_sender_user()?;
|
||||||
|
|
||||||
|
let delayed_event = services
|
||||||
|
.rooms
|
||||||
|
.delayed_events
|
||||||
|
.get(sender_user, &body.delay_id)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(get_delayed_event::v1::Response::new(delayed_event))
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ pub(super) mod backup;
|
|||||||
pub(super) mod capabilities;
|
pub(super) mod capabilities;
|
||||||
pub(super) mod context;
|
pub(super) mod context;
|
||||||
pub(super) mod dehydrated_device;
|
pub(super) mod dehydrated_device;
|
||||||
|
pub(super) mod delayed_events;
|
||||||
pub(super) mod device;
|
pub(super) mod device;
|
||||||
pub(super) mod directory;
|
pub(super) mod directory;
|
||||||
pub(super) mod filter;
|
pub(super) mod filter;
|
||||||
@@ -52,6 +53,7 @@ pub(super) use backup::*;
|
|||||||
pub(super) use capabilities::*;
|
pub(super) use capabilities::*;
|
||||||
pub(super) use context::*;
|
pub(super) use context::*;
|
||||||
pub(super) use dehydrated_device::*;
|
pub(super) use dehydrated_device::*;
|
||||||
|
pub(super) use delayed_events::*;
|
||||||
pub(super) use device::*;
|
pub(super) use device::*;
|
||||||
pub(super) use directory::*;
|
pub(super) use directory::*;
|
||||||
pub(super) use filter::*;
|
pub(super) use filter::*;
|
||||||
|
|||||||
@@ -559,15 +559,16 @@ pub(crate) async fn create_room_route(
|
|||||||
match services
|
match services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.send_state_event_for_key(
|
.send_timeline_event(
|
||||||
|
PartialPdu {
|
||||||
|
event_type: event_type.to_string().into(),
|
||||||
|
content: content.into_json(),
|
||||||
|
state_key: Some(state_key.into()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
sender_user,
|
sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&state_lock,
|
&state_lock,
|
||||||
&event_type,
|
|
||||||
&content,
|
|
||||||
&state_key,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
.boxed()
|
.boxed()
|
||||||
.await
|
.await
|
||||||
|
|||||||
+2
-14
@@ -40,20 +40,8 @@ pub(crate) async fn send_message_event_route(
|
|||||||
.update_device_last_seen(sender_user, sender_device, client_ip)
|
.update_device_last_seen(sender_user, sender_device, client_ip)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
// Forbid m.room.encrypted if encryption is disabled
|
|
||||||
if MessageLikeEventType::RoomEncrypted == body.event_type && !services.config.allow_encryption
|
|
||||||
{
|
|
||||||
return Err!(Request(Forbidden("Encryption has been disabled")));
|
|
||||||
}
|
|
||||||
|
|
||||||
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
|
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
|
||||||
|
|
||||||
if body.event_type == MessageLikeEventType::CallInvite
|
|
||||||
&& services.rooms.directory.is_public_room(&body.room_id).await
|
|
||||||
{
|
|
||||||
return Err!(Request(Forbidden("Room call invites are not allowed in public rooms")));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if this is a new transaction id
|
// Check if this is a new transaction id
|
||||||
if let Ok(response) = services
|
if let Ok(response) = services
|
||||||
.transactions
|
.transactions
|
||||||
@@ -91,7 +79,7 @@ pub(crate) async fn send_message_event_route(
|
|||||||
let event_id = services
|
let event_id = services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.build_and_append_pdu(
|
.send_timeline_event(
|
||||||
PartialPdu {
|
PartialPdu {
|
||||||
event_type: body.event_type.clone().into(),
|
event_type: body.event_type.clone().into(),
|
||||||
content,
|
content,
|
||||||
@@ -108,7 +96,7 @@ pub(crate) async fn send_message_event_route(
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
sender_user,
|
sender_user,
|
||||||
Some(&body.room_id),
|
&body.room_id,
|
||||||
&state_lock,
|
&state_lock,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
+19
-10
@@ -1,7 +1,13 @@
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use conduwuit::{Err, Result, err, matrix::Event};
|
use conduwuit::{
|
||||||
|
Err, Result, err,
|
||||||
|
matrix::{
|
||||||
|
Event,
|
||||||
|
pdu::{PartialPdu, sticky},
|
||||||
|
},
|
||||||
|
};
|
||||||
use futures::{FutureExt, TryStreamExt};
|
use futures::{FutureExt, TryStreamExt};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
RoomId,
|
RoomId,
|
||||||
@@ -42,19 +48,22 @@ pub(crate) async fn send_state_event_for_key_route(
|
|||||||
let event_id = services
|
let event_id = services
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.timeline
|
||||||
.send_state_event_for_key(
|
.send_timeline_event(
|
||||||
sender_user,
|
PartialPdu {
|
||||||
&body.room_id,
|
event_type: body.event_type.to_string().into(),
|
||||||
&state_lock,
|
content: body.body.body.clone().into_json(),
|
||||||
&body.event_type,
|
state_key: Some(body.state_key.as_str().into()),
|
||||||
&body.body.body,
|
sticky: body.sticky_duration_ms.map(sticky::object),
|
||||||
&body.state_key,
|
timestamp: if body.identity.is_appservice() {
|
||||||
body.sticky_duration_ms,
|
|
||||||
if body.identity.is_appservice() {
|
|
||||||
body.timestamp
|
body.timestamp
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
},
|
},
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
sender_user,
|
||||||
|
&body.room_id,
|
||||||
|
&state_lock,
|
||||||
)
|
)
|
||||||
.boxed()
|
.boxed()
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -163,6 +163,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
|||||||
.ruma_route(&client::update_device_route)
|
.ruma_route(&client::update_device_route)
|
||||||
.ruma_route(&client::delete_device_route)
|
.ruma_route(&client::delete_device_route)
|
||||||
.ruma_route(&client::delete_devices_route)
|
.ruma_route(&client::delete_devices_route)
|
||||||
|
.ruma_route(&client::schedule_delayed_event_route)
|
||||||
|
.ruma_route(&client::update_delayed_event_route)
|
||||||
|
.ruma_route(&client::get_delayed_event_route)
|
||||||
.ruma_route(&client::get_tags_route)
|
.ruma_route(&client::get_tags_route)
|
||||||
.ruma_route(&client::update_tag_route)
|
.ruma_route(&client::update_tag_route)
|
||||||
.ruma_route(&client::delete_tag_route)
|
.ruma_route(&client::delete_tag_route)
|
||||||
|
|||||||
+1
-1
@@ -117,7 +117,7 @@ prometheus.workspace = true
|
|||||||
lock_api.workspace = true
|
lock_api.workspace = true
|
||||||
hyper-util.workspace = true
|
hyper-util.workspace = true
|
||||||
resolvematrix.workspace = true
|
resolvematrix.workspace = true
|
||||||
openid.workspace = true
|
openidconnect.workspace = true
|
||||||
libmimalloc-sys.optional = true
|
libmimalloc-sys.optional = true
|
||||||
libmimalloc-sys.workspace = true
|
libmimalloc-sys.workspace = true
|
||||||
mimalloc.optional = true
|
mimalloc.optional = true
|
||||||
|
|||||||
+37
-5
@@ -23,6 +23,7 @@ use figment::providers::{Env, Format, Toml};
|
|||||||
pub use figment::{Figment, value::Value as FigmentValue};
|
pub use figment::{Figment, value::Value as FigmentValue};
|
||||||
use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter};
|
use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter};
|
||||||
use lettre::message::Mailbox;
|
use lettre::message::Mailbox;
|
||||||
|
use openidconnect::{Audience, ClientId, ClientSecret, Scope};
|
||||||
use regex::RegexSet;
|
use regex::RegexSet;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
|
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
|
||||||
@@ -919,6 +920,21 @@ pub struct Config {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub forget_forced_upon_leave: bool,
|
pub forget_forced_upon_leave: bool,
|
||||||
|
|
||||||
|
/// The maximum delay in milliseconds for delayed events (MSC4140). Setting
|
||||||
|
/// this or `delayed_events_max_scheduled` to 0 disables delayed events.
|
||||||
|
///
|
||||||
|
/// default: 604800000
|
||||||
|
#[serde(default = "default_delayed_events_max_delay_ms")]
|
||||||
|
pub delayed_events_max_delay_ms: u64,
|
||||||
|
|
||||||
|
/// The maximum number of delayed events each user can have scheduled at
|
||||||
|
/// once. Setting this or `delayed_events_max_delay_ms` to 0 disables
|
||||||
|
/// delayed events.
|
||||||
|
///
|
||||||
|
/// default: 100
|
||||||
|
#[serde(default = "default_delayed_events_max_scheduled")]
|
||||||
|
pub delayed_events_max_scheduled: u64,
|
||||||
|
|
||||||
/// Set this to true to require authentication when looking up user profiles
|
/// Set this to true to require authentication when looking up user profiles
|
||||||
/// through this server.
|
/// through this server.
|
||||||
///
|
///
|
||||||
@@ -2801,15 +2817,15 @@ pub struct OidcConfig {
|
|||||||
/// automatically fetch the identity provider's metadata from this URL.
|
/// automatically fetch the identity provider's metadata from this URL.
|
||||||
/// Generally you should set this to the base domain your identity provider
|
/// Generally you should set this to the base domain your identity provider
|
||||||
/// runs on.
|
/// runs on.
|
||||||
pub discovery_url: Url,
|
pub discovery_url: String,
|
||||||
|
|
||||||
/// The OAuth client ID for Continuwuity to use when communicating with the
|
/// The OAuth client ID for Continuwuity to use when communicating with the
|
||||||
/// identity provider.
|
/// identity provider.
|
||||||
pub client_id: String,
|
pub client_id: ClientId,
|
||||||
|
|
||||||
/// The OAuth client secret for Continuwuity to use when communicating with
|
/// The OAuth client secret for Continuwuity to use when communicating with
|
||||||
/// the identity provider.
|
/// the identity provider.
|
||||||
pub client_secret: Option<String>,
|
pub client_secret: Option<ClientSecret>,
|
||||||
|
|
||||||
/// A path to a file which Continuwuity will read the client secret from.
|
/// A path to a file which Continuwuity will read the client secret from.
|
||||||
/// If this option is set, it will override `client_secret`.
|
/// If this option is set, it will override `client_secret`.
|
||||||
@@ -2825,7 +2841,19 @@ pub struct OidcConfig {
|
|||||||
///
|
///
|
||||||
/// default: ["profile"]
|
/// default: ["profile"]
|
||||||
#[serde(default = "default_additional_scopes")]
|
#[serde(default = "default_additional_scopes")]
|
||||||
pub additional_scopes: Vec<String>,
|
pub additional_scopes: Vec<Scope>,
|
||||||
|
|
||||||
|
/// Additional trusted audiences that Continuwuity will accept in the `aud`
|
||||||
|
/// claim of the OIDC token returned by the IDP. If your identity
|
||||||
|
/// provider includes other values in the `aud` claim in addition to the
|
||||||
|
/// client ID, they must be listed here for Continuwuity to accept them.
|
||||||
|
///
|
||||||
|
/// Most deployments will not need to set this, because most identity
|
||||||
|
/// providers only include the client ID in the `aud` claim by default.
|
||||||
|
///
|
||||||
|
/// default: []
|
||||||
|
#[serde(default)]
|
||||||
|
pub additional_trusted_audiences: BTreeSet<Audience>,
|
||||||
|
|
||||||
/// The name of the identity provider. If this is set, the login page's
|
/// The name of the identity provider. If this is set, the login page's
|
||||||
/// button reads "Continue with <name>" instead of just "Continue".
|
/// button reads "Continue with <name>" instead of just "Continue".
|
||||||
@@ -3431,7 +3459,11 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
|
|||||||
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
|
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_additional_scopes() -> Vec<String> { vec!["profile".to_owned()] }
|
fn default_delayed_events_max_delay_ms() -> u64 { 7 * 24 * 60 * 60 * 1000 }
|
||||||
|
|
||||||
|
fn default_delayed_events_max_scheduled() -> u64 { 100 }
|
||||||
|
|
||||||
|
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
|
||||||
|
|
||||||
// NOTE: This must be declared *after* every config struct in this file. The
|
// NOTE: This must be declared *after* every config struct in this file. The
|
||||||
// example config generator writes sections in macro expansion order, and the
|
// example config generator writes sections in macro expansion order, and the
|
||||||
|
|||||||
@@ -69,9 +69,11 @@ impl Pdu {
|
|||||||
|
|
||||||
if context.user_id.is_none_or(|u| u != self.sender()) {
|
if context.user_id.is_none_or(|u| u != self.sender()) {
|
||||||
unsigned.remove("transaction_id");
|
unsigned.remove("transaction_id");
|
||||||
|
unsigned.remove("delay_id");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
unsigned.remove("transaction_id");
|
unsigned.remove("transaction_id");
|
||||||
|
unsigned.remove("delay_id");
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(expires_at) = self
|
if let Some(expires_at) = self
|
||||||
|
|||||||
@@ -53,5 +53,8 @@ pub fn unstable_features(experiments: &Experiments) -> BTreeMap<String, bool> {
|
|||||||
// Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354)
|
// Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354)
|
||||||
// Proposal merged, expected for spec v1.20/v2.0
|
// Proposal merged, expected for spec v1.20/v2.0
|
||||||
("org.matrix.msc4354".to_owned(), true),
|
("org.matrix.msc4354".to_owned(), true),
|
||||||
|
// Delayed events (https://github.com/matrix-org/matrix-spec-proposals/pull/4140)
|
||||||
|
// Proposal merged, expected for spec v1.20/v2.0
|
||||||
|
("org.matrix.msc4140.stable".to_owned(), true),
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
@@ -543,4 +543,20 @@ pub(super) static MAPS: &[Descriptor] = &[
|
|||||||
name: "websessionid_session",
|
name: "websessionid_session",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
},
|
},
|
||||||
|
Descriptor {
|
||||||
|
name: "delayid_scheduleddelayedevent",
|
||||||
|
..descriptor::RANDOM_SMALL
|
||||||
|
},
|
||||||
|
Descriptor {
|
||||||
|
name: "delayid_finalizeddelayedevent",
|
||||||
|
..descriptor::RANDOM_SMALL
|
||||||
|
},
|
||||||
|
Descriptor {
|
||||||
|
name: "useriddelayid",
|
||||||
|
..descriptor::RANDOM_SMALL
|
||||||
|
},
|
||||||
|
Descriptor {
|
||||||
|
name: "useridfinalizedtsdelayid",
|
||||||
|
..descriptor::RANDOM_SMALL
|
||||||
|
},
|
||||||
];
|
];
|
||||||
@@ -130,7 +130,10 @@ yansi.workspace = true
|
|||||||
lettre.workspace = true
|
lettre.workspace = true
|
||||||
resolvematrix.workspace = true
|
resolvematrix.workspace = true
|
||||||
serde_urlencoded.workspace = true
|
serde_urlencoded.workspace = true
|
||||||
openid.workspace = true
|
openidconnect.workspace = true
|
||||||
|
# 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
|
rand.workspace = true
|
||||||
|
|
||||||
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
||||||
@@ -140,6 +143,9 @@ sd-notify.optional = true
|
|||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|
||||||
|
[package.metadata.cargo-shear]
|
||||||
|
ignored = ["reqwest_0_12"]
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
opentelemetry.workspace = true
|
opentelemetry.workspace = true
|
||||||
rustls = { workspace = true, features = ["ring"] }
|
rustls = { workspace = true, features = ["ring"] }
|
||||||
@@ -44,3 +44,18 @@ impl reqwest::dns::Resolve for DnsResolver {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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?;
|
||||||
|
let addrs: Addrs = Box::new(SocketAddrs {
|
||||||
|
iter: lookup.iter().collect::<Vec<_>>().into_iter(),
|
||||||
|
});
|
||||||
|
Ok(addrs)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+163
-153
@@ -1,19 +1,26 @@
|
|||||||
use std::{
|
use std::{collections::HashMap, net::IpAddr, str::FromStr, sync::Arc, time::Duration};
|
||||||
collections::{HashMap, HashSet},
|
|
||||||
net::IpAddr,
|
|
||||||
str::FromStr,
|
|
||||||
sync::Arc,
|
|
||||||
};
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Result, SyncRwLock,
|
Result, SyncRwLock,
|
||||||
config::{OidcConfig, OidcProfileKeyImportMode},
|
config::{OidcConfig, OidcProfileKeyImportMode},
|
||||||
debug, err, error, info, utils, warn,
|
debug, err, error, info, warn,
|
||||||
};
|
};
|
||||||
use database::{Deserialized, Map};
|
use database::{Deserialized, Map};
|
||||||
use lettre::Address;
|
use lettre::Address;
|
||||||
use openid::{Claims as _, Options, StandardClaims, Token};
|
use openidconnect::{
|
||||||
|
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,
|
||||||
|
CoreJwsSigningAlgorithm, CoreProviderMetadata, CoreRevocableToken,
|
||||||
|
CoreRevocationErrorResponse, CoreTokenIntrospectionResponse, CoreTokenType,
|
||||||
|
},
|
||||||
|
reqwest,
|
||||||
|
};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedUserId, UserId,
|
OwnedUserId, UserId,
|
||||||
api::client::profile::PropagateTo,
|
api::client::profile::PropagateTo,
|
||||||
@@ -43,7 +50,6 @@ struct Data {
|
|||||||
openidsubjectprofilefield_url: Arc<Map>,
|
openidsubjectprofilefield_url: Arc<Map>,
|
||||||
}
|
}
|
||||||
struct Services {
|
struct Services {
|
||||||
client: Dep<client::Service>,
|
|
||||||
config: Dep<config::Service>,
|
config: Dep<config::Service>,
|
||||||
globals: Dep<globals::Service>,
|
globals: Dep<globals::Service>,
|
||||||
media: Dep<media::Service>,
|
media: Dep<media::Service>,
|
||||||
@@ -52,61 +58,56 @@ struct Services {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct OidcClient {
|
struct OidcClient {
|
||||||
client_secret: String,
|
|
||||||
config: OidcConfig,
|
config: OidcConfig,
|
||||||
client: SetOnce<SyncRwLock<Arc<IdpClient>>>,
|
client_secret: ClientSecret,
|
||||||
|
machine: SetOnce<SyncRwLock<Arc<OidcClientMachine>>>,
|
||||||
|
client: reqwest::Client,
|
||||||
}
|
}
|
||||||
|
|
||||||
type IdpClient = openid::Client<openid::Discovered, Claims>;
|
type OidcClientMachine = openidconnect::Client<
|
||||||
|
AllClaims,
|
||||||
|
CoreAuthDisplay,
|
||||||
|
CoreGenderClaim,
|
||||||
|
CoreJweContentEncryptionAlgorithm,
|
||||||
|
CoreJsonWebKey,
|
||||||
|
CoreAuthPrompt,
|
||||||
|
StandardErrorResponse<CoreErrorResponseType>,
|
||||||
|
StandardTokenResponse<
|
||||||
|
IdTokenFields<
|
||||||
|
AllClaims,
|
||||||
|
EmptyExtraTokenFields,
|
||||||
|
CoreGenderClaim,
|
||||||
|
CoreJweContentEncryptionAlgorithm,
|
||||||
|
CoreJwsSigningAlgorithm,
|
||||||
|
>,
|
||||||
|
CoreTokenType,
|
||||||
|
>,
|
||||||
|
CoreTokenIntrospectionResponse,
|
||||||
|
CoreRevocableToken,
|
||||||
|
CoreRevocationErrorResponse,
|
||||||
|
EndpointSet,
|
||||||
|
EndpointNotSet,
|
||||||
|
EndpointNotSet,
|
||||||
|
EndpointNotSet,
|
||||||
|
EndpointMaybeSet,
|
||||||
|
EndpointMaybeSet,
|
||||||
|
>;
|
||||||
|
|
||||||
|
pub type Claims = IdTokenClaims<AllClaims, CoreGenderClaim>;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
pub struct Claims {
|
pub struct AllClaims {
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
standard_claims: StandardClaims,
|
pub claims: HashMap<String, Value>,
|
||||||
|
|
||||||
#[serde(flatten)]
|
|
||||||
other_claims: HashMap<String, Value>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Claims {
|
impl AdditionalClaims for AllClaims {}
|
||||||
fn get(&self, key: &str) -> Option<&Value> { self.other_claims.get(key) }
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! standard {
|
|
||||||
($($field:ident: $type:ty),*$(,)?) => {
|
|
||||||
$(
|
|
||||||
fn $field(&self) -> $type {
|
|
||||||
self.standard_claims.$field()
|
|
||||||
}
|
|
||||||
)*
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl openid::Claims for Claims {
|
|
||||||
standard! {
|
|
||||||
userinfo: &openid::Userinfo,
|
|
||||||
c_hash: Option<&String>,
|
|
||||||
at_hash: Option<&String>,
|
|
||||||
iss: &Url,
|
|
||||||
sub: &str,
|
|
||||||
aud: &openid::SingleOrMultiple<String>,
|
|
||||||
exp: i64,
|
|
||||||
iat: i64,
|
|
||||||
auth_time: Option<i64>,
|
|
||||||
nonce: Option<&String>,
|
|
||||||
acr: Option<&String>,
|
|
||||||
amr: Option<&Vec<String>>,
|
|
||||||
azp: Option<&String>,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl openid::CompactJson for Claims {}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
pub struct PendingSession {
|
pub struct PendingSession {
|
||||||
pkce_verifier: String,
|
pkce_verifier: PkceCodeVerifier,
|
||||||
nonce: String,
|
nonce: Nonce,
|
||||||
csrf_token: String,
|
csrf_token: CsrfToken,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum SessionCompletionStatus {
|
pub enum SessionCompletionStatus {
|
||||||
@@ -134,7 +135,6 @@ impl crate::Service for Service {
|
|||||||
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||||
Ok(Arc::new(Self {
|
Ok(Arc::new(Self {
|
||||||
services: Services {
|
services: Services {
|
||||||
client: args.depend::<client::Service>("client"),
|
|
||||||
config: args.depend::<config::Service>("config"),
|
config: args.depend::<config::Service>("config"),
|
||||||
globals: args.depend::<globals::Service>("globals"),
|
globals: args.depend::<globals::Service>("globals"),
|
||||||
media: args.depend::<media::Service>("media"),
|
media: args.depend::<media::Service>("media"),
|
||||||
@@ -146,21 +146,43 @@ impl crate::Service for Service {
|
|||||||
openidsubject_localpart: args.db["openidsubject_localpart"].clone(),
|
openidsubject_localpart: args.db["openidsubject_localpart"].clone(),
|
||||||
openidsubjectprofilefield_url: args.db["openidsubjectprofilefield_url"].clone(),
|
openidsubjectprofilefield_url: args.db["openidsubjectprofilefield_url"].clone(),
|
||||||
},
|
},
|
||||||
client: args
|
client: args.server.config.oauth.oidc.as_ref().map(|config| -> Result<OidcClient> {
|
||||||
.server
|
Ok(OidcClient {
|
||||||
.config
|
config: config.clone(),
|
||||||
.oauth
|
client_secret: if let Some(client_secret_file) = &config.client_secret_file {
|
||||||
.oidc
|
std::fs::read_to_string(client_secret_file)
|
||||||
.clone()
|
.map(|client_secret| client_secret.trim().to_owned())
|
||||||
.map(Self::create_client)
|
.map(ClientSecret::new)
|
||||||
.transpose()?,
|
.map_err(|err| err!("Failed to read OIDC client secret file: {err}"))?
|
||||||
|
} else if let Some(client_secret) = &config.client_secret {
|
||||||
|
client_secret.clone()
|
||||||
|
} else {
|
||||||
|
// The config check function should cause an early exit before this happens
|
||||||
|
panic!("neither client secret or client secret file were set");
|
||||||
|
},
|
||||||
|
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::Service>("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))
|
||||||
|
.pool_idle_timeout(Duration::from_secs(args.server.config.request_idle_timeout))
|
||||||
|
.pool_max_idle_per_host(args.server.config.request_idle_per_host.into())
|
||||||
|
.user_agent(conduwuit::user_agent())
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.danger_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)
|
||||||
|
.build()
|
||||||
|
.expect("client should build")
|
||||||
|
})}
|
||||||
|
).transpose()?,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn worker(self: Arc<Self>) -> Result {
|
async fn worker(self: Arc<Self>) -> Result {
|
||||||
if let Some(OidcClient { client, .. }) = &self.client {
|
if let Some(OidcClient { machine, .. }) = &self.client {
|
||||||
let discovered = self.discover().await?;
|
let discovered = self.discover().await?;
|
||||||
client
|
machine
|
||||||
.set(SyncRwLock::new(Arc::new(discovered)))
|
.set(SyncRwLock::new(Arc::new(discovered)))
|
||||||
.expect("machine should be empty");
|
.expect("machine should be empty");
|
||||||
}
|
}
|
||||||
@@ -176,36 +198,13 @@ impl Service {
|
|||||||
// into the media repository. Keep this synced with the list in the
|
// into the media repository. Keep this synced with the list in the
|
||||||
// doc comment for `profile_key_map` in the config.
|
// doc comment for `profile_key_map` in the config.
|
||||||
const IMAGE_PROFILE_KEYS: &[&str] = &["avatar_url", "chat.commet.profile_banner"];
|
const IMAGE_PROFILE_KEYS: &[&str] = &["avatar_url", "chat.commet.profile_banner"];
|
||||||
const NONCE_SIZE: usize = 32;
|
|
||||||
const SERVER_MISCONFIGURED: &str =
|
const SERVER_MISCONFIGURED: &str =
|
||||||
"Identity server is misconfigured. Contact your homeserver's administrator.";
|
"Identity server is misconfigured. Contact your homeserver's administrator.";
|
||||||
|
|
||||||
fn create_nonce() -> String { utils::random_string(Self::NONCE_SIZE) }
|
|
||||||
|
|
||||||
fn create_client(config: OidcConfig) -> Result<OidcClient> {
|
|
||||||
let 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_err(|err| err!("Failed to read OIDC client secret file: {err}"))?
|
|
||||||
} else if let Some(client_secret) = &config.client_secret {
|
|
||||||
client_secret.clone()
|
|
||||||
} else {
|
|
||||||
// The config check function should cause an early exit before this
|
|
||||||
// happens
|
|
||||||
panic!("neither client secret or client secret file were set");
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(OidcClient {
|
|
||||||
client_secret,
|
|
||||||
config,
|
|
||||||
client: SetOnce::new(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn enabled(&self) -> bool { self.client.is_some() }
|
pub fn enabled(&self) -> bool { self.client.is_some() }
|
||||||
|
|
||||||
async fn discover(&self) -> Result<IdpClient> {
|
async fn discover(&self) -> Result<OidcClientMachine> {
|
||||||
let OidcClient { config, client_secret, .. } =
|
let OidcClient { config, client_secret, client, .. } =
|
||||||
self.client.as_ref().expect("oidc should be configured");
|
self.client.as_ref().expect("oidc should be configured");
|
||||||
|
|
||||||
let redirect_url = self
|
let redirect_url = self
|
||||||
@@ -215,15 +214,20 @@ impl Service {
|
|||||||
.join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX))
|
.join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX))
|
||||||
.expect("redirect url should be valid");
|
.expect("redirect url should be valid");
|
||||||
|
|
||||||
IdpClient::discover_with_client(
|
let provider_metadata = CoreProviderMetadata::discover_async(
|
||||||
self.services.client.external_resource.clone(),
|
IssuerUrl::new(config.discovery_url.clone())
|
||||||
config.client_id.clone(),
|
.map_err(|err| err!("Failed to parse OIDC discovery URL: {err}"))?,
|
||||||
Some(client_secret.clone()),
|
client,
|
||||||
Some(redirect_url.to_string()),
|
|
||||||
config.discovery_url.clone(),
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))
|
.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<String> {
|
pub fn provider_name(&self) -> Option<String> {
|
||||||
@@ -252,32 +256,29 @@ impl Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn begin_session(&self, prompt: Option<openid::Prompt>) -> (PendingSession, Url) {
|
pub async fn begin_session(&self, prompt: Option<CoreAuthPrompt>) -> (PendingSession, Url) {
|
||||||
let OidcClient { client, config, .. } =
|
let OidcClient { machine, config, .. } =
|
||||||
self.client.as_ref().expect("oidc should be configured");
|
self.client.as_ref().expect("oidc should be configured");
|
||||||
let client = client.wait().await.read().clone();
|
let machine = machine.wait().await.read().clone();
|
||||||
|
|
||||||
let csrf_token = Self::create_nonce();
|
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||||
let nonce = Self::create_nonce();
|
|
||||||
|
|
||||||
let (auth_url, pkce) = client.auth_url_with_new_pkce(&Options {
|
let mut auth_url = machine
|
||||||
// The client will add the `openid` scope for us.
|
.authorize_url(
|
||||||
scope: Some(config.additional_scopes.join(" ")),
|
CoreAuthenticationFlow::AuthorizationCode,
|
||||||
state: Some(csrf_token.clone()),
|
CsrfToken::new_random,
|
||||||
nonce: Some(nonce.clone()),
|
Nonce::new_random,
|
||||||
prompt: prompt.map(|prompt| HashSet::from_iter([prompt])),
|
|
||||||
|
|
||||||
..Default::default()
|
|
||||||
});
|
|
||||||
|
|
||||||
(
|
|
||||||
PendingSession {
|
|
||||||
pkce_verifier: pkce.code_verifier().to_owned(),
|
|
||||||
nonce,
|
|
||||||
csrf_token,
|
|
||||||
},
|
|
||||||
auth_url,
|
|
||||||
)
|
)
|
||||||
|
.add_scopes(config.additional_scopes.iter().cloned())
|
||||||
|
.set_pkce_challenge(pkce_challenge);
|
||||||
|
|
||||||
|
if let Some(prompt) = prompt {
|
||||||
|
auth_url = auth_url.add_prompt(prompt);
|
||||||
|
}
|
||||||
|
|
||||||
|
let (auth_url, csrf_token, nonce) = auth_url.url();
|
||||||
|
|
||||||
|
(PendingSession { pkce_verifier, nonce, csrf_token }, auth_url)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn exchange_code(
|
pub async fn exchange_code(
|
||||||
@@ -285,77 +286,78 @@ impl Service {
|
|||||||
session: PendingSession,
|
session: PendingSession,
|
||||||
response: AuthorizationCodeResponse,
|
response: AuthorizationCodeResponse,
|
||||||
) -> Result<Claims, &'static str> {
|
) -> Result<Claims, &'static str> {
|
||||||
let Some(OidcClient { client, .. }) = self.client.as_ref() else {
|
let Some(OidcClient { machine, client, config, .. }) = self.client.as_ref() else {
|
||||||
return Err("Delegated authentication is not enabled on this server.");
|
return Err("Delegated authentication is not enabled on this server.");
|
||||||
};
|
};
|
||||||
|
|
||||||
let current = client.wait().await.read().clone();
|
let current = machine.wait().await.read().clone();
|
||||||
|
|
||||||
if session.csrf_token != response.state {
|
if session.csrf_token.into_secret() != response.state {
|
||||||
return Err("State mismatch.");
|
return Err("State mismatch.");
|
||||||
}
|
}
|
||||||
|
|
||||||
let token_response = current
|
let token_response = current
|
||||||
.request_token_pkce(&response.code, Some(&session.pkce_verifier))
|
.exchange_code(AuthorizationCode::new(response.code))
|
||||||
|
.expect("machine should be configured correctly")
|
||||||
|
.set_pkce_verifier(session.pkce_verifier)
|
||||||
|
.request_async(client)
|
||||||
.await
|
.await
|
||||||
.map(Token::<Claims>::from)
|
|
||||||
.map_err(|err| {
|
.map_err(|err| {
|
||||||
error!(error=?err, "Failed to exchange OIDC authorization code");
|
error!(error=?err, "Failed to exchange OIDC authorization code");
|
||||||
"Code exchange failed. The identity provider may be unreachable. Contact your \
|
"Code exchange failed. The identity provider may be unreachable. Contact your \
|
||||||
homeserver's administrator."
|
homeserver's administrator."
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let Some(mut id_token) = token_response.id_token else {
|
let Some(id_token) = token_response.id_token() else {
|
||||||
error!("Identity server did not return an id token");
|
error!("Identity server did not return an id token");
|
||||||
return Err(Self::SERVER_MISCONFIGURED);
|
return Err(Self::SERVER_MISCONFIGURED);
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Err(err) = current.decode_token(&mut id_token) {
|
let verify = |machine: &OidcClientMachine| {
|
||||||
error!(error=?err, "Failed to decode ID token");
|
let verifier =
|
||||||
return Err(Self::SERVER_MISCONFIGURED);
|
machine
|
||||||
}
|
.id_token_verifier()
|
||||||
|
.set_other_audience_verifier_fn(|audience| {
|
||||||
|
config.additional_trusted_audiences.contains(audience)
|
||||||
|
});
|
||||||
|
|
||||||
let verify = |client: &IdpClient| {
|
id_token
|
||||||
client.validate_token(&id_token, Some(session.nonce.as_str()), None)
|
.claims(&verifier, &session.nonce)
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut result = verify(¤t);
|
let mut result = verify(¤t);
|
||||||
|
|
||||||
if matches!(
|
if matches!(
|
||||||
result,
|
result,
|
||||||
Err(openid::error::Error::Jose(openid::error::Jose::ValidationError(
|
Err(ClaimsVerificationError::SignatureVerification(
|
||||||
openid::biscuit::errors::ValidationError::KeyNotFound
|
SignatureVerificationError::NoMatchingKey
|
||||||
)))
|
))
|
||||||
) {
|
) {
|
||||||
match self.discover().await {
|
match self.discover().await {
|
||||||
| Ok(discovered) => {
|
| Ok(discovered) => {
|
||||||
info!("Refreshed OIDC provider metadata after an unknown signing key");
|
info!("Refreshed OIDC provider metadata after an unknown signing key");
|
||||||
result = verify(&discovered);
|
result = verify(&discovered);
|
||||||
*client.wait().await.write() = Arc::new(discovered);
|
*machine.wait().await.write() = Arc::new(discovered);
|
||||||
},
|
},
|
||||||
| Err(err) => warn!("Failed to refresh OIDC provider metadata: {err}"),
|
| Err(err) => warn!("Failed to refresh OIDC provider metadata: {err}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match result {
|
let claims = result.map_err(|err| {
|
||||||
| Ok(()) => {
|
error!("Failed to verify id token claims: {err}");
|
||||||
let (_, claims) = id_token.unwrap_decoded();
|
Self::SERVER_MISCONFIGURED
|
||||||
|
})?;
|
||||||
|
|
||||||
info!(subject = claims.sub(), "Authenticated subject");
|
info!(subject = claims.subject().as_str(), "Authenticated subject");
|
||||||
|
|
||||||
Ok(claims)
|
Ok(claims)
|
||||||
},
|
|
||||||
| Err(err) => {
|
|
||||||
error!("Failed to verify id token claims: {err}");
|
|
||||||
Err(Self::SERVER_MISCONFIGURED)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self, claims), fields(subject = claims.sub().to_owned()))]
|
#[tracing::instrument(skip(self, claims), fields(subject = claims.subject().to_string()))]
|
||||||
pub async fn complete_session(
|
pub async fn complete_session(
|
||||||
&self,
|
&self,
|
||||||
claims: Claims,
|
claims: &Claims,
|
||||||
supplied_user_id: Option<OwnedUserId>,
|
supplied_user_id: Option<OwnedUserId>,
|
||||||
client_ip: &IpAddr,
|
client_ip: &IpAddr,
|
||||||
) -> Result<SessionCompletionStatus, &'static str> {
|
) -> Result<SessionCompletionStatus, &'static str> {
|
||||||
@@ -363,14 +365,21 @@ impl Service {
|
|||||||
return Err("Delegated authentication is not enabled on this server.");
|
return Err("Delegated authentication is not enabled on this server.");
|
||||||
};
|
};
|
||||||
|
|
||||||
debug!(claims = ?claims.other_claims, "Got claims from the identity provider");
|
// this is a truly awful hack but we really need all the claims in a map
|
||||||
|
let all_claims = serde_json::to_value(claims)
|
||||||
|
.expect("should be able to serialize claims")
|
||||||
|
.as_object()
|
||||||
|
.expect("claims should be an object")
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
let subject = claims.sub().to_owned();
|
debug!(?all_claims, "Got claims from the identity provider");
|
||||||
|
|
||||||
|
let subject = claims.subject().as_str();
|
||||||
|
|
||||||
let user_id = if let Ok(localpart) = self
|
let user_id = if let Ok(localpart) = self
|
||||||
.db
|
.db
|
||||||
.openidsubject_localpart
|
.openidsubject_localpart
|
||||||
.get(&subject)
|
.get(subject)
|
||||||
.await
|
.await
|
||||||
.deserialized::<String>()
|
.deserialized::<String>()
|
||||||
{
|
{
|
||||||
@@ -382,7 +391,7 @@ impl Service {
|
|||||||
} else {
|
} else {
|
||||||
return Ok(SessionCompletionStatus::NeedsUserId);
|
return Ok(SessionCompletionStatus::NeedsUserId);
|
||||||
}
|
}
|
||||||
} else if let Some(preferred_username) = claims
|
} else if let Some(preferred_username) = all_claims
|
||||||
.get(&config.preferred_username_claim)
|
.get(&config.preferred_username_claim)
|
||||||
.and_then(|claim| claim.as_str())
|
.and_then(|claim| claim.as_str())
|
||||||
{
|
{
|
||||||
@@ -426,7 +435,7 @@ impl Service {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
self.link_user(&user_id, &subject);
|
self.link_user(&user_id, subject);
|
||||||
|
|
||||||
// Import profile fields
|
// Import profile fields
|
||||||
if matches!(config.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin)
|
if matches!(config.profile_key_import_mode, OidcProfileKeyImportMode::OnLogin)
|
||||||
@@ -436,7 +445,7 @@ impl Service {
|
|||||||
) && new_account_registered)
|
) && new_account_registered)
|
||||||
{
|
{
|
||||||
if let Some(email_claim) = &config.email_claim {
|
if let Some(email_claim) = &config.email_claim {
|
||||||
if let Some(email) = claims.get(email_claim).and_then(|email| email.as_str())
|
if let Some(email) = claims.email().map(|email| email.as_str())
|
||||||
&& let Ok(address) = Address::from_str(email)
|
&& let Ok(address) = Address::from_str(email)
|
||||||
{
|
{
|
||||||
if let Err(err) = self
|
if let Err(err) = self
|
||||||
@@ -456,6 +465,7 @@ impl Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let user_id = user_id.clone();
|
let user_id = user_id.clone();
|
||||||
|
let subject = claims.subject().to_string();
|
||||||
let profile_key_map = config.profile_key_map.clone();
|
let profile_key_map = config.profile_key_map.clone();
|
||||||
let openidsubjectprofilefield_url = self.db.openidsubjectprofilefield_url.clone();
|
let openidsubjectprofilefield_url = self.db.openidsubjectprofilefield_url.clone();
|
||||||
let users = self.services.users.clone();
|
let users = self.services.users.clone();
|
||||||
@@ -465,7 +475,7 @@ impl Service {
|
|||||||
// TODO: once we get support for full profile replacement, use
|
// TODO: once we get support for full profile replacement, use
|
||||||
// that logic instead
|
// that logic instead
|
||||||
for (field, claim) in &profile_key_map {
|
for (field, claim) in &profile_key_map {
|
||||||
let Some(value) = claims.get(claim).cloned() else {
|
let Some(value) = all_claims.get(claim).cloned() else {
|
||||||
warn!(?field, ?claim, "IDP provided no value for this mapped claim");
|
warn!(?field, ?claim, "IDP provided no value for this mapped claim");
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,596 @@
|
|||||||
|
mod submission_queue;
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::BTreeMap,
|
||||||
|
fmt::Write,
|
||||||
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
},
|
||||||
|
time::{Duration, SystemTime},
|
||||||
|
};
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use conduwuit::{
|
||||||
|
Err, Error, Result, Server, debug_warn, err, error,
|
||||||
|
matrix::pdu::{PartialPdu, sticky},
|
||||||
|
utils::{
|
||||||
|
self, MutexMap,
|
||||||
|
stream::{ReadyExt, TryIgnore},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use database::{Deserialized, Ignore, Interfix, Json, Map};
|
||||||
|
use futures::StreamExt;
|
||||||
|
use http::StatusCode;
|
||||||
|
use loole::Sender;
|
||||||
|
use ruma::{
|
||||||
|
DeviceId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedTransactionId,
|
||||||
|
OwnedUserId, TransactionId, UserId,
|
||||||
|
api::{
|
||||||
|
client::delayed_events::{
|
||||||
|
DelayedEvent, DelayedEventCancelled, DelayedEventError, DelayedEventOutcome,
|
||||||
|
DelayedEventSent, FinalizedDelayedEvent as FinalizedDelayedEventData,
|
||||||
|
update_delayed_event::UpdateAction,
|
||||||
|
},
|
||||||
|
error::{ErrorKind, LimitExceededErrorData, RetryAfter, StandardErrorBody},
|
||||||
|
},
|
||||||
|
events::{AnyTimelineEventContent, TimelineEventType, sticky::StickyDurationMs},
|
||||||
|
serde::Raw,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use submission_queue::{QueueUpdate, SubmissionQueue};
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
|
use crate::{Dep, config, rooms, transactions, users};
|
||||||
|
|
||||||
|
const DELAY_ID_LENGTH: usize = 32;
|
||||||
|
|
||||||
|
/// The retention limits for finalized delayed events recommended by MSC4140.
|
||||||
|
const FINALIZED_RETENTION: Duration = Duration::from_hours(7 * 24);
|
||||||
|
const MAX_FINALIZED_PER_USER: usize = 1000;
|
||||||
|
|
||||||
|
struct Data {
|
||||||
|
delayid_scheduleddelayedevent: Arc<Map>,
|
||||||
|
delayid_finalizeddelayedevent: Arc<Map>,
|
||||||
|
useriddelayid: Arc<Map>,
|
||||||
|
useridfinalizedtsdelayid: Arc<Map>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Services {
|
||||||
|
server: Arc<Server>,
|
||||||
|
config: Dep<config::Service>,
|
||||||
|
state: Dep<rooms::state::Service>,
|
||||||
|
timeline: Dep<rooms::timeline::Service>,
|
||||||
|
transactions: Dep<transactions::Service>,
|
||||||
|
users: Dep<users::Service>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Service {
|
||||||
|
db: Data,
|
||||||
|
services: Services,
|
||||||
|
|
||||||
|
/// Ensures each delayed event is only finalized once.
|
||||||
|
event_locks: MutexMap<String, ()>,
|
||||||
|
transaction_locks: MutexMap<OwnedUserId, ()>,
|
||||||
|
submission_queue: Mutex<SubmissionQueue>,
|
||||||
|
submission_queue_sender: Sender<QueueUpdate>,
|
||||||
|
interrupt: Sender<()>,
|
||||||
|
mem_usage: AtomicUsize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl crate::Service for Service {
|
||||||
|
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||||
|
let (sender, receiver) = loole::unbounded();
|
||||||
|
let (interrupt_sender, interrupt_receiver) = loole::bounded(1);
|
||||||
|
|
||||||
|
Ok(Arc::new(Self {
|
||||||
|
db: Data {
|
||||||
|
delayid_scheduleddelayedevent: args.db["delayid_scheduleddelayedevent"].clone(),
|
||||||
|
delayid_finalizeddelayedevent: args.db["delayid_finalizeddelayedevent"].clone(),
|
||||||
|
useriddelayid: args.db["useriddelayid"].clone(),
|
||||||
|
useridfinalizedtsdelayid: args.db["useridfinalizedtsdelayid"].clone(),
|
||||||
|
},
|
||||||
|
services: Services {
|
||||||
|
server: args.server.clone(),
|
||||||
|
config: args.depend::<config::Service>("config"),
|
||||||
|
state: args.depend::<rooms::state::Service>("rooms::state"),
|
||||||
|
timeline: args.depend::<rooms::timeline::Service>("rooms::timeline"),
|
||||||
|
transactions: args.depend::<transactions::Service>("transactions"),
|
||||||
|
users: args.depend::<users::Service>("users"),
|
||||||
|
},
|
||||||
|
event_locks: MutexMap::new(),
|
||||||
|
transaction_locks: MutexMap::new(),
|
||||||
|
submission_queue: Mutex::new(SubmissionQueue::new(receiver, interrupt_receiver)),
|
||||||
|
submission_queue_sender: sender,
|
||||||
|
interrupt: interrupt_sender,
|
||||||
|
mem_usage: AtomicUsize::new(0),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn worker(self: Arc<Self>) -> Result { submission_queue::worker(&self).await }
|
||||||
|
|
||||||
|
fn interrupt(&self) { self.interrupt.try_send(()).ok(); }
|
||||||
|
|
||||||
|
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
|
||||||
|
|
||||||
|
async fn memory_usage(&self, out: &mut (dyn Write + Send)) -> Result {
|
||||||
|
let mem_usage = self.mem_usage.load(Ordering::Relaxed);
|
||||||
|
writeln!(out, "submission_queue: {mem_usage} bytes")?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NewDelayedEvent {
|
||||||
|
pub room_id: OwnedRoomId,
|
||||||
|
pub event_type: TimelineEventType,
|
||||||
|
pub state_key: Option<String>,
|
||||||
|
pub content: Raw<AnyTimelineEventContent>,
|
||||||
|
pub delay: Duration,
|
||||||
|
pub timestamp: Option<MilliSecondsSinceUnixEpoch>,
|
||||||
|
pub sticky_duration_ms: Option<StickyDurationMs>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
struct ScheduledDelayedEvent {
|
||||||
|
user_id: OwnedUserId,
|
||||||
|
room_id: OwnedRoomId,
|
||||||
|
event_type: TimelineEventType,
|
||||||
|
state_key: Option<String>,
|
||||||
|
content: Raw<AnyTimelineEventContent>,
|
||||||
|
delay: Duration,
|
||||||
|
delayed_since: SystemTime,
|
||||||
|
timestamp: Option<MilliSecondsSinceUnixEpoch>,
|
||||||
|
sticky_duration_ms: Option<StickyDurationMs>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ScheduledDelayedEvent {
|
||||||
|
fn send_time(&self) -> SystemTime {
|
||||||
|
// Can't overflow on Unix, where SystemTime holds i64 seconds and the
|
||||||
|
// delay is at most u64::MAX milliseconds.
|
||||||
|
self.delayed_since
|
||||||
|
.checked_add(self.delay)
|
||||||
|
.expect("send time must not overflow SystemTime")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn into_delayed_event(self, delay_id: String) -> DelayedEvent {
|
||||||
|
DelayedEvent::new(
|
||||||
|
delay_id,
|
||||||
|
self.room_id,
|
||||||
|
self.event_type,
|
||||||
|
self.state_key,
|
||||||
|
self.content,
|
||||||
|
self.delay,
|
||||||
|
MilliSecondsSinceUnixEpoch::from_system_time(self.delayed_since)
|
||||||
|
.unwrap_or_else(MilliSecondsSinceUnixEpoch::now),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
struct FinalizedDelayedEvent {
|
||||||
|
event: ScheduledDelayedEvent,
|
||||||
|
finalized: FinalizedDelayedEventData,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FinalizedDelayedEvent {
|
||||||
|
fn into_delayed_event(self, delay_id: String) -> DelayedEvent {
|
||||||
|
let mut event = self.event.into_delayed_event(delay_id);
|
||||||
|
event.finalized = Some(self.finalized);
|
||||||
|
event
|
||||||
|
}
|
||||||
|
|
||||||
|
fn satisfies(&self, action: &UpdateAction) -> bool {
|
||||||
|
matches!(
|
||||||
|
(action, &self.finalized.outcome),
|
||||||
|
(UpdateAction::Send, DelayedEventOutcome::Sent(_))
|
||||||
|
| (
|
||||||
|
UpdateAction::Cancel,
|
||||||
|
DelayedEventOutcome::Cancelled(_) | DelayedEventOutcome::Error(_)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service {
|
||||||
|
/// Returns the maximum delay users may request, or `None` if delayed events
|
||||||
|
/// are disabled.
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_delay(&self) -> Option<Duration> {
|
||||||
|
let config = &self.services.config;
|
||||||
|
(config.delayed_events_max_delay_ms > 0 && config.delayed_events_max_scheduled > 0)
|
||||||
|
.then(|| Duration::from_millis(config.delayed_events_max_delay_ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stores a new delayed event and queues it for sending, returning its
|
||||||
|
/// delay ID. Retries with the same transaction ID return the same delay ID.
|
||||||
|
pub async fn schedule(
|
||||||
|
&self,
|
||||||
|
user_id: &UserId,
|
||||||
|
device_id: Option<&DeviceId>,
|
||||||
|
txn_id: &TransactionId,
|
||||||
|
event: NewDelayedEvent,
|
||||||
|
) -> Result<String> {
|
||||||
|
let txn_id: OwnedTransactionId = format!("delayed_event/{txn_id}").into();
|
||||||
|
let _lock = self.transaction_locks.lock(user_id).await;
|
||||||
|
|
||||||
|
if let Ok(response) = self
|
||||||
|
.services
|
||||||
|
.transactions
|
||||||
|
.get_client_txn(user_id, device_id, &txn_id)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
return utils::string_from_bytes(&response)
|
||||||
|
.map_err(|e| err!(Database("Invalid delay ID in transaction data: {e}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.check_scheduled_limit(user_id).await?;
|
||||||
|
|
||||||
|
let delay_id = utils::random_string(DELAY_ID_LENGTH);
|
||||||
|
let event = ScheduledDelayedEvent {
|
||||||
|
user_id: user_id.to_owned(),
|
||||||
|
room_id: event.room_id,
|
||||||
|
event_type: event.event_type,
|
||||||
|
state_key: event.state_key,
|
||||||
|
content: event.content,
|
||||||
|
delay: event.delay,
|
||||||
|
delayed_since: SystemTime::now(),
|
||||||
|
timestamp: event.timestamp,
|
||||||
|
sticky_duration_ms: event.sticky_duration_ms,
|
||||||
|
};
|
||||||
|
let send_time = event.send_time();
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.delayid_scheduleddelayedevent
|
||||||
|
.raw_put(&delay_id, Json(&event));
|
||||||
|
self.db
|
||||||
|
.useriddelayid
|
||||||
|
.put_raw((user_id, delay_id.as_str()), []);
|
||||||
|
self.services.transactions.add_client_txnid(
|
||||||
|
user_id,
|
||||||
|
device_id,
|
||||||
|
&txn_id,
|
||||||
|
delay_id.as_bytes(),
|
||||||
|
);
|
||||||
|
|
||||||
|
self.submission_queue_sender
|
||||||
|
.send(QueueUpdate::Schedule(send_time, delay_id.clone()))
|
||||||
|
.map_err(|_| err!("The delayed events worker is not running"))?;
|
||||||
|
|
||||||
|
Ok(delay_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns `M_LIMIT_EXCEEDED` if the user already has the maximum number of
|
||||||
|
/// delayed events scheduled, with `Retry-After` set to when the next one is
|
||||||
|
/// due.
|
||||||
|
async fn check_scheduled_limit(&self, user_id: &UserId) -> Result {
|
||||||
|
let max_scheduled = usize::try_from(self.services.config.delayed_events_max_scheduled)
|
||||||
|
.unwrap_or(usize::MAX);
|
||||||
|
|
||||||
|
let send_times: Vec<SystemTime> = self
|
||||||
|
.user_delay_ids(user_id)
|
||||||
|
.filter_map(async |delay_id| {
|
||||||
|
self.get_scheduled(&delay_id)
|
||||||
|
.await
|
||||||
|
.map(|event| event.send_time())
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if send_times.len() < max_scheduled {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let retry_after = send_times
|
||||||
|
.iter()
|
||||||
|
.min()
|
||||||
|
.and_then(|time| time.duration_since(SystemTime::now()).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let retry_after = Duration::from_secs(
|
||||||
|
retry_after
|
||||||
|
.as_millis()
|
||||||
|
// MSC4140 requires rounding up to the nearest second.
|
||||||
|
.div_ceil(1000)
|
||||||
|
.try_into()
|
||||||
|
.unwrap_or(u64::MAX),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut data = LimitExceededErrorData::new();
|
||||||
|
data.retry_after = Some(RetryAfter::Delay(retry_after));
|
||||||
|
|
||||||
|
Err(Error::Request(
|
||||||
|
ErrorKind::LimitExceeded(data),
|
||||||
|
"The maximum number of delayed events has been reached.".into(),
|
||||||
|
StatusCode::TOO_MANY_REQUESTS,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restarts, sends or cancels one of the user's delayed events. Repeating
|
||||||
|
/// an action on an event that was already finalized the same way succeeds,
|
||||||
|
/// and conflicting actions return 409.
|
||||||
|
pub async fn update(&self, user_id: &UserId, delay_id: &str, action: UpdateAction) -> Result {
|
||||||
|
let _lock = self.event_locks.lock(delay_id).await;
|
||||||
|
|
||||||
|
if let Some(mut event) = self.get_scheduled(delay_id).await {
|
||||||
|
if event.user_id != user_id {
|
||||||
|
return Err!(Request(NotFound("No delayed event with this ID was found.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
return match action {
|
||||||
|
| UpdateAction::Restart => {
|
||||||
|
event.delayed_since = SystemTime::now();
|
||||||
|
self.db
|
||||||
|
.delayid_scheduleddelayedevent
|
||||||
|
.raw_put(delay_id, Json(&event));
|
||||||
|
self.queue(QueueUpdate::Schedule(event.send_time(), delay_id.to_owned()));
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
| UpdateAction::Send => {
|
||||||
|
// On error, the event stays scheduled, as recommended by
|
||||||
|
// MSC4140.
|
||||||
|
let event_id = self.send(delay_id, &event).await?;
|
||||||
|
self.finalize(
|
||||||
|
delay_id,
|
||||||
|
event,
|
||||||
|
DelayedEventOutcome::Sent(DelayedEventSent::new(event_id)),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
| UpdateAction::Cancel => {
|
||||||
|
self.finalize(
|
||||||
|
delay_id,
|
||||||
|
event,
|
||||||
|
DelayedEventOutcome::Cancelled(DelayedEventCancelled::new()),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
| _ => Err!(Request(InvalidParam("Unknown delayed event action."))),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.get_finalized(delay_id).await {
|
||||||
|
| Some(finalized) if finalized.event.user_id == user_id =>
|
||||||
|
if finalized.satisfies(&action) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(Error::Request(
|
||||||
|
ErrorKind::Unknown,
|
||||||
|
"The delayed event has already been finalized with a different outcome."
|
||||||
|
.into(),
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
))
|
||||||
|
},
|
||||||
|
| _ => Err!(Request(NotFound("No delayed event with this ID was found."))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns one of the user's delayed events, whether scheduled or
|
||||||
|
/// finalized.
|
||||||
|
pub async fn get(&self, user_id: &UserId, delay_id: &str) -> Result<DelayedEvent> {
|
||||||
|
if let Some(event) = self.get_scheduled(delay_id).await
|
||||||
|
&& event.user_id == user_id
|
||||||
|
{
|
||||||
|
return Ok(event.into_delayed_event(delay_id.to_owned()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(finalized) = self.get_finalized(delay_id).await
|
||||||
|
&& finalized.event.user_id == user_id
|
||||||
|
{
|
||||||
|
return Ok(finalized.into_delayed_event(delay_id.to_owned()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Err!(Request(NotFound("No delayed event with this ID was found.")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes a user's scheduled delayed events without keeping them for
|
||||||
|
/// lookup, for account deactivation.
|
||||||
|
pub async fn remove_all_for_user(&self, user_id: &UserId) {
|
||||||
|
self.user_delay_ids(user_id)
|
||||||
|
.for_each(async |delay_id| {
|
||||||
|
let _lock = self.event_locks.lock(delay_id.as_str()).await;
|
||||||
|
self.db
|
||||||
|
.delayid_scheduleddelayedevent
|
||||||
|
.remove(delay_id.as_str());
|
||||||
|
self.db.useriddelayid.del((user_id, delay_id.as_str()));
|
||||||
|
self.queue(QueueUpdate::Remove(delay_id));
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates the worker's submission queue. This only fails if the worker has
|
||||||
|
/// stopped, and it rebuilds the queue from the database when it starts.
|
||||||
|
fn queue(&self, update: QueueUpdate) { self.submission_queue_sender.send(update).ok(); }
|
||||||
|
|
||||||
|
/// Sends the delayed event if it is due, otherwise requeues it for its send
|
||||||
|
/// time. Called by the worker, which records any error on the finalized
|
||||||
|
/// event as there is no client to return it to.
|
||||||
|
async fn send_if_due(&self, delay_id: &str) {
|
||||||
|
let _lock = self.event_locks.lock(delay_id).await;
|
||||||
|
|
||||||
|
let Some(event) = self.get_scheduled(delay_id).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let send_time = event.send_time();
|
||||||
|
if send_time > SystemTime::now() {
|
||||||
|
self.queue(QueueUpdate::Schedule(send_time, delay_id.to_owned()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let outcome = match self.send(delay_id, &event).await {
|
||||||
|
| Ok(event_id) => DelayedEventOutcome::Sent(DelayedEventSent::new(event_id)),
|
||||||
|
| Err(error) => {
|
||||||
|
debug_warn!(%delay_id, %error, "Failed to send delayed event");
|
||||||
|
let error = StandardErrorBody::new(error.kind(), error.message());
|
||||||
|
DelayedEventOutcome::Error(DelayedEventError::new(error))
|
||||||
|
},
|
||||||
|
};
|
||||||
|
self.finalize(delay_id, event, outcome).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends the delayed event into its room with the same checks as a normal
|
||||||
|
/// send, using the room state at the time of sending.
|
||||||
|
async fn send(&self, delay_id: &str, event: &ScheduledDelayedEvent) -> Result<OwnedEventId> {
|
||||||
|
if self.services.users.is_suspended(&event.user_id).await? {
|
||||||
|
return Err!(Request(UserSuspended(
|
||||||
|
"You cannot perform this action while suspended."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = event.content.clone().into_json();
|
||||||
|
|
||||||
|
let redacts = (event.event_type == TimelineEventType::RoomRedaction)
|
||||||
|
.then(|| serde_json::from_str::<MaybeRedaction>(content.get()).ok())
|
||||||
|
.flatten()
|
||||||
|
.and_then(|redaction| redaction.redacts);
|
||||||
|
|
||||||
|
let mut unsigned = BTreeMap::new();
|
||||||
|
unsigned.insert("delay_id".to_owned(), delay_id.into());
|
||||||
|
|
||||||
|
let partial_pdu = PartialPdu {
|
||||||
|
event_type: event.event_type.clone(),
|
||||||
|
content,
|
||||||
|
state_key: event.state_key.clone().map(Into::into),
|
||||||
|
timestamp: event.timestamp,
|
||||||
|
sticky: event.sticky_duration_ms.map(sticky::object),
|
||||||
|
unsigned: Some(unsigned),
|
||||||
|
redacts,
|
||||||
|
};
|
||||||
|
|
||||||
|
let state_lock = self.services.state.mutex.lock(&event.room_id).await;
|
||||||
|
self.services
|
||||||
|
.timeline
|
||||||
|
.send_timeline_event(partial_pdu, &event.user_id, &event.room_id, &state_lock)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves a scheduled delayed event to the finalized events, where it can
|
||||||
|
/// still be looked up until it is pruned.
|
||||||
|
async fn finalize(
|
||||||
|
&self,
|
||||||
|
delay_id: &str,
|
||||||
|
event: ScheduledDelayedEvent,
|
||||||
|
outcome: DelayedEventOutcome,
|
||||||
|
) {
|
||||||
|
let user_id = event.user_id.clone();
|
||||||
|
let finalized_ts = MilliSecondsSinceUnixEpoch::now();
|
||||||
|
|
||||||
|
// The finalized event is written before the scheduled one is removed,
|
||||||
|
// so it isn't lost if the server stops in between.
|
||||||
|
self.db.delayid_finalizeddelayedevent.raw_put(
|
||||||
|
delay_id,
|
||||||
|
Json(FinalizedDelayedEvent {
|
||||||
|
event,
|
||||||
|
finalized: FinalizedDelayedEventData::new(outcome, finalized_ts),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
self.db
|
||||||
|
.useridfinalizedtsdelayid
|
||||||
|
.put_raw((&user_id, u64::from(finalized_ts.get()), delay_id), []);
|
||||||
|
self.db.useriddelayid.del((&user_id, delay_id));
|
||||||
|
self.db.delayid_scheduleddelayedevent.remove(delay_id);
|
||||||
|
self.queue(QueueUpdate::Remove(delay_id.to_owned()));
|
||||||
|
|
||||||
|
self.limit_finalized(&user_id).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes the user's oldest finalized delayed events beyond
|
||||||
|
/// [`MAX_FINALIZED_PER_USER`].
|
||||||
|
async fn limit_finalized(&self, user_id: &UserId) {
|
||||||
|
let prefix = (user_id, Interfix);
|
||||||
|
let count = self
|
||||||
|
.db
|
||||||
|
.useridfinalizedtsdelayid
|
||||||
|
.keys_prefix_raw(&prefix)
|
||||||
|
.count()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.useridfinalizedtsdelayid
|
||||||
|
.keys_prefix(&prefix)
|
||||||
|
.ignore_err()
|
||||||
|
.take(count.saturating_sub(MAX_FINALIZED_PER_USER))
|
||||||
|
.ready_for_each(|(_, finalized_ts, delay_id): (Ignore, u64, &str)| {
|
||||||
|
self.remove_finalized(user_id, finalized_ts, delay_id);
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_finalized(&self, user_id: &UserId, finalized_ts: u64, delay_id: &str) {
|
||||||
|
self.db
|
||||||
|
.useridfinalizedtsdelayid
|
||||||
|
.del((user_id, finalized_ts, delay_id));
|
||||||
|
self.db.delayid_finalizeddelayedevent.remove(delay_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes finalized delayed events older than [`FINALIZED_RETENTION`].
|
||||||
|
/// Called periodically by the worker. Only the index keys are scanned, so
|
||||||
|
/// the events themselves are never deserialized.
|
||||||
|
async fn prune_finalized(&self) {
|
||||||
|
let Some(cutoff) = SystemTime::now()
|
||||||
|
.checked_sub(FINALIZED_RETENTION)
|
||||||
|
.and_then(MilliSecondsSinceUnixEpoch::from_system_time)
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let cutoff = u64::from(cutoff.get());
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.useridfinalizedtsdelayid
|
||||||
|
.keys::<(OwnedUserId, u64, &str)>()
|
||||||
|
.ignore_err()
|
||||||
|
.ready_filter(|(_, finalized_ts, _)| *finalized_ts < cutoff)
|
||||||
|
.ready_for_each(|(user_id, finalized_ts, delay_id)| {
|
||||||
|
self.remove_finalized(&user_id, finalized_ts, delay_id);
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_scheduled(&self, delay_id: &str) -> Option<ScheduledDelayedEvent> {
|
||||||
|
self.db
|
||||||
|
.delayid_scheduleddelayedevent
|
||||||
|
.get(delay_id)
|
||||||
|
.await
|
||||||
|
.deserialized()
|
||||||
|
.inspect_err(|e| {
|
||||||
|
if !e.is_not_found() {
|
||||||
|
error!(%delay_id, "Invalid scheduled delayed event in the database: {e}");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_finalized(&self, delay_id: &str) -> Option<FinalizedDelayedEvent> {
|
||||||
|
self.db
|
||||||
|
.delayid_finalizeddelayedevent
|
||||||
|
.get(delay_id)
|
||||||
|
.await
|
||||||
|
.deserialized()
|
||||||
|
.inspect_err(|e| {
|
||||||
|
if !e.is_not_found() {
|
||||||
|
error!(%delay_id, "Invalid finalized delayed event in the database: {e}");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Streams the delay IDs of the user's scheduled delayed events.
|
||||||
|
fn user_delay_ids<'a>(
|
||||||
|
&'a self,
|
||||||
|
user_id: &'a UserId,
|
||||||
|
) -> impl futures::Stream<Item = String> + Send + 'a {
|
||||||
|
self.db
|
||||||
|
.useriddelayid
|
||||||
|
.keys_prefix(&(user_id, Interfix))
|
||||||
|
.ignore_err()
|
||||||
|
.map(|(_, delay_id): (Ignore, &str)| delay_id.to_owned())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct MaybeRedaction {
|
||||||
|
redacts: Option<OwnedEventId>,
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
use std::{
|
||||||
|
collections::{BTreeSet, HashMap},
|
||||||
|
sync::{Arc, atomic::Ordering},
|
||||||
|
time::{Duration, SystemTime},
|
||||||
|
};
|
||||||
|
|
||||||
|
use conduwuit::{Result, utils::stream::TryIgnore};
|
||||||
|
use futures::StreamExt;
|
||||||
|
use loole::Receiver;
|
||||||
|
use tokio::{
|
||||||
|
select,
|
||||||
|
time::{MissedTickBehavior, interval, sleep},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{DELAY_ID_LENGTH, ScheduledDelayedEvent, Service};
|
||||||
|
|
||||||
|
const PRUNE_INTERVAL: Duration = Duration::from_hours(1);
|
||||||
|
|
||||||
|
pub(super) enum QueueUpdate {
|
||||||
|
/// Queues the delayed event to be sent at the given time, replacing any
|
||||||
|
/// existing entry for it.
|
||||||
|
Schedule(SystemTime, String),
|
||||||
|
/// Removes a delayed event that was finalized before it was due.
|
||||||
|
Remove(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct SubmissionQueue {
|
||||||
|
receiver: Receiver<QueueUpdate>,
|
||||||
|
interrupt: Receiver<()>,
|
||||||
|
queue: BTreeSet<(SystemTime, String)>,
|
||||||
|
send_times: HashMap<String, SystemTime>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SubmissionQueue {
|
||||||
|
pub(super) fn new(receiver: Receiver<QueueUpdate>, interrupt: Receiver<()>) -> Self {
|
||||||
|
Self {
|
||||||
|
receiver,
|
||||||
|
interrupt,
|
||||||
|
queue: BTreeSet::new(),
|
||||||
|
send_times: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schedule(&mut self, time: SystemTime, delay_id: String) {
|
||||||
|
if let Some(old_time) = self.send_times.insert(delay_id.clone(), time) {
|
||||||
|
self.queue.remove(&(old_time, delay_id.clone()));
|
||||||
|
}
|
||||||
|
self.queue.insert((time, delay_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&mut self, delay_id: String) {
|
||||||
|
if let Some(time) = self.send_times.remove(&delay_id) {
|
||||||
|
self.queue.remove(&(time, delay_id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pop(&mut self) -> Option<String> {
|
||||||
|
let (_, delay_id) = self.queue.pop_first()?;
|
||||||
|
self.send_times.remove(&delay_id);
|
||||||
|
Some(delay_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn worker(service: &Arc<Service>) -> Result {
|
||||||
|
let mut queue = service
|
||||||
|
.submission_queue
|
||||||
|
.try_lock()
|
||||||
|
.expect("only one delayed events worker should be running");
|
||||||
|
let receiver = queue.receiver.clone();
|
||||||
|
let interrupt = queue.interrupt.clone();
|
||||||
|
|
||||||
|
let scheduled: Vec<_> = service
|
||||||
|
.db
|
||||||
|
.delayid_scheduleddelayedevent
|
||||||
|
.stream::<'_, &str, ScheduledDelayedEvent>()
|
||||||
|
.ignore_err()
|
||||||
|
.map(|(delay_id, event)| (event.send_time(), delay_id.to_owned()))
|
||||||
|
.collect()
|
||||||
|
.await;
|
||||||
|
for (time, delay_id) in scheduled {
|
||||||
|
queue.schedule(time, delay_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut prune = interval(PRUNE_INTERVAL);
|
||||||
|
prune.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let mem_usage = queue.queue.len().saturating_mul(
|
||||||
|
// Each delay ID and send time is stored in both the queue and the
|
||||||
|
// index.
|
||||||
|
DELAY_ID_LENGTH
|
||||||
|
.saturating_add(size_of::<SystemTime>())
|
||||||
|
.saturating_mul(2),
|
||||||
|
);
|
||||||
|
service.mem_usage.store(mem_usage, Ordering::Relaxed);
|
||||||
|
|
||||||
|
let next_due = async {
|
||||||
|
let (time, _) = queue.queue.first()?;
|
||||||
|
if let Ok(wait) = time.duration_since(SystemTime::now()) {
|
||||||
|
sleep(wait).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
queue.pop()
|
||||||
|
};
|
||||||
|
|
||||||
|
// All of these are cancellation-safe
|
||||||
|
select! {
|
||||||
|
Some(delay_id) = next_due => {
|
||||||
|
// Sent in the background so one slow room doesn't hold up the others.
|
||||||
|
let task_service = service.clone();
|
||||||
|
service.services.server.runtime().spawn(async move {
|
||||||
|
task_service.send_if_due(&delay_id).await;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
Ok(update) = receiver.recv_async() => match update {
|
||||||
|
| QueueUpdate::Schedule(time, delay_id) => queue.schedule(time, delay_id),
|
||||||
|
| QueueUpdate::Remove(delay_id) => queue.remove(delay_id),
|
||||||
|
},
|
||||||
|
_ = prune.tick() => {
|
||||||
|
let task_service = service.clone();
|
||||||
|
service.services.server.runtime().spawn(async move {
|
||||||
|
task_service.prune_finalized().await;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
_ = interrupt.recv_async() => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
pub mod alias;
|
pub mod alias;
|
||||||
pub mod auth_chain;
|
pub mod auth_chain;
|
||||||
|
pub mod delayed_events;
|
||||||
pub mod directory;
|
pub mod directory;
|
||||||
pub mod event_handler;
|
pub mod event_handler;
|
||||||
pub mod lazy_loading;
|
pub mod lazy_loading;
|
||||||
@@ -26,6 +27,7 @@ pub struct Service {
|
|||||||
pub alias: Arc<alias::Service>,
|
pub alias: Arc<alias::Service>,
|
||||||
pub auth_chain: Arc<auth_chain::Service>,
|
pub auth_chain: Arc<auth_chain::Service>,
|
||||||
pub directory: Arc<directory::Service>,
|
pub directory: Arc<directory::Service>,
|
||||||
|
pub delayed_events: Arc<delayed_events::Service>,
|
||||||
pub event_handler: Arc<event_handler::Service>,
|
pub event_handler: Arc<event_handler::Service>,
|
||||||
pub lazy_loading: Arc<lazy_loading::Service>,
|
pub lazy_loading: Arc<lazy_loading::Service>,
|
||||||
pub membership: Arc<membership::Service>,
|
pub membership: Arc<membership::Service>,
|
||||||
|
|||||||
@@ -2,13 +2,13 @@
|
|||||||
|
|
||||||
pub(crate) use conduwuit::{
|
pub(crate) use conduwuit::{
|
||||||
Err, Event, Result, err,
|
Err, Event, Result, err,
|
||||||
matrix::pdu::{PartialPdu, UnsignedContext, sticky},
|
matrix::pdu::{PartialPdu, UnsignedContext},
|
||||||
trace,
|
trace,
|
||||||
};
|
};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, UserId,
|
OwnedEventId, RoomId, UserId,
|
||||||
events::{
|
events::{
|
||||||
AnyStateEventContent, AnyTimelineEvent, StateEventType,
|
AnyStateEventContent, AnyTimelineEvent, MessageLikeEventType, StateEventType,
|
||||||
room::{
|
room::{
|
||||||
canonical_alias::RoomCanonicalAliasEventContent,
|
canonical_alias::RoomCanonicalAliasEventContent,
|
||||||
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
|
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
|
||||||
@@ -16,7 +16,6 @@ use ruma::{
|
|||||||
member::RoomMemberEventContent,
|
member::RoomMemberEventContent,
|
||||||
server_acl::RoomServerAclEventContent,
|
server_acl::RoomServerAclEventContent,
|
||||||
},
|
},
|
||||||
sticky::StickyDurationMs,
|
|
||||||
},
|
},
|
||||||
serde::Raw,
|
serde::Raw,
|
||||||
};
|
};
|
||||||
@@ -24,42 +23,43 @@ use ruma::{
|
|||||||
use crate::rooms::state::RoomMutexGuard;
|
use crate::rooms::state::RoomMutexGuard;
|
||||||
|
|
||||||
impl super::Service {
|
impl super::Service {
|
||||||
#[allow(clippy::too_many_arguments)]
|
/// Checks that a local user may send an event, then sends it.
|
||||||
pub async fn send_state_event_for_key(
|
pub async fn send_timeline_event(
|
||||||
&self,
|
&self,
|
||||||
|
mut partial_pdu: PartialPdu,
|
||||||
sender: &UserId,
|
sender: &UserId,
|
||||||
room_id: &RoomId,
|
room_id: &RoomId,
|
||||||
state_lock: &RoomMutexGuard,
|
state_lock: &RoomMutexGuard,
|
||||||
event_type: &StateEventType,
|
|
||||||
content: &Raw<AnyStateEventContent>,
|
|
||||||
state_key: &str,
|
|
||||||
sticky_duration_ms: Option<StickyDurationMs>,
|
|
||||||
timestamp: Option<MilliSecondsSinceUnixEpoch>,
|
|
||||||
) -> Result<OwnedEventId> {
|
) -> Result<OwnedEventId> {
|
||||||
let content: Raw<AnyStateEventContent> = content.clone();
|
if let Some(state_key) = &partial_pdu.state_key {
|
||||||
self.assert_allowed_to_send_state_event(room_id, event_type, state_key, &content)
|
let content = Raw::<AnyStateEventContent>::from_json(partial_pdu.content);
|
||||||
.await?;
|
self.assert_allowed_to_send_state_event(
|
||||||
|
room_id,
|
||||||
let content = serde_json::from_str(content.json().get())
|
&partial_pdu.event_type.to_string().into(),
|
||||||
.map_err(|e| err!(Request(BadJson("Invalid JSON body: {e}"))))?;
|
state_key,
|
||||||
|
&content,
|
||||||
let event_id = self
|
|
||||||
.build_and_append_pdu(
|
|
||||||
PartialPdu {
|
|
||||||
event_type: event_type.to_string().into(),
|
|
||||||
content,
|
|
||||||
sticky: sticky_duration_ms.map(sticky::object),
|
|
||||||
state_key: Some(state_key.into()),
|
|
||||||
timestamp,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
sender,
|
|
||||||
Some(room_id),
|
|
||||||
state_lock,
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
partial_pdu.content = content.into_json();
|
||||||
|
} else {
|
||||||
|
self.assert_allowed_to_send_message_event(
|
||||||
|
&partial_pdu.event_type.to_string().into(),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(event_id)
|
self.build_and_append_pdu(partial_pdu, sender, Some(room_id), state_lock)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_allowed_to_send_message_event(&self, event_type: &MessageLikeEventType) -> Result {
|
||||||
|
// Forbid m.room.encrypted if encryption is disabled
|
||||||
|
if *event_type == MessageLikeEventType::RoomEncrypted
|
||||||
|
&& !self.services.config.allow_encryption
|
||||||
|
{
|
||||||
|
return Err!(Request(Forbidden("Encryption has been disabled")));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn assert_allowed_to_send_state_event(
|
async fn assert_allowed_to_send_state_event(
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ impl Services {
|
|||||||
rooms: rooms::Service {
|
rooms: rooms::Service {
|
||||||
alias: build!(rooms::alias::Service),
|
alias: build!(rooms::alias::Service),
|
||||||
auth_chain: build!(rooms::auth_chain::Service),
|
auth_chain: build!(rooms::auth_chain::Service),
|
||||||
|
delayed_events: build!(rooms::delayed_events::Service),
|
||||||
directory: build!(rooms::directory::Service),
|
directory: build!(rooms::directory::Service),
|
||||||
event_handler: build!(rooms::event_handler::Service),
|
event_handler: build!(rooms::event_handler::Service),
|
||||||
lazy_loading: build!(rooms::lazy_loading::Service),
|
lazy_loading: build!(rooms::lazy_loading::Service),
|
||||||
|
|||||||
@@ -466,6 +466,12 @@ impl super::Service {
|
|||||||
// Mark user as deactivated
|
// Mark user as deactivated
|
||||||
self.db.userid_deactivated.insert(user_id, "");
|
self.db.userid_deactivated.insert(user_id, "");
|
||||||
|
|
||||||
|
// Delayed events must not be sent after deactivation
|
||||||
|
self.services
|
||||||
|
.delayed_events
|
||||||
|
.remove_all_for_user(user_id)
|
||||||
|
.await;
|
||||||
|
|
||||||
// TODO: Unhook 3PID
|
// TODO: Unhook 3PID
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ struct Services {
|
|||||||
alias: Dep<alias::Service>,
|
alias: Dep<alias::Service>,
|
||||||
appservice: Dep<appservice::Service>,
|
appservice: Dep<appservice::Service>,
|
||||||
config: Dep<config::Service>,
|
config: Dep<config::Service>,
|
||||||
|
delayed_events: Dep<rooms::delayed_events::Service>,
|
||||||
firstrun: Dep<firstrun::Service>,
|
firstrun: Dep<firstrun::Service>,
|
||||||
globals: Dep<globals::Service>,
|
globals: Dep<globals::Service>,
|
||||||
membership: Dep<membership::Service>,
|
membership: Dep<membership::Service>,
|
||||||
@@ -110,6 +111,8 @@ impl crate::Service for Service {
|
|||||||
alias: args.depend::<alias::Service>("rooms::alias"),
|
alias: args.depend::<alias::Service>("rooms::alias"),
|
||||||
appservice: args.depend::<appservice::Service>("appservice"),
|
appservice: args.depend::<appservice::Service>("appservice"),
|
||||||
config: args.depend::<config::Service>("config"),
|
config: args.depend::<config::Service>("config"),
|
||||||
|
delayed_events: args
|
||||||
|
.depend::<rooms::delayed_events::Service>("rooms::delayed_events"),
|
||||||
firstrun: args.depend::<firstrun::Service>("firstrun"),
|
firstrun: args.depend::<firstrun::Service>("firstrun"),
|
||||||
globals: args.depend::<globals::Service>("globals"),
|
globals: args.depend::<globals::Service>("globals"),
|
||||||
membership: args.depend::<membership::Service>("rooms::membership"),
|
membership: args.depend::<membership::Service>("rooms::membership"),
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ form_urlencoded = "1.2.2"
|
|||||||
futures.workspace = true
|
futures.workspace = true
|
||||||
lettre.workspace = true
|
lettre.workspace = true
|
||||||
memory-serve = "2.4.0"
|
memory-serve = "2.4.0"
|
||||||
openid.workspace = true
|
openidconnect.workspace = true
|
||||||
ruma.workspace = true
|
ruma.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use axum::{
|
|||||||
routing::{get, on},
|
routing::{get, on},
|
||||||
};
|
};
|
||||||
use conduwuit_api::client::handle_login;
|
use conduwuit_api::client::handle_login;
|
||||||
use openid::Prompt;
|
use openidconnect::core::CoreAuthPrompt;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedUserId,
|
OwnedUserId,
|
||||||
api::client::uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
api::client::uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
|
||||||
@@ -86,8 +86,8 @@ async fn route_login(
|
|||||||
let (session, redirect_url) = services
|
let (session, redirect_url) = services
|
||||||
.oidc
|
.oidc
|
||||||
.begin_session(match intent {
|
.begin_session(match intent {
|
||||||
| Some(LoginIntent::SwitchAccounts) => Some(Prompt::SelectAccount),
|
| Some(LoginIntent::SwitchAccounts) => Some(CoreAuthPrompt::SelectAccount),
|
||||||
| _ if reauthenticate => Some(Prompt::Consent),
|
| _ if reauthenticate => Some(CoreAuthPrompt::Consent),
|
||||||
| _ => None,
|
| _ => None,
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
|||||||
@@ -106,7 +106,10 @@ async fn route_complete(
|
|||||||
.await
|
.await
|
||||||
.expect("should be able to serialize oidc session");
|
.expect("should be able to serialize oidc session");
|
||||||
|
|
||||||
Box::pin(services.oidc.complete_session(claims, None, &client_ip)).await
|
services
|
||||||
|
.oidc
|
||||||
|
.complete_session(&claims, None, &client_ip)
|
||||||
|
.await
|
||||||
},
|
},
|
||||||
| OidcSessionState::Authorized { claims } => {
|
| OidcSessionState::Authorized { claims } => {
|
||||||
let supplied_user_id = if let Some(form) = form {
|
let supplied_user_id = if let Some(form) = form {
|
||||||
@@ -163,11 +166,9 @@ async fn route_complete(
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
Box::pin(
|
|
||||||
services
|
services
|
||||||
.oidc
|
.oidc
|
||||||
.complete_session(*claims, supplied_user_id, &client_ip),
|
.complete_session(&claims, supplied_user_id, &client_ip)
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user