Compare commits

..
21 changed files with 346 additions and 178 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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
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/gingershaped/ruwuma.git?rev=4eeece8f461b653d16f91064256080e8a959f584#4eeece8f461b653d16f91064256080e8a959f584" source = "git+https://github.com/ruma/ruma.git?rev=d6621e1355419c5ef9a7c260b28ae1c0e6722b86#d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
+2 -3
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/gingershaped/ruwuma.git" git = "https://github.com/ruma/ruma.git"
rev = "4eeece8f461b653d16f91064256080e8a959f584" rev = "d6621e1355419c5ef9a7c260b28ae1c0e6722b86"
features = [ features = [
"appservice-api-c", "appservice-api-c",
"client-api", "client-api",
@@ -390,7 +390,6 @@ features = [
"unstable-msc4363", "unstable-msc4363",
"unstable-msc4406", "unstable-msc4406",
"unstable-msc4439", "unstable-msc4439",
"unstable-msc4322",
"unstable-msc4354", "unstable-msc4354",
"unstable-msc4388", "unstable-msc4388",
"unstable-msc4480", "unstable-msc4480",
+1
View File
@@ -0,0 +1 @@
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.
-3
View File
@@ -1,3 +0,0 @@
Added unstable support for [MSC4322] media redaction. Contributed by @ginger.
[MSC4322]: https://github.com/matrix-org/matrix-spec-proposals/pull/4322
+42
View File
@@ -2675,6 +2675,48 @@
# 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.
+1 -22
View File
@@ -18,7 +18,7 @@ use ruma::{
get_content, get_content_as_filename, get_content_thumbnail, get_media_config, get_content, get_content_as_filename, get_content_thumbnail, get_media_config,
get_media_preview, get_media_preview,
}, },
media::{self, create_content}, media::create_content,
}, },
}; };
use service::media::mxc::Mxc; use service::media::mxc::Mxc;
@@ -240,27 +240,6 @@ pub(crate) async fn get_media_preview_route(
}) })
} }
/// # `POST /_matrix/client/unstable/uk.timedout.msc4322/media/redact/{server_name}/{media_id}`
pub(crate) async fn unstable_redact_media_route(
State(services): State<crate::State>,
body: Ruma<media::redact::msc4322::Request>,
) -> Result<media::redact::msc4322::Response> {
let user = body.identity.expect_sender_user()?;
let mxc = Mxc {
server_name: &body.server_name,
media_id: &body.media_id,
};
if !(services.media.user_owns(user, &mxc).await || services.admin.user_is_admin(user).await) {
return Err!(Request(Forbidden("You cannot redact this media.")));
}
services.media.redact(&mxc).await?;
Ok(media::redact::msc4322::Response::new())
}
async fn fetch_thumbnail_meta( async fn fetch_thumbnail_meta(
services: &Services, services: &Services,
mxc: &Mxc<'_>, mxc: &Mxc<'_>,
+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"], "grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "client_credentials"],
"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,
+10 -3
View File
@@ -2,6 +2,7 @@ use std::collections::BTreeMap;
use axum::extract::State; use axum::extract::State;
use conduwuit::{Err, Result}; use conduwuit::{Err, Result};
use conduwuit_service::sending::EduBuf;
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
api::{ api::{
@@ -43,8 +44,9 @@ pub(crate) async fn send_event_to_device_route(
messages.insert(target_user_id.clone(), map); messages.insert(target_user_id.clone(), map);
let count = services.globals.next_count()?; let count = services.globals.next_count()?;
services.sending.send_edu_server( let mut buf = EduBuf::new();
target_user_id.server_name(), serde_json::to_writer(
&mut buf,
&Edu::DirectToDevice(assign!( &Edu::DirectToDevice(assign!(
DirectDeviceContent::new( DirectDeviceContent::new(
sender_user.to_owned(), sender_user.to_owned(),
@@ -53,7 +55,12 @@ pub(crate) async fn send_event_to_device_route(
), ),
{ messages } { messages }
)), )),
)?; )
.expect("DirectToDevice EDU can be serialized");
services
.sending
.send_edu_server(target_user_id.server_name(), buf)?;
continue; continue;
} }
-1
View File
@@ -158,7 +158,6 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::get_content_as_filename_route) .ruma_route(&client::get_content_as_filename_route)
.ruma_route(&client::get_media_preview_route) .ruma_route(&client::get_media_preview_route)
.ruma_route(&client::get_media_config_route) .ruma_route(&client::get_media_config_route)
.ruma_route(&client::unstable_redact_media_route)
.ruma_route(&client::get_devices_route) .ruma_route(&client::get_devices_route)
.ruma_route(&client::get_device_route) .ruma_route(&client::get_device_route)
.ruma_route(&client::update_device_route) .ruma_route(&client::update_device_route)
+25 -1
View File
@@ -47,6 +47,7 @@ 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 {
@@ -54,6 +55,7 @@ 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,
} }
} }
@@ -61,6 +63,8 @@ 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."))),
} }
} }
@@ -68,6 +72,7 @@ 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,
} }
} }
@@ -77,12 +82,14 @@ 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 { .. } => None, | Self::User { .. } | Self::StaticClient => None,
| Self::Appservice { appservice_info, .. } => Some(appservice_info), | Self::Appservice { appservice_info, .. } => Some(appservice_info),
} }
} }
@@ -425,6 +432,23 @@ 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.
-4
View File
@@ -38,10 +38,6 @@ pub(crate) async fn get_content_route(
content_disposition, content_disposition,
); );
services
.media
.track_remote_download(&body.identity, &body.media_id);
Ok(get_content::v1::Response::new( Ok(get_content::v1::Response::new(
ContentMetadata::new(), ContentMetadata::new(),
FileOrLocation::File(content), FileOrLocation::File(content),
+9
View File
@@ -346,6 +346,15 @@ 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(())
} }
+54
View File
@@ -29,6 +29,7 @@ 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,
}, },
@@ -2750,7 +2751,12 @@ 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 {
@@ -2992,6 +2998,54 @@ 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",
+3 -28
View File
@@ -1,15 +1,12 @@
use std::{collections::HashSet, sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
use conduwuit::{ use conduwuit::{
Err, Result, at, debug, debug_info, err, Err, Result, debug, debug_info, err,
utils::{ReadyExt, str_from_bytes, stream::TryIgnore, string_from_bytes}, utils::{ReadyExt, str_from_bytes, stream::TryIgnore, string_from_bytes},
}; };
use database::{Database, Interfix, Map}; use database::{Database, Interfix, Map};
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{OwnedMxcUri, OwnedUserId, UserId, http_headers::ContentDisposition};
OwnedMxcUri, OwnedServerName, OwnedUserId, ServerName, UserId,
http_headers::ContentDisposition,
};
use super::{preview::UrlPreviewData, thumbnail::Dim}; use super::{preview::UrlPreviewData, thumbnail::Dim};
use crate::media::mxc::Mxc; use crate::media::mxc::Mxc;
@@ -18,8 +15,6 @@ pub(crate) struct Data {
mediaid_file: Arc<Map>, mediaid_file: Arc<Map>,
mediaid_user: Arc<Map>, mediaid_user: Arc<Map>,
url_previews: Arc<Map>, url_previews: Arc<Map>,
mediaidremote_remotedownload: Arc<Map>,
mediaid_redacted: Arc<Map>,
} }
#[derive(Debug)] #[derive(Debug)]
@@ -35,8 +30,6 @@ impl Data {
mediaid_file: db["mediaid_file"].clone(), mediaid_file: db["mediaid_file"].clone(),
mediaid_user: db["mediaid_user"].clone(), mediaid_user: db["mediaid_user"].clone(),
url_previews: db["url_previews"].clone(), url_previews: db["url_previews"].clone(),
mediaidremote_remotedownload: db["mediaidremote_remotedownload"].clone(),
mediaid_redacted: db["mediaid_redacted"].clone(),
} }
} }
@@ -337,22 +330,4 @@ impl Data {
* I'll do it later. */ * I'll do it later. */
}) })
} }
pub(super) fn track_remote_download(&self, remote: &ServerName, media_id: &str) {
self.mediaidremote_remotedownload
.put_raw((media_id, remote), []);
}
pub(super) async fn find_remote_downloads(&self, media_id: &str) -> HashSet<OwnedServerName> {
self.mediaidremote_remotedownload
.keys_prefix::<(String, OwnedServerName), _>(media_id)
.ignore_err()
.map(at!(1))
.collect()
.await
}
pub(super) fn mark_redacted(&self, media_id: &str) {
self.mediaid_redacted.insert(media_id, []);
}
} }
+2 -45
View File
@@ -5,7 +5,7 @@ mod preview;
mod remote; mod remote;
mod tests; mod tests;
mod thumbnail; mod thumbnail;
use std::{collections::HashSet, path::PathBuf, sync::Arc, time::SystemTime}; use std::{path::PathBuf, sync::Arc, time::SystemTime};
use async_trait::async_trait; use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose}; use base64::{Engine as _, engine::general_purpose};
@@ -19,11 +19,7 @@ use conduwuit::{
}, },
warn, warn,
}; };
use ruma::{ use ruma::{OwnedMxcUri, UserId, http_headers::ContentDisposition};
OwnedMxcUri, OwnedServerName, ServerName, UserId,
api::federation::transactions::edu::{Edu, MediaRedactionContent},
http_headers::ContentDisposition,
};
use tokio::{ use tokio::{
fs, fs,
io::{AsyncReadExt, AsyncWriteExt, BufReader}, io::{AsyncReadExt, AsyncWriteExt, BufReader},
@@ -175,31 +171,6 @@ impl Service {
} }
} }
/// Mark a media file as redacted and delete it from the database.
pub async fn redact(&self, mxc: &Mxc<'_>) -> Result<()> {
self.db.mark_redacted(mxc.media_id);
self.delete(mxc).await?;
let edu = Edu::MediaRedaction(MediaRedactionContent::new(mxc.media_id.to_owned()));
for server in self.find_remote_downloads(mxc.media_id).await {
if let Err(err) = self.services.sending.send_edu_server(&server, &edu) {
error!(?server, %mxc, ?err, "Failed to queue media redaction EDU");
}
}
Ok(())
}
/// Check if a user uploaded a file with the given MXC.
pub async fn user_owns(&self, user: &UserId, mxc: &Mxc<'_>) -> bool {
// TODO: do this more efficiently when we refactor this garbage fire of
// a service
let mxc = OwnedMxcUri::from(mxc.to_string());
self.db.get_all_user_mxcs(user).await.contains(&mxc)
}
/// Deletes all media by the specified user /// Deletes all media by the specified user
/// ///
/// currently, this is only practical for local users /// currently, this is only practical for local users
@@ -292,20 +263,6 @@ impl Service {
Ok(mxcs) Ok(mxcs)
} }
/// Mark a remote server as having downloaded a media file.
pub fn track_remote_download(&self, remote: &ServerName, media_id: &str) {
self.db.track_remote_download(remote, media_id);
}
/// Find all remote servers that have downloaded the local media file with
/// the given ID.
pub fn find_remote_downloads(
&self,
media_id: &str,
) -> impl Future<Output = HashSet<OwnedServerName>> {
self.db.find_remote_downloads(media_id)
}
/// Deletes all media files in the given time frame. /// Deletes all media files in the given time frame.
/// Returns a usize with the amount of media files deleted. /// Returns a usize with the amount of media files deleted.
pub async fn delete_all_media_within_timeframe( pub async fn delete_all_media_within_timeframe(
+7
View File
@@ -125,6 +125,12 @@ impl ClientMetadata {
} }
} }
if self.grant_types.contains(&GrantType::ClientCredentials) {
return Err(
"Dynamically registered clients may not use the client credentials grant."
);
}
Ok(()) Ok(())
} }
} }
@@ -144,6 +150,7 @@ 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)]
+8 -2
View File
@@ -102,7 +102,7 @@ impl Display for RequestedScopes {
} }
} }
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct RawScopes(String); pub struct RawScopes(String);
impl RawScopes { impl RawScopes {
@@ -257,6 +257,11 @@ pub enum TokenRequestType {
RefreshToken { RefreshToken {
refresh_token: String, refresh_token: String,
}, },
ClientCredentials {
client_secret: String,
#[serde(default)]
scope: RawScopes,
},
} }
impl TokenRequestType { impl TokenRequestType {
@@ -266,6 +271,7 @@ 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,
} }
} }
} }
@@ -275,7 +281,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: String, pub refresh_token: Option<String>,
pub scope: String, pub scope: String,
} }
+119 -12
View File
@@ -7,10 +7,10 @@ use std::{
use base64::Engine; use base64::Engine;
use conduwuit::{ use conduwuit::{
Result, SyncMutex, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard,
config::experiments::ToggledExperiment, config::experiments::ToggledExperiment,
error, info, error, info,
utils::{self, MutexMap, hash::sha256}, utils::{self, MutexMap, hash::sha256, string::constant_time_eq},
warn, warn,
}; };
use database::{Deserialized, Json, Map}; use database::{Deserialized, Json, Map};
@@ -27,8 +27,9 @@ 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, RequestedScopes, DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RawScopes,
ResponseMode, TokenRequest, TokenRequestType, TokenResponse, TokenType, RequestedScopes, ResponseMode, TokenRequest, TokenRequestType, TokenResponse,
TokenType,
}, },
}, },
users::{self, DeviceToken, PreviousTokenAction}, users::{self, DeviceToken, PreviousTokenAction},
@@ -53,6 +54,7 @@ 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 {
@@ -106,6 +108,12 @@ 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,
@@ -201,6 +209,7 @@ 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(),
})) }))
} }
@@ -497,12 +506,25 @@ 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;
let Some(client_metadata) = self.get_client_metadata(&client_id).await else { if !matches!(request, TokenRequestType::ClientCredentials { .. }) {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Invalid client ID")); // The client credentials grant can only be used by statically
}; // 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.
if !client_metadata.grant_types.contains(&request.grant_type()) { let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
return Err(OAuthError::unauthorized_client("Client cannot request this grant type")); return Err(OAuthError::new_static(
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 {
@@ -574,6 +596,8 @@ 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),
} }
} }
@@ -590,8 +614,12 @@ 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 refersh token")); return Err(OAuthError::invalid_grant("Invalid access or refresh token."));
}; };
// This will also call [`Self::remove_session`] // This will also call [`Self::remove_session`]
@@ -728,7 +756,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, refresh_token: Some(refresh_token),
}) })
} }
@@ -855,10 +883,89 @@ 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: new_refresh_token, refresh_token: Some(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;
+18 -10
View File
@@ -23,7 +23,11 @@ use ruma::{
}; };
use self::data::{Data, ReceiptItem}; use self::data::{Data, ReceiptItem};
use crate::{Dep, rooms, sending, sync}; use crate::{
Dep, rooms,
sending::{self, EduBuf},
sync,
};
pub struct Service { pub struct Service {
services: Services, services: Services,
@@ -68,10 +72,12 @@ impl Service {
self.services.sync.wake_all_joined(room_id).await; self.services.sync.wake_all_joined(room_id).await;
// update appservices // update appservices
let edu = EphemeralData::Receipt(event); let edu = EphemeralData::Receipt(event);
let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &edu).expect("Serialized EphemeralData::Receipt");
_ = self _ = self
.services .services
.sending .sending
.send_edu_appservice_room(room_id, &edu) .send_edu_appservice_room(room_id, buf)
.await .await
.log_err(); .log_err();
} }
@@ -154,17 +160,19 @@ impl Service {
)]), )]),
)]), )]),
)]; )];
let event = ReceiptEvent::new(
room_id.to_owned(),
ReceiptEventContent::from_iter(receipt_content),
);
let edu = EphemeralData::Receipt(event);
let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &edu).expect("Serialized EphemeralData::Receipt");
_ = self _ = self
.services .services
.sending .sending
.send_edu_appservice_room_filtered( .send_edu_appservice_room_filtered(room_id, buf, |appservice| {
room_id, appservice.is_user_match(user_id)
&EphemeralData::Receipt(ReceiptEvent::new( })
room_id.to_owned(),
ReceiptEventContent::from_iter(receipt_content),
)),
|appservice| appservice.is_user_match(user_id),
)
.await .await
.log_err(); .log_err();
} }
+11 -4
View File
@@ -15,7 +15,7 @@ use ruma::{
events::{EphemeralRoomEvent, SyncEphemeralRoomEvent, typing::TypingEventContent}, events::{EphemeralRoomEvent, SyncEphemeralRoomEvent, typing::TypingEventContent},
}; };
use crate::{Dep, globals, sending, sync, users}; use crate::{Dep, globals, sending, sending::EduBuf, sync, users};
pub struct Service { pub struct Service {
server: Arc<Server>, server: Arc<Server>,
@@ -244,9 +244,13 @@ impl Service {
return Ok(()); return Ok(());
} }
let edu = Edu::Typing(TypingContent::new(room_id.to_owned(), user_id.to_owned(), typing)); let content = TypingContent::new(room_id.to_owned(), user_id.to_owned(), typing);
let edu = Edu::Typing(content);
self.services.sending.send_edu_room(room_id, &edu).await?; let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &edu).expect("Serialized Edu::Typing");
self.services.sending.send_edu_room(room_id, buf).await?;
Ok(()) Ok(())
} }
@@ -257,9 +261,12 @@ impl Service {
self.typings_content(room_id), self.typings_content(room_id),
)); ));
let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &edu).expect("Serialized Edu::Typing");
self.services self.services
.sending .sending
.send_edu_appservice_room(room_id, &edu) .send_edu_appservice_room(room_id, buf)
.await .await
} }
} }
+22 -28
View File
@@ -30,9 +30,8 @@ use futures::{FutureExt, Stream, StreamExt, stream::FuturesUnordered};
use ruma::{ use ruma::{
OwnedServerName, RoomId, ServerName, UserId, OwnedServerName, RoomId, ServerName, UserId,
api::{ api::{
OutgoingRequest, OutgoingRequest, auth_scheme::NoAuthentication,
appservice::event::push_events::v1::EphemeralData, auth_scheme::NoAuthentication, federation::authentication::ServerSignatures, path_builder::PathBuilder,
federation::{authentication::ServerSignatures, transactions::edu::Edu}, path_builder::PathBuilder,
}, },
}; };
use tokio::{task, task::JoinSet, time::sleep}; use tokio::{task, task::JoinSet, time::sleep};
@@ -279,12 +278,10 @@ impl Service {
Ok(()) Ok(())
} }
#[tracing::instrument(skip(self, server, edu), level = "debug")] #[tracing::instrument(skip(self, server, serialized), level = "debug")]
pub fn send_edu_server(&self, server: &ServerName, edu: &Edu) -> Result { pub fn send_edu_server(&self, server: &ServerName, serialized: EduBuf) -> Result {
let dest = Destination::Federation(server.to_owned()); let dest = Destination::Federation(server.to_owned());
let mut buf = EduBuf::new(); let event = SendingEvent::Edu(serialized);
serde_json::to_writer(&mut buf, edu).expect("should be able to serialize edu");
let event = SendingEvent::Edu(buf);
let _cork = self.db.db.cork(); let _cork = self.db.db.cork();
let keys = self.db.queue_requests(once((&event, &dest))); let keys = self.db.queue_requests(once((&event, &dest)));
self.dispatch(Msg { self.dispatch(Msg {
@@ -294,12 +291,10 @@ impl Service {
}) })
} }
#[tracing::instrument(skip(self, edu), level = "debug")] #[tracing::instrument(skip(self, serialized), level = "debug")]
pub fn send_edu_appservice(&self, appservice_id: &str, edu: &EphemeralData) -> Result { pub fn send_edu_appservice(&self, appservice_id: &str, serialized: EduBuf) -> Result {
let dest = Destination::Appservice(appservice_id.to_owned()); let dest = Destination::Appservice(appservice_id.to_owned());
let mut buf = EduBuf::new(); let event = SendingEvent::Edu(serialized);
serde_json::to_writer(&mut buf, edu).expect("should be able to serialize edu");
let event = SendingEvent::Edu(buf);
let _cork = self.db.db.cork(); let _cork = self.db.db.cork();
let keys = self.db.queue_requests(once((&event, &dest))); let keys = self.db.queue_requests(once((&event, &dest)));
self.dispatch(Msg { self.dispatch(Msg {
@@ -309,21 +304,21 @@ impl Service {
}) })
} }
#[tracing::instrument(skip(self, room_id, edu), level = "debug")] #[tracing::instrument(skip(self, room_id, serialized), level = "debug")]
pub async fn send_edu_appservice_room( pub async fn send_edu_appservice_room(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
edu: &EphemeralData, serialized: EduBuf,
) -> Result<()> { ) -> Result<()> {
self.send_edu_appservice_room_filtered(room_id, edu, |_| true) self.send_edu_appservice_room_filtered(room_id, serialized, |_| true)
.await .await
} }
#[tracing::instrument(skip(self, room_id, edu, filter), level = "debug")] #[tracing::instrument(skip(self, room_id, serialized, filter), level = "debug")]
pub async fn send_edu_appservice_room_filtered<F>( pub async fn send_edu_appservice_room_filtered<F>(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
edu: &EphemeralData, serialized: EduBuf,
filter: F, filter: F,
) -> Result<()> ) -> Result<()>
where where
@@ -355,7 +350,7 @@ impl Service {
|| matching_aliases(appservice.aliases.clone()).await || matching_aliases(appservice.aliases.clone()).await
{ {
_ = self _ = self
.send_edu_appservice(&appservice.registration.id, edu) .send_edu_appservice(&appservice.registration.id, serialized.clone())
.inspect_err(|e| { .inspect_err(|e| {
warn!( warn!(
"failed to send EDU to appservice {}: {e:?}", "failed to send EDU to appservice {}: {e:?}",
@@ -367,27 +362,26 @@ impl Service {
Ok(()) Ok(())
} }
#[tracing::instrument(skip(self, room_id, edu), level = "debug")] #[tracing::instrument(skip(self, room_id, serialized), level = "debug")]
pub async fn send_edu_room(&self, room_id: &RoomId, edu: &Edu) -> Result { pub async fn send_edu_room(&self, room_id: &RoomId, serialized: EduBuf) -> Result {
let servers = self let servers = self
.services .services
.state_cache .state_cache
.room_servers(room_id) .room_servers(room_id)
.ready_filter(|server_name| !self.services.globals.server_is_ours(server_name)); .ready_filter(|server_name| !self.services.globals.server_is_ours(server_name));
self.send_edu_servers(servers, edu).await self.send_edu_servers(servers, serialized).await
} }
#[tracing::instrument(skip(self, servers, edu), level = "debug")] #[tracing::instrument(skip(self, servers, serialized), level = "debug")]
pub async fn send_edu_servers<S>(&self, servers: S, edu: &Edu) -> Result pub async fn send_edu_servers<S>(&self, servers: S, serialized: EduBuf) -> Result
where where
S: Stream<Item = OwnedServerName> + Send, S: Stream<Item = OwnedServerName> + Send,
{ {
let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, edu).expect("should be able to serialize edu");
let requests = servers let requests = servers
.map(|server| (Destination::Federation(server), SendingEvent::Edu(buf.clone()))) .map(|server| {
(Destination::Federation(server), SendingEvent::Edu(serialized.clone()))
})
.collect::<Vec<_>>() .collect::<Vec<_>>()
.await; .await;