Compare commits

..
Author SHA1 Message Date
Ginger 6e526b40c4 chore: News fragment 2026-11-04 15:50:50 -05:00
Ginger 7b8af120aa feat: Add support for MSC4322 2026-11-04 15:47:54 -05:00
Ginger 4b4918d677 refactor(sending): Stop passing byte buffers(?!) to EDU send methods 2026-11-04 15:47:54 -05:00
29 changed files with 199 additions and 390 deletions

No files matched your search

Generated
+11 -11
View File
@@ -4997,7 +4997,7 @@ dependencies = [
[[package]]
name = "ruma"
version = "0.17.2"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"assign",
"js_int",
@@ -5016,7 +5016,7 @@ dependencies = [
[[package]]
name = "ruma-appservice-api"
version = "0.17.1"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"http",
"js_int",
@@ -5029,7 +5029,7 @@ dependencies = [
[[package]]
name = "ruma-client-api"
version = "0.25.2"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"as_variant",
"assign",
@@ -5051,7 +5051,7 @@ dependencies = [
[[package]]
name = "ruma-common"
version = "0.20.2"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"as_variant",
"base64 0.23.1",
@@ -5084,7 +5084,7 @@ dependencies = [
[[package]]
name = "ruma-events"
version = "0.35.2"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"as_variant",
"indexmap 2.14.2",
@@ -5105,7 +5105,7 @@ dependencies = [
[[package]]
name = "ruma-federation-api"
version = "0.16.1"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"bytes",
"http",
@@ -5127,7 +5127,7 @@ dependencies = [
[[package]]
name = "ruma-identifiers-validation"
version = "0.14.0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"js_int",
"thiserror 2.0.21",
@@ -5136,7 +5136,7 @@ dependencies = [
[[package]]
name = "ruma-macros"
version = "0.20.2"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"as_variant",
"cfg-if",
@@ -5152,7 +5152,7 @@ dependencies = [
[[package]]
name = "ruma-push-gateway-api"
version = "0.16.0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"js_int",
"ruma-common",
@@ -5164,7 +5164,7 @@ dependencies = [
[[package]]
name = "ruma-signatures"
version = "0.22.1"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"base64 0.23.1",
"ed25519-dalek 3.0.0",
@@ -5181,7 +5181,7 @@ dependencies = [
[[package]]
name = "ruma-state-res"
version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
source = "git+https://github.com/gingershaped/ruwuma.git?rev=1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62#1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
dependencies = [
"js_int",
"ruma-common",
+3 -2
View File
@@ -348,8 +348,8 @@ version = "1.1.1"
# Used for matrix spec type definitions and helpers
[workspace.dependencies.ruma]
git = "https://github.com/ruma/ruma.git"
rev = "0ed7fba34213f18a628a56f527c6cc795cd7eef5"
git = "https://github.com/gingershaped/ruwuma.git"
rev = "1e2c07dc7b65df9a35d9e3c2cedc13857dae8a62"
features = [
"appservice-api-c",
"client-api",
@@ -381,6 +381,7 @@ features = [
"unstable-msc4143",
"unstable-msc4293",
"unstable-msc4363",
"unstable-msc4322",
"unstable-msc4406",
"unstable-msc4439",
"unstable-msc4354",
-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 +0,0 @@
Fix new devices sometimes never reaching other users' device lists. Contributed by @eleboucher.
@@ -1 +0,0 @@
Fix to-device messages, including room keys, sometimes being lost before delivery. Contributed by @eleboucher.
-1
View File
@@ -1 +0,0 @@
Fixed push notifications for membership events setting `user_is_target` based on the sender rather than the user being notified.
+3
View File
@@ -0,0 +1,3 @@
Added unstable support for [MSC4322] media redaction. Contributed by @ginger.
[MSC4322]: https://github.com/matrix-org/matrix-spec-proposals/pull/4322
-42
View File
@@ -2680,45 +2680,3 @@
#
# env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE
#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 = []
+22 -1
View File
@@ -18,7 +18,7 @@ use ruma::{
get_content, get_content_as_filename, get_content_thumbnail, get_media_config,
get_media_preview,
},
media::create_content,
media::{self, create_content},
},
};
use service::media::mxc::Mxc;
@@ -238,6 +238,27 @@ 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::unstable::Request>,
) -> Result<media::redact::unstable::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::unstable::Response::new())
}
async fn fetch_thumbnail_meta(
services: &Services,
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(),
"code_challenge_methods_supported": ["S256"],
"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(),
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
"prompt_values_supported": prompt_values_supported,
+3 -10
View File
@@ -2,7 +2,6 @@ use std::collections::BTreeMap;
use axum::extract::State;
use conduwuit::{Err, Result};
use conduwuit_service::sending::EduBuf;
use futures::StreamExt;
use ruma::{
api::{
@@ -44,9 +43,8 @@ pub(crate) async fn send_event_to_device_route(
messages.insert(target_user_id.clone(), map);
let count = services.globals.next_count()?;
let mut buf = EduBuf::new();
serde_json::to_writer(
&mut buf,
services.sending.send_edu_server(
target_user_id.server_name(),
&Edu::DirectToDevice(assign!(
DirectDeviceContent::new(
sender_user.to_owned(),
@@ -55,12 +53,7 @@ pub(crate) async fn send_event_to_device_route(
),
{ messages }
)),
)
.expect("DirectToDevice EDU can be serialized");
services
.sending
.send_edu_server(target_user_id.server_name(), buf)?;
)?;
continue;
}
+1
View File
@@ -157,6 +157,7 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::get_content_as_filename_route)
.ruma_route(&client::get_media_preview_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_device_route)
.ruma_route(&client::update_device_route)
+1 -25
View File
@@ -41,7 +41,6 @@ pub(crate) enum ClientIdentity {
sender_device: Option<OwnedDeviceId>,
appservice_info: Box<RegistrationInfo>,
},
StaticClient,
}
impl ClientIdentity {
@@ -49,7 +48,6 @@ impl ClientIdentity {
match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Some(sender_user),
| Self::StaticClient => None,
}
}
@@ -57,8 +55,6 @@ impl ClientIdentity {
match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Ok(sender_user),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
}
}
@@ -66,7 +62,6 @@ impl ClientIdentity {
match self {
| Self::User { sender_device, .. } => Some(sender_device),
| Self::Appservice { sender_device, .. } => sender_device.as_deref(),
| Self::StaticClient => None,
}
}
@@ -76,14 +71,12 @@ impl ClientIdentity {
| Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device),
| Self::Appservice { sender_device: None, .. } =>
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> {
match self {
| Self::User { .. } | Self::StaticClient => None,
| Self::User { .. } => None,
| Self::Appservice { appservice_info, .. } => Some(appservice_info),
}
}
@@ -399,23 +392,6 @@ async fn check_access_token(
sender_device,
appservice_info: Box::new(appservice_info),
})
} else if let Some(session) = services.oauth.get_client_credentials_session(token).await {
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 {
Err(Error::Request(
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
+4
View File
@@ -38,6 +38,10 @@ pub(crate) async fn get_content_route(
content_disposition,
);
services
.media
.track_remote_download(&body.identity, &body.media_id);
Ok(get_content::v1::Response::new(
ContentMetadata::new(),
FileOrLocation::File(content),
-9
View File
@@ -353,15 +353,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(())
}
-54
View File
@@ -24,7 +24,6 @@ use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
RoomVersionId, ServerName,
api::{
OAuthClientScope,
client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
federation::discovery::OldVerifyKey,
},
@@ -2747,12 +2746,7 @@ pub struct OauthConfig {
compatibility_mode: OAuthMode,
/// display: hidden
#[serde(default)]
pub oidc: Option<OidcConfig>,
/// display: hidden
#[serde(default)]
pub clients: HashMap<String, OAuthClient>,
}
impl OauthConfig {
@@ -2966,54 +2960,6 @@ impl TrustedServerConfig {
}
}
#[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] = &[
"cache_capacity",
"conduit_cache_capacity_modifier",
+2 -6
View File
@@ -21,9 +21,7 @@ impl Data {
}
}
pub fn next_count(&self) -> Result<u64> { self.next_count_with(|_| ()) }
pub fn next_count_with(&self, write: impl FnOnce(u64)) -> Result<u64> {
pub fn next_count(&self) -> Result<u64> {
let _cork = self.db.cork();
let mut lock = self.counter.write();
let counter: &mut u64 = &mut lock;
@@ -32,9 +30,7 @@ impl Data {
"counter mismatch"
);
let next = counter.checked_add(1).unwrap_or(*counter);
write(next);
*counter = next;
*counter = counter.checked_add(1).unwrap_or(*counter);
self.global.insert(COUNTER, counter.to_be_bytes());
-5
View File
@@ -80,11 +80,6 @@ impl Service {
#[inline]
pub fn next_count(&self) -> Result<u64> { self.db.next_count() }
#[inline]
pub fn next_count_with(&self, write: impl FnOnce(u64)) -> Result<u64> {
self.db.next_count_with(write)
}
#[inline]
pub fn current_count(&self) -> Result<u64> { Ok(self.db.current_count()) }
+28 -3
View File
@@ -1,12 +1,15 @@
use std::{sync::Arc, time::Duration};
use std::{collections::HashSet, sync::Arc, time::Duration};
use conduwuit::{
Err, Result, debug, debug_info, err,
Err, Result, at, debug, debug_info, err,
utils::{ReadyExt, str_from_bytes, stream::TryIgnore, string_from_bytes},
};
use database::{Database, Interfix, Map};
use futures::StreamExt;
use ruma::{OwnedMxcUri, OwnedUserId, UserId, http_headers::ContentDisposition};
use ruma::{
OwnedMxcUri, OwnedServerName, OwnedUserId, ServerName, UserId,
http_headers::ContentDisposition,
};
use super::{preview::UrlPreviewData, thumbnail::Dim};
use crate::media::mxc::Mxc;
@@ -15,6 +18,8 @@ pub(crate) struct Data {
mediaid_file: Arc<Map>,
mediaid_user: Arc<Map>,
url_previews: Arc<Map>,
mediaidremote_remotedownload: Arc<Map>,
mediaid_redacted: Arc<Map>,
}
#[derive(Debug)]
@@ -30,6 +35,8 @@ impl Data {
mediaid_file: db["mediaid_file"].clone(),
mediaid_user: db["mediaid_user"].clone(),
url_previews: db["url_previews"].clone(),
mediaidremote_remotedownload: db["mediaidremote_remotedownload"].clone(),
mediaid_redacted: db["mediaid_redacted"].clone(),
}
}
@@ -348,4 +355,22 @@ impl Data {
audio_size,
})
}
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, []);
}
}
+45 -2
View File
@@ -5,7 +5,7 @@ mod preview;
mod remote;
mod tests;
mod thumbnail;
use std::{path::PathBuf, sync::Arc, time::SystemTime};
use std::{collections::HashSet, path::PathBuf, sync::Arc, time::SystemTime};
use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose};
@@ -19,7 +19,11 @@ use conduwuit::{
},
warn,
};
use ruma::{OwnedMxcUri, UserId, http_headers::ContentDisposition};
use ruma::{
OwnedMxcUri, OwnedServerName, ServerName, UserId,
api::federation::transactions::edu::{Edu, MediaRedactionContent},
http_headers::ContentDisposition,
};
use tokio::{
fs,
io::{AsyncReadExt, AsyncWriteExt, BufReader},
@@ -158,6 +162,31 @@ 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
///
/// currently, this is only practical for local users
@@ -255,6 +284,20 @@ impl Service {
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.
/// Returns a usize with the amount of media files deleted.
pub async fn delete_all_media_within_timeframe(
-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(())
}
}
@@ -150,7 +144,6 @@ pub enum GrantType {
#[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
DeviceCode,
RefreshToken,
ClientCredentials,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
+1 -6
View File
@@ -225,10 +225,6 @@ pub enum TokenRequestType {
RefreshToken {
refresh_token: String,
},
ClientCredentials {
client_secret: String,
scope: RawScopes,
},
}
impl TokenRequestType {
@@ -238,7 +234,6 @@ impl TokenRequestType {
| Self::AuthorizationCode { .. } => GrantType::AuthorizationCode,
| Self::DeviceCode { .. } => GrantType::DeviceCode,
| Self::RefreshToken { .. } => GrantType::RefreshToken,
| Self::ClientCredentials { .. } => GrantType::ClientCredentials,
}
}
}
@@ -248,7 +243,7 @@ pub struct TokenResponse {
pub access_token: String,
pub token_type: TokenType,
pub expires_in: u64,
pub refresh_token: Option<String>,
pub refresh_token: String,
pub scope: String,
}
+10 -114
View File
@@ -23,9 +23,8 @@ use crate::{
client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType},
grant::{
AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RawScopes,
RequestedScopes, ResponseMode, TokenRequest, TokenRequestType, TokenResponse,
TokenType,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RequestedScopes,
ResponseMode, TokenRequest, TokenRequestType, TokenResponse, TokenType,
},
},
users::{self, DeviceToken},
@@ -40,7 +39,6 @@ pub struct Service {
tickets: SyncMutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>,
pending_auth_code_grants: SyncMutex<LruCache<String, PendingAuthCodeGrant>>,
pending_device_code_grants: SyncMutex<LruCache<String, PendingDeviceCodeGrant>>,
client_credential_sessions: tokio::sync::Mutex<HashMap<String, ClientCredentialsSession>>,
}
struct Data {
@@ -80,12 +78,6 @@ struct RefreshTokenInfo {
device_id: OwnedDeviceId,
}
pub struct ClientCredentialsSession {
pub client_id: String,
pub scopes: BTreeSet<OAuthClientScope>,
created_at: SystemTime,
}
struct PendingAuthCodeGrant {
authorizing_user: OwnedUserId,
requested_scopes: RequestedScopes,
@@ -180,7 +172,6 @@ impl crate::Service for Service {
tickets: SyncMutex::default(),
pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
client_credential_sessions: tokio::sync::Mutex::default(),
}))
}
@@ -457,25 +448,12 @@ impl Service {
pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> {
let TokenRequest { client_id, request } = request;
if !matches!(request, TokenRequestType::ClientCredentials { .. }) {
// 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.
let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Invalid client ID"));
};
let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
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",
));
}
if !client_metadata.grant_types.contains(&request.grant_type()) {
return Err(OAuthError::unauthorized_client("Client cannot request this grant type"));
}
match request {
@@ -547,9 +525,6 @@ impl Service {
},
| TokenRequestType::RefreshToken { refresh_token } =>
self.refresh_session(client_id, refresh_token).await,
| TokenRequestType::ClientCredentials { client_secret, scope: scopes } =>
self.create_client_credentials_token(&client_id, &client_secret, scopes)
.await,
}
}
@@ -567,7 +542,7 @@ impl Service {
{
(user_id, device_id)
} 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`]
@@ -693,7 +668,7 @@ impl Service {
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope: response_scope,
refresh_token: Some(refresh_token),
refresh_token,
})
}
@@ -763,89 +738,10 @@ impl Service {
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope,
refresh_token: Some(new_refresh_token),
refresh_token: new_refresh_token,
})
}
async 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 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().await;
// 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 async fn get_client_credentials_session(
&self,
token: &str,
) -> Option<tokio::sync::MappedMutexGuard<'_, ClientCredentialsSession>> {
let sessions = self.client_credential_sessions.lock().await;
tokio::sync::MutexGuard::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) {
let session_info = self.get_session_info_for_device(user_id, device_id).await;
+1 -5
View File
@@ -532,7 +532,6 @@ impl Service {
let notify = self
.build_notification(
user,
pusher,
&http.data,
http.format.as_ref(),
@@ -550,7 +549,6 @@ impl Service {
| PusherKind::WebPush(data) => {
let notify = self
.build_notification(
user,
pusher,
&data.data,
data.format.as_ref(),
@@ -566,10 +564,8 @@ impl Service {
}
}
#[allow(clippy::too_many_arguments)]
async fn build_notification<E>(
&self,
user: &UserId,
pusher: &Pusher,
data: &JsonObject,
format: Option<&PushFormat>,
@@ -618,7 +614,7 @@ impl Service {
notify.content = serde_json::value::to_raw_value(event.content()).ok();
if *event.kind() == TimelineEventType::RoomMember {
notify.user_is_target = event.state_key() == Some(user.as_str());
notify.user_is_target = event.state_key() == Some(event.sender().as_str());
}
notify.sender_display_name =
+10 -18
View File
@@ -23,11 +23,7 @@ use ruma::{
};
use self::data::{Data, ReceiptItem};
use crate::{
Dep, rooms,
sending::{self, EduBuf},
sync,
};
use crate::{Dep, rooms, sending, sync};
pub struct Service {
services: Services,
@@ -69,12 +65,10 @@ impl Service {
self.services.sync.wake_all_joined(room_id).await;
// update appservices
let edu = EphemeralData::Receipt(event);
let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &edu).expect("Serialized EphemeralData::Receipt");
_ = self
.services
.sending
.send_edu_appservice_room(room_id, buf)
.send_edu_appservice_room(room_id, &edu)
.await
.log_err();
}
@@ -156,19 +150,17 @@ 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
.services
.sending
.send_edu_appservice_room_filtered(room_id, buf, |appservice| {
appservice.is_user_match(user_id)
})
.send_edu_appservice_room_filtered(
room_id,
&EphemeralData::Receipt(ReceiptEvent::new(
room_id.to_owned(),
ReceiptEventContent::from_iter(receipt_content),
)),
|appservice| appservice.is_user_match(user_id),
)
.await
.log_err();
}
+4 -11
View File
@@ -15,7 +15,7 @@ use ruma::{
events::{EphemeralRoomEvent, SyncEphemeralRoomEvent, typing::TypingEventContent},
};
use crate::{Dep, globals, sending, sending::EduBuf, sync, users};
use crate::{Dep, globals, sending, sync, users};
pub struct Service {
server: Arc<Server>,
@@ -244,13 +244,9 @@ impl Service {
return Ok(());
}
let content = TypingContent::new(room_id.to_owned(), user_id.to_owned(), typing);
let edu = Edu::Typing(content);
let edu = Edu::Typing(TypingContent::new(room_id.to_owned(), user_id.to_owned(), typing));
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?;
self.services.sending.send_edu_room(room_id, &edu).await?;
Ok(())
}
@@ -261,12 +257,9 @@ impl Service {
self.typings_content(room_id),
));
let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &edu).expect("Serialized Edu::Typing");
self.services
.sending
.send_edu_appservice_room(room_id, buf)
.send_edu_appservice_room(room_id, &edu)
.await
}
}
+27 -21
View File
@@ -24,8 +24,9 @@ use ruma::{
OwnedServerName, RoomId, ServerName, UserId,
api::{
OutgoingRequest,
appservice::event::push_events::v1::EphemeralData,
auth_scheme::{NoAccessToken, NoAuthentication, SendAccessToken},
federation::authentication::ServerSignatures,
federation::{authentication::ServerSignatures, transactions::edu::Edu},
path_builder::PathBuilder,
},
};
@@ -220,10 +221,12 @@ impl Service {
Ok(())
}
#[tracing::instrument(skip(self, server, serialized), level = "debug")]
pub fn send_edu_server(&self, server: &ServerName, serialized: EduBuf) -> Result {
#[tracing::instrument(skip(self, server, edu), level = "debug")]
pub fn send_edu_server(&self, server: &ServerName, edu: &Edu) -> Result {
let dest = Destination::Federation(server.to_owned());
let event = SendingEvent::Edu(serialized);
let mut buf = EduBuf::new();
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 keys = self.db.queue_requests(once((&event, &dest)));
self.dispatch(Msg {
@@ -233,10 +236,12 @@ impl Service {
})
}
#[tracing::instrument(skip(self, serialized), level = "debug")]
pub fn send_edu_appservice(&self, appservice_id: &str, serialized: EduBuf) -> Result {
#[tracing::instrument(skip(self, edu), level = "debug")]
pub fn send_edu_appservice(&self, appservice_id: &str, edu: &EphemeralData) -> Result {
let dest = Destination::Appservice(appservice_id.to_owned());
let event = SendingEvent::Edu(serialized);
let mut buf = EduBuf::new();
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 keys = self.db.queue_requests(once((&event, &dest)));
self.dispatch(Msg {
@@ -246,21 +251,21 @@ impl Service {
})
}
#[tracing::instrument(skip(self, room_id, serialized), level = "debug")]
#[tracing::instrument(skip(self, room_id, edu), level = "debug")]
pub async fn send_edu_appservice_room(
&self,
room_id: &RoomId,
serialized: EduBuf,
edu: &EphemeralData,
) -> Result<()> {
self.send_edu_appservice_room_filtered(room_id, serialized, |_| true)
self.send_edu_appservice_room_filtered(room_id, edu, |_| true)
.await
}
#[tracing::instrument(skip(self, room_id, serialized, filter), level = "debug")]
#[tracing::instrument(skip(self, room_id, edu, filter), level = "debug")]
pub async fn send_edu_appservice_room_filtered<F>(
&self,
room_id: &RoomId,
serialized: EduBuf,
edu: &EphemeralData,
filter: F,
) -> Result<()>
where
@@ -292,7 +297,7 @@ impl Service {
|| matching_aliases(appservice.aliases.clone()).await
{
_ = self
.send_edu_appservice(&appservice.registration.id, serialized.clone())
.send_edu_appservice(&appservice.registration.id, edu)
.inspect_err(|e| {
warn!(
"failed to send EDU to appservice {}: {e:?}",
@@ -304,26 +309,27 @@ impl Service {
Ok(())
}
#[tracing::instrument(skip(self, room_id, serialized), level = "debug")]
pub async fn send_edu_room(&self, room_id: &RoomId, serialized: EduBuf) -> Result {
#[tracing::instrument(skip(self, room_id, edu), level = "debug")]
pub async fn send_edu_room(&self, room_id: &RoomId, edu: &Edu) -> Result {
let servers = self
.services
.state_cache
.room_servers(room_id)
.ready_filter(|server_name| !self.services.globals.server_is_ours(server_name));
self.send_edu_servers(servers, serialized).await
self.send_edu_servers(servers, edu).await
}
#[tracing::instrument(skip(self, servers, serialized), level = "debug")]
pub async fn send_edu_servers<S>(&self, servers: S, serialized: EduBuf) -> Result
#[tracing::instrument(skip(self, servers, edu), level = "debug")]
pub async fn send_edu_servers<S>(&self, servers: S, edu: &Edu) -> Result
where
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
.map(|server| {
(Destination::Federation(server), SendingEvent::Edu(serialized.clone()))
})
.map(|server| (Destination::Federation(server), SendingEvent::Edu(buf.clone())))
.collect::<Vec<_>>()
.await;
+11 -13
View File
@@ -216,19 +216,17 @@ impl super::Service {
event_type: &str,
content: serde_json::Value,
) {
let event = Json(json!({
"type": event_type,
"sender": sender,
"content": content,
}));
self.services
.globals
.next_count_with(|count| {
self.db
.todeviceid_events
.put((target_user_id, target_device_id, count), event);
})
.unwrap();
let count = self.services.globals.next_count().unwrap();
let key = (target_user_id, target_device_id, count);
self.db.todeviceid_events.put(
key,
Json(json!({
"type": event_type,
"sender": sender,
"content": content,
})),
);
self.services.sync.wake(target_user_id).await;
}
+11 -20
View File
@@ -442,8 +442,9 @@ impl super::Service {
/// Marks that a user's device keys have been updated, so that other users
/// can be notified of the change.
pub async fn mark_device_key_update(&self, user_id: &UserId) {
let encrypted_rooms: Vec<_> = self
.services
let count = self.services.globals.next_count().unwrap();
self.services
.state_cache
.rooms_joined(user_id)
// Don't send key updates to unencrypted rooms
@@ -459,26 +460,16 @@ impl super::Service {
None
}
})
.collect()
.for_each(async |room_id| {
let key = (&room_id, count);
self.db.keychangeid_userid.put_raw(key, user_id);
self.services.sync.wake_all_joined(&room_id).await;
})
.await;
self.services
.globals
.next_count_with(|count| {
self.db
.keychangeid_userid
.put_raw((user_id, count), user_id);
for room_id in &encrypted_rooms {
self.db
.keychangeid_userid
.put_raw((room_id, count), user_id);
}
})
.unwrap();
for room_id in &encrypted_rooms {
self.services.sync.wake_all_joined(room_id).await;
}
let key = (user_id, count);
self.db.keychangeid_userid.put_raw(key, user_id);
}
/// Returns the device identity keys for a given device.