Compare commits

..
Author SHA1 Message Date
timedout ca5b43c6bb wip: Room data purging 2026-05-01 17:38:43 +01:00
69 changed files with 1617 additions and 648 deletions

No files matched your search

+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@b5fddbb5361bce8a06fb168c9d403a6cc552b084 # v2
uses: https://github.com/taiki-e/install-action@787505cde8a44ea468a00478fe52baf23b15bccd # v2
with:
tool: git-warp-time,timelord-cli@3.0.1
+2
View File
@@ -45,6 +45,7 @@ If you aren't sure about some, feel free to ask for clarification in #dev:contin
- [ ] I have [tested my contribution][c1t] (or proof-read it for documentation-only changes)
myself, if applicable. This includes ensuring code compiles.
- [ ] My commit messages follow the [commit message format][c1cm] and are descriptive.
- [ ] I have written a [news fragment][n1] for this PR, if applicable<!--(can be done after hitting open!)-->.
<!--
Notes on these requirements:
@@ -78,3 +79,4 @@ Notes on these requirements:
[c1pc]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#pre-commit-checks
[c1t]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#running-tests-locally
[c1cm]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#commit-messages
[n1]: https://towncrier.readthedocs.io/en/stable/tutorial.html#creating-news-fragments
Generated
+339 -205
View File
File diff suppressed because it is too large. Load diff
+10 -8
View File
@@ -39,10 +39,7 @@ features = ["ffi", "std", "union"]
version = "1.1.0"
[workspace.dependencies.ctor]
version = "0.13.0"
[workspace.dependencies.dtor]
version = "0.13.0"
version = "0.10.0"
[workspace.dependencies.cargo_toml]
version = "0.22"
@@ -433,7 +430,7 @@ features = ["http", "grpc-tonic", "trace", "logs", "metrics"]
# optional sentry metrics for crash/panic reporting
[workspace.dependencies.sentry]
version = "0.48.0"
version = "0.47.0"
default-features = false
features = [
"backtrace",
@@ -448,9 +445,9 @@ features = [
]
[workspace.dependencies.sentry-tracing]
version = "0.48.0"
version = "0.47.0"
[workspace.dependencies.sentry-tower]
version = "0.48.0"
version = "0.47.0"
# jemalloc usage
[workspace.dependencies.tikv-jemalloc-sys]
@@ -549,11 +546,16 @@ features = ["std"]
[workspace.dependencies.maplit]
version = "1.0.2"
[workspace.dependencies.ldap3]
version = "0.12.0"
default-features = false
features = ["sync", "tls-rustls", "rustls-provider"]
[workspace.dependencies.yansi]
version = "1.0.1"
[workspace.dependencies.askama]
version = "0.16.0"
version = "0.15.0"
[workspace.dependencies.lettre]
version = "0.11.19"
-1
View File
@@ -1 +0,0 @@
The invite recipient's membership event is now included in invite stripped state, which should fix flaky invite display in some clients. Contributed by @ginger
-1
View File
@@ -1 +0,0 @@
Removed support for guest user registration, a little-used and deprecated approach to room previews.
-1
View File
@@ -1 +0,0 @@
Removed support for LDAP.
-1
View File
@@ -1 +0,0 @@
Clarified in the config that `max_request_size` affects federated media as well.
-1
View File
@@ -1 +0,0 @@
Added support for fallback encryption keys.
+2
View File
@@ -7,6 +7,7 @@
[global]
address = "0.0.0.0"
allow_device_name_federation = true
allow_guest_registration = true
allow_public_room_directory_over_federation = true
allow_registration = true
database_path = "/database"
@@ -31,6 +32,7 @@ rocksdb_log_level = "info"
rocksdb_max_log_files = 1
rocksdb_recovery_mode = 0
rocksdb_paranoid_file_checks = true
log_guest_registrations = false
allow_legacy_media = true
startup_netburst = true
startup_netburst_keep = -1
+111 -1
View File
@@ -291,7 +291,6 @@
#ip_lookup_strategy = 5
# Max request size for file uploads in bytes. Defaults to 20MB.
# Also limits incoming federated media.
#
#max_request_size = 20971520
@@ -1271,6 +1270,21 @@
#
#brotli_compression = false
# Set to true to allow user type "guest" registrations. Some clients like
# Element attempt to register guest users automatically.
#
#allow_guest_registration = false
# Set to true to log guest registrations in the admin room. Note that
# these may be noisy or unnecessary if you're a public homeserver.
#
#log_guest_registrations = false
# Set to true to allow guest registrations/users to auto join any rooms
# specified in `auto_join_rooms`.
#
#allow_guests_auto_join_rooms = false
# Enable the legacy unauthenticated Matrix media repository endpoints.
# These endpoints consist of:
# - /_matrix/media/*/config
@@ -1919,6 +1933,102 @@
#
#foci = []
[global.ldap]
# Whether to enable LDAP login.
#
# example: "true"
#
#enable = false
# Whether to force LDAP authentication or authorize classical password
# login.
#
# example: "true"
#
#ldap_only = false
# URI of the LDAP server.
#
# example: "ldap://ldap.example.com:389"
#
#uri = ""
# StartTLS for LDAP connections.
#
#use_starttls = false
# Skip TLS certificate verification, possibly dangerous.
#
#disable_tls_verification = false
# Root of the searches.
#
# example: "ou=users,dc=example,dc=org"
#
#base_dn = ""
# Bind DN if anonymous search is not enabled.
#
# You can use the variable `{username}` that will be replaced by the
# entered username. In such case, the password used to bind will be the
# one provided for the login and not the one given by
# `bind_password_file`. Beware: automatically granting admin rights will
# not work if you use this direct bind instead of a LDAP search.
#
# example: "cn=ldap-reader,dc=example,dc=org" or
# "cn={username},ou=users,dc=example,dc=org"
#
#bind_dn = ""
# Path to a file on the system that contains the password for the
# `bind_dn`.
#
# The server must be able to access the file, and it must not be empty.
#
#bind_password_file = ""
# Search filter to limit user searches.
#
# You can use the variable `{username}` that will be replaced by the
# entered username for more complex filters.
#
# example: "(&(objectClass=person)(memberOf=matrix))"
#
#filter = "(objectClass=*)"
# Attribute to use to uniquely identify the user.
#
# example: "uid" or "cn"
#
#uid_attribute = "uid"
# Attribute containing the display name of the user.
#
# example: "givenName" or "sn"
#
#name_attribute = "givenName"
# Root of the searches for admin users.
#
# Defaults to `base_dn` if empty.
#
# example: "ou=admins,dc=example,dc=org"
#
#admin_base_dn = ""
# The LDAP search filter to find administrative users for continuwuity.
#
# If left blank, administrative state must be configured manually for each
# user.
#
# You can use the variable `{username}` that will be replaced by the
# entered username for more complex filters.
#
# example: "(objectClass=conduwuitAdmin)" or "(uid={username})"
#
#admin_filter = ""
#[global.antispam]
#[global.antispam.meowlnir]
+1 -1
View File
@@ -50,7 +50,7 @@ EOF
# Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.19.0
ENV BINSTALL_VERSION=1.18.1
# renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree
+1 -1
View File
@@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \
# Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.19.0
ENV BINSTALL_VERSION=1.18.1
# renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree
+1 -1
View File
@@ -7,7 +7,7 @@ Admin commands allow server administrators to manage the server from within thei
* All commands listed here may be used by server administrators in the admin room by sending them as messages.
* If the `admin_escape_commands` configuration option is enabled, server administrators may run certain commands in public rooms by prefixing them with a single backslash. These commands will only run on _their_ homeserver, even if they are a member of another homeserver's admin room. Some sensitive commands cannot be used outside the admin room and will return an error.
* All commands listed here may be used in the server's console, if it is enabled. Commands entered in the console do not require the `!admin` prefix.
* All commands listed here may be used in the server's console, if it is enabled. Commands entered in the console do not require the `!admin` prefix. If Continuwuity is deployed via Docker, be sure to set the appropriate options detailed in [the Docker deployment guide](../../deploying/docker.mdx#accessing-the-servers-console) to enable access to the server's console.
## Categories
Generated
+15 -15
View File
@@ -3,11 +3,11 @@
"advisory-db": {
"flake": false,
"locked": {
"lastModified": 1777645914,
"narHash": "sha256-P1T7QVQS13OvkXEuEhI91CLaQfyv6iqV9vW8IBLLDYg=",
"lastModified": 1775907537,
"narHash": "sha256-vbeLNgmsx1Z6TwnlDV0dKyeBCcon3UpkV9yLr/yc6HM=",
"owner": "rustsec",
"repo": "advisory-db",
"rev": "d6ba1f7070ba91f45efe372d68eb648be67d0417",
"rev": "d99f7b9eb81731bddebf80a355f8be7b2f8b1b28",
"type": "github"
},
"original": {
@@ -18,11 +18,11 @@
},
"crane": {
"locked": {
"lastModified": 1777335812,
"narHash": "sha256-bEg5xoAxAwsyfnGhkEX7RJViTIBIYPd8ISg4O1c0HFc=",
"lastModified": 1775839657,
"narHash": "sha256-SPm9ck7jh3Un9nwPuMGbRU04UroFmOHjLP56T10MOeM=",
"owner": "ipetkov",
"repo": "crane",
"rev": "5e0fb2f64edff2822249f21293b8304dedaaf676",
"rev": "7cf72d978629469c4bd4206b95c402514c1f6000",
"type": "github"
},
"original": {
@@ -39,11 +39,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1777624102,
"narHash": "sha256-thSyElkje577x/kAbP72nHlfiFc1a+tCudskLPHXe9s=",
"lastModified": 1775891769,
"narHash": "sha256-EOfVlTKw2n8w1uhfh46GS4hEGnQ7oWrIWQfIY6utIkI=",
"owner": "nix-community",
"repo": "fenix",
"rev": "4d81601e0b73f20d81d066754ad0e7d1e7f75a06",
"rev": "6fbc54dde15aee725bdc7aae5e478849685d5f56",
"type": "github"
},
"original": {
@@ -89,11 +89,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1777268161,
"narHash": "sha256-bxrdOn8SCOv8tN4JbTF/TXq7kjo9ag4M+C8yzzIRYbE=",
"lastModified": 1775710090,
"narHash": "sha256-ar3rofg+awPB8QXDaFJhJ2jJhu+KqN/PRCXeyuXR76E=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "1c3fe55ad329cbcb28471bb30f05c9827f724c76",
"rev": "4c1018dae018162ec878d42fec712642d214fdfa",
"type": "github"
},
"original": {
@@ -132,11 +132,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1777583169,
"narHash": "sha256-dVJ4+wrRKc8oIgp3rLOFSq1obt/sCKlXy3h47qof/w0=",
"lastModified": 1775843361,
"narHash": "sha256-j53ZgyDvmYf3Sjh1IPvvTjqa614qUfVQSzj59+MpzkY=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "aa64e4828a2bbba44463c1229a81c748d3cce583",
"rev": "9eb97ea96d8400e8957ddd56702e962614296583",
"type": "github"
},
"original": {
+17 -17
View File
@@ -1399,9 +1399,9 @@
}
},
"node_modules/hookable": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/hookable/-/hookable-6.1.1.tgz",
"integrity": "sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==",
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/hookable/-/hookable-6.1.0.tgz",
"integrity": "sha512-ZoKZSJgu8voGK2geJS+6YtYjvIzu9AOM/KZXsBxr83uhLL++e9pEv/dlgwgy3dvHg06kTz6JOh1hk3C8Ceiymw==",
"dev": true,
"license": "MIT"
},
@@ -2683,20 +2683,20 @@
"license": "MIT"
},
"node_modules/oniguruma-parser": {
"version": "0.12.2",
"resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz",
"integrity": "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==",
"version": "0.12.1",
"resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.1.tgz",
"integrity": "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==",
"dev": true,
"license": "MIT"
},
"node_modules/oniguruma-to-es": {
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.6.tgz",
"integrity": "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==",
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.5.tgz",
"integrity": "sha512-Zjygswjpsewa0NLTsiizVuMQZbp0MDyM6lIt66OxsF21npUDlzpHi1Mgb/qhQdkb+dWFTzJmFbEWdvZgRho8eQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"oniguruma-parser": "^0.12.2",
"oniguruma-parser": "^0.12.1",
"regex": "^6.1.0",
"regex-recursion": "^6.0.2"
}
@@ -2822,9 +2822,9 @@
}
},
"node_modules/react-router": {
"version": "7.14.2",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.14.2.tgz",
"integrity": "sha512-yCqNne6I8IB6rVCH7XUvlBK7/QKyqypBFGv+8dj4QBFJiiRX+FG7/nkdAvGElyvVZ/HQP5N19wzteuTARXi5Gw==",
"version": "7.14.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.14.0.tgz",
"integrity": "sha512-m/xR9N4LQLmAS0ZhkY2nkPA1N7gQ5TUVa5n8TgANuDTARbn1gt+zLPXEm7W0XDTbrQ2AJSJKhoa6yx1D8BcpxQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2845,13 +2845,13 @@
}
},
"node_modules/react-router-dom": {
"version": "7.14.2",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.14.2.tgz",
"integrity": "sha512-YZcM5ES8jJSM+KrJ9BdvHHqlnGTg5tH3sC5ChFRj4inosKctdyzBDhOyyHdGk597q2OT6NTrCA1OvB/YDwfekQ==",
"version": "7.14.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.14.0.tgz",
"integrity": "sha512-2G3ajSVSZMEtmTjIklRWlNvo8wICEpLihfD/0YMDxbWK2UyP5EGfnoIn9AIQGnF3G/FX0MRbHXdFcD+rL1ZreQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"react-router": "7.14.2"
"react-router": "7.14.0"
},
"engines": {
"node": ">=20.0.0"
-1
View File
@@ -81,7 +81,6 @@ conduwuit-macros.workspace = true
conduwuit-service.workspace = true
const-str.workspace = true
ctor.workspace = true
dtor.workspace = true
futures.workspace = true
lettre.workspace = true
log.workspace = true
+14
View File
@@ -15,6 +15,10 @@ pub enum UsersCommand {
IterUsers2,
PasswordHash {
user_id: OwnedUserId,
},
ListDevices {
user_id: OwnedUserId,
},
@@ -231,6 +235,16 @@ async fn count_users(&self) -> Result {
.await
}
#[admin_command]
async fn password_hash(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now();
let result = self.services.users.password_hash(&user_id).await;
let query_time = timer.elapsed();
self.write_str(&format!("Query completed in {query_time:?}:\n\n```rs\n{result:#?}\n```"))
.await
}
#[admin_command]
async fn list_devices(&self, user_id: OwnedUserId) -> Result {
let timer = tokio::time::Instant::now();
+68 -3
View File
@@ -1,9 +1,9 @@
use api::client::leave_room;
use clap::Subcommand;
use conduwuit::{
Err, Result, debug, info,
utils::{IterStream, ReadyExt},
warn,
debug, info, utils::{IterStream, ReadyExt}, warn,
Err,
Result,
};
use futures::{FutureExt, StreamExt};
use ruma::{OwnedRoomId, OwnedRoomOrAliasId, RoomAliasId, RoomId, RoomOrAliasId};
@@ -43,6 +43,12 @@ pub enum RoomModerationCommand {
/// information
no_details: bool,
},
/// Deletes a room
Delete {
/// The room ID
room_id: OwnedRoomId,
},
}
#[admin_command]
@@ -452,3 +458,62 @@ async fn list_banned_rooms(&self, no_details: bool) -> Result {
self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```"))
.await
}
#[admin_command]
async fn delete(&self, room_id: OwnedRoomId) -> Result {
let is_banned = self.services.rooms.metadata.is_banned(&room_id).await;
let is_disabled = self.services.rooms.metadata.is_disabled(&room_id).await;
// Temporarily forcefully ban the room to prevent people trying to join while
// deletion is ongoing.
self.services.rooms.metadata.disable_room(&room_id, true);
self.services.rooms.metadata.ban_room(&room_id, true);
let mut users = self
.services
.rooms
.state_cache
.room_members(&room_id)
.ready_filter(|user| self.services.globals.user_is_local(user))
.boxed();
while let Some(ref user_id) = users.next().await {
info!("Removing {user_id} from {room_id}",);
if let Err(e) = leave_room(self.services, user_id, &room_id, None)
.boxed()
.await
{
warn!("Failed to remove {user_id} from {room_id}: {e}");
}
self.services.rooms.state_cache.forget(&room_id, user_id);
}
self.services
.rooms
.alias
.local_aliases_for_room(&room_id)
.for_each(|local_alias| async move {
info!("Removing alias {local_alias}");
self.services
.rooms
.alias
.remove_alias(&local_alias, &self.services.globals.server_user)
.await
.ok();
})
.await;
info!("Removing the room from the directory if it is present");
self.services.rooms.directory.set_not_public(&room_id);
info!("Removing lazy-loading metadata");
self.services.rooms.lazy_loading.purge(&room_id).await;
info!("Removing PDU metadata");
self.services.rooms.pdu_metadata.purge(&room_id).await;
info!("Removing state cache");
self.services.rooms.state_cache.purge(&room_id).await;
info!("Removing room state");
self.services.rooms.state.purge(&room_id).await;
Ok(())
}
+15 -9
View File
@@ -24,7 +24,6 @@ use ruma::{
tag::{TagEvent, TagEventContent, TagInfo},
},
};
use service::users::HashedPassword;
use crate::{
admin_command, get_room_info,
@@ -71,7 +70,7 @@ pub(super) async fn create_user(&self, username: String, password: Option<String
// Create user
self.services
.users
.create(&user_id, Some(HashedPassword::new(&password)?))
.create(&user_id, Some(password.as_str()), None)
.await?;
// Default to pretty displayname
@@ -144,6 +143,7 @@ pub(super) async fn create_user(&self, username: String, password: Option<String
self.services.globals.server_name().to_owned(),
room_server_name.to_owned(),
],
&None,
)
.await
{
@@ -274,13 +274,17 @@ pub(super) async fn reset_password(
let new_password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
self.services
match self
.services
.users
.set_password(&user_id, Some(HashedPassword::new(&new_password)?));
self.write_str(&format!(
"Successfully reset the password for user {user_id}: `{new_password}`"
))
.set_password(&user_id, Some(new_password.as_str()))
.await
{
| Err(e) => return Err!("Couldn't reset the password for user {user_id}: {e}"),
| Ok(()) => {
write!(self, "Successfully reset the password for user {user_id}: `{new_password}`")
},
}
.await?;
if logout {
@@ -558,6 +562,7 @@ pub(super) async fn force_join_list_of_local_users(
&room_id,
Some(String::from(BULK_JOIN_REASON)),
&servers,
&None,
)
.await
{
@@ -641,6 +646,7 @@ pub(super) async fn force_join_all_local_users(
&room_id,
Some(String::from(BULK_JOIN_REASON)),
&servers,
&None,
)
.await
{
@@ -679,7 +685,7 @@ pub(super) async fn force_join_room(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
join_room_by_id_helper(self.services, &user_id, &room_id, None, &servers).await?;
join_room_by_id_helper(self.services, &user_id, &room_id, None, &servers, &None).await?;
self.write_str(&format!("{user_id} has been joined to {room_id}."))
.await
+1 -1
View File
@@ -48,7 +48,7 @@ pub(crate) fn parse_local_user_id(services: &Services, user_id: &str) -> Result<
Ok(user_id)
}
/// Parses user ID that is an active (not deactivated) local user
/// Parses user ID that is an active (not guest or deactivated) local user
pub(crate) async fn parse_active_local_user_id(
services: &Services,
user_id: &str,
+3 -1
View File
@@ -48,6 +48,9 @@ jemalloc_stats = [
"conduwuit-core/jemalloc_stats",
"conduwuit-service/jemalloc_stats",
]
ldap = [
"conduwuit-service/ldap"
]
release_max_log_level = [
"conduwuit-core/release_max_log_level",
"conduwuit-service/release_max_log_level",
@@ -74,7 +77,6 @@ conduwuit-macros.workspace = true
conduwuit-service.workspace = true
const-str.workspace = true
ctor.workspace = true
dtor.workspace = true
futures.workspace = true
hmac.workspace = true
http.workspace = true
+14 -5
View File
@@ -24,7 +24,7 @@ use ruma::{
power_levels::RoomPowerLevelsEventContent,
},
};
use service::{mailer::messages, uiaa::Identity, users::HashedPassword};
use service::{mailer::messages, uiaa::Identity};
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH, join_room_by_id_helper};
use crate::Ruma;
@@ -150,7 +150,8 @@ pub(crate) async fn change_password_route(
services
.users
.set_password(&sender_user, Some(HashedPassword::new(&body.new_password)?));
.set_password(&sender_user, Some(&body.new_password))
.await?;
if body.logout_devices {
// Logout all devices except the current one
@@ -238,11 +239,19 @@ pub(crate) async fn request_password_change_token_via_email_route(
///
/// Note: Also works for Application Services
pub(crate) async fn whoami_route(
State(_): State<crate::State>,
State(services): State<crate::State>,
body: Ruma<whoami::v3::Request>,
) -> Result<whoami::v3::Response> {
Ok(assign!(whoami::v3::Response::new(body.sender_user().to_owned(), false), {
device_id: body.sender_device,
let is_guest = services
.users
.is_deactivated(body.sender_user())
.await
.map_err(|_| {
err!(Request(Forbidden("Application service has not registered this user.")))
})? && body.appservice_info.is_none();
Ok(assign!(whoami::v3::Response::new(body.sender_user().to_owned(), is_guest), {
device_id: body.sender_device.clone(),
}))
}
+144 -52
View File
@@ -10,11 +10,12 @@ use conduwuit::{
use conduwuit_service::Services;
use futures::{FutureExt, StreamExt};
use lettre::{Address, message::Mailbox};
use register::RegistrationKind;
use ruma::{
OwnedUserId, UserId,
api::client::{
account::{
register::{self, LoginType, RegistrationKind},
register::{self, LoginType},
request_registration_token_via_email,
},
uiaa::{AuthFlow, AuthType},
@@ -27,7 +28,7 @@ use ruma::{
push,
};
use serde_json::value::RawValue;
use service::{mailer::messages, users::HashedPassword};
use service::mailer::messages;
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH, join_room_by_id_helper};
use crate::Ruma;
@@ -41,6 +42,16 @@ const RANDOM_USER_ID_LENGTH: usize = 10;
/// You can use [`GET
/// /_matrix/client/v3/register/available`](fn.get_register_available_route.
/// html) to check if the user id is valid and available.
///
/// - Only works if registration is enabled
/// - If type is guest: ignores all parameters except
/// initial_device_display_name
/// - If sender is not appservice: Requires UIAA (but we only use a dummy stage)
/// - If type is not guest and no username is given: Always fails after UIAA
/// check
/// - Creates a new account and populates it with default account data
/// - If `inhibit_login` is false: Creates a device and returns device id and
/// access_token
#[allow(clippy::doc_markdown)]
#[tracing::instrument(skip_all, fields(%client), name = "register", level = "info")]
pub(crate) async fn register_route(
@@ -48,10 +59,7 @@ pub(crate) async fn register_route(
ClientIp(client): ClientIp,
body: Ruma<register::v3::Request>,
) -> Result<register::v3::Response> {
if body.kind != RegistrationKind::User {
return Err!(Request(GuestAccessForbidden("Guests may not register on this server.")));
}
let is_guest = body.kind == RegistrationKind::Guest;
let emergency_mode_enabled = services.config.emergency_password.is_some();
// Allow registration if it's enabled in the config file or if this is the first
@@ -60,19 +68,69 @@ pub(crate) async fn register_route(
services.config.allow_registration || services.firstrun.is_first_run();
if !allow_registration && body.appservice_info.is_none() {
info!(
?body.username,
?body.initial_device_display_name,
"Rejecting registration attempt as registration is disabled"
);
match (body.username.as_ref(), body.initial_device_display_name.as_ref()) {
| (Some(username), Some(device_display_name)) => {
info!(
%is_guest,
user = %username,
device_name = %device_display_name,
"Rejecting registration attempt as registration is disabled"
);
},
| (Some(username), _) => {
info!(
%is_guest,
user = %username,
"Rejecting registration attempt as registration is disabled"
);
},
| (_, Some(device_display_name)) => {
info!(
%is_guest,
device_name = %device_display_name,
"Rejecting registration attempt as registration is disabled"
);
},
| (None, _) => {
info!(
%is_guest,
"Rejecting registration attempt as registration is disabled"
);
},
}
return Err!(Request(Forbidden(
"This server is not accepting registrations at this time."
)));
}
let identity = if body.appservice_info.is_some() {
// Appservices can skip auth
if is_guest && !services.config.allow_guest_registration {
info!(
"Guest registration disabled, rejecting guest registration attempt, initial device \
name: \"{}\"",
body.initial_device_display_name.as_deref().unwrap_or("")
);
return Err!(Request(GuestAccessForbidden("Guest registration is disabled.")));
}
// forbid guests from registering if there is not a real admin user yet. give
// generic user error.
if is_guest && services.firstrun.is_first_run() {
warn!(
"Guest account attempted to register before a real admin user has been registered, \
rejecting registration. Guest's initial device name: \"{}\"",
body.initial_device_display_name.as_deref().unwrap_or("")
);
return Err!(Request(Forbidden(
"This server is not accepting registrations at this time."
)));
}
// Appeservices and guests get to skip auth
let skip_auth = body.appservice_info.is_some() || is_guest;
let identity = if skip_auth {
// Appservices and guests have no identity
None
} else {
// Perform UIAA to determine the user's identity
@@ -99,9 +157,13 @@ pub(crate) async fn register_route(
}
});
let user_id =
determine_registration_user_id(&services, supplied_username, emergency_mode_enabled)
.await?;
let user_id = determine_registration_user_id(
&services,
supplied_username,
is_guest,
emergency_mode_enabled,
)
.await?;
if body.body.login_type == Some(LoginType::ApplicationService) {
// For appservice logins, make sure that the user ID is in the appservice's
@@ -125,16 +187,10 @@ pub(crate) async fn register_route(
return Err!(Request(Exclusive("Username is reserved by an appservice.")));
}
let password = if body.appservice_info.is_some() {
None
} else if let Some(password) = body.password.as_deref() {
Some(HashedPassword::new(password)?)
} else {
return Err!(Request(InvalidParam("A password must be provided")));
};
let password = if is_guest { None } else { body.password.as_deref() };
// Create user
services.users.create(&user_id, password).await?;
services.users.create(&user_id, password, None).await?;
// Set an initial display name
let mut displayname = user_id.localpart().to_owned();
@@ -166,9 +222,7 @@ pub(crate) async fn register_route(
// Generate new device id if the user didn't specify one
let (token, device) = if !body.inhibit_login {
let device_id = body
.device_id
.clone()
let device_id = if is_guest { None } else { body.device_id.clone() }
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
// Generate new token for the device
@@ -209,7 +263,8 @@ pub(crate) async fn register_route(
let device_display_name = body.initial_device_display_name.as_deref().unwrap_or("");
if body.appservice_info.is_none() {
// log in conduit admin channel if a non-guest user registered
if body.appservice_info.is_none() && !is_guest {
if !device_display_name.is_empty() {
let notice = format!(
"New user \"{user_id}\" registered on this server from IP {client} and device \
@@ -230,32 +285,65 @@ pub(crate) async fn register_route(
}
}
// Make the first user to register an administrator and disable first-run mode.
let was_first_user = services.firstrun.empower_first_user(&user_id).await?;
// log in conduit admin channel if a guest registered
if body.appservice_info.is_none() && is_guest && services.config.log_guest_registrations {
debug_info!("New guest user \"{user_id}\" registered on this server.");
// If the registering user was not the first and we're suspending users on
// register, suspend them.
if !was_first_user && services.config.suspend_on_register {
// Note that we can still do auto joins for suspended users
services
.users
.suspend_account(&user_id, &services.globals.server_user)
.await;
// And send an @room notice to the admin room, to prompt admins to review the
// new user and ideally unsuspend them if deemed appropriate.
if services.server.config.admin_room_notices {
services
.admin
.send_loud_message(RoomMessageEventContent::text_plain(format!(
"User {user_id} has been suspended as they are not the first user on this \
server. Please review and unsuspend them if appropriate."
)))
.await
.ok();
if !device_display_name.is_empty() {
if services.server.config.admin_room_notices {
services
.admin
.notice(&format!(
"Guest user \"{user_id}\" with device display name \
\"{device_display_name}\" registered on this server from IP {client}"
))
.await;
}
} else {
#[allow(clippy::collapsible_else_if)]
if services.server.config.admin_room_notices {
services
.admin
.notice(&format!(
"Guest user \"{user_id}\" with no device display name registered on \
this server from IP {client}",
))
.await;
}
}
}
if body.appservice_info.is_none() && !services.server.config.auto_join_rooms.is_empty() {
if !is_guest {
// Make the first user to register an administrator and disable first-run mode.
let was_first_user = services.firstrun.empower_first_user(&user_id).await?;
// If the registering user was not the first and we're suspending users on
// register, suspend them.
if !was_first_user && services.config.suspend_on_register {
// Note that we can still do auto joins for suspended users
services
.users
.suspend_account(&user_id, &services.globals.server_user)
.await;
// And send an @room notice to the admin room, to prompt admins to review the
// new user and ideally unsuspend them if deemed appropriate.
if services.server.config.admin_room_notices {
services
.admin
.send_loud_message(RoomMessageEventContent::text_plain(format!(
"User {user_id} has been suspended as they are not the first user on \
this server. Please review and unsuspend them if appropriate."
)))
.await
.ok();
}
}
}
if body.appservice_info.is_none()
&& !services.server.config.auto_join_rooms.is_empty()
&& (services.config.allow_guests_auto_join_rooms || !is_guest)
{
for room in &services.server.config.auto_join_rooms {
let Ok(room_id) = services.rooms.alias.resolve(room).await else {
error!(
@@ -284,6 +372,7 @@ pub(crate) async fn register_route(
&room_id,
Some("Automatically joining this room upon registration".to_owned()),
&[services.globals.server_name().to_owned(), room_server_name.to_owned()],
&body.appservice_info,
)
.boxed()
.await
@@ -422,9 +511,12 @@ async fn create_registration_uiaa_session(
async fn determine_registration_user_id(
services: &Services,
supplied_username: Option<String>,
is_guest: bool,
emergency_mode_enabled: bool,
) -> Result<OwnedUserId> {
if let Some(supplied_username) = supplied_username {
if let Some(supplied_username) = supplied_username
&& !is_guest
{
// The user gets to pick their username. Do some validation to make sure it's
// acceptable.
@@ -477,7 +569,7 @@ async fn determine_registration_user_id(
Ok(user_id)
} else {
// The user didn't specify a username. Generate a username for
// The user is a guest or didn't specify a username. Generate a username for
// them.
loop {
+10
View File
@@ -122,6 +122,16 @@ pub(crate) async fn set_room_visibility_route(
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
if services
.users
.is_deactivated(sender_user)
.await
.unwrap_or(false)
&& body.appservice_info.is_none()
{
return Err!(Request(Forbidden("Guests cannot publish to room directories")));
}
if !user_can_publish_room(&services, sender_user, &body.room_id).await? {
return Err!(Request(Forbidden("User is not allowed to publish this room")));
}
-21
View File
@@ -64,27 +64,6 @@ pub(crate) async fn upload_keys_route(
.await?;
}
for (key_id, fallback_key) in &body.fallback_keys {
if fallback_key
.deserialize()
.inspect_err(|e| {
debug_warn!(
%key_id,
?fallback_key,
"Invalid one time key JSON submitted by client, skipping: {e}"
);
})
.is_err()
{
continue;
}
services
.users
.add_fallback_key(sender_user, sender_device, key_id, fallback_key, false)
.await?;
}
if let Some(device_keys) = &body.device_keys {
let deser_device_keys = device_keys.deserialize().map_err(|e| {
err!(Request(BadJson(debug_warn!(
+3 -2
View File
@@ -118,8 +118,9 @@ pub(crate) async fn get_content_thumbnail_route(
} = match fetch_thumbnail_meta(&services, &mxc, user, body.timeout_ms, &dim).await {
| Ok(meta) => meta,
| Err(conduwuit::Error::Io(e)) => match e.kind() {
| std::io::ErrorKind::NotFound =>
return Err!(Request(NotFound("Thumbnail not found."))),
| std::io::ErrorKind::NotFound => {
return Err!(Request(NotFound("Thumbnail not found.")));
},
| std::io::ErrorKind::PermissionDenied => {
error!("Permission denied when trying to read file: {e:?}");
return Err!(Request(Unknown("Unknown error when fetching thumbnail.")));
+1 -5
View File
@@ -163,11 +163,7 @@ pub(crate) async fn invite_helper(
)
.await?;
let invite_room_state = services
.rooms
.state
.summary_stripped(&pdu, room_id, recipient_user)
.await;
let invite_room_state = services.rooms.state.summary_stripped(&pdu, room_id).await;
drop(state_lock);
+34 -7
View File
@@ -39,6 +39,7 @@ use ruma::{
};
use service::{
Services,
appservice::RegistrationInfo,
rooms::{
state::RoomMutexGuard,
state_compressor::{CompressedState, HashSetCompressStateEvent},
@@ -111,9 +112,16 @@ pub(crate) async fn join_room_by_id_route(
shuffle(&mut servers);
let servers = deprioritize(servers, &services.config.deprioritize_joins_through_servers);
join_room_by_id_helper(&services, sender_user, &body.room_id, body.reason.clone(), &servers)
.boxed()
.await
join_room_by_id_helper(
&services,
sender_user,
&body.room_id,
body.reason.clone(),
&servers,
&body.appservice_info,
)
.boxed()
.await
}
/// # `POST /_matrix/client/r0/join/{roomIdOrAlias}`
@@ -132,6 +140,7 @@ pub(crate) async fn join_room_by_id_or_alias_route(
body: Ruma<join_room_by_id_or_alias::v3::Request>,
) -> Result<join_room_by_id_or_alias::v3::Response> {
let sender_user = body.sender_user();
let appservice_info = &body.appservice_info;
let body = &body.body;
if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
@@ -226,10 +235,16 @@ pub(crate) async fn join_room_by_id_or_alias_route(
};
let servers = deprioritize(servers, &services.config.deprioritize_joins_through_servers);
let join_room_response =
join_room_by_id_helper(&services, sender_user, &room_id, body.reason.clone(), &servers)
.boxed()
.await?;
let join_room_response = join_room_by_id_helper(
&services,
sender_user,
&room_id,
body.reason.clone(),
&servers,
appservice_info,
)
.boxed()
.await?;
Ok(join_room_by_id_or_alias::v3::Response::new(join_room_response.room_id))
}
@@ -240,9 +255,21 @@ pub async fn join_room_by_id_helper(
room_id: &RoomId,
reason: Option<String>,
servers: &[OwnedServerName],
appservice_info: &Option<RegistrationInfo>,
) -> Result<join_room_by_id::v3::Response> {
let state_lock = services.rooms.state.mutex.lock(room_id).await;
let user_is_guest = services
.users
.is_deactivated(sender_user)
.await
.unwrap_or(false)
&& appservice_info.is_none();
if user_is_guest && !services.rooms.state_accessor.guest_can_join(room_id).await {
return Err!(Request(Forbidden("Guests are not allowed to join this room")));
}
if services
.rooms
.state_cache
+9 -2
View File
@@ -238,8 +238,15 @@ async fn knock_room_by_id_helper(
// join_room_by_id_helper We need to release the lock here and let
// join_room_by_id_helper acquire it again
drop(state_lock);
match join_room_by_id_helper(services, sender_user, room_id, reason.clone(), servers)
.await
match join_room_by_id_helper(
services,
sender_user,
room_id,
reason.clone(),
servers,
&None,
)
.await
{
| Ok(_) => return Ok(knock_room::v3::Response::new(room_id.to_owned())),
| Err(e) => {
+130 -3
View File
@@ -4,9 +4,10 @@ use axum::extract::State;
use axum_client_ip::ClientIp;
use conduwuit::{
Err, Result, debug, err, info,
utils::{self, ReadyExt, stream::BroadbandExt},
utils::{self, ReadyExt, hash, stream::BroadbandExt},
warn,
};
use conduwuit_core::{debug_error, debug_warn};
use conduwuit_service::Services;
use futures::StreamExt;
use lettre::Address;
@@ -53,6 +54,113 @@ pub(crate) async fn get_login_types_route(
]))
}
/// Authenticates the given user by its ID and its password.
///
/// Returns the user ID if successful, and an error otherwise.
#[tracing::instrument(skip_all, fields(%user_id), name = "password", level = "debug")]
pub(crate) async fn password_login(
services: &Services,
user_id: &UserId,
lowercased_user_id: &UserId,
password: &str,
) -> Result<OwnedUserId> {
// Restrict login to accounts only of type 'password', including untyped
// legacy accounts which are equivalent to 'password'.
if services
.users
.origin(user_id)
.await
.is_ok_and(|origin| origin != "password")
{
return Err!(Request(Forbidden("Account does not permit password login.")));
}
let (hash, user_id) = match services.users.password_hash(user_id).await {
| Ok(hash) => (hash, user_id),
| Err(_) => services
.users
.password_hash(lowercased_user_id)
.await
.map(|hash| (hash, lowercased_user_id))
.map_err(|_| err!(Request(Forbidden("Invalid identifier or password."))))?,
};
if hash.is_empty() {
return Err!(Request(UserDeactivated("The user has been deactivated")));
}
hash::verify_password(password, &hash)
.inspect_err(|e| debug_error!("{e}"))
.map_err(|_| err!(Request(Forbidden("Invalid identifier or password."))))?;
Ok(user_id.to_owned())
}
/// Authenticates the given user through the configured LDAP server.
///
/// Creates the user if the user is found in the LDAP and do not already have an
/// account.
#[tracing::instrument(skip_all, fields(%user_id), name = "ldap", level = "debug")]
pub(super) async fn ldap_login(
services: &Services,
user_id: &UserId,
lowercased_user_id: &UserId,
password: &str,
) -> Result<OwnedUserId> {
let (user_dn, is_ldap_admin) = match services.config.ldap.bind_dn.as_ref() {
| Some(bind_dn) if bind_dn.contains("{username}") =>
(bind_dn.replace("{username}", lowercased_user_id.localpart()), None),
| _ => {
debug!("Searching user in LDAP");
let dns = services.users.search_ldap(user_id).await?;
if dns.len() >= 2 {
return Err!(Ldap("LDAP search returned two or more results"));
}
let Some((user_dn, is_admin)) = dns.first() else {
return password_login(services, user_id, lowercased_user_id, password).await;
};
(user_dn.clone(), *is_admin)
},
};
let user_id = services
.users
.auth_ldap(&user_dn, password)
.await
.map(|()| lowercased_user_id.to_owned())?;
// LDAP users are automatically created on first login attempt. This is a very
// common feature that can be seen on many services using a LDAP provider for
// their users (synapse, Nextcloud, Jellyfin, ...).
//
// LDAP users are crated with a dummy password but non empty because an empty
// password is reserved for deactivated accounts. The conduwuit password field
// will never be read to login a LDAP user so it's not an issue.
if !services.users.exists(lowercased_user_id).await {
services
.users
.create(lowercased_user_id, Some("*"), Some("ldap"))
.await?;
}
// Only sync admin status if LDAP can actually determine it.
// None means LDAP cannot determine admin status (manual config required).
if let Some(is_ldap_admin) = is_ldap_admin {
let is_conduwuit_admin = services.admin.user_is_admin(lowercased_user_id).await;
if is_ldap_admin && !is_conduwuit_admin {
Box::pin(services.admin.make_user_admin(lowercased_user_id)).await?;
} else if !is_ldap_admin && is_conduwuit_admin {
Box::pin(services.admin.revoke_admin(lowercased_user_id)).await?;
}
}
Ok(user_id)
}
pub(crate) async fn handle_login(
services: &Services,
identifier: Option<&UserIdentifier>,
@@ -83,7 +191,15 @@ pub(crate) async fn handle_login(
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name)
.map_err(|_| err!(Request(InvalidUsername("User ID is malformed"))))?;
if !services.globals.user_is_local(&user_id) {
let lowercased_user_id = UserId::parse_with_server_name(
user_id.localpart().to_lowercase(),
&services.config.server_name,
)
.unwrap();
if !services.globals.user_is_local(&user_id)
|| !services.globals.user_is_local(&lowercased_user_id)
{
return Err!(Request(InvalidParam("User ID does not belong to this homeserver")));
}
@@ -96,7 +212,18 @@ pub(crate) async fn handle_login(
return Err!(Request(Forbidden("This account is not permitted to log in.")));
}
services.users.check_password(&user_id, password).await
if cfg!(feature = "ldap") && services.config.ldap.enable {
match Box::pin(ldap_login(services, &user_id, &lowercased_user_id, password)).await {
| Ok(user_id) => Ok(user_id),
| Err(err) if services.config.ldap.ldap_only => Err(err),
| Err(err) => {
debug_warn!("{err}");
password_login(services, &user_id, &lowercased_user_id, password).await
},
}
} else {
password_login(services, &user_id, &lowercased_user_id, password).await
}
}
/// # `POST /_matrix/client/v3/login`
+3 -2
View File
@@ -375,7 +375,7 @@ async fn allowed_to_send_state_event(
},
}
},
| StateEventType::RoomMember =>
| StateEventType::RoomMember => {
match json.deserialize_as_unchecked::<RoomMemberEventContent>() {
| Ok(mut membership_content) => {
let Ok(state_key) = UserId::parse(state_key) else {
@@ -434,7 +434,8 @@ async fn allowed_to_send_state_event(
membership state: {e}"
)));
},
},
}
},
| _ => (),
}
+3 -8
View File
@@ -395,10 +395,6 @@ pub(crate) async fn build_sync_events(
.users
.count_one_time_keys(syncing_user, syncing_device);
let unused_fallback_key_types = services
.users
.list_unused_fallback_key_types(syncing_user, syncing_device);
let (
(joined_rooms, mut device_list_updates),
left_rooms,
@@ -409,7 +405,6 @@ pub(crate) async fn build_sync_events(
to_device_events,
keys_changed,
device_one_time_keys_count,
unused_fallback_key_types,
) = async {
futures::join!(
joined_rooms,
@@ -420,8 +415,7 @@ pub(crate) async fn build_sync_events(
account_data,
to_device_events,
keys_changed,
device_one_time_keys_count,
unused_fallback_key_types,
device_one_time_keys_count
)
}
.boxed()
@@ -439,7 +433,8 @@ pub(crate) async fn build_sync_events(
account_data: assign!(GlobalAccountData::new(), { events: account_data }),
device_lists: device_list_updates.into(),
device_one_time_keys_count,
device_unused_fallback_key_types: Some(unused_fallback_key_types),
// Fallback keys are not yet supported
device_unused_fallback_key_types: None,
presence: assign!(Presence::new(), {
events: presence_updates
.into_iter()
+1 -1
View File
@@ -80,7 +80,7 @@ pub(crate) async fn conduwuit_server_version() -> Result<impl IntoResponse> {
///
/// conduwuit-specific API to return the amount of users registered on this
/// homeserver. Endpoint is disabled if federation is disabled for privacy. This
/// only includes active users (not deactivated, etc)
/// only includes active users (not deactivated, no guests, etc)
pub(crate) async fn conduwuit_local_user_count(
State(services): State<crate::State>,
) -> Result<impl IntoResponse> {
+3 -2
View File
@@ -19,10 +19,11 @@ pub(crate) async fn well_known_client(
) -> Result<discover_homeserver::Response> {
let client_url = match services.config.well_known.client.as_ref() {
| Some(url) => url.to_string(),
| None =>
| None => {
return Err!(Request(NotFound(
"This server is not configured to serve well-known client information."
))),
)));
},
};
Ok(assign!(discover_homeserver::Response::new(HomeserverInfo::new(client_url)), {
+3 -2
View File
@@ -89,8 +89,9 @@ impl CheckAuth for ServerSignatures {
origin: Some(output.origin.clone()),
..Default::default()
}),
| Err(err) =>
Err!(Request(Unauthorized(warn!("Failed to verify X-Matrix header: {err}")))),
| Err(err) => {
Err!(Request(Unauthorized(warn!("Failed to verify X-Matrix header: {err}"))))
},
}
}
}
+3 -2
View File
@@ -252,7 +252,7 @@ pub(crate) async fn user_can_perform_restricted_join(
return Ok(true);
}
},
| other if other.rule_type() == "fi.mau.spam_checker" =>
| other if other.rule_type() == "fi.mau.spam_checker" => {
return match services
.antispam
.meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned())
@@ -260,7 +260,8 @@ pub(crate) async fn user_can_perform_restricted_join(
{
| Ok(()) => Ok(true),
| Err(_) => Err!(Request(Forbidden("Antispam rejected join request."))),
},
};
},
| _ => {
// We don't recognise this join rule, so we cannot satisfy the request.
could_satisfy = false;
+1 -1
View File
@@ -183,7 +183,7 @@ pub(crate) async fn create_knock_event_v1_route(
let knock_room_state = services
.rooms
.state
.summary_stripped(&pdu, &body.room_id, &sender)
.summary_stripped(&pdu, &body.room_id)
.await;
Ok(create_knock_event::v1::Response::new(knock_room_state))
-1
View File
@@ -70,7 +70,6 @@ conduwuit-build-metadata.workspace = true
const-str.workspace = true
core_affinity.workspace = true
ctor.workspace = true
dtor.workspace = true
cyborgtime.workspace = true
either.workspace = true
figment.workspace = true
+1 -1
View File
@@ -47,7 +47,7 @@ type Key = ArrayVec<usize, KEY_SEGS>;
const NAME_MAX: usize = 128;
const KEY_SEGS: usize = 8;
#[ctor::ctor(unsafe)]
#[ctor::ctor]
fn _static_initialization() {
acq_epoch().expect("pre-initialization of jemalloc failed");
acq_epoch().expect("pre-initialization of jemalloc failed");
+145 -1
View File
@@ -371,7 +371,6 @@ pub struct Config {
pub ip_lookup_strategy: u8,
/// Max request size for file uploads in bytes. Defaults to 20MB.
/// Also limits incoming federated media.
///
/// default: 20971520
#[serde(default = "default_max_request_size")]
@@ -1486,6 +1485,21 @@ pub struct Config {
#[serde(default)]
pub brotli_compression: bool,
/// Set to true to allow user type "guest" registrations. Some clients like
/// Element attempt to register guest users automatically.
#[serde(default)]
pub allow_guest_registration: bool,
/// Set to true to log guest registrations in the admin room. Note that
/// these may be noisy or unnecessary if you're a public homeserver.
#[serde(default)]
pub log_guest_registrations: bool,
/// Set to true to allow guest registrations/users to auto join any rooms
/// specified in `auto_join_rooms`.
#[serde(default)]
pub allow_guests_auto_join_rooms: bool,
/// Enable the legacy unauthenticated Matrix media repository endpoints.
/// These endpoints consist of:
/// - /_matrix/media/*/config
@@ -2115,6 +2129,10 @@ pub struct Config {
#[serde(default)]
pub allow_web_indexing: bool,
/// display: nested
#[serde(default)]
pub ldap: LdapConfig,
/// Configuration for antispam support
/// display: nested
#[serde(default)]
@@ -2276,6 +2294,126 @@ impl MatrixRtcConfig {
}
}
#[derive(Clone, Debug, Default, Deserialize)]
#[config_example_generator(filename = "conduwuit-example.toml", section = "global.ldap")]
pub struct LdapConfig {
/// Whether to enable LDAP login.
///
/// example: "true"
#[serde(default)]
pub enable: bool,
/// Whether to force LDAP authentication or authorize classical password
/// login.
///
/// example: "true"
#[serde(default)]
pub ldap_only: bool,
/// URI of the LDAP server.
///
/// example: "ldap://ldap.example.com:389"
///
/// default: ""
#[serde(default)]
pub uri: Option<Url>,
/// StartTLS for LDAP connections.
///
/// default: false
#[serde(default)]
pub use_starttls: bool,
/// Skip TLS certificate verification, possibly dangerous.
///
/// default: false
#[serde(default)]
pub disable_tls_verification: bool,
/// Root of the searches.
///
/// example: "ou=users,dc=example,dc=org"
///
/// default: ""
#[serde(default)]
pub base_dn: String,
/// Bind DN if anonymous search is not enabled.
///
/// You can use the variable `{username}` that will be replaced by the
/// entered username. In such case, the password used to bind will be the
/// one provided for the login and not the one given by
/// `bind_password_file`. Beware: automatically granting admin rights will
/// not work if you use this direct bind instead of a LDAP search.
///
/// example: "cn=ldap-reader,dc=example,dc=org" or
/// "cn={username},ou=users,dc=example,dc=org"
///
/// default: ""
#[serde(default)]
pub bind_dn: Option<String>,
/// Path to a file on the system that contains the password for the
/// `bind_dn`.
///
/// The server must be able to access the file, and it must not be empty.
///
/// default: ""
#[serde(default)]
pub bind_password_file: Option<PathBuf>,
/// Search filter to limit user searches.
///
/// You can use the variable `{username}` that will be replaced by the
/// entered username for more complex filters.
///
/// example: "(&(objectClass=person)(memberOf=matrix))"
///
/// default: "(objectClass=*)"
#[serde(default = "default_ldap_search_filter")]
pub filter: String,
/// Attribute to use to uniquely identify the user.
///
/// example: "uid" or "cn"
///
/// default: "uid"
#[serde(default = "default_ldap_uid_attribute")]
pub uid_attribute: String,
/// Attribute containing the display name of the user.
///
/// example: "givenName" or "sn"
///
/// default: "givenName"
#[serde(default = "default_ldap_name_attribute")]
pub name_attribute: String,
/// Root of the searches for admin users.
///
/// Defaults to `base_dn` if empty.
///
/// example: "ou=admins,dc=example,dc=org"
///
/// default: ""
#[serde(default)]
pub admin_base_dn: String,
/// The LDAP search filter to find administrative users for continuwuity.
///
/// If left blank, administrative state must be configured manually for each
/// user.
///
/// You can use the variable `{username}` that will be replaced by the
/// entered username for more complex filters.
///
/// example: "(objectClass=conduwuitAdmin)" or "(uid={username})"
///
/// default: ""
#[serde(default)]
pub admin_filter: String,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(transparent)]
struct ListeningPort {
@@ -2796,3 +2934,9 @@ pub(super) fn default_blurhash_x_component() -> u32 { 4 }
pub(super) fn default_blurhash_y_component() -> u32 { 3 }
// end recommended & blurhashing defaults
fn default_ldap_search_filter() -> String { "(objectClass=*)".to_owned() }
fn default_ldap_uid_attribute() -> String { String::from("uid") }
fn default_ldap_name_attribute() -> String { String::from("givenName") }
+1 -1
View File
@@ -62,7 +62,7 @@ pub const INFO_SPAN_LEVEL: Level = if cfg!(debug_assertions) {
pub static DEBUGGER: LazyLock<bool> =
LazyLock::new(|| env::var("_").unwrap_or_default().ends_with("gdb"));
#[cfg_attr(debug_assertions, ctor::ctor(unsafe))]
#[cfg_attr(debug_assertions, ctor::ctor)]
#[cfg_attr(not(debug_assertions), allow(dead_code))]
fn set_panic_trap() {
if !*DEBUGGER {
+2
View File
@@ -110,6 +110,8 @@ pub enum Error {
InconsistentRoomState(&'static str, ruma::OwnedRoomId),
#[error(transparent)]
IntoHttp(#[from] ruma::api::error::IntoHttpError),
#[error("{0}")]
Ldap(Cow<'static, str>),
#[error(transparent)]
Mxc(#[from] ruma::MxcUriError),
#[error(transparent)]
-1
View File
@@ -58,7 +58,6 @@ conduwuit-core.workspace = true
conduwuit-macros.workspace = true
const-str.workspace = true
ctor.workspace = true
dtor.workspace = true
futures.workspace = true
log.workspace = true
minicbor.workspace = true
+2 -8
View File
@@ -288,14 +288,8 @@ impl<'a, 'de: 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
}
#[cfg_attr(unabridged, tracing::instrument(level = "trace", skip_all))]
fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
let byte = self
.buf
.get(self.pos)
.ok_or(Self::Error::SerdeDe("bool buffer underflow".into()))?;
self.inc_pos(1);
visitor.visit_bool(*byte != 0x00)
fn deserialize_bool<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value> {
unhandled!("deserialize bool not implemented")
}
#[cfg_attr(unabridged, tracing::instrument(level = "trace", skip_all))]
-4
View File
@@ -120,10 +120,6 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "onetimekeyid_onetimekeys",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "fallbackkeyid_fallbackkey",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "passwordresettoken_info",
..descriptor::RANDOM_SMALL
+2 -2
View File
@@ -297,8 +297,8 @@ impl<W: Write> ser::Serializer for &mut Serializer<'_, W> {
fn serialize_u8(self, v: u8) -> Result<Self::Ok> { self.write(&[v]) }
fn serialize_bool(self, v: bool) -> Result<Self::Ok> {
if v { self.write(&[0x01]) } else { self.write(&[0x00]) }
fn serialize_bool(self, _v: bool) -> Result<Self::Ok> {
unhandled!("serialize bool not implemented")
}
fn serialize_unit(self) -> Result<Self::Ok> { unhandled!("serialize unit not implemented") }
+2 -2
View File
@@ -32,11 +32,11 @@ pub(super) fn introspect(_args: TokenStream) -> Result<TokenStream> {
const CRATE_NAME: &str = #crate_name;
/// Register this crate's features with the global registry during static initialization
#[::ctor::ctor(unsafe)]
#[::ctor::ctor]
fn register() {
conduwuit_core::info::introspection::ENABLED_FEATURES.lock().unwrap().insert(#crate_name, &ENABLED);
}
#[::dtor::dtor(unsafe)]
#[::ctor::dtor]
fn unregister() {
conduwuit_core::info::introspection::ENABLED_FEATURES.lock().unwrap().remove(#crate_name);
}
+4 -1
View File
@@ -55,6 +55,7 @@ standard = [
"jemalloc",
"jemalloc_conf",
"journald",
"ldap",
"media_thumbnail",
"systemd",
"url_preview",
@@ -125,6 +126,9 @@ jemalloc_stats = [
jemalloc_conf = [
"conduwuit-core/jemalloc_conf",
]
ldap = [
"conduwuit-api/ldap",
]
media_thumbnail = [
"conduwuit-service/media_thumbnail",
]
@@ -213,7 +217,6 @@ conduwuit-macros.workspace = true
clap.workspace = true
ctor.workspace = true
dtor.workspace = true
console-subscriber.optional = true
console-subscriber.workspace = true
const-str.workspace = true
-1
View File
@@ -105,7 +105,6 @@ conduwuit-service.workspace = true
conduwuit-web.workspace = true
const-str.workspace = true
ctor.workspace = true
dtor.workspace = true
futures.workspace = true
http.workspace = true
http-body-util.workspace = true
+5 -1
View File
@@ -52,6 +52,9 @@ jemalloc_stats = [
"conduwuit-core/jemalloc_stats",
"conduwuit-database/jemalloc_stats",
]
ldap = [
"dep:ldap3"
]
media_thumbnail = [
"dep:image",
]
@@ -86,7 +89,6 @@ conduwuit-database.workspace = true
conduwuit-macros.workspace = true
const-str.workspace = true
ctor.workspace = true
dtor.workspace = true
either.workspace = true
futures.workspace = true
governor.workspace = true
@@ -96,6 +98,8 @@ image.workspace = true
image.optional = true
ipaddress.workspace = true
itertools.workspace = true
ldap3.workspace = true
ldap3.optional = true
log.workspace = true
loole.workspace = true
lru-cache.workspace = true
+5 -2
View File
@@ -37,7 +37,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
// Create a user for the server
let server_user = services.globals.server_user.as_ref();
services.users.create(server_user, None).await?;
services.users.create(server_user, None, None).await?;
let mut create_content = {
use RoomVersionId::*;
@@ -160,7 +160,10 @@ pub async fn create_admin_room(services: &Services) -> Result {
.boxed()
.await?;
let room_topic = format!("Manage {} | Run commands prefixed with `!admin` | Run `!admin -h` for help | Documentation: https://continuwuity.org/", services.config.server_name);
let room_topic = format!(
"Manage {} | Run commands prefixed with `!admin` | Run `!admin -h` for help | Documentation: https://continuwuity.org/",
services.config.server_name
);
services
.rooms
.timeline
+5 -2
View File
@@ -111,7 +111,7 @@ impl Service {
if !self.services.users.exists(&appservice_user_id).await {
self.services
.users
.create(&appservice_user_id, None)
.create(&appservice_user_id, None, None)
.await?;
} else if self
.services
@@ -121,7 +121,10 @@ impl Service {
.unwrap_or(false)
{
// Reactivate the appservice user if it was accidentally deactivated
self.services.users.set_password(&appservice_user_id, None);
self.services
.users
.set_password(&appservice_user_id, None)
.await?;
}
self.registration_info
+10 -13
View File
@@ -9,10 +9,7 @@ use ruma::{
push::Ruleset,
};
use crate::{
Dep, account_data, config, globals,
users::{self, HashedPassword},
};
use crate::{Dep, account_data, config, globals, users};
pub struct Service {
services: Services,
@@ -40,6 +37,11 @@ impl crate::Service for Service {
}
async fn worker(self: Arc<Self>) -> Result {
if self.services.config.ldap.enable {
warn!("emergency password feature not available with LDAP enabled.");
return Ok(());
}
self.set_emergency_access().await.inspect_err(|e| {
error!("Could not set the configured emergency password for the server user: {e}");
})
@@ -54,15 +56,10 @@ impl Service {
async fn set_emergency_access(&self) -> Result {
let server_user = &self.services.globals.server_user;
self.services.users.set_password(
server_user,
self.services
.config
.emergency_password
.as_deref()
.map(HashedPassword::new)
.transpose()?,
);
self.services
.users
.set_password(server_user, self.services.config.emergency_password.as_deref())
.await?;
let (ruleset, pwd_set) = match self.services.config.emergency_password {
| Some(_) => (Ruleset::server_default(server_user), true),
+3 -1
View File
@@ -312,7 +312,9 @@ impl Service {
to open the console."
);
}
eprintln!("If you need assistance setting up your homeserver, make a Matrix account on another homeserver and join our chatroom: https://matrix.to/#/#continuwuity:continuwuity.org");
eprintln!(
"If you need assistance setting up your homeserver, make a Matrix account on another homeserver and join our chatroom: https://matrix.to/#/#continuwuity:continuwuity.org"
);
eprintln!("{}", "============".bold());
}
+1 -1
View File
@@ -802,7 +802,7 @@ async fn fix_local_invite_state(services: &Services) -> Result {
&& services.globals.user_is_local(&membership_event.sender) {
// build and save stripped state for their invite in the database
let stripped_state = services.rooms.state.summary_stripped(&membership_event, &room_id, &user_id).await;
let stripped_state = services.rooms.state.summary_stripped(&membership_event, &room_id).await;
userroomid_invitestate.put((&user_id, &room_id), Json(stripped_state));
fixed = fixed.saturating_add(1);
}
+14 -5
View File
@@ -6,10 +6,7 @@ use conduwuit::{Err, Result, utils};
use data::{Data, ResetTokenInfo};
use ruma::OwnedUserId;
use crate::{
Dep, globals,
users::{self, HashedPassword},
};
use crate::{Dep, globals, users};
pub const PASSWORD_RESET_PATH: &str = "/_continuwuity/account/reset_password";
pub const RESET_TOKEN_QUERY_PARAM: &str = "token";
@@ -61,6 +58,17 @@ impl Service {
return Err!("Cannot issue a password reset token for the server user");
}
if self
.services
.users
.origin(&user_id)
.await
.unwrap_or_else(|_| "password".to_owned())
!= "password"
{
return Err!("Cannot issue a password reset token for non-internal user {user_id}");
}
if self.services.users.is_deactivated(&user_id).await? {
return Err!("Cannot issue a password reset token for deactivated user {user_id}");
}
@@ -103,7 +111,8 @@ impl Service {
self.db.remove_token(&token);
self.services
.users
.set_password(&info.user, Some(HashedPassword::new(new_password)?));
.set_password(&info.user, Some(new_password))
.await?;
}
Ok(())
+11
View File
@@ -67,6 +67,17 @@ pub async fn reset(&self, ctx: &Context<'_>) {
.await;
}
#[implement(Service)]
pub async fn purge(&self, room_id: &RoomId) {
let prefix = (Interfix, Interfix, room_id, Interfix);
self.db
.lazyloadedids
.keys_prefix_raw(&prefix)
.ignore_err()
.ready_for_each(|key| self.db.lazyloadedids.remove(key))
.await;
}
/// Returns only the subset of `senders` which should be sent to the client
/// according to the provided lazy loading context.
#[implement(Service)]
+15 -1
View File
@@ -9,7 +9,7 @@ use conduwuit::{
u64_from_u8,
},
};
use database::Map;
use database::{Interfix, Map};
use futures::{Stream, StreamExt};
use ruma::{EventId, RoomId, UserId, api::Direction};
@@ -46,6 +46,16 @@ impl Data {
}
}
pub(super) async fn purge(&self, room_id: &RoomId) {
// NOTE: This does not remove soft-failed event references, that must be done
// somewhere else.
self.referencedevents
.keys_prefix_raw(&(room_id, Interfix))
.ignore_err()
.ready_for_each(|key| self.referencedevents.remove(key))
.await;
}
pub(super) fn add_relation(&self, from: u64, to: u64) {
const BUFSIZE: usize = size_of::<u64>() * 2;
@@ -121,4 +131,8 @@ impl Data {
pub(super) async fn is_event_soft_failed(&self, event_id: &EventId) -> bool {
self.softfailedeventids.get(event_id).await.is_ok()
}
pub(super) async fn remove_soft_fail_marker(&self, event_id: &EventId) {
self.softfailedeventids.remove(event_id);
}
}
+6
View File
@@ -140,4 +140,10 @@ impl Service {
pub async fn is_event_soft_failed(&self, event_id: &EventId) -> bool {
self.db.is_event_soft_failed(event_id).await
}
pub async fn purge(&self, room_id: &RoomId) { self.db.purge(room_id).await; }
pub async fn remove_soft_fail_marker(&self, event_id: &EventId) {
self.db.remove_soft_fail_marker(event_id).await;
}
}
+8
View File
@@ -115,4 +115,12 @@ impl Data {
.deserialized()
.unwrap_or(0)
}
pub(super) async fn purge(&self, room_id: &RoomId) {
self.readreceiptid_readreceipt
.keys_prefix_raw(room_id)
.ignore_err()
.ready_for_each(|key| self.readreceiptid_readreceipt.remove(key))
.await;
}
}
+2
View File
@@ -142,6 +142,8 @@ impl Service {
pub async fn last_privateread_update(&self, user_id: &UserId, room_id: &RoomId) -> u64 {
self.db.last_privateread_update(user_id, room_id).await
}
pub async fn purge(&self, room_id: &RoomId) { self.db.purge(room_id).await }
}
#[must_use]
+36 -23
View File
@@ -3,32 +3,32 @@ use std::{collections::HashMap, fmt::Write, sync::Arc};
use async_trait::async_trait;
use conduwuit::debug;
use conduwuit_core::{
Event, PduEvent, Result, err,
result::FlatOk,
state_res::{self, StateMap},
utils::{
IterStream, MutexMap, MutexMapGuard, ReadyExt, calculate_hash,
stream::{BroadbandExt, TryIgnore},
err, result::FlatOk, state_res::{self, StateMap}, utils::{
calculate_hash, stream::{BroadbandExt, TryIgnore}, IterStream, MutexMap, MutexMapGuard,
ReadyExt,
},
warn,
Event,
PduEvent,
Result,
};
use conduwuit_database::{Deserialized, Ignore, Interfix, Map};
use futures::{
FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::join_all, pin_mut,
future::join_all, pin_mut, FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt,
};
use ruma::{
EventId, OwnedEventId, OwnedRoomId, RoomId, RoomVersionId, UserId,
api::federation::membership::RawStrippedState,
events::{StateEventType, TimelineEventType, room::create::RoomCreateEventContent},
room_version_rules::RoomVersionRules,
api::federation::membership::RawStrippedState, events::{room::create::RoomCreateEventContent, StateEventType, TimelineEventType}, room_version_rules::RoomVersionRules, EventId, OwnedEventId, OwnedRoomId,
RoomId,
RoomVersionId,
UserId,
};
use crate::{
Dep, globals, rooms,
rooms::{
globals, rooms, rooms::{
short::{ShortEventId, ShortStateHash},
state_compressor::{CompressedState, parse_compressed_state_event},
state_compressor::{parse_compressed_state_event, CompressedState},
},
Dep,
};
pub struct Service {
@@ -89,6 +89,25 @@ impl crate::Service for Service {
}
impl Service {
pub async fn purge(&self, room_id: &RoomId) {
self.db.roomid_pduleaves
.keys_prefix_raw(room_id)
.ignore_err()
.ready_for_each(|k| self.db.roomid_pduleaves.remove(k))
.await;
let mut shortstatehashes = self.db.roomid_shortstatehash
.keys_prefix_raw(room_id)
.ignore_err();
while let Some(key) = shortstatehashes.next().await {
self.db.shorteventid_shortstatehash
.keys_prefix_raw(&(Interfix, key))
.ignore_err()
.ready_for_each(|key| self.db.shorteventid_shortstatehash.remove(key))
.await;
self.db.roomid_shortstatehash.remove(key);
};
}
/// Set the room to the given statehash and update caches.
pub async fn force_state(
&self,
@@ -300,13 +319,12 @@ impl Service {
&self,
event: &'a E,
room_id: &RoomId,
target_user: &UserId,
) -> Vec<RawStrippedState>
where
E: Event + Send + Sync,
&'a E: Event + Send,
{
let mut state_events = [
let cells = [
(&StateEventType::RoomCreate, ""),
(&StateEventType::RoomJoinRules, ""),
(&StateEventType::RoomCanonicalAlias, ""),
@@ -315,14 +333,9 @@ impl Service {
(&StateEventType::RoomMember, event.sender().as_str()), // Add recommended events
(&StateEventType::RoomEncryption, ""),
(&StateEventType::RoomTopic, ""),
]
.to_vec();
];
if target_user != event.sender() {
state_events.push((&StateEventType::RoomMember, target_user.as_str()));
}
let fetches = state_events.into_iter().map(|(event_type, state_key)| {
let fetches = cells.into_iter().map(|(event_type, state_key)| {
self.services
.state_accessor
.room_state_get(room_id, event_type, state_key)
+96 -11
View File
@@ -4,20 +4,21 @@ mod via;
use std::{collections::HashMap, sync::Arc};
use conduwuit::{
Pdu, Result, SyncRwLock, implement,
result::LogErr,
utils::{ReadyExt, stream::TryIgnore},
warn,
implement, result::LogErr, utils::{stream::TryIgnore, ReadyExt}, warn,
Pdu,
Result,
SyncRwLock,
};
use database::{Deserialized, Ignore, Interfix, Map};
use futures::{Stream, StreamExt, future::join5, pin_mut};
use futures::{future::join5, pin_mut, Stream, StreamExt};
use ruma::{
OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, ServerName, UserId,
events::{AnyStrippedStateEvent, room::member::MembershipState},
serde::Raw,
events::{room::member::MembershipState, AnyStrippedStateEvent}, serde::Raw, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId,
ServerName,
UserId,
};
use tokio::join;
use crate::{Dep, account_data, appservice::RegistrationInfo, config, globals, rooms, users};
use crate::{account_data, appservice::RegistrationInfo, config, globals, rooms, users, Dep};
pub struct Service {
appservice_in_room_cache: AppServiceInRoomCache,
@@ -93,6 +94,90 @@ impl crate::Service for Service {
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
}
#[implement(Service)]
#[tracing::instrument(skip(self))]
pub async fn purge(&self, room_id: &RoomId) {
let roomuser_key = (room_id, Interfix);
let userroom_key = (Interfix, room_id);
join!(
self.db
.roomid_invitedcount
.keys_prefix_raw(room_id)
.ignore_err()
.ready_for_each(|key| self.db.roomid_invitedcount.remove(key)),
self.db
.roomid_inviteviaservers
.keys_prefix_raw(room_id)
.ignore_err()
.ready_for_each(|key| self.db.roomid_inviteviaservers.remove(key)),
self.db
.roomid_joinedcount
.keys_prefix_raw(room_id)
.ignore_err()
.ready_for_each(|key| self.db.roomid_joinedcount.remove(key)),
self.db
.roomserverids
.keys_prefix_raw(room_id)
.ignore_err()
.ready_for_each(|key| self.db.roomserverids.remove(key)),
self.db
.roomuserid_invitecount
.keys_prefix_raw(&roomuser_key)
.ignore_err()
.ready_for_each(|key| self.db.roomuserid_invitecount.remove(key)),
self.db
.roomuserid_joined
.keys_prefix_raw(&roomuser_key)
.ignore_err()
.ready_for_each(|key| self.db.roomuserid_joined.remove(key)),
self.db
.roomuserid_leftcount
.keys_prefix_raw(&roomuser_key)
.ignore_err()
.ready_for_each(|key| self.db.roomuserid_leftcount.remove(key)),
self.db
.roomuserid_knockedcount
.keys_prefix_raw(&roomuser_key)
.ignore_err()
.ready_for_each(|key| self.db.roomuserid_knockedcount.remove(key)),
self.db
.roomuseroncejoinedids
.keys_prefix_raw(room_id)
.ignore_err()
.ready_for_each(|key| self.db.roomuseroncejoinedids.remove(key)),
self.db
.userroomid_invitestate
.keys_prefix_raw(&userroom_key)
.ignore_err()
.ready_for_each(|key| self.db.userroomid_invitestate.remove(key)),
self.db
.userroomid_joined
.keys_prefix_raw(&userroom_key)
.ignore_err()
.ready_for_each(|key| self.db.userroomid_joined.remove(key)),
self.db
.userroomid_leftstate
.keys_prefix_raw(&userroom_key)
.ignore_err()
.ready_for_each(|key| self.db.userroomid_leftstate.remove(key)),
self.db
.userroomid_knockedstate
.keys_prefix_raw(&userroom_key)
.ignore_err()
.ready_for_each(|key| self.db.userroomid_knockedstate.remove(key)),
self.db
.userroomid_invitesender
.keys_prefix_raw(&userroom_key)
.ignore_err()
.ready_for_each(|key| self.db.userroomid_invitesender.remove(key)),
self.db
.serverroomids
.keys_prefix_raw(&(Interfix, room_id))
.ignore_err()
.ready_for_each(|key| self.db.serverroomids.remove(key)),
);
}
#[implement(Service)]
#[tracing::instrument(level = "trace", skip_all)]
pub async fn appservice_in_room(&self, room_id: &RoomId, appservice: &RegistrationInfo) -> bool {
@@ -238,7 +323,7 @@ pub async fn room_joined_count(&self, room_id: &RoomId) -> Result<u64> {
#[implement(Service)]
#[tracing::instrument(skip(self), level = "debug")]
/// Returns an iterator of all our local users in the room, even if they're
/// deactivated
/// deactivated/guests
pub fn local_users_in_room<'a>(
&'a self,
room_id: &'a RoomId,
@@ -248,7 +333,7 @@ pub fn local_users_in_room<'a>(
}
/// Returns an iterator of all our local joined users in a room who are
/// active (not deactivated)
/// active (not deactivated, not guest)
#[implement(Service)]
#[tracing::instrument(skip(self), level = "trace")]
pub fn active_local_users_in_room<'a>(
+2 -6
View File
@@ -47,7 +47,7 @@ pub async fn update_membership(
#[allow(clippy::collapsible_if)]
if !self.services.globals.user_is_local(user_id) {
if !self.services.users.exists(user_id).await {
self.services.users.create(user_id, None).await?;
self.services.users.create(user_id, None, None).await?;
}
}
@@ -119,11 +119,7 @@ pub async fn update_membership(
self.mark_as_joined(user_id, room_id);
},
| MembershipState::Invite => {
let last_state = self
.services
.state
.summary_stripped(pdu, room_id, user_id)
.await;
let last_state = self.services.state.summary_stripped(pdu, room_id).await;
self.mark_as_invited(user_id, room_id, pdu.sender(), last_state, None)
.await?;
+3 -2
View File
@@ -54,8 +54,9 @@ where
if !status.is_success() {
debug_error!("Antispam response bytes: {:?}", utils::string_from_bytes(&body));
return match status {
| http::StatusCode::FORBIDDEN =>
Err!(Request(Forbidden("Request was rejected by antispam service.",))),
| http::StatusCode::FORBIDDEN => {
Err!(Request(Forbidden("Request was rejected by antispam service.",)))
},
| _ => Err!(BadServerResponse(warn!(
"Antispam returned unsuccessful HTTP response {status}",
))),
+30 -10
View File
@@ -4,7 +4,7 @@ use std::{
sync::Arc,
};
use conduwuit::{Err, Error, Result, error, utils};
use conduwuit::{Err, Error, Result, error, utils, utils::hash};
use lettre::Address;
use ruma::{
UserId,
@@ -360,11 +360,12 @@ impl Service {
));
}
},
| _ =>
| _ => {
return Err(StandardErrorBody::new(
ErrorKind::Unrecognized,
"Identifier type not recognized".to_owned(),
)),
));
},
};
let Ok(user_id) = UserId::parse_with_server_name(
@@ -377,13 +378,32 @@ impl Service {
));
};
if self
.services
.users
.check_password(&user_id, password)
.await
.is_ok()
{
// Check if password is correct
let mut password_verified = false;
// First try local password hash verification
if let Ok(hash) = self.services.users.password_hash(&user_id).await {
password_verified = hash::verify_password(password, &hash).is_ok();
}
// If local password verification failed, try LDAP authentication
#[cfg(feature = "ldap")]
if !password_verified && self.services.config.ldap.enable {
// Search for user in LDAP to get their DN
if let Ok(dns) = self.services.users.search_ldap(&user_id).await {
if let Some((user_dn, _is_admin)) = dns.first() {
// Try to authenticate with LDAP
password_verified = self
.services
.users
.auth_ldap(user_dn, password)
.await
.is_ok();
}
}
}
if password_verified {
identity.try_set_localpart(user_id.localpart().to_owned())?;
Ok(AuthType::Password)
+242 -161
View File
@@ -1,16 +1,24 @@
pub(super) mod dehydrated_device;
#[cfg(feature = "ldap")]
use std::collections::HashMap;
use std::{collections::BTreeMap, mem, net::IpAddr, sync::Arc};
#[cfg(feature = "ldap")]
use conduwuit::result::LogErr;
use conduwuit::{
Err, Error, Result, Server, debug_error, debug_warn, err, trace,
Err, Error, Result, Server, debug_warn, err, is_equal_to, trace,
utils::{self, ReadyExt, stream::TryIgnore, string::Unquoted},
};
#[cfg(feature = "ldap")]
use conduwuit_core::{debug, error};
use database::{Deserialized, Ignore, Interfix, Json, Map};
use futures::{Stream, StreamExt, TryFutureExt};
#[cfg(feature = "ldap")]
use ldap3::{LdapConnAsync, LdapConnSettings, Scope, SearchEntry};
use ruma::{
DeviceId, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OneTimeKeyId, OneTimeKeyName,
OwnedDeviceId, OwnedKeyId, OwnedMxcUri, OwnedOneTimeKeyId, OwnedUserId, RoomId, UInt, UserId,
DeviceId, KeyId, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OneTimeKeyId,
OneTimeKeyName, OwnedDeviceId, OwnedKeyId, OwnedMxcUri, OwnedUserId, RoomId, UInt, UserId,
api::{
client::{device::Device, filter::FilterDefinition},
error::ErrorKind,
@@ -38,19 +46,6 @@ pub struct UserSuspension {
pub suspended_by: String,
}
/// A password hash. This is only for use when setting a user's password,
/// if the hash needs to be kept around for a while without keeping the password
/// in memory.
pub struct HashedPassword(String);
impl HashedPassword {
pub fn new(password: &str) -> Result<Self> {
Ok(Self(utils::hash::password(password).map_err(|e| {
err!(Request(InvalidParam("Password does not meet the requirements: {e}")))
})?))
}
}
pub struct Service {
services: Services,
db: Data,
@@ -70,7 +65,6 @@ struct Data {
keychangeid_userid: Arc<Map>,
keyid_key: Arc<Map>,
onetimekeyid_onetimekeys: Arc<Map>,
fallbackkeyid_fallbackkey: Arc<Map>,
openidtoken_expiresatuserid: Arc<Map>,
logintoken_expiresatuserid: Arc<Map>,
todeviceid_events: Arc<Map>,
@@ -85,6 +79,7 @@ struct Data {
userid_displayname: Arc<Map>,
userid_lastonetimekeyupdate: Arc<Map>,
userid_masterkeyid: Arc<Map>,
userid_origin: Arc<Map>,
userid_password: Arc<Map>,
userid_suspension: Arc<Map>,
userid_lock: Arc<Map>,
@@ -111,7 +106,6 @@ impl crate::Service for Service {
keychangeid_userid: args.db["keychangeid_userid"].clone(),
keyid_key: args.db["keyid_key"].clone(),
onetimekeyid_onetimekeys: args.db["onetimekeyid_onetimekeys"].clone(),
fallbackkeyid_fallbackkey: args.db["fallbackkeyid_fallbackkey"].clone(),
openidtoken_expiresatuserid: args.db["openidtoken_expiresatuserid"].clone(),
logintoken_expiresatuserid: args.db["logintoken_expiresatuserid"].clone(),
todeviceid_events: args.db["todeviceid_events"].clone(),
@@ -126,6 +120,7 @@ impl crate::Service for Service {
userid_displayname: args.db["userid_displayname"].clone(),
userid_lastonetimekeyupdate: args.db["userid_lastonetimekeyupdate"].clone(),
userid_masterkeyid: args.db["userid_masterkeyid"].clone(),
userid_origin: args.db["userid_origin"].clone(),
userid_password: args.db["userid_password"].clone(),
userid_suspension: args.db["userid_suspension"].clone(),
userid_lock: args.db["userid_lock"].clone(),
@@ -183,24 +178,31 @@ impl Service {
}
/// Create a new user account on this homeserver.
///
/// User origin is by default "password" (meaning that it will login using
/// its user_id/password). Users with other origins (currently only "ldap"
/// is available) have special login processes.
#[inline]
pub async fn create(&self, user_id: &UserId, password: Option<HashedPassword>) -> Result<()> {
if !self.services.globals.user_is_local(user_id) && password.is_some() {
return Err!("Cannot create a nonlocal user with a set password");
pub async fn create(
&self,
user_id: &UserId,
password: Option<&str>,
origin: Option<&str>,
) -> Result<()> {
if !self.services.globals.user_is_local(user_id)
&& (password.is_some() || origin.is_some())
{
return Err!("Cannot create a nonlocal user with a set password or origin");
}
self.set_password(user_id, password);
self.db
.userid_origin
.insert(user_id, origin.unwrap_or("password"));
self.set_password(user_id, password).await?;
Ok(())
}
// /// Create a new account for a local human or bot user.
// pub async fn create_local_account(
// &self,
// username: String,
// password:
// )
/// Deactivate account
pub async fn deactivate_account(&self, user_id: &UserId) -> Result<()> {
// Remove all associated devices
@@ -212,7 +214,7 @@ impl Service {
// result in an empty string, so the user will not be able to log in again.
// Systems like changing the password without logging in should check if the
// account is deactivated.
self.set_password(user_id, None);
self.set_password(user_id, None).await?;
// TODO: Unhook 3PID
Ok(())
@@ -358,42 +360,46 @@ impl Service {
.ready_filter_map(|(u, p): (OwnedUserId, &[u8])| (!p.is_empty()).then_some(u))
}
/// Set a user's password.
pub fn set_password(&self, user_id: &UserId, password: Option<HashedPassword>) {
if let Some(hash) = password {
self.db.userid_password.insert(user_id, hash.0);
} else {
self.db.userid_password.insert(user_id, b"");
}
/// Returns the origin of the user (password/LDAP/...).
pub async fn origin(&self, user_id: &UserId) -> Result<String> {
self.db.userid_origin.get(user_id).await.deserialized()
}
/// Check a user's password.
pub async fn check_password(&self, user_id: &UserId, password: &str) -> Result<OwnedUserId> {
let (hash, user_id): (String, OwnedUserId) = if let Ok(hash) =
self.db.userid_password.get(user_id).await.deserialized()
/// Returns the password hash for the given user.
pub async fn password_hash(&self, user_id: &UserId) -> Result<String> {
self.db.userid_password.get(user_id).await.deserialized()
}
/// Hash and set the user's password to the Argon2 hash
pub async fn set_password(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
// Cannot change the password of a LDAP user. There are two special cases :
// - a `None` password can be used to deactivate a LDAP user
// - a "*" password is used as the default password of an active LDAP user
if cfg!(feature = "ldap")
&& password.is_some_and(|pwd| pwd != "*")
&& self
.db
.userid_origin
.get(user_id)
.await
.deserialized::<String>()
.is_ok_and(is_equal_to!("ldap"))
{
(hash, user_id.to_owned())
} else {
// We also check the lowercased version of the user ID to handle legacy user IDs
// better
let lowercase_user_id = UserId::parse(user_id.as_str().to_lowercase()).unwrap();
if let Ok(hash) = self.db.userid_password.get(user_id).await.deserialized() {
(hash, lowercase_user_id)
} else {
return Err!(Request(InvalidParam("This user cannot log in with a password.")));
}
};
if hash.is_empty() {
return Err!(Request(UserDeactivated("This user is deactivated")));
return Err!(Request(InvalidParam("Cannot change password of a LDAP user")));
}
utils::hash::verify_password(password, &hash)
.inspect_err(|e| debug_error!("{e}"))
.map_err(|_| err!(Request(Forbidden("Invalid identifier or password."))))?;
password
.map(utils::hash::password)
.transpose()
.map_err(|e| {
err!(Request(InvalidParam("Password does not meet the requirements: {e}")))
})?
.map_or_else(
|| self.db.userid_password.insert(user_id, b""),
|hash| self.db.userid_password.insert(user_id, hash),
);
Ok(user_id)
Ok(())
}
/// Returns the displayname of a user on this homeserver.
@@ -589,7 +595,7 @@ impl Service {
&self,
user_id: &UserId,
device_id: &DeviceId,
one_time_key_key: &OneTimeKeyId,
one_time_key_key: &KeyId<OneTimeKeyAlgorithm, OneTimeKeyName>,
one_time_key_value: &Raw<OneTimeKey>,
) -> Result {
// All devices have metadata
@@ -626,39 +632,6 @@ impl Service {
Ok(())
}
/// Save a fallback key for the given user, device, and algorithm
/// This key will replace an existing fallback key
pub async fn add_fallback_key(
&self,
user_id: &UserId,
device_id: &DeviceId,
fallback_key_id: &OneTimeKeyId,
fallback_key: &Raw<OneTimeKey>,
used: bool,
) -> Result {
// All devices have metadata
// Only existing devices should be able to call this, but we shouldn't assert
// either...
let key = (user_id, device_id);
if self.db.userdeviceid_metadata.qry(&key).await.is_err() {
return Err!(Database(error!(
%user_id,
%device_id,
"User does not exist or device has no metadata."
)));
}
// There is one fallback key slot per user, per device, per algorithm
// Therefore we use this as the DB key for this column
let db_key = (user_id, device_id, fallback_key_id.algorithm());
self.db
.fallbackkeyid_fallbackkey
.put(db_key, (used, fallback_key_id.as_str(), Json(fallback_key)));
Ok(())
}
pub async fn last_one_time_keys_update(&self, user_id: &UserId) -> u64 {
self.db
.userid_lastonetimekeyupdate
@@ -690,8 +663,6 @@ impl Service {
.onetimekeyid_onetimekeys
.raw_stream_prefix(&prefix)
.ignore_err()
.next()
.await
.map(|(key, val)| {
self.db.onetimekeyid_onetimekeys.remove(key);
@@ -710,44 +681,11 @@ impl Service {
.unwrap();
(key, val)
});
})
.next()
.await;
if let Some(result) = one_time_key {
return Ok(result);
}
// No one-time key has been found. Look for a fallback key.
let db_key = (user_id, device_id, key_algorithm);
let fallback_key = self
.db
.fallbackkeyid_fallbackkey
.qry(&db_key)
.await
.ok()
.and_then(|handle| {
handle
.deserialized::<(bool, OwnedOneTimeKeyId, Raw<OneTimeKey>)>()
.ok()
});
if let Some((used, fallback_key_id, fallback_key_value)) = fallback_key {
if !used {
// write the key to the database again to mark it as used
self.add_fallback_key(
user_id,
device_id,
&fallback_key_id,
&fallback_key_value,
true,
)
.await?;
}
return Ok((fallback_key_id, fallback_key_value));
}
Err(err!(Request(NotFound("No one-time key or fallback key found"))))
one_time_key.ok_or_else(|| err!(Request(NotFound("No one-time-key found"))))
}
pub async fn count_one_time_keys(
@@ -780,34 +718,6 @@ impl Service {
algorithm_counts
}
pub async fn list_unused_fallback_key_types(
&self,
user_id: &UserId,
device_id: &DeviceId,
) -> Vec<OneTimeKeyAlgorithm> {
type KeyVal = ((String, String, OneTimeKeyAlgorithm), (bool, String, Ignore));
let mut query = user_id.as_bytes().to_vec();
query.push(0xFF);
query.extend_from_slice(device_id.as_bytes());
query.push(0xFF);
let mut unused_algorithms = Vec::new();
self.db
.fallbackkeyid_fallbackkey
.stream_prefix(&query)
.ignore_err()
.ready_for_each(|((_, _, fallback_key_algorithm), (used, ..)): KeyVal| {
if !used {
unused_algorithms.push(fallback_key_algorithm);
}
})
.await;
unused_algorithms
}
pub async fn add_device_keys(
&self,
user_id: &UserId,
@@ -1382,6 +1292,177 @@ impl Service {
.ready_for_each(|(key, _)| self.set_profile_key(user_id, &key, None))
.await;
}
#[cfg(feature = "ldap")]
async fn create_ldap_connection(
config: &conduwuit_core::config::LdapConfig,
uri: &str,
) -> Result<(LdapConnAsync, ldap3::Ldap), ldap3::LdapError> {
let mut settings = LdapConnSettings::new();
if config.use_starttls {
settings = settings.set_starttls(true);
}
if config.disable_tls_verification {
settings = settings.set_no_tls_verify(true);
}
LdapConnAsync::with_settings(settings, uri).await
}
#[cfg(not(feature = "ldap"))]
pub async fn search_ldap(&self, _user_id: &UserId) -> Result<Vec<(String, Option<bool>)>> {
Err!(FeatureDisabled("ldap"))
}
#[cfg(feature = "ldap")]
pub async fn search_ldap(&self, user_id: &UserId) -> Result<Vec<(String, Option<bool>)>> {
let localpart = user_id.localpart().to_owned();
let lowercased_localpart = localpart.to_lowercase();
let config = &self.services.server.config.ldap;
let uri = config
.uri
.as_ref()
.ok_or_else(|| err!(Ldap(error!("LDAP URI is not configured."))))?;
debug!(?uri, "LDAP creating connection...");
let (conn, mut ldap) = Self::create_ldap_connection(config, uri.as_str())
.await
.map_err(|e| err!(Ldap(error!(%user_id, "LDAP connection setup error: {e}"))))?;
let driver = self.services.server.runtime().spawn(async move {
match conn.drive().await {
| Err(e) => error!("LDAP connection error: {e}"),
| Ok(()) => debug!("LDAP connection completed."),
}
});
match (&config.bind_dn, &config.bind_password_file) {
| (Some(bind_dn), Some(bind_password_file)) => {
let bind_pw = String::from_utf8(std::fs::read(bind_password_file)?)?;
ldap.simple_bind(bind_dn, bind_pw.trim())
.await
.and_then(ldap3::LdapResult::success)
.map_err(|e| err!(Ldap(error!("LDAP bind error: {e}"))))?;
},
| (..) => {},
}
let attr = [&config.uid_attribute, &config.name_attribute];
let user_filter = &config.filter.replace("{username}", &lowercased_localpart);
let (entries, _result) = ldap
.search(&config.base_dn, Scope::Subtree, user_filter, &attr)
.await
.and_then(ldap3::SearchResult::success)
.inspect(|(entries, result)| trace!(?entries, ?result, "LDAP Search"))
.map_err(|e| err!(Ldap(error!(?attr, ?user_filter, "LDAP search error: {e}"))))?;
let mut dns: HashMap<String, Option<bool>> = entries
.into_iter()
.filter_map(|entry| {
let search_entry = SearchEntry::construct(entry);
debug!(?search_entry, "LDAP search entry");
search_entry
.attrs
.get(&config.uid_attribute)
.into_iter()
.chain(search_entry.attrs.get(&config.name_attribute))
.any(|ids| ids.contains(&localpart) || ids.contains(&lowercased_localpart))
.then_some((search_entry.dn, None))
})
.collect();
if !config.admin_filter.is_empty() {
// Update all existing entries to Some(false) since we can now determine admin
// status
for admin_status in dns.values_mut() {
*admin_status = Some(false);
}
let admin_base_dn = if config.admin_base_dn.is_empty() {
&config.base_dn
} else {
&config.admin_base_dn
};
let admin_filter = &config
.admin_filter
.replace("{username}", &lowercased_localpart);
let (admin_entries, _result) = ldap
.search(admin_base_dn, Scope::Subtree, admin_filter, &attr)
.await
.and_then(ldap3::SearchResult::success)
.inspect(|(entries, result)| trace!(?entries, ?result, "LDAP Admin Search"))
.map_err(|e| {
err!(Ldap(error!(?attr, ?admin_filter, "Ldap admin search error: {e}")))
})?;
dns.extend(admin_entries.into_iter().filter_map(|entry| {
let search_entry = SearchEntry::construct(entry);
debug!(?search_entry, "LDAP search entry");
search_entry
.attrs
.get(&config.uid_attribute)
.into_iter()
.chain(search_entry.attrs.get(&config.name_attribute))
.any(|ids| ids.contains(&localpart) || ids.contains(&lowercased_localpart))
.then_some((search_entry.dn, Some(true)))
}));
}
ldap.unbind()
.await
.map_err(|e| err!(Ldap(error!("LDAP unbind error: {e}"))))?;
driver.await.log_err().ok();
Ok(dns.drain().collect())
}
#[cfg(not(feature = "ldap"))]
pub async fn auth_ldap(&self, _user_dn: &str, _password: &str) -> Result {
Err!(FeatureDisabled("ldap"))
}
#[cfg(feature = "ldap")]
pub async fn auth_ldap(&self, user_dn: &str, password: &str) -> Result {
let config = &self.services.server.config.ldap;
let uri = config
.uri
.as_ref()
.ok_or_else(|| err!(Ldap(error!("LDAP URI is not configured."))))?;
debug!(?uri, "LDAP creating connection...");
let (conn, mut ldap) = Self::create_ldap_connection(config, uri.as_str())
.await
.map_err(|e| err!(Ldap(error!(%user_dn, "LDAP connection setup error: {e}"))))?;
let driver = self.services.server.runtime().spawn(async move {
match conn.drive().await {
| Err(e) => error!("LDAP connection error: {e}"),
| Ok(()) => debug!("LDAP connection completed."),
}
});
ldap.simple_bind(user_dn, password)
.await
.and_then(ldap3::LdapResult::success)
.map_err(|e| {
err!(Request(Forbidden(debug_error!("LDAP authentication error: {e}"))))
})?;
ldap.unbind()
.await
.map_err(|e| err!(Ldap(error!("LDAP unbind error: {e}"))))?;
driver.await.log_err().ok();
Ok(())
}
}
pub fn parse_master_key(
+1 -1
View File
@@ -14,7 +14,7 @@ conduwuit-admin.workspace = true
conduwuit.workspace = true
clap.workspace = true
askama = "0.16.0"
askama = "0.15.1"
cargo_metadata = "0.23.1"
[lints]