Compare commits

..
54 changed files with 583 additions and 1567 deletions

No files matched your search

+3 -4
View File
@@ -17,7 +17,7 @@ go to "files changed", and click on the "+" symbol in the line number gutter,
and attach comments to the lines that you think would benefit from some clarification. and attach comments to the lines that you think would benefit from some clarification.
--> -->
This pull request... <!-- do not forget to write here! --> This pull request...
<!-- Example: <!-- Example:
This pull request allows us to warp through time and space ten times faster than before by This pull request allows us to warp through time and space ten times faster than before by
@@ -26,8 +26,8 @@ efficient. This resolves the common issue where we have to wait more than 10 mil
engage, use, and disengage the warp drive when travelling between galaxies. engage, use, and disengage the warp drive when travelling between galaxies.
--> -->
<!-- Closes #... --> <!-- Closes: #... -->
<!-- Fixes #... --> <!-- Fixes: #... -->
<!-- Uncomment the above line(s) if your pull request fixes an issue or closes another pull request <!-- Uncomment the above line(s) if your pull request fixes an issue or closes another pull request
by superseding it. Replace `#...` with the issue/pr number, such as `#123`. --> by superseding it. Replace `#...` with the issue/pr number, such as `#123`. -->
@@ -73,7 +73,6 @@ Notes on these requirements:
main, it's difficult to get out cleanly, so put on your best dress, smile for the cameras! main, it's difficult to get out cleanly, so put on your best dress, smile for the cameras!
--> -->
<!-- Do not delete below this line -->
[c1]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md [c1]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md
[c2]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/docs/development/code_style.mdx [c2]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/docs/development/code_style.mdx
[c1pc]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#pre-commit-checks [c1pc]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#pre-commit-checks
+2 -2
View File
@@ -56,7 +56,7 @@ repos:
hooks: hooks:
- id: cargo-clippy - id: cargo-clippy
name: cargo clippy name: cargo clippy
entry: cargo clippy -- entry: cargo clippy -- -D warnings
language: system language: system
pass_filenames: false pass_filenames: false
types: [ rust ] types: [ rust ]
@@ -64,7 +64,7 @@ repos:
- pre-push - pre-push
- repo: https://code.forgejo.org/forgejo/runner - repo: https://code.forgejo.org/forgejo/runner
rev: v13.3.0 rev: v13.2.1
hooks: hooks:
- id: forgejo-runner-validate - id: forgejo-runner-validate
stages: stages:
Generated
+14 -14
View File
@@ -1026,7 +1026,7 @@ dependencies = [
"serde-saphyr", "serde-saphyr",
"serde_json", "serde_json",
"serde_regex", "serde_regex",
"sha2 0.11.3", "sha2 0.11.2",
"smallstr", "smallstr",
"smallvec", "smallvec",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -1152,7 +1152,7 @@ dependencies = [
"serde-saphyr", "serde-saphyr",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
"sha2 0.11.3", "sha2 0.11.2",
"termimad", "termimad",
"tokio", "tokio",
"tracing", "tracing",
@@ -1866,7 +1866,7 @@ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"ed25519", "ed25519",
"serde", "serde",
"sha2 0.11.3", "sha2 0.11.2",
"signature 3.0.0", "signature 3.0.0",
"subtle", "subtle",
"zeroize", "zeroize",
@@ -3245,9 +3245,9 @@ dependencies = [
[[package]] [[package]]
name = "lettre" name = "lettre"
version = "0.11.25" version = "0.11.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15000d8223b52e56d577590183331413c0ef732ebdd9c9b6aebce15824aba899" checksum = "f294f3d7cdb313e578acef7d7727d4e8d897e0fcd0d6d58c19959cec95073f19"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"base64 0.23.1", "base64 0.23.1",
@@ -4182,7 +4182,7 @@ dependencies = [
"elliptic-curve 0.14.3", "elliptic-curve 0.14.3",
"primefield", "primefield",
"primeorder 0.14.0", "primeorder 0.14.0",
"sha2 0.11.3", "sha2 0.11.2",
] ]
[[package]] [[package]]
@@ -4196,7 +4196,7 @@ dependencies = [
"fiat-crypto", "fiat-crypto",
"primefield", "primefield",
"primeorder 0.14.0", "primeorder 0.14.0",
"sha2 0.11.3", "sha2 0.11.2",
] ]
[[package]] [[package]]
@@ -5226,7 +5226,7 @@ dependencies = [
"ruma-common", "ruma-common",
"ruma-events", "ruma-events",
"serde_json", "serde_json",
"sha2 0.11.3", "sha2 0.11.2",
"thiserror 2.0.21", "thiserror 2.0.21",
] ]
@@ -5327,9 +5327,9 @@ dependencies = [
[[package]] [[package]]
name = "rustls" name = "rustls"
version = "0.23.47" version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ac0e747c10d93d873fd4c50b26ef47ad92d1bfb48f6922003bb514070f6e88c" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [ dependencies = [
"aws-lc-rs", "aws-lc-rs",
"log", "log",
@@ -5704,7 +5704,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9"
dependencies = [ dependencies = [
"annotate-snippets", "annotate-snippets",
"base64 0.22.1", "base64 0.23.1",
"encoding_rs_io", "encoding_rs_io",
"granit-parser", "granit-parser",
"nohash-hasher", "nohash-hasher",
@@ -5909,9 +5909,9 @@ dependencies = [
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.11.3" version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cpufeatures 0.3.1", "cpufeatures 0.3.1",
@@ -7120,7 +7120,7 @@ dependencies = [
"hkdf 0.13.0", "hkdf 0.13.0",
"http", "http",
"p256 0.13.2", "p256 0.13.2",
"sha2 0.11.3", "sha2 0.11.2",
] ]
[[package]] [[package]]
+1 -2
View File
@@ -385,7 +385,6 @@ features = [
"unstable-msc4203", "unstable-msc4203",
"unstable-msc4310", "unstable-msc4310",
"unstable-msc4380", "unstable-msc4380",
"unstable-msc4140",
"unstable-msc4143", "unstable-msc4143",
"unstable-msc4293", "unstable-msc4293",
"unstable-msc4363", "unstable-msc4363",
@@ -597,7 +596,7 @@ version = "0.3.18"
version = "0.3.0" version = "0.3.0"
[workspace.dependencies.resolvematrix] [workspace.dependencies.resolvematrix]
version = "1.6.0" version = "1.5.0"
features = ["unstable-msc4188"] features = ["unstable-msc4188"]
[workspace.dependencies.serde_urlencoded] [workspace.dependencies.serde_urlencoded]
+1
View File
@@ -0,0 +1 @@
Continuwuity now supports the OAuth 2.0 client credentials grant type, allowing secure automated access to the Matrix homeserver admin API, as well as future administrative functionality. Contributed by @ginger.
-1
View File
@@ -1 +0,0 @@
Add support for delayed events (MSC4140), including the stable endpoints and the `m.delayed_events` capability. The limits can be configured with `delayed_events_max_delay_ms` and `delayed_events_max_scheduled`. Contributed by @eve and @Henry-Hiles.
@@ -1 +0,0 @@
Fixed read receipts for all but one of a user's threads not being sent over federation. Contributed by @eleboucher.
-1
View File
@@ -1 +0,0 @@
The `element_hacks` build feature, which has done almost nothing for many versions, has been removed completely. Contributed by @ginger.
+42 -13
View File
@@ -813,19 +813,6 @@
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE # env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
#forget_forced_upon_leave = false #forget_forced_upon_leave = false
# The maximum delay in milliseconds for delayed events (MSC4140). Setting
# this or `delayed_events_max_scheduled` to 0 disables delayed events.
#
# env: CONTINUWUITY_DELAYED_EVENTS_MAX_DELAY_MS
#delayed_events_max_delay_ms = 604800000
# The maximum number of delayed events each user can have scheduled at
# once. Setting this or `delayed_events_max_delay_ms` to 0 disables
# delayed events.
#
# env: CONTINUWUITY_DELAYED_EVENTS_MAX_SCHEDULED
#delayed_events_max_scheduled = 100
# Set this to true to require authentication when looking up user profiles # Set this to true to require authentication when looking up user profiles
# through this server. # through this server.
# #
@@ -2688,6 +2675,48 @@
# env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE # env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE
#profile_key_import_mode = "on_registration" #profile_key_import_mode = "on_registration"
#[global.oauth.clients."$id"]
# Use this section to add static OAuth clients for bots and automation.
# Clients added here may use the client credentials OAuth grant to authorize
# themselves with Continuwuity.
#
# Make sure to replace `$id` in the header with your client ID of choice! You can
# add more copies of this section with different IDs to add multiple clients.
#
# Because the client credentials grant authorizes the client as itself, without
# an attached user, clients that use it will not be able to access most of the Matrix
# client-server API. Administrative functionality that does not require a user
# will still be available.
# The client's client secret.
#
# This must be supplied as the `client_secret` parameter when requesting
# an access token with the OAuth 2.0 token endpoint. Continuwuity does
# not check the `Authorization` header for requests to this endpoint.
#
#client_secret =
# A list of scopes that the client may request. Continuwuity allows static
# clients to request the following scopes:
#
# - "urn:matrix:client:cc.c10y.msc4484.server_administration" (MSC4484):
# This scope grants access to the Matrix server administration APIs, as
# well as Continuwuity's internal admin API (currently a work in
# progress).
# - "urn:matrix:client:api:*": This scope grants access to the Matrix
# client-server API. Most endpoints require an authenticated Matrix user
# and thus will not be usable by static clients.
#
# The `urn:matrix:client:device:<id>` scope may not be requested by static
# clients.
#
# Scopes listed here are not granted by default. The client must
# explicitly include them in the `scope` parameter of its access token
# request.
#
#scopes = []
[global.experiments] [global.experiments]
# Continuwuity's experimental features are frequently updated. # Continuwuity's experimental features are frequently updated.
# If you got this configuration via a package manager, chances are it's outdated. # If you got this configuration via a package manager, chances are it's outdated.
+1 -1
View File
@@ -102,7 +102,7 @@ look like this:
RUSTFLAGS="--cfg tokio_unstable" cargo +nightly build \ RUSTFLAGS="--cfg tokio_unstable" cargo +nightly build \
--release \ --release \
--no-default-features \ --no-default-features \
--features=systemd,gzip_compression,brotli_compression,zstd_compression,tokio_console --features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console
``` ```
You will also need to enable the `tokio_console` config option in Continuwuity You will also need to enable the `tokio_console` config option in Continuwuity
+1 -1
View File
@@ -146,7 +146,7 @@ cargo clippy \
--locked \ --locked \
--profile test \ --profile test \
--no-default-features \ --no-default-features \
--features=console,systemd,direct_tls,perf_measurements,brotli_compression \ --features=console,systemd,element_hacks,direct_tls,perf_measurements,brotli_compression \
--color=always \ --color=always \
-- \ -- \
-D warnings -D warnings
+95 -132
View File
@@ -16,38 +16,35 @@
} }
}, },
"node_modules/@emnapi/core": { "node_modules/@emnapi/core": {
"version": "1.11.3", "version": "2.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.3.tgz",
"integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", "integrity": "sha512-KA+gOBtbifRATmUa/Gpf5C2B2EJ0r4brHUT3XSgACeHREcuiObXH56xd+B3fFsEFbUT04VBEe6MuZiCtMp0tQg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true,
"dependencies": { "dependencies": {
"@emnapi/wasi-threads": "1.2.3", "@emnapi/wasi-threads": "2.2.0",
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"node_modules/@emnapi/runtime": { "node_modules/@emnapi/runtime": {
"version": "1.11.3", "version": "2.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.3.tgz",
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", "integrity": "sha512-ayb/PyyLzpwRyFVxeC0uoEHu59QlB1iWGcGsOpXQcaB/Dc+uGfBmNmpCHp3HmTT0t8lSsMmg3j7+tdJW/TlHjQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"node_modules/@emnapi/wasi-threads": { "node_modules/@emnapi/wasi-threads": {
"version": "1.2.3", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
"integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
@@ -131,13 +128,13 @@
} }
}, },
"node_modules/@rsbuild/core": { "node_modules/@rsbuild/core": {
"version": "2.3.7", "version": "2.3.6",
"resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.7.tgz", "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.6.tgz",
"integrity": "sha512-IvJZFEeVGcjeSiSHfMlRxJbyL5+xLGcvkNmD34wmIXo85n0va6b8cnqShmprdUKjvXyzE4dPPB9trRunaUY+mA==", "integrity": "sha512-IVuWh/0DO6XT8075eCAzxWIcVGA7c4xKggf/VEePq3yXqEiU302n6OVGD7uCxQwPaB4R9ViX4cAqalcQV/sxKQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rspack/core": "~2.3.5", "@rspack/core": "~2.3.4",
"@swc/helpers": "^0.5.24" "@swc/helpers": "^0.5.24"
}, },
"bin": { "bin": {
@@ -175,32 +172,32 @@
} }
}, },
"node_modules/@rspack/binding": { "node_modules/@rspack/binding": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.4.tgz",
"integrity": "sha512-W3x7zw5d/mIH9WhWt4pO9RKYURoqgdUxeLSV5IhDCajnhXdRr7R59u5S2j5ZXzSk3eMGUC0PenfKIIdW7t0ufQ==", "integrity": "sha512-wSOT16LVITL/IKeIiLXgN5Q5jZIDqnQ7Gmk+wzKOSZ6OHYNfEBXAKhSJuYtCBq8ovJuGl8cJjdqatAlHE5XKIA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"optionalDependencies": { "optionalDependencies": {
"@rspack/binding-darwin-arm64": "2.3.5", "@rspack/binding-darwin-arm64": "2.3.4",
"@rspack/binding-darwin-x64": "2.3.5", "@rspack/binding-darwin-x64": "2.3.4",
"@rspack/binding-linux-arm64-gnu": "2.3.5", "@rspack/binding-linux-arm64-gnu": "2.3.4",
"@rspack/binding-linux-arm64-musl": "2.3.5", "@rspack/binding-linux-arm64-musl": "2.3.4",
"@rspack/binding-linux-ppc64-gnu": "2.3.5", "@rspack/binding-linux-ppc64-gnu": "2.3.4",
"@rspack/binding-linux-riscv64-gnu": "2.3.5", "@rspack/binding-linux-riscv64-gnu": "2.3.4",
"@rspack/binding-linux-riscv64-musl": "2.3.5", "@rspack/binding-linux-riscv64-musl": "2.3.4",
"@rspack/binding-linux-s390x-gnu": "2.3.5", "@rspack/binding-linux-s390x-gnu": "2.3.4",
"@rspack/binding-linux-x64-gnu": "2.3.5", "@rspack/binding-linux-x64-gnu": "2.3.4",
"@rspack/binding-linux-x64-musl": "2.3.5", "@rspack/binding-linux-x64-musl": "2.3.4",
"@rspack/binding-wasm32-wasi": "2.3.5", "@rspack/binding-wasm32-wasi": "2.3.4",
"@rspack/binding-win32-arm64-msvc": "2.3.5", "@rspack/binding-win32-arm64-msvc": "2.3.4",
"@rspack/binding-win32-ia32-msvc": "2.3.5", "@rspack/binding-win32-ia32-msvc": "2.3.4",
"@rspack/binding-win32-x64-msvc": "2.3.5" "@rspack/binding-win32-x64-msvc": "2.3.4"
} }
}, },
"node_modules/@rspack/binding-darwin-arm64": { "node_modules/@rspack/binding-darwin-arm64": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.4.tgz",
"integrity": "sha512-A5XnBdSoJvcYV4t2Y+XJiCF0UZ42nOKE2D0ZlegfErGhzlQG1t3hDOzskSB2fPD3z+w5QeREoclqQ0zFOZyBpw==", "integrity": "sha512-eBD71fbmoJKnxcHD03bukbAIOP5r7nD0Ehs+mUrUQlZ6N53EhuJsTeJ1oYdg5L4GoSeQ+KecCqME81Nm0COLrA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -212,9 +209,9 @@
] ]
}, },
"node_modules/@rspack/binding-darwin-x64": { "node_modules/@rspack/binding-darwin-x64": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.4.tgz",
"integrity": "sha512-iZrweqTIj2cM4f0ADRj6FXn9a0FOpD1Mx/++zrsbrQzmnY0c8wmfpvZ5xA5Zfcq9O6nuUBS6GnhkmoFTgviHwQ==", "integrity": "sha512-CqdfzTLPVFQCniOy/GDVWbg+rqg31qfdzbFf8NYCzdDkCQg+p15hU2HsckD/1sLsaNB8Y55EjGz4ZyGDny0cHg==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -226,9 +223,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-arm64-gnu": { "node_modules/@rspack/binding-linux-arm64-gnu": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.4.tgz",
"integrity": "sha512-aWE9V0ZhmclKsJNuO37cxUMLtXMjhLtFzrWDWC82mksUX6qM2rzOpPuye9i/c9NGqyrIH7EFQre8bskJvNHGuQ==", "integrity": "sha512-T/Y1FYiSegcNc+oHuDOLRGIcc+eSdBnfbS70d51EWQj4+0TG/tlfuqFKeAIL3mnKUV5lDLaTz3vsoD0Sws5Fxw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -243,9 +240,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-arm64-musl": { "node_modules/@rspack/binding-linux-arm64-musl": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.4.tgz",
"integrity": "sha512-I8ENTXdv7Th/OHEYhL7uu3B7DA9r1oTWSifkGHJtuT1XJ0KDsxoA6ORpYz1R2qIs87l+8+5QUnRH7iWyZrnroA==", "integrity": "sha512-WZHCzZ532UfXFXNU8XyM8jb+I6wddegbs/7IXsyw7xiPwwZX1D/M6iKFVpBYdvKcupUM8bS8Uw2REirR/cERVw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -260,9 +257,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-ppc64-gnu": { "node_modules/@rspack/binding-linux-ppc64-gnu": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.4.tgz",
"integrity": "sha512-ps5do0cKf4aTBWd+LHqvwm8Gdn7J/gvzmx9pWJhAIThvzii45wJREFjGOzJNxdQl+pzKq8JFuzbShNskCN9k2w==", "integrity": "sha512-WeizqeI6HIh7Ax9w2tlmpTtipJWxXcdgt3QqI3N9LOixymlMD5yMBMZNPqwZ6cHXT9gOQ69SvPcVgMwxsdmceQ==",
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
@@ -277,9 +274,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-riscv64-gnu": { "node_modules/@rspack/binding-linux-riscv64-gnu": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.4.tgz",
"integrity": "sha512-3XXIEMS4SSr1/9wIAGgPT1oj1SzhnlejAG5xeVbGJR5y6iFp/oFKYzUPqyuuzZCkWph2/hJ+Q16sa+BJn1YIkg==", "integrity": "sha512-h+001Vbq8LyGwPMNkeRWidPOVKwlAbwNPskY3CjNlSw3euHkVchfhM3uo6+1h0GyTtb3rzsWqsfm1kar7m/tiQ==",
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
@@ -294,9 +291,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-riscv64-musl": { "node_modules/@rspack/binding-linux-riscv64-musl": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.4.tgz",
"integrity": "sha512-z2DbQNcLbUEY9OvUa3gahsHey+dW4acLc9d3QlyJm7TJE//rL9C/XBk4kETvCgtdhqrwBSfWrZfislBPKODjvA==", "integrity": "sha512-S1rlaCnNVG5s4WZ9odLsqN3ySh5TEdNTLXWapEK8x3iQl56aLtdvqXTfbJWHWnYLJuS7M1WqnQGdJNdjy2NDsA==",
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
@@ -311,9 +308,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-s390x-gnu": { "node_modules/@rspack/binding-linux-s390x-gnu": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.4.tgz",
"integrity": "sha512-n2UudDpzt9G2AOmycVS7uWRMcNMd2k4ubU4b4SX3FfU/uT6mfSNzuwhBhCi0RSZQAGBU0ombJ+sqw8vKXjGGbw==", "integrity": "sha512-0SkgGrgulVMam3xel5dMNKQ+U7BEpCczhF1avGT1DzDVIbMfIOsbb32gApQNSz0E7RfAQ/Pa5eWiA9oyRq7ZMQ==",
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
@@ -328,9 +325,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-x64-gnu": { "node_modules/@rspack/binding-linux-x64-gnu": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.4.tgz",
"integrity": "sha512-1sxASGJXg9luaYsFSmAQxSFbUbnMnPA5Mr94yIlLsq4q94sHUIn5YjG1XGcT+cPhUYF9fHkCsKRmQlzrN9fR8A==", "integrity": "sha512-q7E6x3rJJ/9fJyLuRe5+KyEPi23BF/xkAU4xCM5VwLkTf+rVyOkDZfu0qOkxmILjrxllQPV+b/ojBL/ZaIeQPw==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -345,9 +342,9 @@
] ]
}, },
"node_modules/@rspack/binding-linux-x64-musl": { "node_modules/@rspack/binding-linux-x64-musl": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.4.tgz",
"integrity": "sha512-/S4pe1wAo8CBTs0X8DNKu1ZOJ2vQcnThLBKS2CxOPiuQXI7UfAsJCEABBoa8yCrZANWh63fJ90UwLb/s245Gsw==", "integrity": "sha512-rey4Tyasui/WeMn6KfhH5xyZGOMt+Ny+GDK7nGh9TSz/cb3/bisxqGzpbu6GJK8leDmTUDD5ZdpODexytA5rzQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -362,9 +359,9 @@
] ]
}, },
"node_modules/@rspack/binding-wasm32-wasi": { "node_modules/@rspack/binding-wasm32-wasi": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.4.tgz",
"integrity": "sha512-GQnswrv6AyBdDCcTy8dTVhD0JqnvmgewzPz6qnOYWGKxpCY99Bv6FL4jvxI1yh64Uk3ykEfbwhrPnaA8Px4KJA==", "integrity": "sha512-sDt2MSXZrIaMBa6UaEqmXEqebwpTOPAXLdo9CYJ2Fa9FJWP4TCYbn30mbvV38ZC2n5YX411DRbjck+s97CceIg==",
"cpu": [ "cpu": [
"wasm32" "wasm32"
], ],
@@ -372,49 +369,15 @@
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"dependencies": { "dependencies": {
"@emnapi/core": "2.0.0-beta.4", "@emnapi/core": "2.0.0-beta.3",
"@emnapi/runtime": "2.0.0-beta.4", "@emnapi/runtime": "2.0.0-beta.3",
"@napi-rs/wasm-runtime": "1.2.7" "@napi-rs/wasm-runtime": "1.2.7"
} }
}, },
"node_modules/@rspack/binding-wasm32-wasi/node_modules/@emnapi/core": {
"version": "2.0.0-beta.4",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.4.tgz",
"integrity": "sha512-AhU/vMMXtGgLCrWsL3PjZGSpCWXlGETabnyyB2pBUd6h7AMy2toffJO2T7yXOYXtw8FyD6dYK/5b3u5eRK3yhw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "2.2.0",
"tslib": "^2.4.0"
}
},
"node_modules/@rspack/binding-wasm32-wasi/node_modules/@emnapi/runtime": {
"version": "2.0.0-beta.4",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.4.tgz",
"integrity": "sha512-UKxc3beuftD67T1mPCVf0mnwRKOBsq9XrhLCDGGQKsbG9jx6osvGyjIbJm9DsucyUtFSMTV2ZxsjiuTMjEqWkA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@rspack/binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@rspack/binding-win32-arm64-msvc": { "node_modules/@rspack/binding-win32-arm64-msvc": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.4.tgz",
"integrity": "sha512-XVKu3Zs5KGr+P5Seh6NtSNU0UQ1GSgSDFANQRZlT1uFZ1NpBCX+9NB8FVZB0hBBoBKI1kU4b0Cr6Df1Xx0K4nQ==", "integrity": "sha512-24YC1YSodLAJ8VsMQJmJSHCNvHTqK9JP5hj50T50WE8lCHNsNl/rIYXO9V0VlCYT/HshE6EHHzAeKdahiEOtcw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -426,9 +389,9 @@
] ]
}, },
"node_modules/@rspack/binding-win32-ia32-msvc": { "node_modules/@rspack/binding-win32-ia32-msvc": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.4.tgz",
"integrity": "sha512-ejCqSuctPcOev2dyi0ayZyfIUY3fJdYHYvrTfSVrrGC19TspuRATXu+RLyu3xvB6TrQF3+JEF4KeG4/ZeWuXOg==", "integrity": "sha512-xmUNu6kgV9lLEkRP1Zb+t6i1Z1ZMEWXmLlMalPx8tHqndz2RflNMBBx6kjB2nAPQBIZgWufwm7dVGS0HKomCmw==",
"cpu": [ "cpu": [
"ia32" "ia32"
], ],
@@ -440,9 +403,9 @@
] ]
}, },
"node_modules/@rspack/binding-win32-x64-msvc": { "node_modules/@rspack/binding-win32-x64-msvc": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.4.tgz",
"integrity": "sha512-IPvkjM3xAwL1z2N4Jp/GBcZUme703uDy5vrP1IMtXJEl/EOLLfwl7cRb4sSzdeOYGDDHs5dPYDcpgP5eRSRauA==", "integrity": "sha512-WY+AkJqpbLtLEZiG1fE7CVJZ54y0qHeCiVmLxGBsh4OOGIDCs6v2Ub5COcPrYVzGJFGyeHUS29dV7JAs93qIHw==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -454,13 +417,13 @@
] ]
}, },
"node_modules/@rspack/core": { "node_modules/@rspack/core": {
"version": "2.3.5", "version": "2.3.4",
"resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.4.tgz",
"integrity": "sha512-4TG6zGTemEU/FU7bymDgeFOO7CRdd7ucn0CmXo+3cG6EhYmY5+hpAFYBRgxDbDuL4Bwo/s5GsgUvZuI7rLqVbQ==", "integrity": "sha512-T8HGkIjPVDlGlIN8st/ICe8Gfixq8te75g/8crSdNSf8F+6884sBcKNky0CRdfPxao1C5SXV+Vjv1XJTjyu83w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rspack/binding": "2.3.5" "@rspack/binding": "2.3.4"
}, },
"engines": { "engines": {
"node": "^20.19.0 || >=22.12.0" "node": "^20.19.0 || >=22.12.0"
@@ -495,22 +458,22 @@
} }
}, },
"node_modules/@rspress/core": { "node_modules/@rspress/core": {
"version": "2.1.6", "version": "2.1.5",
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.6.tgz", "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.5.tgz",
"integrity": "sha512-a+CBJcslana9Zmr6j2o3RP6O19y+rcyfa8jeDToC1b29e/RGiD+xpAQJF2eBvnjNUHouXARTaFa7pE1myyV0Rg==", "integrity": "sha512-kzTqrfJ4UiW+RLLHLunoW/rET5Vjb6Qz4YjhEhiWEp4HYM+KxLVhfyYB5aL8af9+mdnwiTaqlu1s+BZGrMD2zw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@mdx-js/mdx": "^3.1.1", "@mdx-js/mdx": "^3.1.1",
"@mdx-js/react": "^3.1.1", "@mdx-js/react": "^3.1.1",
"@rsbuild/core": "^2.3.7", "@rsbuild/core": "^2.3.3",
"@rsbuild/plugin-react": "~2.1.1", "@rsbuild/plugin-react": "~2.1.1",
"@rspress/shared": "2.1.6", "@rspress/shared": "2.1.5",
"@shikijs/rehype": "^4.2.0", "@shikijs/rehype": "^4.2.0",
"@shikijs/transformers": "^4.2.0", "@shikijs/transformers": "^4.2.0",
"@types/mdast": "^4.0.4", "@types/mdast": "^4.0.4",
"@types/react": "^19.3.3", "@types/react": "^19.3.0",
"@unhead/react": "^2.1.19", "@unhead/react": "^2.1.18",
"body-scroll-lock": "4.0.0-beta.0", "body-scroll-lock": "4.0.0-beta.0",
"clsx": "2.1.1", "clsx": "2.1.1",
"copy-to-clipboard": "^3.3.3", "copy-to-clipboard": "^3.3.3",
@@ -527,7 +490,7 @@
"react-dom": "^19.3.1", "react-dom": "^19.3.1",
"react-lazy-with-preload": "^2.2.1", "react-lazy-with-preload": "^2.2.1",
"react-render-to-markdown": "19.2.0", "react-render-to-markdown": "19.2.0",
"react-router-dom": "^7.18.7", "react-router-dom": "^7.18.6",
"rehype-external-links": "^3.0.0", "rehype-external-links": "^3.0.0",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"remark-cjk-friendly": "^2.3.4", "remark-cjk-friendly": "^2.3.4",
@@ -551,9 +514,9 @@
} }
}, },
"node_modules/@rspress/plugin-client-redirects": { "node_modules/@rspress/plugin-client-redirects": {
"version": "2.1.6", "version": "2.1.5",
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.6.tgz", "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.5.tgz",
"integrity": "sha512-lnSIA3oD44PZa0o0r4gvTBBGWeImD3T7D28FRJlzCdrWQX3kOHpyhxd9fCcK9mE32DYItlu/ipsmpSozmDN9ZA==", "integrity": "sha512-vqAi7ynOgVsuwJi7cXwWEF5UgoNhXqGOyBfQubeZHZKWRtdNHRU42P9rG9DZLTss2dZUiDKlVrM2/vNY40t5hw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -564,15 +527,15 @@
} }
}, },
"node_modules/@rspress/shared": { "node_modules/@rspress/shared": {
"version": "2.1.6", "version": "2.1.5",
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.6.tgz", "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.5.tgz",
"integrity": "sha512-ecHmNItlMsMU5FEf0CeBKZa4XNCE5fpwCED+1/lmcwIhozyBvd4j4Ook/8IyTT3UqgruJDZ2DwQqfyvCW7zmLg==", "integrity": "sha512-XXxegxRZ7VPADS2veN9FTNmmLlA65ieydKH0tOhOZbMJC4OJpKbr/d/JS2jxxAO4u+ZmZxbDyEEir83NQHLKIw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@rsbuild/core": "^2.3.7", "@rsbuild/core": "^2.3.3",
"@shikijs/rehype": "^4.2.0", "@shikijs/rehype": "^4.2.0",
"@types/react": "^19.3.3", "@types/react": "^19.3.0",
"mdast-util-mdx-jsx": "^3.2.2", "mdast-util-mdx-jsx": "^3.2.2",
"unified": "^11.0.5" "unified": "^11.0.5"
} }
-46
View File
@@ -1,46 +0,0 @@
#-------------------------------------------------------------------------------#
# Qodana analysis is configured by qodana.yaml file #
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
#-------------------------------------------------------------------------------#
#################################################################################
# WARNING: Do not store sensitive information in this file, #
# as its contents will be included in the Qodana report. #
#################################################################################
version: "1.0"
#Specify inspection profile for code analysis
profile:
name: qodana.starter
#Enable inspections
#include:
# - name: <SomeEnabledInspectionId>
#Disable inspections
#exclude:
# - name: <SomeDisabledInspectionId>
# paths:
# - <path/where/not/run/inspection>
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
#bootstrap: sh ./prepare-qodana.sh
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
#plugins:
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
# Quality gate. Will fail the CI/CD pipeline if any condition is not met
# severityThresholds - configures maximum thresholds for different problem severities
# testCoverageThresholds - configures minimum code coverage on a whole project and newly added code
# Code Coverage is available in Ultimate and Ultimate Plus plans
#failureConditions:
# severityThresholds:
# any: 15
# critical: 5
# testCoverageThresholds:
# fresh: 70
# total: 50
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
linter: jetbrains/qodana-<linter>:2026.2
+3
View File
@@ -21,6 +21,9 @@ brotli_compression = [
"conduwuit-service/brotli_compression", "conduwuit-service/brotli_compression",
"reqwest/brotli", "reqwest/brotli",
] ]
element_hacks = [
"conduwuit-service/element_hacks",
]
gzip_compression = [ gzip_compression = [
"conduwuit-core/gzip_compression", "conduwuit-core/gzip_compression",
"conduwuit-service/gzip_compression", "conduwuit-service/gzip_compression",
+4 -13
View File
@@ -1,20 +1,16 @@
use std::{ use std::collections::{BTreeMap, BTreeSet};
collections::{BTreeMap, BTreeSet},
time::Duration,
};
use axum::extract::State; use axum::extract::State;
use conduwuit::{Result, Server, config::experiments::ToggledExperiment}; use conduwuit::{Result, Server, config::experiments::ToggledExperiment};
use ruma::{ use ruma::{
RoomVersionId, UInt, RoomVersionId,
api::{ api::{
OAuthClientScope, OAuthClientScope,
client::discovery::get_capabilities::{ client::discovery::get_capabilities::{
self, self,
v3::{ v3::{
AdminCapability, Capabilities, DelayedEventsCapability, GetLoginTokenCapability, AdminCapability, Capabilities, GetLoginTokenCapability, ProfileFieldsCapability,
ProfileFieldsCapability, RoomVersionStability, RoomVersionsCapability, RoomVersionStability, RoomVersionsCapability, ThirdPartyIdChangesCapability,
ThirdPartyIdChangesCapability,
}, },
}, },
}, },
@@ -68,11 +64,6 @@ pub(crate) async fn get_capabilities_route(
assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }), assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }),
); );
capabilities.delayed_events = Some(assign!(DelayedEventsCapability::new(), {
max_delay_ms: Some(Duration::from_millis(services.config.delayed_events_max_delay_ms)),
max_scheduled: Some(UInt::new_saturating(services.config.delayed_events_max_scheduled)),
}));
capabilities.set( capabilities.set(
"org.matrix.msc4174.webpush", "org.matrix.msc4174.webpush",
json!({ json!({
-144
View File
@@ -1,144 +0,0 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use ruma::{
api::client::delayed_events::{
get_delayed_event, schedule_delayed_event,
update_delayed_event::{self, UpdateAction},
},
events::TimelineEventType,
signatures::MAX_PDU_BYTES,
};
use serde_json::{Map as JsonMap, Value as JsonValue};
use service::rooms::delayed_events::NewDelayedEvent;
use crate::{Ruma, client_ip::ClientIp};
/// The largest content we accept for a delayed event, leaving 4 KiB of the PDU
/// size limit for the rest of the event (IDs, hashes, signatures, etc).
const MAX_CONTENT_BYTES: usize = MAX_PDU_BYTES - 4096;
/// # `PUT /_matrix/client/v3/rooms/{roomId}/delayed_event/{eventType}/{txnId}`
///
/// Schedules an event to be sent into a room after a delay.
pub(crate) async fn schedule_delayed_event_route(
State(services): State<crate::State>,
ClientIp(client_ip): ClientIp,
body: Ruma<schedule_delayed_event::v3::Request>,
) -> Result<schedule_delayed_event::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
let sender_device = body.identity.sender_device();
if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
services
.users
.update_device_last_seen(sender_user, sender_device, client_ip)
.await;
let Some(max_delay) = services.rooms.delayed_events.max_delay() else {
return Err!(Request(Forbidden("Delayed events are disabled on this server.")));
};
if body.delay_ms.is_zero() {
return Err!(Request(BadJson("delay_ms must be greater than 0.")));
}
if body.delay_ms > max_delay {
return Err!(Request(DelayTooLarge(
"The requested delay exceeds the maximum of {}ms.",
max_delay.as_millis()
)));
}
if serde_json::from_str::<JsonMap<String, JsonValue>>(body.content.json().get()).is_err() {
return Err!(Request(BadJson("The event content must be a JSON object.")));
}
// The full PDU is size checked again when it is sent.
if body.content.json().get().len() > MAX_CONTENT_BYTES {
return Err!(Request(TooLarge(
"The event content exceeds the maximum of {MAX_CONTENT_BYTES} bytes."
)));
}
// Auth is checked again when the event is sent
let is_own_membership = body.event_type == TimelineEventType::RoomMember
&& body.state_key.as_deref() == Some(sender_user.as_str());
if !is_own_membership
&& !services
.rooms
.state_cache
.is_joined(sender_user, &body.room_id)
.await
{
return Err!(Request(Forbidden("You are not joined to this room.")));
}
let timestamp =
if body.identity.is_appservice() || services.admin.user_is_admin(sender_user).await {
body.timestamp
} else {
None
};
let body = body.body;
let delay_id = services
.rooms
.delayed_events
.schedule(sender_user, sender_device, &body.txn_id, NewDelayedEvent {
room_id: body.room_id,
event_type: body.event_type,
state_key: body.state_key,
content: body.content,
delay: body.delay_ms,
timestamp,
sticky_duration_ms: body.sticky_duration_ms,
})
.await?;
Ok(schedule_delayed_event::v3::Response::new(delay_id))
}
/// # `POST /_matrix/client/v1/delayed_events/{delayId}/{action}`
///
/// Restarts, sends or cancels a scheduled delayed event.
pub(crate) async fn update_delayed_event_route(
State(services): State<crate::State>,
body: Ruma<update_delayed_event::v1::Request>,
) -> Result<update_delayed_event::v1::Response> {
let sender_user = body.identity.expect_sender_user()?;
let update_delayed_event::v1::Request { delay_id, action, .. } = body.body;
// Cancelling is still allowed, since it only stops activity.
if action != UpdateAction::Cancel && services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
services
.rooms
.delayed_events
.update(sender_user, &delay_id, action)
.await?;
Ok(update_delayed_event::v1::Response::new())
}
/// # `GET /_matrix/client/v1/delayed_events/{delayId}`
///
/// Returns a scheduled or finalized delayed event.
pub(crate) async fn get_delayed_event_route(
State(services): State<crate::State>,
body: Ruma<get_delayed_event::v1::Request>,
) -> Result<get_delayed_event::v1::Response> {
let sender_user = body.identity.expect_sender_user()?;
let delayed_event = services
.rooms
.delayed_events
.get(sender_user, &body.delay_id)
.await?;
Ok(get_delayed_event::v1::Response::new(delayed_event))
}
-2
View File
@@ -7,7 +7,6 @@ pub(super) mod backup;
pub(super) mod capabilities; pub(super) mod capabilities;
pub(super) mod context; pub(super) mod context;
pub(super) mod dehydrated_device; pub(super) mod dehydrated_device;
pub(super) mod delayed_events;
pub(super) mod device; pub(super) mod device;
pub(super) mod directory; pub(super) mod directory;
pub(super) mod filter; pub(super) mod filter;
@@ -53,7 +52,6 @@ pub(super) use backup::*;
pub(super) use capabilities::*; pub(super) use capabilities::*;
pub(super) use context::*; pub(super) use context::*;
pub(super) use dehydrated_device::*; pub(super) use dehydrated_device::*;
pub(super) use delayed_events::*;
pub(super) use device::*; pub(super) use device::*;
pub(super) use directory::*; pub(super) use directory::*;
pub(super) use filter::*; pub(super) use filter::*;
+1 -1
View File
@@ -61,7 +61,7 @@ pub(crate) async fn authorization_server_metadata(services: &Services) -> Value
"authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(), "authorization_endpoint": endpoint_base.join(AUTH_CODE_PATH).unwrap(),
"code_challenge_methods_supported": ["S256"], "code_challenge_methods_supported": ["S256"],
"device_authorization_endpoint": endpoint_base.join(DEVICE_AUTHORIZATION_PATH).unwrap(), "device_authorization_endpoint": endpoint_base.join(DEVICE_AUTHORIZATION_PATH).unwrap(),
"grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"], "grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "client_credentials"],
"issuer": services.config.get_client_domain(), "issuer": services.config.get_client_domain(),
"jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(), "jwks_uri": endpoint_base.join(JWKS_URI_PATH).unwrap(),
"prompt_values_supported": prompt_values_supported, "prompt_values_supported": prompt_values_supported,
+9 -23
View File
@@ -9,7 +9,7 @@ use service::Services;
use crate::{Ruma, router::ClientIdentity}; use crate::{Ruma, router::ClientIdentity};
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous` /// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous`
pub(crate) async fn discover_rendezvous_route( pub(crate) async fn discover_rendezvous_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<discover_rendezvous::msc4388::Request>, body: Ruma<discover_rendezvous::msc4388::Request>,
@@ -20,7 +20,7 @@ pub(crate) async fn discover_rendezvous_route(
))) )))
} }
/// `POST /_matrix/client/unstable/io.element.msc4388/rendezvous` /// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/`
pub(crate) async fn create_rendezvous_session_route( pub(crate) async fn create_rendezvous_session_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<create_rendezvous_session::msc4388::Request>, body: Ruma<create_rendezvous_session::msc4388::Request>,
@@ -32,7 +32,7 @@ pub(crate) async fn create_rendezvous_session_route(
services.rendezvous.create_session(body.data.clone()) services.rendezvous.create_session(body.data.clone())
} }
/// `PUT /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}/{txn_id}` /// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}`
pub(crate) async fn update_rendezvous_session_route( pub(crate) async fn update_rendezvous_session_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<update_rendezvous_session::msc4388::Request>, body: Ruma<update_rendezvous_session::msc4388::Request>,
@@ -45,30 +45,16 @@ pub(crate) async fn update_rendezvous_session_route(
) )
} }
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}` /// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
pub(crate) async fn get_rendezvous_session_route( pub(crate) async fn get_rendezvous_session_route(
State(services): State<crate::State>, State(services): State<crate::State>,
headers: HeaderMap, headers: HeaderMap,
body: Ruma<get_rendezvous_session::msc4388::Request>, body: Ruma<get_rendezvous_session::msc4388::Request>,
) -> Result<get_rendezvous_session::msc4388::Response> { ) -> Result<get_rendezvous_session::msc4388::Response> {
let is_navigation_mode = headers if let Some(mode) = headers.get("Sec-Fetch-Mode")
.get_all("Sec-Fetch-Mode") && let Ok(mode) = mode.to_str()
.iter() && mode == "navigate"
.filter_map(|v| v.to_str().ok()) {
.any(|mode| {
mode.eq_ignore_ascii_case("navigate") || mode.eq_ignore_ascii_case("nested-navigate")
});
let is_navigation_dest = headers
.get_all("Sec-Fetch-Dest")
.iter()
.filter_map(|v| v.to_str().ok())
.any(|dest| {
matches!(
dest.to_ascii_lowercase().as_str(),
"document" | "iframe" | "frame" | "object" | "embed" | "fencedframe"
)
});
if is_navigation_mode || is_navigation_dest {
return Err!(Request(Forbidden( return Err!(Request(Forbidden(
"Rendezvous sessions do not accept browser navigation requests." "Rendezvous sessions do not accept browser navigation requests."
))); )));
@@ -77,7 +63,7 @@ pub(crate) async fn get_rendezvous_session_route(
services.rendezvous.get_session(&body.id) services.rendezvous.get_session(&body.id)
} }
/// `DELETE /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}` /// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
pub(crate) async fn delete_rendezvous_session_route( pub(crate) async fn delete_rendezvous_session_route(
State(services): State<crate::State>, State(services): State<crate::State>,
body: Ruma<delete_rendezvous_session::msc4388::Request>, body: Ruma<delete_rendezvous_session::msc4388::Request>,
+6 -7
View File
@@ -559,16 +559,15 @@ pub(crate) async fn create_room_route(
match services match services
.rooms .rooms
.timeline .timeline
.send_timeline_event( .send_state_event_for_key(
PartialPdu {
event_type: event_type.to_string().into(),
content: content.into_json(),
state_key: Some(state_key.into()),
..Default::default()
},
sender_user, sender_user,
&room_id, &room_id,
&state_lock, &state_lock,
&event_type,
&content,
&state_key,
None,
None,
) )
.boxed() .boxed()
.await .await
+14 -2
View File
@@ -40,8 +40,20 @@ pub(crate) async fn send_message_event_route(
.update_device_last_seen(sender_user, sender_device, client_ip) .update_device_last_seen(sender_user, sender_device, client_ip)
.await; .await;
// Forbid m.room.encrypted if encryption is disabled
if MessageLikeEventType::RoomEncrypted == body.event_type && !services.config.allow_encryption
{
return Err!(Request(Forbidden("Encryption has been disabled")));
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await; let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
if body.event_type == MessageLikeEventType::CallInvite
&& services.rooms.directory.is_public_room(&body.room_id).await
{
return Err!(Request(Forbidden("Room call invites are not allowed in public rooms")));
}
// Check if this is a new transaction id // Check if this is a new transaction id
if let Ok(response) = services if let Ok(response) = services
.transactions .transactions
@@ -79,7 +91,7 @@ pub(crate) async fn send_message_event_route(
let event_id = services let event_id = services
.rooms .rooms
.timeline .timeline
.send_timeline_event( .build_and_append_pdu(
PartialPdu { PartialPdu {
event_type: body.event_type.clone().into(), event_type: body.event_type.clone().into(),
content, content,
@@ -96,7 +108,7 @@ pub(crate) async fn send_message_event_route(
..Default::default() ..Default::default()
}, },
sender_user, sender_user,
&body.room_id, Some(&body.room_id),
&state_lock, &state_lock,
) )
.await?; .await?;
+11 -20
View File
@@ -1,13 +1,7 @@
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
use axum::extract::State; use axum::extract::State;
use conduwuit::{ use conduwuit::{Err, Result, err, matrix::Event};
Err, Result, err,
matrix::{
Event,
pdu::{PartialPdu, sticky},
},
};
use futures::{FutureExt, TryStreamExt}; use futures::{FutureExt, TryStreamExt};
use ruma::{ use ruma::{
RoomId, RoomId,
@@ -48,22 +42,19 @@ pub(crate) async fn send_state_event_for_key_route(
let event_id = services let event_id = services
.rooms .rooms
.timeline .timeline
.send_timeline_event( .send_state_event_for_key(
PartialPdu {
event_type: body.event_type.to_string().into(),
content: body.body.body.clone().into_json(),
state_key: Some(body.state_key.as_str().into()),
sticky: body.sticky_duration_ms.map(sticky::object),
timestamp: if body.identity.is_appservice() {
body.timestamp
} else {
None
},
..Default::default()
},
sender_user, sender_user,
&body.room_id, &body.room_id,
&state_lock, &state_lock,
&body.event_type,
&body.body.body,
&body.state_key,
body.sticky_duration_ms,
if body.identity.is_appservice() {
body.timestamp
} else {
None
},
) )
.boxed() .boxed()
.await?; .await?;
+5 -20
View File
@@ -163,9 +163,6 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::update_device_route) .ruma_route(&client::update_device_route)
.ruma_route(&client::delete_device_route) .ruma_route(&client::delete_device_route)
.ruma_route(&client::delete_devices_route) .ruma_route(&client::delete_devices_route)
.ruma_route(&client::schedule_delayed_event_route)
.ruma_route(&client::update_delayed_event_route)
.ruma_route(&client::get_delayed_event_route)
.ruma_route(&client::get_tags_route) .ruma_route(&client::get_tags_route)
.ruma_route(&client::update_tag_route) .ruma_route(&client::update_tag_route)
.ruma_route(&client::delete_tag_route) .ruma_route(&client::delete_tag_route)
@@ -194,23 +191,11 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::get_rtc_transports) .ruma_route(&client::get_rtc_transports)
.ruma_route(&client::get_rtc_transports_unstable) .ruma_route(&client::get_rtc_transports_unstable)
.ruma_route(&client::room_initial_sync_route) .ruma_route(&client::room_initial_sync_route)
.merge( .ruma_route(&client::discover_rendezvous_route)
Router::new() .ruma_route(&client::create_rendezvous_session_route)
.ruma_route(&client::discover_rendezvous_route) .ruma_route(&client::update_rendezvous_session_route)
.ruma_route(&client::create_rendezvous_session_route) .ruma_route(&client::get_rendezvous_session_route)
.ruma_route(&client::update_rendezvous_session_route) .ruma_route(&client::delete_rendezvous_session_route)
.ruma_route(&client::get_rendezvous_session_route)
.ruma_route(&client::delete_rendezvous_session_route)
.layer(axum::middleware::map_response(
async |mut response: axum::response::Response| {
response.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_static("no-store"),
);
response
},
)),
)
.ruma_route(&client::get_authorization_server_metadata_route) .ruma_route(&client::get_authorization_server_metadata_route)
.merge(client::oauth::router(state)) .merge(client::oauth::router(state))
.route("/_continuwuity/server_version", get(client::continuwuity_server_version)) .route("/_continuwuity/server_version", get(client::continuwuity_server_version))
+3 -17
View File
@@ -11,11 +11,7 @@ use axum::{
use conduwuit::{Error, Result, err, error}; use conduwuit::{Error, Result, err, error};
use ruma::{ use ruma::{
CanonicalJsonObject, CanonicalJsonObject,
api::{ api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
IncomingRequest, IncomingRequestExt,
auth_scheme::AuthScheme,
error::{DeserializationError, FromHttpRequestError},
},
}; };
use serde::Deserialize; use serde::Deserialize;
@@ -118,18 +114,8 @@ where
.await?; .await?;
// Deserialize the body // Deserialize the body
let body_is_empty = body.is_empty(); let body = R::try_from_http_request(request, &borrowed_path)
let body = R::try_from_http_request(request, &borrowed_path).map_err(|e| match e { .map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
| FromHttpRequestError::Deserialization(DeserializationError::Json(ref json_err))
if body_is_empty || json_err.is_syntax() || json_err.is_eof() =>
err!(Request(NotJson(debug_warn!("{e}")))),
| FromHttpRequestError::Deserialization(DeserializationError::Utf8(_)) =>
err!(Request(NotJson(debug_warn!("{e}")))),
| FromHttpRequestError::Deserialization(
DeserializationError::Ident(_) | DeserializationError::Query(_),
) => err!(Request(InvalidParam(debug_warn!("{e}")))),
| _ => err!(Request(BadJson(debug_warn!("{e}")))),
})?;
Ok(Self { body, json_body, identity }) Ok(Self { body, json_body, identity })
} }
+26 -25
View File
@@ -47,6 +47,7 @@ pub(crate) enum ClientIdentity {
sender_device: Option<OwnedDeviceId>, sender_device: Option<OwnedDeviceId>,
appservice_info: Box<RegistrationInfo>, appservice_info: Box<RegistrationInfo>,
}, },
StaticClient,
} }
impl ClientIdentity { impl ClientIdentity {
@@ -54,6 +55,7 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } => | Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Some(sender_user), Some(sender_user),
| Self::StaticClient => None,
} }
} }
@@ -61,6 +63,8 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } => | Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
Ok(sender_user), Ok(sender_user),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
} }
} }
@@ -68,6 +72,7 @@ impl ClientIdentity {
match self { match self {
| Self::User { sender_device, .. } => Some(sender_device), | Self::User { sender_device, .. } => Some(sender_device),
| Self::Appservice { sender_device, .. } => sender_device.as_deref(), | Self::Appservice { sender_device, .. } => sender_device.as_deref(),
| Self::StaticClient => None,
} }
} }
@@ -77,12 +82,14 @@ impl ClientIdentity {
| Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device), | Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device),
| Self::Appservice { sender_device: None, .. } => | Self::Appservice { sender_device: None, .. } =>
Err!(Request(Forbidden("Appservices must masquerade to use this endpoint."))), Err!(Request(Forbidden("Appservices must masquerade to use this endpoint."))),
| Self::StaticClient =>
Err!(Request(Forbidden("Static clients cannot use this endpoint."))),
} }
} }
pub(crate) fn appservice_info(&self) -> Option<&RegistrationInfo> { pub(crate) fn appservice_info(&self) -> Option<&RegistrationInfo> {
match self { match self {
| Self::User { .. } => None, | Self::User { .. } | Self::StaticClient => None,
| Self::Appservice { appservice_info, .. } => Some(appservice_info), | Self::Appservice { appservice_info, .. } => Some(appservice_info),
} }
} }
@@ -194,10 +201,6 @@ impl CheckAuth for AccessTokenOptional {
authentication: Self::Output, authentication: Self::Output,
query: AuthQueryParams, query: AuthQueryParams,
) -> Result<Self::Identity> { ) -> Result<Self::Identity> {
if R::RATE_LIMITED && is_rendezvous_create_route(TypeId::of::<R>()) {
services.rendezvous.check_create_ratelimit(request_ip)?;
}
if let Some(authentication) = authentication { if let Some(authentication) = authentication {
check_access_token( check_access_token(
services, services,
@@ -282,11 +285,6 @@ impl CheckAuth for NoAccessToken {
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err)))) err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
})?; })?;
let is_rendezvous_session = is_rendezvous_session_route(TypeId::of::<R>());
if R::RATE_LIMITED && is_rendezvous_session {
services.rendezvous.check_session_ratelimit(request_ip)?;
}
if let Some(authentication) = authentication { if let Some(authentication) = authentication {
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[ check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
OAuthClientScope::ApiFullAccess, OAuthClientScope::ApiFullAccess,
@@ -294,7 +292,7 @@ impl CheckAuth for NoAccessToken {
.await .await
.map(Some) .map(Some)
} else { } else {
if R::RATE_LIMITED && !is_rendezvous_session { if R::RATE_LIMITED {
check_unauthenticated_request_ratelimiting(services, request_ip)?; check_unauthenticated_request_ratelimiting(services, request_ip)?;
} }
@@ -434,6 +432,23 @@ async fn check_access_token(
sender_device, sender_device,
appservice_info: Box::new(appservice_info), appservice_info: Box::new(appservice_info),
}) })
} else if let Some(session) = services.oauth.get_client_credentials_session(token) {
if !required_scopes
.iter()
.any(|scope| session.scopes.contains(scope))
{
return Err(Error::Request(
ErrorKind::InsufficientUserAuthentication(Box::new(
assign!(InsufficientUserAuthenticationErrorData::new(), {
scope: required_scopes.iter().cloned().collect()
}),
)),
"You do not have permission to access this endpoint.".into(),
StatusCode::UNAUTHORIZED,
));
}
Ok(ClientIdentity::StaticClient)
} else if services.users.is_previous_token(token).await { } else if services.users.is_previous_token(token).await {
// Return a soft-logout for previous tokens. This is necessary // Return a soft-logout for previous tokens. This is necessary
// to make token refreshing idempotent. // to make token refreshing idempotent.
@@ -460,20 +475,6 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result<Regi
Ok(appservice_info) Ok(appservice_info)
} }
fn is_rendezvous_create_route(route: TypeId) -> bool {
route == TypeId::of::<client::rendezvous::discover_rendezvous::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::create_rendezvous_session::msc4388::Request>()
}
fn is_rendezvous_session_route(route: TypeId) -> bool {
route == TypeId::of::<client::rendezvous::get_rendezvous_session::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::update_rendezvous_session::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::delete_rendezvous_session::msc4388::Request>()
}
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> { fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
if services if services
.config .config
+9
View File
@@ -346,6 +346,15 @@ pub fn check(config: &Config) -> Result {
} }
})?; })?;
for (id, client) in &config.oauth.clients {
if client.scopes.is_empty() {
warn!(
"The static OAuth client `{id}` has no scopes configured. It will not be able \
to access any API endpoints."
);
}
}
Ok(()) Ok(())
} }
+69 -39
View File
@@ -29,6 +29,7 @@ use ruma::{
OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId,
RoomVersionId, ServerName, RoomVersionId, ServerName,
api::{ api::{
OAuthClientScope,
client::{discovery::discover_support::ContactRole, rtc::RtcTransport}, client::{discovery::discover_support::ContactRole, rtc::RtcTransport},
federation::discovery::OldVerifyKey, federation::discovery::OldVerifyKey,
}, },
@@ -920,21 +921,6 @@ pub struct Config {
#[serde(default)] #[serde(default)]
pub forget_forced_upon_leave: bool, pub forget_forced_upon_leave: bool,
/// The maximum delay in milliseconds for delayed events (MSC4140). Setting
/// this or `delayed_events_max_scheduled` to 0 disables delayed events.
///
/// default: 604800000
#[serde(default = "default_delayed_events_max_delay_ms")]
pub delayed_events_max_delay_ms: u64,
/// The maximum number of delayed events each user can have scheduled at
/// once. Setting this or `delayed_events_max_delay_ms` to 0 disables
/// delayed events.
///
/// default: 100
#[serde(default = "default_delayed_events_max_scheduled")]
pub delayed_events_max_scheduled: u64,
/// Set this to true to require authentication when looking up user profiles /// Set this to true to require authentication when looking up user profiles
/// through this server. /// through this server.
/// ///
@@ -2765,7 +2751,12 @@ pub struct OauthConfig {
compatibility_mode: OAuthMode, compatibility_mode: OAuthMode,
/// display: hidden /// display: hidden
#[serde(default)]
pub oidc: Option<OidcConfig>, pub oidc: Option<OidcConfig>,
/// display: hidden
#[serde(default)]
pub clients: HashMap<String, OAuthClient>,
} }
impl OauthConfig { impl OauthConfig {
@@ -3007,6 +2998,54 @@ impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter<K> {
} }
} }
#[derive(Clone, Debug, Deserialize)]
#[config_example_generator(
filename = "conduwuit-example.toml",
section = "global.oauth.clients.\"$id\"",
optional = "true",
subheader = "\
# Use this section to add static OAuth clients for bots and automation.
# Clients added here may use the client credentials OAuth grant to authorize
# themselves with Continuwuity.
#
# Make sure to replace `$id` in the header with your client ID of choice! You can
# add more copies of this section with different IDs to add multiple clients.
#
# Because the client credentials grant authorizes the client as itself, without
# an attached user, clients that use it will not be able to access most of the Matrix
# client-server API. Administrative functionality that does not require a user
# will still be available."
)]
pub struct OAuthClient {
/// The client's client secret.
///
/// This must be supplied as the `client_secret` parameter when requesting
/// an access token with the OAuth 2.0 token endpoint. Continuwuity does
/// not check the `Authorization` header for requests to this endpoint.
pub client_secret: String,
/// A list of scopes that the client may request. Continuwuity allows static
/// clients to request the following scopes:
///
/// - "urn:matrix:client:cc.c10y.msc4484.server_administration" (MSC4484):
/// This scope grants access to the Matrix server administration APIs, as
/// well as Continuwuity's internal admin API (currently a work in
/// progress).
/// - "urn:matrix:client:api:*": This scope grants access to the Matrix
/// client-server API. Most endpoints require an authenticated Matrix user
/// and thus will not be usable by static clients.
///
/// The `urn:matrix:client:device:<id>` scope may not be requested by static
/// clients.
///
/// Scopes listed here are not granted by default. The client must
/// explicitly include them in the `scope` parameter of its access token
/// request.
///
/// default: []
pub scopes: BTreeSet<OAuthClientScope>,
}
const DEPRECATED_KEYS: &[&str] = &[ const DEPRECATED_KEYS: &[&str] = &[
"allow_check_for_updates", "allow_check_for_updates",
"allow_moderators_to_view_redacted_content", "allow_moderators_to_view_redacted_content",
@@ -3155,41 +3194,41 @@ fn default_database_backups_to_keep() -> i16 { 1 }
fn default_db_write_buffer_capacity_mb() -> f64 { 48.0 + parallelism_scaled_f64(4.0) } fn default_db_write_buffer_capacity_mb() -> f64 { 48.0 + parallelism_scaled_f64(4.0) }
fn default_db_cache_capacity_mb() -> f64 { 512.0 + parallelism_scaled_f64(512.0) } fn default_db_cache_capacity_mb() -> f64 { 128.0 + parallelism_scaled_f64(64.0) }
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(50_000).saturating_add(100_000) } fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(10_000).saturating_add(100_000) }
fn default_cache_capacity_modifier() -> f64 { 1.0 } fn default_cache_capacity_modifier() -> f64 { 1.0 }
fn default_auth_chain_cache_capacity() -> u32 { fn default_auth_chain_cache_capacity() -> u32 {
parallelism_scaled_u32(50_000).saturating_add(100_000) parallelism_scaled_u32(10_000).saturating_add(100_000)
} }
fn default_shorteventid_cache_capacity() -> u32 { fn default_shorteventid_cache_capacity() -> u32 {
parallelism_scaled_u32(100_000).saturating_add(100_000) parallelism_scaled_u32(50_000).saturating_add(100_000)
} }
fn default_eventidshort_cache_capacity() -> u32 { fn default_eventidshort_cache_capacity() -> u32 {
parallelism_scaled_u32(50_000).saturating_add(100_000) parallelism_scaled_u32(25_000).saturating_add(100_000)
} }
fn default_eventid_pdu_cache_capacity() -> u32 { fn default_eventid_pdu_cache_capacity() -> u32 {
parallelism_scaled_u32(50_000).saturating_add(100_000) parallelism_scaled_u32(25_000).saturating_add(100_000)
} }
fn default_shortstatekey_cache_capacity() -> u32 { fn default_shortstatekey_cache_capacity() -> u32 {
parallelism_scaled_u32(100_000).saturating_add(100_000) parallelism_scaled_u32(10_000).saturating_add(100_000)
} }
fn default_statekeyshort_cache_capacity() -> u32 { fn default_statekeyshort_cache_capacity() -> u32 {
parallelism_scaled_u32(50_000).saturating_add(100_000) parallelism_scaled_u32(10_000).saturating_add(100_000)
} }
fn default_servernameevent_data_cache_capacity() -> u32 { fn default_servernameevent_data_cache_capacity() -> u32 {
parallelism_scaled_u32(100_000).saturating_add(100_000) parallelism_scaled_u32(100_000).saturating_add(500_000)
} }
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(500).clamp(100, 12000) } fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(100) }
fn default_dns_cache_entries() -> u32 { 32768 } fn default_dns_cache_entries() -> u32 { 32768 }
@@ -3411,20 +3450,15 @@ fn default_admin_log_capture() -> String {
fn default_admin_room_tag() -> String { "m.server_notice".to_owned() } fn default_admin_room_tag() -> String { "m.server_notice".to_owned() }
#[must_use]
#[allow(clippy::as_conversions, clippy::cast_precision_loss)] #[allow(clippy::as_conversions, clippy::cast_precision_loss)]
pub fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) } fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
#[must_use] fn parallelism_scaled_u32(val: u32) -> u32 {
#[allow(clippy::as_conversions, clippy::cast_possible_truncation)] let val = val.try_into().expect("failed to cast u32 to usize");
pub fn parallelism_scaled_u32(val: u32) -> u32 { parallelism_scaled(val).try_into().unwrap_or(u32::MAX)
val.saturating_mul(sys::available_parallelism() as u32)
} }
#[must_use] fn parallelism_scaled(val: usize) -> usize { val.saturating_mul(sys::available_parallelism()) }
pub fn parallelism_scaled(val: usize) -> usize {
val.saturating_mul(sys::available_parallelism())
}
fn default_db_pool_workers() -> usize { fn default_db_pool_workers() -> usize {
sys::available_parallelism() sys::available_parallelism()
@@ -3464,10 +3498,6 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap())) PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
} }
fn default_delayed_events_max_delay_ms() -> u64 { 7 * 24 * 60 * 60 * 1000 }
fn default_delayed_events_max_scheduled() -> u64 { 100 }
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] } fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
// NOTE: This must be declared *after* every config struct in this file. The // NOTE: This must be declared *after* every config struct in this file. The
+1 -3
View File
@@ -171,14 +171,13 @@ impl Error {
/// Returns the Matrix error code / error kind /// Returns the Matrix error code / error kind
#[inline] #[inline]
pub fn kind(&self) -> ErrorKind { pub fn kind(&self) -> ErrorKind {
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized}; use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
match self { match self {
| Self::Federation(_, error) | Self::Ruma(error) => | Self::Federation(_, error) | Self::Ruma(error) =>
response::ruma_error_kind(error).clone(), response::ruma_error_kind(error).clone(),
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(), | BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
| Self::FeatureDisabled(..) => Unrecognized, | Self::FeatureDisabled(..) => Unrecognized,
| Self::Path(_) | Self::Query(_) => InvalidParam,
| _ => Unknown, | _ => Unknown,
} }
} }
@@ -195,7 +194,6 @@ impl Error {
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()), | Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), | Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
| Self::Conflict(_) => StatusCode::CONFLICT, | Self::Conflict(_) => StatusCode::CONFLICT,
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
| Self::Io(error) => response::io_error_code(error.kind()), | Self::Io(error) => response::io_error_code(error.kind()),
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED, | Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
| _ => StatusCode::INTERNAL_SERVER_ERROR, | _ => StatusCode::INTERNAL_SERVER_ERROR,
-3
View File
@@ -73,9 +73,6 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
// 413 // 413
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE, | TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
// 409
| ConcurrentWrite => StatusCode::CONFLICT,
// 404 // 404
| Unrecognized | NotFound => StatusCode::NOT_FOUND, | Unrecognized | NotFound => StatusCode::NOT_FOUND,
-2
View File
@@ -69,11 +69,9 @@ impl Pdu {
if context.user_id.is_none_or(|u| u != self.sender()) { if context.user_id.is_none_or(|u| u != self.sender()) {
unsigned.remove("transaction_id"); unsigned.remove("transaction_id");
unsigned.remove("delay_id");
} }
} else { } else {
unsigned.remove("transaction_id"); unsigned.remove("transaction_id");
unsigned.remove("delay_id");
} }
if let Some(expires_at) = self if let Some(expires_at) = self
-4
View File
@@ -53,9 +53,5 @@ pub fn unstable_features(experiments: &Experiments) -> BTreeMap<String, bool> {
// Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354) // Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354)
// Proposal merged, expected for spec v1.20/v2.0 // Proposal merged, expected for spec v1.20/v2.0
("org.matrix.msc4354".to_owned(), true), ("org.matrix.msc4354".to_owned(), true),
// Delayed events (https://github.com/matrix-org/matrix-spec-proposals/pull/4140)
// Proposal merged, expected for spec v1.20/v2.0
("org.matrix.msc4140".to_owned(), true),
("org.matrix.msc4140.stable".to_owned(), true),
]) ])
} }
-3
View File
@@ -5,7 +5,6 @@ pub type DigestOut = [u8; 256 / 8];
/// Sha256 hash (input gather joined by 0xFF bytes) /// Sha256 hash (input gather joined by 0xFF bytes)
#[must_use] #[must_use]
#[tracing::instrument(skip(inputs), level = "trace")] #[tracing::instrument(skip(inputs), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn delimited<'a, T, I>(mut inputs: I) -> DigestOut pub fn delimited<'a, T, I>(mut inputs: I) -> DigestOut
where where
I: Iterator<Item = T> + 'a, I: Iterator<Item = T> + 'a,
@@ -26,7 +25,6 @@ where
/// Sha256 hash (input gather) /// Sha256 hash (input gather)
#[must_use] #[must_use]
#[tracing::instrument(skip(inputs), level = "trace")] #[tracing::instrument(skip(inputs), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn concat<'a, T, I>(inputs: I) -> DigestOut pub fn concat<'a, T, I>(inputs: I) -> DigestOut
where where
I: Iterator<Item = T> + 'a, I: Iterator<Item = T> + 'a,
@@ -45,7 +43,6 @@ where
#[inline] #[inline]
#[must_use] #[must_use]
#[tracing::instrument(skip(input), level = "trace")] #[tracing::instrument(skip(input), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn hash<T>(input: T) -> DigestOut pub fn hash<T>(input: T) -> DigestOut
where where
T: AsRef<[u8]>, T: AsRef<[u8]>,
+1 -1
View File
@@ -29,7 +29,7 @@ fn descriptor_cf_options(
let mut opts = set_table_options(opts, &desc, cache)?; let mut opts = set_table_options(opts, &desc, cache)?;
opts.set_min_write_buffer_number(1); opts.set_min_write_buffer_number(1);
opts.set_max_write_buffer_number(3); opts.set_max_write_buffer_number(2);
opts.set_write_buffer_size(desc.write_size); opts.set_write_buffer_size(desc.write_size);
opts.set_target_file_size_base(desc.file_size); opts.set_target_file_size_base(desc.file_size);
-16
View File
@@ -543,20 +543,4 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "websessionid_session", name: "websessionid_session",
..descriptor::RANDOM_SMALL ..descriptor::RANDOM_SMALL
}, },
Descriptor {
name: "delayid_scheduleddelayedevent",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "delayid_finalizeddelayedevent",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "useriddelayid",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "useridfinalizedtsdelayid",
..descriptor::RANDOM_SMALL
},
]; ];
+5
View File
@@ -55,6 +55,7 @@ default = [
standard = [ standard = [
"brotli_compression", "brotli_compression",
"direct_tls", "direct_tls",
"element_hacks",
"gzip_compression", "gzip_compression",
"io_uring", "io_uring",
"jemalloc_conf", "jemalloc_conf",
@@ -85,6 +86,10 @@ console = [
direct_tls = [ direct_tls = [
"conduwuit-router/direct_tls" "conduwuit-router/direct_tls"
] ]
element_hacks = [
"conduwuit-service/element_hacks",
"conduwuit-router/element_hacks",
]
gzip_compression = [ gzip_compression = [
"conduwuit-core/gzip_compression", "conduwuit-core/gzip_compression",
"conduwuit-router/gzip_compression", "conduwuit-router/gzip_compression",
+3
View File
@@ -27,6 +27,9 @@ direct_tls = [
"axum-server/tls-rustls-no-provider", "axum-server/tls-rustls-no-provider",
"dep:axum-server-dual-protocol", "dep:axum-server-dual-protocol",
] ]
element_hacks = [
"conduwuit-api/element_hacks",
]
gzip_compression = [ gzip_compression = [
"conduwuit-admin/gzip_compression", "conduwuit-admin/gzip_compression",
"conduwuit-api/gzip_compression", "conduwuit-api/gzip_compression",
+4 -4
View File
@@ -8,7 +8,7 @@ use axum::{
extract::State, extract::State,
response::{IntoResponse, Response}, response::{IntoResponse, Response},
}; };
use conduwuit::{Result, debug_warn, err, error, info, trace}; use conduwuit::{Result, debug, debug_error, debug_warn, err, error, trace};
use conduwuit_service::Services; use conduwuit_service::Services;
use futures::FutureExt; use futures::FutureExt;
use http::{Method, StatusCode, Uri}; use http::{Method, StatusCode, Uri};
@@ -106,11 +106,11 @@ 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() {
info!(%method, %uri, "{code} {reason}"); error!(%method, %uri, "{code} {reason}");
} else if status.is_client_error() { } else if status.is_client_error() {
info!(%method, %uri, "{code} {reason}"); debug_error!(%method, %uri, "{code} {reason}");
} else if status.is_redirection() { } else if status.is_redirection() {
trace!(%method, %uri, "{code} {reason}"); debug!(%method, %uri, "{code} {reason}");
} else { } else {
trace!(%method, %uri, "{code} {reason}"); trace!(%method, %uri, "{code} {reason}");
} }
+1
View File
@@ -30,6 +30,7 @@ console = [
"dep:rustyline-async", "dep:rustyline-async",
"dep:termimad", "dep:termimad",
] ]
element_hacks = []
gzip_compression = [ gzip_compression = [
"conduwuit-core/gzip_compression", "conduwuit-core/gzip_compression",
"reqwest/gzip", "reqwest/gzip",
+1 -9
View File
@@ -9,7 +9,6 @@ use conduwuit::{
Err, Error, Result, debug, debug_error, debug_info, debug_warn, err, metrics::KeyValue, Err, Error, Result, debug, debug_error, debug_info, debug_warn, err, metrics::KeyValue,
trace, utils::response::LimitReadExt, trace, utils::response::LimitReadExt,
}; };
use http::header::HOST;
use ipaddress::IPAddress; use ipaddress::IPAddress;
use reqwest::{Client, Method, Request, Response, Url}; use reqwest::{Client, Method, Request, Response, Url};
use resolvematrix::resolution::Resolution; use resolvematrix::resolution::Resolution;
@@ -153,18 +152,11 @@ impl super::Service {
self.mark_destination_stale(dest); self.mark_destination_stale(dest);
})?; })?;
let mut request = Request::try_from(request.try_into_http_request::<Vec<u8>>( let request = Request::try_from(request.try_into_http_request::<Vec<u8>>(
actual.base_url().as_str(), actual.base_url().as_str(),
authentication, authentication,
PathBuilderInput::create(), PathBuilderInput::create(),
)?)?; )?)?;
if actual.is_override {
request
.headers_mut()
.insert(HOST, actual.host.clone().try_into()?);
}
self.validate_url(request.url())?; self.validate_url(request.url())?;
self.services.server.check_running()?; self.services.server.check_running()?;
+7
View File
@@ -125,6 +125,12 @@ impl ClientMetadata {
} }
} }
if self.grant_types.contains(&GrantType::ClientCredentials) {
return Err(
"Dynamically registered clients may not use the client credentials grant."
);
}
Ok(()) Ok(())
} }
} }
@@ -144,6 +150,7 @@ pub enum GrantType {
#[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")] #[serde(rename = "urn:ietf:params:oauth:grant-type:device_code")]
DeviceCode, DeviceCode,
RefreshToken, RefreshToken,
ClientCredentials,
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
+8 -2
View File
@@ -102,7 +102,7 @@ impl Display for RequestedScopes {
} }
} }
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct RawScopes(String); pub struct RawScopes(String);
impl RawScopes { impl RawScopes {
@@ -257,6 +257,11 @@ pub enum TokenRequestType {
RefreshToken { RefreshToken {
refresh_token: String, refresh_token: String,
}, },
ClientCredentials {
client_secret: String,
#[serde(default)]
scope: RawScopes,
},
} }
impl TokenRequestType { impl TokenRequestType {
@@ -266,6 +271,7 @@ impl TokenRequestType {
| Self::AuthorizationCode { .. } => GrantType::AuthorizationCode, | Self::AuthorizationCode { .. } => GrantType::AuthorizationCode,
| Self::DeviceCode { .. } => GrantType::DeviceCode, | Self::DeviceCode { .. } => GrantType::DeviceCode,
| Self::RefreshToken { .. } => GrantType::RefreshToken, | Self::RefreshToken { .. } => GrantType::RefreshToken,
| Self::ClientCredentials { .. } => GrantType::ClientCredentials,
} }
} }
} }
@@ -275,7 +281,7 @@ pub struct TokenResponse {
pub access_token: String, pub access_token: String,
pub token_type: TokenType, pub token_type: TokenType,
pub expires_in: u64, pub expires_in: u64,
pub refresh_token: String, pub refresh_token: Option<String>,
pub scope: String, pub scope: String,
} }
+119 -12
View File
@@ -7,10 +7,10 @@ use std::{
use base64::Engine; use base64::Engine;
use conduwuit::{ use conduwuit::{
Result, SyncMutex, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard,
config::experiments::ToggledExperiment, config::experiments::ToggledExperiment,
error, info, error, info,
utils::{self, MutexMap, hash::sha256}, utils::{self, MutexMap, hash::sha256, string::constant_time_eq},
warn, warn,
}; };
use database::{Deserialized, Json, Map}; use database::{Deserialized, Json, Map};
@@ -27,8 +27,9 @@ use crate::{
client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType}, client_metadata::{ApplicationType, ClientMetadata, GrantType, ResponseType},
grant::{ grant::{
AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod, AuthorizationCodeQuery, AuthorizationCodeResponse, CodeChallengeMethod,
DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RequestedScopes, DeviceCodeRequest, DeviceCodeResponse, ErrorCode, OAuthError, RawScopes,
ResponseMode, TokenRequest, TokenRequestType, TokenResponse, TokenType, RequestedScopes, ResponseMode, TokenRequest, TokenRequestType, TokenResponse,
TokenType,
}, },
}, },
users::{self, DeviceToken, PreviousTokenAction}, users::{self, DeviceToken, PreviousTokenAction},
@@ -53,6 +54,7 @@ pub struct Service {
tickets: SyncMutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>, tickets: SyncMutex<HashMap<String, HashMap<OAuthTicket, SystemTime>>>,
pending_auth_code_grants: SyncMutex<LruCache<String, PendingAuthCodeGrant>>, pending_auth_code_grants: SyncMutex<LruCache<String, PendingAuthCodeGrant>>,
pending_device_code_grants: SyncMutex<LruCache<String, PendingDeviceCodeGrant>>, pending_device_code_grants: SyncMutex<LruCache<String, PendingDeviceCodeGrant>>,
client_credential_sessions: SyncMutex<HashMap<String, ClientCredentialsSession>>,
} }
struct Data { struct Data {
@@ -106,6 +108,12 @@ struct RefreshTokenInfo {
device_id: OwnedDeviceId, device_id: OwnedDeviceId,
} }
pub struct ClientCredentialsSession {
pub client_id: String,
pub scopes: BTreeSet<OAuthClientScope>,
created_at: SystemTime,
}
struct PendingAuthCodeGrant { struct PendingAuthCodeGrant {
authorizing_user: OwnedUserId, authorizing_user: OwnedUserId,
requested_scopes: RequestedScopes, requested_scopes: RequestedScopes,
@@ -201,6 +209,7 @@ impl crate::Service for Service {
tickets: SyncMutex::default(), tickets: SyncMutex::default(),
pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)),
client_credential_sessions: SyncMutex::default(),
})) }))
} }
@@ -497,12 +506,25 @@ impl Service {
pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> { pub async fn issue_token(&self, request: TokenRequest) -> Result<TokenResponse, OAuthError> {
let TokenRequest { client_id, request } = request; let TokenRequest { client_id, request } = request;
let Some(client_metadata) = self.get_client_metadata(&client_id).await else { if !matches!(request, TokenRequestType::ClientCredentials { .. }) {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Invalid client ID")); // The client credentials grant can only be used by statically
}; // registered clients, and the other grant types can
// only be used by dynamically registered clients, so we
// don't look up the dynamic client metadata if the token request is
// for the client credentials grant.
if !client_metadata.grant_types.contains(&request.grant_type()) { let Some(client_metadata) = self.get_client_metadata(&client_id).await else {
return Err(OAuthError::unauthorized_client("Client cannot request this grant type")); return Err(OAuthError::new_static(
ErrorCode::InvalidClient,
"Invalid client ID",
));
};
if !client_metadata.grant_types.contains(&request.grant_type()) {
return Err(OAuthError::unauthorized_client(
"Client cannot request this grant type",
));
}
} }
match request { match request {
@@ -574,6 +596,8 @@ impl Service {
}, },
| TokenRequestType::RefreshToken { refresh_token } => | TokenRequestType::RefreshToken { refresh_token } =>
self.refresh_session(client_id, refresh_token).await, self.refresh_session(client_id, refresh_token).await,
| TokenRequestType::ClientCredentials { client_secret, scope: scopes } =>
self.create_client_credentials_token(&client_id, &client_secret, &scopes),
} }
} }
@@ -590,8 +614,12 @@ impl Service {
self.services.users.find_from_token(&token).await self.services.users.find_from_token(&token).await
{ {
(user_id, device_id) (user_id, device_id)
} else if self.get_client_credentials_session(&token).is_some() {
return Err(OAuthError::invalid_grant(
"Access tokens for static clients cannot be revoked.",
));
} else { } else {
return Err(OAuthError::invalid_grant("Invalid access or refersh token")); return Err(OAuthError::invalid_grant("Invalid access or refresh token."));
}; };
// This will also call [`Self::remove_session`] // This will also call [`Self::remove_session`]
@@ -728,7 +756,7 @@ impl Service {
token_type: TokenType::Bearer, token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(), expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope: response_scope, scope: response_scope,
refresh_token, refresh_token: Some(refresh_token),
}) })
} }
@@ -855,10 +883,89 @@ impl Service {
token_type: TokenType::Bearer, token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(), expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
scope, scope,
refresh_token: new_refresh_token, refresh_token: Some(new_refresh_token),
}) })
} }
fn create_client_credentials_token(
&self,
client_id: &str,
client_secret: &str,
scopes: &RawScopes,
) -> Result<TokenResponse, OAuthError> {
let now = SystemTime::now();
let Some(client) = self.services.config.oauth.clients.get(client_id) else {
return Err(OAuthError::new_static(ErrorCode::InvalidClient, "Unknown client ID"));
};
let RequestedScopes { device_id, scopes } = scopes
.to_scopes()
.map_err(|err| OAuthError::new(ErrorCode::InvalidGrant, err))?;
if device_id.is_some() {
return Err(OAuthError::new_static(
ErrorCode::InvalidGrant,
"Static clients may not request a device ID",
));
}
if !constant_time_eq(client_secret, &client.client_secret) {
return Err(OAuthError::new_static(
ErrorCode::InvalidClient,
"Client secret does not match",
));
}
if !scopes.is_subset(&client.scopes) {
return Err(OAuthError::new_static(
ErrorCode::InvalidScope,
"This client may not request those scopes",
));
}
let mut sessions = self.client_credential_sessions.lock();
// Clear expired sessions while we're at it
sessions.retain(|_, session| {
now.duration_since(session.created_at)
.is_ok_and(|age| age <= Self::ACCESS_TOKEN_MAX_AGE)
});
let access_token = Self::generate_token();
let scope = scopes.iter().join(" ");
sessions.insert(access_token.clone(), ClientCredentialsSession {
client_id: client_id.to_owned(),
scopes,
created_at: now,
});
Ok(TokenResponse {
access_token,
token_type: TokenType::Bearer,
expires_in: Self::ACCESS_TOKEN_MAX_AGE.as_secs(),
refresh_token: None,
scope,
})
}
pub fn get_client_credentials_session(
&self,
token: &str,
) -> Option<SyncMappedMutexGuard<'_, ClientCredentialsSession>> {
let sessions = self.client_credential_sessions.lock();
SyncMutexGuard::try_map(sessions, |sessions| {
sessions.get_mut(token).filter(|session| {
SystemTime::now()
.duration_since(session.created_at)
.is_ok_and(|age| age <= Self::ACCESS_TOKEN_MAX_AGE)
})
})
.ok()
}
pub async fn remove_session(&self, user_id: &UserId, device_id: &DeviceId) { pub async fn remove_session(&self, user_id: &UserId, device_id: &DeviceId) {
let _lock = self.session_mutex.lock(&(user_id, device_id)).await; let _lock = self.session_mutex.lock(&(user_id, device_id)).await;
let session_info = self.get_session_info_for_device(user_id, device_id).await; let session_info = self.get_session_info_for_device(user_id, device_id).await;
+21 -93
View File
@@ -1,38 +1,25 @@
use std::{ use std::{
net::IpAddr,
sync::Arc, sync::Arc,
time::{Duration, Instant}, time::{Duration, SystemTime},
}; };
use conduwuit::{ use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils};
Err, Error, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils,
};
use governor::{
DefaultKeyedRateLimiter, Quota, RateLimiter,
clock::{Clock, DefaultClock},
};
use lru_cache::LruCache; use lru_cache::LruCache;
use nonzero_ext::nonzero;
use ruma::{ use ruma::{
OwnedTransactionId, OwnedTransactionId,
api::{ api::client::rendezvous::{
client::rendezvous::{ create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session, update_rendezvous_session,
update_rendezvous_session,
},
error::{ErrorKind, LimitExceededErrorData, RetryAfter},
}, },
}; };
pub struct Service { pub struct Service {
sessions: SyncMutex<LruCache<String, Session>>, sessions: SyncMutex<LruCache<String, Session>>,
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
} }
struct Session { struct Session {
data: String, data: String,
created_at: Instant, created_at: SystemTime,
last_sequence_token: String, last_sequence_token: String,
transaction_sequences: LruCache<OwnedTransactionId, String>, transaction_sequences: LruCache<OwnedTransactionId, String>,
} }
@@ -40,31 +27,20 @@ struct Session {
impl Session { impl Session {
const SAVED_TRANSACTION_SEQUENCES: usize = 256; const SAVED_TRANSACTION_SEQUENCES: usize = 256;
fn new(data: String, sequence_token: String, now: Instant) -> Self { fn new(data: String, sequence_token: String) -> Self {
Self { Self {
data, data,
created_at: now, created_at: SystemTime::now(),
last_sequence_token: sequence_token, last_sequence_token: sequence_token,
transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES), transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES),
} }
} }
fn time_remaining(&self, now: Instant) -> Option<Duration> {
let age = now.saturating_duration_since(self.created_at);
(age < Service::SESSION_MAX_AGE)
.then(|| Service::SESSION_MAX_AGE.saturating_sub(age))
.filter(|remaining| !remaining.is_zero())
}
fn is_expired(&self, now: Instant) -> bool { self.time_remaining(now).is_none() }
} }
impl crate::Service for Service { impl crate::Service for Service {
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> { fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
Ok(Arc::new(Self { Ok(Arc::new(Self {
sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)), sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)),
create_ratelimiter: RateLimiter::keyed(Self::CREATE_RATELIMIT),
session_ratelimiter: RateLimiter::keyed(Self::SESSION_RATELIMIT),
})) }))
} }
@@ -72,64 +48,25 @@ impl crate::Service for Service {
} }
impl Service { impl Service {
const CREATE_RATELIMIT: Quota = Quota::per_minute(nonzero!(30_u32));
const MAX_DATA_SIZE_BYTES: usize = 4096; const MAX_DATA_SIZE_BYTES: usize = 4096;
const MAX_SESSIONS: usize = 256; const MAX_SESSIONS: usize = 256;
const SESSION_MAX_AGE: Duration = Duration::from_secs(300); const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
const SESSION_RATELIMIT: Quota = Quota::per_minute(nonzero!(300_u32));
const TOKEN_LENGTH: usize = 32; const TOKEN_LENGTH: usize = 32;
pub fn check_create_ratelimit(&self, ip: IpAddr) -> Result<()> {
Self::check_ratelimiter(&self.create_ratelimiter, ip)
}
pub fn check_session_ratelimit(&self, ip: IpAddr) -> Result<()> {
Self::check_ratelimiter(&self.session_ratelimiter, ip)
}
fn check_ratelimiter(
ratelimiter: &DefaultKeyedRateLimiter<IpAddr>,
ip: IpAddr,
) -> Result<()> {
if let Err(not_until) = ratelimiter.check_key(&ip) {
let wait_time = not_until.wait_time_from(DefaultClock::default().now());
let mut data = LimitExceededErrorData::new();
data.retry_after = Some(RetryAfter::Delay(wait_time));
return Err(Error::BadRequest(
ErrorKind::LimitExceeded(data),
"Rate limit exceeded.",
));
}
Ok(())
}
fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) } fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) }
fn is_valid_opaque_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 255
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~'))
}
/// Lock and fetch an unexpired rendezvous session. /// Lock and fetch an unexpired rendezvous session.
fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, Session>> { fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, Session>> {
self.lock_session_at(id, Instant::now())
}
fn lock_session_at(
&self,
id: &str,
now: Instant,
) -> Result<SyncMappedMutexGuard<'_, Session>> {
// We don't clear out expired sessions manually, the LRU cache will // We don't clear out expired sessions manually, the LRU cache will
// evict them over time // evict them over time
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| { SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
sessions sessions
.get_mut(id) .get_mut(id)
.filter(|session| !session.is_expired(now)) .filter(|session| {
SystemTime::now()
.duration_since(session.created_at)
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
})
.ok_or_else(|| err!(Request(NotFound("Unknown session")))) .ok_or_else(|| err!(Request(NotFound("Unknown session"))))
}) })
.map_err(at!(1)) .map_err(at!(1))
@@ -149,7 +86,7 @@ impl Service {
self.sessions self.sessions
.lock() .lock()
.insert(id.clone(), Session::new(data, sequence_token.clone(), Instant::now())); .insert(id.clone(), Session::new(data, sequence_token.clone()));
Ok(create_rendezvous_session::msc4388::Response::new( Ok(create_rendezvous_session::msc4388::Response::new(
id, id,
@@ -166,12 +103,6 @@ impl Service {
sequence_token: String, sequence_token: String,
data: String, data: String,
) -> Result<update_rendezvous_session::msc4388::Response> { ) -> Result<update_rendezvous_session::msc4388::Response> {
if !Self::is_valid_opaque_id(transaction.as_str()) {
return Err!(Request(InvalidParam(
"Transaction ID does not comply with the opaque identifier grammar"
)));
}
let mut session = self.lock_session(id)?; let mut session = self.lock_session(id)?;
// If the provided transaction ID was used already, we have to return // If the provided transaction ID was used already, we have to return
@@ -206,12 +137,13 @@ impl Service {
/// Look up a rendezvous session by ID. /// Look up a rendezvous session by ID.
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> { pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
let now = Instant::now(); let session = self.lock_session(id)?;
let session = self.lock_session_at(id, now)?;
let session_time_remaining = session let session_age = SystemTime::now()
.time_remaining(now) .duration_since(session.created_at)
.unwrap_or_else(|| Duration::from_millis(1)); .unwrap_or(Duration::MAX);
let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age);
Ok(get_rendezvous_session::msc4388::Response::new( Ok(get_rendezvous_session::msc4388::Response::new(
session.last_sequence_token.clone(), session.last_sequence_token.clone(),
@@ -226,12 +158,8 @@ impl Service {
id: &str, id: &str,
) -> Result<delete_rendezvous_session::msc4388::Response> { ) -> Result<delete_rendezvous_session::msc4388::Response> {
let mut sessions = self.sessions.lock(); let mut sessions = self.sessions.lock();
let now = Instant::now();
if sessions if sessions.remove(id).is_some() {
.remove(id)
.is_some_and(|session| !session.is_expired(now))
{
Ok(delete_rendezvous_session::msc4388::Response::new()) Ok(delete_rendezvous_session::msc4388::Response::new())
} else { } else {
Err!(Request(NotFound("Unknown session"))) Err!(Request(NotFound("Unknown session")))
-584
View File
@@ -1,584 +0,0 @@
mod submission_queue;
use std::{
collections::BTreeMap,
fmt::Write,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::{Duration, SystemTime},
};
use async_trait::async_trait;
use conduwuit::{
Err, Error, Result, Server, debug_warn, err, error,
matrix::pdu::{PartialPdu, sticky},
utils::{
self, MutexMap,
stream::{ReadyExt, TryIgnore},
},
};
use database::{Deserialized, Ignore, Interfix, Json, Map};
use futures::StreamExt;
use http::StatusCode;
use loole::Sender;
use ruma::{
DeviceId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedTransactionId,
OwnedUserId, TransactionId, UserId,
api::{
client::delayed_events::{
DelayedEvent, DelayedEventCancelled, DelayedEventError, DelayedEventOutcome,
DelayedEventSent, FinalizedDelayedEvent as FinalizedDelayedEventData,
update_delayed_event::UpdateAction,
},
error::{ErrorKind, LimitExceededErrorData, RetryAfter, StandardErrorBody},
},
events::{AnyTimelineEventContent, TimelineEventType, sticky::StickyDurationMs},
serde::Raw,
};
use serde::{Deserialize, Serialize};
use submission_queue::SubmissionQueue;
use tokio::sync::Mutex;
use crate::{Dep, config, rooms, transactions, users};
const DELAY_ID_LENGTH: usize = 32;
/// The retention limits for finalized delayed events recommended by MSC4140.
const FINALIZED_RETENTION: Duration = Duration::from_hours(7 * 24);
const MAX_FINALIZED_PER_USER: usize = 1000;
struct Data {
delayid_scheduleddelayedevent: Arc<Map>,
delayid_finalizeddelayedevent: Arc<Map>,
useriddelayid: Arc<Map>,
useridfinalizedtsdelayid: Arc<Map>,
}
struct Services {
server: Arc<Server>,
config: Dep<config::Service>,
state: Dep<rooms::state::Service>,
timeline: Dep<rooms::timeline::Service>,
transactions: Dep<transactions::Service>,
users: Dep<users::Service>,
}
pub struct Service {
db: Data,
services: Services,
/// Ensures each delayed event is only finalized once.
event_locks: MutexMap<String, ()>,
transaction_locks: MutexMap<OwnedUserId, ()>,
submission_queue: Mutex<SubmissionQueue>,
submission_queue_sender: Sender<(SystemTime, String)>,
interrupt: Sender<()>,
mem_usage: AtomicUsize,
}
#[async_trait]
impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
let (sender, receiver) = loole::unbounded();
let (interrupt_sender, interrupt_receiver) = loole::bounded(1);
Ok(Arc::new(Self {
db: Data {
delayid_scheduleddelayedevent: args.db["delayid_scheduleddelayedevent"].clone(),
delayid_finalizeddelayedevent: args.db["delayid_finalizeddelayedevent"].clone(),
useriddelayid: args.db["useriddelayid"].clone(),
useridfinalizedtsdelayid: args.db["useridfinalizedtsdelayid"].clone(),
},
services: Services {
server: args.server.clone(),
config: args.depend::<config::Service>("config"),
state: args.depend::<rooms::state::Service>("rooms::state"),
timeline: args.depend::<rooms::timeline::Service>("rooms::timeline"),
transactions: args.depend::<transactions::Service>("transactions"),
users: args.depend::<users::Service>("users"),
},
event_locks: MutexMap::new(),
transaction_locks: MutexMap::new(),
submission_queue: Mutex::new(SubmissionQueue::new(receiver, interrupt_receiver)),
submission_queue_sender: sender,
interrupt: interrupt_sender,
mem_usage: AtomicUsize::new(0),
}))
}
async fn worker(self: Arc<Self>) -> Result { submission_queue::worker(&self).await }
fn interrupt(&self) { self.interrupt.try_send(()).ok(); }
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
async fn memory_usage(&self, out: &mut (dyn Write + Send)) -> Result {
let mem_usage = self.mem_usage.load(Ordering::Relaxed);
writeln!(out, "submission_queue: {mem_usage} bytes")?;
Ok(())
}
}
pub struct NewDelayedEvent {
pub room_id: OwnedRoomId,
pub event_type: TimelineEventType,
pub state_key: Option<String>,
pub content: Raw<AnyTimelineEventContent>,
pub delay: Duration,
pub timestamp: Option<MilliSecondsSinceUnixEpoch>,
pub sticky_duration_ms: Option<StickyDurationMs>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ScheduledDelayedEvent {
user_id: OwnedUserId,
room_id: OwnedRoomId,
event_type: TimelineEventType,
state_key: Option<String>,
content: Raw<AnyTimelineEventContent>,
delay: Duration,
delayed_since: SystemTime,
timestamp: Option<MilliSecondsSinceUnixEpoch>,
sticky_duration_ms: Option<StickyDurationMs>,
}
impl ScheduledDelayedEvent {
fn send_time(&self) -> SystemTime {
self.delayed_since
.checked_add(self.delay)
.unwrap_or(self.delayed_since)
}
fn into_delayed_event(self, delay_id: String) -> DelayedEvent {
DelayedEvent::new(
delay_id,
self.room_id,
self.event_type,
self.state_key,
self.content,
self.delay,
MilliSecondsSinceUnixEpoch::from_system_time(self.delayed_since)
.unwrap_or_else(MilliSecondsSinceUnixEpoch::now),
)
}
}
#[derive(Debug, Serialize, Deserialize)]
struct FinalizedDelayedEvent {
event: ScheduledDelayedEvent,
finalized: FinalizedDelayedEventData,
}
impl FinalizedDelayedEvent {
fn into_delayed_event(self, delay_id: String) -> DelayedEvent {
let mut event = self.event.into_delayed_event(delay_id);
event.finalized = Some(self.finalized);
event
}
fn satisfies(&self, action: &UpdateAction) -> bool {
matches!(
(action, &self.finalized.outcome),
(UpdateAction::Send, DelayedEventOutcome::Sent(_))
| (
UpdateAction::Cancel,
DelayedEventOutcome::Cancelled(_) | DelayedEventOutcome::Error(_)
)
)
}
}
impl Service {
/// Returns the maximum delay users may request, or `None` if delayed events
/// are disabled.
#[must_use]
pub fn max_delay(&self) -> Option<Duration> {
let config = &self.services.config;
(config.delayed_events_max_delay_ms > 0 && config.delayed_events_max_scheduled > 0)
.then(|| Duration::from_millis(config.delayed_events_max_delay_ms))
}
/// Stores a new delayed event and queues it for sending, returning its
/// delay ID. Retries with the same transaction ID return the same delay ID.
pub async fn schedule(
&self,
user_id: &UserId,
device_id: Option<&DeviceId>,
txn_id: &TransactionId,
event: NewDelayedEvent,
) -> Result<String> {
let txn_id: OwnedTransactionId = format!("delayed_event/{txn_id}").into();
let _lock = self.transaction_locks.lock(user_id).await;
if let Ok(response) = self
.services
.transactions
.get_client_txn(user_id, device_id, &txn_id)
.await
{
return utils::string_from_bytes(&response)
.map_err(|e| err!(Database("Invalid delay ID in transaction data: {e}")));
}
self.check_scheduled_limit(user_id).await?;
let delay_id = utils::random_string(DELAY_ID_LENGTH);
let event = ScheduledDelayedEvent {
user_id: user_id.to_owned(),
room_id: event.room_id,
event_type: event.event_type,
state_key: event.state_key,
content: event.content,
delay: event.delay,
delayed_since: SystemTime::now(),
timestamp: event.timestamp,
sticky_duration_ms: event.sticky_duration_ms,
};
let send_time = event.send_time();
self.db
.delayid_scheduleddelayedevent
.raw_put(&delay_id, Json(&event));
self.db
.useriddelayid
.put_raw((user_id, delay_id.as_str()), []);
self.services.transactions.add_client_txnid(
user_id,
device_id,
&txn_id,
delay_id.as_bytes(),
);
self.submission_queue_sender
.send((send_time, delay_id.clone()))
.map_err(|_| err!("The delayed events worker is not running"))?;
Ok(delay_id)
}
/// Returns `M_LIMIT_EXCEEDED` if the user already has the maximum number of
/// delayed events scheduled, with `Retry-After` set to when the next one is
/// due.
async fn check_scheduled_limit(&self, user_id: &UserId) -> Result {
let max_scheduled = usize::try_from(self.services.config.delayed_events_max_scheduled)
.unwrap_or(usize::MAX);
let send_times: Vec<SystemTime> = self
.user_delay_ids(user_id)
.filter_map(async |delay_id| {
self.get_scheduled(&delay_id)
.await
.map(|event| event.send_time())
})
.collect()
.await;
if send_times.len() < max_scheduled {
return Ok(());
}
let retry_after = send_times
.iter()
.min()
.and_then(|time| time.duration_since(SystemTime::now()).ok())
.unwrap_or_default();
let retry_after = Duration::from_secs(
retry_after
.as_millis()
// MSC4140 requires rounding up to the nearest second.
.div_ceil(1000)
.try_into()
.unwrap_or(u64::MAX),
);
let mut data = LimitExceededErrorData::new();
data.retry_after = Some(RetryAfter::Delay(retry_after));
Err(Error::Request(
ErrorKind::LimitExceeded(data),
"The maximum number of delayed events has been reached.".into(),
StatusCode::TOO_MANY_REQUESTS,
))
}
/// Restarts, sends or cancels one of the user's delayed events. Repeating
/// an action on an event that was already finalized the same way succeeds,
/// and conflicting actions return 409.
pub async fn update(&self, user_id: &UserId, delay_id: &str, action: UpdateAction) -> Result {
let _lock = self.event_locks.lock(delay_id).await;
if let Some(mut event) = self.get_scheduled(delay_id).await {
if event.user_id != user_id {
return Err!(Request(NotFound("No delayed event with this ID was found.")));
}
return match action {
| UpdateAction::Restart => {
// The worker requeues it when the old send time is reached.
event.delayed_since = SystemTime::now();
self.db
.delayid_scheduleddelayedevent
.raw_put(delay_id, Json(&event));
Ok(())
},
| UpdateAction::Send => {
// On error, the event stays scheduled, as recommended by
// MSC4140.
let event_id = self.send(delay_id, &event).await?;
self.finalize(
delay_id,
event,
DelayedEventOutcome::Sent(DelayedEventSent::new(event_id)),
)
.await;
Ok(())
},
| UpdateAction::Cancel => {
self.finalize(
delay_id,
event,
DelayedEventOutcome::Cancelled(DelayedEventCancelled::new()),
)
.await;
Ok(())
},
| _ => Err!(Request(InvalidParam("Unknown delayed event action."))),
};
}
match self.get_finalized(delay_id).await {
| Some(finalized) if finalized.event.user_id == user_id =>
if finalized.satisfies(&action) {
Ok(())
} else {
Err(Error::Request(
ErrorKind::Unknown,
"The delayed event has already been finalized with a different outcome."
.into(),
StatusCode::CONFLICT,
))
},
| _ => Err!(Request(NotFound("No delayed event with this ID was found."))),
}
}
/// Returns one of the user's delayed events, whether scheduled or
/// finalized.
pub async fn get(&self, user_id: &UserId, delay_id: &str) -> Result<DelayedEvent> {
if let Some(event) = self.get_scheduled(delay_id).await
&& event.user_id == user_id
{
return Ok(event.into_delayed_event(delay_id.to_owned()));
}
if let Some(finalized) = self.get_finalized(delay_id).await
&& finalized.event.user_id == user_id
{
return Ok(finalized.into_delayed_event(delay_id.to_owned()));
}
Err!(Request(NotFound("No delayed event with this ID was found.")))
}
/// Removes a user's scheduled delayed events without keeping them for
/// lookup, for account deactivation.
pub async fn remove_all_for_user(&self, user_id: &UserId) {
self.user_delay_ids(user_id)
.for_each(async |delay_id| {
let _lock = self.event_locks.lock(delay_id.as_str()).await;
self.db
.delayid_scheduleddelayedevent
.remove(delay_id.as_str());
self.db.useriddelayid.del((user_id, delay_id.as_str()));
})
.await;
}
/// Sends the delayed event if it is due, otherwise returns its send time.
/// Called by the worker, which records any error on the finalized event as
/// there is no client to return it to.
async fn send_if_due(&self, delay_id: &str) -> Option<SystemTime> {
let _lock = self.event_locks.lock(delay_id).await;
let event = self.get_scheduled(delay_id).await?;
let send_time = event.send_time();
if send_time > SystemTime::now() {
return Some(send_time);
}
let outcome = match self.send(delay_id, &event).await {
| Ok(event_id) => DelayedEventOutcome::Sent(DelayedEventSent::new(event_id)),
| Err(error) => {
debug_warn!(%delay_id, %error, "Failed to send delayed event");
let error = StandardErrorBody::new(error.kind(), error.message());
DelayedEventOutcome::Error(DelayedEventError::new(error))
},
};
self.finalize(delay_id, event, outcome).await;
None
}
/// Sends the delayed event into its room with the same checks as a normal
/// send, using the room state at the time of sending.
async fn send(&self, delay_id: &str, event: &ScheduledDelayedEvent) -> Result<OwnedEventId> {
if self.services.users.is_suspended(&event.user_id).await? {
return Err!(Request(UserSuspended(
"You cannot perform this action while suspended."
)));
}
let content = event.content.clone().into_json();
let redacts = (event.event_type == TimelineEventType::RoomRedaction)
.then(|| serde_json::from_str::<MaybeRedaction>(content.get()).ok())
.flatten()
.and_then(|redaction| redaction.redacts);
let mut unsigned = BTreeMap::new();
unsigned.insert("delay_id".to_owned(), delay_id.into());
let partial_pdu = PartialPdu {
event_type: event.event_type.clone(),
content,
state_key: event.state_key.clone().map(Into::into),
timestamp: event.timestamp,
sticky: event.sticky_duration_ms.map(sticky::object),
unsigned: Some(unsigned),
redacts,
};
let state_lock = self.services.state.mutex.lock(&event.room_id).await;
self.services
.timeline
.send_timeline_event(partial_pdu, &event.user_id, &event.room_id, &state_lock)
.await
}
/// Moves a scheduled delayed event to the finalized events, where it can
/// still be looked up until it is pruned.
async fn finalize(
&self,
delay_id: &str,
event: ScheduledDelayedEvent,
outcome: DelayedEventOutcome,
) {
let user_id = event.user_id.clone();
let finalized_ts = MilliSecondsSinceUnixEpoch::now();
self.db.useriddelayid.del((&user_id, delay_id));
self.db.delayid_scheduleddelayedevent.remove(delay_id);
self.db
.useridfinalizedtsdelayid
.put_raw((&user_id, u64::from(finalized_ts.get()), delay_id), []);
self.db.delayid_finalizeddelayedevent.raw_put(
delay_id,
Json(FinalizedDelayedEvent {
event,
finalized: FinalizedDelayedEventData::new(outcome, finalized_ts),
}),
);
self.limit_finalized(&user_id).await;
}
/// Removes the user's oldest finalized delayed events beyond
/// [`MAX_FINALIZED_PER_USER`].
async fn limit_finalized(&self, user_id: &UserId) {
let prefix = (user_id, Interfix);
let count = self
.db
.useridfinalizedtsdelayid
.keys_prefix_raw(&prefix)
.count()
.await;
self.db
.useridfinalizedtsdelayid
.keys_prefix(&prefix)
.ignore_err()
.take(count.saturating_sub(MAX_FINALIZED_PER_USER))
.ready_for_each(|(_, finalized_ts, delay_id): (Ignore, u64, &str)| {
self.remove_finalized(user_id, finalized_ts, delay_id);
})
.await;
}
fn remove_finalized(&self, user_id: &UserId, finalized_ts: u64, delay_id: &str) {
self.db
.useridfinalizedtsdelayid
.del((user_id, finalized_ts, delay_id));
self.db.delayid_finalizeddelayedevent.remove(delay_id);
}
/// Removes finalized delayed events older than [`FINALIZED_RETENTION`].
/// Called periodically by the worker.
async fn prune_finalized(&self) {
let Some(cutoff) = SystemTime::now()
.checked_sub(FINALIZED_RETENTION)
.and_then(MilliSecondsSinceUnixEpoch::from_system_time)
else {
return;
};
self.db
.delayid_finalizeddelayedevent
.stream::<'_, &str, FinalizedDelayedEvent>()
.ignore_err()
.ready_filter(|(_, event)| event.finalized.finalized_ts < cutoff)
.ready_for_each(|(delay_id, event)| {
let finalized_ts = u64::from(event.finalized.finalized_ts.get());
self.remove_finalized(&event.event.user_id, finalized_ts, delay_id);
})
.await;
}
async fn get_scheduled(&self, delay_id: &str) -> Option<ScheduledDelayedEvent> {
self.db
.delayid_scheduleddelayedevent
.get(delay_id)
.await
.deserialized()
.inspect_err(|e| {
if !e.is_not_found() {
error!(%delay_id, "Invalid scheduled delayed event in the database: {e}");
}
})
.ok()
}
async fn get_finalized(&self, delay_id: &str) -> Option<FinalizedDelayedEvent> {
self.db
.delayid_finalizeddelayedevent
.get(delay_id)
.await
.deserialized()
.inspect_err(|e| {
if !e.is_not_found() {
error!(%delay_id, "Invalid finalized delayed event in the database: {e}");
}
})
.ok()
}
/// Streams the delay IDs of the user's scheduled delayed events.
fn user_delay_ids<'a>(
&'a self,
user_id: &'a UserId,
) -> impl futures::Stream<Item = String> + Send + 'a {
self.db
.useriddelayid
.keys_prefix(&(user_id, Interfix))
.ignore_err()
.map(|(_, delay_id): (Ignore, &str)| delay_id.to_owned())
}
}
#[derive(Deserialize)]
struct MaybeRedaction {
redacts: Option<OwnedEventId>,
}
@@ -1,94 +0,0 @@
use std::{
cmp::Reverse,
collections::BinaryHeap,
sync::{Arc, atomic::Ordering},
time::{Duration, SystemTime},
};
use conduwuit::{Result, utils::stream::TryIgnore};
use futures::StreamExt;
use loole::Receiver;
use tokio::{
select,
time::{MissedTickBehavior, interval, sleep},
};
use super::{DELAY_ID_LENGTH, ScheduledDelayedEvent, Service};
const PRUNE_INTERVAL: Duration = Duration::from_hours(1);
pub(super) struct SubmissionQueue {
receiver: Receiver<(SystemTime, String)>,
interrupt: Receiver<()>,
queue: BinaryHeap<(Reverse<SystemTime>, String)>,
}
impl SubmissionQueue {
pub(super) fn new(receiver: Receiver<(SystemTime, String)>, interrupt: Receiver<()>) -> Self {
Self {
receiver,
interrupt,
queue: BinaryHeap::new(),
}
}
}
pub(super) async fn worker(service: &Arc<Service>) -> Result {
let mut queue = service
.submission_queue
.try_lock()
.expect("only one delayed events worker should be running");
let receiver = queue.receiver.clone();
let interrupt = queue.interrupt.clone();
let scheduled: Vec<_> = service
.db
.delayid_scheduleddelayedevent
.stream::<'_, &str, ScheduledDelayedEvent>()
.ignore_err()
.map(|(delay_id, event)| (Reverse(event.send_time()), delay_id.to_owned()))
.collect()
.await;
queue.queue.extend(scheduled);
let mut prune = interval(PRUNE_INTERVAL);
prune.set_missed_tick_behavior(MissedTickBehavior::Delay);
loop {
let mem_usage = queue
.queue
.len()
.saturating_mul(DELAY_ID_LENGTH.saturating_add(size_of::<SystemTime>()));
service.mem_usage.store(mem_usage, Ordering::Relaxed);
let next_due = async {
let (Reverse(time), _) = queue.queue.peek()?;
if let Ok(wait) = time.duration_since(SystemTime::now()) {
sleep(wait).await;
}
queue.queue.pop().map(|(_, delay_id)| delay_id)
};
// All of these are cancellation-safe
select! {
Some(delay_id) = next_due => {
// Sent in the background so one slow room doesn't hold up the others.
// Events that were restarted come back through the receiver.
let task_service = service.clone();
service.services.server.runtime().spawn(async move {
if let Some(time) = task_service.send_if_due(&delay_id).await {
task_service.submission_queue_sender.send((time, delay_id)).ok();
}
});
},
Ok((time, delay_id)) = receiver.recv_async() => {
queue.queue.push((Reverse(time), delay_id));
},
_ = prune.tick() => service.prune_finalized().await,
_ = interrupt.recv_async() => break,
}
}
Ok(())
}
+2 -1
View File
@@ -75,7 +75,8 @@ impl Service {
"lazy loading should be enabled by your options" "lazy loading should be enabled by your options"
); );
let include_redundant = ctx.options.is_some_and(Options::include_redundant_members); let include_redundant = cfg!(feature = "element_hacks")
|| ctx.options.is_some_and(Options::include_redundant_members);
let witness = self let witness = self
.witness(ctx, senders.iter().map(AsRef::as_ref)) .witness(ctx, senders.iter().map(AsRef::as_ref))
-2
View File
@@ -1,6 +1,5 @@
pub mod alias; pub mod alias;
pub mod auth_chain; pub mod auth_chain;
pub mod delayed_events;
pub mod directory; pub mod directory;
pub mod event_handler; pub mod event_handler;
pub mod lazy_loading; pub mod lazy_loading;
@@ -27,7 +26,6 @@ pub struct Service {
pub alias: Arc<alias::Service>, pub alias: Arc<alias::Service>,
pub auth_chain: Arc<auth_chain::Service>, pub auth_chain: Arc<auth_chain::Service>,
pub directory: Arc<directory::Service>, pub directory: Arc<directory::Service>,
pub delayed_events: Arc<delayed_events::Service>,
pub event_handler: Arc<event_handler::Service>, pub event_handler: Arc<event_handler::Service>,
pub lazy_loading: Arc<lazy_loading::Service>, pub lazy_loading: Arc<lazy_loading::Service>,
pub membership: Arc<membership::Service>, pub membership: Arc<membership::Service>,
+22 -35
View File
@@ -112,44 +112,31 @@ impl Service {
query: &'a RoomQuery<'a>, query: &'a RoomQuery<'a>,
sender_user: &'a UserId, sender_user: &'a UserId,
) -> Result<(usize, impl Stream<Item = PduEvent> + Send + 'a)> { ) -> Result<(usize, impl Stream<Item = PduEvent> + Send + 'a)> {
let (count, page) = if let Some(user_id) = query.user_id { let pdu_ids: Vec<_> = self.search_pdu_ids(query).await?.collect().await;
let filter = &query.criteria.filter;
self.search_pdu_ids(query)
.await?
.wide_filter_map(move |result_pdu_id: RawPduId| async move {
self.services
.timeline
.get_pdu_from_id(&result_pdu_id)
.await
.ok()
})
.ready_filter(|pdu| !pdu.is_redacted())
.ready_filter(move |pdu| filter.matches(pdu))
.wide_filter_map(move |pdu| async move {
self.services
.state_accessor
.user_can_see_event(user_id, &pdu.room_id_or_hash(), pdu.event_id())
.await
.then_some(pdu)
})
.ready_fold(
(0_usize, Vec::with_capacity(query.limit)),
|(mut count, mut page), pdu| {
if count >= query.skip && page.len() < query.limit {
page.push(pdu);
}
count = count.saturating_add(1);
(count, page)
},
)
.await
} else {
(0, Vec::new())
};
let pdus = page let filter = &query.criteria.filter;
let count = pdu_ids.len();
let pdus = pdu_ids
.into_iter() .into_iter()
.stream() .stream()
.wide_filter_map(move |result_pdu_id: RawPduId| async move {
self.services
.timeline
.get_pdu_from_id(&result_pdu_id)
.await
.ok()
})
.ready_filter(|pdu| !pdu.is_redacted())
.ready_filter(move |pdu| filter.matches(pdu))
.wide_filter_map(move |pdu| async move {
self.services
.state_accessor
.user_can_see_event(query.user_id?, pdu.room_id().unwrap(), pdu.event_id())
.await
.then_some(pdu)
})
.skip(query.skip)
.take(query.limit)
.wide_filter_map(async move |mut pdu| { .wide_filter_map(async move |mut pdu| {
let ctx = self let ctx = self
.services .services
+32 -32
View File
@@ -2,13 +2,13 @@
pub(crate) use conduwuit::{ pub(crate) use conduwuit::{
Err, Event, Result, err, Err, Event, Result, err,
matrix::pdu::{PartialPdu, UnsignedContext}, matrix::pdu::{PartialPdu, UnsignedContext, sticky},
trace, trace,
}; };
use ruma::{ use ruma::{
OwnedEventId, RoomId, UserId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, UserId,
events::{ events::{
AnyStateEventContent, AnyTimelineEvent, MessageLikeEventType, StateEventType, AnyStateEventContent, AnyTimelineEvent, StateEventType,
room::{ room::{
canonical_alias::RoomCanonicalAliasEventContent, canonical_alias::RoomCanonicalAliasEventContent,
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent}, history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
@@ -16,6 +16,7 @@ use ruma::{
member::RoomMemberEventContent, member::RoomMemberEventContent,
server_acl::RoomServerAclEventContent, server_acl::RoomServerAclEventContent,
}, },
sticky::StickyDurationMs,
}, },
serde::Raw, serde::Raw,
}; };
@@ -23,43 +24,42 @@ use ruma::{
use crate::rooms::state::RoomMutexGuard; use crate::rooms::state::RoomMutexGuard;
impl super::Service { impl super::Service {
/// Checks that a local user may send an event, then sends it. #[allow(clippy::too_many_arguments)]
pub async fn send_timeline_event( pub async fn send_state_event_for_key(
&self, &self,
mut partial_pdu: PartialPdu,
sender: &UserId, sender: &UserId,
room_id: &RoomId, room_id: &RoomId,
state_lock: &RoomMutexGuard, state_lock: &RoomMutexGuard,
event_type: &StateEventType,
content: &Raw<AnyStateEventContent>,
state_key: &str,
sticky_duration_ms: Option<StickyDurationMs>,
timestamp: Option<MilliSecondsSinceUnixEpoch>,
) -> Result<OwnedEventId> { ) -> Result<OwnedEventId> {
if let Some(state_key) = &partial_pdu.state_key { let content: Raw<AnyStateEventContent> = content.clone();
let content = Raw::<AnyStateEventContent>::from_json(partial_pdu.content); self.assert_allowed_to_send_state_event(room_id, event_type, state_key, &content)
self.assert_allowed_to_send_state_event( .await?;
room_id,
&partial_pdu.event_type.to_string().into(), let content = serde_json::from_str(content.json().get())
state_key, .map_err(|e| err!(Request(BadJson("Invalid JSON body: {e}"))))?;
&content,
let event_id = self
.build_and_append_pdu(
PartialPdu {
event_type: event_type.to_string().into(),
content,
sticky: sticky_duration_ms.map(sticky::object),
state_key: Some(state_key.into()),
timestamp,
..Default::default()
},
sender,
Some(room_id),
state_lock,
) )
.await?; .await?;
partial_pdu.content = content.into_json();
} else {
self.assert_allowed_to_send_message_event(
&partial_pdu.event_type.to_string().into(),
)?;
}
self.build_and_append_pdu(partial_pdu, sender, Some(room_id), state_lock) Ok(event_id)
.await
}
fn assert_allowed_to_send_message_event(&self, event_type: &MessageLikeEventType) -> Result {
// Forbid m.room.encrypted if encryption is disabled
if *event_type == MessageLikeEventType::RoomEncrypted
&& !self.services.config.allow_encryption
{
return Err!(Request(Forbidden("Encryption has been disabled")));
}
Ok(())
} }
async fn assert_allowed_to_send_state_event( async fn assert_allowed_to_send_state_event(
+33 -104
View File
@@ -522,6 +522,13 @@ impl Service {
let device_changes = let device_changes =
self.select_edus_device_changes(server_name, batch, &max_edu_count, &events_len); self.select_edus_device_changes(server_name, batch, &max_edu_count, &events_len);
let receipts: OptionFuture<_> = self
.server
.config
.allow_outgoing_read_receipts
.then(|| self.select_edus_receipts(server_name, batch, &max_edu_count))
.into();
let presence: OptionFuture<_> = self let presence: OptionFuture<_> = self
.server .server
.config .config
@@ -529,20 +536,11 @@ impl Service {
.then(|| self.select_edus_presence(server_name, batch, &max_edu_count)) .then(|| self.select_edus_presence(server_name, batch, &max_edu_count))
.into(); .into();
let (device_changes, presence) = join!(device_changes, presence); let (device_changes, receipts, presence) = join!(device_changes, receipts, presence);
let mut events = device_changes; let mut events = device_changes;
events.extend(presence.into_iter().flatten()); events.extend(presence.into_iter().flatten());
events.extend(receipts.into_iter().flatten());
// leave a slot for the queued event, but always allow one receipt EDU
let edu_limit = (EDU_LIMIT - 1).saturating_sub(events.len()).max(1);
if self.server.config.allow_outgoing_read_receipts {
// must be selected last, as it may lower max_edu_count
events.extend(
self.select_edus_receipts(server_name, batch, &max_edu_count, edu_limit)
.await,
);
}
// TODO(nex): some EDUs like typing need flattening // TODO(nex): some EDUs like typing need flattening
@@ -618,11 +616,9 @@ impl Service {
server_name: &ServerName, server_name: &ServerName,
since: (u64, u64), since: (u64, u64),
max_edu_count: &AtomicU64, max_edu_count: &AtomicU64,
edu_limit: usize, ) -> Option<EduBuf> {
) -> EduVec {
let num = AtomicUsize::new(0); let num = AtomicUsize::new(0);
let deferred = AtomicU64::new(u64::MAX); let receipts: BTreeMap<OwnedRoomId, ReceiptMap> = self
let rooms: Vec<_> = self
.services .services
.state_cache .state_cache
.server_rooms(server_name) .server_rooms(server_name)
@@ -631,54 +627,33 @@ impl Service {
return None; return None;
} }
let maps = self let receipt_map = self
.select_edus_receipts_room( .select_edus_receipts_room(&room_id, since, max_edu_count, &num)
&room_id,
since,
max_edu_count,
&num,
edu_limit,
&deferred,
)
.await; .await;
(!maps.is_empty()).then_some((room_id, maps)) (!receipt_map.read.is_empty()).then_some((room_id, receipt_map))
}) })
.collect() .collect()
.await; .await;
// the next transaction starts at the first receipt that did not fit if receipts.is_empty() {
max_edu_count return None;
.fetch_min(deferred.load(Ordering::Relaxed).saturating_sub(1), Ordering::Relaxed);
let mut contents = Vec::<BTreeMap<OwnedRoomId, ReceiptMap>>::new();
for (room_id, maps) in rooms {
for (index, read) in maps.into_iter().enumerate() {
if index == contents.len() {
contents.push(BTreeMap::new());
}
contents[index].insert(room_id.clone(), ReceiptMap::new(read));
}
} }
contents let receipt_content = Edu::Receipt(ReceiptContent::new(receipts));
.into_iter()
.map(|content| {
let edu = Edu::Receipt(ReceiptContent::new(content));
let mut buf = EduBuf::new(); let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &edu) serde_json::to_writer(&mut buf, &receipt_content)
.expect("Failed to serialize Receipt EDU to JSON vec"); .expect("Failed to serialize Receipt EDU to JSON vec");
buf
}) Some(buf)
.collect()
} }
/// Look for read receipts in this room /// Look for read receipts in this room
#[tracing::instrument( #[tracing::instrument(
name = "receipts", name = "receipts",
level = "trace", level = "trace",
skip(self, since, max_edu_count, num, deferred) skip(self, since, max_edu_count, num)
)] )]
async fn select_edus_receipts_room( async fn select_edus_receipts_room(
&self, &self,
@@ -686,16 +661,14 @@ impl Service {
since: (u64, u64), since: (u64, u64),
max_edu_count: &AtomicU64, max_edu_count: &AtomicU64,
num: &AtomicUsize, num: &AtomicUsize,
edu_limit: usize, ) -> ReceiptMap {
deferred: &AtomicU64,
) -> Vec<BTreeMap<OwnedUserId, ReceiptData>> {
let receipts = self let receipts = self
.services .services
.read_receipt .read_receipt
.readreceipts_since(room_id, Some(since.0)); .readreceipts_since(room_id, Some(since.0));
pin_mut!(receipts); pin_mut!(receipts);
let mut maps = Vec::new(); let mut read = BTreeMap::<OwnedUserId, ReceiptData>::new();
while let Some((user_id, count, read_receipt)) = receipts.next().await { while let Some((user_id, count, read_receipt)) = receipts.next().await {
if count > since.1 { if count > since.1 {
break; break;
@@ -731,20 +704,14 @@ impl Service {
let receipt_data = ReceiptData::new(receipt, vec![event_id]); let receipt_data = ReceiptData::new(receipt, vec![event_id]);
let Some(index) = add_receipt(&mut maps, user_id, receipt_data, edu_limit) else { if read.insert(user_id, receipt_data).is_none() {
deferred.fetch_min(count, Ordering::Relaxed); if num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT {
break; break;
}; }
// only a user's first receipt counts towards the limit
if index == 0
&& num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT
{
break;
} }
} }
maps ReceiptMap::new(read)
} }
/// Look for presence /// Look for presence
@@ -1003,8 +970,6 @@ impl Service {
} }
} }
let mut first_push_error = None;
for pdu in pdus { for pdu in pdus {
// Redacted events are not notification targets (we don't send push // Redacted events are not notification targets (we don't send push
// for them) // for them)
@@ -1030,27 +995,15 @@ impl Service {
.try_into() .try_into()
.expect("notification count can't go that high"); .expect("notification count can't go that high");
let response = self let _response = self
.services .services
.pusher .pusher
.send_push_notice(&user_id, unread, &pusher, rules_for_user, &pdu) .send_push_notice(&user_id, unread, &pusher, rules_for_user, &pdu)
.await .await
.map_err(|e| (Destination::Push(user_id.clone(), pushkey.clone()), Box::new(e))); .map_err(|e| (Destination::Push(user_id.clone(), pushkey.clone()), e));
if let Err(err) = response {
error!(event = %pdu.event_id, pusher = %pusher.app_display_name, "Failed to deliver push notification: {err:?}");
if first_push_error.is_none() {
first_push_error = Some(err);
}
}
} }
if let Some(err) = first_push_error { Ok(Destination::Push(user_id, pushkey))
Err(err)
} else {
Ok(Destination::Push(user_id, pushkey))
}
} }
async fn send_events_dest_federation( async fn send_events_dest_federation(
@@ -1157,27 +1110,3 @@ impl Service {
) )
} }
} }
/// Adds the receipt to the first map without one from the user and returns
/// that map's index, or `None` if all `limit` maps have one.
fn add_receipt(
maps: &mut Vec<BTreeMap<OwnedUserId, ReceiptData>>,
user_id: OwnedUserId,
receipt: ReceiptData,
limit: usize,
) -> Option<usize> {
let index = maps
.iter()
.position(|map| !map.contains_key(&user_id))
.unwrap_or(maps.len());
if index >= limit {
return None;
}
if index == maps.len() {
maps.push(BTreeMap::new());
}
maps[index].insert(user_id, receipt);
Some(index)
}
+3 -22
View File
@@ -1,19 +1,14 @@
use std::{collections::BTreeMap, iter::once}; use std::iter::once;
use conduwuit::{ use conduwuit::{
Error, Error,
matrix::{PartialPdu, pdu::sticky}, matrix::{PartialPdu, pdu::sticky},
}; };
use futures::{StreamExt, stream::FuturesUnordered}; use futures::{StreamExt, stream::FuturesUnordered};
use ruma::{ use ruma::{RoomId, UserId, events::sticky::StickyDurationMs, server_name};
RoomId, UserId,
api::federation::transactions::edu::ReceiptData,
events::{receipt::Receipt, sticky::StickyDurationMs},
server_name, user_id,
};
use serde_json::{json, value::to_raw_value}; use serde_json::{json, value::to_raw_value};
use super::{CurTransactionStatus, TransactionStatus, add_receipt}; use super::{CurTransactionStatus, TransactionStatus};
use crate::{ use crate::{
sending::{Destination, EduBuf, SendingEvent}, sending::{Destination, EduBuf, SendingEvent},
test_utils::{test_services, test_services_with}, test_utils::{test_services, test_services_with},
@@ -201,17 +196,3 @@ async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled(
assert_eq!(active_after_startup, 0); assert_eq!(active_after_startup, 0);
assert_eq!(sending_after_startup, 0); assert_eq!(sending_after_startup, 0);
} }
#[test]
fn add_receipt_separates_receipts_of_one_user() {
let alice = user_id!("@alice:example.org");
let bob = user_id!("@bob:example.org");
let receipt = || ReceiptData::new(Receipt::default(), vec![]);
let mut maps = Vec::new();
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), Some(0));
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), Some(1));
assert_eq!(add_receipt(&mut maps, bob.to_owned(), receipt(), 2), Some(0));
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), None);
assert_eq!(maps.iter().map(BTreeMap::len).collect::<Vec<_>>(), [2, 1]);
}
-1
View File
@@ -94,7 +94,6 @@ impl Services {
rooms: rooms::Service { rooms: rooms::Service {
alias: build!(rooms::alias::Service), alias: build!(rooms::alias::Service),
auth_chain: build!(rooms::auth_chain::Service), auth_chain: build!(rooms::auth_chain::Service),
delayed_events: build!(rooms::delayed_events::Service),
directory: build!(rooms::directory::Service), directory: build!(rooms::directory::Service),
event_handler: build!(rooms::event_handler::Service), event_handler: build!(rooms::event_handler::Service),
lazy_loading: build!(rooms::lazy_loading::Service), lazy_loading: build!(rooms::lazy_loading::Service),
-6
View File
@@ -466,12 +466,6 @@ impl super::Service {
// Mark user as deactivated // Mark user as deactivated
self.db.userid_deactivated.insert(user_id, ""); self.db.userid_deactivated.insert(user_id, "");
// Delayed events must not be sent after deactivation
self.services
.delayed_events
.remove_all_for_user(user_id)
.await;
// TODO: Unhook 3PID // TODO: Unhook 3PID
Ok(()) Ok(())
} }
-3
View File
@@ -57,7 +57,6 @@ struct Services {
alias: Dep<alias::Service>, alias: Dep<alias::Service>,
appservice: Dep<appservice::Service>, appservice: Dep<appservice::Service>,
config: Dep<config::Service>, config: Dep<config::Service>,
delayed_events: Dep<rooms::delayed_events::Service>,
firstrun: Dep<firstrun::Service>, firstrun: Dep<firstrun::Service>,
globals: Dep<globals::Service>, globals: Dep<globals::Service>,
membership: Dep<membership::Service>, membership: Dep<membership::Service>,
@@ -111,8 +110,6 @@ impl crate::Service for Service {
alias: args.depend::<alias::Service>("rooms::alias"), alias: args.depend::<alias::Service>("rooms::alias"),
appservice: args.depend::<appservice::Service>("appservice"), appservice: args.depend::<appservice::Service>("appservice"),
config: args.depend::<config::Service>("config"), config: args.depend::<config::Service>("config"),
delayed_events: args
.depend::<rooms::delayed_events::Service>("rooms::delayed_events"),
firstrun: args.depend::<firstrun::Service>("firstrun"), firstrun: args.depend::<firstrun::Service>("firstrun"),
globals: args.depend::<globals::Service>("globals"), globals: args.depend::<globals::Service>("globals"),
membership: args.depend::<membership::Service>("rooms::membership"), membership: args.depend::<membership::Service>("rooms::membership"),