Compare commits

..
Author SHA1 Message Date
timedout 7aae412ee3 chore: Update config reference 2026-12-02 18:48:05 +00:00
timedout 45449c431c chore: Add changelog 2026-12-02 18:44:05 +00:00
timedout bf7dd2867c feat: Implement MSC4596: Selective Ignores 2026-12-02 18:39:11 +00:00
21 changed files with 159 additions and 317 deletions

No files matched your search

Generated
+11 -11
View File
@@ -5049,7 +5049,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma" name = "ruma"
version = "0.18.0" version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"assign", "assign",
"js_int", "js_int",
@@ -5068,7 +5068,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-appservice-api" name = "ruma-appservice-api"
version = "0.18.0" version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"http", "http",
"js_int", "js_int",
@@ -5081,7 +5081,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-client-api" name = "ruma-client-api"
version = "0.26.0" version = "0.26.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"as_variant", "as_variant",
"assign", "assign",
@@ -5103,7 +5103,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-common" name = "ruma-common"
version = "0.21.0" version = "0.21.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"as_variant", "as_variant",
"base64 0.23.1", "base64 0.23.1",
@@ -5136,7 +5136,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-events" name = "ruma-events"
version = "0.36.0" version = "0.36.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"as_variant", "as_variant",
"indexmap 2.14.2", "indexmap 2.14.2",
@@ -5157,7 +5157,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-federation-api" name = "ruma-federation-api"
version = "0.17.0" version = "0.17.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"bytes", "bytes",
"http", "http",
@@ -5179,7 +5179,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-identifiers-validation" name = "ruma-identifiers-validation"
version = "0.14.1" version = "0.14.1"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"js_int", "js_int",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -5188,7 +5188,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-macros" name = "ruma-macros"
version = "0.20.3" version = "0.20.3"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"as_variant", "as_variant",
"cfg-if", "cfg-if",
@@ -5204,7 +5204,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-push-gateway-api" name = "ruma-push-gateway-api"
version = "0.17.0" version = "0.17.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
@@ -5216,7 +5216,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-signatures" name = "ruma-signatures"
version = "0.23.0" version = "0.23.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"ed25519-dalek", "ed25519-dalek",
@@ -5233,7 +5233,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-state-res" name = "ruma-state-res"
version = "0.19.0" version = "0.19.0"
source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86" source = "git+https://github.com/timedoutuk/ruma.git?rev=fd2bf57dfcc2acc30df86054996ce5988bf22d01#fd2bf57dfcc2acc30df86054996ce5988bf22d01"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
+3 -2
View File
@@ -356,8 +356,8 @@ version = "1.1.1"
# Used for matrix spec type definitions and helpers # Used for matrix spec type definitions and helpers
[workspace.dependencies.ruma] [workspace.dependencies.ruma]
git = "https://github.com/ruma/ruma.git" git = "https://github.com/timedoutuk/ruma.git"
rev = "d6621e1355419c5ef9a7c260b28ae1c0e6722b86" rev = "fd2bf57dfcc2acc30df86054996ce5988bf22d01"
features = [ features = [
"appservice-api-c", "appservice-api-c",
"client-api", "client-api",
@@ -399,6 +399,7 @@ features = [
"unstable-msc4540", "unstable-msc4540",
"unstable-msc4560", "unstable-msc4560",
"unstable-msc4563", "unstable-msc4563",
"unstable-msc4596",
"unstable-extensible-events", "unstable-extensible-events",
] ]
-1
View File
@@ -1 +0,0 @@
Continuwuity now supports the OAuth 2.0 client credentials grant type, allowing secure automated access to the Matrix homeserver admin API, as well as future administrative functionality. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Implemented support for [MSC4596: Selective Ignores](https://github.com/matrix-org/matrix-spec-proposals/pull/4596).
+18 -42
View File
@@ -2675,48 +2675,6 @@
# env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE # env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE
#profile_key_import_mode = "on_registration" #profile_key_import_mode = "on_registration"
#[global.oauth.clients."$id"]
# Use this section to add static OAuth clients for bots and automation.
# Clients added here may use the client credentials OAuth grant to authorize
# themselves with Continuwuity.
#
# Make sure to replace `$id` in the header with your client ID of choice! You can
# add more copies of this section with different IDs to add multiple clients.
#
# Because the client credentials grant authorizes the client as itself, without
# an attached user, clients that use it will not be able to access most of the Matrix
# client-server API. Administrative functionality that does not require a user
# will still be available.
# The client's client secret.
#
# This must be supplied as the `client_secret` parameter when requesting
# an access token with the OAuth 2.0 token endpoint. Continuwuity does
# not check the `Authorization` header for requests to this endpoint.
#
#client_secret =
# A list of scopes that the client may request. Continuwuity allows static
# clients to request the following scopes:
#
# - "urn:matrix:client:cc.c10y.msc4484.server_administration" (MSC4484):
# This scope grants access to the Matrix server administration APIs, as
# well as Continuwuity's internal admin API (currently a work in
# progress).
# - "urn:matrix:client:api:*": This scope grants access to the Matrix
# client-server API. Most endpoints require an authenticated Matrix user
# and thus will not be usable by static clients.
#
# The `urn:matrix:client:device:<id>` scope may not be requested by static
# clients.
#
# Scopes listed here are not granted by default. The client must
# explicitly include them in the `scope` parameter of its access token
# request.
#
#scopes = []
[global.experiments] [global.experiments]
# Continuwuity's experimental features are frequently updated. # Continuwuity's experimental features are frequently updated.
# If you got this configuration via a package manager, chances are it's outdated. # If you got this configuration via a package manager, chances are it's outdated.
@@ -2862,6 +2820,24 @@
# env: CONTINUWUITY_EXPERIMENTS__MSC4563 # env: CONTINUWUITY_EXPERIMENTS__MSC4563
#msc4563 = false #msc4563 = false
# MSC4596: Selective Ignores
#
# Adds more granular control over ignoring users, introducing
# "soft-ignores", which instructs the server to send ignored messages to
# the client. Useful for moderators that want to see messages from ignored
# users in rooms they moderate, but nowhere else.
#
# Allows for per-room overrides.
#
# This will likely supersede the
# `send_messages_from_ignored_users_to_client` configuration option, which
# is a global setting that applies to all rooms and users.
#
# https://github.com/matrix-org/matrix-spec-proposals/pull/4596
#
# env: CONTINUWUITY_EXPERIMENTS__MSC4596
#msc4596 = false
#[global.experiments.msc2815] #[global.experiments.msc2815]
# MSC2815: Proposal to allow room moderators to view redacted event content # MSC2815: Proposal to allow room moderators to view redacted event content
# #
+2 -1
View File
@@ -53,8 +53,9 @@ pub(crate) async fn invite_user_route(
// silently drop invites to users the sender has ignored // silently drop invites to users the sender has ignored
if services if services
.users .users
.user_is_ignored(recipient_user, sender_user) .user_ignore_mode(recipient_user, sender_user, None)
.await .await
.is_some()
{ {
return Ok(invite_user::v3::Response::new()); return Ok(invite_user::v3::Response::new());
} }
+22 -19
View File
@@ -34,6 +34,7 @@ use ruma::{
events::{ events::{
AnyStateEvent, StateEventType, SyncEphemeralRoomEvent, AnyStateEvent, StateEventType, SyncEphemeralRoomEvent,
TimelineEventType::{self, *}, TimelineEventType::{self, *},
ignored_user_list::IgnoredUserMode,
receipt::ReceiptEventContent, receipt::ReceiptEventContent,
}, },
serde::Raw, serde::Raw,
@@ -305,10 +306,6 @@ where
let server_ignored = services let server_ignored = services
.moderation .moderation
.is_remote_server_ignored(sender_user.server_name()); .is_remote_server_ignored(sender_user.server_name());
let user_ignored = services
.users
.user_is_ignored(sender_user, recipient_user)
.await;
if !type_ignored { if !type_ignored {
// We cannot safely ignore this type // We cannot safely ignore this type
@@ -327,22 +324,28 @@ where
}; };
} }
if user_ignored && !services.config.send_messages_from_ignored_users_to_client { let user_ignore_mode = services
// the recipient of this PDU has the sender ignored, and we're not .users
// configured to send ignored messages to clients .user_ignore_mode(sender_user, recipient_user, event.room_id())
return if services.config.experiments.msc4406.is_enabled() { .await;
Err(Error::BadRequest(
ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender(
event.sender().to_owned(),
)),
"You have ignored this sender.",
))
} else {
Err!(Request(NotFound("You have ignored the sender of this event.")))
};
}
Ok(false) match user_ignore_mode {
| None | Some(IgnoredUserMode::Soft) => Ok(false),
| _ => {
// the recipient of this PDU has the sender ignored, and we're not
// configured to send ignored messages to clients
if services.config.experiments.msc4406.is_enabled() {
Err(Error::BadRequest(
ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender(
event.sender().to_owned(),
)),
"You have ignored this sender.",
))
} else {
Err!(Request(NotFound("You have ignored the sender of this event.")))
}
},
}
} }
#[inline] #[inline]
+1 -1
View File
@@ -61,7 +61,7 @@ pub(crate) async fn authorization_server_metadata(services: &Services) -> Value
"authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(), "authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(),
"code_challenge_methods_supported": ["S256"], "code_challenge_methods_supported": ["S256"],
"device_authorization_endpoint": endpoint_base.join(DEVICE_AUTHORIZATION_PATH).unwrap(), "device_authorization_endpoint": endpoint_base.join(DEVICE_AUTHORIZATION_PATH).unwrap(),
"grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "client_credentials"], "grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"],
"issuer": services.config.get_client_domain(), "issuer": services.config.get_client_domain(),
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(), "jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
"prompt_values_supported": prompt_values_supported, "prompt_values_supported": prompt_values_supported,
+2 -1
View File
@@ -189,8 +189,9 @@ pub(crate) async fn create_room_route(
// silently drop invites to users the creator has ignored // silently drop invites to users the creator has ignored
if services if services
.users .users
.user_is_ignored(recipient_user, sender_user) .user_ignore_mode(recipient_user, sender_user, None)
.await .await
.is_some()
{ {
continue; continue;
} }
+4 -2
View File
@@ -33,6 +33,7 @@ use ruma::{
events::{ events::{
StateEventType, StateEventType,
TimelineEventType::*, TimelineEventType::*,
ignored_user_list::IgnoredUserMode,
room::member::{MembershipState, RoomMemberEventContent}, room::member::{MembershipState, RoomMemberEventContent},
}, },
serde::Raw, serde::Raw,
@@ -162,8 +163,9 @@ async fn build_ephemeral(
.filter_map(async |(read_user, _, edu)| { .filter_map(async |(read_user, _, edu)| {
let is_ignored = services let is_ignored = services
.users .users
.user_is_ignored(&read_user, syncing_user) .user_ignore_mode(&read_user, syncing_user, Some(room_id))
.await; .await
.is_some_and(|mode| matches!(mode, IgnoredUserMode::Hard));
// filter out read receipts for ignored users // filter out read receipts for ignored users
is_ignored.or_some(edu) is_ignored.or_some(edu)
+5 -2
View File
@@ -42,6 +42,7 @@ use ruma::{
AnyStrippedStateEvent, AnySyncEphemeralRoomEvent, AnySyncStateEvent, AnyStrippedStateEvent, AnySyncEphemeralRoomEvent, AnySyncStateEvent,
GlobalAccountDataEventType, StateEventType, TimelineEventType, GlobalAccountDataEventType, StateEventType, TimelineEventType,
direct::DirectEvent, direct::DirectEvent,
ignored_user_list::IgnoredUserMode,
room::{ room::{
create::RoomCreateEventContent, create::RoomCreateEventContent,
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
@@ -902,8 +903,9 @@ where
.filter_map(|(read_user, _ts, v)| async move { .filter_map(|(read_user, _ts, v)| async move {
services services
.users .users
.user_is_ignored(&read_user, sender_user) .user_ignore_mode(&read_user, sender_user, Some(room_id))
.await .await
.is_none_or(|mode| matches!(mode, IgnoredUserMode::Soft))
.or_some(v) .or_some(v)
}) })
.collect() .collect()
@@ -1173,8 +1175,9 @@ async fn collect_sticky_events(
} }
if services if services
.users .users
.user_is_ignored(pdu.sender(), sender_user) .user_ignore_mode(pdu.sender(), sender_user, pdu.room_id())
.await .await
.is_some_and(|mode| matches!(mode, IgnoredUserMode::Hard))
{ {
continue; continue;
} }
+1 -25
View File
@@ -47,7 +47,6 @@ pub(crate) enum ClientIdentity {
sender_device: Option<OwnedDeviceId>, sender_device: Option<OwnedDeviceId>,
appservice_info: Box<RegistrationInfo>, appservice_info: Box<RegistrationInfo>,
}, },
StaticClient,
} }
impl ClientIdentity { impl ClientIdentity {
@@ -55,7 +54,6 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } => | Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Some(sender_user), Some(sender_user),
| Self::StaticClient => None,
} }
} }
@@ -63,8 +61,6 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } => | Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Ok(sender_user), Ok(sender_user),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
} }
} }
@@ -72,7 +68,6 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_device, .. } => Some(sender_device), | Self::User { sender_device, .. } => Some(sender_device),
| Self::Appservice { sender_device, .. } => sender_device.as_deref(), | Self::Appservice { sender_device, .. } => sender_device.as_deref(),
| Self::StaticClient => None,
} }
} }
@@ -82,14 +77,12 @@ impl ClientIdentity {
| Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device), | Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device),
| Self::Appservice { sender_device: None, .. } => | Self::Appservice { sender_device: None, .. } =>
Err!(Request(Forbidden("Appservices must masquerade to use this endpoint."))), Err!(Request(Forbidden("Appservices must masquerade to use this endpoint."))),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
} }
} }
pub(crate) fn appservice_info(&self) -> Option<&RegistrationInfo> { pub(crate) fn appservice_info(&self) -> Option<&RegistrationInfo> {
match self { match self {
| Self::User { .. } | Self::StaticClient => None, | Self::User { .. } => None,
| Self::Appservice { appservice_info, .. } => Some(appservice_info), | Self::Appservice { appservice_info, .. } => Some(appservice_info),
} }
} }
@@ -432,23 +425,6 @@ async fn check_access_token(
sender_device, sender_device,
appservice_info: Box::new(appservice_info), appservice_info: Box::new(appservice_info),
}) })
} else if let Some(session) = services.oauth.get_client_credentials_session(token) {
if !required_scopes
.iter()
.any(|scope| session.scopes.contains(scope))
{
return Err(Error::Request(
ErrorKind::InsufficientUserAuthentication(Box::new(
assign!(InsufficientUserAuthenticationErrorData::new(), {
scope: required_scopes.iter().cloned().collect()
}),
)),
"You do not have permission to access this endpoint.".into(),
StatusCode::UNAUTHORIZED,
));
}
Ok(ClientIdentity::StaticClient)
} else if services.users.is_previous_token(token).await { } else if services.users.is_previous_token(token).await {
// Return a soft-logout for previous tokens. This is necessary // Return a soft-logout for previous tokens. This is necessary
// to make token refreshing idempotent. // to make token refreshing idempotent.
-9
View File
@@ -346,15 +346,6 @@ pub fn check(config: &Config) -> Result {
} }
})?; })?;
for (id, client) in &config.oauth.clients {
if client.scopes.is_empty() {
warn!(
"The static OAuth client `{id}` has no scopes configured. It will not be able \
to access any API endpoints."
);
}
}
Ok(()) Ok(())
} }
+18
View File
@@ -159,6 +159,24 @@ pub struct Experiments {
/// default: false /// default: false
#[serde(default)] #[serde(default)]
pub msc4563: SimpleExperiment, pub msc4563: SimpleExperiment,
/// MSC4596: Selective Ignores
///
/// Adds more granular control over ignoring users, introducing
/// "soft-ignores", which instructs the server to send ignored messages to
/// the client. Useful for moderators that want to see messages from ignored
/// users in rooms they moderate, but nowhere else.
///
/// Allows for per-room overrides.
///
/// This will likely supersede the
/// `send_messages_from_ignored_users_to_client` configuration option, which
/// is a global setting that applies to all rooms and users.
///
/// https://github.com/matrix-org/matrix-spec-proposals/pull/4596
///
/// default: false
pub msc4596: SimpleExperiment,
} }
/// Represents a "simple" experiment, which is either disabled or enabled. /// Represents a "simple" experiment, which is either disabled or enabled.
-54
View File
@@ -29,7 +29,6 @@ use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
RoomVersionId, ServerName, RoomVersionId, ServerName,
api::{ api::{
OAuthClientScope,
client::{discovery::discover_support::ContactRole, rtc::RtcTransport}, client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
federation::discovery::OldVerifyKey, federation::discovery::OldVerifyKey,
}, },
@@ -2751,12 +2750,7 @@ pub struct OauthConfig {
compatibility_mode: OAuthMode, compatibility_mode: OAuthMode,
/// display: hidden /// display: hidden
#[serde(default)]
pub oidc: Option<OidcConfig>, pub oidc: Option<OidcConfig>,
/// display: hidden
#[serde(default)]
pub clients: HashMap<String, OAuthClient>,
} }
impl OauthConfig { impl OauthConfig {
@@ -2998,54 +2992,6 @@ impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter<K> {
} }
} }
#[derive(Clone, Debug, Deserialize)]
#[config_example_generator(
filename = "conduwuit-example.toml",
section = "global.oauth.clients.\"$id\"",
optional = "true",
subheader = "\
# Use this section to add static OAuth clients for bots and automation.
# Clients added here may use the client credentials OAuth grant to authorize
# themselves with Continuwuity.
#
# Make sure to replace `$id` in the header with your client ID of choice! You can
# add more copies of this section with different IDs to add multiple clients.
#
# Because the client credentials grant authorizes the client as itself, without
# an attached user, clients that use it will not be able to access most of the Matrix
# client-server API. Administrative functionality that does not require a user
# will still be available."
)]
pub struct OAuthClient {
/// The client's client secret.
///
/// This must be supplied as the `client_secret` parameter when requesting
/// an access token with the OAuth 2.0 token endpoint. Continuwuity does
/// not check the `Authorization` header for requests to this endpoint.
pub client_secret: String,
/// A list of scopes that the client may request. Continuwuity allows static
/// clients to request the following scopes:
///
/// - "urn:matrix:client:cc.c10y.msc4484.server_administration" (MSC4484):
/// This scope grants access to the Matrix server administration APIs, as
/// well as Continuwuity's internal admin API (currently a work in
/// progress).
/// - "urn:matrix:client:api:*": This scope grants access to the Matrix
/// client-server API. Most endpoints require an authenticated Matrix user
/// and thus will not be usable by static clients.
///
/// The `urn:matrix:client:device:<id>` scope may not be requested by static
/// clients.
///
/// Scopes listed here are not granted by default. The client must
/// explicitly include them in the `scope` parameter of its access token
/// request.
///
/// default: []
pub scopes: BTreeSet<OAuthClientScope>,
}
const DEPRECATED_KEYS: &[&str] = &[ const DEPRECATED_KEYS: &[&str] = &[
"allow_check_for_updates", "allow_check_for_updates",
"allow_moderators_to_view_redacted_content", "allow_moderators_to_view_redacted_content",
-7
View File
@@ -125,12 +125,6 @@ impl ClientMetadata {
} }
} }
if self.grant_types.contains(&GrantType::ClientCredentials) {
return Err(
"Dynamically registered clients may not use the client credentials grant."
);
}
Ok(()) Ok(())
} }
} }
@@ -150,7 +144,6 @@ pub enum GrantType {
#[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")] #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
DeviceCode, DeviceCode,
RefreshToken, RefreshToken,
ClientCredentials,
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
+2 -8
View File
@@ -102,7 +102,7 @@ impl Display for RequestedScopes {
} }
} }
#[derive(Debug, Clone, Default, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RawScopes(String); pub struct RawScopes(String);
impl RawScopes { impl RawScopes {
@@ -257,11 +257,6 @@ pub enum TokenRequestType {
RefreshToken { RefreshToken {
refresh_token: String, refresh_token: String,
}, },
ClientCredentials {
client_secret: String,
#[serde(default)]
scope: RawScopes,
},
} }
impl TokenRequestType { impl TokenRequestType {
@@ -271,7 +266,6 @@ impl TokenRequestType {
| Self::AuthorizationCode { .. } => GrantType::AuthorizationCode, | Self::AuthorizationCode { .. } => GrantType::AuthorizationCode,
| Self::DeviceCode { .. } => GrantType::DeviceCode, | Self::DeviceCode { .. } => GrantType::DeviceCode,
| Self::RefreshToken { .. } => GrantType::RefreshToken, | Self::RefreshToken { .. } => GrantType::RefreshToken,
| Self::ClientCredentials { .. } => GrantType::ClientCredentials,
} }
} }
} }
@@ -281,7 +275,7 @@ pub struct TokenResponse {
pub access_token: String, pub access_token: String,
pub token_type: TokenType, pub token_type: TokenType,
pub expires_in: u64, pub expires_in: u64,
pub refresh_token: Option<String>, pub refresh_token: String,
pub scope: String, pub scope: String,
} }
+12 -119
View File
@@ -7,10 +7,10 @@ use std::{
use base64::Engine; use base64::Engine;
use conduwuit::{ use conduwuit::{
Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, Result, SyncMutex,
config::experiments::ToggledExperiment, config::experiments::ToggledExperiment,
error, info, error, info,
utils::{self, MutexMap, hash::sha256, string::constant_time_eq}, utils::{self, MutexMap, hash::sha256},
warn, warn,
}; };
use database::{Deserialized, Json, Map}; use database::{Deserialized, Json, Map};
@@ -27,9 +27,8 @@ use crate::{
client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType}, client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType},
grant::{ grant::{
AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod, AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RawScopes, DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RequestedScopes,
RequestedScopes, ResponseMode, TokenRequest, TokenRequestType, TokenResponse, ResponseMode, TokenRequest, TokenRequestType, TokenResponse, TokenType,
TokenType,
}, },
}, },
users::{self, DeviceToken, PreviousTokenAction}, users::{self, DeviceToken, PreviousTokenAction},
@@ -54,7 +53,6 @@ pub struct Service {
tickets: SyncMutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>, tickets: SyncMutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>,
pending_auth_code_grants: SyncMutex<LruCache<String, PendingAuthCodeGrant>>, pending_auth_code_grants: SyncMutex<LruCache<String, PendingAuthCodeGrant>>,
pending_device_code_grants: SyncMutex<LruCache<String, PendingDeviceCodeGrant>>, pending_device_code_grants: SyncMutex<LruCache<String, PendingDeviceCodeGrant>>,
client_credential_sessions: SyncMutex<HashMap<String, ClientCredentialsSession>>,
} }
struct Data { struct Data {
@@ -108,12 +106,6 @@ struct RefreshTokenInfo {
device_id: OwnedDeviceId, device_id: OwnedDeviceId,
} }
pub struct ClientCredentialsSession {
pub client_id: String,
pub scopes: BTreeSet<OAuthClientScope>,
created_at: SystemTime,
}
struct PendingAuthCodeGrant { struct PendingAuthCodeGrant {
authorizing_user: OwnedUserId, authorizing_user: OwnedUserId,
requested_scopes: RequestedScopes, requested_scopes: RequestedScopes,
@@ -209,7 +201,6 @@ impl crate::Service for Service {
tickets: SyncMutex::default(), tickets: SyncMutex::default(),
pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
client_credential_sessions: SyncMutex::default(),
})) }))
} }
@@ -506,25 +497,12 @@ impl Service {
pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> { pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> {
let TokenRequest { client_id, request } = request; let TokenRequest { client_id, request } = request;
if !matches!(request, TokenRequestType::ClientCredentials { .. }) { let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
// The client credentials grant can only be used by statically return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Invalid client ID"));
// registered clients, and the other grant types can };
// only be used by dynamically registered clients, so we
// don't look up the dynamic client metadata if the token request is
// for the client credentials grant.
let Some(client_metadata) = self.get_client_metadata(&client_id).await else { if !client_metadata.grant_types.contains(&request.grant_type()) {
return Err(OAuthError::new_static( return Err(OAuthError::unauthorized_client("Client cannot request this grant type"));
ErrorCode::InvalidClient,
"Invalid client ID",
));
};
if !client_metadata.grant_types.contains(&request.grant_type()) {
return Err(OAuthError::unauthorized_client(
"Client cannot request this grant type",
));
}
} }
match request { match request {
@@ -596,8 +574,6 @@ impl Service {
}, },
| TokenRequestType::RefreshToken { refresh_token } => | TokenRequestType::RefreshToken { refresh_token } =>
self.refresh_session(client_id, refresh_token).await, self.refresh_session(client_id, refresh_token).await,
| TokenRequestType::ClientCredentials { client_secret, scope: scopes } =>
self.create_client_credentials_token(&client_id, &client_secret, &scopes),
} }
} }
@@ -614,12 +590,8 @@ impl Service {
self.services.users.find_from_token(&token).await self.services.users.find_from_token(&token).await
{ {
(user_id, device_id) (user_id, device_id)
} else if self.get_client_credentials_session(&token).is_some() {
return Err(OAuthError::invalid_grant(
"Access tokens for static clients cannot be revoked.",
));
} else { } else {
return Err(OAuthError::invalid_grant("Invalid access or refresh token.")); return Err(OAuthError::invalid_grant("Invalid access or refersh token"));
}; };
// This will also call [`Self::remove_session`] // This will also call [`Self::remove_session`]
@@ -756,7 +728,7 @@ impl Service {
token_type: TokenType::Bearer, token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(), expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope: response_scope, scope: response_scope,
refresh_token: Some(refresh_token), refresh_token,
}) })
} }
@@ -883,89 +855,10 @@ impl Service {
token_type: TokenType::Bearer, token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(), expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope, scope,
refresh_token: Some(new_refresh_token), refresh_token: new_refresh_token,
}) })
} }
fn create_client_credentials_token(
&self,
client_id: &str,
client_secret: &str,
scopes: &RawScopes,
) -> Result<TokenResponse, OAuthError> {
let now = SystemTime::now();
let Some(client) = self.services.config.oauth.clients.get(client_id) else {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Unknown client ID"));
};
let RequestedScopes { device_id, scopes } = scopes
.to_scopes()
.map_err(|err| OAuthError::new(ErrorCode::InvalidGrant, err))?;
if device_id.is_some() {
return Err(OAuthError::new_static(
ErrorCode::InvalidGrant,
"Static clients may not request a device ID",
));
}
if !constant_time_eq(client_secret, &client.client_secret) {
return Err(OAuthError::new_static(
ErrorCode::InvalidClient,
"Client secret does not match",
));
}
if !scopes.is_subset(&client.scopes) {
return Err(OAuthError::new_static(
ErrorCode::InvalidScope,
"This client may not request those scopes",
));
}
let mut sessions = self.client_credential_sessions.lock();
// Clear expired sessions while we're at it
sessions.retain(|_, session| {
now.duration_since(session.created_at)
.is_ok_and(|age| age <= Self::ACCESS_TOKEN_MAX_AGE)
});
let access_token = Self::generate_token();
let scope = scopes.iter().join(" ");
sessions.insert(access_token.clone(), ClientCredentialsSession {
client_id: client_id.to_owned(),
scopes,
created_at: now,
});
Ok(TokenResponse {
access_token,
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
refresh_token: None,
scope,
})
}
pub fn get_client_credentials_session(
&self,
token: &str,
) -> Option<SyncMappedMutexGuard<'_, ClientCredentialsSession>> {
let sessions = self.client_credential_sessions.lock();
SyncMutexGuard::try_map(sessions, |sessions| {
sessions.get_mut(token).filter(|session| {
SystemTime::now()
.duration_since(session.created_at)
.is_ok_and(|age| age <= Self::ACCESS_TOKEN_MAX_AGE)
})
})
.ok()
}
pub async fn remove_session(&self, user_id: &UserId, device_id: &DeviceId) { pub async fn remove_session(&self, user_id: &UserId, device_id: &DeviceId) {
let _lock = self.session_mutex.lock(&(user_id, device_id)).await; let _lock = self.session_mutex.lock(&(user_id, device_id)).await;
let session_info = self.get_session_info_for_device(user_id, device_id).await; let session_info = self.get_session_info_for_device(user_id, device_id).await;
+5 -4
View File
@@ -27,6 +27,7 @@ use ruma::{
RoomVersionId, ServerName, UserId, RoomVersionId, ServerName, UserId,
events::{ events::{
AnySyncTimelineEvent, GlobalAccountDataEventType, TimelineEventType, AnySyncTimelineEvent, GlobalAccountDataEventType, TimelineEventType,
ignored_user_list::IgnoredUserMode,
push_rules::PushRulesEvent, push_rules::PushRulesEvent,
room::{ room::{
encrypted::Relation, encrypted::Relation,
@@ -402,11 +403,11 @@ impl super::Service {
// Don't notify the sender of their own events, and don't send from ignored users // Don't notify the sender of their own events, and don't send from ignored users
.ready_filter(|user| *user != pdu.sender()) .ready_filter(|user| *user != pdu.sender())
.filter_map(|recipient_user| async move { .filter_map(|recipient_user| async move {
(!self self.services
.services
.users .users
.user_is_ignored(pdu.sender(), &recipient_user) .user_ignore_mode(pdu.sender(), &recipient_user, pdu.room_id())
.await) .await
.is_none_or(|mode| matches!(mode, IgnoredUserMode::Soft))
.then_some(recipient_user) .then_some(recipient_user)
}) })
.collect() .collect()
+8 -5
View File
@@ -12,7 +12,10 @@ use ruma::{
appservice::event::push_events::v1::EphemeralData, appservice::event::push_events::v1::EphemeralData,
federation::transactions::edu::{Edu, TypingContent}, federation::transactions::edu::{Edu, TypingContent},
}, },
events::{EphemeralRoomEvent, SyncEphemeralRoomEvent, typing::TypingEventContent}, events::{
EphemeralRoomEvent, SyncEphemeralRoomEvent, ignored_user_list::IgnoredUserMode,
typing::TypingEventContent,
},
}; };
use crate::{Dep, globals, sending, sending::EduBuf, sync, users}; use crate::{Dep, globals, sending, sending::EduBuf, sync, users};
@@ -206,11 +209,11 @@ impl Service {
.into_keys() .into_keys()
.stream() .stream()
.filter_map(|typing_user_id| async move { .filter_map(|typing_user_id| async move {
(!self self.services
.services
.users .users
.user_is_ignored(&typing_user_id, sender_user) .user_ignore_mode(&typing_user_id, sender_user, Some(room_id))
.await) .await
.is_none_or(|mode| matches!(mode, IgnoredUserMode::Soft))
.then_some(typing_user_id) .then_some(typing_user_id)
}) })
.collect() .collect()
+44 -4
View File
@@ -14,11 +14,13 @@ use database::{Deserialized, Json};
use futures::{FutureExt, Stream, StreamExt}; use futures::{FutureExt, Stream, StreamExt};
use lettre::Address; use lettre::Address;
use ruma::{ use ruma::{
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, UserId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, RoomId, UserId,
api::client::profile::PropagateTo, api::client::profile::PropagateTo,
events::{ events::{
GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent, GlobalAccountDataEventType,
invite_permission_config::InvitePermissionAction, push_rules::PushRulesEvent, ignored_user_list::{IgnoredUserListEvent, IgnoredUserMode},
invite_permission_config::InvitePermissionAction,
push_rules::PushRulesEvent,
room::message::RoomMessageEventContent, room::message::RoomMessageEventContent,
}, },
profile::ProfileFieldValue, profile::ProfileFieldValue,
@@ -65,6 +67,7 @@ impl AccountStatus {
impl super::Service { impl super::Service {
/// Returns true/false based on whether the recipient/receiving user has /// Returns true/false based on whether the recipient/receiving user has
/// ignored the sender. /// ignored the sender.
#[deprecated(note = "Use user_ignore_mode instead")]
pub async fn user_is_ignored(&self, sender_user: &UserId, recipient_user: &UserId) -> bool { pub async fn user_is_ignored(&self, sender_user: &UserId, recipient_user: &UserId) -> bool {
self.services self.services
.account_data .account_data
@@ -79,6 +82,39 @@ impl super::Service {
}) })
} }
/// Returns the recipient's ignore mode for the sender, if the sender is
/// ignored. `None` if the recipient is not ignored at all.
pub async fn user_ignore_mode(
&self,
sender_user: &UserId,
recipient_user: &UserId,
room_id: Option<&RoomId>,
) -> Option<IgnoredUserMode> {
self.services
.account_data
.get_global(recipient_user, GlobalAccountDataEventType::IgnoredUserList)
.await
.ok()
.and_then(|ignored: IgnoredUserListEvent| {
ignored
.content
.ignored_users
.get(sender_user)
.map(ToOwned::to_owned)
})
.map(|ignore_entry| {
if !self.services.config.experiments.msc4596.is_enabled() {
IgnoredUserMode::Hard
} else {
match room_id {
| Some(room_id) => ignore_entry.mode(room_id),
| None => &ignore_entry.mode,
}
.to_owned()
}
})
}
/// Returns the recipient's filter level for an invite from the sender. /// Returns the recipient's filter level for an invite from the sender.
/// ///
/// If the sender is ignored by the recipient, `Ignore` is returned. /// If the sender is ignored by the recipient, `Ignore` is returned.
@@ -89,7 +125,11 @@ impl super::Service {
sender_user: &UserId, sender_user: &UserId,
recipient_user: &UserId, recipient_user: &UserId,
) -> FilterLevel { ) -> FilterLevel {
if self.user_is_ignored(sender_user, recipient_user).await { if self
.user_ignore_mode(sender_user, recipient_user, None)
.await
.is_some()
{
FilterLevel::Ignore FilterLevel::Ignore
} else { } else {
let (stable, unstable) = tokio::join!( let (stable, unstable) = tokio::join!(