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
57 changed files with 2172 additions and 1299 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 = []
File diff suppressed because it is too large. Load diff
+202
View File
@@ -1,8 +1,12 @@
mod commands;
pub(crate) mod tester;
use clap::Subcommand;
use conduwuit::Result;
use ruma::{OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName};
use service::rooms::short::{ShortEventId, ShortRoomId};
use self::tester::TesterCommand;
use crate::admin_command_dispatch;
#[admin_command_dispatch]
@@ -13,6 +17,177 @@ pub enum DebugCommand {
message: Vec<String>,
},
/// Loads the auth_chain of a PDU, reporting how long it took.
GetAuthChain {
/// An event ID (the $ character followed by the base64 reference hash)
event_id: OwnedEventId,
},
/// Walks & displays the auth_chain of a PDU in a mermaid graph format.
///
/// This is useless to basically anyone but developers, and is also probably
/// slow and memory hungry.
ShowAuthChain {
/// The root event ID to start walking back from.
event_id: OwnedEventId,
},
/// Parse and print a PDU from a JSON
///
/// The PDU event is only checked for validity and is not added to the
/// database.
///
/// This command needs a JSON blob provided in a Markdown code block below
/// the command.
ParsePdu,
/// Retrieve and print a PDU by EventID from the Continuwuity database
GetPdu {
/// An event ID (a $ followed by the base64 reference hash)
event_id: OwnedEventId,
},
/// Retrieve and print a PDU by PduId from the Continuwuity database
GetShortPdu {
/// Shortroomid integer
shortroomid: ShortRoomId,
/// Shorteventid integer
shorteventid: ShortEventId,
},
/// Attempts to retrieve a PDU from a remote server. **Does not** insert
/// it into the database
/// or persist it anywhere.
GetRemotePdu {
/// An event ID (a $ followed by the base64 reference hash)
event_id: OwnedEventId,
/// Argument for us to attempt to fetch the event from the
/// specified remote server.
server: OwnedServerName,
},
/// Same as `get-remote-pdu` but accepts a codeblock newline delimited
/// list of PDUs and a single server to fetch from
GetRemotePduList {
/// Argument for us to attempt to fetch all the events from the
/// specified remote server.
server: OwnedServerName,
/// If set, ignores errors, else stops at the first error/failure.
#[arg(short, long)]
force: bool,
},
/// Gets all the room state events for the specified room.
///
/// This is functionally equivalent to `GET
/// /_matrix/client/v3/rooms/{roomid}/state`, except the admin command does
/// *not* check if the sender user is allowed to see state events. This is
/// done because it's implied that server admins here have database access
/// and can see/get room info themselves anyways if they were malicious
/// admins.
///
/// Of course the check is still done on the actual client API.
GetRoomState {
/// Room ID
room_id: OwnedRoomOrAliasId,
},
/// Gets all the room state events at the specified event.
///
/// State at event might not be available for some PDUs, such as rejected
/// ones.
GetStateAt {
event_id: OwnedEventId,
},
/// Sends a federation request to the remote server's
/// `/_matrix/federation/v1/version` endpoint and measures the latency it
/// took for the server to respond
Ping {
server: OwnedServerName,
},
/// Forces device lists for all local and remote users to be updated (as
/// having new keys available)
ForceDeviceListUpdates,
/// Change tracing log level/filter on the fly
///
/// This accepts the same format as the `log` config option.
ChangeLogLevel {
/// Log level/filter
filter: Option<String>,
/// Resets the log level/filter to the one in your config
#[arg(short, long)]
reset: bool,
},
/// Verify JSON signatures
///
/// This command needs a JSON blob provided in a Markdown code block below
/// the command.
VerifyJson,
/// Verify PDU
///
/// This re-verifies a PDU existing in the database found by ID.
VerifyPdu {
event_id: OwnedEventId,
},
/// Prints the very first PDU in the specified room (typically
/// m.room.create)
FirstPduInRoom {
/// The room ID
room_id: OwnedRoomId,
},
/// Prints the latest ("last") PDU in the specified room (typically a
/// message)
LatestPduInRoom {
/// The room ID
room_id: OwnedRoomId,
},
/// Forcefully replaces the room state of our local copy of the specified
/// room, with the copy (auth chain and room state events) the specified
/// remote server says.
///
/// A common desire for room deletion is to simply "reset" our copy of the
/// room. While this admin command is not a replacement for that, if you
/// know you have split/broken room state and you know another server in the
/// room that has the best/working room state, this command can let you use
/// their room state. Such example is your server saying users are in a
/// room, but other servers are saying they're not in the room in question.
///
/// This command will get the latest PDU in the room we know about, and
/// request the room state at that point in time via
/// `/_matrix/federation/v1/state/{roomId}`.
ForceSetRoomStateFromServer {
/// The impacted room ID
room_id: OwnedRoomId,
/// The server we will use to query the room state for
server_name: OwnedServerName,
/// The event ID of the latest known PDU in the room. Will be found
/// automatically if not provided.
event_id: Option<OwnedEventId>,
},
/// Runs a server name through Continuwuity's true destination resolution
/// process
///
/// Useful for debugging well-known issues
ResolveTrueDestination {
server_name: OwnedServerName,
#[arg(short, long)]
no_cache: bool,
},
/// Print extended memory usage
///
/// Optional argument is a character mask (a sequence of characters in any
@@ -29,6 +204,9 @@ pub enum DebugCommand {
/// invocation.
RuntimeInterval,
/// Print the current time
Time,
/// Get database statistics
DatabaseStats {
property: Option<String>,
@@ -55,4 +233,28 @@ pub enum DebugCommand {
RoomsByExtremityCount {
page: Option<usize>,
},
RoomExtremities {
room_id: OwnedRoomId,
},
/// Lists remote servers that are currently in a "backoff" state.
///
/// Servers in this list will not be contacted until the retry time elapses,
/// or they make contact first.
///
/// "Stale" indicates that routing information may be out of date, and the
/// remote will be re-resolved immediately before the next contact attempt.
ServersInBackoff {
#[arg(short, long, alias = "room")]
room_id: Option<OwnedRoomId>,
#[arg(short, long)]
name: Option<OwnedServerName>,
},
/// Developer test stubs
#[command(subcommand)]
#[allow(non_snake_case)]
#[clap(hide(true))]
Tester(TesterCommand),
}
+48
View File
@@ -0,0 +1,48 @@
use conduwuit::{Err, Result};
use crate::admin_command_dispatch;
#[admin_command_dispatch]
#[derive(Debug, clap::Subcommand)]
pub enum TesterCommand {
Panic,
Failure,
Tester,
Timer,
}
#[allow(clippy::unused_async_trait_impl)]
impl crate::Context<'_> {
#[rustfmt::skip]
async fn panic(&self) -> Result {
panic!("panicked")
}
#[rustfmt::skip]
async fn failure(&self) -> Result {
Err!("failed")
}
#[inline(never)]
#[rustfmt::skip]
async fn tester(&self) -> Result {
self.write_str("Ok").await
}
#[inline(never)]
#[rustfmt::skip]
async fn timer(&self) -> Result {
let started = std::time::Instant::now();
timed(self.body);
let elapsed = started.elapsed();
self.write_str(&format!("completed in {elapsed:#?}")).await
}
}
#[inline(never)]
#[rustfmt::skip]
#[allow(unused_variables)]
fn timed(body: &[&str]) {
}
+46 -77
View File
@@ -1,23 +1,20 @@
use std::fmt::Write;
use conduwuit::{Err, Result, utils::response::LimitReadExt};
use resolvematrix::{
resolution::ResolvedDestination,
server::{MatrixResolver, MatrixResolverBuilder},
};
use ruma::{MilliSecondsSinceUnixEpoch, OwnedRoomOrAliasId, OwnedServerName};
use futures::StreamExt;
use ruma::{MilliSecondsSinceUnixEpoch, OwnedRoomId, OwnedServerName, OwnedUserId};
use crate::get_room_info;
impl crate::Context<'_> {
pub(super) async fn disable_room(&self, room: OwnedRoomOrAliasId) -> Result {
pub(super) async fn disable_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?;
self.services.rooms.metadata.disable_room(&room_id, true);
self.write_str("Room disabled.").await
}
pub(super) async fn enable_room(&self, room: OwnedRoomOrAliasId) -> Result {
pub(super) async fn enable_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?;
self.services.rooms.metadata.disable_room(&room_id, false);
self.write_str("Room enabled.").await
}
@@ -36,13 +33,13 @@ impl crate::Context<'_> {
map.len(),
self.services.transactions.txn_active_handle_count()
);
for (room_id, (event_id, started_at)) in map.iter() {
let elapsed = started_at.elapsed();
for (r, (e, i)) in map.iter() {
let elapsed = i.elapsed();
writeln!(
msg,
"{} {}: {}m{}s",
room_id,
event_id,
r,
e,
elapsed.as_secs() / 60,
elapsed.as_secs() % 60
)?;
@@ -53,7 +50,7 @@ impl crate::Context<'_> {
self.write_str(&msg).await
}
pub(super) async fn fetch_support(&self, server_name: OwnedServerName) -> Result {
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result {
let response = self
.services
.client
@@ -100,6 +97,41 @@ impl crate::Context<'_> {
.await
}
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
if user_id.server_name() == self.services.server.name {
return Err!(
"User belongs to our server, please use `list-joined-rooms` user admin command \
instead.",
);
}
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
.services
.rooms
.state_cache
.rooms_joined(&user_id)
.then(async |room_id| get_room_info(self.services, &room_id).await)
.collect()
.await;
if rooms.is_empty() {
return Err!("User is not in any rooms.");
}
rooms.sort_by_key(|r| r.1);
rooms.reverse();
let num = rooms.len();
let body = rooms
.iter()
.map(|(id, members, name)| format!("{id} | Members: {members} | Name: {name}"))
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
.await
}
pub(super) async fn get_signing_keys(&self, server_name: OwnedServerName) -> Result {
let response = self
.services
@@ -125,67 +157,4 @@ impl crate::Context<'_> {
Ok(())
}
pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
let timer = tokio::time::Instant::now();
match self
.services
.sending
.send_unauthenticated_request(
&server,
ruma::api::federation::discovery::get_server_version::v1::Request::new(),
)
.await
{
| Err(e) => {
return Err!("Failed sending federation request to specified server:\n\n{e}");
},
| Ok(response) => {
let ping_time = timer.elapsed();
let json_text_res = serde_json::to_string_pretty(&response.server);
let out = if let Ok(json) = json_text_res {
format!("Got response which took {ping_time:?} time:\n```json\n{json}\n```")
} else {
format!("Got non-JSON response which took {ping_time:?} time:\n{response:?}")
};
write!(self, "{out}")
},
}
.await
}
pub(super) async fn resolve_true_destination(
&self,
server_name: OwnedServerName,
no_cache: bool,
) -> Result {
if !self.services.server.config.allow_federation {
return Err!("Federation is disabled on this homeserver.",);
}
let resolver: &MatrixResolver = if no_cache {
&MatrixResolverBuilder::new()
.dangerous_tls_accept_invalid_certs(self.services.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure)
.http_client(self.services.client.dns.clone())
.build()?
} else {
&self.services.client.matrix_resolver
};
let actual = resolver.resolve_server(server_name.as_str()).await?;
let destination = match actual.destination {
| ResolvedDestination::Literal(addr) => addr.to_string(),
| ResolvedDestination::Named(host, port) => format!("{host}:{port}"),
};
let msg = format!(
"Destination: {}\nHostname URI (SNI): {}\nIs override?: {}\nResolution step: {}",
destination, actual.host, actual.is_override, actual.resolution_step
);
self.write_str(&msg).await
}
}
-161
View File
@@ -1,161 +0,0 @@
use std::time::Duration;
use clap::Subcommand;
use conduwuit::Result;
use conduwuit_macros::admin_command_dispatch;
use futures::StreamExt;
use ruma::{OwnedRoomOrAliasId, OwnedServerName};
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum HealthCommand {
/// Lists all servers that are currently marked as unhealthy (i.e. we
/// previously failed to establish direct federation and have not succeeded
/// since).
#[clap(name = "list")]
ListUnhealthyServers {
/// An optional filter to only check servers that are in a specific room
/// (ID or alias).
room: Option<OwnedRoomOrAliasId>,
},
/// Displays the current health status of the given remote server.
#[clap(name = "status")]
ServerHealthStatus {
server_name: OwnedServerName,
},
/// Forces the server to consider the remote server healthy.
///
/// This is generally unnecessary as this already happens when the remote
/// server makes contact with this server, or if this server successfully
/// makes a request to the remote server after the backoff window.
ForceHealthy {
server_name: OwnedServerName,
},
/// Forces the server to consider the remote server unhealthy.
///
/// This is generally unnecessary as this already happens when the remote
/// server fails to resolve or connect, or returns unusual errors.
/// If you are looking to stop contacting a specific server, take a look at
/// the `forbidden_remote_server_names` configuration option.
ForceUnhealthy {
server_name: OwnedServerName,
/// If set, the server will also be marked as having stale routing
/// information. This means the address will be re-resolved on the next
/// connection attempt.
#[arg(long)]
stale: bool,
},
}
impl crate::Context<'_> {
pub(super) async fn list_unhealthy_servers(
&self,
room: Option<OwnedRoomOrAliasId>,
) -> Result {
let unhealthy = self.services.federation.remote_health();
if unhealthy.is_empty() {
return self
.write_str("No servers are currently tracked as unhealthy.")
.await;
}
let stale_destinations = self.services.federation.stale_destinations();
let mut candidates: Vec<_> = if let Some(room) = room {
let room_id = self.services.rooms.alias.resolve(&room).await?;
self.services
.rooms
.state_cache
.room_servers(&room_id)
.collect()
.await
} else {
unhealthy
.keys()
.chain(stale_destinations.iter())
.cloned()
.collect()
};
candidates.retain(|name| unhealthy.contains_key(name));
candidates.sort();
candidates.dedup();
if candidates.is_empty() {
return self
.write_str("No servers are currently unhealthy meeting the given criteria.")
.await;
}
for server_name in candidates {
let Some((retries, retry_at)) = unhealthy.get(&server_name) else { continue };
let is_stale = if stale_destinations.contains(&server_name) {
"Yes"
} else {
"No"
};
self.write_str(&format!("| {server_name} | {retries} | {retry_at} | {is_stale} |\n"))
.await?;
}
Ok(())
}
pub(super) async fn server_health_status(&self, server_name: OwnedServerName) -> Result {
let stale = self
.services
.federation
.stale_destinations()
.contains(&server_name);
let Some((retries, retry_at_ts)) = self
.services
.federation
.remote_health()
.get(&server_name)
.copied()
else {
return self
.write_str(&if stale {
format!(
"{server_name} is currently healthy, but may have stale routing \
information."
)
} else {
format!("{server_name} is currently healthy.")
})
.await;
};
let state = if stale {
"unhealthy with potentially stale routing information"
} else {
"unhealthy"
};
self.write_str(&format!(
"{server_name} is currently {state}: {retries} consecutive connections have \
failed,and no new connection will be attempted for another {}.",
conduwuit::utils::time::pretty(Duration::from_millis(retry_at_ts)),
))
.await
}
pub(super) async fn force_healthy(&self, server_name: OwnedServerName) -> Result {
self.services.federation.mark_healthy(&server_name);
self.write_str("Done.").await
}
pub(super) async fn force_unhealthy(
&self,
server_name: OwnedServerName,
stale: bool,
) -> Result {
if stale {
self.services
.federation
.mark_destination_stale(&server_name);
}
self.services.federation.hit_unhealthy(server_name);
self.write_str("Done.").await
}
}
+16 -35
View File
@@ -1,66 +1,47 @@
mod commands;
mod health;
use clap::Subcommand;
use conduwuit::Result;
use ruma::{OwnedRoomOrAliasId, OwnedServerName};
use ruma::{OwnedRoomId, OwnedServerName, OwnedUserId};
use crate::{admin_command_dispatch, federation::health::HealthCommand};
use crate::admin_command_dispatch;
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum FederationCommand {
/// List all rooms we are currently handling an incoming pdu from
#[clap(name = "incoming", alias = "inbound")]
IncomingFederation,
/// Disables incoming federation handling for a room.
///
/// The room can still be used locally, but events from other servers will
/// stop being received.
DisableRoom {
room: OwnedRoomOrAliasId,
room_id: OwnedRoomId,
},
/// Enables incoming federation handling for a room again.
///
/// This does not unban the room if it was banned, it only re-enables
/// incoming events.
EnableRoom {
room: OwnedRoomOrAliasId,
room_id: OwnedRoomId,
},
/// Fetch support details from the given server.
/// Fetch `/.well-known/matrix/support` from the specified server
///
/// This makes a request to `https://<server_name>/.well-known/matrix/support`. Many servers do not advertise support information, but those that do usually provide a way to contact homeserver administrators.
FetchSupport {
/// Despite the name, this is not a federation endpoint and does not go
/// through the federation / server resolution process as per-spec this is
/// supposed to be served at the server_name.
///
/// Respecting homeservers put this file here for listing administration,
/// moderation, and security inquiries. This command provides a way to
/// easily fetch that information.
FetchSupportWellKnown {
server_name: OwnedServerName,
},
/// Runs a server name through Continuwuity's server-to-server address
/// resolution process.
#[clap(name = "resolve")]
ResolveTrueDestination {
server_name: OwnedServerName,
#[arg(short, long)]
skip_cache: bool,
/// Lists all the rooms we share/track with the specified *remote* user
RemoteUserInRooms {
user_id: OwnedUserId,
},
/// Queries the remote server for their current signing keys.
GetSigningKeys {
server_name: OwnedServerName,
},
/// Makes a federation request to the remote server, to test connectivity.
///
/// The request is made to the federation version endpoint, which if
/// successful, will also reveal how long the request took and what the
/// remote server's software is.
Ping {
server_name: OwnedServerName,
},
#[command(subcommand)]
Health(HealthCommand),
}
-401
View File
@@ -1,401 +0,0 @@
use std::{
collections::{HashMap, HashSet},
fmt::Write,
};
use clap::Subcommand;
use conduwuit::{Err, Event, PduEvent, Result, err, utils::stream::BroadbandExt};
use conduwuit_macros::admin_command_dispatch;
use futures::StreamExt;
use ruma::{EventId, OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, UInt};
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum GraphCommand {
/// Lists all forward extremities in a room.
ListExtremities {
room: OwnedRoomOrAliasId,
},
/// Fetches a PDU (event) by its event ID, as stored in the database. Also
/// includes details about the PDU state.
GetPDU {
event_id: OwnedEventId,
},
/// Fetches a PDU over federation. Does not store the result.
FetchPDU {
event_id: OwnedEventId,
server_name: OwnedServerName,
},
/// Yields the first PDU we became aware of in a room.
/// This is always the room's create event for local rooms, or the first
/// membership event that introduced us to the remote room.
#[clap(name = "first-pdu")]
FirstPduInRoom {
room_id: OwnedRoomId,
},
/// Yields the most recent PDU in a room.
#[clap(name = "latest-pdu")]
LatestPduInRoom {
room_id: OwnedRoomId,
},
/// Draws a mermaid graph of the auth chain for an event.
ShowAuthChain {
event_id: OwnedEventId,
},
}
impl crate::Context<'_> {
pub(super) async fn list_extremities(&self, room: OwnedRoomOrAliasId) -> Result {
let room_id = self.services.rooms.alias.resolve(&room).await?;
let mut extremities = self
.services
.rooms
.state
.get_forward_extremities(&room_id)
.broad_filter_map(|event_id| async move {
self.services.rooms.timeline.get_pdu(&event_id).await.ok()
})
.collect::<Vec<_>>()
.await;
extremities.sort_by_key(|pdu| (pdu.depth, pdu.origin_server_ts));
if extremities.is_empty() {
return Err!("No room extremities.");
}
self.write_str("| Event ID | Type | Sender | Timestamp | Depth |\n")
.await?;
self.write_str("| -------- | ---- | ------ | --------- | ----- |\n")
.await?;
for pdu in extremities {
let url = format!(
"https://matrix.to/#/{}/{}?via={}",
room_id,
pdu.event_id(),
self.services.server.name
);
self.write_str(&format!(
"| [`{}`]({url}) | `{}` | `{}` | `{}` | `{}` |\n",
pdu.event_id(),
pdu.kind(),
pdu.sender(),
pdu.origin_server_ts,
pdu.depth
))
.await?;
}
Ok(())
}
pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result {
let mut outlier = false;
let mut pdu_json = self
.services
.rooms
.timeline
.get_non_outlier_pdu_json(&event_id)
.await;
if pdu_json.is_err() {
outlier = true;
pdu_json = self.services.rooms.timeline.get_pdu_json(&event_id).await;
}
let rejected = self
.services
.rooms
.pdu_metadata
.is_event_rejected(&event_id)
.await;
let soft_failed = self
.services
.rooms
.pdu_metadata
.is_event_soft_failed(&event_id)
.await;
match pdu_json {
| Err(_) => return Err!("PDU not found locally."),
| Ok(json) => {
let text = serde_json::to_string_pretty(&json)?;
let msg = if rejected {
"Rejected PDU:"
} else if soft_failed {
"Soft-failed PDU:"
} else if outlier {
"Outlier PDU:"
} else {
"Timeline PDU:"
};
write!(self, "{msg}\n```json\n{text}\n```")
},
}
.await
}
pub(super) async fn fetch_pdu(
&self,
event_id: OwnedEventId,
server: OwnedServerName,
) -> Result {
let response = self
.services
.sending
.send_federation_request(
&server,
ruma::api::federation::event::get_event::v1::Request::new(event_id.clone()),
)
.await?;
let (real_event_id, room_id, pdu_json) = self
.services
.rooms
.event_handler
.parse_incoming_pdu(&response.pdu, None)
.await?;
self.write_str(&format!(
"Event ID: {real_event_id}\nRoom ID: {room_id}\nPDU:\n```json\n{}\n```",
serde_json::to_string_pretty(&pdu_json)?
))
.await
}
pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
let first_pdu = self
.services
.rooms
.timeline
.first_pdu_in_room(&room_id)
.await
.map(Event::into_canonical_object)
.and_then(|v| serde_json::to_string_pretty(&v).map_err(Into::into))
.map_err(|e| err!(Database("Failed to find the first PDU in database: {e:?}")))?;
let out = format!("```json\n{first_pdu}\n```");
self.write_str(&out).await
}
pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
let latest_pdu = self
.services
.rooms
.timeline
.latest_pdu_in_room(&room_id)
.await
.map(Event::into_canonical_object)
.and_then(|v| serde_json::to_string_pretty(&v).map_err(Into::into))
.map_err(|e| err!(Database("Failed to find the latest PDU in database: {e:?}")))?;
let out = format!("```json\n{latest_pdu}\n```");
self.write_str(&out).await
}
pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
// TODO: This command sucks and really needs to elide redundant auth
// edges.
let node_status = async |event_id: &EventId, missing: bool| -> NodeStatus {
if self
.services
.rooms
.pdu_metadata
.is_event_rejected(event_id)
.await
{
NodeStatus::Rejected(missing)
} else if self
.services
.rooms
.pdu_metadata
.is_event_soft_failed(event_id)
.await
{
NodeStatus::SoftFailed(missing)
} else {
NodeStatus::Normal(missing)
}
};
let Ok(root) = self.services.rooms.timeline.get_pdu(&event_id).await else {
return Err!("Event not found.");
};
let mut graph = String::from(
"```mermaid\n%% This is a mermaid graph. You can plug this output into\n\
%% https://mermaid.live/edit to visualise it on-the-fly.\nflowchart TD\n\
classDef rejected fill:#ffe5e5,stroke:#cc0000,stroke-width:2px,color:#000;\n\
classDef soft_failed fill:#fff6cc,stroke:#c9a400,stroke-width:2px,color:#000;\n"
);
let mut node_ids: HashMap<OwnedEventId, String> = HashMap::new();
let mut cached_events: HashMap<OwnedEventId, PduEvent> =
HashMap::from([(event_id.clone(), root.clone())]);
let mut scheduled: HashSet<OwnedEventId> = HashSet::from([event_id.clone()]);
let mut visited: HashSet<OwnedEventId> = HashSet::new();
let mut stack = vec![root];
let mut next_node_id = 0_usize;
let node_id_for = |event_id: &OwnedEventId,
node_ids: &mut HashMap<OwnedEventId, String>,
next_node_id: &mut usize| {
node_ids
.entry(event_id.clone())
.or_insert_with(|| {
let id = format!("n{}", *next_node_id);
*next_node_id = next_node_id.saturating_add(1);
id
})
.clone()
};
let node_name = |e: &PduEvent| {
if let Some(state_key) = e.state_key() {
format!("{},'{}'", e.event_type(), state_key)
} else {
format!("{}", e.event_type())
}
};
while let Some(event) = stack.pop() {
let current_event_id = event.event_id().to_owned();
if !visited.insert(current_event_id.clone()) {
continue;
}
let current_node_id =
node_id_for(&current_event_id, &mut node_ids, &mut next_node_id);
let current_status = node_status(&current_event_id, false).await;
render_node(
&mut graph,
&current_node_id,
&current_event_id,
&node_name(&event),
current_status,
)?;
let mut children = Vec::with_capacity(event.auth_events.len());
for auth_event_id in event.auth_events().rev() {
let auth_event_id = auth_event_id.to_owned();
let auth_node_id = node_id_for(&auth_event_id, &mut node_ids, &mut next_node_id);
writeln!(graph, "{current_node_id} --> {auth_node_id}")?;
let first_seen = scheduled.insert(auth_event_id.clone());
let auth_pdu = if let Some(auth_pdu) = cached_events.get(&auth_event_id) {
// NOTE: events might be referenced multiple times (like the
// create event) so this saves some cheeky db lookup
// time
Some(auth_pdu.clone())
} else if first_seen {
match self.services.rooms.timeline.get_pdu(&auth_event_id).await {
| Ok(auth_event) => {
cached_events.insert(auth_event_id.clone(), auth_event.clone());
Some(auth_event)
},
| Err(_) => None,
}
} else {
None
};
// NOTE: Depth is used as the primary sorting key here, even
// though it has no bearing on state resolution or anything.
// Timestamp is used as a tiebreaker, failing back to
// lexicographical comparison.
let (depth, ts) = auth_pdu
.as_ref()
.map_or((UInt::MAX, UInt::MAX), |pdu| (pdu.depth, pdu.origin_server_ts));
children.push(AuthChild {
node_id: auth_node_id,
event_id: auth_event_id,
depth,
ts,
first_seen,
pdu: auth_pdu,
});
}
children.sort_by(|a, b| {
a.depth
.cmp(&b.depth)
.then(a.ts.cmp(&b.ts))
.then(a.event_id.as_str().cmp(b.event_id.as_str()))
});
for child in children.into_iter().rev() {
if !child.first_seen {
continue;
}
if let Some(child_pdu) = child.pdu {
// We have this PDU so will want to traverse it.
stack.push(child_pdu);
} else {
// We don't have this PDU locally so we can't traverse its
// auth events, but we can still render it as a node.
render_node(
&mut graph,
&child.node_id,
&child.event_id,
"",
node_status(&child.event_id, true).await,
)?;
}
}
}
graph.push_str("```\n");
self.write_str(&graph).await
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum NodeStatus {
Normal(bool),
SoftFailed(bool),
Rejected(bool),
}
struct AuthChild {
node_id: String,
event_id: OwnedEventId,
depth: UInt,
ts: UInt,
first_seen: bool,
pdu: Option<PduEvent>,
}
fn render_node(
graph: &mut String,
node_id: &str,
event_id: &EventId,
name: &str,
status: NodeStatus,
) -> Result {
let evt_str = event_id.to_string();
let status_label = match status {
| NodeStatus::Normal(false) => format!("{evt_str}: {name}"),
| NodeStatus::Normal(true) => format!("{evt_str}: {name} (missing locally)"),
| NodeStatus::SoftFailed(false) => format!("{evt_str}: {name} (soft-failed)"),
| NodeStatus::SoftFailed(true) =>
format!("{evt_str}: {name} (soft-failed & missing locally)"),
| NodeStatus::Rejected(false) => format!("{evt_str}: {name} (rejected)"),
| NodeStatus::Rejected(true) => format!("{evt_str}: {name} (rejected & missing locally)"),
};
writeln!(graph, "{node_id}[\"{}\"]", status_label.as_str())?;
match status {
| NodeStatus::Rejected(_) => writeln!(graph, "class {node_id} rejected;")?,
| NodeStatus::SoftFailed(_) => writeln!(graph, "class {node_id} soft_failed;")?,
| NodeStatus::Normal(_) => {},
}
Ok(())
}
-167
View File
@@ -1,167 +0,0 @@
use std::hash::RandomState;
use clap::Subcommand;
use conduwuit::{Err, Result, info};
use conduwuit_macros::admin_command_dispatch;
use futures::StreamExt;
use ruma::{OwnedRoomOrAliasId, OwnedServerName, OwnedUserId};
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum RoomMembershipCommands {
/// Make a local user join a room.
#[clap(name = "join")]
JoinRoom {
/// The user to make join the room. Must be a local user.
user_id: OwnedUserId,
/// The room (ID or alias) to join.
room: OwnedRoomOrAliasId,
/// The server to join through, if a remote room.
///
/// Residents returned after resolving an alias override this option.
#[arg(long)]
via: Option<OwnedServerName>,
},
/// Makes all local users join the designated room.
JoinAllLocalUsers {
/// The room (ID or alias) to join.
room: OwnedRoomOrAliasId,
},
/// Make a local user leave a room or reject an invite.
#[clap(name = "leave", alias = "reject-invite")]
LeaveRoom {
/// The user to make leave the room. Must be a local user.
user_id: OwnedUserId,
/// The room (ID or alias) to leave.
room: OwnedRoomOrAliasId,
/// The server to leave through, if a room we are not a member of (e.g.
/// an invite).
///
/// Residents returned after resolving an alias override this option.
#[arg(long)]
via: Option<OwnedServerName>,
},
}
impl crate::Context<'_> {
pub(super) async fn join_room(
&self,
user_id: OwnedUserId,
room: OwnedRoomOrAliasId,
via: Option<OwnedServerName>,
) -> Result {
self.bail_restricted()?;
if !self.services.globals.user_is_local(&user_id) {
return Err!("User {user_id:?} does not belong to our server.");
}
let (room_id, residents) = self
.services
.rooms
.alias
.resolve_with_servers(&room, via.map(|v| vec![v]))
.await?;
self.services
.rooms
.membership
.join_room(&user_id, &room_id, None, &residents)
.await?;
self.write_str(&format!("Successfully joined {room_id} as {user_id}."))
.await
}
pub(super) async fn join_all_local_users(&self, room: OwnedRoomOrAliasId) -> Result {
self.bail_restricted()?;
let (room_id, residents) = self
.services
.rooms
.alias
.resolve_with_servers(&room, None)
.await?;
if !self
.services
.rooms
.state_cache
.is_joined(
self.sender
.expect("This command must be executed by a user"),
&room_id,
)
.await
{
return Err!("You must be a member of the room you want to join everyone to.");
}
let mut success = 0_usize;
let mut failed = 0_usize;
let mut local_users = self.services.users.stream_local_users();
while let Some(user_id) = local_users.next().await {
if self
.services
.rooms
.membership
.join_room(&user_id, &room_id, None, &residents)
.await
.is_ok()
{
success = success.saturating_add(1);
} else {
failed = failed.saturating_add(1);
}
}
self.write_str(&format!("Done: {success} successful joins, {failed} failed."))
.await
}
pub(super) async fn leave_room(
&self,
user_id: OwnedUserId,
room: OwnedRoomOrAliasId,
via: Option<OwnedServerName>,
) -> Result {
self.bail_restricted()?;
if !self.services.globals.user_is_local(&user_id) {
return Err!("User {user_id:?} does not belong to our server.");
}
let no_explicit_via = via.is_none();
let (room_id, residents) = self
.services
.rooms
.alias
.resolve_with_servers(&room, via.map(|v| vec![v]))
.await?;
if no_explicit_via
|| self
.services
.rooms
.state_cache
.server_in_room(self.services.globals.server_name(), &room_id)
.await
{
if !self
.services
.rooms
.state_cache
.is_joined(&user_id, &room_id)
.await
{
return Err!("User {user_id:?} is not a member of room {room_id:?}.");
}
info!("Leaving room locally...");
conduwuit_api::client::leave_room(self.services, &user_id, &room_id, None).await?;
} else {
info!("Leaving room remotely...");
conduwuit_api::client::remote_leave_room::<RandomState>(
self.services,
&user_id,
&room_id,
None,
residents.into_iter().collect(),
)
.await?;
}
self.write_str(&format!("Successfully made {user_id} leave {room_id}."))
.await
}
}
+6 -22
View File
@@ -1,20 +1,16 @@
mod alias;
mod commands;
mod directory;
mod graph;
mod info;
mod membership;
mod moderation;
mod state;
use clap::Subcommand;
use conduwuit::Result;
use ruma::OwnedRoomId;
use self::{
alias::RoomAliasCommand, directory::RoomDirectoryCommand, graph::GraphCommand,
info::RoomInfoCommand, membership::RoomMembershipCommands, moderation::RoomModerationCommand,
state::RoomStateCommand,
alias::RoomAliasCommand, directory::RoomDirectoryCommand, info::RoomInfoCommand,
moderation::RoomModerationCommand,
};
use crate::admin_command_dispatch;
@@ -44,34 +40,22 @@ pub enum RoomCommand {
no_details: bool,
},
/// View information about a room we know about
#[command(subcommand)]
/// View information about a room we know about
Info(RoomInfoCommand),
/// Manage moderation of remote or local rooms
#[command(subcommand)]
/// Manage moderation of remote or local rooms
Moderation(RoomModerationCommand),
/// Manage rooms' aliases
#[command(subcommand)]
/// Manage rooms' aliases
Alias(RoomAliasCommand),
#[command(subcommand)]
/// Manage the room directory
#[command(subcommand)]
Directory(RoomDirectoryCommand),
/// Manage room memberships (join, leave, invite, etc.) for local users.
#[command(subcommand)]
Membership(RoomMembershipCommands),
/// Interface with room graphs directly (advanced).
#[command(subcommand)]
Graph(GraphCommand),
/// Interface with room state directly (advanced).
#[command(subcommand)]
State(RoomStateCommand),
/// Check if we know about a room
Exists {
room_id: OwnedRoomId,
-286
View File
@@ -1,286 +0,0 @@
use std::collections::HashMap;
use clap::Subcommand;
use conduwuit::{Err, Event, PduEvent, Result, debug_error, err, info, warn};
use conduwuit_macros::admin_command_dispatch;
use futures::StreamExt;
#[allow(unused_imports)]
// necessary to stop RustRover from importing this trait for some reason
use ruma::state_res::Event as _;
use ruma::{
OwnedEventId, OwnedRoomOrAliasId, OwnedServerName, api::federation::event::get_room_state,
};
use service::rooms::state_compressor::HashSetCompressStateEvent;
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum RoomStateCommand {
/// Exports the room's current state as a JSON file.
/// If an event ID is supplied, the state at that event (the state preceding
/// it, plus any change made by the named event) is returned instead, if it
/// is known.
#[clap(name = "export")]
ExportState {
/// The room ID or alias to get the state for.
room: OwnedRoomOrAliasId,
/// The event ID to get the state at, if any.
event_id: Option<OwnedEventId>,
},
/// Downloads the current state of a room from a remote server, and replaces
/// the local copy of the room's state with it.
///
/// If you're reading this, this command does not do what you think it does.
Transplant {
/// The room ID or alias to replace the current state of.
room: OwnedRoomOrAliasId,
/// The server name to fetch the state from. Make sure this is a trusted
/// server, as the result will be implicitly trusted.
server_name: OwnedServerName,
/// The latest event ID in the room to use as the "latest event".
/// Calculated by default.
at_event: Option<OwnedEventId>,
/// Try to force the state even if the server thinks it isn't in the
/// target room.
///
/// Using this on rooms the server has never joined may break
/// everything.
#[arg(long)]
force: bool,
// (the "may break everything" part isn't necessarily true, but it is highly likely that
// things will actually break in an unrecoverable way, so being dramatic gets the main
// point across)
},
}
impl crate::Context<'_> {
pub(super) async fn export_state(
&self,
room: OwnedRoomOrAliasId,
event_id: Option<OwnedEventId>,
) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?;
let shortstatehash = match &event_id {
| Some(event_id) =>
self.services
.rooms
.state_accessor
.pdu_shortstatehash(event_id)
.await?,
| None =>
self.services
.rooms
.state
.get_room_shortstatehash(&room_id)
.await?,
};
let mut state_at: Vec<_> = self
.services
.rooms
.state_accessor
.state_full_pdus(shortstatehash)
.map(Event::into_pdu)
.collect()
.await;
if let Some(event_id) = event_id {
let pdu = self.services.rooms.timeline.get_pdu(&event_id).await?;
if let Some(state_key) = pdu.state_key() {
state_at.retain(|p| p.kind() != pdu.kind() || p.state_key() != Some(state_key));
state_at.push(pdu);
}
}
if state_at.is_empty() {
return Err!(Request(NotFound("No state found.")));
}
let json = serde_json::to_string_pretty(&state_at).map_err(|e| {
err!(Database(
"Failed to convert room state events to pretty JSON, possible invalid room \
state events in the database: {e:?}",
))
})?;
self.write_str(&format!("```json\n{json}\n```")).await
}
pub(super) async fn transplant(
&self,
room: OwnedRoomOrAliasId,
server_name: OwnedServerName,
latest_event: Option<OwnedEventId>,
force: bool,
) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?;
if !force
&& !self
.services
.rooms
.state_cache
.server_in_room(&self.services.server.name, &room_id)
.await
{
return Err!(
"We are not participating in the room / we don't know about the room ID."
);
}
let at_event_id = match latest_event {
| Some(event_id) => event_id,
| None => self
.services
.rooms
.timeline
.latest_pdu_in_room(&room_id)
.await
.map_err(|_| err!(Database("Failed to find the latest PDU in database")))?
.event_id()
.to_owned(),
};
let room_version = self.services.rooms.state.get_room_version(&room_id).await?;
let room_version_rules = room_version.rules().unwrap();
let mut state: HashMap<u64, OwnedEventId> = HashMap::new();
let state_lock = self.services.rooms.state.mutex.lock(&*room_id).await;
// TODO: Use /state_ids and fetch events we're missing atomically,
// instead of /state, which is very large and frequently times out.
let remote_state_response = self
.services
.sending
.send_federation_request(
&server_name,
get_room_state::v1::Request::new(at_event_id.clone(), room_id.clone()),
)
.await?;
for pdu in remote_state_response.pdus.clone() {
match self
.services
.rooms
.event_handler
.parse_incoming_pdu(&pdu, Some(&room_version_rules))
.await
{
| Ok(t) => t,
| Err(e) => {
warn!("Could not parse PDU, ignoring: {e}");
continue;
},
};
}
info!("Going through room_state response PDUs");
for result in remote_state_response.pdus.iter().map(|pdu| {
self.services
.server_keys
.verify_event_json_no_fetch_add_event_id(pdu, &room_version_rules)
}) {
let Ok((event_id, value)) = result.await else {
continue;
};
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
debug_error!(
"Invalid PDU in fetching remote room state PDUs response: {value:#?}"
);
err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}")))
})?;
self.services
.rooms
.outlier
.add_pdu_outlier(&event_id, &value);
if let Some(state_key) = &pdu.state_key {
let shortstatekey = self
.services
.rooms
.short
.get_or_create_shortstatekey(&pdu.kind.to_string().into(), state_key)
.await;
state.insert(shortstatekey, pdu.event_id.clone());
self.services
.rooms
.pdu_metadata
.clear_pdu_markers(pdu.event_id());
}
}
info!("Going through auth_chain response");
for result in remote_state_response.auth_chain.iter().map(|pdu| {
self.services
.server_keys
.verify_event_json_no_fetch_add_event_id(pdu, &room_version_rules)
}) {
let Ok((event_id, value)) = result.await else {
continue;
};
self.services
.rooms
.outlier
.add_pdu_outlier(&event_id, &value);
self.services
.rooms
.pdu_metadata
.clear_pdu_markers(&event_id);
}
info!("Resolving new room state");
let new_room_state = self
.services
.rooms
.event_handler
.resolve_state(&room_id, &room_version_rules, state)
.await?;
info!("Compressing new room state");
let HashSetCompressStateEvent {
shortstatehash: short_state_hash,
added,
removed,
} = self
.services
.rooms
.state_compressor
.save_state(room_id.clone().as_ref(), new_room_state)
.await?;
info!("Forcing new room state");
self.services
.rooms
.state
.force_state(room_id.clone().as_ref(), short_state_hash, added, removed, &state_lock)
.await?;
info!("Replacing forward extremities");
self.services
.rooms
.state
.replace_forward_extremities(
&room_id,
std::iter::once(at_event_id.as_ref()),
&state_lock,
)
.await;
info!("Updating joined counts for room");
self.services
.rooms
.state_cache
.update_joined_count(&room_id)
.await;
self.write_str("Successfully forced the room state from the requested remote server.")
.await
}
}
+1 -35
View File
@@ -1,12 +1,11 @@
use std::{fmt::Write, path::PathBuf, sync::Arc};
use conduwuit::{
Err, Result, err,
Err, Result,
utils::{stream::IterStream, time},
warn,
};
use futures::TryStreamExt;
use tracing_subscriber::EnvFilter;
impl crate::Context<'_> {
pub(super) async fn uptime(&self) -> Result {
@@ -235,37 +234,4 @@ impl crate::Context<'_> {
self.write_str(&info).await
}
pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool) -> Result {
let handles = &["console"];
if reset {
let old_filter_layer = EnvFilter::try_new(&self.services.server.config.log)
.map_err(|e| err!("Log level from config appears to be invalid now: {e}"))?;
self.services
.server
.log
.reload
.reload(&old_filter_layer, Some(handles))
.map_err(|e| {
err!("Failed to modify and reload the global tracing log level: {e}")
})?;
self.write_str("Successfully changed log level back to config value")
.await
} else {
let filter = filter.ok_or_else(|| err!("No log level was specified."))?;
let new_filter_layer = EnvFilter::try_new(filter)
.map_err(|e| err!("Invalid log level filter specified: {e}"))?;
self.services
.server
.log
.reload
.reload(&new_filter_layer, Some(handles))
.map_err(|e| {
err!("Failed to modify and reload the global tracing log level: {e}")
})?;
self.write_str("Successfully changed log level back to config value")
.await
}
}
}
-12
View File
@@ -58,16 +58,4 @@ pub enum ServerCommand {
/// Build information
BuildInfo,
/// Change tracing log level/filter on the fly
///
/// This accepts the same format as the `log` config option.
ChangeLogLevel {
/// Log level/filter
filter: Option<String>,
/// Resets the log level/filter to the one in your config
#[arg(short, long)]
reset: bool,
},
}
+315 -5
View File
@@ -1,16 +1,19 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashSet};
use api::client::{full_user_deactivate, leave_room, recreate_push_rules_and_return};
use api::client::{
full_user_deactivate, leave_room, recreate_push_rules_and_return, remote_leave_room,
};
use conduwuit::{
Err, Result, info,
Err, Result, debug_warn, info,
matrix::{Event, pdu::PartialPdu},
utils::{self},
utils::{self, ReadyExt},
warn,
};
use futures::{FutureExt, StreamExt};
use lettre::Address;
use ruma::{
OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedUserId, UserId, assign,
OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, ServerName,
UserId, assign,
events::{
RoomAccountDataEventType,
room::{power_levels::RoomPowerLevelsEventContent, redaction::RoomRedactionEventContent},
@@ -25,6 +28,7 @@ use crate::{
};
const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
const BULK_JOIN_REASON: &str = "Bulk force joining this room as initiated by the server admin.";
impl crate::Context<'_> {
pub(super) async fn list_users(
@@ -460,6 +464,272 @@ impl crate::Context<'_> {
.await
}
pub(super) async fn force_join_list_of_local_users(
&self,
room_id: OwnedRoomOrAliasId,
yes_i_want_to_do_this: bool,
) -> Result {
if self.body.len() < 2
|| !self.body[0].trim().starts_with("```")
|| self.body.last().unwrap_or(&"").trim() != "```"
{
return Err!("Expected code block in command body. Add --help for details.",);
}
if !yes_i_want_to_do_this {
return Err!(
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to \
force bulk join all specified local users.",
);
}
let server_admins = self.services.admin.get_admins().await;
if server_admins.is_empty() {
return Err!("There are no admins set for this server.");
}
let (room_id, servers) = self
.services
.rooms
.alias
.resolve_with_servers(&room_id, None)
.await?;
if !self
.services
.rooms
.state_cache
.server_in_room(self.services.globals.server_name(), &room_id)
.await
{
return Err!("We are not joined in this room.");
}
if !self
.services
.rooms
.state_cache
.room_members(&room_id)
.ready_any(|user_id| server_admins.contains(&user_id))
.await
{
return Err!("There is not a single server admin in the room.",);
}
let usernames = self
.body
.to_vec()
.drain(1..self.body.len().saturating_sub(1))
.collect::<Vec<_>>();
let mut user_ids: Vec<OwnedUserId> = Vec::with_capacity(usernames.len());
for username in usernames {
match parse_active_local_user_id(self.services, username).await {
| Ok(user_id) => {
// don't make the server service account join
if user_id == self.services.globals.server_user {
self.services
.admin
.send_text(&format!(
"{username} is the server service account, skipping over"
))
.await;
continue;
}
user_ids.push(user_id);
},
| Err(e) => {
self.services
.admin
.send_text(&format!(
"{username} is not a valid username, skipping over: {e}"
))
.await;
continue;
},
}
}
let mut failed_joins: usize = 0;
let mut successful_joins: usize = 0;
for user_id in user_ids {
match self
.services
.rooms
.membership
.join_room(&user_id, &room_id, Some(String::from(BULK_JOIN_REASON)), &servers)
.await
{
| Ok(_res) => {
successful_joins = successful_joins.saturating_add(1);
},
| Err(e) => {
debug_warn!(
"Failed force joining {user_id} to {room_id} during bulk join: {e}"
);
failed_joins = failed_joins.saturating_add(1);
},
}
}
self.write_str(&format!(
"{successful_joins} local users have been joined to {room_id}. {failed_joins} joins \
failed.",
))
.await
}
pub(super) async fn force_join_all_local_users(
&self,
room_id: OwnedRoomOrAliasId,
yes_i_want_to_do_this: bool,
) -> Result {
if !yes_i_want_to_do_this {
return Err!(
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to \
force bulk join all local users.",
);
}
let server_admins = self.services.admin.get_admins().await;
if server_admins.is_empty() {
return Err!("There are no admins set for this server.");
}
let (room_id, servers) = self
.services
.rooms
.alias
.resolve_with_servers(&room_id, None)
.await?;
if !self
.services
.rooms
.state_cache
.server_in_room(self.services.globals.server_name(), &room_id)
.await
{
return Err!("We are not joined in this room.");
}
if !self
.services
.rooms
.state_cache
.room_members(&room_id)
.ready_any(|user_id| server_admins.contains(&user_id))
.await
{
return Err!("There is not a single server admin in the room.",);
}
let mut failed_joins: usize = 0;
let mut successful_joins: usize = 0;
for user_id in &self
.services
.users
.stream_local_users()
.collect::<Vec<_>>()
.await
{
match self
.services
.rooms
.membership
.join_room(user_id, &room_id, Some(String::from(BULK_JOIN_REASON)), &servers)
.await
{
| Ok(_res) => {
successful_joins = successful_joins.saturating_add(1);
},
| Err(e) => {
debug_warn!(
"Failed force joining {user_id} to {room_id} during bulk join: {e}"
);
failed_joins = failed_joins.saturating_add(1);
},
}
}
self.write_str(&format!(
"{successful_joins} local users have been joined to {room_id}. {failed_joins} joins \
failed.",
))
.await
}
pub(super) async fn force_join_room(
&self,
user_id: String,
room_id: OwnedRoomOrAliasId,
via: Option<String>,
) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?;
let (room_id, mut servers) = self
.services
.rooms
.alias
.resolve_with_servers(&room_id, None)
.await?;
if let Some(via) = via.map(ServerName::parse).transpose()? {
servers.retain(|n| *n != via);
servers.insert(0, via);
}
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
self.services
.rooms
.membership
.join_room(&user_id, &room_id, None, &servers)
.await?;
self.write_str(&format!("{user_id} has been joined to {room_id}."))
.await
}
pub(super) async fn force_leave_room(
&self,
user_id: String,
room_id: OwnedRoomOrAliasId,
) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?;
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
if !self
.services
.rooms
.state_cache
.is_joined(&user_id, &room_id)
.await
{
return Err!("{user_id} is not joined in the room");
}
leave_room(self.services, &user_id, &room_id, None)
.boxed()
.await?;
self.write_str(&format!("{user_id} has left {room_id}."))
.await
}
pub(super) async fn force_demote(
&self,
user_id: String,
@@ -673,6 +943,46 @@ impl crate::Context<'_> {
.await
}
pub(super) async fn force_leave_remote_room(
&self,
user_id: String,
room_id: OwnedRoomOrAliasId,
via: Option<String>,
) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?;
let (room_id, vias_raw) = self
.services
.rooms
.alias
.resolve_with_servers(
&room_id,
if let Some(v) = via.clone() {
Some(vec![ServerName::parse(v)?])
} else {
None
},
)
.await?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
let mut vias: HashSet<OwnedServerName> = HashSet::new();
if let Some(via) = via {
vias.insert(ServerName::parse(via)?);
}
for server in vias_raw {
vias.insert(server);
}
remote_leave_room(self.services, &user_id, &room_id, None, vias)
.boxed()
.await?;
self.write_str(&format!("{user_id} successfully left {room_id} via remote server."))
.await
}
pub(super) async fn lock(&self, user_id: String) -> Result {
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
+53
View File
@@ -193,6 +193,32 @@ pub enum UserCommand {
user_id: String,
},
/// Manually join a local user to a room.
ForceJoinRoom {
/// The user to join
user_id: String,
/// The room to join
room_id: OwnedRoomOrAliasId,
/// The server name to join via.
///
/// This server will always be tried first, however if more are
/// available, they may be tried after.
via: Option<String>,
},
/// Manually leave a local user from a room.
ForceLeaveRoom {
user_id: String,
room_id: OwnedRoomOrAliasId,
},
/// Manually leave a remote room for a local user.
ForceLeaveRemoteRoom {
user_id: String,
room_id: OwnedRoomOrAliasId,
via: Option<String>,
},
/// Forces the specified user to drop their power levels to the room
/// default, if their permissions allow and the auth check permits
ForceDemote {
@@ -239,6 +265,33 @@ pub enum UserCommand {
event_id: OwnedEventId,
},
/// Force joins a specified list of local users to join the specified
/// room.
///
/// Specify a codeblock of usernames.
///
/// At least 1 server admin must be in the room to reduce abuse.
///
/// Requires the `--yes-i-want-to-do-this` flag.
ForceJoinListOfLocalUsers {
room_id: OwnedRoomOrAliasId,
#[arg(long)]
yes_i_want_to_do_this: bool,
},
/// Force joins all local users to the specified room.
///
/// At least 1 server admin must be in the room to reduce abuse.
///
/// Requires the `--yes-i-want-to-do-this` flag.
ForceJoinAllLocalUsers {
room_id: OwnedRoomOrAliasId,
#[arg(long)]
yes_i_want_to_do_this: bool,
},
/// Resets the push-rules (notification settings) of the target user to the
/// server defaults.
ResetPushRules {
+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
@@ -214,7 +214,7 @@ pub async fn leave_room(
Ok(())
}
pub async fn remote_leave_room<S: std::hash::BuildHasher>(
pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
services: &Services,
user_id: &UserId,
room_id: &RoomId,
+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)]
+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;
@@ -382,7 +382,7 @@ impl super::Service {
/// returned the correct event.
/// Allows `fetch_and_handle_missing_events` to atomically fetch events from
/// multiple remotes in parallel.
pub async fn fetch_event_via(
async fn fetch_event_via(
&self,
remote: OwnedServerName,
event_id: OwnedEventId,
@@ -93,7 +93,7 @@ impl super::Service {
room_version_rules: Option<&RoomVersionRules>,
) -> Result<Parsed> {
let value = serde_json::from_str::<CanonicalJsonObject>(pdu.get()).map_err(|e| {
err!(BadServerResponse(debug_warn!("Error parsing incoming event as JSON {e:?}")))
err!(BadServerResponse(debug_warn!("Error parsing incoming event {e:?}")))
})?;
let event_type = value
.get("type")
+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.")));