Compare commits

..
130 changed files with 784 additions and 2102 deletions

No files matched your search

+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
name: Renovate name: Renovate
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: ghcr.io/renovatebot/renovate:42.70.2@sha256:3c2ac1b94fa92ef2fa4d1a0493f2c3ba564454720a32fdbcac2db2846ff1ee47 image: ghcr.io/renovatebot/renovate:42.11.0@sha256:656c1e5b808279eac16c37b89562fb4c699e02fc7e219244f4a1fc2f0a7ce367
options: --tmpfs /tmp:exec options: --tmpfs /tmp:exec
steps: steps:
- name: Checkout - name: Checkout
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
persist-credentials: true persist-credentials: true
token: ${{ secrets.FORGEJO_TOKEN }} token: ${{ secrets.FORGEJO_TOKEN }}
- uses: https://github.com/cachix/install-nix-action@4e002c8ec80594ecd40e759629461e26c8abed15 # v31.9.0 - uses: https://github.com/cachix/install-nix-action@7ab6e7fd29da88e74b1e314a4ae9ac6b5cda3801 # v31.8.0
with: with:
nix_path: nixpkgs=channel:nixos-unstable nix_path: nixpkgs=channel:nixos-unstable
+2 -2
View File
@@ -23,7 +23,7 @@ repos:
- id: check-added-large-files - id: check-added-large-files
- repo: https://github.com/crate-ci/typos - repo: https://github.com/crate-ci/typos
rev: v1.41.0 rev: v1.40.0
hooks: hooks:
- id: typos - id: typos
- id: typos - id: typos
@@ -31,7 +31,7 @@ repos:
stages: [commit-msg] stages: [commit-msg]
- repo: https://github.com/crate-ci/committed - repo: https://github.com/crate-ci/committed
rev: v1.1.9 rev: v1.1.8
hooks: hooks:
- id: committed - id: committed
Generated
+18 -40
View File
@@ -1632,16 +1632,6 @@ dependencies = [
"litrs", "litrs",
] ]
[[package]]
name = "draupnir-antispam"
version = "0.1.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d"
dependencies = [
"ruma-common",
"serde",
"serde_json",
]
[[package]] [[package]]
name = "dtor" name = "dtor"
version = "0.1.0" version = "0.1.0"
@@ -1760,7 +1750,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [ dependencies = [
"libc", "libc",
"windows-sys 0.61.2", "windows-sys 0.52.0",
] ]
[[package]] [[package]]
@@ -2415,7 +2405,7 @@ dependencies = [
"libc", "libc",
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"socket2 0.6.1", "socket2 0.5.10",
"tokio", "tokio",
"tower-service", "tower-service",
"tracing", "tracing",
@@ -2992,16 +2982,6 @@ version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
[[package]]
name = "meowlnir-antispam"
version = "0.1.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d"
dependencies = [
"ruma-common",
"serde",
"serde_json",
]
[[package]] [[package]]
name = "mime" name = "mime"
version = "0.3.17" version = "0.3.17"
@@ -3141,7 +3121,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.60.2",
] ]
[[package]] [[package]]
@@ -3769,7 +3749,7 @@ dependencies = [
"quinn-udp", "quinn-udp",
"rustc-hash", "rustc-hash",
"rustls", "rustls",
"socket2 0.6.1", "socket2 0.5.10",
"thiserror 2.0.17", "thiserror 2.0.17",
"tokio", "tokio",
"tracing", "tracing",
@@ -3806,9 +3786,9 @@ dependencies = [
"cfg_aliases", "cfg_aliases",
"libc", "libc",
"once_cell", "once_cell",
"socket2 0.6.1", "socket2 0.5.10",
"tracing", "tracing",
"windows-sys 0.60.2", "windows-sys 0.52.0",
] ]
[[package]] [[package]]
@@ -4085,13 +4065,11 @@ checksum = "88f8660c1ff60292143c98d08fc6e2f654d722db50410e3f3797d40baaf9d8f3"
[[package]] [[package]]
name = "ruma" name = "ruma"
version = "0.10.1" version = "0.10.1"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"assign", "assign",
"draupnir-antispam",
"js_int", "js_int",
"js_option", "js_option",
"meowlnir-antispam",
"ruma-appservice-api", "ruma-appservice-api",
"ruma-client-api", "ruma-client-api",
"ruma-common", "ruma-common",
@@ -4107,7 +4085,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-appservice-api" name = "ruma-appservice-api"
version = "0.10.0" version = "0.10.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
@@ -4119,7 +4097,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-client-api" name = "ruma-client-api"
version = "0.18.0" version = "0.18.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"as_variant", "as_variant",
"assign", "assign",
@@ -4142,7 +4120,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-common" name = "ruma-common"
version = "0.13.0" version = "0.13.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"as_variant", "as_variant",
"base64 0.22.1", "base64 0.22.1",
@@ -4174,7 +4152,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-events" name = "ruma-events"
version = "0.28.1" version = "0.28.1"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"as_variant", "as_variant",
"indexmap", "indexmap",
@@ -4199,7 +4177,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-federation-api" name = "ruma-federation-api"
version = "0.9.0" version = "0.9.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"bytes", "bytes",
"headers", "headers",
@@ -4221,7 +4199,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-identifiers-validation" name = "ruma-identifiers-validation"
version = "0.9.5" version = "0.9.5"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"js_int", "js_int",
"thiserror 2.0.17", "thiserror 2.0.17",
@@ -4230,7 +4208,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-identity-service-api" name = "ruma-identity-service-api"
version = "0.9.0" version = "0.9.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
@@ -4240,7 +4218,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-macros" name = "ruma-macros"
version = "0.13.0" version = "0.13.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"proc-macro-crate", "proc-macro-crate",
@@ -4255,7 +4233,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-push-gateway-api" name = "ruma-push-gateway-api"
version = "0.9.0" version = "0.9.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"js_int", "js_int",
"ruma-common", "ruma-common",
@@ -4267,7 +4245,7 @@ dependencies = [
[[package]] [[package]]
name = "ruma-signatures" name = "ruma-signatures"
version = "0.15.0" version = "0.15.0"
source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=79abd5d331bca596b7f37e367a9f2cebccd9f64d#79abd5d331bca596b7f37e367a9f2cebccd9f64d" source = "git+https://forgejo.ellis.link/continuwuation/ruwuma?rev=27abe0dcd33fd4056efc94bab3582646b31b6ce9#27abe0dcd33fd4056efc94bab3582646b31b6ce9"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"ed25519-dalek", "ed25519-dalek",
@@ -4347,7 +4325,7 @@ dependencies = [
"errno", "errno",
"libc", "libc",
"linux-raw-sys", "linux-raw-sys",
"windows-sys 0.61.2", "windows-sys 0.52.0",
] ]
[[package]] [[package]]
+73 -66
View File
@@ -1,17 +1,26 @@
#cargo-features = ["profile-rustflags"]
[workspace] [workspace]
resolver = "2" resolver = "2"
members = ["src/*", "xtask/*"] members = ["src/*", "xtask/*"]
default-members = ["src/*"] default-members = ["src/*"]
[workspace.package] [workspace.package]
authors = ["Continuwuity Team and contributors <team@continuwuity.org>"] authors = [
description = "A Matrix homeserver written in Rust, the official continuation of the conduwuit homeserver." "June Clementine Strawberry <june@girlboss.ceo>",
"strawberry <strawberry@puppygock.gay>", # woof
"Jason Volk <jason@zemos.net>",
]
categories = ["network-programming"]
description = "a very cool Matrix chat homeserver written in Rust"
edition = "2024" edition = "2024"
homepage = "https://continuwuity.org/" homepage = "https://continuwuity.org/"
keywords = ["chat", "matrix", "networking", "server", "uwu"]
license = "Apache-2.0" license = "Apache-2.0"
# See also `rust-toolchain.toml` # See also `rust-toolchain.toml`
readme = "README.md" readme = "README.md"
repository = "https://forgejo.ellis.link/continuwuation/continuwuity" repository = "https://forgejo.ellis.link/continuwuation/continuwuity"
rust-version = "1.86.0"
version = "0.5.1" version = "0.5.1"
[workspace.metadata.crane] [workspace.metadata.crane]
@@ -24,11 +33,11 @@ features = ["serde"]
[workspace.dependencies.smallvec] [workspace.dependencies.smallvec]
version = "1.14.0" version = "1.14.0"
features = [ features = [
"const_generics", "const_generics",
"const_new", "const_new",
"serde", "serde",
"union", "union",
"write", "write",
] ]
[workspace.dependencies.smallstr] [workspace.dependencies.smallstr]
@@ -87,13 +96,13 @@ version = "1.11.1"
version = "0.7.9" version = "0.7.9"
default-features = false default-features = false
features = [ features = [
"form", "form",
"http1", "http1",
"http2", "http2",
"json", "json",
"matched-path", "matched-path",
"tokio", "tokio",
"tracing", "tracing",
] ]
[workspace.dependencies.axum-extra] [workspace.dependencies.axum-extra]
@@ -140,10 +149,10 @@ features = ["aws_lc_rs"]
version = "0.12.15" version = "0.12.15"
default-features = false default-features = false
features = [ features = [
"rustls-tls-native-roots", "rustls-tls-native-roots",
"socks", "socks",
"hickory-dns", "hickory-dns",
"http2", "http2",
] ]
[workspace.dependencies.serde] [workspace.dependencies.serde]
@@ -179,18 +188,18 @@ default-features = false
version = "0.25.5" version = "0.25.5"
default-features = false default-features = false
features = [ features = [
"jpeg", "jpeg",
"png", "png",
"gif", "gif",
"webp", "webp",
] ]
[workspace.dependencies.blurhash] [workspace.dependencies.blurhash]
version = "0.2.3" version = "0.2.3"
default-features = false default-features = false
features = [ features = [
"fast-linear-to-srgb", "fast-linear-to-srgb",
"image", "image",
] ]
# logging # logging
@@ -220,13 +229,13 @@ default-features = false
version = "4.5.35" version = "4.5.35"
default-features = false default-features = false
features = [ features = [
"derive", "derive",
"env", "env",
"error-context", "error-context",
"help", "help",
"std", "std",
"string", "string",
"usage", "usage",
] ]
[workspace.dependencies.futures] [workspace.dependencies.futures]
@@ -238,15 +247,15 @@ features = ["std", "async-await"]
version = "1.44.2" version = "1.44.2"
default-features = false default-features = false
features = [ features = [
"fs", "fs",
"net", "net",
"macros", "macros",
"sync", "sync",
"signal", "signal",
"time", "time",
"rt-multi-thread", "rt-multi-thread",
"io-util", "io-util",
"tracing", "tracing",
] ]
[workspace.dependencies.tokio-metrics] [workspace.dependencies.tokio-metrics]
@@ -271,18 +280,18 @@ default-features = false
version = "1.6.0" version = "1.6.0"
default-features = false default-features = false
features = [ features = [
"server", "server",
"http1", "http1",
"http2", "http2",
] ]
[workspace.dependencies.hyper-util] [workspace.dependencies.hyper-util]
version = "=0.1.17" version = "=0.1.17"
default-features = false default-features = false
features = [ features = [
"server-auto", "server-auto",
"server-graceful", "server-graceful",
"tokio", "tokio",
] ]
# to support multiple variations of setting a config option # to support multiple variations of setting a config option
@@ -301,9 +310,9 @@ features = ["env", "toml"]
version = "0.25.1" version = "0.25.1"
default-features = false default-features = false
features = [ features = [
"serde", "serde",
"system-config", "system-config",
"tokio", "tokio",
] ]
# Used for conduwuit::Error type # Used for conduwuit::Error type
@@ -342,7 +351,7 @@ version = "0.1.2"
# Used for matrix spec type definitions and helpers # Used for matrix spec type definitions and helpers
[workspace.dependencies.ruma] [workspace.dependencies.ruma]
git = "https://forgejo.ellis.link/continuwuation/ruwuma" git = "https://forgejo.ellis.link/continuwuation/ruwuma"
rev = "79abd5d331bca596b7f37e367a9f2cebccd9f64d" rev = "27abe0dcd33fd4056efc94bab3582646b31b6ce9"
features = [ features = [
"compat", "compat",
"rand", "rand",
@@ -372,13 +381,13 @@ features = [
"unstable-msc4095", "unstable-msc4095",
"unstable-msc4121", "unstable-msc4121",
"unstable-msc4125", "unstable-msc4125",
"unstable-msc4155", "unstable-msc4155",
"unstable-msc4186", "unstable-msc4186",
"unstable-msc4203", # sending to-device events to appservices "unstable-msc4203", # sending to-device events to appservices
"unstable-msc4210", # remove legacy mentions "unstable-msc4210", # remove legacy mentions
"unstable-extensible-events", "unstable-extensible-events",
"unstable-pdu", "unstable-pdu",
"unstable-msc4155" "unstable-msc4155"
] ]
[workspace.dependencies.rust-rocksdb] [workspace.dependencies.rust-rocksdb]
@@ -386,11 +395,11 @@ git = "https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1"
rev = "61d9d23872197e9ace4a477f2617d5c9f50ecb23" rev = "61d9d23872197e9ace4a477f2617d5c9f50ecb23"
default-features = false default-features = false
features = [ features = [
"multi-threaded-cf", "multi-threaded-cf",
"mt_static", "mt_static",
"lz4", "lz4",
"zstd", "zstd",
"bzip2", "bzip2",
] ]
[workspace.dependencies.sha2] [workspace.dependencies.sha2]
@@ -449,16 +458,16 @@ git = "https://forgejo.ellis.link/continuwuation/jemallocator"
rev = "82af58d6a13ddd5dcdc7d4e91eae3b63292995b8" rev = "82af58d6a13ddd5dcdc7d4e91eae3b63292995b8"
default-features = false default-features = false
features = [ features = [
"background_threads_runtime_support", "background_threads_runtime_support",
"unprefixed_malloc_on_supported_platforms", "unprefixed_malloc_on_supported_platforms",
] ]
[workspace.dependencies.tikv-jemallocator] [workspace.dependencies.tikv-jemallocator]
git = "https://forgejo.ellis.link/continuwuation/jemallocator" git = "https://forgejo.ellis.link/continuwuation/jemallocator"
rev = "82af58d6a13ddd5dcdc7d4e91eae3b63292995b8" rev = "82af58d6a13ddd5dcdc7d4e91eae3b63292995b8"
default-features = false default-features = false
features = [ features = [
"background_threads_runtime_support", "background_threads_runtime_support",
"unprefixed_malloc_on_supported_platforms", "unprefixed_malloc_on_supported_platforms",
] ]
[workspace.dependencies.tikv-jemalloc-ctl] [workspace.dependencies.tikv-jemalloc-ctl]
git = "https://forgejo.ellis.link/continuwuation/jemallocator" git = "https://forgejo.ellis.link/continuwuation/jemallocator"
@@ -482,9 +491,9 @@ default-features = false
version = "0.1.2" version = "0.1.2"
default-features = false default-features = false
features = [ features = [
"static", "static",
"gcc", "gcc",
"light", "light",
] ]
[workspace.dependencies.rustyline-async] [workspace.dependencies.rustyline-async]
@@ -839,8 +848,6 @@ unknown_lints = "allow"
################### ###################
cargo = { level = "warn", priority = -1 } cargo = { level = "warn", priority = -1 }
# Nobody except for us should be consuming these crates, they don't need metadata
cargo_common_metadata = { level = "allow"}
## some sadness ## some sadness
multiple_crate_versions = { level = "allow", priority = 1 } multiple_crate_versions = { level = "allow", priority = 1 }
-1
View File
@@ -1 +0,0 @@
Certain potentially dangerous admin commands are now restricted to only be usable in the admin room and server console.
-1
View File
@@ -1 +0,0 @@
Implemented a configuration defined admin list independent of the admin room. (@Terryiscool160).
-1
View File
@@ -1 +0,0 @@
Fixed unreliable room summary fetching and improved error messages. Contributed by @nex.
-2
View File
@@ -1,2 +0,0 @@
Client requested timeout parameter is now applied to e2ee key lookups and claims. Related federation requests are now
also concurrent. Contributed by @nex.
-2
View File
@@ -1,2 +0,0 @@
Added support for invite and join anti-spam via Draupnir and Meowlnir, similar to that of synapse-http-antispam.
Contributed by @nex.
-1
View File
@@ -1 +0,0 @@
Implemented account locking functionality, to complement user suspension. Contributed by @nex.
-1
View File
@@ -1 +0,0 @@
Added admin command to forcefully log out all of a user's existing sessions. Contributed by @nex.
-1
View File
@@ -1 +0,0 @@
Implemented toggling the ability for an account to log in without mutating any of its data. Contributed by @nex.
-1
View File
@@ -1 +0,0 @@
Added support for issuing additional registration tokens, stored in the database, which supplement the existing registration token hardcoded in the config file. These tokens may optionally expire after a certain number of uses or after a certain amount of time has passed. Additionally, the `registration_token_file` configuration option is superseded by this feature and **has been removed**.
+13 -54
View File
@@ -421,7 +421,7 @@
# `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` # `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
# #
# If you would like registration only via token reg, please configure # If you would like registration only via token reg, please configure
# `registration_token`. # `registration_token` or `registration_token_file`.
# #
#allow_registration = false #allow_registration = false
@@ -452,13 +452,22 @@
# `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` # `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
# to true to allow open registration without any conditions. # to true to allow open registration without any conditions.
# #
# If you do not want to set a static token, the `!admin token` commands # YOU NEED TO EDIT THIS OR USE registration_token_file.
# may also be used to manage registration tokens.
# #
# example: "o&^uCtes4HPf0Vu@F20jQeeWE7" # example: "o&^uCtes4HPf0Vu@F20jQeeWE7"
# #
#registration_token = #registration_token =
# Path to a file on the system that gets read for additional registration
# tokens. Multiple tokens can be added if you separate them with
# whitespace
#
# continuwuity must be able to access the file, and it must not be empty
#
# example: "/etc/continuwuity/.reg_token"
#
#registration_token_file =
# The public site key for reCaptcha. If this is provided, reCaptcha # The public site key for reCaptcha. If this is provided, reCaptcha
# becomes required during registration. If both captcha *and* # becomes required during registration. If both captcha *and*
# registration token are enabled, both will be required during # registration token are enabled, both will be required during
@@ -1581,18 +1590,6 @@
# #
#admin_room_tag = "m.server_notice" #admin_room_tag = "m.server_notice"
# A list of Matrix IDs that are qualified as server admins.
#
# Any Matrix IDs within this list are regarded as an admin
# regardless of whether they are in the admin room or not
#
#admins_list = []
# Defines whether those within the admin room are added to the
# admins_list.
#
#admins_from_room = true
# Sentry.io crash/panic reporting, performance monitoring/metrics, etc. # Sentry.io crash/panic reporting, performance monitoring/metrics, etc.
# This is NOT enabled by default. # This is NOT enabled by default.
# #
@@ -1638,7 +1635,7 @@
# Enable the tokio-console. This option is only relevant to developers. # Enable the tokio-console. This option is only relevant to developers.
# #
# For more information, see: # For more information, see:
# https://continuwuity.org/development.html#debugging-with-tokio-console # https://continuwuity.org/development.html#debugging-with-tokio-console
# #
#tokio_console = false #tokio_console = false
@@ -1914,41 +1911,3 @@
# example: "(objectClass=conduwuitAdmin)" or "(uid={username})" # example: "(objectClass=conduwuitAdmin)" or "(uid={username})"
# #
#admin_filter = "" #admin_filter = ""
[global.antispam.meowlnir]
# The base URL on which to contact Meowlnir (before /_meowlnir/antispam).
#
# Example: "http://127.0.0.1:29339"
#
#base_url =
# The authentication secret defined in antispam->secret. Required for
# continuwuity to talk to Meowlnir.
#
#secret =
# The management room for which to send requests
#
#management_room =
# If enabled run all federated join attempts (both federated and local)
# through the Meowlnir anti-spam checks.
#
# By default, only join attempts for rooms with the `fi.mau.spam_checker`
# restricted join rule are checked.
#
#check_all_joins = false
[global.antispam.draupnir]
# The base URL on which to contact Draupnir (before /api/).
#
# Example: "http://127.0.0.1:29339"
#
#base_url =
# The authentication secret defined in
# web->synapseHTTPAntispam->authorization
#
#secret =
+1 -1
View File
@@ -52,7 +52,7 @@ ENV BINSTALL_VERSION=1.16.6
# renovate: datasource=github-releases depName=psastras/sbom-rs # renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1 ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree # renovate: datasource=crate depName=lddtree
ENV LDDTREE_VERSION=0.4.0 ENV LDDTREE_VERSION=0.3.7
# renovate: datasource=crate depName=timelord-cli # renovate: datasource=crate depName=timelord-cli
ENV TIMELORD_VERSION=3.0.1 ENV TIMELORD_VERSION=3.0.1
+1 -1
View File
@@ -22,7 +22,7 @@ ENV BINSTALL_VERSION=1.16.6
# renovate: datasource=github-releases depName=psastras/sbom-rs # renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1 ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree # renovate: datasource=crate depName=lddtree
ENV LDDTREE_VERSION=0.4.0 ENV LDDTREE_VERSION=0.3.7
# Install unpackaged tools # Install unpackaged tools
RUN <<EOF RUN <<EOF
+9 -27
View File
@@ -11,10 +11,10 @@ OCI images for Continuwuity are available in the registries listed below.
| Registry | Image | Notes | | Registry | Image | Notes |
| --------------- | --------------------------------------------------------------- | -----------------------| | --------------- | --------------------------------------------------------------- | -----------------------|
| Forgejo Registry| [forgejo.ellis.link/continuwuation/continuwuity:latest](https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/latest) | Latest tagged image. | | Forgejo Registry| [forgejo.ellis.link/continuwuation/continuwuity:latest][fj] | Latest tagged image. |
| Forgejo Registry| [forgejo.ellis.link/continuwuation/continuwuity:main](https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/main) | Main branch image. | | Forgejo Registry| [forgejo.ellis.link/continuwuation/continuwuity:main][fj] | Main branch image. |
| Forgejo Registry| [forgejo.ellis.link/continuwuation/continuwuity:latest-maxperf](https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/latest-maxperf) | Performance optimised version. |
| Forgejo Registry| [forgejo.ellis.link/continuwuation/continuwuity:main-maxperf](https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity/main-maxperf) | Performance optimised version. | [fj]: https://forgejo.ellis.link/continuwuation/-/packages/container/continuwuity
Use Use
@@ -24,15 +24,6 @@ docker image pull $LINK
to pull it to your machine. to pull it to your machine.
#### Mirrors
Images are mirrored to multiple locations automatically, on a schedule:
- `ghcr.io/continuwuity/continuwuity`
- `docker.io/jadedblueeyes/continuwuity`
- `registry.gitlab.com/continuwuity/continuwuity`
- `git.nexy7574.co.uk/mirrored/continuwuity` (releases only, no `main`)
### Run ### Run
When you have the image, you can simply run it with When you have the image, you can simply run it with
@@ -58,7 +49,7 @@ If you just want to test Continuwuity for a short time, you can use the `--rm`
flag, which cleans up everything related to your container after you stop flag, which cleans up everything related to your container after you stop
it. it.
### Docker Compose ### Docker-compose
If the `docker run` command is not suitable for you or your setup, you can also use one If the `docker run` command is not suitable for you or your setup, you can also use one
of the provided `docker-compose` files. of the provided `docker-compose` files.
@@ -167,19 +158,8 @@ docker buildx build --load --tag continuwuity:latest -f docker/Dockerfile .
# Example: Build for specific platforms and push to a registry. # Example: Build for specific platforms and push to a registry.
# docker buildx build --platform linux/amd64,linux/arm64 --tag registry.io/org/continuwuity:latest -f docker/Dockerfile . --push # docker buildx build --platform linux/amd64,linux/arm64 --tag registry.io/org/continuwuity:latest -f docker/Dockerfile . --push
# Example: Build binary optimised for the current CPU (standard release profile) # Example: Build binary optimized for the current CPU
# docker buildx build --load \ # docker buildx build --load --tag continuwuity:latest --build-arg TARGET_CPU=native -f docker/Dockerfile .
# --tag continuwuity:latest \
# --build-arg TARGET_CPU=native \
# -f docker/Dockerfile .
# Example: Build maxperf variant (release-max-perf profile with LTO)
# Optimised for runtime performance and smaller binary size, but requires longer build time
# docker buildx build --load \
# --tag continuwuity:latest-maxperf \
# --build-arg TARGET_CPU=native \
# --build-arg RUST_PROFILE=release-max-perf \
# -f docker/Dockerfile .
``` ```
Refer to the Docker Buildx documentation for more advanced build options. Refer to the Docker Buildx documentation for more advanced build options.
@@ -218,3 +198,5 @@ Alternatively, you can use Continuwuity's built-in delegation file capability. S
## Voice communication ## Voice communication
See the [TURN](../turn.md) page. See the [TURN](../turn.md) page.
[nix-buildlayeredimage]: https://ryantm.github.io/nixpkgs/builders/images/dockertools/#ssec-pkgs-dockerTools-buildLayeredImage
+18 -28
View File
@@ -8,39 +8,29 @@
## Installing Continuwuity ## Installing Continuwuity
### Prebuilt binary ### Static prebuilt binary
Download the binary for your architecture (x86_64 or aarch64) - You may simply download the binary that fits your machine architecture (x86_64
run the `uname -m` to check which you need. or aarch64). Run `uname -m` to see what you need.
Prebuilt binaries are available from: You can download prebuilt fully static musl binaries from the latest tagged
- **Tagged releases**: [Latest release page](https://forgejo.ellis.link/continuwuation/continuwuity/releases/latest) release [here](https://forgejo.ellis.link/continuwuation/continuwuity/releases/latest) or
- **Development builds**: CI artifacts from the `main` branch from the `main` CI branch workflow artifact output. These also include Debian/Ubuntu
(includes Debian/Ubuntu packages) packages.
When browsing CI artifacts, `ci-bins` contains binaries organised You can download these directly using curl. The `ci-bins` are CI workflow binaries organized by commit
by commit hash, while `releases` contains tagged versions. Sort hash/revision, and `releases` are tagged releases. Sort by descending last
by last modified date to find the most recent builds. modified date to find the latest.
The binaries require jemalloc and io_uring on the host system. Currently These binaries have jemalloc and io_uring statically linked and included with
we can't cross-build static binaries - contributions are welcome here. them, so no additional dynamic dependencies need to be installed.
#### Performance-optimised builds For the **best** performance: if you are using an `x86_64` CPU made in the last ~15 years,
we recommend using the `-haswell-` optimized binaries. These set
For x86_64 systems with CPUs from the last ~15 years, use the `-march=haswell`, which provides the most compatible and highest performance with
`-haswell-` optimised binaries for best performance. These optimized binaries. The database backend, RocksDB, benefits most from this as it
binaries enable hardware-accelerated CRC32 checksumming in uses hardware-accelerated CRC32 hashing/checksumming, which is critical
RocksDB, which significantly improves database performance. for performance.
The haswell instruction set provides an excellent balance of
compatibility and speed.
If you're using Docker instead, equivalent performance-optimised
images are available with the `-maxperf` suffix (e.g.
`forgejo.ellis.link/continuwuation/continuwuity:latest-maxperf`).
These images use the `release-max-perf`
build profile with
[link-time optimisation (LTO)](https://doc.rust-lang.org/cargo/reference/profiles.html#lto)
and, for amd64, target the haswell CPU architecture.
### Compiling ### Compiling
+2 -2
View File
@@ -128,7 +128,7 @@ Keep in mind the frequency that the log will be reached, and the relevancy to a
```rs ```rs
// Good // Good
error!( error!(
error = ?err, error = %err,
room_id = %room_id, room_id = %room_id,
"Failed to send event to room" "Failed to send event to room"
); );
@@ -264,7 +264,7 @@ pub async fn send_federation_request(
warn!( warn!(
destination = %destination, destination = %destination,
attempt = attempt, attempt = attempt,
error = ?err, error = %err,
retry_delay_ms = retry_delay.as_millis(), retry_delay_ms = retry_delay.as_millis(),
"Federation request failed, retrying" "Federation request failed, retrying"
); );
+1 -1
View File
@@ -8,7 +8,7 @@ This document contains the help content for the `continuwuity` command-line prog
## `continuwuity` ## `continuwuity`
A Matrix homeserver written in Rust, the official continuation of the conduwuit homeserver. a very cool Matrix chat homeserver written in Rust
**Usage:** `continuwuity [OPTIONS]` **Usage:** `continuwuity [OPTIONS]`
+2 -2
View File
@@ -4,7 +4,7 @@
Name: continuwuity Name: continuwuity
Version: {{{ git_repo_version }}} Version: {{{ git_repo_version }}}
Release: 1%{?dist} Release: 1%{?dist}
Summary: A Matrix homeserver written in Rust. Summary: Very cool Matrix chat homeserver written in Rust
License: Apache-2.0 AND MIT License: Apache-2.0 AND MIT
@@ -23,7 +23,7 @@ Requires: glibc
Requires: libstdc++ Requires: libstdc++
%global _description %{expand: %global _description %{expand:
A Matrix homeserver written in Rust, the official continuation of the conduwuit homeserver.} A cool hard fork of Conduit, a Matrix homeserver written in Rust}
%description %{_description} %description %{_description}
+2
View File
@@ -1,7 +1,9 @@
[package] [package]
name = "conduwuit_admin" name = "conduwuit_admin"
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
+8 -36
View File
@@ -2,17 +2,10 @@ use clap::Parser;
use conduwuit::Result; use conduwuit::Result;
use crate::{ use crate::{
appservice::{self, AppserviceCommand}, appservice, appservice::AppserviceCommand, check, check::CheckCommand, context::Context,
check::{self, CheckCommand}, debug, debug::DebugCommand, federation, federation::FederationCommand, media,
context::Context, media::MediaCommand, query, query::QueryCommand, room, room::RoomCommand, server,
debug::{self, DebugCommand}, server::ServerCommand, user, user::UserCommand,
federation::{self, FederationCommand},
media::{self, MediaCommand},
query::{self, QueryCommand},
room::{self, RoomCommand},
server::{self, ServerCommand},
token::{self, TokenCommand},
user::{self, UserCommand},
}; };
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
@@ -26,10 +19,6 @@ pub enum AdminCommand {
/// - Commands for managing local users /// - Commands for managing local users
Users(UserCommand), Users(UserCommand),
#[command(subcommand)]
/// - Commands for managing registration tokens
Token(TokenCommand),
#[command(subcommand)] #[command(subcommand)]
/// - Commands for managing rooms /// - Commands for managing rooms
Rooms(RoomCommand), Rooms(RoomCommand),
@@ -59,36 +48,19 @@ pub enum AdminCommand {
Query(QueryCommand), Query(QueryCommand),
} }
#[tracing::instrument(skip_all, name = "command", level = "info")] #[tracing::instrument(skip_all, name = "command")]
pub(super) async fn process(command: AdminCommand, context: &Context<'_>) -> Result { pub(super) async fn process(command: AdminCommand, context: &Context<'_>) -> Result {
use AdminCommand::*; use AdminCommand::*;
match command { match command {
| Appservices(command) => { | Appservices(command) => appservice::process(command, context).await,
// appservice commands are all restricted
context.bail_restricted()?;
appservice::process(command, context).await
},
| Media(command) => media::process(command, context).await, | Media(command) => media::process(command, context).await,
| Users(command) => { | Users(command) => user::process(command, context).await,
// user commands are all restricted
context.bail_restricted()?;
user::process(command, context).await
},
| Token(command) => {
// token commands are all restricted
context.bail_restricted()?;
token::process(command, context).await
},
| Rooms(command) => room::process(command, context).await, | Rooms(command) => room::process(command, context).await,
| Federation(command) => federation::process(command, context).await, | Federation(command) => federation::process(command, context).await,
| Server(command) => server::process(command, context).await, | Server(command) => server::process(command, context).await,
| Debug(command) => debug::process(command, context).await, | Debug(command) => debug::process(command, context).await,
| Query(command) => { | Query(command) => query::process(command, context).await,
// query commands are all restricted
context.bail_restricted()?;
query::process(command, context).await
},
| Check(command) => check::process(command, context).await, | Check(command) => check::process(command, context).await,
} }
} }
+1 -21
View File
@@ -1,6 +1,6 @@
use std::{fmt, time::SystemTime}; use std::{fmt, time::SystemTime};
use conduwuit::{Err, Result}; use conduwuit::Result;
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::{ use futures::{
Future, FutureExt, TryFutureExt, Future, FutureExt, TryFutureExt,
@@ -8,7 +8,6 @@ use futures::{
lock::Mutex, lock::Mutex,
}; };
use ruma::{EventId, UserId}; use ruma::{EventId, UserId};
use service::admin::InvocationSource;
pub(crate) struct Context<'a> { pub(crate) struct Context<'a> {
pub(crate) services: &'a Services, pub(crate) services: &'a Services,
@@ -17,7 +16,6 @@ pub(crate) struct Context<'a> {
pub(crate) reply_id: Option<&'a EventId>, pub(crate) reply_id: Option<&'a EventId>,
pub(crate) sender: Option<&'a UserId>, pub(crate) sender: Option<&'a UserId>,
pub(crate) output: Mutex<BufWriter<Vec<u8>>>, pub(crate) output: Mutex<BufWriter<Vec<u8>>>,
pub(crate) source: InvocationSource,
} }
impl Context<'_> { impl Context<'_> {
@@ -45,22 +43,4 @@ impl Context<'_> {
self.sender self.sender
.unwrap_or_else(|| self.services.globals.server_user.as_ref()) .unwrap_or_else(|| self.services.globals.server_user.as_ref())
} }
/// Returns an Err if the [`Self::source`] of this context does not allow
/// restricted commands to be executed.
///
/// This is intended to be placed at the start of restricted commands'
/// implementations, like so:
///
/// ```ignore
/// self.bail_restricted()?;
/// // actual command impl
/// ```
pub(crate) fn bail_restricted(&self) -> Result {
if self.source.allows_restricted() {
Ok(())
} else {
Err!("This command can only be used in the admin room.")
}
}
} }
+24 -11
View File
@@ -291,8 +291,6 @@ pub(super) async fn get_remote_pdu(
#[admin_command] #[admin_command]
pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result { pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?; let room_id = self.services.rooms.alias.resolve(&room).await?;
let room_state: Vec<Raw<AnyStateEvent>> = self let room_state: Vec<Raw<AnyStateEvent>> = self
.services .services
@@ -419,6 +417,27 @@ pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool)
Err!("No log level was specified.") Err!("No log level was specified.")
} }
#[admin_command]
pub(super) async fn sign_json(&self) -> 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.");
}
let string = self.body[1..self.body.len().checked_sub(1).unwrap()].join("\n");
match serde_json::from_str(&string) {
| Err(e) => return Err!("Invalid json: {e}"),
| Ok(mut value) => {
self.services.server_keys.sign_json(&mut value)?;
let json_text = serde_json::to_string_pretty(&value)?;
write!(self, "{json_text}")
},
}
.await
}
#[admin_command] #[admin_command]
pub(super) async fn verify_json(&self) -> Result { pub(super) async fn verify_json(&self) -> Result {
if self.body.len() < 2 if self.body.len() < 2
@@ -456,10 +475,8 @@ pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result {
} }
#[admin_command] #[admin_command]
#[tracing::instrument(skip(self), level = "info")] #[tracing::instrument(skip(self))]
pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
if !self if !self
.services .services
.rooms .rooms
@@ -483,10 +500,8 @@ pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
} }
#[admin_command] #[admin_command]
#[tracing::instrument(skip(self), level = "info")] #[tracing::instrument(skip(self))]
pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
if !self if !self
.services .services
.rooms .rooms
@@ -510,15 +525,13 @@ pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
} }
#[admin_command] #[admin_command]
#[tracing::instrument(skip(self), level = "info")] #[tracing::instrument(skip(self))]
pub(super) async fn force_set_room_state_from_server( pub(super) async fn force_set_room_state_from_server(
&self, &self,
room_id: OwnedRoomId, room_id: OwnedRoomId,
server_name: OwnedServerName, server_name: OwnedServerName,
at_event: Option<OwnedEventId>, at_event: Option<OwnedEventId>,
) -> Result { ) -> Result {
self.bail_restricted()?;
if !self if !self
.services .services
.rooms .rooms
+9 -3
View File
@@ -47,9 +47,9 @@ pub enum DebugCommand {
shorteventid: ShortEventId, shorteventid: ShortEventId,
}, },
/// - Attempts to retrieve a PDU from a remote server. **Does not** insert /// - Attempts to retrieve a PDU from a remote server. Inserts it into our
/// it into the database /// database/timeline if found and we do not have this PDU already
/// or persist it anywhere. /// (following normal event auth rules, handles it as an incoming PDU).
GetRemotePdu { GetRemotePdu {
/// An event ID (a $ followed by the base64 reference hash) /// An event ID (a $ followed by the base64 reference hash)
event_id: OwnedEventId, event_id: OwnedEventId,
@@ -125,6 +125,12 @@ pub enum DebugCommand {
reset: bool, reset: bool,
}, },
/// - Sign JSON blob
///
/// This command needs a JSON blob provided in a Markdown code block below
/// the command.
SignJson,
/// - Verify JSON signatures /// - Verify JSON signatures
/// ///
/// This command needs a JSON blob provided in a Markdown code block below /// This command needs a JSON blob provided in a Markdown code block below
-2
View File
@@ -8,14 +8,12 @@ use crate::{admin_command, get_room_info};
#[admin_command] #[admin_command]
pub(super) async fn disable_room(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn disable_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
self.services.rooms.metadata.disable_room(&room_id, true); self.services.rooms.metadata.disable_room(&room_id, true);
self.write_str("Room disabled.").await self.write_str("Room disabled.").await
} }
#[admin_command] #[admin_command]
pub(super) async fn enable_room(&self, room_id: OwnedRoomId) -> Result { pub(super) async fn enable_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
self.services.rooms.metadata.disable_room(&room_id, false); self.services.rooms.metadata.disable_room(&room_id, false);
self.write_str("Room enabled.").await self.write_str("Room enabled.").await
} }
-8
View File
@@ -16,8 +16,6 @@ pub(super) async fn delete(
mxc: Option<OwnedMxcUri>, mxc: Option<OwnedMxcUri>,
event_id: Option<OwnedEventId>, event_id: Option<OwnedEventId>,
) -> Result { ) -> Result {
self.bail_restricted()?;
if event_id.is_some() && mxc.is_some() { if event_id.is_some() && mxc.is_some() {
return Err!("Please specify either an MXC or an event ID, not both.",); return Err!("Please specify either an MXC or an event ID, not both.",);
} }
@@ -178,8 +176,6 @@ pub(super) async fn delete(
#[admin_command] #[admin_command]
pub(super) async fn delete_list(&self) -> Result { pub(super) async fn delete_list(&self) -> Result {
self.bail_restricted()?;
if self.body.len() < 2 if self.body.len() < 2
|| !self.body[0].trim().starts_with("```") || !self.body[0].trim().starts_with("```")
|| self.body.last().unwrap_or(&"").trim() != "```" || self.body.last().unwrap_or(&"").trim() != "```"
@@ -235,8 +231,6 @@ pub(super) async fn delete_past_remote_media(
after: bool, after: bool,
yes_i_want_to_delete_local_media: bool, yes_i_want_to_delete_local_media: bool,
) -> Result { ) -> Result {
self.bail_restricted()?;
if before && after { if before && after {
return Err!("Please only pick one argument, --before or --after.",); return Err!("Please only pick one argument, --before or --after.",);
} }
@@ -279,8 +273,6 @@ pub(super) async fn delete_all_from_server(
server_name: OwnedServerName, server_name: OwnedServerName,
yes_i_want_to_delete_local_media: bool, yes_i_want_to_delete_local_media: bool,
) -> Result { ) -> Result {
self.bail_restricted()?;
if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media { if server_name == self.services.globals.server_name() && !yes_i_want_to_delete_local_media {
return Err!("This command only works for remote media by default.",); return Err!("This command only works for remote media by default.",);
} }
-1
View File
@@ -17,7 +17,6 @@ pub(crate) mod media;
pub(crate) mod query; pub(crate) mod query;
pub(crate) mod room; pub(crate) mod room;
pub(crate) mod server; pub(crate) mod server;
pub(crate) mod token;
pub(crate) mod user; pub(crate) mod user;
extern crate conduwuit_api as api; extern crate conduwuit_api as api;
+1 -2
View File
@@ -37,7 +37,7 @@ pub(super) fn dispatch(services: Arc<Services>, command: CommandInput) -> Proces
Box::pin(handle_command(services, command)) Box::pin(handle_command(services, command))
} }
#[tracing::instrument(skip_all, name = "admin", level = "info")] #[tracing::instrument(skip_all, name = "admin")]
async fn handle_command(services: Arc<Services>, command: CommandInput) -> ProcessorResult { async fn handle_command(services: Arc<Services>, command: CommandInput) -> ProcessorResult {
AssertUnwindSafe(Box::pin(process_command(services, &command))) AssertUnwindSafe(Box::pin(process_command(services, &command)))
.catch_unwind() .catch_unwind()
@@ -59,7 +59,6 @@ async fn process_command(services: Arc<Services>, input: &CommandInput) -> Proce
reply_id: input.reply_id.as_deref(), reply_id: input.reply_id.as_deref(),
sender: input.sender.as_deref(), sender: input.sender.as_deref(),
output: BufWriter::new(Vec::new()).into(), output: BufWriter::new(Vec::new()).into(),
source: input.source,
}; };
let (result, mut logs) = process(&context, command, &args).await; let (result, mut logs) = process(&context, command, &args).await;
+3 -3
View File
@@ -98,7 +98,7 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result {
{ {
| Ok((room_id, servers)) => { | Ok((room_id, servers)) => {
debug!( debug!(
%room_id, ?room_id,
?servers, ?servers,
"Got federation response fetching room ID for room {room}" "Got federation response fetching room ID for room {room}"
); );
@@ -240,7 +240,7 @@ async fn ban_list_of_rooms(&self) -> Result {
{ {
| Ok((room_id, servers)) => { | Ok((room_id, servers)) => {
debug!( debug!(
%room_id, ?room_id,
?servers, ?servers,
"Got federation response fetching room ID for \ "Got federation response fetching room ID for \
{room}", {room}",
@@ -397,7 +397,7 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result {
{ {
| Ok((room_id, servers)) => { | Ok((room_id, servers)) => {
debug!( debug!(
%room_id, ?room_id,
?servers, ?servers,
"Got federation response fetching room ID for room {room}" "Got federation response fetching room ID for room {room}"
); );
-8
View File
@@ -24,8 +24,6 @@ pub(super) async fn uptime(&self) -> Result {
#[admin_command] #[admin_command]
pub(super) async fn show_config(&self) -> Result { pub(super) async fn show_config(&self) -> Result {
self.bail_restricted()?;
self.write_str(&format!("{}", *self.services.server.config)) self.write_str(&format!("{}", *self.services.server.config))
.await .await
} }
@@ -120,8 +118,6 @@ pub(super) async fn list_backups(&self) -> Result {
#[admin_command] #[admin_command]
pub(super) async fn backup_database(&self) -> Result { pub(super) async fn backup_database(&self) -> Result {
self.bail_restricted()?;
let db = Arc::clone(&self.services.db); let db = Arc::clone(&self.services.db);
let result = self let result = self
.services .services
@@ -148,8 +144,6 @@ pub(super) async fn admin_notice(&self, message: Vec<String>) -> Result {
#[admin_command] #[admin_command]
pub(super) async fn reload_mods(&self) -> Result { pub(super) async fn reload_mods(&self) -> Result {
self.bail_restricted()?;
self.services.server.reload()?; self.services.server.reload()?;
self.write_str("Reloading server...").await self.write_str("Reloading server...").await
@@ -174,8 +168,6 @@ pub(super) async fn restart(&self, force: bool) -> Result {
#[admin_command] #[admin_command]
pub(super) async fn shutdown(&self) -> Result { pub(super) async fn shutdown(&self) -> Result {
self.bail_restricted()?;
warn!("shutdown command"); warn!("shutdown command");
self.services.server.shutdown()?; self.services.server.shutdown()?;
-76
View File
@@ -1,76 +0,0 @@
use conduwuit::{Err, Result, utils};
use conduwuit_macros::admin_command;
use futures::StreamExt;
use service::registration_tokens::TokenExpires;
#[admin_command]
pub(super) async fn issue_token(&self, expires: super::TokenExpires) -> Result {
let expires = {
if expires.immortal {
None
} else if let Some(max_uses) = expires.max_uses {
Some(TokenExpires::AfterUses(max_uses))
} else if expires.once {
Some(TokenExpires::AfterUses(1))
} else if let Some(max_age) = expires
.max_age
.as_deref()
.map(|max_age| utils::time::timepoint_from_now(utils::time::parse_duration(max_age)?))
.transpose()?
{
Some(TokenExpires::AfterTime(max_age))
} else {
unreachable!();
}
};
let (token, info) = self
.services
.registration_tokens
.issue_token(self.sender_or_service_user().into(), expires);
self.write_str(&format!(
"New registration token issued: `{token}`. {}.",
if let Some(expires) = info.expires {
format!("{expires}")
} else {
"Never expires".to_owned()
}
))
.await
}
#[admin_command]
pub(super) async fn revoke_token(&self, token: String) -> Result {
let Some(token) = self
.services
.registration_tokens
.validate_token(token)
.await
else {
return Err!("This token does not exist or has already expired.");
};
self.services.registration_tokens.revoke_token(token)?;
self.write_str("Token revoked successfully.").await
}
#[admin_command]
pub(super) async fn list_tokens(&self) -> Result {
let tokens: Vec<_> = self
.services
.registration_tokens
.iterate_tokens()
.collect()
.await;
self.write_str(&format!("Found {} registration tokens:\n", tokens.len()))
.await?;
for token in tokens {
self.write_str(&format!("- {token}\n")).await?;
}
Ok(())
}
-51
View File
@@ -1,51 +0,0 @@
mod commands;
use clap::{Args, Subcommand};
use conduwuit::Result;
use crate::admin_command_dispatch;
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum TokenCommand {
/// - Issue a new registration token
#[clap(name = "issue")]
IssueToken {
/// When this token will expire.
#[command(flatten)]
expires: TokenExpires,
},
/// - Revoke a registration token
#[clap(name = "revoke")]
RevokeToken {
/// The token to revoke.
token: String,
},
/// - List all registration tokens
#[clap(name = "list")]
ListTokens,
}
#[derive(Debug, Args)]
#[group(required = true, multiple = false)]
pub struct TokenExpires {
/// The maximum number of times this token is allowed to be used before it
/// expires.
#[arg(long)]
max_uses: Option<u64>,
/// The maximum age of this token (e.g. 30s, 5m, 7d). It will expire after
/// this much time has passed.
#[arg(long)]
max_age: Option<String>,
/// This token will never expire.
#[arg(long)]
immortal: bool,
/// A shortcut for `--max-uses 1`.
#[arg(long)]
once: bool,
}
+26 -140
View File
@@ -238,7 +238,6 @@ pub(super) async fn deactivate(&self, no_leave_rooms: bool, user_id: String) ->
#[admin_command] #[admin_command]
pub(super) async fn suspend(&self, user_id: String) -> Result { pub(super) async fn suspend(&self, user_id: String) -> Result {
self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
if user_id == self.services.globals.server_user { if user_id == self.services.globals.server_user {
@@ -263,7 +262,6 @@ pub(super) async fn suspend(&self, user_id: String) -> Result {
#[admin_command] #[admin_command]
pub(super) async fn unsuspend(&self, user_id: String) -> Result { pub(super) async fn unsuspend(&self, user_id: String) -> Result {
self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?; let user_id = parse_local_user_id(self.services, &user_id)?;
if user_id == self.services.globals.server_user { if user_id == self.services.globals.server_user {
@@ -280,12 +278,7 @@ pub(super) async fn unsuspend(&self, user_id: String) -> Result {
} }
#[admin_command] #[admin_command]
pub(super) async fn reset_password( pub(super) async fn reset_password(&self, username: String, password: Option<String>) -> Result {
&self,
logout: bool,
username: String,
password: Option<String>,
) -> Result {
let user_id = parse_local_user_id(self.services, &username)?; let user_id = parse_local_user_id(self.services, &username)?;
if user_id == self.services.globals.server_user { if user_id == self.services.globals.server_user {
@@ -308,18 +301,7 @@ pub(super) async fn reset_password(
write!(self, "Successfully reset the password for user {user_id}: `{new_password}`") write!(self, "Successfully reset the password for user {user_id}: `{new_password}`")
}, },
} }
.await?; .await
if logout {
self.services
.users
.all_device_ids(&user_id)
.for_each(|device_id| self.services.users.remove_device(&user_id, device_id))
.await;
write!(self, "\nAll existing sessions have been logged out.").await?;
}
Ok(())
} }
#[admin_command] #[admin_command]
@@ -479,11 +461,9 @@ pub(super) async fn force_join_list_of_local_users(
); );
} }
let server_admins = self.services.admin.get_admins().await; let Ok(admin_room) = self.services.admin.get_admin_room().await else {
return Err!("There is not an admin room to check for server admins.",);
if server_admins.is_empty() { };
return Err!("There are no admins set for this server.");
}
let (room_id, servers) = self let (room_id, servers) = self
.services .services
@@ -502,6 +482,15 @@ pub(super) async fn force_join_list_of_local_users(
return Err!("We are not joined in this room."); return Err!("We are not joined in this room.");
} }
let server_admins: Vec<_> = self
.services
.rooms
.state_cache
.active_local_users_in_room(&admin_room)
.map(ToOwned::to_owned)
.collect()
.await;
if !self if !self
.services .services
.rooms .rooms
@@ -594,11 +583,9 @@ pub(super) async fn force_join_all_local_users(
); );
} }
let server_admins = self.services.admin.get_admins().await; let Ok(admin_room) = self.services.admin.get_admin_room().await else {
return Err!("There is not an admin room to check for server admins.",);
if server_admins.is_empty() { };
return Err!("There are no admins set for this server.");
}
let (room_id, servers) = self let (room_id, servers) = self
.services .services
@@ -617,6 +604,15 @@ pub(super) async fn force_join_all_local_users(
return Err!("We are not joined in this room."); return Err!("We are not joined in this room.");
} }
let server_admins: Vec<_> = self
.services
.rooms
.state_cache
.active_local_users_in_room(&admin_room)
.map(ToOwned::to_owned)
.collect()
.await;
if !self if !self
.services .services
.rooms .rooms
@@ -992,113 +988,3 @@ pub(super) async fn force_leave_remote_room(
self.write_str(&format!("{user_id} successfully left {room_id} via remote server.")) self.write_str(&format!("{user_id} successfully left {room_id} via remote server."))
.await .await
} }
#[admin_command]
pub(super) async fn lock(&self, user_id: String) -> Result {
self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
if user_id == self.services.globals.server_user {
return Err!("Not allowed to lock the server service account.",);
}
if !self.services.users.exists(&user_id).await {
return Err!("User {user_id} does not exist.");
}
if self.services.users.is_admin(&user_id).await {
return Err!("Admin users cannot be locked.");
}
self.services
.users
.lock_account(&user_id, self.sender_or_service_user())
.await;
self.write_str(&format!("User {user_id} has been locked."))
.await
}
#[admin_command]
pub(super) async fn unlock(&self, user_id: String) -> Result {
self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
self.services.users.unlock_account(&user_id).await;
self.write_str(&format!("User {user_id} has been unlocked."))
.await
}
#[admin_command]
pub(super) async fn logout(&self, user_id: String) -> Result {
self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
if user_id == self.services.globals.server_user {
return Err!("Not allowed to log out the server service account.",);
}
if !self.services.users.exists(&user_id).await {
return Err!("User {user_id} does not exist.");
}
if self.services.users.is_admin(&user_id).await {
return Err!("You cannot forcefully log out admin users.");
}
self.services
.users
.all_device_ids(&user_id)
.for_each(|device_id| self.services.users.remove_device(&user_id, device_id))
.await;
self.write_str(&format!("User {user_id} has been logged out from all devices."))
.await
}
#[admin_command]
pub(super) async fn disable_login(&self, user_id: String) -> Result {
self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
if user_id == self.services.globals.server_user {
return Err!("Not allowed to disable login for the server service account.",);
}
if !self.services.users.exists(&user_id).await {
return Err!("User {user_id} does not exist.");
}
if self.services.users.is_admin(&user_id).await {
return Err!("Admin users cannot have their login disallowed.");
}
self.services.users.disable_login(&user_id);
self.write_str(&format!(
"{user_id} can no longer log in. Their existing sessions remain unaffected."
))
.await
}
#[admin_command]
pub(super) async fn enable_login(&self, user_id: String) -> Result {
self.bail_restricted()?;
let user_id = parse_local_user_id(self.services, &user_id)?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
if !self.services.users.exists(&user_id).await {
return Err!("User {user_id} does not exist.");
}
self.services.users.enable_login(&user_id);
self.write_str(&format!("{user_id} can now log in.")).await
}
-51
View File
@@ -20,9 +20,6 @@ pub enum UserCommand {
/// - Reset user password /// - Reset user password
ResetPassword { ResetPassword {
/// Log out existing sessions
#[arg(short, long)]
logout: bool,
/// Username of the user for whom the password should be reset /// Username of the user for whom the password should be reset
username: String, username: String,
/// New password for the user, if unspecified one is generated /// New password for the user, if unspecified one is generated
@@ -62,18 +59,6 @@ pub enum UserCommand {
force: bool, force: bool,
}, },
/// - Forcefully log a user out of all of their devices.
///
/// This will invalidate all access tokens for the specified user,
/// effectively logging them out from all sessions.
/// Note that this is destructive and may result in data loss for the user,
/// such as encryption keys. Use with caution. Can only be used in the admin
/// room.
Logout {
/// Username of the user to log out
user_id: String,
},
/// - Suspend a user /// - Suspend a user
/// ///
/// Suspended users are able to log in, sync, and read messages, but are not /// Suspended users are able to log in, sync, and read messages, but are not
@@ -96,42 +81,6 @@ pub enum UserCommand {
user_id: String, user_id: String,
}, },
/// - Lock a user
///
/// Locked users are unable to use their accounts beyond logging out. This
/// is akin to a temporary deactivation that does not change the user's
/// password. This can be used to quickly prevent a user from accessing
/// their account.
Lock {
/// Username of the user to lock
user_id: String,
},
/// - Unlock a user
///
/// Reverses the effects of the `lock` command, allowing the user to use
/// their account again.
Unlock {
/// Username of the user to unlock
user_id: String,
},
/// - Enable login for a user
EnableLogin {
/// Username of the user to enable login for
user_id: String,
},
/// - Disable login for a user
///
/// Disables login for the specified user without deactivating or locking
/// their account. This prevents the user from obtaining new access tokens,
/// but does not invalidate existing sessions.
DisableLogin {
/// Username of the user to disable login for
user_id: String,
},
/// - List local users in the database /// - List local users in the database
#[clap(alias = "list")] #[clap(alias = "list")]
ListUsers, ListUsers,
+2
View File
@@ -1,7 +1,9 @@
[package] [package]
name = "conduwuit_api" name = "conduwuit_api"
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
+17 -43
View File
@@ -49,7 +49,7 @@ const RANDOM_USER_ID_LENGTH: usize = 10;
/// ///
/// Note: This will not reserve the username, so the username might become /// Note: This will not reserve the username, so the username might become
/// invalid when trying to register /// invalid when trying to register
#[tracing::instrument(skip_all, fields(%client), name = "register_available", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "register_available")]
pub(crate) async fn get_register_available_route( pub(crate) async fn get_register_available_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -138,7 +138,7 @@ pub(crate) async fn get_register_available_route(
/// - If `inhibit_login` is false: Creates a device and returns device id and /// - If `inhibit_login` is false: Creates a device and returns device id and
/// access_token /// access_token
#[allow(clippy::doc_markdown)] #[allow(clippy::doc_markdown)]
#[tracing::instrument(skip_all, fields(%client), name = "register", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "register")]
pub(crate) async fn register_route( pub(crate) async fn register_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -179,18 +179,13 @@ pub(crate) async fn register_route(
}, },
} }
return Err!(Request(Forbidden( return Err!(Request(Forbidden("Registration has been disabled.")));
"This server is not accepting registrations at this time."
)));
} }
if is_guest if is_guest
&& (!services.config.allow_guest_registration && (!services.config.allow_guest_registration
|| (services.config.allow_registration || (services.config.allow_registration
&& services && services.globals.registration_token.is_some()))
.registration_tokens
.get_config_file_token()
.is_some()))
{ {
info!( info!(
"Guest registration disabled / registration enabled with token configured, \ "Guest registration disabled / registration enabled with token configured, \
@@ -208,9 +203,7 @@ pub(crate) async fn register_route(
rejecting registration. Guest's initial device name: \"{}\"", rejecting registration. Guest's initial device name: \"{}\"",
body.initial_device_display_name.as_deref().unwrap_or("") body.initial_device_display_name.as_deref().unwrap_or("")
); );
return Err!(Request(Forbidden( return Err!(Request(Forbidden("Registration is temporarily disabled.")));
"This server is not accepting registrations at this time."
)));
} }
let user_id = match (body.username.as_ref(), is_guest) { let user_id = match (body.username.as_ref(), is_guest) {
@@ -308,13 +301,7 @@ pub(crate) async fn register_route(
let skip_auth = body.appservice_info.is_some() || is_guest; let skip_auth = body.appservice_info.is_some() || is_guest;
// Populate required UIAA flows // Populate required UIAA flows
if services if services.globals.registration_token.is_some() {
.registration_tokens
.iterate_tokens()
.next()
.await
.is_some()
{
// Registration token required // Registration token required
uiaainfo.flows.push(AuthFlow { uiaainfo.flows.push(AuthFlow {
stages: vec![AuthType::RegistrationToken], stages: vec![AuthType::RegistrationToken],
@@ -336,19 +323,7 @@ pub(crate) async fn register_route(
} }
if uiaainfo.flows.is_empty() && !skip_auth { if uiaainfo.flows.is_empty() && !skip_auth {
// Registration isn't _disabled_, but there's no captcha configured and no // No registration token necessary, but clients must still go through the flow
// registration tokens currently set. Bail out by default unless open
// registration was explicitly enabled.
if !services
.config
.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
{
return Err!(Request(Forbidden(
"This server is not accepting registrations at this time."
)));
}
// We have open registration enabled (😧), provide a dummy stage
uiaainfo = UiaaInfo { uiaainfo = UiaaInfo {
flows: vec![AuthFlow { stages: vec![AuthType::Dummy] }], flows: vec![AuthFlow { stages: vec![AuthType::Dummy] }],
completed: Vec::new(), completed: Vec::new(),
@@ -628,7 +603,7 @@ pub(crate) async fn register_route(
/// last seen ts) /// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
#[tracing::instrument(skip_all, fields(%client), name = "change_password", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "change_password")]
pub(crate) async fn change_password_route( pub(crate) async fn change_password_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -752,7 +727,7 @@ pub(crate) async fn whoami_route(
/// - Forgets all to-device events /// - Forgets all to-device events
/// - Triggers device list updates /// - Triggers device list updates
/// - Removes ability to log in again /// - Removes ability to log in again
#[tracing::instrument(skip_all, fields(%client), name = "deactivate", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "deactivate")]
pub(crate) async fn deactivate_route( pub(crate) async fn deactivate_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -871,20 +846,19 @@ pub(crate) async fn request_3pid_management_token_via_msisdn_route(
/// # `GET /_matrix/client/v1/register/m.login.registration_token/validity` /// # `GET /_matrix/client/v1/register/m.login.registration_token/validity`
/// ///
/// Checks if the provided registration token is valid at the time of checking. /// Checks if the provided registration token is valid at the time of checking
///
/// Currently does not have any ratelimiting, and this isn't very practical as
/// there is only one registration token allowed.
pub(crate) async fn check_registration_token_validity( pub(crate) async fn check_registration_token_validity(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<check_registration_token_validity::v1::Request>, body: Ruma<check_registration_token_validity::v1::Request>,
) -> Result<check_registration_token_validity::v1::Response> { ) -> Result<check_registration_token_validity::v1::Response> {
// TODO: ratelimit this pretty heavily let Some(reg_token) = services.globals.registration_token.clone() else {
return Err!(Request(Forbidden("Server does not allow token registration")));
};
let valid = services Ok(check_registration_token_validity::v1::Response { valid: reg_token == body.token })
.registration_tokens
.validate_token(body.token.clone())
.await
.is_some();
Ok(check_registration_token_validity::v1::Response { valid })
} }
/// Runs through all the deactivation steps: /// Runs through all the deactivation steps:
+1 -1
View File
@@ -102,7 +102,7 @@ pub(crate) async fn get_alias_route(
}; };
let servers = room_available_servers(&services, &room_id, &room_alias, servers).await; let servers = room_available_servers(&services, &room_id, &room_alias, servers).await;
debug!(%room_alias, %room_id, "available servers: {servers:?}"); debug!(?room_alias, ?room_id, "available servers: {servers:?}");
Ok(get_alias::v3::Response::new(room_id, servers)) Ok(get_alias::v3::Response::new(room_id, servers))
} }
+1 -1
View File
@@ -74,7 +74,7 @@ pub(crate) async fn get_context_route(
} }
if !visible { if !visible {
debug_warn!(req_evt = %event_id, ?base_id, %room_id, "Event requested by {sender_user} but is not allowed to see it, returning 404"); debug_warn!(req_evt = ?event_id, ?base_id, ?room_id, "Event requested by {sender_user} but is not allowed to see it, returning 404");
return Err!(Request(NotFound("Event not found."))); return Err!(Request(NotFound("Event not found.")));
} }
+1 -1
View File
@@ -49,7 +49,7 @@ pub(crate) async fn get_device_route(
/// # `PUT /_matrix/client/r0/devices/{deviceId}` /// # `PUT /_matrix/client/r0/devices/{deviceId}`
/// ///
/// Updates the metadata on a given device of the sender user. /// Updates the metadata on a given device of the sender user.
#[tracing::instrument(skip_all, fields(%client), name = "update_device", level = "debug")] #[tracing::instrument(skip_all, fields(%client), name = "update_device")]
pub(crate) async fn update_device_route( pub(crate) async fn update_device_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
+3 -3
View File
@@ -44,7 +44,7 @@ use crate::Ruma;
/// Lists the public rooms on this server. /// Lists the public rooms on this server.
/// ///
/// - Rooms are ordered by the number of joined members /// - Rooms are ordered by the number of joined members
#[tracing::instrument(skip_all, fields(%client), name = "publicrooms", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "publicrooms")]
pub(crate) async fn get_public_rooms_filtered_route( pub(crate) async fn get_public_rooms_filtered_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -80,7 +80,7 @@ pub(crate) async fn get_public_rooms_filtered_route(
/// Lists the public rooms on this server. /// Lists the public rooms on this server.
/// ///
/// - Rooms are ordered by the number of joined members /// - Rooms are ordered by the number of joined members
#[tracing::instrument(skip_all, fields(%client), name = "publicrooms", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "publicrooms")]
pub(crate) async fn get_public_rooms_route( pub(crate) async fn get_public_rooms_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -116,7 +116,7 @@ pub(crate) async fn get_public_rooms_route(
/// # `PUT /_matrix/client/r0/directory/list/room/{roomId}` /// # `PUT /_matrix/client/r0/directory/list/room/{roomId}`
/// ///
/// Sets the visibility of a given room in the room directory. /// Sets the visibility of a given room in the room directory.
#[tracing::instrument(skip_all, fields(%client), name = "room_directory", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "room_directory")]
pub(crate) async fn set_room_visibility_route( pub(crate) async fn set_room_visibility_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
+32 -61
View File
@@ -1,15 +1,7 @@
use std::{ use std::collections::{BTreeMap, HashMap, HashSet};
collections::{BTreeMap, HashMap, HashSet},
time::Duration,
};
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{Err, Error, Result, debug, debug_warn, err, result::NotFound, utils};
Err, Error, Result, debug, debug_warn, err,
result::NotFound,
utils,
utils::{IterStream, stream::WidebandExt},
};
use conduwuit_service::{Services, users::parse_master_key}; use conduwuit_service::{Services, users::parse_master_key};
use futures::{StreamExt, stream::FuturesUnordered}; use futures::{StreamExt, stream::FuturesUnordered};
use ruma::{ use ruma::{
@@ -52,7 +44,7 @@ pub(crate) async fn upload_keys_route(
.deserialize() .deserialize()
.inspect_err(|e| { .inspect_err(|e| {
debug_warn!( debug_warn!(
%key_id, ?key_id,
?one_time_key, ?one_time_key,
"Invalid one time key JSON submitted by client, skipping: {e}" "Invalid one time key JSON submitted by client, skipping: {e}"
); );
@@ -94,8 +86,8 @@ pub(crate) async fn upload_keys_route(
{ {
if existing_keys.json().get() == device_keys.json().get() { if existing_keys.json().get() == device_keys.json().get() {
debug!( debug!(
%sender_user, ?sender_user,
%sender_device, ?sender_device,
?device_keys, ?device_keys,
"Ignoring user uploaded keys as they are an exact copy already in the \ "Ignoring user uploaded keys as they are an exact copy already in the \
database" database"
@@ -142,7 +134,6 @@ pub(crate) async fn get_keys_route(
&body.device_keys, &body.device_keys,
|u| u == sender_user, |u| u == sender_user,
true, // Always allow local users to see device names of other local users true, // Always allow local users to see device names of other local users
body.timeout.unwrap_or(Duration::from_secs(10)),
) )
.await .await
} }
@@ -154,12 +145,7 @@ pub(crate) async fn claim_keys_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<claim_keys::v3::Request>, body: Ruma<claim_keys::v3::Request>,
) -> Result<claim_keys::v3::Response> { ) -> Result<claim_keys::v3::Response> {
claim_keys_helper( claim_keys_helper(&services, &body.one_time_keys).await
&services,
&body.one_time_keys,
body.timeout.unwrap_or(Duration::from_secs(10)),
)
.await
} }
/// # `POST /_matrix/client/r0/keys/device_signing/upload` /// # `POST /_matrix/client/r0/keys/device_signing/upload`
@@ -338,7 +324,7 @@ pub(crate) async fn upload_signatures_route(
for (user_id, keys) in &body.signed_keys { for (user_id, keys) in &body.signed_keys {
for (key_id, key) in keys { for (key_id, key) in keys {
let Ok(key) = serde_json::to_value(key) let Ok(key) = serde_json::to_value(key)
.inspect_err(|e| debug_warn!(%key_id, "Invalid \"key\" JSON: {e}")) .inspect_err(|e| debug_warn!(?key_id, "Invalid \"key\" JSON: {e}"))
else { else {
continue; continue;
}; };
@@ -435,7 +421,6 @@ pub(crate) async fn get_keys_helper<F>(
device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>, device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
allowed_signatures: F, allowed_signatures: F,
include_display_names: bool, include_display_names: bool,
timeout: Duration,
) -> Result<get_keys::v3::Response> ) -> Result<get_keys::v3::Response>
where where
F: Fn(&UserId) -> bool + Send + Sync, F: Fn(&UserId) -> bool + Send + Sync,
@@ -527,10 +512,9 @@ where
let mut failures = BTreeMap::new(); let mut failures = BTreeMap::new();
let futures = get_over_federation let mut futures: FuturesUnordered<_> = get_over_federation
.into_iter() .into_iter()
.stream() .map(|(server, vec)| async move {
.wide_filter_map(|(server, vec)| async move {
let mut device_keys_input_fed = BTreeMap::new(); let mut device_keys_input_fed = BTreeMap::new();
for (user_id, keys) in vec { for (user_id, keys) in vec {
device_keys_input_fed.insert(user_id.to_owned(), keys.clone()); device_keys_input_fed.insert(user_id.to_owned(), keys.clone());
@@ -538,22 +522,17 @@ where
let request = let request =
federation::keys::get_keys::v1::Request { device_keys: device_keys_input_fed }; federation::keys::get_keys::v1::Request { device_keys: device_keys_input_fed };
let response = tokio::time::timeout(
timeout,
services.sending.send_federation_request(server, request),
)
.await
// Need to flatten the Result<Result<V, E>, E> into Result<V, E>
.map_err(|_| err!(Request(Unknown("Timeout when getting keys over federation."))))
.and_then(|res| res);
Some((server, response)) let response = services
.sending
.send_federation_request(server, request)
.await;
(server, response)
}) })
.collect::<FuturesUnordered<_>>() .collect();
.await
.into_iter();
for (server, response) in futures { while let Some((server, response)) = futures.next().await {
match response { match response {
| Ok(response) => { | Ok(response) => {
for (user, master_key) in response.master_keys { for (user, master_key) in response.master_keys {
@@ -585,8 +564,8 @@ where
self_signing_keys.extend(response.self_signing_keys); self_signing_keys.extend(response.self_signing_keys);
device_keys.extend(response.device_keys); device_keys.extend(response.device_keys);
}, },
| Err(e) => { | _ => {
failures.insert(server.to_string(), json!({ "error": e.to_string() })); failures.insert(server.to_string(), json!({}));
}, },
} }
} }
@@ -629,7 +608,6 @@ fn add_unsigned_device_display_name(
pub(crate) async fn claim_keys_helper( pub(crate) async fn claim_keys_helper(
services: &Services, services: &Services,
one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, OneTimeKeyAlgorithm>>, one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, OneTimeKeyAlgorithm>>,
timeout: Duration,
) -> Result<claim_keys::v3::Response> { ) -> Result<claim_keys::v3::Response> {
let mut one_time_keys = BTreeMap::new(); let mut one_time_keys = BTreeMap::new();
@@ -660,39 +638,32 @@ pub(crate) async fn claim_keys_helper(
let mut failures = BTreeMap::new(); let mut failures = BTreeMap::new();
let futures = get_over_federation let mut futures: FuturesUnordered<_> = get_over_federation
.into_iter() .into_iter()
.stream() .map(|(server, vec)| async move {
.wide_filter_map(|(server, vec)| async move {
let mut one_time_keys_input_fed = BTreeMap::new(); let mut one_time_keys_input_fed = BTreeMap::new();
for (user_id, keys) in vec { for (user_id, keys) in vec {
one_time_keys_input_fed.insert(user_id.clone(), keys.clone()); one_time_keys_input_fed.insert(user_id.clone(), keys.clone());
} }
let response = tokio::time::timeout( (
timeout, server,
services.sending.send_federation_request( services
server, .sending
federation::keys::claim_keys::v1::Request { .send_federation_request(server, federation::keys::claim_keys::v1::Request {
one_time_keys: one_time_keys_input_fed, one_time_keys: one_time_keys_input_fed,
}, })
), .await,
) )
.await
.map_err(|_| err!(Request(Unknown("Timeout when claiming keys over federation."))))
.and_then(|res| res);
Some((server, response))
}) })
.collect::<FuturesUnordered<_>>() .collect();
.await
.into_iter();
for (server, response) in futures { while let Some((server, response)) = futures.next().await {
match response { match response {
| Ok(keys) => { | Ok(keys) => {
one_time_keys.extend(keys.one_time_keys); one_time_keys.extend(keys.one_time_keys);
}, },
| Err(e) => { | Err(_e) => {
failures.insert(server.to_string(), json!({"error": e.to_string()})); failures.insert(server.to_string(), json!({}));
}, },
} }
} }
+1 -14
View File
@@ -3,7 +3,6 @@ use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
Err, Result, debug_error, err, info, Err, Result, debug_error, err, info,
matrix::{event::gen_event_id_canonical_json, pdu::PduBuilder}, matrix::{event::gen_event_id_canonical_json, pdu::PduBuilder},
warn,
}; };
use futures::FutureExt; use futures::FutureExt;
use ruma::{ use ruma::{
@@ -22,7 +21,7 @@ use crate::Ruma;
/// # `POST /_matrix/client/r0/rooms/{roomId}/invite` /// # `POST /_matrix/client/r0/rooms/{roomId}/invite`
/// ///
/// Tries to send an invite event into the room. /// Tries to send an invite event into the room.
#[tracing::instrument(skip_all, fields(%client), name = "invite", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "invite")]
pub(crate) async fn invite_user_route( pub(crate) async fn invite_user_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -125,18 +124,6 @@ pub(crate) async fn invite_helper(
return Err!(Request(Forbidden("Invites are not allowed on this server."))); return Err!(Request(Forbidden("Invites are not allowed on this server.")));
} }
if let Err(e) = services
.antispam
.user_may_invite(sender_user.to_owned(), recipient_user.to_owned(), room_id.to_owned())
.await
{
warn!(
"Invite from {} to {} in room {} blocked by antispam: {e:?}",
sender_user, recipient_user, room_id
);
return Err!(Request(Forbidden("Invite blocked by antispam service.")));
}
if !services.globals.user_is_local(recipient_user) { if !services.globals.user_is_local(recipient_user) {
let (pdu, pdu_json, invite_room_state) = { let (pdu, pdu_json, invite_room_state) = {
let state_lock = services.rooms.state.mutex.lock(room_id).await; let state_lock = services.rooms.state.mutex.lock(room_id).await;
+54 -89
View File
@@ -33,7 +33,7 @@ use ruma::{
events::{ events::{
StateEventType, StateEventType,
room::{ room::{
join_rules::{AllowRule, JoinRule}, join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent}, member::{MembershipState, RoomMemberEventContent},
}, },
}, },
@@ -59,7 +59,7 @@ use crate::Ruma;
/// rules locally /// rules locally
/// - If the server does not know about the room: asks other servers over /// - If the server does not know about the room: asks other servers over
/// federation /// federation
#[tracing::instrument(skip_all, fields(%client), name = "join", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "join")]
pub(crate) async fn join_room_by_id_route( pub(crate) async fn join_room_by_id_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -131,7 +131,7 @@ pub(crate) async fn join_room_by_id_route(
/// - If the server does not know about the room: use the server name query /// - If the server does not know about the room: use the server name query
/// param if specified. if not specified, asks other servers over federation /// param if specified. if not specified, asks other servers over federation
/// via room alias server name and room ID server name /// via room alias server name and room ID server name
#[tracing::instrument(skip_all, fields(%client), name = "join", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "join")]
pub(crate) async fn join_room_by_id_or_alias_route( pub(crate) async fn join_room_by_id_or_alias_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -288,23 +288,6 @@ pub async fn join_room_by_id_helper(
return Ok(join_room_by_id::v3::Response { room_id: room_id.into() }); return Ok(join_room_by_id::v3::Response { room_id: room_id.into() });
} }
if let Err(e) = services
.antispam
.user_may_join_room(
sender_user.to_owned(),
room_id.to_owned(),
services
.rooms
.state_cache
.is_invited(sender_user, room_id)
.await,
)
.await
{
warn!("Antispam prevented user {} from joining room {}: {}", sender_user, room_id, e);
return Err!(Request(Forbidden("You are not allowed to join this room.")));
}
let server_in_room = services let server_in_room = services
.rooms .rooms
.state_cache .state_cache
@@ -338,17 +321,6 @@ pub async fn join_room_by_id_helper(
))); )));
} }
if services.antispam.check_all_joins() {
if let Err(e) = services
.antispam
.meowlnir_accept_make_join(room_id.to_owned(), sender_user.to_owned())
.await
{
warn!("Antispam prevented user {} from joining room {}: {}", sender_user, room_id, e);
return Err!(Request(Forbidden("Antispam rejected join request.")));
}
}
if server_in_room { if server_in_room {
join_room_by_id_helper_local( join_room_by_id_helper_local(
services, services,
@@ -375,10 +347,11 @@ pub async fn join_room_by_id_helper(
.boxed() .boxed()
.await?; .await?;
} }
Ok(join_room_by_id::v3::Response::new(room_id.to_owned())) Ok(join_room_by_id::v3::Response::new(room_id.to_owned()))
} }
#[tracing::instrument(skip_all, fields(%sender_user, %room_id), name = "join_remote", level = "info")] #[tracing::instrument(skip_all, fields(%sender_user, %room_id), name = "join_remote")]
async fn join_room_by_id_helper_remote( async fn join_room_by_id_helper_remote(
services: &Services, services: &Services,
sender_user: &UserId, sender_user: &UserId,
@@ -736,7 +709,7 @@ async fn join_room_by_id_helper_remote(
Ok(()) Ok(())
} }
#[tracing::instrument(skip_all, fields(%sender_user, %room_id), name = "join_local", level = "info")] #[tracing::instrument(skip_all, fields(%sender_user, %room_id), name = "join_local")]
async fn join_room_by_id_helper_local( async fn join_room_by_id_helper_local(
services: &Services, services: &Services,
sender_user: &UserId, sender_user: &UserId,
@@ -747,51 +720,45 @@ async fn join_room_by_id_helper_local(
state_lock: RoomMutexGuard, state_lock: RoomMutexGuard,
) -> Result { ) -> Result {
debug_info!("We can join locally"); debug_info!("We can join locally");
let join_rules = services.rooms.state_accessor.get_join_rules(room_id).await;
let mut restricted_join_authorized = None; let join_rules_event_content = services
match join_rules { .rooms
| JoinRule::Restricted(restricted) | JoinRule::KnockRestricted(restricted) => { .state_accessor
for restriction in restricted.allow { .room_state_get_content::<RoomJoinRulesEventContent>(
match restriction { room_id,
| AllowRule::RoomMembership(membership) => { &StateEventType::RoomJoinRules,
if services "",
.rooms )
.state_cache .await;
.is_joined(sender_user, &membership.room_id)
.await let restriction_rooms = match join_rules_event_content {
{ | Ok(RoomJoinRulesEventContent {
restricted_join_authorized = Some(true); join_rule: JoinRule::Restricted(restricted) | JoinRule::KnockRestricted(restricted),
break; }) => restricted
} .allow
}, .into_iter()
| AllowRule::UnstableSpamChecker => { .filter_map(|a| match a {
match services | AllowRule::RoomMembership(r) => Some(r.room_id),
.antispam | _ => None,
.meowlnir_accept_make_join(room_id.to_owned(), sender_user.to_owned()) })
.await .collect(),
{ | _ => Vec::new(),
| Ok(()) => { };
restricted_join_authorized = Some(true);
break; let join_authorized_via_users_server: Option<OwnedUserId> = {
}, if restriction_rooms
| Err(_) => .iter()
return Err!(Request(Forbidden( .stream()
"Antispam rejected join request." .any(|restriction_room_id| {
))), trace!("Checking if {sender_user} is joined to {restriction_room_id}");
} services
}, .rooms
| _ => {}, .state_cache
} .is_joined(sender_user, restriction_room_id)
} })
}, .await
| _ => {}, {
} services
let join_authorized_via_users_server = if restricted_join_authorized.is_none() {
None
} else {
match restricted_join_authorized.unwrap() {
| true => services
.rooms .rooms
.state_cache .state_cache
.local_users_in_room(room_id) .local_users_in_room(room_id)
@@ -807,14 +774,10 @@ async fn join_room_by_id_helper_local(
.boxed() .boxed()
.next() .next()
.await .await
.map(ToOwned::to_owned), .map(ToOwned::to_owned)
| false => { } else {
warn!( trace!("No restriction rooms are joined by {sender_user}");
"Join authorization failed for restricted join in room {room_id} for user \ None
{sender_user}"
);
return Err!(Request(Forbidden("You are not authorized to join this room.")));
},
} }
}; };
@@ -842,14 +805,16 @@ async fn join_room_by_id_helper_local(
return Ok(()); return Ok(());
}; };
if servers.is_empty() || servers.len() == 1 && services.globals.server_is_ours(&servers[0]) { if restriction_rooms.is_empty()
&& (servers.is_empty()
|| servers.len() == 1 && services.globals.server_is_ours(&servers[0]))
{
return Err(error); return Err(error);
} }
warn!( warn!(
?error, "We couldn't do the join locally, maybe federation can help to satisfy the restricted \
servers = %servers.len(), join requirements"
"Could not join restricted room locally, attempting remote join",
); );
let Ok((make_join_response, remote_server)) = let Ok((make_join_response, remote_server)) =
make_join_request(services, sender_user, room_id, servers).await make_join_request(services, sender_user, room_id, servers).await
+1 -1
View File
@@ -44,7 +44,7 @@ use crate::Ruma;
/// # `POST /_matrix/client/*/knock/{roomIdOrAlias}` /// # `POST /_matrix/client/*/knock/{roomIdOrAlias}`
/// ///
/// Tries to knock the room to ask permission to join for the sender user. /// Tries to knock the room to ask permission to join for the sender user.
#[tracing::instrument(skip_all, fields(%client), name = "knock", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "knock")]
pub(crate) async fn knock_room_route( pub(crate) async fn knock_room_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
-1
View File
@@ -186,7 +186,6 @@ pub async fn leave_room(
// we save a `None` to the `roomuserid_leftcount` table, which generates // we save a `None` to the `roomuserid_leftcount` table, which generates
// and sends a dummy leave to the client. // and sends a dummy leave to the client.
warn!( warn!(
?err,
"Trying to leave room not cached as leave, sending dummy leave \ "Trying to leave room not cached as leave, sending dummy leave \
event to client" event to client"
); );
+1 -1
View File
@@ -63,7 +63,7 @@ pub(crate) async fn joined_rooms_route(
/// ///
/// Performs automatic deactivation if `auto_deactivate_banned_room_attempts` is /// Performs automatic deactivation if `auto_deactivate_banned_room_attempts` is
/// enabled /// enabled
#[tracing::instrument(skip(services), level = "info")] #[tracing::instrument(skip(services))]
pub(crate) async fn banned_room_check( pub(crate) async fn banned_room_check(
services: &Services, services: &Services,
user_id: &UserId, user_id: &UserId,
+1 -1
View File
@@ -115,7 +115,7 @@ async fn paginate_relations_with_filter(
.user_can_see_event(sender_user, room_id, target) .user_can_see_event(sender_user, room_id, target)
.await .await
{ {
debug_warn!(req_evt = %target, %room_id, "Event relations requested by {sender_user} but is not allowed to see it, returning 404"); debug_warn!(req_evt = ?target, ?room_id, "Event relations requested by {sender_user} but is not allowed to see it, returning 404");
return Err!(Request(NotFound("Event not found."))); return Err!(Request(NotFound("Event not found.")));
} }
+3 -3
View File
@@ -29,7 +29,7 @@ struct Report {
/// # `POST /_matrix/client/v3/rooms/{roomId}/report` /// # `POST /_matrix/client/v3/rooms/{roomId}/report`
/// ///
/// Reports an abusive room to homeserver admins /// Reports an abusive room to homeserver admins
#[tracing::instrument(skip_all, fields(%client), name = "report_room", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "report_room")]
pub(crate) async fn report_room_route( pub(crate) async fn report_room_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -85,7 +85,7 @@ pub(crate) async fn report_room_route(
/// # `POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}` /// # `POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}`
/// ///
/// Reports an inappropriate event to homeserver admins /// Reports an inappropriate event to homeserver admins
#[tracing::instrument(skip_all, fields(%client), name = "report_event", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "report_event")]
pub(crate) async fn report_event_route( pub(crate) async fn report_event_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -133,7 +133,7 @@ pub(crate) async fn report_event_route(
Ok(report_content::v3::Response {}) Ok(report_content::v3::Response {})
} }
#[tracing::instrument(skip_all, fields(%client), name = "report_user", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "report_user")]
pub(crate) async fn report_user_route( pub(crate) async fn report_user_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
+4 -4
View File
@@ -492,7 +492,7 @@ pub(crate) async fn create_room_route(
.boxed() .boxed()
.await .await
{ {
warn!(?e, "Failed to send invite"); warn!(%e, "Failed to send invite");
} }
} }
@@ -627,7 +627,7 @@ async fn room_alias_check(
.map_err(|e| { .map_err(|e| {
err!(Request(InvalidParam(debug_error!( err!(Request(InvalidParam(debug_error!(
?e, ?e,
%room_alias_name, ?room_alias_name,
"Failed to parse room alias.", "Failed to parse room alias.",
)))) ))))
})?; })?;
@@ -711,7 +711,7 @@ fn custom_room_id_check(services: &Services, custom_room_id: &str) -> Result<Own
} }
}) })
.inspect(|full_room_id| { .inspect(|full_room_id| {
debug_info!(%full_room_id, "Full custom room ID"); debug_info!(?full_room_id, "Full custom room ID");
}) })
.inspect_err(|e| warn!(?e, %custom_room_id, "Failed to create room with custom room ID",)) .inspect_err(|e| warn!(?e, ?custom_room_id, "Failed to create room with custom room ID",))
} }
+50 -65
View File
@@ -1,11 +1,11 @@
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
Err, Result, debug, debug_warn, info, trace, Err, Result, debug_warn, trace,
utils::{IterStream, future::TryExtExt}, utils::{IterStream, future::TryExtExt},
}; };
use futures::{ use futures::{
FutureExt, StreamExt, TryFutureExt, FutureExt, StreamExt,
future::{OptionFuture, join3}, future::{OptionFuture, join3},
stream::FuturesUnordered, stream::FuturesUnordered,
}; };
@@ -46,7 +46,7 @@ pub(crate) async fn get_room_summary_legacy(
/// # `GET /_matrix/client/v1/room_summary/{roomIdOrAlias}` /// # `GET /_matrix/client/v1/room_summary/{roomIdOrAlias}`
/// ///
/// Returns a short description of the state of a room. /// Returns a short description of the state of a room.
#[tracing::instrument(skip_all, fields(%client), name = "room_summary", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "room_summary")]
pub(crate) async fn get_room_summary( pub(crate) async fn get_room_summary(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -79,15 +79,9 @@ async fn room_summary_response(
.server_in_room(services.globals.server_name(), room_id) .server_in_room(services.globals.server_name(), room_id)
.await .await
{ {
match local_room_summary_response(services, room_id, sender_user) return local_room_summary_response(services, room_id, sender_user)
.boxed() .boxed()
.await .await;
{
| Ok(response) => return Ok(response),
| Err(e) => {
debug_warn!("Failed to get local room summary: {e:?}, falling back to remote");
},
}
} }
let room = let room =
@@ -116,31 +110,27 @@ async fn local_room_summary_response(
room_id: &RoomId, room_id: &RoomId,
sender_user: Option<&UserId>, sender_user: Option<&UserId>,
) -> Result<get_summary::msc3266::Response> { ) -> Result<get_summary::msc3266::Response> {
trace!( trace!(?sender_user, "Sending local room summary response for {room_id:?}");
sender_user = sender_user.map(tracing::field::display), let join_rule = services.rooms.state_accessor.get_join_rules(room_id);
"Sending local room summary response for {room_id:?}"
);
let (join_rule, world_readable, guest_can_join) = join3(
services.rooms.state_accessor.get_join_rules(room_id),
services.rooms.state_accessor.is_world_readable(room_id),
services.rooms.state_accessor.guest_can_join(room_id),
)
.await;
// Synapse allows server admins to bypass visibility checks. let world_readable = services.rooms.state_accessor.is_world_readable(room_id);
// That seems neat so we'll copy that behaviour.
if sender_user.is_none() || !services.users.is_admin(sender_user.unwrap()).await { let guest_can_join = services.rooms.state_accessor.guest_can_join(room_id);
user_can_see_summary(
services, let (join_rule, world_readable, guest_can_join) =
room_id, join3(join_rule, world_readable, guest_can_join).await;
&join_rule.clone().into(),
guest_can_join, trace!("{join_rule:?}, {world_readable:?}, {guest_can_join:?}");
world_readable, user_can_see_summary(
join_rule.allowed_rooms(), services,
sender_user, room_id,
) &join_rule.clone().into(),
.await?; guest_can_join,
} world_readable,
join_rule.allowed_rooms(),
sender_user,
)
.await?;
let canonical_alias = services let canonical_alias = services
.rooms .rooms
@@ -231,7 +221,7 @@ async fn remote_room_summary_hierarchy_response(
servers: &[OwnedServerName], servers: &[OwnedServerName],
sender_user: Option<&UserId>, sender_user: Option<&UserId>,
) -> Result<SpaceHierarchyParentSummary> { ) -> Result<SpaceHierarchyParentSummary> {
trace!(sender_user = ?sender_user.map(tracing::field::display), ?servers, "Sending remote room summary response for {room_id:?}"); trace!(?sender_user, ?servers, "Sending remote room summary response for {room_id:?}");
if !services.config.allow_federation { if !services.config.allow_federation {
return Err!(Request(Forbidden("Federation is disabled."))); return Err!(Request(Forbidden("Federation is disabled.")));
} }
@@ -241,27 +231,15 @@ async fn remote_room_summary_hierarchy_response(
"Federaton of room {room_id} is currently disabled on this server." "Federaton of room {room_id} is currently disabled on this server."
))); )));
} }
if servers.is_empty() {
return Err!(Request(MissingParam(
"No servers were provided to fetch the room over federation"
)));
}
let request = get_hierarchy::v1::Request::new(room_id.to_owned()); let request = get_hierarchy::v1::Request::new(room_id.to_owned());
let mut requests: FuturesUnordered<_> = servers let mut requests: FuturesUnordered<_> = servers
.iter() .iter()
.map(|server| { .map(|server| {
info!("Fetching room summary for {room_id} from server {server}");
services services
.sending .sending
.send_federation_request(server, request.clone()) .send_federation_request(server, request.clone())
.inspect_ok(move |v| {
debug!("Fetched room summary for {room_id} from server {server}: {v:?}");
})
.inspect_err(move |e| {
info!("Failed to fetch room summary for {room_id} from server {server}: {e}");
})
}) })
.collect(); .collect();
@@ -277,23 +255,23 @@ async fn remote_room_summary_hierarchy_response(
continue; continue;
} }
if sender_user.is_none() || !services.users.is_admin(sender_user.unwrap()).await { return user_can_see_summary(
return user_can_see_summary( services,
services, room_id,
room_id, &room.join_rule,
&room.join_rule, room.guest_can_join,
room.guest_can_join, room.world_readable,
room.world_readable, room.allowed_room_ids.iter().map(AsRef::as_ref),
room.allowed_room_ids.iter().map(AsRef::as_ref), sender_user,
sender_user, )
) .await
.await .map(|()| room);
.map(|()| room);
}
return Ok(room);
} }
Err!(Request(NotFound("Room not found or is not accessible"))) Err!(Request(NotFound(
"Room is unknown to this server and was unable to fetch over federation with the \
provided servers available"
)))
} }
async fn user_can_see_summary<'a, I>( async fn user_can_see_summary<'a, I>(
@@ -333,14 +311,21 @@ where
return Ok(()); return Ok(());
} }
Err!(Request(Forbidden("Room is not accessible"))) Err!(Request(Forbidden(
"Room is not world readable, not publicly accessible/joinable, restricted room \
conditions not met, and guest access is forbidden. Not allowed to see details \
of this room."
)))
}, },
| None => { | None => {
if is_public_room || world_readable { if is_public_room || world_readable {
return Ok(()); return Ok(());
} }
Err!(Request(Forbidden("Room is not accessible"))) Err!(Request(Forbidden(
"Room is not world readable or publicly accessible/joinable, authentication is \
required"
)))
}, },
} }
} }
+7 -18
View File
@@ -5,7 +5,6 @@ use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
Err, Error, Result, debug, err, info, Err, Error, Result, debug, err, info,
utils::{self, ReadyExt, hash}, utils::{self, ReadyExt, hash},
warn,
}; };
use conduwuit_core::{debug_error, debug_warn}; use conduwuit_core::{debug_error, debug_warn};
use conduwuit_service::{Services, uiaa::SESSION_ID_LENGTH}; use conduwuit_service::{Services, uiaa::SESSION_ID_LENGTH};
@@ -13,7 +12,6 @@ use futures::StreamExt;
use ruma::{ use ruma::{
OwnedUserId, UserId, OwnedUserId, UserId,
api::client::{ api::client::{
error::ErrorKind,
session::{ session::{
get_login_token, get_login_token,
get_login_types::{ get_login_types::{
@@ -37,7 +35,7 @@ use crate::Ruma;
/// ///
/// Get the supported login types of this server. One of these should be used as /// Get the supported login types of this server. One of these should be used as
/// the `type` field when logging in. /// the `type` field when logging in.
#[tracing::instrument(skip_all, fields(%client), name = "login", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "login")]
pub(crate) async fn get_login_types_route( pub(crate) async fn get_login_types_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -55,7 +53,7 @@ pub(crate) async fn get_login_types_route(
/// Authenticates the given user by its ID and its password. /// Authenticates the given user by its ID and its password.
/// ///
/// Returns the user ID if successful, and an error otherwise. /// Returns the user ID if successful, and an error otherwise.
#[tracing::instrument(skip_all, fields(%user_id), name = "password", level = "debug")] #[tracing::instrument(skip_all, fields(%user_id), name = "password")]
pub(crate) async fn password_login( pub(crate) async fn password_login(
services: &Services, services: &Services,
user_id: &UserId, user_id: &UserId,
@@ -98,7 +96,7 @@ pub(crate) async fn password_login(
/// ///
/// Creates the user if the user is found in the LDAP and do not already have an /// Creates the user if the user is found in the LDAP and do not already have an
/// account. /// account.
#[tracing::instrument(skip_all, fields(%user_id), name = "ldap", level = "debug")] #[tracing::instrument(skip_all, fields(%user_id), name = "ldap")]
pub(super) async fn ldap_login( pub(super) async fn ldap_login(
services: &Services, services: &Services,
user_id: &UserId, user_id: &UserId,
@@ -186,15 +184,6 @@ pub(crate) async fn handle_login(
return Err!(Request(Unknown("User ID does not belong to this homeserver"))); return Err!(Request(Unknown("User ID does not belong to this homeserver")));
} }
if services.users.is_locked(&user_id).await? {
return Err(Error::BadRequest(ErrorKind::UserLocked, "This account has been locked."));
}
if services.users.is_login_disabled(&user_id).await {
warn!(%user_id, "user attempted to log in with a login-disabled account");
return Err!(Request(Forbidden("This account is not permitted to log in.")));
}
if cfg!(feature = "ldap") && services.config.ldap.enable { if cfg!(feature = "ldap") && services.config.ldap.enable {
match Box::pin(ldap_login(services, &user_id, &lowercased_user_id, password)).await { match Box::pin(ldap_login(services, &user_id, &lowercased_user_id, password)).await {
| Ok(user_id) => Ok(user_id), | Ok(user_id) => Ok(user_id),
@@ -223,7 +212,7 @@ pub(crate) async fn handle_login(
/// Note: You can use [`GET /// Note: You can use [`GET
/// /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see /// /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see
/// supported login types. /// supported login types.
#[tracing::instrument(skip_all, fields(%client), name = "login", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "login")]
pub(crate) async fn login_route( pub(crate) async fn login_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -356,7 +345,7 @@ pub(crate) async fn login_route(
/// to log in with the m.login.token flow. /// to log in with the m.login.token flow.
/// ///
/// <https://spec.matrix.org/v1.13/client-server-api/#post_matrixclientv1loginget_token> /// <https://spec.matrix.org/v1.13/client-server-api/#post_matrixclientv1loginget_token>
#[tracing::instrument(skip_all, fields(%client), name = "login_token", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "login_token")]
pub(crate) async fn login_token_route( pub(crate) async fn login_token_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -424,7 +413,7 @@ pub(crate) async fn login_token_route(
/// last seen ts) /// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
#[tracing::instrument(skip_all, fields(%client), name = "logout", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "logout")]
pub(crate) async fn logout_route( pub(crate) async fn logout_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -451,7 +440,7 @@ pub(crate) async fn logout_route(
/// Note: This is equivalent to calling [`GET /// Note: This is equivalent to calling [`GET
/// /_matrix/client/r0/logout`](fn.logout_route.html) from each device of this /// /_matrix/client/r0/logout`](fn.logout_route.html) from each device of this
/// user. /// user.
#[tracing::instrument(skip_all, fields(%client), name = "logout", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "logout")]
pub(crate) async fn logout_all_route( pub(crate) async fn logout_all_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
+7 -7
View File
@@ -140,8 +140,8 @@ pub(crate) async fn get_state_events_for_key_route(
.await .await
.map_err(|_| { .map_err(|_| {
err!(Request(NotFound(debug_warn!( err!(Request(NotFound(debug_warn!(
room_id = %body.room_id, room_id = ?body.room_id,
event_type = %body.event_type, event_type = ?body.event_type,
"State event not found in room.", "State event not found in room.",
)))) ))))
})?; })?;
@@ -226,7 +226,7 @@ async fn allowed_to_send_state_event(
match event_type { match event_type {
| StateEventType::RoomCreate => { | StateEventType::RoomCreate => {
return Err!(Request(BadJson(debug_warn!( return Err!(Request(BadJson(debug_warn!(
%room_id, ?room_id,
"You cannot update m.room.create after a room has been created." "You cannot update m.room.create after a room has been created."
)))); ))));
}, },
@@ -237,7 +237,7 @@ async fn allowed_to_send_state_event(
| Ok(acl_content) => { | Ok(acl_content) => {
if acl_content.allow_is_empty() { if acl_content.allow_is_empty() {
return Err!(Request(BadJson(debug_warn!( return Err!(Request(BadJson(debug_warn!(
%room_id, ?room_id,
"Sending an ACL event with an empty allow key will permanently \ "Sending an ACL event with an empty allow key will permanently \
brick the room for non-conduwuit's as this equates to no servers \ brick the room for non-conduwuit's as this equates to no servers \
being allowed to participate in this room." being allowed to participate in this room."
@@ -246,7 +246,7 @@ async fn allowed_to_send_state_event(
if acl_content.deny_contains("*") && acl_content.allow_contains("*") { if acl_content.deny_contains("*") && acl_content.allow_contains("*") {
return Err!(Request(BadJson(debug_warn!( return Err!(Request(BadJson(debug_warn!(
%room_id, ?room_id,
"Sending an ACL event with a deny and allow key value of \"*\" will \ "Sending an ACL event with a deny and allow key value of \"*\" will \
permanently brick the room for non-conduwuit's as this equates to \ permanently brick the room for non-conduwuit's as this equates to \
no servers being allowed to participate in this room." no servers being allowed to participate in this room."
@@ -258,7 +258,7 @@ async fn allowed_to_send_state_event(
&& !acl_content.allow_contains(services.globals.server_name().as_str()) && !acl_content.allow_contains(services.globals.server_name().as_str())
{ {
return Err!(Request(BadJson(debug_warn!( return Err!(Request(BadJson(debug_warn!(
%room_id, ?room_id,
"Sending an ACL event with a deny key value of \"*\" and without \ "Sending an ACL event with a deny key value of \"*\" and without \
your own server name in the allow key will result in you being \ your own server name in the allow key will result in you being \
unable to participate in this room." unable to participate in this room."
@@ -270,7 +270,7 @@ async fn allowed_to_send_state_event(
&& !acl_content.allow_contains(services.globals.server_name().as_str()) && !acl_content.allow_contains(services.globals.server_name().as_str())
{ {
return Err!(Request(BadJson(debug_warn!( return Err!(Request(BadJson(debug_warn!(
%room_id, ?room_id,
"Sending an ACL event for an allow key without \"*\" and without \ "Sending an ACL event for an allow key without \"*\" and without \
your own server name in the allow key will result in you being \ your own server name in the allow key will result in you being \
unable to participate in this room." unable to participate in this room."
+5 -5
View File
@@ -50,8 +50,8 @@ use crate::client::{
level = "debug", level = "debug",
skip_all, skip_all,
fields( fields(
room_id = %room_id, room_id = ?room_id,
syncing_user = %sync_context.syncing_user, syncing_user = ?sync_context.syncing_user,
), ),
)] )]
pub(super) async fn load_joined_room( pub(super) async fn load_joined_room(
@@ -578,7 +578,7 @@ async fn build_notification_counts(
) )
.await; .await;
trace!(%notification_count, %highlight_count, "syncing new notification counts"); trace!(?notification_count, ?highlight_count, "syncing new notification counts");
Ok(Some(UnreadNotificationsCount { Ok(Some(UnreadNotificationsCount {
notification_count: Some(notification_count), notification_count: Some(notification_count),
@@ -692,8 +692,8 @@ async fn build_room_summary(
}; };
trace!( trace!(
%joined_member_count, ?joined_member_count,
%invited_member_count, ?invited_member_count,
heroes_length = heroes.as_ref().map(HashSet::len), heroes_length = heroes.as_ref().map(HashSet::len),
"syncing updated summary" "syncing updated summary"
); );
+2 -2
View File
@@ -307,8 +307,8 @@ async fn build_left_state_and_timeline(
} }
trace!( trace!(
%timeline_start_count, ?timeline_start_count,
%timeline_end_count, ?timeline_end_count,
"syncing {} timeline events (limited = {}) and {} state events", "syncing {} timeline events (limited = {}) and {} state events",
timeline.pdus.len(), timeline.pdus.len(),
timeline.limited, timeline.limited,
+1 -1
View File
@@ -275,7 +275,7 @@ pub(crate) async fn build_sync_events(
match joined_room { match joined_room {
| Ok((room, updates)) => Some((room_id, room, updates)), | Ok((room, updates)) => Some((room_id, room, updates)),
| Err(err) => { | Err(err) => {
warn!(?err, %room_id, "error loading joined room"); warn!(?err, ?room_id, "error loading joined room {}", room_id);
None None
}, },
} }
+1 -1
View File
@@ -217,7 +217,7 @@ pub(super) async fn build_state_incremental<'a>(
the performance penalty is acceptable. the performance penalty is acceptable.
*/ */
trace!(%timeline_is_linear, %timeline.limited, "computing state for incremental sync"); trace!(?timeline_is_linear, ?timeline.limited, "computing state for incremental sync");
// fetch the shorteventids of state events in the timeline // fetch the shorteventids of state events in the timeline
let state_events_in_timeline: BTreeSet<ShortEventId> = services let state_events_in_timeline: BTreeSet<ShortEventId> = services
+1 -1
View File
@@ -26,7 +26,7 @@ use crate::Ruma;
/// TODO: Implement pagination, currently this just returns everything /// TODO: Implement pagination, currently this just returns everything
/// ///
/// An implementation of [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666) /// An implementation of [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666)
#[tracing::instrument(skip_all, fields(%client), name = "mutual_rooms", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "mutual_rooms")]
pub(crate) async fn get_mutual_rooms_route( pub(crate) async fn get_mutual_rooms_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
+14 -10
View File
@@ -1,5 +1,6 @@
use axum::{Json, extract::State, response::IntoResponse}; use axum::{Json, extract::State, response::IntoResponse};
use conduwuit::{Error, Result}; use conduwuit::{Error, Result};
use futures::StreamExt;
use ruma::api::client::{ use ruma::api::client::{
discovery::{ discovery::{
discover_homeserver::{self, HomeserverInfo, SlidingSyncProxyInfo}, discover_homeserver::{self, HomeserverInfo, SlidingSyncProxyInfo},
@@ -70,18 +71,21 @@ pub(crate) async fn well_known_support(
// Try to add admin users as contacts if no contacts are configured // Try to add admin users as contacts if no contacts are configured
if contacts.is_empty() { if contacts.is_empty() {
let admin_users = services.admin.get_admins().await; if let Ok(admin_room) = services.admin.get_admin_room().await {
let admin_users = services.rooms.state_cache.room_members(&admin_room);
let mut stream = admin_users;
for user_id in &admin_users { while let Some(user_id) = stream.next().await {
if *user_id == services.globals.server_user { // Skip server user
continue; if *user_id == services.globals.server_user {
continue;
}
contacts.push(Contact {
role: role_value.clone(),
email_address: None,
matrix_id: Some(user_id.to_owned()),
});
} }
contacts.push(Contact {
role: role_value.clone(),
email_address: None,
matrix_id: Some(user_id.to_owned()),
});
} }
} }
+6 -24
View File
@@ -137,30 +137,12 @@ pub(super) async fn auth(
| ( | (
AuthScheme::AccessToken | AuthScheme::AccessTokenOptional | AuthScheme::None, AuthScheme::AccessToken | AuthScheme::AccessTokenOptional | AuthScheme::None,
Token::User((user_id, device_id)), Token::User((user_id, device_id)),
) => { ) => Ok(Auth {
let is_locked = services.users.is_locked(&user_id).await.map_err(|e| { origin: None,
err!(Request(Forbidden(warn!("Failed to check user lock status: {e}")))) sender_user: Some(user_id),
})?; sender_device: Some(device_id),
if is_locked { appservice_info: None,
// Only /logout and /logout/all are allowed for locked users }),
if !matches!(
metadata,
&ruma::api::client::session::logout::v3::Request::METADATA
| &ruma::api::client::session::logout_all::v3::Request::METADATA
) {
return Err(Error::BadRequest(
ErrorKind::UserLocked,
"This account has been locked.",
));
}
}
Ok(Auth {
origin: None,
sender_user: Some(user_id),
sender_device: Some(device_id),
appservice_info: None,
})
},
| (AuthScheme::ServerSignatures, Token::None) => | (AuthScheme::ServerSignatures, Token::None) =>
Ok(auth_server(services, request, json_body).await?), Ok(auth_server(services, request, json_body).await?),
| ( | (
+3 -3
View File
@@ -40,7 +40,7 @@ pub(crate) async fn get_missing_events_route(
while i < queued_events.len() && events.len() < limit { while i < queued_events.len() && events.len() < limit {
let Ok(pdu) = services.rooms.timeline.get_pdu(&queued_events[i]).await else { let Ok(pdu) = services.rooms.timeline.get_pdu(&queued_events[i]).await else {
debug!( debug!(
body.origin = body.origin.as_ref().map(tracing::field::display), ?body.origin,
"Event {} does not exist locally, skipping", &queued_events[i] "Event {} does not exist locally, skipping", &queued_events[i]
); );
i = i.saturating_add(1); i = i.saturating_add(1);
@@ -59,7 +59,7 @@ pub(crate) async fn get_missing_events_route(
.await .await
{ {
debug!( debug!(
body.origin = body.origin.as_ref().map(tracing::field::display), ?body.origin,
"Server cannot see {:?} in {:?}, skipping", pdu.event_id, pdu.room_id "Server cannot see {:?} in {:?}, skipping", pdu.event_id, pdu.room_id
); );
i = i.saturating_add(1); i = i.saturating_add(1);
@@ -68,7 +68,7 @@ pub(crate) async fn get_missing_events_route(
let Ok(event) = to_canonical_object(&pdu) else { let Ok(event) = to_canonical_object(&pdu) else {
debug_error!( debug_error!(
body.origin = body.origin.as_ref().map(tracing::field::display), ?body.origin,
"Failed to convert PDU in database to canonical JSON: {pdu:?}" "Failed to convert PDU in database to canonical JSON: {pdu:?}"
); );
i = i.saturating_add(1); i = i.saturating_add(1);
+1 -10
View File
@@ -19,7 +19,7 @@ use crate::Ruma;
/// # `PUT /_matrix/federation/v2/invite/{roomId}/{eventId}` /// # `PUT /_matrix/federation/v2/invite/{roomId}/{eventId}`
/// ///
/// Invites a remote user to a room. /// Invites a remote user to a room.
#[tracing::instrument(skip_all, fields(%client), name = "invite", level = "info")] #[tracing::instrument(skip_all, fields(%client), name = "invite")]
pub(crate) async fn create_invite_route( pub(crate) async fn create_invite_route(
State(services): State<crate::State>, State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
@@ -148,15 +148,6 @@ pub(crate) async fn create_invite_route(
return Err!(Request(Forbidden("This server does not allow room invites."))); return Err!(Request(Forbidden("This server does not allow room invites.")));
} }
if let Err(e) = services
.antispam
.user_may_invite(sender_user.to_owned(), recipient_user.clone(), body.room_id.clone())
.await
{
warn!("Antispam rejected invite: {e:?}");
return Err!(Request(Forbidden("Invite rejected by antispam service.")));
}
let mut invite_state = body.invite_room_state.clone(); let mut invite_state = body.invite_room_state.clone();
let mut event: JsonObject = serde_json::from_str(body.event.get()) let mut event: JsonObject = serde_json::from_str(body.event.get())
+23 -51
View File
@@ -1,7 +1,7 @@
use std::borrow::ToOwned;
use axum::extract::State; use axum::extract::State;
use conduwuit::{Err, Error, Result, debug, debug_info, info, matrix::pdu::PduBuilder, warn}; use conduwuit::{
Err, Error, Result, debug_info, info, matrix::pdu::PduBuilder, utils::IterStream, warn,
};
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::StreamExt; use futures::StreamExt;
use ruma::{ use ruma::{
@@ -22,7 +22,7 @@ use crate::Ruma;
/// # `GET /_matrix/federation/v1/make_join/{roomId}/{userId}` /// # `GET /_matrix/federation/v1/make_join/{roomId}/{userId}`
/// ///
/// Creates a join template. /// Creates a join template.
#[tracing::instrument(skip_all, fields(room_id = %body.room_id, user_id = %body.user_id, origin = %body.origin()), level = "info")] #[tracing::instrument(skip_all, fields(room_id = %body.room_id, user_id = %body.user_id, origin = %body.origin()))]
pub(crate) async fn create_join_event_template_route( pub(crate) async fn create_join_event_template_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<prepare_join_event::v1::Request>, body: Ruma<prepare_join_event::v1::Request>,
@@ -122,16 +122,6 @@ pub(crate) async fn create_join_event_template_route(
None None
} }
}; };
if services.antispam.check_all_joins() && join_authorized_via_users_server.is_none() {
if services
.antispam
.meowlnir_accept_make_join(body.room_id.clone(), body.user_id.clone())
.await
.is_err()
{
return Err!(Request(Forbidden("Antispam rejected join request.")));
}
}
let (_pdu, mut pdu_json) = services let (_pdu, mut pdu_json) = services
.rooms .rooms
@@ -146,6 +136,7 @@ pub(crate) async fn create_join_event_template_route(
&state_lock, &state_lock,
) )
.await?; .await?;
drop(state_lock); drop(state_lock);
// room v3 and above removed the "event_id" field from remote PDU format // room v3 and above removed the "event_id" field from remote PDU format
@@ -201,44 +192,25 @@ pub(crate) async fn user_can_perform_restricted_join(
return Ok(false); return Ok(false);
} }
for allow_rule in &r.allow { if r.allow
match allow_rule { .iter()
| AllowRule::RoomMembership(membership) => { .filter_map(|rule| {
if services if let AllowRule::RoomMembership(membership) = rule {
.rooms Some(membership)
.state_cache } else {
.is_joined(user_id, &membership.room_id) None
.await }
{ })
debug!( .stream()
"User {} is allowed to join room {} via membership in room {}", .any(|m| services.rooms.state_cache.is_joined(user_id, &m.room_id))
user_id, room_id, membership.room_id .await
); {
return Ok(true); Ok(true)
} } else {
}, Err!(Request(UnableToAuthorizeJoin(
| AllowRule::UnstableSpamChecker => "Joining user is not known to be in any required room."
return match services )))
.antispam
.meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned())
.await
{
| Ok(()) => Ok(true),
| Err(_) => Err!(Request(Forbidden("Antispam rejected join request."))),
},
| _ => {
debug_info!(
"Unsupported allow rule in restricted join for room {}: {:?}",
room_id,
allow_rule
);
},
}
} }
Err!(Request(UnableToAuthorizeJoin(
"Joining user is not known to be in any required room."
)))
} }
pub(crate) fn maybe_strip_event_id( pub(crate) fn maybe_strip_event_id(
+8 -6
View File
@@ -3,7 +3,9 @@ use std::{collections::BTreeMap, net::IpAddr, time::Instant};
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{ use conduwuit::{
Err, Error, Result, debug, debug_warn, err, error, Err, Error, Result, debug,
debug::INFO_SPAN_LEVEL,
debug_warn, err, error,
result::LogErr, result::LogErr,
trace, trace,
utils::{ utils::{
@@ -46,7 +48,7 @@ type Pdu = (OwnedRoomId, OwnedEventId, CanonicalJsonObject);
/// Push EDUs and PDUs to this server. /// Push EDUs and PDUs to this server.
#[tracing::instrument( #[tracing::instrument(
name = "txn", name = "txn",
level = "debug", level = INFO_SPAN_LEVEL,
skip_all, skip_all,
fields( fields(
%client, %client,
@@ -81,8 +83,8 @@ pub(crate) async fn send_transaction_message_route(
pdus = body.pdus.len(), pdus = body.pdus.len(),
edus = body.edus.len(), edus = body.edus.len(),
elapsed = ?txn_start_time.elapsed(), elapsed = ?txn_start_time.elapsed(),
id = %body.transaction_id, id = ?body.transaction_id,
origin = %body.origin(), origin =?body.origin(),
"Starting txn", "Starting txn",
); );
@@ -108,8 +110,8 @@ pub(crate) async fn send_transaction_message_route(
pdus = body.pdus.len(), pdus = body.pdus.len(),
edus = body.edus.len(), edus = body.edus.len(),
elapsed = ?txn_start_time.elapsed(), elapsed = ?txn_start_time.elapsed(),
id = %body.transaction_id, id = ?body.transaction_id,
origin = %body.origin(), origin =?body.origin(),
"Finished txn", "Finished txn",
); );
for (id, result) in &results { for (id, result) in &results {
+1 -1
View File
@@ -26,7 +26,7 @@ use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
use crate::Ruma; use crate::Ruma;
/// helper method for /send_join v1 and v2 /// helper method for /send_join v1 and v2
#[tracing::instrument(skip(services, pdu, omit_members), fields(room_id = room_id.as_str(), origin = origin.as_str()), level = "info")] #[tracing::instrument(skip(services, pdu, omit_members), fields(room_id = room_id.as_str(), origin = origin.as_str()))]
async fn create_join_event( async fn create_join_event(
services: &Services, services: &Services,
origin: &ServerName, origin: &ServerName,
+1 -5
View File
@@ -1,5 +1,3 @@
use std::time::Duration;
use axum::extract::State; use axum::extract::State;
use conduwuit::{Error, Result}; use conduwuit::{Error, Result};
use futures::{FutureExt, StreamExt, TryFutureExt}; use futures::{FutureExt, StreamExt, TryFutureExt};
@@ -98,7 +96,6 @@ pub(crate) async fn get_keys_route(
&body.device_keys, &body.device_keys,
|u| Some(u.server_name()) == body.origin.as_deref(), |u| Some(u.server_name()) == body.origin.as_deref(),
services.globals.allow_device_name_federation(), services.globals.allow_device_name_federation(),
Duration::from_secs(0),
) )
.await?; .await?;
@@ -127,8 +124,7 @@ pub(crate) async fn claim_keys_route(
)); ));
} }
let result = let result = claim_keys_helper(&services, &body.one_time_keys).await?;
claim_keys_helper(&services, &body.one_time_keys, Duration::from_secs(0)).await?;
Ok(claim_keys::v1::Response { one_time_keys: result.one_time_keys }) Ok(claim_keys::v1::Response { one_time_keys: result.one_time_keys })
} }
+2
View File
@@ -1,7 +1,9 @@
[package] [package]
name = "conduwuit_build_metadata" name = "conduwuit_build_metadata"
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
+2
View File
@@ -1,7 +1,9 @@
[package] [package]
name = "conduwuit_core" name = "conduwuit_core"
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
+2 -2
View File
@@ -340,7 +340,7 @@ where
#[tracing::instrument( #[tracing::instrument(
name = "get", name = "get",
level = "trace", level = "trace"
skip_all, skip_all,
fields(?key) fields(?key)
)] )]
@@ -357,7 +357,7 @@ where
#[tracing::instrument( #[tracing::instrument(
name = "xchg", name = "xchg",
level = "trace", level = "trace"
skip_all, skip_all,
fields(?key, ?val) fields(?key, ?val)
)] )]
+36
View File
@@ -146,6 +146,22 @@ pub fn check(config: &Config) -> Result {
)); ));
} }
// check if we can read the token file path, and check if the file is empty
if config.registration_token_file.as_ref().is_some_and(|path| {
let Ok(token) = std::fs::read_to_string(path).inspect_err(|e| {
error!("Failed to read the registration token file: {e}");
}) else {
return true;
};
token == String::new()
}) {
return Err!(Config(
"registration_token_file",
"Registration token file was specified but is empty or failed to be read"
));
}
if config.max_request_size < 10_000_000 { if config.max_request_size < 10_000_000 {
return Err!(Config( return Err!(Config(
"max_request_size", "max_request_size",
@@ -171,9 +187,29 @@ pub fn check(config: &Config) -> Result {
)); ));
} }
if config.allow_registration
&& !config.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
&& config.registration_token.is_none()
&& config.registration_token_file.is_none()
&& config.recaptcha_site_key.is_none()
{
return Err!(Config(
"registration_token",
"!! You have `allow_registration` enabled without a token or captcha configured \
which means you are allowing ANYONE to register on your continuwuity instance \
without any 2nd-step (e.g. registration token, captcha), which is FREQUENTLY \
abused by malicious actors. If this is not the intended behaviour, please set a \
registration token. For security and safety reasons, continuwuity will shut down. \
If you are extra sure this is the desired behaviour you want, please set the \
following config option to true:
`yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`"
));
}
if config.allow_registration if config.allow_registration
&& config.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse && config.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
&& config.registration_token.is_none() && config.registration_token.is_none()
&& config.registration_token_file.is_none()
{ {
warn!( warn!(
"Open registration is enabled via setting \ "Open registration is enabled via setting \
+1 -1
View File
@@ -59,7 +59,7 @@ impl Deref for Manager {
/// Update the active configuration, returning prior configuration. /// Update the active configuration, returning prior configuration.
#[implement(Manager)] #[implement(Manager)]
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all)]
pub fn update(&self, config: Config) -> Result<Arc<Config>> { pub fn update(&self, config: Config) -> Result<Arc<Config>> {
let config = Arc::new(config); let config = Arc::new(config);
let new = Arc::into_raw(config); let new = Arc::into_raw(config);
+15 -80
View File
@@ -18,7 +18,7 @@ use figment::providers::{Env, Format, Toml};
pub use figment::{Figment, value::Value as FigmentValue}; pub use figment::{Figment, value::Value as FigmentValue};
use regex::RegexSet; use regex::RegexSet;
use ruma::{ use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomVersionId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomVersionId,
api::client::discovery::discover_support::ContactRole, api::client::discovery::discover_support::ContactRole,
}; };
use serde::{Deserialize, de::IgnoredAny}; use serde::{Deserialize, de::IgnoredAny};
@@ -53,8 +53,7 @@ use crate::{Result, err, error::Error, utils::sys};
### For more information, see: ### For more information, see:
### https://continuwuity.org/configuration.html ### https://continuwuity.org/configuration.html
"#, "#,
ignore = "config_paths catchall well_known tls blurhashing \ ignore = "config_paths catchall well_known tls blurhashing allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure"
allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure antispam"
)] )]
pub struct Config { pub struct Config {
// Paths to config file(s). Not supposed to be set manually in the config file, // Paths to config file(s). Not supposed to be set manually in the config file,
@@ -545,7 +544,7 @@ pub struct Config {
/// `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` /// `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
/// ///
/// If you would like registration only via token reg, please configure /// If you would like registration only via token reg, please configure
/// `registration_token`. /// `registration_token` or `registration_token_file`.
#[serde(default)] #[serde(default)]
pub allow_registration: bool, pub allow_registration: bool,
@@ -576,14 +575,22 @@ pub struct Config {
/// `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` /// `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`
/// to true to allow open registration without any conditions. /// to true to allow open registration without any conditions.
/// ///
/// If you do not want to set a static token, the `!admin token` commands /// YOU NEED TO EDIT THIS OR USE registration_token_file.
/// may also be used to manage registration tokens.
/// ///
/// example: "o&^uCtes4HPf0Vu@F20jQeeWE7" /// example: "o&^uCtes4HPf0Vu@F20jQeeWE7"
/// ///
/// display: sensitive /// display: sensitive
pub registration_token: Option<String>, pub registration_token: Option<String>,
/// Path to a file on the system that gets read for additional registration
/// tokens. Multiple tokens can be added if you separate them with
/// whitespace
///
/// continuwuity must be able to access the file, and it must not be empty
///
/// example: "/etc/continuwuity/.reg_token"
pub registration_token_file: Option<PathBuf>,
/// The public site key for reCaptcha. If this is provided, reCaptcha /// The public site key for reCaptcha. If this is provided, reCaptcha
/// becomes required during registration. If both captcha *and* /// becomes required during registration. If both captcha *and*
/// registration token are enabled, both will be required during /// registration token are enabled, both will be required during
@@ -1812,22 +1819,6 @@ pub struct Config {
#[serde(default = "default_admin_room_tag")] #[serde(default = "default_admin_room_tag")]
pub admin_room_tag: String, pub admin_room_tag: String,
/// A list of Matrix IDs that are qualified as server admins.
///
/// Any Matrix IDs within this list are regarded as an admin
/// regardless of whether they are in the admin room or not
///
/// default: []
#[serde(default)]
pub admins_list: Vec<OwnedUserId>,
/// Defines whether those within the admin room are added to the
/// admins_list.
///
/// default: true
#[serde(default = "true_fn")]
pub admins_from_room: bool,
/// Sentry.io crash/panic reporting, performance monitoring/metrics, etc. /// Sentry.io crash/panic reporting, performance monitoring/metrics, etc.
/// This is NOT enabled by default. /// This is NOT enabled by default.
#[serde(default)] #[serde(default)]
@@ -1880,7 +1871,7 @@ pub struct Config {
/// Enable the tokio-console. This option is only relevant to developers. /// Enable the tokio-console. This option is only relevant to developers.
/// ///
/// For more information, see: /// For more information, see:
/// https://continuwuity.org/development.html#debugging-with-tokio-console /// https://continuwuity.org/development.html#debugging-with-tokio-console
#[serde(default)] #[serde(default)]
pub tokio_console: bool, pub tokio_console: bool,
@@ -2017,10 +2008,6 @@ pub struct Config {
#[serde(default)] #[serde(default)]
pub ldap: LdapConfig, pub ldap: LdapConfig,
/// Configuration for antispam support
#[serde(default)]
pub antispam: Option<Antispam>,
// external structure; separate section // external structure; separate section
#[serde(default)] #[serde(default)]
pub blurhashing: BlurhashConfig, pub blurhashing: BlurhashConfig,
@@ -2237,58 +2224,7 @@ struct ListeningAddr {
addrs: Either<IpAddr, Vec<IpAddr>>, addrs: Either<IpAddr, Vec<IpAddr>>,
} }
#[derive(Clone, Debug, Deserialize)] const DEPRECATED_KEYS: &[&str; 9] = &[
pub struct Antispam {
pub meowlnir: Option<MeowlnirConfig>,
pub draupnir: Option<DraupnirConfig>,
}
#[derive(Clone, Debug, Deserialize)]
#[config_example_generator(
filename = "conduwuit-example.toml",
section = "global.antispam.meowlnir"
)]
pub struct MeowlnirConfig {
/// The base URL on which to contact Meowlnir (before /_meowlnir/antispam).
///
/// Example: "http://127.0.0.1:29339"
pub base_url: Url,
/// The authentication secret defined in antispam->secret. Required for
/// continuwuity to talk to Meowlnir.
pub secret: String,
/// The management room for which to send requests
pub management_room: OwnedRoomId,
/// If enabled run all federated join attempts (both federated and local)
/// through the Meowlnir anti-spam checks.
///
/// By default, only join attempts for rooms with the `fi.mau.spam_checker`
/// restricted join rule are checked.
#[serde(default)]
pub check_all_joins: bool,
}
// TODO: the DraupnirConfig and MeowlnirConfig are basically identical.
// Maybe management_room could just become an Option<> and these structs merged?
#[derive(Clone, Debug, Deserialize)]
#[config_example_generator(
filename = "conduwuit-example.toml",
section = "global.antispam.draupnir"
)]
pub struct DraupnirConfig {
/// The base URL on which to contact Draupnir (before /api/).
///
/// Example: "http://127.0.0.1:29339"
pub base_url: Url,
/// The authentication secret defined in
/// web->synapseHTTPAntispam->authorization
pub secret: String,
}
const DEPRECATED_KEYS: &[&str] = &[
"cache_capacity", "cache_capacity",
"conduit_cache_capacity_modifier", "conduit_cache_capacity_modifier",
"max_concurrent_requests", "max_concurrent_requests",
@@ -2298,7 +2234,6 @@ const DEPRECATED_KEYS: &[&str] = &[
"well_known_support_role", "well_known_support_role",
"well_known_support_email", "well_known_support_email",
"well_known_support_mxid", "well_known_support_mxid",
"registration_token_file",
]; ];
impl Config { impl Config {
+1 -3
View File
@@ -75,12 +75,10 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
| ThreepidDenied | ThreepidDenied
| InviteBlocked | InviteBlocked
| WrongRoomKeysVersion { .. } | WrongRoomKeysVersion { .. }
| UserSuspended
| Forbidden { .. } => StatusCode::FORBIDDEN, | Forbidden { .. } => StatusCode::FORBIDDEN,
// 401 // 401
| UnknownToken { .. } | MissingToken | Unauthorized | UserLocked => | UnknownToken { .. } | MissingToken | Unauthorized => StatusCode::UNAUTHORIZED,
StatusCode::UNAUTHORIZED,
// 400 // 400
| _ => StatusCode::BAD_REQUEST, | _ => StatusCode::BAD_REQUEST,
+10 -11
View File
@@ -532,8 +532,8 @@ where
if sender_power_level < invite_level { if sender_power_level < invite_level {
warn!( warn!(
%sender, %sender,
has=%sender_power_level, has=?sender_power_level,
required=%invite_level, required=?invite_level,
"sender cannot send invites in this room" "sender cannot send invites in this room"
); );
return Ok(false); return Ok(false);
@@ -605,8 +605,8 @@ where
if !check_redaction(room_version, incoming_event, sender_power_level, redact_level)? { if !check_redaction(room_version, incoming_event, sender_power_level, redact_level)? {
warn!( warn!(
%sender, %sender,
%sender_power_level, ?sender_power_level,
%redact_level, ?redact_level,
"redaction event was not allowed" "redaction event was not allowed"
); );
return Ok(false); return Ok(false);
@@ -772,12 +772,11 @@ where
power_levels_event.as_ref().is_some(), power_levels_event.as_ref().is_some(),
) || auth_user_pl >= invite_level; ) || auth_user_pl >= invite_level;
trace!( trace!(
%auth_user_pl, auth_user_pl=?auth_user_pl,
%auth_user_pl, invite_level=?invite_level,
%invite_level, user_joined=?user_joined,
%user_joined, okay_power=?okay_power,
%okay_power, passing=?(user_joined && okay_power),
passing=%(user_joined && okay_power),
"user for join auth is valid check details" "user for join auth is valid check details"
); );
user_joined && okay_power user_joined && okay_power
@@ -1212,7 +1211,7 @@ fn can_send_event(event: &impl Event, ple: Option<&impl Event>, user_level: Int)
{ {
warn!( warn!(
%user_level, %user_level,
required=%event_type_power_level, required=?event_type_power_level,
state_key=?event.state_key(), state_key=?event.state_key(),
sender=%event.sender(), sender=%event.sender(),
"state_key starts with @ but does not match sender", "state_key starts with @ but does not match sender",
+2
View File
@@ -1,7 +1,9 @@
[package] [package]
name = "conduwuit_database" name = "conduwuit_database"
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
+1 -1
View File
@@ -7,7 +7,7 @@ use super::Engine;
use crate::util::map_err; use crate::util::map_err;
#[implement(Engine)] #[implement(Engine)]
#[tracing::instrument(skip(self), level = "info")] #[tracing::instrument(skip(self))]
pub fn backup(&self) -> Result { pub fn backup(&self) -> Result {
let mut engine = self.backup_engine()?; let mut engine = self.backup_engine()?;
let config = &self.ctx.server.config; let config = &self.ctx.server.config;
+1 -1
View File
@@ -4,7 +4,7 @@ use rocksdb::LogLevel;
#[tracing::instrument( #[tracing::instrument(
parent = None, parent = None,
name = "rocksdb", name = "rocksdb",
level = "trace", level = "trace"
skip(msg), skip(msg),
)] )]
pub(crate) fn handle(level: LogLevel, msg: &str) { pub(crate) fn handle(level: LogLevel, msg: &str) {
+3 -3
View File
@@ -17,7 +17,7 @@ use super::{
use crate::{Context, or_else}; use crate::{Context, or_else};
#[implement(Engine)] #[implement(Engine)]
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all)]
pub(crate) async fn open(ctx: Arc<Context>, desc: &[Descriptor]) -> Result<Arc<Self>> { pub(crate) async fn open(ctx: Arc<Context>, desc: &[Descriptor]) -> Result<Arc<Self>> {
let server = &ctx.server; let server = &ctx.server;
let config = &server.config; let config = &server.config;
@@ -63,7 +63,7 @@ pub(crate) async fn open(ctx: Arc<Context>, desc: &[Descriptor]) -> Result<Arc<S
} }
#[implement(Engine)] #[implement(Engine)]
#[tracing::instrument(name = "configure", skip_all, level = "debug")] #[tracing::instrument(name = "configure", skip_all)]
fn configure_cfds( fn configure_cfds(
ctx: &Arc<Context>, ctx: &Arc<Context>,
db_opts: &Options, db_opts: &Options,
@@ -119,7 +119,7 @@ fn configure_cfds(
} }
#[implement(Engine)] #[implement(Engine)]
#[tracing::instrument(name = "discover", skip_all, level = "debug")] #[tracing::instrument(name = "discover", skip_all)]
fn discover_cfs(path: &Path, opts: &Options) -> BTreeSet<String> { fn discover_cfs(path: &Path, opts: &Options) -> BTreeSet<String> {
Db::list_cf(opts, path) Db::list_cf(opts, path)
.unwrap_or_default() .unwrap_or_default()
+1 -1
View File
@@ -26,7 +26,7 @@ pub struct Options {
#[implement(super::Map)] #[implement(super::Map)]
#[tracing::instrument( #[tracing::instrument(
name = "compact", name = "compact",
level = "info", level = "info"
skip(self), skip(self),
fields(%self), fields(%self),
)] )]
-12
View File
@@ -141,10 +141,6 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "referencedevents", name: "referencedevents",
..descriptor::RANDOM ..descriptor::RANDOM
}, },
Descriptor {
name: "registrationtoken_info",
..descriptor::RANDOM_SMALL
},
Descriptor { Descriptor {
name: "roomid_invitedcount", name: "roomid_invitedcount",
..descriptor::RANDOM_SMALL ..descriptor::RANDOM_SMALL
@@ -390,14 +386,6 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "userid_suspension", name: "userid_suspension",
..descriptor::RANDOM_SMALL ..descriptor::RANDOM_SMALL
}, },
Descriptor {
name: "userid_lock",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userid_logindisabled",
..descriptor::RANDOM_SMALL
},
Descriptor { Descriptor {
name: "userid_presenceid", name: "userid_presenceid",
..descriptor::RANDOM_SMALL ..descriptor::RANDOM_SMALL
+4 -4
View File
@@ -113,7 +113,7 @@ impl Drop for Pool {
} }
#[implement(Pool)] #[implement(Pool)]
#[tracing::instrument(skip_all, level = "debug")] #[tracing::instrument(skip_all)]
pub(crate) fn close(&self) { pub(crate) fn close(&self) {
let workers = take(&mut *self.workers.lock()); let workers = take(&mut *self.workers.lock());
@@ -147,8 +147,8 @@ pub(crate) fn close(&self) {
.map(|result| result.map_err(Error::from_panic)) .map(|result| result.map_err(Error::from_panic))
.enumerate() .enumerate()
.for_each(|(id, result)| match result { .for_each(|(id, result)| match result {
| Ok(()) => trace!(%id, "worker joined"), | Ok(()) => trace!(?id, "worker joined"),
| Err(error) => error!(%id, "worker joined with error: {error}"), | Err(error) => error!(?id, "worker joined with error: {error}"),
}); });
} }
@@ -297,7 +297,7 @@ fn worker_init(&self, id: usize) {
} }
debug!( debug!(
%group, ?group,
affinity = ?affinity.collect::<Vec<_>>(), affinity = ?affinity.collect::<Vec<_>>(),
"worker ready" "worker ready"
); );
+9 -9
View File
@@ -105,8 +105,8 @@ pub(super) fn configure(server: &Arc<Server>) -> (usize, Vec<usize>, Vec<usize>)
.unwrap_or("None"), .unwrap_or("None"),
?worker_counts, ?worker_counts,
?queue_sizes, ?queue_sizes,
%total_workers, ?total_workers,
stream_width = %stream::automatic_width(), stream_width = ?stream::automatic_width(),
"Frontend topology", "Frontend topology",
); );
@@ -139,13 +139,13 @@ fn update_stream_width(server: &Arc<Server>, num_queues: usize, total_workers: u
let (old_width, new_width) = stream::set_width(req_width); let (old_width, new_width) = stream::set_width(req_width);
let (old_amp, new_amp) = stream::set_amplification(req_amp); let (old_amp, new_amp) = stream::set_amplification(req_amp);
debug!( debug!(
scale = %config.stream_width_scale, scale = ?config.stream_width_scale,
%num_queues, ?num_queues,
%req_width, ?req_width,
%old_width, ?old_width,
%new_width, ?new_width,
%old_amp, ?old_amp,
%new_amp, ?new_amp,
"Updated global stream width" "Updated global stream width"
); );
} }
+2
View File
@@ -1,7 +1,9 @@
[package] [package]
name = "conduwuit_macros" name = "conduwuit_macros"
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
+6 -2
View File
@@ -2,12 +2,15 @@
name = "conduwuit" name = "conduwuit"
default-run = "conduwuit" default-run = "conduwuit"
authors.workspace = true authors.workspace = true
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
homepage.workspace = true homepage.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
rust-version.workspace = true
version.workspace = true version.workspace = true
metadata.crane.workspace = true metadata.crane.workspace = true
@@ -20,13 +23,14 @@ crate-type = [
[package.metadata.deb] [package.metadata.deb]
name = "continuwuity" name = "continuwuity"
maintainer = "Continuwuity Team and contributors <team@continuwuity.org>" maintainer = "continuwuity developers <contact@continuwuity.org>"
copyright = "2024, continuwuity developers"
license-file = ["../../LICENSE", "3"] license-file = ["../../LICENSE", "3"]
depends = "$auto, ca-certificates" depends = "$auto, ca-certificates"
breaks = ["conduwuit (<<0.5.0)"] breaks = ["conduwuit (<<0.5.0)"]
replaces = ["conduwuit (<<0.5.0)"] replaces = ["conduwuit (<<0.5.0)"]
extended-description = """\ extended-description = """\
A Matrix homeserver written in Rust, the official continuation of the conduwuit homeserver.""" a cool hard fork of Conduit, a Matrix homeserver written in Rust"""
section = "net" section = "net"
priority = "optional" priority = "optional"
conf-files = ["/etc/conduwuit/conduwuit.toml"] conf-files = ["/etc/conduwuit/conduwuit.toml"]
+2 -3
View File
@@ -6,7 +6,6 @@ use conduwuit_core::{
debug_warn, err, debug_warn, err,
log::{ConsoleFormat, ConsoleWriter, LogLevelReloadHandles, capture, fmt_span}, log::{ConsoleFormat, ConsoleWriter, LogLevelReloadHandles, capture, fmt_span},
result::UnwrapOrErr, result::UnwrapOrErr,
warn,
}; };
#[cfg(feature = "otlp_telemetry")] #[cfg(feature = "otlp_telemetry")]
use opentelemetry::trace::TracerProvider; use opentelemetry::trace::TracerProvider;
@@ -86,7 +85,7 @@ pub(crate) fn init(
let exporter = match config.otlp_protocol.as_str() { let exporter = match config.otlp_protocol.as_str() {
| "grpc" => opentelemetry_otlp::SpanExporter::builder() | "grpc" => opentelemetry_otlp::SpanExporter::builder()
.with_tonic() .with_tonic()
.with_protocol(opentelemetry_otlp::Protocol::Grpc) // TODO: build from env when 0.32 is released .with_protocol(opentelemetry_otlp::Protocol::Grpc)
.build() .build()
.expect("Failed to create OTLP gRPC exporter"), .expect("Failed to create OTLP gRPC exporter"),
| "http" => opentelemetry_otlp::SpanExporter::builder() | "http" => opentelemetry_otlp::SpanExporter::builder()
@@ -94,7 +93,7 @@ pub(crate) fn init(
.build() .build()
.expect("Failed to create OTLP HTTP exporter"), .expect("Failed to create OTLP HTTP exporter"),
| protocol => { | protocol => {
warn!( debug_warn!(
"Invalid OTLP protocol '{}', falling back to HTTP. Valid options are \ "Invalid OTLP protocol '{}', falling back to HTTP. Valid options are \
'http' or 'grpc'.", 'http' or 'grpc'.",
protocol protocol
+1 -2
View File
@@ -50,8 +50,7 @@ pub fn run_with_args(args: &Args) -> Result<()> {
#[tracing::instrument( #[tracing::instrument(
name = "main", name = "main",
parent = None, parent = None,
skip_all, skip_all
level = "info"
)] )]
async fn async_main(server: &Arc<Server>) -> Result<(), Error> { async fn async_main(server: &Arc<Server>) -> Result<(), Error> {
extern crate conduwuit_router as router; extern crate conduwuit_router as router;
+3 -3
View File
@@ -6,7 +6,7 @@ use tokio::signal;
use super::server::Server; use super::server::Server;
#[cfg(unix)] #[cfg(unix)]
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all)]
pub(super) async fn signal(server: Arc<Server>) { pub(super) async fn signal(server: Arc<Server>) {
use signal::unix; use signal::unix;
use unix::SignalKind; use unix::SignalKind;
@@ -39,13 +39,13 @@ pub(super) async fn signal(server: Arc<Server>) {
}; };
if let Err(e) = result { if let Err(e) = result {
debug_error!(%sig, "signal: {e}"); debug_error!(?sig, "signal: {e}");
} }
} }
} }
#[cfg(not(unix))] #[cfg(not(unix))]
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all)]
pub(super) async fn signal(server: Arc<Server>) { pub(super) async fn signal(server: Arc<Server>) {
loop { loop {
tokio::select! { tokio::select! {
+2
View File
@@ -1,7 +1,9 @@
[package] [package]
name = "conduwuit_router" name = "conduwuit_router"
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
+1 -4
View File
@@ -66,10 +66,7 @@ pub(crate) fn build(services: &Arc<Services>) -> Result<(Router, Guard)> {
.layer(RequestBodyTimeoutLayer::new(Duration::from_secs( .layer(RequestBodyTimeoutLayer::new(Duration::from_secs(
server.config.client_receive_timeout, server.config.client_receive_timeout,
))) )))
.layer(TimeoutLayer::with_status_code( .layer(TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, Duration::from_secs(server.config.client_request_timeout)))
StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(server.config.client_request_timeout),
))
.layer(SetResponseHeaderLayer::if_not_present( .layer(SetResponseHeaderLayer::if_not_present(
HeaderName::from_static("origin-agent-cluster"), // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin-Agent-Cluster HeaderName::from_static("origin-agent-cluster"), // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin-Agent-Cluster
HeaderValue::from_static("?1"), HeaderValue::from_static("?1"),
+4 -4
View File
@@ -102,13 +102,13 @@ fn handle_result(method: &Method, uri: &Uri, result: Response) -> Result<Respons
let reason = status.canonical_reason().unwrap_or("Unknown Reason"); let reason = status.canonical_reason().unwrap_or("Unknown Reason");
if status.is_server_error() { if status.is_server_error() {
error!(%method, %uri, "{code} {reason}"); error!(method = ?method, uri = ?uri, "{code} {reason}");
} else if status.is_client_error() { } else if status.is_client_error() {
debug_error!(%method, %uri, "{code} {reason}"); debug_error!(method = ?method, uri = ?uri, "{code} {reason}");
} else if status.is_redirection() { } else if status.is_redirection() {
debug!(%method, %uri, "{code} {reason}"); debug!(method = ?method, uri = ?uri, "{code} {reason}");
} else { } else {
trace!(%method, %uri, "{code} {reason}"); trace!(method = ?method, uri = ?uri, "{code} {reason}");
} }
if status == StatusCode::METHOD_NOT_ALLOWED { if status == StatusCode::METHOD_NOT_ALLOWED {
+5 -5
View File
@@ -19,7 +19,7 @@ use tokio::{
use crate::serve; use crate::serve;
/// Main loop base /// Main loop base
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all)]
pub(crate) async fn run(services: Arc<Services>) -> Result<()> { pub(crate) async fn run(services: Arc<Services>) -> Result<()> {
let server = &services.server; let server = &services.server;
debug!("Start"); debug!("Start");
@@ -58,7 +58,7 @@ pub(crate) async fn run(services: Arc<Services>) -> Result<()> {
} }
/// Async initializations /// Async initializations
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all)]
pub(crate) async fn start(server: Arc<Server>) -> Result<Arc<Services>> { pub(crate) async fn start(server: Arc<Server>) -> Result<Arc<Services>> {
debug!("Starting..."); debug!("Starting...");
@@ -73,7 +73,7 @@ pub(crate) async fn start(server: Arc<Server>) -> Result<Arc<Services>> {
} }
/// Async destructions /// Async destructions
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all)]
pub(crate) async fn stop(services: Arc<Services>) -> Result<()> { pub(crate) async fn stop(services: Arc<Services>) -> Result<()> {
debug!("Shutting down..."); debug!("Shutting down...");
@@ -108,7 +108,7 @@ pub(crate) async fn stop(services: Arc<Services>) -> Result<()> {
Ok(()) Ok(())
} }
#[tracing::instrument(skip_all, level = "info")] #[tracing::instrument(skip_all)]
async fn signal(server: Arc<Server>, tx: Sender<()>, handle: axum_server::Handle) { async fn signal(server: Arc<Server>, tx: Sender<()>, handle: axum_server::Handle) {
server server
.clone() .clone()
@@ -126,7 +126,7 @@ async fn handle_shutdown(server: Arc<Server>, tx: Sender<()>, handle: axum_serve
let timeout = Duration::from_secs(timeout); let timeout = Duration::from_secs(timeout);
debug!( debug!(
?timeout, ?timeout,
handle_active = %server.metrics.requests_handle_active.load(Ordering::Relaxed), handle_active = ?server.metrics.requests_handle_active.load(Ordering::Relaxed),
"Notifying for graceful shutdown" "Notifying for graceful shutdown"
); );
+2
View File
@@ -1,7 +1,9 @@
[package] [package]
name = "conduwuit_service" name = "conduwuit_service"
categories.workspace = true
description.workspace = true description.workspace = true
edition.workspace = true edition.workspace = true
keywords.workspace = true
license.workspace = true license.workspace = true
readme.workspace = true readme.workspace = true
repository.workspace = true repository.workspace = true
+2 -9
View File
@@ -9,10 +9,7 @@ use rustyline_async::{Readline, ReadlineError, ReadlineEvent};
use termimad::MadSkin; use termimad::MadSkin;
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use crate::{ use crate::{Dep, admin};
Dep,
admin::{self, InvocationSource},
};
pub struct Console { pub struct Console {
server: Arc<Server>, server: Arc<Server>,
@@ -163,11 +160,7 @@ impl Console {
} }
async fn process(self: Arc<Self>, line: String) { async fn process(self: Arc<Self>, line: String) {
match self match self.admin.command_in_place(line, None).await {
.admin
.command_in_place(line, None, InvocationSource::Console)
.await
{
| Ok(Some(ref content)) => self.output(content), | Ok(Some(ref content)) => self.output(content),
| Err(ref content) => self.output_err(content), | Err(ref content) => self.output_err(content),
| _ => unreachable!(), | _ => unreachable!(),
+1 -6
View File
@@ -2,8 +2,6 @@ use conduwuit::{Err, Result, debug, debug_info, error, implement, info};
use ruma::events::room::message::RoomMessageEventContent; use ruma::events::room::message::RoomMessageEventContent;
use tokio::time::{Duration, sleep}; use tokio::time::{Duration, sleep};
use crate::admin::InvocationSource;
pub(super) const SIGNAL: &str = "SIGUSR2"; pub(super) const SIGNAL: &str = "SIGUSR2";
/// Possibly spawn the terminal console at startup if configured. /// Possibly spawn the terminal console at startup if configured.
@@ -90,10 +88,7 @@ pub(super) async fn signal_execute(&self) -> Result {
async fn execute_command(&self, i: usize, command: String) -> Result { async fn execute_command(&self, i: usize, command: String) -> Result {
debug!("Execute command #{i}: executing {command:?}"); debug!("Execute command #{i}: executing {command:?}");
match self match self.command_in_place(command, None).await {
.command_in_place(command, None, InvocationSource::Console)
.await
{
| Ok(Some(output)) => Self::execute_command_output(i, &output), | Ok(Some(output)) => Self::execute_command_output(i, &output),
| Err(output) => Self::execute_command_error(i, &output), | Err(output) => Self::execute_command_error(i, &output),
| Ok(None) => { | Ok(None) => {
+2 -17
View File
@@ -1,8 +1,6 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use conduwuit::{ use conduwuit::{Err, Result, debug_info, debug_warn, error, implement, matrix::pdu::PduBuilder};
Err, Result, debug_info, debug_warn, error, implement, matrix::pdu::PduBuilder, warn,
};
use ruma::{ use ruma::{
RoomId, UserId, RoomId, UserId,
events::{ events::{
@@ -122,7 +120,7 @@ pub async fn make_user_admin(&self, user_id: &UserId) -> Result {
let room_tag = self.services.server.config.admin_room_tag.as_str(); let room_tag = self.services.server.config.admin_room_tag.as_str();
if !room_tag.is_empty() { if !room_tag.is_empty() {
if let Err(e) = self.set_room_tag(&room_id, user_id, room_tag).await { if let Err(e) = self.set_room_tag(&room_id, user_id, room_tag).await {
error!(%room_id, %user_id, %room_tag, "Failed to set tag for admin grant: {e}"); error!(?room_id, ?user_id, ?room_tag, "Failed to set tag for admin grant: {e}");
} }
} }
@@ -178,19 +176,6 @@ async fn set_room_tag(&self, room_id: &RoomId, user_id: &UserId, tag: &str) -> R
pub async fn revoke_admin(&self, user_id: &UserId) -> Result { pub async fn revoke_admin(&self, user_id: &UserId) -> Result {
use MembershipState::{Invite, Join, Knock, Leave}; use MembershipState::{Invite, Join, Knock, Leave};
if self
.services
.server
.config
.admins_list
.contains(&user_id.to_owned())
{
warn!(
"Revoking the admin status of {user_id} will not work correctly as they are within \
the admins_list config."
);
}
let Ok(room_id) = self.get_admin_room().await else { let Ok(room_id) = self.get_admin_room().await else {
return Err!(error!("No admin room available or created.")); return Err!(error!("No admin room available or created."));
}; };
+61 -129
View File
@@ -14,10 +14,10 @@ use conduwuit_core::{
Error, Event, Result, Server, debug, err, error, error::default_log, pdu::PduBuilder, Error, Event, Result, Server, debug, err, error, error::default_log, pdu::PduBuilder,
}; };
pub use create::create_admin_room; pub use create::create_admin_room;
use futures::{Future, FutureExt, StreamExt, TryFutureExt}; use futures::{Future, FutureExt, TryFutureExt};
use loole::{Receiver, Sender}; use loole::{Receiver, Sender};
use ruma::{ use ruma::{
Mxc, OwnedEventId, OwnedMxcUri, OwnedRoomId, OwnedUserId, RoomId, UInt, UserId, Mxc, OwnedEventId, OwnedMxcUri, OwnedRoomId, RoomId, UInt, UserId,
events::{ events::{
Mentions, Mentions,
room::{ room::{
@@ -54,37 +54,15 @@ struct Services {
media: Dep<crate::media::Service>, media: Dep<crate::media::Service>,
} }
/// Inputs to a command are a multi-line string, invocation source, optional /// Inputs to a command are a multi-line string, optional reply_id, and optional
/// reply_id, and optional sender. /// sender.
#[derive(Debug)] #[derive(Debug)]
pub struct CommandInput { pub struct CommandInput {
pub command: String, pub command: String,
pub reply_id: Option<OwnedEventId>, pub reply_id: Option<OwnedEventId>,
pub source: InvocationSource,
pub sender: Option<Box<UserId>>, pub sender: Option<Box<UserId>>,
} }
/// Where a command is being invoked from.
#[derive(Debug, Clone, Copy)]
pub enum InvocationSource {
/// The server's private admin room
AdminRoom,
/// An escaped `\!admin` command in a public room
EscapedCommand,
/// The server's admin console
Console,
/// Some other trusted internal source
Internal,
}
impl InvocationSource {
/// Returns whether this invocation source allows "restricted"
/// commands, i.e. ones that could be potentially dangerous if executed by
/// an attacker or in a public room.
#[must_use]
pub fn allows_restricted(&self) -> bool { !matches!(self, Self::EscapedCommand) }
}
/// Prototype of the tab-completer. The input is buffered text when tab /// Prototype of the tab-completer. The input is buffered text when tab
/// asserted; the output will fully replace the input buffer. /// asserted; the output will fully replace the input buffer.
pub type Completer = fn(&str) -> String; pub type Completer = fn(&str) -> String;
@@ -298,15 +276,10 @@ impl Service {
/// Posts a command to the command processor queue and returns. Processing /// Posts a command to the command processor queue and returns. Processing
/// will take place on the service worker's task asynchronously. Errors if /// will take place on the service worker's task asynchronously. Errors if
/// the queue is full. /// the queue is full.
pub fn command( pub fn command(&self, command: String, reply_id: Option<OwnedEventId>) -> Result<()> {
&self,
command: String,
reply_id: Option<OwnedEventId>,
source: InvocationSource,
) -> Result<()> {
self.channel self.channel
.0 .0
.send(CommandInput { command, reply_id, source, sender: None }) .send(CommandInput { command, reply_id, sender: None })
.map_err(|e| err!("Failed to enqueue admin command: {e:?}")) .map_err(|e| err!("Failed to enqueue admin command: {e:?}"))
} }
@@ -317,17 +290,11 @@ impl Service {
&self, &self,
command: String, command: String,
reply_id: Option<OwnedEventId>, reply_id: Option<OwnedEventId>,
source: InvocationSource,
sender: Box<UserId>, sender: Box<UserId>,
) -> Result<()> { ) -> Result<()> {
self.channel self.channel
.0 .0
.send(CommandInput { .send(CommandInput { command, reply_id, sender: Some(sender) })
command,
reply_id,
source,
sender: Some(sender),
})
.map_err(|e| err!("Failed to enqueue admin command: {e:?}")) .map_err(|e| err!("Failed to enqueue admin command: {e:?}"))
} }
@@ -337,9 +304,8 @@ impl Service {
&self, &self,
command: String, command: String,
reply_id: Option<OwnedEventId>, reply_id: Option<OwnedEventId>,
source: InvocationSource,
) -> ProcessorResult { ) -> ProcessorResult {
self.process_command(CommandInput { command, reply_id, source, sender: None }) self.process_command(CommandInput { command, reply_id, sender: None })
.await .await
} }
@@ -383,50 +349,16 @@ impl Service {
handle(services, command).await handle(services, command).await
} }
/// Returns the list of admins for this server. First loads
/// the admin_list from the configuration, then adds users from
/// the admin room if applicable.
pub async fn get_admins(&self) -> Vec<OwnedUserId> {
let mut generated_admin_list: Vec<OwnedUserId> =
self.services.server.config.admins_list.clone();
if self.services.server.config.admins_from_room {
if let Ok(admin_room) = self.get_admin_room().await {
let admin_users = self.services.state_cache.room_members(&admin_room);
let mut stream = admin_users;
while let Some(user_id) = stream.next().await {
generated_admin_list.push(user_id.to_owned());
}
}
}
generated_admin_list
}
/// Checks whether a given user is an admin of this server /// Checks whether a given user is an admin of this server
pub async fn user_is_admin(&self, user_id: &UserId) -> bool { pub async fn user_is_admin(&self, user_id: &UserId) -> bool {
if self let Ok(admin_room) = self.get_admin_room().await else {
.services return false;
.server };
.config
.admins_list
.contains(&user_id.to_owned())
{
return true;
}
if self.services.server.config.admins_from_room { self.services
if let Ok(admin_room) = self.get_admin_room().await { .state_cache
return self .is_joined(user_id, &admin_room)
.services .await
.state_cache
.is_joined(user_id, &admin_room)
.await;
}
}
false
} }
/// Gets the room ID of the admin room /// Gets the room ID of the admin room
@@ -527,59 +459,59 @@ impl Service {
Ok(()) Ok(())
} }
pub async fn is_admin_command<E>(&self, event: &E, body: &str) -> Option<InvocationSource> pub async fn is_admin_command<E>(&self, event: &E, body: &str) -> bool
where where
E: Event + Send + Sync, E: Event + Send + Sync,
{ {
// If the user isn't an admin they definitely can't run admin commands // Server-side command-escape with public echo
if !self.user_is_admin(event.sender()).await { let is_escape = body.starts_with('\\');
return None; let is_public_escape = is_escape && body.trim_start_matches('\\').starts_with("!admin");
// Admin command with public echo (in admin room)
let server_user = &self.services.globals.server_user;
let is_public_prefix =
body.starts_with("!admin") || body.starts_with(server_user.as_str());
// Expected backward branch
if !is_public_escape && !is_public_prefix {
return false;
} }
if let Some(room_id) = event.room_id() let user_is_local = self.services.globals.user_is_local(event.sender());
&& self.is_admin_room(room_id).await
// only allow public escaped commands by local admins
if is_public_escape && !user_is_local {
return false;
}
// Check if server-side command-escape is disabled by configuration
if is_public_escape && !self.services.server.config.admin_escape_commands {
return false;
}
// Prevent unescaped !admin from being used outside of the admin room
if event.room_id().is_some()
&& is_public_prefix
&& !self.is_admin_room(event.room_id().unwrap()).await
{ {
// This is a message in the admin room return false;
// Ignore messages which aren't admin commands
let server_user = &self.services.globals.server_user;
if !(body.starts_with("!admin") || body.starts_with(server_user.as_str())) {
return None;
}
// Ignore messages from the server user _unless_ the emergency password is set
let emergency_password_set = self.services.server.config.emergency_password.is_some();
if event.sender() == server_user && !emergency_password_set {
return None;
}
// Looks good
Some(InvocationSource::AdminRoom)
} else {
// This is a message outside the admin room
// Is it an escaped admin command? i.e. `\!admin --help`
let is_public_escape =
body.starts_with('\\') && body.trim_start_matches('\\').starts_with("!admin");
// Ignore the message if it's not
if !is_public_escape {
return None;
}
// Only admin users belonging to this server can use escaped commands
if !self.services.globals.user_is_local(event.sender()) {
return None;
}
// Check if escaped commands are disabled in the config
if !self.services.server.config.admin_escape_commands {
return None;
}
// Looks good
Some(InvocationSource::EscapedCommand)
} }
// Only senders who are admin can proceed
if !self.user_is_admin(event.sender()).await {
return false;
}
// This will evaluate to false if the emergency password is set up so that
// the administrator can execute commands as the server user
let emergency_password_set = self.services.server.config.emergency_password.is_some();
let from_server = event.sender() == server_user && !emergency_password_set;
if from_server && self.is_admin_room(event.room_id().unwrap()).await {
return false;
}
// Authentic admin command
true
} }
#[must_use] #[must_use]
+1 -1
View File
@@ -96,7 +96,7 @@ impl crate::Service for Service {
} }
if let Err(e) = self.check().await { if let Err(e) = self.check().await {
warn!(?e, "Failed to check for announcements"); warn!(%e, "Failed to check for announcements");
} }
} }
-182
View File
@@ -1,182 +0,0 @@
use std::{fmt::Debug, sync::Arc};
use async_trait::async_trait;
use conduwuit::{Result, config::Antispam, debug};
use ruma::{OwnedRoomId, OwnedUserId, draupnir_antispam, meowlnir_antispam};
use crate::{client, config, sending, service::Dep};
struct Services {
config: Dep<config::Service>,
client: Dep<client::Service>,
}
pub struct Service {
services: Services,
}
#[async_trait]
impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
Ok(Arc::new(Self {
services: Services {
client: args.depend::<client::Service>("client"),
config: args.depend::<config::Service>("config"),
},
}))
}
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
}
impl Service {
async fn send_antispam_request<T>(
&self,
base_url: &str,
secret: &str,
request: T,
) -> Result<T::IncomingResponse>
where
T: ruma::api::OutgoingRequest + Debug + Send,
{
sending::antispam::send_antispam_request(
&self.services.client.appservice,
base_url,
secret,
request,
)
.await
}
/// Checks with the antispam service whether `inviter` may invite `invitee`
/// to `room_id`.
///
/// If no antispam service is configured, this always returns `Ok(())`.
/// If an error is returned, the invite should be blocked - the antispam
/// service was unreachable, or refused the invite.
pub async fn user_may_invite(
&self,
inviter: OwnedUserId,
invitee: OwnedUserId,
room_id: OwnedRoomId,
) -> Result<()> {
if let Some(config) = &self.services.config.antispam {
let result = if let Some(meowlnir) = &config.meowlnir {
debug!(?room_id, ?inviter, ?invitee, "Asking meowlnir for user_may_invite");
self.send_antispam_request(
meowlnir.base_url.as_str(),
&meowlnir.secret,
meowlnir_antispam::user_may_invite::v1::Request::new(
meowlnir.management_room.clone(),
inviter,
invitee,
room_id,
),
)
.await
.inspect(|_| debug!("meowlnir allowed the invite"))
.inspect_err(|e| debug!("meowlnir denied the invite: {e:?}"))
.map(|_| ())
} else if let Some(draupnir) = &config.draupnir {
debug!(?room_id, ?inviter, ?invitee, "Asking draupnir for user_may_invite");
self.send_antispam_request(
draupnir.base_url.as_str(),
&draupnir.secret,
draupnir_antispam::user_may_invite::v1::Request::new(
room_id, inviter, invitee,
),
)
.await
.inspect(|_| debug!("draupnir allowed the invite"))
.inspect_err(|e| debug!("draupnir denied the invite: {e:?}"))
.map(|_| ())
} else {
Ok(())
};
return result;
}
Ok(())
}
/// Checks with the antispam service whether `user_id` may join `room_id`.
pub async fn user_may_join_room(
&self,
user_id: OwnedUserId,
room_id: OwnedRoomId,
is_invited: bool,
) -> Result<()> {
if let Some(config) = &self.services.config.antispam {
let result = if let Some(meowlnir) = &config.meowlnir {
debug!(?room_id, ?user_id, ?is_invited, "Asking meowlnir for user_may_join_room");
self.send_antispam_request(
meowlnir.base_url.as_str(),
&meowlnir.secret,
meowlnir_antispam::user_may_join_room::v1::Request::new(
meowlnir.management_room.clone(),
user_id,
room_id,
is_invited,
),
)
.await
.inspect(|_| debug!("meowlnir allowed the join"))
.inspect_err(|e| debug!("meowlnir denied the join: {e:?}"))
.map(|_| ())
} else if let Some(draupnir) = &config.draupnir {
debug!(?room_id, ?user_id, ?is_invited, "Asking draupnir for user_may_join_room");
self.send_antispam_request(
draupnir.base_url.as_str(),
&draupnir.secret,
draupnir_antispam::user_may_join_room::v1::Request::new(
user_id, room_id, is_invited,
),
)
.await
.inspect(|_| debug!("draupnir allowed the join"))
.inspect_err(|e| debug!("draupnir denied the join: {e:?}"))
.map(|_| ())
} else {
Ok(())
};
return result;
}
Ok(())
}
/// Checks with Meowlnir whether the incoming federated `make_join` request
/// should be allowed. Applies the `fi.mau.spam_checker` join rule.
pub async fn meowlnir_accept_make_join(
&self,
room_id: OwnedRoomId,
user_id: OwnedUserId,
) -> Result<()> {
if let Some(Antispam { meowlnir: Some(meowlnir), .. }) = &self.services.config.antispam {
debug!(?room_id, ?user_id, "Asking meowlnir for accept_make_join");
self.send_antispam_request(
meowlnir.base_url.as_str(),
&meowlnir.secret,
meowlnir_antispam::accept_make_join::v1::Request::new(
meowlnir.management_room.clone(),
user_id,
room_id,
),
)
.await
.inspect(|_| debug!("meowlnir allowed the make_join"))
.inspect_err(|e| debug!("meowlnir denied the make_join: {e:?}"))
.map(|_| ())
} else {
Ok(())
}
}
/// Returns whether all joins should be checked with Meowlnir.
/// Is always false if Meowlnir is not configured.
pub fn check_all_joins(&self) -> bool {
if let Some(Antispam { meowlnir: Some(cfg), .. }) = &self.services.config.antispam {
cfg.check_all_joins
} else {
false
}
}
}
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more