Compare commits

...
Author SHA1 Message Date
Ginger fe8314bb4d chore: Fix typo 2026-11-05 10:35:18 -05:00
Ginger 4922e5da01 feat: Add support for OAuth client credentials grant 2026-11-05 10:35:17 -05:00
Erwan Leboucher 8c720e5427 fix: Store to-device messages before syncs can read their count 2026-11-05 15:17:36 +00:00
Erwan Leboucher fb389cb6f9 fix: Record device list changes before syncs can read their count
Signed-off-by: Erwan Leboucher <erwanleboucher@gmail.com>
2026-11-05 15:17:23 +00:00
Bardi Harborow db86d42801 fix: Compare push user_is_target against the notified user
`user_is_target` was set by comparing a member event's `state_key` to its
sender, rather than to the user receiving the notification.
2026-11-05 15:27:50 +11:00
Bardi Harborow 223e889459 fix: Return 405 when setting m.fully_read via account data
The spec requires servers to reject client writes to server-managed
account data types with 405 M_BAD_JSON. We returned 400.
2026-11-04 19:32:17 +00:00
Bardi Harborow 219e8d2e1e fix: Return M_UNKNOWN_DEVICE for unknown masqueraded appservice devices
When an appservice masqueraded as a device_id that does not exist for
the user, we returned 403 M_FORBIDDEN. The spec requires 400
M_UNKNOWN_DEVICE.
2026-11-04 19:32:17 +00:00
Bardi Harborow 4d0ccd998f fix: Return M_PROFILE_TOO_LARGE for oversize profiles
Profile updates that would push the profile over 64 KiB were rejected
with an untyped error, producing a 500. The spec requires 400
M_PROFILE_TOO_LARGE, which ruma now provides.
2026-11-04 19:32:17 +00:00
Bardi Harborow 42609eab02 fix: Return M_KEY_TOO_LARGE for oversize profile keys
Profile keys longer than 255 bytes were rejected with 413 M_TOO_LARGE.
The spec requires 400 M_KEY_TOO_LARGE, which ruma now provides.
2026-11-04 19:32:17 +00:00
Bardi Harborow dad9e1426c fix: Advertise m.forget_forced_upon_leave capability according to config 2026-11-04 18:48:40 +00:00
Ginger 34c5787af0 fix: Fix join rule evaluation for servers again
Reviewed-by: timedout <git@nexy7574.co.uk>
Reviewed-by: Jade Ellis <jade@ellis.link>
2026-11-04 12:24:51 -05:00
Renovate Bot d2eeae34a9 chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.210.1 2026-11-04 05:01:50 +00:00
Ginger 2ee28c1b82 fix: Fix busted axum feature list 2026-11-03 20:48:58 -05:00
Ginger c77bbf6d18 fix: Fix busted url_preview feature gate 2026-11-03 20:41:11 -05:00
Erwan Leboucher 0727d564a2 fix: Avoid v12 room ID collisions when creating rooms concurrently
Fixes #2424. v12 rooms created by the same user in the same millisecond got the same room ID, so they ended up as one room.

Reviewed-on: https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2433
Reviewed-by: nex <me@nexy7574.co.uk>
Reviewed-by: Jade Ellis <jade@ellis.link>
2026-11-03 09:52:43 +00:00
Renovate Bot 0e5baa9399 chore(deps): update https://github.com/taiki-e/install-action digest to 682ce6c 2026-11-03 05:03:31 +00:00
Ginger d8229a7933 fix(ci): Use local versions of workflows hosted on tomfos.tr 2026-11-02 14:03:52 -05:00
Renovate Bot ddbdd1ed0c chore(deps): update ruma digest to 0ed7fba 2026-11-02 05:36:01 +00:00
timedout f3d8e8d688 chore: Reformat 2026-11-02 00:50:41 +00:00
Ginger 5a4f3acae4 chore: Changelog 2026-11-02 00:44:02 +00:00
Ginger dc03f2136a fix: Validate OAuth HTTPS redirect URIs are subdomains of the client domain 2026-11-02 00:44:02 +00:00
Erwan Leboucher abf8f878bc fix: gap fill outliers that are missing prev events
Signed-off-by: Erwan Leboucher <erwanleboucher@gmail.com>
2026-10-31 09:02:27 +01:00
42 changed files with 392 additions and 91 deletions

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ runs:
using: composite
steps:
- name: Install sccache
uses: https://git.tomfos.tr/tom/sccache-action@v1
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
- name: Configure sccache
uses: https://github.com/actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
with:
@@ -29,7 +29,7 @@ runs:
steps:
- name: Detect runner OS
id: runner-os
uses: https://git.tomfos.tr/actions/detect-versions@v1
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
- name: Configure cross-compilation architecture
if: inputs.dpkg-arch != ''
+2 -2
View File
@@ -39,7 +39,7 @@ runs:
steps:
- name: Detect runner OS
id: runner-os
uses: https://git.tomfos.tr/actions/detect-versions@v1
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
- name: Configure Cargo environment
shell: bash
@@ -147,7 +147,7 @@ runs:
run: echo "::group::📦 Restoring build cache"
- name: Setup sccache
uses: https://git.tomfos.tr/tom/sccache-action@v1
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
- name: End build cache restore group
shell: bash
+1 -1
View File
@@ -71,7 +71,7 @@ runs:
- name: Install timelord-cli and git-warp-time
if: steps.check-binaries.outputs.need-install == 'true'
uses: https://github.com/taiki-e/install-action@5488ac5a951645ce95062214902ac4b6bc1a1037 # v2
uses: https://github.com/taiki-e/install-action@682ce6c3c696a4cd5168a05f98e51aa02b877941 # v2
with:
tool: git-warp-time,timelord-cli@3.0.1
+1 -1
View File
@@ -60,7 +60,7 @@ jobs:
cargo-debian-${{ steps.debian-version.outputs.distribution }}-${{ matrix.arch }}-
- name: Setup sccache
uses: https://git.tomfos.tr/tom/sccache-action@v1
uses: https://forgejo.ellis.link/continuwuation/sccache-action@v1
- name: Configure sccache environment
run: |
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
- name: Detect runner environment
id: runner-env
uses: https://git.tomfos.tr/actions/detect-versions@v1
uses: https://forgejo.ellis.link/continuwuation/detect-versions@v1
- name: Setup Node.js
if: steps.runner-env.outputs.node_major == '' || steps.runner-env.outputs.node_major < '20'
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
name: Renovate
runs-on: ubuntu-latest
container:
image: ghcr.io/renovatebot/renovate:44.190.1@sha256:1b1306e7f1f0bafc56f6c471b6c309760ab990e9a60901623bcd14016717a528
image: ghcr.io/renovatebot/renovate:44.210.1@sha256:45cc73346c44a9afe037f2d19766f2b545b59b2ed31b937b5b09017d2958e45f
options: --tmpfs /tmp:exec
steps:
- name: Checkout
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
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=e03080c0790ba7b24ea37f9fd11794678cc975b0#e03080c0790ba7b24ea37f9fd11794678cc975b0"
source = "git+https://github.com/ruma/ruma.git?rev=0ed7fba34213f18a628a56f527c6cc795cd7eef5#0ed7fba34213f18a628a56f527c6cc795cd7eef5"
dependencies = [
"js_int",
"ruma-common",
+2 -1
View File
@@ -104,6 +104,7 @@ version = "0.8.8"
default-features = false
features = [
"form",
"query",
"http1",
"http2",
"json",
@@ -348,7 +349,7 @@ version = "1.1.1"
# Used for matrix spec type definitions and helpers
[workspace.dependencies.ruma]
git = "https://github.com/ruma/ruma.git"
rev = "e03080c0790ba7b24ea37f9fd11794678cc975b0"
rev = "0ed7fba34213f18a628a56f527c6cc795cd7eef5"
features = [
"appservice-api-c",
"client-api",
+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.
@@ -0,0 +1 @@
Fix new devices sometimes never reaching other users' device lists. Contributed by @eleboucher.
@@ -0,0 +1 @@
Fix gap filling skipping outlier events that are missing their previous events. Contributed by @eleboucher.
@@ -0,0 +1 @@
Fix to-device messages, including room keys, sometimes being lost before delivery. Contributed by @eleboucher.
+1
View File
@@ -0,0 +1 @@
Redirect URIs in OAuth clients' metadata are now properly validated to be on a subdomain of the OAuth issuer URL domain. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Fix v12 rooms created by the same user in the same millisecond ending up as the same room. Contributed by @eleboucher.
+1
View File
@@ -0,0 +1 @@
Setting a profile key longer than 255 bytes now returns 400 `M_KEY_TOO_LARGE` as required by the spec, instead of 413 `M_TOO_LARGE`.
+1
View File
@@ -0,0 +1 @@
Setting profile data that would make the profile exceed 64 KiB now returns 400 `M_PROFILE_TOO_LARGE` as required by the spec, instead of a 500 error.
+1
View File
@@ -0,0 +1 @@
Appservices masquerading as a device that does not exist now receive 400 `M_UNKNOWN_DEVICE` as required by the spec, instead of 403 `M_FORBIDDEN`.
+1
View File
@@ -0,0 +1 @@
Setting `m.fully_read` via the account data endpoints now returns 405 `M_BAD_JSON` as required by the spec, instead of 400.
+1
View File
@@ -0,0 +1 @@
The `m.forget_forced_upon_leave` capability now reflects the `forget_forced_upon_leave` config option instead of always being advertised as enabled.
+1
View File
@@ -0,0 +1 @@
Fixed push notifications for membership events setting `user_is_target` based on the sender rather than the user being notified.
+42
View File
@@ -2680,3 +2680,45 @@
#
# 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 = []
+7 -4
View File
@@ -117,10 +117,13 @@ async fn set_account_data(
data: &RawJsonValue,
) -> Result {
if event_type_s == "m.fully_read" {
return Err!(Request(BadJson(
"This endpoint cannot be used for marking a room as fully read (setting \
m.fully_read)"
)));
return Err!(Request(
BadJson(
"This endpoint cannot be used for marking a room as fully read (setting \
m.fully_read)"
),
METHOD_NOT_ALLOWED
));
}
let data: serde_json::Value = serde_json::from_str(data.get())
+2 -1
View File
@@ -46,7 +46,8 @@ pub(crate) async fn get_capabilities_route(
capabilities.get_login_token =
GetLoginTokenCapability::new(services.server.config.login_via_existing_session);
capabilities.forget_forced_upon_leave.enabled = true;
capabilities.forget_forced_upon_leave.enabled =
services.server.config.forget_forced_upon_leave;
if services.users.is_admin(sender_user).await {
capabilities.account_moderation.lock = true;
+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"],
"grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "client_credentials"],
"issuer": services.config.get_client_domain(),
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
"prompt_values_supported": prompt_values_supported,
+20 -4
View File
@@ -1,18 +1,21 @@
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
sync::atomic::{AtomicU64, Ordering::SeqCst},
};
use axum::extract::State;
use conduwuit::{
Err, Error, Result, debug, debug_info, err, info,
matrix::{StateKey, pdu::PartialPdu},
trace,
utils::to_canonical_object,
utils::{self, to_canonical_object},
warn,
};
use conduwuit_service::{Services, appservice::RegistrationInfo};
use futures::FutureExt;
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, Int, MilliSecondsSinceUnixEpoch, OwnedRoomAliasId,
OwnedUserId, RoomAliasId, RoomId,
OwnedUserId, RoomAliasId, RoomId, UInt,
api::{
client::room::{
self,
@@ -46,6 +49,8 @@ use serde_json::value::to_raw_value;
use crate::{Ruma, client::invite_helper};
static LAST_CREATE_TS: AtomicU64 = AtomicU64::new(0);
// We use this to keep around extra data in the `creation_content`
// while still parsing and validating keys that we care about.
#[derive(Deserialize, Default)]
@@ -307,6 +312,17 @@ pub(crate) async fn create_room_route(
.map(MilliSecondsSinceUnixEpoch)
};
// v12+ room IDs are the create event's hash, so give each create event a
// unique timestamp to avoid collisions.
let create_timestamp = custom_origin_server_ts.or_else(|| {
room_id.is_none().then(|| {
let now = utils::millis_since_unix_epoch();
let next = |last: u64| now.max(last.saturating_add(1));
let prev = LAST_CREATE_TS.update(SeqCst, SeqCst, next);
MilliSecondsSinceUnixEpoch(UInt::new_saturating(next(prev)))
})
});
let mut create_event_content = to_canonical_object(create_event_content)
.expect("should be able to serialize create event content");
@@ -322,7 +338,7 @@ pub(crate) async fn create_room_route(
event_type: TimelineEventType::RoomCreate,
content: to_raw_value(&create_event_content)?,
state_key: Some(StateKey::new()),
timestamp: custom_origin_server_ts,
timestamp: create_timestamp,
..Default::default()
},
sender_user,
+26 -5
View File
@@ -41,6 +41,7 @@ pub(crate) enum ClientIdentity {
sender_device: Option<OwnedDeviceId>,
appservice_info: Box<RegistrationInfo>,
},
StaticClient,
}
impl ClientIdentity {
@@ -48,6 +49,7 @@ impl ClientIdentity {
match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Some(sender_user),
| Self::StaticClient => None,
}
}
@@ -55,6 +57,8 @@ 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."))),
}
}
@@ -62,6 +66,7 @@ impl ClientIdentity {
match self {
| Self::User { sender_device, .. } => Some(sender_device),
| Self::Appservice { sender_device, .. } => sender_device.as_deref(),
| Self::StaticClient => None,
}
}
@@ -71,12 +76,14 @@ 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 { .. } => None,
| Self::User { .. } | Self::StaticClient => None,
| Self::Appservice { appservice_info, .. } => Some(appservice_info),
}
}
@@ -379,10 +386,7 @@ async fn check_access_token(
.await
.is_err()
{
return Err!(Request(Forbidden(
"Device does not exist for user or appservice cannot masquerade as this \
device."
)));
return Err!(Request(UnknownDevice("Device does not exist for this user.")));
}
Some(device_id.to_owned())
@@ -395,6 +399,23 @@ 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()),
+9
View File
@@ -353,6 +353,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(())
}
+54
View File
@@ -24,6 +24,7 @@ use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
RoomVersionId, ServerName,
api::{
OAuthClientScope,
client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
federation::discovery::OldVerifyKey,
},
@@ -2746,7 +2747,12 @@ 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 {
@@ -2960,6 +2966,54 @@ 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",
+6 -2
View File
@@ -21,7 +21,9 @@ impl Data {
}
}
pub fn next_count(&self) -> Result<u64> {
pub fn next_count(&self) -> Result<u64> { self.next_count_with(|_| ()) }
pub fn next_count_with(&self, write: impl FnOnce(u64)) -> Result<u64> {
let _cork = self.db.cork();
let mut lock = self.counter.write();
let counter: &mut u64 = &mut lock;
@@ -30,7 +32,9 @@ impl Data {
"counter mismatch"
);
*counter = counter.checked_add(1).unwrap_or(*counter);
let next = counter.checked_add(1).unwrap_or(*counter);
write(next);
*counter = next;
self.global.insert(COUNTER, counter.to_be_bytes());
+5
View File
@@ -80,6 +80,11 @@ 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()) }
+1 -5
View File
@@ -7,17 +7,13 @@
use std::time::SystemTime;
#[cfg(feature = "url_preview")]
use conduwuit::utils::response::LimitReadExt;
use conduwuit::{Err, Result, debug, err};
use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt};
use ipaddress::IPAddress;
#[cfg(feature = "url_preview")]
use ruma::OwnedMxcUri;
use serde::Serialize;
use url::Url;
use super::Service;
#[cfg(feature = "url_preview")]
use crate::media::mxc::Mxc;
#[derive(Serialize, Default)]
+4 -3
View File
@@ -167,10 +167,11 @@ migration!(stringify!($name) => $name)
// names, preventing users from signing in.
VersionBump(22),
migration!(fix_oauth_scope_names),
// Removes any extremities in roomid_pduleaves that we do not know about (and
// consequently should not reference).
// Removes any extremities in roomid_pduleaves that we do not know about
// (and consequently should not reference).
migration!(remove_unknown_extremities),
// Re-calculates extremities for any rooms that actually lack any extremities at all.
// Re-calculates extremities for any rooms that actually lack any
// extremities at all.
migration!(consistency_check_extremity_tracker),
]
};
+16
View File
@@ -81,6 +81,15 @@ impl ClientMetadata {
if !uri.username().is_empty() || uri.password().is_some() {
return Err("HTTPS redirect URIs must not contain credentials.");
}
if !uri
.domain()
.is_some_and(|domain| is_subdomain(domain, client_domain))
{
return Err(
"All HTTPS redirect URIs must be subdomains of the client URI."
);
}
},
| "http" if self.application_type == ApplicationType::Native => {
if uri
@@ -116,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(())
}
}
@@ -135,6 +150,7 @@ 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)]
+6 -1
View File
@@ -225,6 +225,10 @@ pub enum TokenRequestType {
RefreshToken {
refresh_token: String,
},
ClientCredentials {
client_secret: String,
scope: RawScopes,
},
}
impl TokenRequestType {
@@ -234,6 +238,7 @@ impl TokenRequestType {
| Self::AuthorizationCode { .. } => GrantType::AuthorizationCode,
| Self::DeviceCode { .. } => GrantType::DeviceCode,
| Self::RefreshToken { .. } => GrantType::RefreshToken,
| Self::ClientCredentials { .. } => GrantType::ClientCredentials,
}
}
}
@@ -243,7 +248,7 @@ pub struct TokenResponse {
pub access_token: String,
pub token_type: TokenType,
pub expires_in: u64,
pub refresh_token: String,
pub refresh_token: Option<String>,
pub scope: String,
}
+114 -10
View File
@@ -23,8 +23,9 @@ use crate::{
client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType},
grant::{
AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RequestedScopes,
ResponseMode, TokenRequest, TokenRequestType, TokenResponse, TokenType,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RawScopes,
RequestedScopes, ResponseMode, TokenRequest, TokenRequestType, TokenResponse,
TokenType,
},
},
users::{self, DeviceToken},
@@ -39,6 +40,7 @@ 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 {
@@ -78,6 +80,12 @@ 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,
@@ -172,6 +180,7 @@ 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(),
}))
}
@@ -448,12 +457,25 @@ impl Service {
pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> {
let TokenRequest { client_id, request } = request;
let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Invalid client ID"));
};
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.
if !client_metadata.grant_types.contains(&request.grant_type()) {
return Err(OAuthError::unauthorized_client("Client cannot request this grant type"));
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",
));
}
}
match request {
@@ -525,6 +547,9 @@ 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,
}
}
@@ -542,7 +567,7 @@ impl Service {
{
(user_id, device_id)
} 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`]
@@ -668,7 +693,7 @@ impl Service {
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope: response_scope,
refresh_token,
refresh_token: Some(refresh_token),
})
}
@@ -738,10 +763,89 @@ impl Service {
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope,
refresh_token: new_refresh_token,
refresh_token: Some(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;
+5 -1
View File
@@ -532,6 +532,7 @@ impl Service {
let notify = self
.build_notification(
user,
pusher,
&http.data,
http.format.as_ref(),
@@ -549,6 +550,7 @@ impl Service {
| PusherKind::WebPush(data) => {
let notify = self
.build_notification(
user,
pusher,
&data.data,
data.format.as_ref(),
@@ -564,8 +566,10 @@ impl Service {
}
}
#[allow(clippy::too_many_arguments)]
async fn build_notification<E>(
&self,
user: &UserId,
pusher: &Pusher,
data: &JsonObject,
format: Option<&PushFormat>,
@@ -614,7 +618,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(event.sender().as_str());
notify.user_is_target = event.state_key() == Some(user.as_str());
}
notify.sender_display_name =
@@ -310,9 +310,9 @@ impl super::Service {
.stream()
.fold(0_u8, |i, event_id| async move {
if self.services.timeline.pdu_exists(event_id).await {
i.expected_add(1)
} else {
i
} else {
i.expected_add(1)
}
})
.await;
+3 -3
View File
@@ -901,7 +901,7 @@ impl Service {
.server_in_room(self.services.globals.server_name(), condition_room)
.await
{
let is_joined = match entity {
let is_joined_to_condition_room = match entity {
| JoinConditionEntity::User(user_id) =>
self.services
.state_cache
@@ -910,11 +910,11 @@ impl Service {
| JoinConditionEntity::Server(server) =>
self.services
.state_cache
.server_in_room(server, room_id)
.server_in_room(server, condition_room)
.await,
};
if is_joined {
if is_joined_to_condition_room {
debug!(
?entity,
?room_id,
+13 -11
View File
@@ -216,17 +216,19 @@ impl super::Service {
event_type: &str,
content: serde_json::Value,
) {
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,
})),
);
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();
self.services.sync.wake(target_user_id).await;
}
+20 -11
View File
@@ -442,9 +442,8 @@ 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 count = self.services.globals.next_count().unwrap();
self.services
let encrypted_rooms: Vec<_> = self
.services
.state_cache
.rooms_joined(user_id)
// Don't send key updates to unencrypted rooms
@@ -460,16 +459,26 @@ impl super::Service {
None
}
})
.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;
})
.collect()
.await;
let key = (user_id, count);
self.db.keychangeid_userid.put_raw(key, user_id);
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;
}
}
/// Returns the device identity keys for a given device.
+3 -7
View File
@@ -51,12 +51,8 @@ impl super::Service {
let field_name = change.field_name();
// TODO: The spec mentions special error codes (M_PROFILE_TOO_LARGE,
// M_KEY_TOO_LARGE) for profile field size limits, but they're not in
// its list of error codes and Ruma doesn't have them. Should we
// return those, or is M_TOO_LARGE okay?
if field_name.as_str().len() > MAX_KEY_LENGTH_BYTES {
return Err!(Request(TooLarge(
return Err!(Request(KeyTooLarge(
"Individual profile keys must not exceed {MAX_KEY_LENGTH_BYTES} bytes in length."
)));
}
@@ -84,10 +80,10 @@ impl super::Service {
.len()
> MAX_PROFILE_LENGTH_BYTES
{
return Err!(
return Err!(Request(ProfileTooLarge(
"Profile data must not exceed {MAX_PROFILE_LENGTH_BYTES} bytes in \
length."
);
)));
}
} else {
return Err!(Request(BadJson("Failed to canonicalize profile.")));