Compare commits

...
Author SHA1 Message Date
Jacob Taylor 8ebf0a11fa feat: Rendezvous-y 2026-11-23 15:03:06 -08:00
Jacob Taylor 45cefde919 feat: Continuwuity Notarizes the Notary 2026-11-23 15:02:41 -08:00
Erwan Leboucher 17b05974e2 fix(federation): Send a read receipt for each thread 2026-11-23 14:44:44 -08:00
Jacob Taylor 38ac8f5e13 fix: Complete ripping hardened malloc out 2026-11-23 14:44:44 -08:00
Jacob Taylor b5a4f85ef6 chore: No Auth Media, No UnAuth Profiles 2026-11-23 14:44:44 -08:00
Jacob Taylor 84037431b9 Chore: Revert "chore(deps): Upgrade rocksdb and jemalloc", and add cargo.lock changes clippy discovered
This reverts commit 1af92add88.
This reverts commit 779374bb54.

chore(deps): update rust crate syn to v3.0.10

chore: Fix Clippy
2026-11-23 14:44:44 -08:00
Jacob Taylor 0930738140 feat: Enable converged 6g at the edge in continuwuity 2026-11-23 14:43:30 -08:00
Jacob Taylor 40fba31500 chore: Commit basic QoDana config for local QA usage 2026-11-23 14:43:30 -08:00
Jacob Taylor dde062d857 fix: Delete silly 2026-11-23 14:43:30 -08:00
Jacob Taylor 0c50835932 chore: Fix some clippy lints 2026-11-23 14:43:30 -08:00
Jacob Taylor de844be77f bump the number of allowed immutable memtables by 1, to allow for greater flood protection
this should probably not be applied if you have rocksdb_atomic_flush = false (the default)
2026-11-23 14:43:30 -08:00
Jade Ellis 2c79a67130 feat: Warn when the system allocator is used 2026-11-23 22:32:35 +00:00
Jade Ellis 8b9000cdf4 chore: Add changelog fragment 2026-11-23 22:32:35 +00:00
Jade Ellis 370fa43b5a chore: Reshuffle allocator features 2026-11-23 22:32:35 +00:00
Jade Ellis bf5f77a94a fix(knock): Align knock state handling with Matrix spec
Updates state_cache on MembershipState::Knock, avoids stale local state
checks and holding state_lock across federation, drops invalid
knock_room_state entries without failing post-send_knock, allows
re-knocking, and honours via servers.
2026-11-23 21:54:33 +00:00
Jade Ellis 506c4a0376 fix(leave): Rescind remote knocks over federation
Remote knocks no longer populate local room state, so leaving a room
we are not in must go through remote_leave_room even when knocked.
2026-11-23 21:54:33 +00:00
Jade Ellis d9b94b98ad refactor(invite): Extract per-event partial membership validation
Allows callers like remote knocking to filter invalid stripped state
events individually per MSC4311 instead of failing the entire request.
2026-11-23 21:54:33 +00:00
timedout 26cdaeec99 fix: Re-use validate_partial_membership_state 2026-11-23 21:54:32 +00:00
timedout 73fbdd6056 style: Improve logging for knocking 2026-11-23 21:54:32 +00:00
timedout d591385bed fix: Stop blowing up in send_knock 2026-11-23 21:54:32 +00:00
timedout cbb1b70c99 fix: Invert server identity check 2026-11-23 21:54:32 +00:00
timedout 748603549c chore: Add news fragment 2026-11-23 21:54:32 +00:00
timedout 6115693193 fix: Modernise knocking helpers 2026-11-23 21:54:31 +00:00
Jade Ellis e9974043f2 ci: Add towncrier to pre-commit checks 2026-11-23 21:10:20 +00:00
timedout 415b3dd671 chore: Add changelog fragment 2026-11-23 19:23:24 +00:00
Jade Ellis 3774f3e7e4 chore: Advertise client-server v1.6 support 2026-11-23 19:20:02 +00:00
Henry-Hiles 2408ded7b4 feat: Support stable MSC4143 RTC transports endpoint 2026-11-23 13:14:39 -05:00
Henry-Hiles a3cc73bc08 fix(nix): Add libclang to devshell 2026-11-23 17:27:55 +00:00
Ginger 20bc28cd2f chore: News fragment 2026-11-23 15:30:36 +00:00
Ginger 9877464857 feat: Request profile scope from OIDC providers by default 2026-11-23 15:30:36 +00:00
Ginger a6e051fa3b chore: News fragment 2026-11-23 10:10:19 -05:00
Ginger cdda575d4a fix: Return 403 instead of 404 when UIAA is disabled 2026-11-23 10:09:08 -05:00
Renovate Bot c82aba6f5a chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.257.9 2026-11-23 05:05:22 +00:00
Jade Ellis 14739ffaf7 chore: Remove redundant Mxc import in download_image 2026-11-22 17:57:49 +00:00
Jade Ellis 733c25ce5a chore: Update Cargo.lock 2026-11-22 17:57:49 +00:00
Jade Ellis 8c4a2d0ce9 chore: Downgrade per-request URL preview route logs to debug 2026-11-22 17:57:49 +00:00
Jade Ellis c0f69f23dd fix: Resolve relative OpenGraph asset URLs and avoid cloning HTML body 2026-11-22 17:57:49 +00:00
Jade Ellis c6b87fb033 fix: Check CIDR range and HTTP status when downloading preview media 2026-11-22 17:57:49 +00:00
Jade Ellis 635fccf11f fix: Populate image_size when downloading URL preview images 2026-11-22 17:57:49 +00:00
Jade Ellis def987f935 fix: Gate webpage usage and update disabled url_preview stubs 2026-11-22 17:57:49 +00:00
Jade Ellis 137805693e refactor: Use mime::Mime instead of lettre ContentType for URL previews 2026-11-22 17:57:49 +00:00
timedout bd7450f52a fix: Remove attachment metadata when the attachment has no URL 2026-11-22 17:57:49 +00:00
timedout 66be5efeec fix: Properly select correct properties, fixup unit test 2026-11-22 17:57:49 +00:00
timedout 33ed0a2e75 feat: Automatically populate UrlPreviewData, correctly populate media fields 2026-11-22 17:57:49 +00:00
timedout 16f18f8516 feat: Make url preview logs more informative 2026-11-22 17:57:49 +00:00
timedout 4710c227db chore: Add @silversys to refactor TODO 2026-11-22 17:57:49 +00:00
timedout f5bd8d0a7c chore: Add newsfrag 2026-11-22 17:57:49 +00:00
timedout 5ad6c35f0b fix: Default to asset type when not at top-level 2026-11-22 17:57:49 +00:00
timedout 17af942cbf feat: Support most other specified opengraph tags 2026-11-22 17:57:49 +00:00
timedout 9f7fb54bd4 fix: Don't fail entire preview requests when auxiliary requests fail 2026-11-22 17:57:49 +00:00
Jade Ellis 21f3f0c1eb perf(service/sending): Seek past destination prefixes in queued_destinations 2026-11-22 17:21:50 +00:00
Jade Ellis 613bb1b2a8 fix(service/sending): Avoid spawning restarted workers during shutdown 2026-11-22 17:21:50 +00:00
Jade Ellis a0d9e71eac fix(service/sending): Use Flush to wake queued destinations 2026-11-22 17:21:50 +00:00
Jade Ellis d477417909 fix(service/sending): Preserve sticky events during restarted worker netburst 2026-11-22 17:21:50 +00:00
Jade Ellis cd7910009a fix(service/sending): Apply local backoff to panicked federation transactions 2026-11-22 17:21:50 +00:00
Erwan Leboucher 793c06c17b fix(service/sending): Address review feedback on sender supervision
Signed-off-by: Erwan Leboucher <erwanleboucher@gmail.com>
2026-11-22 17:21:50 +00:00
Erwan Leboucher cf45dcffbb fix(service/sending): Restart crashed sender workers and resend queued backlogs
Signed-off-by: Erwan Leboucher <erwanleboucher@gmail.com>
2026-11-22 17:21:50 +00:00
Erwan Leboucher 919fea9b97 fix: Index remote events by origin_server_ts 2026-11-22 02:02:37 +00:00
Erwan Leboucher 5687847fe3 style: Address review nits on timestamp index 2026-11-22 02:02:37 +00:00
Erwan Leboucher 251086670f feat: Add timestamp to event endpoint backed by a timestamp index 2026-11-22 02:02:37 +00:00
Jade Ellis 3379badbd4 fix(service): Prevent potential corruption in state diffs
This fixes a non-atomicity issue. Also fixes incorrect
calculation of a buffer size that would result in
reallocation.
2026-11-22 01:02:59 +00:00
Jade Ellis cc28a01e49 fix(core): Fix BoolExt::or short-circuiting
This would mean that or would return false when one of the
inputs was true.

Also fix double futures in type signatures
2026-11-21 21:38:55 +00:00
Renovate Bot 95392ccc46 chore(deps): update rust-non-major 2026-11-21 20:14:56 +00:00
Julian Anderson f3289f150c ci(docs): Set Rspress config values based on prod/preview status 2026-11-21 14:15:26 -05:00
Julian Anderson cbc089df1b ci(docs): Expire preview doc deployments after 14 days 2026-11-21 13:27:50 -05:00
Julian Anderson 0b738e835b ci(docs): Replace preview docs workflow with Grebedoc 2026-11-21 13:27:47 -05:00
83 changed files with 2933 additions and 1279 deletions

No files matched your search

+14 -6
View File
@@ -49,6 +49,8 @@ jobs:
run: npm ci
- name: Build Rspress documentation
env:
SITE_PATH: ${{ github.ref != 'refs/heads/main' && format('/pr/{0}/', '${{ forgejo.event.number }}') || '/' }}
run: npm run docs:build
- name: Install Wrangler
@@ -62,10 +64,16 @@ jobs:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
command: pages deploy ./doc_build --branch="main" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}"
- name: Deploy to Cloudflare Pages (Preview)
if: github.ref != 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != ''
uses: https://github.com/cloudflare/wrangler-action@953926a2e2182532811c01a25e53647d93bf07c0 # v4
- name: Deploy to Grebedoc (Preview)
if: github.ref != 'refs/heads/main'
uses: actions/git-pages@v2
with:
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
command: pages deploy ./doc_build --branch="${{ github.head_ref || github.ref_name }}" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}"
site: https://preview.continuwuity.org
path: "pr/${{ forgejo.event.number }}"
server: grebedoc.dev
token: ${{ forgejo.token }}
source: doc_build/
strict: true
pretty-urls: true
expires: 14
comment: ${{ forgejo.sha }}
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
name: Renovate
runs-on: ubuntu-latest
container:
image: ghcr.io/renovatebot/renovate:44.241.0@sha256:22d22b4ca7d768b5b469309d34379783bf91cd94a58faecf1cd0f4528a65d21c
image: ghcr.io/renovatebot/renovate:44.257.9@sha256:578179439fceea89646662dd583b27efdad8d1429e0cbd90681c40dde068589e
options: --tmpfs /tmp:exec
steps:
- name: Checkout
+6 -1
View File
@@ -36,6 +36,11 @@ repos:
hooks:
- id: committed
- repo: https://github.com/twisted/towncrier
rev: 26.9.0
hooks:
- id: towncrier-check
- repo: local
hooks:
- id: cargo-fmt
@@ -51,7 +56,7 @@ repos:
hooks:
- id: cargo-clippy
name: cargo clippy
entry: cargo clippy -- -D warnings
entry: cargo clippy --
language: system
pass_filenames: false
types: [ rust ]
Generated
+99 -65
View File
@@ -485,19 +485,20 @@ dependencies = [
[[package]]
name = "bindgen"
version = "0.73.2"
version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"bitflags",
"cexpr",
"clang-sys",
"itertools 0.13.0",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex",
"syn 3.0.10",
"shlex 1.3.0",
"syn 2.0.119",
]
[[package]]
@@ -671,7 +672,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
dependencies = [
"semver",
"serde",
"toml 1.2.1+spec-1.1.0",
"toml 1.2.2+spec-1.1.0",
]
[[package]]
@@ -683,7 +684,7 @@ dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
"shlex 2.0.1",
]
[[package]]
@@ -764,9 +765,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.6.8"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a"
checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c"
dependencies = [
"clap_builder",
"clap_derive",
@@ -784,9 +785,9 @@ dependencies = [
[[package]]
name = "clap_derive"
version = "4.6.8"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a"
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
dependencies = [
"heck",
"proc-macro2",
@@ -873,9 +874,13 @@ dependencies = [
name = "conduwuit"
version = "26.11.0-alpha.2"
dependencies = [
"aws-lc-rs",
"clap",
"conduwuit_admin",
"conduwuit_api",
"conduwuit_build_metadata",
"conduwuit_core",
"conduwuit_database",
"conduwuit_macros",
"conduwuit_router",
"conduwuit_service",
@@ -883,6 +888,7 @@ dependencies = [
"const-str",
"ctor",
"dtor",
"log",
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry-prometheus",
@@ -890,10 +896,13 @@ dependencies = [
"opentelemetry_sdk",
"parking_lot",
"prometheus",
"reqwest 0.13.5",
"rustls",
"sentry",
"sentry-tower",
"sentry-tracing",
"tokio",
"tokio-metrics",
"tracing",
"tracing-flame",
"tracing-journald",
@@ -1029,7 +1038,7 @@ dependencies = [
"tikv-jemallocator",
"tokio",
"tokio-metrics",
"toml 1.2.1+spec-1.1.0",
"toml 1.2.2+spec-1.1.0",
"tracing",
"tracing-core",
"tracing-subscriber",
@@ -1127,13 +1136,13 @@ dependencies = [
"log",
"loole",
"lru-cache",
"mime",
"nonzero_ext",
"openidconnect",
"opentelemetry",
"p256 0.14.0",
"rand 0.10.4",
"regex",
"reqwest 0.12.28",
"reqwest 0.13.5",
"resolvematrix",
"ruma",
@@ -2104,9 +2113,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -2711,10 +2720,10 @@ dependencies = [
"hyper",
"hyper-util",
"rustls",
"rustls-native-certs",
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
]
[[package]]
@@ -2988,6 +2997,15 @@ dependencies = [
"serde",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.14.0"
@@ -3258,9 +3276,9 @@ dependencies = [
[[package]]
name = "libz-sys"
version = "1.1.32"
version = "1.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69965d2409bff8c8cea3829009fff66a86f05a0570656552ef70f616e8e4bd85"
checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9"
dependencies = [
"cc",
"pkg-config",
@@ -4179,6 +4197,12 @@ dependencies = [
"phc",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pear"
version = "0.2.9"
@@ -4842,8 +4866,8 @@ dependencies = [
"log",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"serde",
"serde_json",
@@ -4858,6 +4882,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots",
]
[[package]]
@@ -4985,8 +5010,8 @@ dependencies = [
[[package]]
name = "ruma"
version = "0.17.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"assign",
"js_int",
@@ -5004,8 +5029,8 @@ dependencies = [
[[package]]
name = "ruma-appservice-api"
version = "0.17.1"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"http",
"js_int",
@@ -5017,8 +5042,8 @@ dependencies = [
[[package]]
name = "ruma-client-api"
version = "0.25.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.26.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"as_variant",
"assign",
@@ -5039,8 +5064,8 @@ dependencies = [
[[package]]
name = "ruma-common"
version = "0.20.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.21.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"as_variant",
"base64 0.23.1",
@@ -5072,8 +5097,8 @@ dependencies = [
[[package]]
name = "ruma-events"
version = "0.35.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.36.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"as_variant",
"indexmap 2.14.2",
@@ -5093,8 +5118,8 @@ dependencies = [
[[package]]
name = "ruma-federation-api"
version = "0.16.1"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.17.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"bytes",
"http",
@@ -5115,8 +5140,8 @@ dependencies = [
[[package]]
name = "ruma-identifiers-validation"
version = "0.14.0"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.14.1"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"js_int",
"thiserror 2.0.21",
@@ -5124,8 +5149,8 @@ dependencies = [
[[package]]
name = "ruma-macros"
version = "0.20.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.20.3"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"as_variant",
"cfg-if",
@@ -5135,13 +5160,13 @@ dependencies = [
"ruma-identifiers-validation",
"serde",
"syn 3.0.10",
"toml 1.2.1+spec-1.1.0",
"toml 1.2.2+spec-1.1.0",
]
[[package]]
name = "ruma-push-gateway-api"
version = "0.16.0"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.17.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"js_int",
"ruma-common",
@@ -5152,8 +5177,8 @@ dependencies = [
[[package]]
name = "ruma-signatures"
version = "0.22.1"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.23.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"base64 0.23.1",
"ed25519-dalek",
@@ -5169,8 +5194,8 @@ dependencies = [
[[package]]
name = "ruma-state-res"
version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.19.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"js_int",
"ruma-common",
@@ -5196,8 +5221,8 @@ dependencies = [
[[package]]
name = "rust-librocksdb-sys"
version = "0.49.0+11.12.0"
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b"
version = "0.45.1+11.1.1"
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
dependencies = [
"bindgen",
"bzip2-sys",
@@ -5207,15 +5232,14 @@ dependencies = [
"libz-sys",
"lz4-sys",
"pkg-config",
"rustflags",
"tikv-jemalloc-sys",
"zstd-sys",
]
[[package]]
name = "rust-rocksdb"
version = "0.54.0"
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b"
version = "0.49.1"
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
dependencies = [
"libc",
"parking_lot",
@@ -5243,12 +5267,6 @@ dependencies = [
"semver",
]
[[package]]
name = "rustflags"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a39e0e9135d7a7208ee80aa4e3e4b88f0f5ad7be92153ed70686c38a03db2e63"
[[package]]
name = "rustix"
version = "1.1.6"
@@ -5641,7 +5659,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9"
dependencies = [
"annotate-snippets",
"base64 0.23.1",
"base64 0.22.1",
"encoding_rs_io",
"granit-parser",
"nohash-hasher",
@@ -5876,6 +5894,12 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "shlex"
version = "2.0.1"
@@ -6235,17 +6259,18 @@ dependencies = [
[[package]]
name = "tikv-jemalloc-ctl"
version = "0.7.0"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
version = "0.6.1"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
dependencies = [
"libc",
"paste",
"tikv-jemalloc-sys",
]
[[package]]
name = "tikv-jemalloc-sys"
version = "0.7.0+5.4.0-0-g7a34f18502e7b222724097cdcd499b437d189acc"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
dependencies = [
"cc",
"libc",
@@ -6253,8 +6278,8 @@ dependencies = [
[[package]]
name = "tikv-jemallocator"
version = "0.7.0"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
version = "0.6.1"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
dependencies = [
"libc",
"tikv-jemalloc-sys",
@@ -6395,9 +6420,9 @@ dependencies = [
[[package]]
name = "toml"
version = "1.2.1+spec-1.1.0"
version = "1.2.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b"
dependencies = [
"indexmap 2.14.2",
"serde_core",
@@ -6454,9 +6479,9 @@ dependencies = [
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31"
dependencies = [
"winnow 1.0.5",
]
@@ -6853,9 +6878,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
@@ -7112,6 +7137,15 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webpki-roots"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "weezl"
version = "0.1.12"
+8 -17
View File
@@ -166,15 +166,6 @@ features = [
"form",
]
# Needed for as long as openidconnect is on an outdated reqwest
[workspace.dependencies.reqwest_0_12]
package = "reqwest"
version = "0.12"
default-features = false
features = [
"rustls-tls-native-roots-no-provider",
]
[workspace.dependencies.serde]
version = "1.0.229"
default-features = false
@@ -357,7 +348,7 @@ version = "1.1.1"
# Used for matrix spec type definitions and helpers
[workspace.dependencies.ruma]
git = "https://github.com/ruma/ruma.git"
rev = "472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
rev = "decdf3f6c5160e1db595d4edb4d65d5de935e13c"
features = [
"appservice-api-c",
"client-api",
@@ -370,7 +361,6 @@ features = [
"compat-upload-signatures",
"compat-optional-txn-pdus",
"compat-get-3pids",
"unstable-msc2867",
"unstable-msc2870",
"unstable-msc3814",
"unstable-msc3245",
@@ -404,7 +394,7 @@ features = [
[workspace.dependencies.rust-rocksdb]
git = "https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1"
rev = "85ded20348e3dab902c239967075795e9c6d101b"
rev = "0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
default-features = false
features = [
"multi-threaded-cf",
@@ -424,8 +414,6 @@ default-features = false
[workspace.dependencies.openidconnect]
version = "4.1.0"
default-features = false
features = ["reqwest"]
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
[workspace.dependencies.opentelemetry]
@@ -488,7 +476,7 @@ version = "0.49.5"
# jemalloc usage
[workspace.dependencies.tikv-jemalloc-sys]
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
rev = "46e7821917b06636cdb5b203d312799970eaea92"
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
default-features = false
features = [
"background_threads_runtime_support",
@@ -496,7 +484,7 @@ features = [
]
[workspace.dependencies.tikv-jemallocator]
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
rev = "46e7821917b06636cdb5b203d312799970eaea92"
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
default-features = false
features = [
"background_threads_runtime_support",
@@ -504,7 +492,7 @@ features = [
]
[workspace.dependencies.tikv-jemalloc-ctl]
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
rev = "46e7821917b06636cdb5b203d312799970eaea92"
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
default-features = false
features = ["use_std"]
@@ -589,6 +577,9 @@ version = "0.10.4"
default-features = false
features = ["std"]
[workspace.dependencies.mime]
version = "0.3.18"
[workspace.dependencies.nonzero_ext]
version = "0.3.0"
@@ -0,0 +1 @@
Fixed read receipts for all but one of a user's threads not being sent over federation. Contributed by @eleboucher.
@@ -0,0 +1 @@
Added support for the stable MatrixRTC transports discovery endpoint (`GET /_matrix/client/v1/rtc/transports`) from the accepted MSC4143, advertised via the `org.matrix.msc4143.stable` unstable feature. The unstable endpoint remains available. Contributed by @Henry-Hiles (QuadRadical).
@@ -0,0 +1 @@
Added the `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event` endpoint as per MSC3030, letting clients find the event closest to a given timestamp. Contributed by @eleboucher.
+1
View File
@@ -0,0 +1 @@
Added support for acting as a trusted server, meaning the `trusted_servers` list can consist of servers that are either Synapse OR continuwuity.
+1
View File
@@ -0,0 +1 @@
URL previews no longer completely fail if downloading auxiliary content (images/videos/audio) fails. Contributed by @nex.
+1
View File
@@ -0,0 +1 @@
Modernised the room knocking helper functions to make them match the behaviour of our room join helpers, which are safer and more efficient. This also fixes a bug that caused an error when knocking on rooms not local to the server. Contributed by @nex.
+1
View File
@@ -0,0 +1 @@
Continuwuity will now request the `profile` OIDC scope from identity providers by default to improve compatibility with identity providers that require it to access users' profile claims, as recommended by the OIDC specification. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Attempting to start a UIAA session on a homeserver with UIAA disabled will now return `403 M_UNAUTHORIZED` instead of `404 M_UNSUPPORTED`. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Advertise support for Matrix v1.6. Contributed by @jade
+1
View File
@@ -0,0 +1 @@
Moved the `jemalloc` feature out of `standard` (and `full`) into `default` so builders can more easily swap allocators. Builders using `--no-default-features` with the `full` or `standard` feature should now explicitly select an allocator (either `jemalloc` or `mimalloc`). Contributed by @Jade
+1
View File
@@ -0,0 +1 @@
Fix outgoing federation stalling after a sender worker panics. Contributed by @eleboucher.
+22 -19
View File
@@ -813,18 +813,6 @@
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
#forget_forced_upon_leave = false
# Set this to true to require authentication when looking up user profiles
# through this server.
#
# By default this is false, allowing tools such as matrix.to to access
# profiles of users on this server and on other servers.
# Setting this to true will block those tools, and may block automated
# crawlers from scraping users' profiles, although it will not block
# other homeservers from accessing users' profiles.
#
# env: CONTINUWUITY_REQUIRE_AUTH_FOR_PROFILE_REQUESTS
#require_auth_for_profile_requests = false
# Set this to true to require authentication to create a rendezvous
# session. Rendezvous sessions are used for QR code login.
#
@@ -1043,10 +1031,7 @@
# (trusted key notary servers), as well as serve as trusted servers for
# other operations like backfill and event fetching.
#
# Currently, continuwuity doesn't support inbound key requests, so
# this list should only contain other Synapse servers.
#
# example: ["matrix.org", "starstruck.systems"]
# example: ["continuwuity.org", "matrix.org"]
#
# It is possible to restrict which signing keys trusted servers are
# allowed to sign responses with. Without configuring this, all responses
@@ -1084,7 +1069,7 @@
# is discouraged for performance and reliability reasons.
#
# env: CONTINUWUITY_TRUSTED_SERVERS
#trusted_servers = ["matrix.org"]
#trusted_servers = ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
# Whether to prioritise trusted server lookups over origin server lookups.
#
@@ -2582,10 +2567,12 @@
# Additional scopes Continuwuity should request from the IDP. This may be
# necessary to access certain claims. Continuwuity always requests the
# `openid` scope.
# `openid` scope, regardless of the contents of this option,
# and will also request the `profile` scope by default if this option is
# not set.
#
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES
#additional_scopes = []
#additional_scopes = ["profile"]
# Additional trusted audiences that Continuwuity will accept in the `aud`
# claim of the OIDC token returned by the IDP. If your identity
@@ -2781,6 +2768,22 @@
# env: CONTINUWUITY_EXPERIMENTS__MSC4494
#msc4494 = false
# MSC4556: Notary request limits
#
# Creates a new key notary server route that has stricter limits on how
# many signing keys can be requested in one query, to avoid a resource
# exhaustion exploit vector in the existing key notary endpoint.
#
# Continuwuity mitigates the exploit vector in the old notary endpoint
# anyway, so you do not need to enable this to be protected.
#
# Requires that remote servers support this MSC before it does anything.
#
# https://github.com/matrix-org/matrix-spec-proposals/pull/4556
#
# env: CONTINUWUITY_EXPERIMENTS__MSC4556
#msc4556 = false
# MSC4560: Stripped state requests over federation
#
# Implements a more efficient way for servers to acquire and serve
+3
View File
@@ -71,6 +71,9 @@ Names below are as they appear in Prometheus. OTLP uses the dotted OpenTelemetry
| `continuwuity_sender_events_total` | counter | `destination`, `kind`, `outcome` | PDUs and EDUs sent in outgoing transactions |
| `continuwuity_sender_events_queued_total` | counter | `destination`, `kind` | PDUs and EDUs queued for sending |
| `continuwuity_sender_queue_depth` | gauge | | Messages waiting for the sender workers |
| `continuwuity_sender_requests` | gauge | `state` | Estimated outgoing requests stored as `queued` or `active` (in flight) |
| `continuwuity_sender_workers` | gauge | | Running sender workers; below the configured count means a worker is restarting |
| `continuwuity_sender_panics_total` | counter | `scope` | Panics caught in a single outgoing `transaction` or a whole sender `worker` |
| `continuwuity_users` | gauge | `origin` | Known `local` users, including deactivated, and `remote` users |
| `continuwuity_invites_total` | counter | `direction`, `destination`, `outcome` | Invites sent by local users or received over federation |
| `continuwuity_media_write_size_bytes` | histogram | `origin` | Media files written, from local uploads or cached remote media |
+1
View File
@@ -26,6 +26,7 @@
LD_LIBRARY_PATH = lib.makeLibraryPath (
[
pkgs.stdenv.cc.cc.lib
pkgs.llvmPackages.libclang.lib
]
++ lib.optionals pkgs.stdenv.hostPlatform.isLinux [
pkgs.liburing
+18 -38
View File
@@ -11,7 +11,7 @@
"devDependencies": {
"@rspress/core": "^2.0.0",
"@rspress/plugin-client-redirects": "^2.0.0",
"@rspress/plugin-sitemap": "^2.0.0",
"@types/node": "^26.6.6",
"typescript": "^7.0.0"
}
},
@@ -230,9 +230,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -247,9 +244,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -264,9 +258,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -281,9 +272,6 @@
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -298,9 +286,6 @@
"riscv64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -315,9 +300,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -332,9 +314,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -349,9 +328,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -524,19 +500,6 @@
"@rspress/core": "^2.1.0-beta.2"
}
},
"node_modules/@rspress/plugin-sitemap": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.4.tgz",
"integrity": "sha512-TObDTXgBKFAHEWEth47aehQSYtFfpIkqM4w14a0hUbPLkbu2AZ2cKnMzFTKK+W6I/3LN54scvfGYTL5CPQsDXw==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"peerDependencies": {
"@rspress/core": "^2.1.0-beta.2"
}
},
"node_modules/@rspress/shared": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.4.tgz",
@@ -770,6 +733,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "26.6.6",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
@@ -3842,6 +3815,13 @@
"@typescript/typescript-win32-x64": "7.0.2"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/unhead": {
"version": "2.1.17",
"resolved": "https://registry.npmjs.org/unhead/-/unhead-2.1.17.tgz",
+2 -2
View File
@@ -20,11 +20,11 @@
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"type": "module",
"devDependencies": {
"@rspress/core": "^2.0.0",
"@rspress/plugin-client-redirects": "^2.0.0",
"@rspress/plugin-sitemap": "^2.0.0",
"@types/node": "^26.6.6",
"typescript": "^7.0.0"
}
}
+46
View File
@@ -0,0 +1,46 @@
#-------------------------------------------------------------------------------#
# 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
+8 -9
View File
@@ -1,10 +1,13 @@
import { defineConfig } from '@rspress/core';
import { pluginSitemap } from '@rspress/plugin-sitemap';
import { pluginClientRedirects } from '@rspress/plugin-client-redirects';
const sitePath: string = process.env.SITE_PATH ?? '/';
export default defineConfig({
root: 'docs',
title: 'Continuwuity',
siteOrigin: sitePath != "/" ? "https://preview.continuwuity.org" : "https://continuwuity.org",
base: sitePath,
description: 'A community-driven Matrix homeserver',
icon: '/assets/logo.svg',
logo: {
@@ -75,14 +78,10 @@ export default defineConfig({
lastUpdated: true,
enableContentAnimation: true,
enableAppearanceAnimation: false,
footer: {
},
footer: {},
},
plugins: [pluginSitemap({
siteUrl: 'https://continuwuity.org', // TODO: Set automatically in build pipeline
}),
pluginClientRedirects({
plugins: [pluginClientRedirects({
redirects: [{
from: '^/config_reference$',
to: '/reference/config'
@@ -105,8 +104,8 @@ export default defineConfig({
from: "^/source(|_code)$",
to: "https://forgejo.ellis.link/continuwuation/continuwuity",
}, {
from: "^/(CONTRIBUTING.md|contributing)$",
to: "/development/contributing"
from: "^/(CONTRIBUTING.md|contributing)$",
to: "/development/contributing"
}
]
})],
+3 -1
View File
@@ -2,7 +2,7 @@ use std::time::Duration;
use axum::extract::State;
use conduwuit::{
Err, Result, err,
Err, Result, debug, err,
utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize},
};
use conduwuit_core::error;
@@ -219,10 +219,12 @@ pub(crate) async fn get_media_preview_route(
)));
}
debug!("Fetching a URL preview for {url} on behalf of {sender_user}");
let preview = services
.media
.get_url_preview(&url)
.await
.inspect(|_| debug!(user=%sender_user, %url, "Finished fetching a URL preview"))
.map_err(|error| {
err!(Request(Unknown(
debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}")
+238 -474
View File
@@ -1,9 +1,10 @@
use std::{borrow::Borrow, collections::HashMap, sync::Arc};
use std::collections::{HashMap, hash_map::Entry};
use axum::extract::State;
use conduwuit::{
Err, Result, debug, debug_info, debug_warn, err, info,
Err, EventTypeExt, Result, debug, debug_warn, err, info,
matrix::{
StateKey,
event::gen_event_id,
pdu::{PartialPdu, PduEvent},
},
@@ -15,28 +16,25 @@ use conduwuit::{
use futures::{FutureExt, StreamExt};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName,
OwnedUserId, RoomId, UserId,
api::{client::knock::knock_room, federation},
OwnedUserId, RoomId, RoomVersionId, UserId,
api::{
client::knock::knock_room,
error::{ErrorKind, IncompatibleRoomVersionErrorData},
federation::{self, membership::RawStrippedState},
},
canonical_json::to_canonical_value,
events::{
StateEventType,
room::{
join_rules::{AllowRule, JoinRule},
member::{MembershipState, RoomMemberEventContent},
},
room::member::{MembershipState, RoomMemberEventContent},
},
};
use service::{
Services,
rooms::{
membership::validate_remote_member_event_stub,
state::RoomMutexGuard,
state_compressor::{CompressedState, HashSetCompressStateEvent},
},
rooms::{membership::validate_remote_member_event_stub, state::RoomMutexGuard},
};
use super::banned_room_check;
use crate::Ruma;
use crate::{Ruma, server::validate_partial_membership_event};
/// # `POST /_matrix/client/*/knock/{roomIdOrAlias}`
///
@@ -58,30 +56,42 @@ pub(crate) async fn knock_room_route(
.await?;
let mut servers = body.via.clone();
servers.extend(
services
.rooms
.state_cache
.servers_invite_via(&room_id)
.collect::<Vec<_>>()
.await,
);
if servers.is_empty() {
debug!("No via servers provided for knock, injecting some.");
servers.extend(
services
.rooms
.state_cache
.servers_invite_via(&room_id)
.collect::<Vec<_>>()
.await,
);
servers.extend(
services
let invite_state = services
.rooms
.state_cache
.invite_state(sender_user, &room_id)
.await
.unwrap_or_default()
.iter()
.filter_map(|event| event.get_field("sender").ok().flatten())
.filter_map(|sender: &str| UserId::parse(sender).ok())
.map(|user| user.server_name().to_owned()),
);
.unwrap_or_default();
let knock_state = services
.rooms
.state_cache
.knock_state(sender_user, &room_id)
.await
.unwrap_or_default();
if let Some(server) = room_id.server_name() {
servers.push(server.to_owned());
servers.extend(
invite_state
.iter()
.chain(knock_state.iter())
.filter_map(|event| event.get_field("sender").ok().flatten())
.filter_map(|sender: &str| UserId::parse(sender).ok())
.map(|user| user.server_name().to_owned()),
);
if let Some(server) = room_id.server_name() {
servers.push(server.to_owned());
}
}
servers.sort_unstable();
@@ -103,20 +113,28 @@ pub(crate) async fn knock_room_route(
let addl_via_servers = services.rooms.state_cache.servers_invite_via(&room_id);
let addl_state_servers = services
let addl_invite_state = services
.rooms
.state_cache
.invite_state(sender_user, &room_id)
.await
.unwrap_or_default();
let addl_knock_state = services
.rooms
.state_cache
.knock_state(sender_user, &room_id)
.await
.unwrap_or_default();
let mut addl_servers: Vec<_> = addl_state_servers
let mut addl_servers: Vec<_> = addl_invite_state
.iter()
.chain(addl_knock_state.iter())
.map(|event| event.get_field("sender"))
.filter_map(FlatOk::flat_ok)
.map(|user: OwnedUserId| user.server_name().to_owned())
.stream()
.chain(addl_via_servers)
.chain(body.via.iter().cloned().stream())
.collect()
.await;
@@ -143,165 +161,69 @@ async fn knock_room_by_id_helper(
) -> Result<knock_room::v3::Response> {
let state_lock = services.rooms.state.mutex.lock(room_id).await;
if services
.rooms
.state_cache
.is_invited(sender_user, room_id)
.await
{
debug_warn!("{sender_user} is already invited in {room_id} but attempted to knock");
return Err!(Request(Forbidden(
"You cannot knock on a room you are already invited/accepted to."
)));
}
if services
.rooms
.state_cache
.is_joined(sender_user, room_id)
.await
{
debug_warn!("{sender_user} is already joined in {room_id} but attempted to knock");
return Err!(Request(Forbidden("You cannot knock on a room you are already joined in.")));
}
if services
.rooms
.state_cache
.is_knocked(sender_user, room_id)
.await
{
debug_warn!("{sender_user} is already knocked in {room_id}");
return Ok(knock_room::v3::Response::new(room_id.into()));
}
if let Ok(membership) = services
.rooms
.state_accessor
.get_member(room_id, sender_user)
.await
{
if membership.membership == MembershipState::Ban {
debug_warn!("{sender_user} is banned from {room_id} but attempted to knock");
return Err!(Request(Forbidden("You cannot knock on a room you are banned from.")));
}
}
// For knock_restricted rooms, check if the user meets the restricted
// conditions If they do, attempt to join instead of knock
// This is not mentioned in the spec, but should be allowable (we're allowed
// to auto-join invites to knocked rooms)
let join_rule = services.rooms.state_accessor.get_join_rules(room_id).await;
if let JoinRule::KnockRestricted(restricted) = &join_rule {
let restriction_rooms: Vec<_> = restricted
.allow
.iter()
.filter_map(|a| match a {
| AllowRule::RoomMembership(r) => Some(&r.room_id),
| _ => None,
})
.collect();
// Check if the user is in any of the allowed rooms
let mut user_meets_restrictions = false;
for restriction_room_id in &restriction_rooms {
if services
.rooms
.state_cache
.is_joined(sender_user, restriction_room_id)
.await
{
user_meets_restrictions = true;
break;
}
}
// If the user meets the restrictions, try joining instead
if user_meets_restrictions {
debug_info!(
"{sender_user} meets the restricted criteria in knock_restricted room \
{room_id}, attempting to join instead of knock"
);
// For this case, we need to drop the state lock and get a new one
// in join_room_by_id_helper We need to release the lock here and
// let join_room_by_id_helper acquire it again
drop(state_lock);
match services
.rooms
.membership
.join_room(sender_user, room_id, reason.clone(), servers)
.await
{
| Ok(_) => return Ok(knock_room::v3::Response::new(room_id.to_owned())),
| Err(e) => {
debug_warn!(
"Failed to convert knock to join for {sender_user} in {room_id}: {e:?}"
);
// Get a new state lock for the remaining knock logic
let new_state_lock = services.rooms.state.mutex.lock(room_id).await;
let server_in_room = services
.rooms
.state_cache
.server_in_room(services.globals.server_name(), room_id)
.await;
let local_knock = server_in_room
|| servers.is_empty()
|| (servers.len() == 1 && services.globals.server_is_ours(&servers[0]));
if local_knock {
knock_room_helper_local(
services,
sender_user,
room_id,
reason,
servers,
new_state_lock,
)
.boxed()
.await?;
} else {
knock_room_helper_remote(
services,
sender_user,
room_id,
reason,
servers,
new_state_lock,
)
.boxed()
.await?;
}
return Ok(knock_room::v3::Response::new(room_id.to_owned()));
},
}
}
} else if !matches!(join_rule, JoinRule::Knock | JoinRule::KnockRestricted(_)) {
debug_warn!(
"{sender_user} attempted to knock on room {room_id} but its join rule is \
{join_rule:?}, not knock or knock_restricted"
);
}
let server_in_room = services
.rooms
.state_cache
.server_in_room(services.globals.server_name(), room_id)
.await;
let local_knock = server_in_room
|| servers.is_empty()
|| (servers.len() == 1 && services.globals.server_is_ours(&servers[0]));
// Only check our known membership if we're already in the room.
if server_in_room {
if services
.rooms
.state_cache
.is_invited(sender_user, room_id)
.await
{
debug_warn!("{sender_user} is already invited in {room_id} but attempted to knock");
return Err!(Request(Forbidden(
"You cannot knock on a room you are already invited/accepted to."
)));
}
if local_knock {
knock_room_helper_local(services, sender_user, room_id, reason, servers, state_lock)
if services
.rooms
.state_cache
.is_joined(sender_user, room_id)
.await
{
debug_warn!("{sender_user} is already joined in {room_id} but attempted to knock");
return Err!(Request(Forbidden(
"You cannot knock on a room you are already joined in."
)));
}
if let Ok(membership) = services
.rooms
.state_accessor
.get_member(room_id, sender_user)
.await
&& membership.membership == MembershipState::Ban
{
debug_warn!("{sender_user} is banned from {room_id} but attempted to knock");
return Err!(Request(Forbidden("You cannot knock on a room you are banned from.")));
}
// Local knocks can't fail unless the room is corrupted, so we don't
// fall back to remote knocks like we do with remote joins.
knock_room_helper_local(services, sender_user, room_id, reason, state_lock)
.boxed()
.await?;
} else {
knock_room_helper_remote(services, sender_user, room_id, reason, servers, state_lock)
drop(state_lock);
let remote_servers: Vec<_> = servers
.iter()
.filter(|sn| !services.globals.server_is_ours(sn))
.cloned()
.collect();
if remote_servers.is_empty() {
return Err!(Request(NotFound(
"Room {room_id} not found and no remote servers were provided to discover it"
)));
}
knock_room_helper_remote(services, sender_user, room_id, reason, &remote_servers)
.boxed()
.await?;
}
@@ -309,16 +231,14 @@ async fn knock_room_by_id_helper(
Ok(knock_room::v3::Response::new(room_id.to_owned()))
}
#[tracing::instrument(name = "local", skip(services, reason, state_lock))]
async fn knock_room_helper_local(
services: &Services,
sender_user: &UserId,
room_id: &RoomId,
reason: Option<String>,
servers: &[OwnedServerName],
state_lock: RoomMutexGuard,
) -> Result {
debug_info!("We can knock locally");
let room_version = services.rooms.state.get_room_version(room_id).await?;
let room_version_rules = room_version
.rules()
@@ -331,10 +251,9 @@ async fn knock_room_helper_local(
let mut content = RoomMemberEventContent::new(MembershipState::Knock);
content.displayname = services.users.displayname(sender_user).await.ok();
content.avatar_url = services.users.avatar_url(sender_user).await.ok();
content.reason.clone_from(&reason.clone());
content.reason = reason;
// Try normal knock first
let Err(error) = services
services
.rooms
.timeline
.build_and_append_pdu(
@@ -344,147 +263,24 @@ async fn knock_room_helper_local(
&state_lock,
)
.await
else {
return Ok(());
};
if servers.is_empty() || (servers.len() == 1 && services.globals.server_is_ours(&servers[0]))
{
return Err(error);
}
let (make_knock_response, remote_server) =
make_knock_request(services, sender_user, room_id, servers).await?;
info!("make_knock finished");
let room_version = make_knock_response.room_version;
let room_version_rules = room_version
.rules()
.expect("room version should have defined rules");
if !services.server.supported_room_version(&room_version) {
return Err!(BadServerResponse("Remote room version {room_version} is not supported"));
}
let mut knock_event_stub = serde_json::from_str::<CanonicalJsonObject>(
make_knock_response.event.get(),
)
.map_err(|e| {
err!(BadServerResponse("Invalid make_knock event json received from server: {e:?}"))
})?;
validate_remote_member_event_stub(
&MembershipState::Knock,
sender_user,
room_id,
&knock_event_stub,
)?;
knock_event_stub.insert(
"origin".to_owned(),
CanonicalJsonValue::String(services.globals.server_name().as_str().to_owned()),
);
knock_event_stub.insert(
"origin_server_ts".to_owned(),
CanonicalJsonValue::Integer(
utils::millis_since_unix_epoch()
.try_into()
.expect("Timestamp is valid js_int value"),
),
);
knock_event_stub.insert(
"content".to_owned(),
to_canonical_value(content).expect("event is valid, we just created it"),
);
// In order to create a compatible ref hash (EventID) the `hashes` field
// needs to be present
services
.server_keys
.hash_and_sign_event(&mut knock_event_stub, &room_version_rules)?;
// Generate event id
let event_id = gen_event_id(&knock_event_stub, &room_version_rules)?;
// Add event_id
knock_event_stub
.insert("event_id".to_owned(), CanonicalJsonValue::String(event_id.clone().into()));
// It has enough fields to be called a proper event now
let knock_event = knock_event_stub;
info!("Asking {remote_server} for send_knock in room {room_id}");
let send_knock_request = federation::membership::create_knock_event::v1::Request::new(
room_id.to_owned(),
event_id.clone(),
services
.sending
.convert_to_outgoing_federation_event(knock_event.clone())
.await,
);
services
.sending
.send_federation_request(&remote_server, send_knock_request)
.await?;
info!("send_knock finished");
services
.rooms
.short
.get_or_create_shortroomid(room_id)
.await;
info!("Parsing knock event");
let parsed_knock_pdu = PduEvent::from_id_val(&event_id, knock_event.clone())
.map_err(|e| err!(BadServerResponse("Invalid knock event PDU: {e:?}")))?;
info!("Updating membership locally to knock state with provided stripped state events");
// TODO: this call does not appear to do anything because
// `update_membership` doesn't call `mark_as_knock`. investigate further,
// ideally with the aim of removing this call entirely -- Ginger thinks
// `update_membership` should only be called from `force_state` and
// `append_pdu`.
services
.rooms
.state_cache
.update_membership(room_id, sender_user, &parsed_knock_pdu, false)
.await?;
info!("Appending room knock event locally");
services
.rooms
.timeline
.progress_extremities(&parsed_knock_pdu)
.await?;
services
.rooms
.timeline
.append_pdu(&parsed_knock_pdu, knock_event, room_id)
.await;
Ok(())
.map(|_| ())
}
#[tracing::instrument(name = "remote", skip(services, reason, servers))]
async fn knock_room_helper_remote(
services: &Services,
sender_user: &UserId,
room_id: &RoomId,
reason: Option<String>,
servers: &[OwnedServerName],
state_lock: RoomMutexGuard,
) -> Result {
info!("Knocking {room_id} over federation.");
info!(via=?servers, "Knocking on {room_id} over federation.");
let (make_knock_response, remote_server) =
let (mut stub, room_version, remote_server) =
make_knock_request(services, sender_user, room_id, servers).await?;
info!("make_knock finished");
info!(%remote_server, "make_knock finished");
let room_version = make_knock_response.room_version;
let room_version_rules = room_version
.rules()
.expect("room version should have defined rules");
@@ -493,16 +289,7 @@ async fn knock_room_helper_remote(
return Err!(BadServerResponse("Remote room version {room_version} is not supported"));
}
let mut knock_event_stub: CanonicalJsonObject =
serde_json::from_str(make_knock_response.event.get()).map_err(|e| {
err!(BadServerResponse("Invalid make_knock event json received from server: {e:?}"))
})?;
knock_event_stub.insert(
"origin".to_owned(),
CanonicalJsonValue::String(services.globals.server_name().as_str().to_owned()),
);
knock_event_stub.insert(
stub.insert(
"origin_server_ts".to_owned(),
CanonicalJsonValue::Integer(
utils::millis_since_unix_epoch()
@@ -516,7 +303,7 @@ async fn knock_room_helper_remote(
knock_content.avatar_url = services.users.avatar_url(sender_user).await.ok();
knock_content.reason = reason;
knock_event_stub.insert(
stub.insert(
"content".to_owned(),
to_canonical_value(knock_content).expect("event is valid, we just created it"),
);
@@ -525,17 +312,15 @@ async fn knock_room_helper_remote(
// needs to be present
services
.server_keys
.hash_and_sign_event(&mut knock_event_stub, &room_version_rules)?;
.hash_and_sign_event(&mut stub, &room_version_rules)?;
// Generate event id
let event_id = gen_event_id(&knock_event_stub, &room_version_rules)?;
let event_id = gen_event_id(&stub, &room_version_rules)?;
// Add event_id
knock_event_stub
.insert("event_id".to_owned(), CanonicalJsonValue::String(event_id.clone().into()));
// It has enough fields to be called a proper event now
let knock_event = knock_event_stub;
// Just verify that this event isn't hilariously malformed before we sent it
// off.
debug!(?stub, "Parsing knock event");
PduEvent::from_id_val(&event_id, stub.clone())
.map_err(|e| err!(BadServerResponse("Invalid knock event PDU: {e:?}")))?;
info!("Asking {remote_server} for send_knock in room {room_id}");
let request = federation::membership::create_knock_event::v1::Request::new(
@@ -543,7 +328,7 @@ async fn knock_room_helper_remote(
event_id.clone(),
services
.sending
.convert_to_outgoing_federation_event(knock_event.clone())
.convert_to_outgoing_federation_event(stub.clone())
.await,
);
@@ -554,126 +339,95 @@ async fn knock_room_helper_remote(
info!("send_knock finished");
info!("Validating send_knock response");
services
.rooms
.short
.get_or_create_shortroomid(room_id)
.await;
let mut state: HashMap<(StateEventType, StateKey), CanonicalJsonObject> =
HashMap::with_capacity(send_knock_response.knock_room_state.len().saturating_add(1));
let mut create_event: Option<(OwnedEventId, CanonicalJsonObject)> = None;
info!("Parsing knock event");
let parsed_knock_pdu = PduEvent::from_id_val(&event_id, knock_event.clone())
.map_err(|e| err!(BadServerResponse("Invalid knock event PDU: {e:?}")))?;
info!("Going through send_knock response knock state events");
let state = send_knock_response
.knock_room_state
.iter()
.map(|event| {
#[allow(deprecated)]
let raw_value = match event {
| federation::membership::RawStrippedState::Stripped(raw_state) =>
&raw_state.clone().into_json(),
| federation::membership::RawStrippedState::Pdu(raw_value) => raw_value,
| _ => panic!("unknown raw stripped state type"),
};
serde_json::from_str::<CanonicalJsonObject>(raw_value.get())
})
.filter_map(Result::ok);
let mut state_map: HashMap<u64, OwnedEventId> = HashMap::new();
for mut event in state {
let Some(state_key) = event.get("state_key") else {
debug_warn!("send_knock stripped state event missing state_key: {event:?}");
continue;
};
let Some(event_type) = event.get("type") else {
debug_warn!("send_knock stripped state event missing event type: {event:?}");
continue;
for (idx, event) in send_knock_response.knock_room_state.iter().enumerate() {
let (state_event_id, key, state_event_json) = match validate_partial_membership_event(
services,
event,
&room_version_rules,
room_id,
idx,
)
.await
{
| Ok(res) => res,
| Err(e) => {
debug_warn!(%idx, "Dropping invalid event from knock_room_state: {e}");
continue;
},
};
let Ok(state_key) = serde_json::from_value::<String>(state_key.clone().into()) else {
debug_warn!("send_knock stripped state event has invalid state_key: {event:?}");
continue;
};
let Ok(event_type) = serde_json::from_value::<StateEventType>(event_type.clone().into())
else {
debug_warn!("send_knock stripped state event has invalid event type: {event:?}");
continue;
};
let event_id = gen_event_id(&event, &room_version_rules)?;
let shortstatekey = services
.rooms
.short
.get_or_create_shortstatekey(&event_type, &state_key)
.await;
event.insert("event_id".into(), CanonicalJsonValue::String(event_id.to_string()));
services.rooms.outlier.add_pdu_outlier(&event_id, &event);
state_map.insert(shortstatekey, event_id.clone());
match state.entry(key) {
| Entry::Occupied(entry) => {
debug_warn!(
key=?entry.key(),
"Dropping duplicate state event from knock_room_state"
);
},
| Entry::Vacant(entry) => {
if entry.key().0 == StateEventType::RoomCreate {
create_event = Some((state_event_id, state_event_json.clone()));
}
entry.insert(state_event_json);
},
}
}
info!("Compressing state from send_knock");
let compressed: CompressedState = services
.rooms
.state_compressor
.compress_state_events(state_map.iter().map(|(ssk, eid)| (ssk, eid.borrow())))
.collect()
.await;
if let Some((create_event_id, create_event_json)) = &create_event {
state.retain(|key, event_json| {
if let Err(e) = service::rooms::event_handler::Service::pdu_format_check_1(
event_json,
&room_version_rules,
create_event_id,
) {
debug_warn!(
?key,
"Dropping event from knock_room_state violating room event format: {e}"
);
return false;
}
true
});
debug!("Saving compressed state");
let HashSetCompressStateEvent {
shortstatehash: statehash_before_knock,
added,
removed,
} = services
.rooms
.state_compressor
.save_state(room_id, Arc::new(compressed))
.await?;
// Much like when receiving an invite over federation, if we're in this
// room we'll receive the knock PDU over /send. Otherwise, we need to
// add it as an outlier. Since this function isn't a fallback when local
// knocks fail, we can do this unconditionally.
services
.rooms
.outlier
.add_pdu_outlier(create_event_id, create_event_json);
}
debug!("Forcing state for new room");
services
.rooms
.state
.force_state(room_id, statehash_before_knock, added, removed, &state_lock)
.await?;
state.insert(StateEventType::RoomMember.with_state_key(sender_user.as_str()), stub);
let statehash_after_knock = services
.rooms
.state
.append_to_state(&parsed_knock_pdu, room_id)
.await?;
let knocked_state = state
.into_values()
.filter_map(|event_json| serde_json::value::to_raw_value(&event_json).ok())
.map(RawStrippedState::Pdu)
.collect();
info!("Updating membership locally to knock state with provided stripped state events");
// TODO: see TODO on the other call to `update_membership`
info!("Saving knock data");
services
.rooms
.state_cache
.update_membership(room_id, sender_user, &parsed_knock_pdu, false)
.await?;
info!("Appending room knock event locally");
.mark_as_knocked(sender_user, room_id, knocked_state);
services
.rooms
.timeline
.progress_extremities(&parsed_knock_pdu)
.await?;
services
.rooms
.timeline
.append_pdu(&parsed_knock_pdu, knock_event, room_id)
.state_cache
.update_joined_count(room_id)
.await;
info!("Setting final room state for new room");
// We set the room state after inserting the pdu, so that we never have a
// moment in time where events in the current room state do not exist
services
.rooms
.state
.set_room_state(room_id, statehash_after_knock, &state_lock);
services.sync.wake(sender_user).await;
Ok(())
}
@@ -683,18 +437,13 @@ async fn make_knock_request(
sender_user: &UserId,
room_id: &RoomId,
servers: &[OwnedServerName],
) -> Result<(federation::membership::prepare_knock_event::v1::Response, OwnedServerName)> {
let mut make_knock_response_and_server =
Err!(BadServerResponse("No server available to assist in knocking."));
let mut make_knock_counter: usize = 0;
for remote_server in servers {
) -> Result<(CanonicalJsonObject, RoomVersionId, OwnedServerName)> {
for (idx, remote_server) in servers.iter().enumerate() {
if services.globals.server_is_ours(remote_server) {
continue;
}
info!("Asking {remote_server} for make_knock ({make_knock_counter})");
info!("Asking {remote_server} for make_knock ({})", idx.saturating_add(1));
let mut request = federation::membership::prepare_knock_event::v1::Request::new(
room_id.to_owned(),
@@ -708,36 +457,51 @@ async fn make_knock_request(
.await;
trace!("make_knock response: {make_knock_response:?}");
make_knock_counter = make_knock_counter.saturating_add(1);
if let Ok(r) = &make_knock_response {
if let Err(e) = validate_remote_member_event_stub(
&MembershipState::Knock,
sender_user,
room_id,
&to_canonical_object(&r.event)?,
) {
warn!("make_knock response from {remote_server} failed validation: {e}");
continue;
}
}
make_knock_response_and_server = make_knock_response.map(|r| (r, remote_server.clone()));
if make_knock_response_and_server.is_ok() {
break;
}
if make_knock_counter > 40 {
warn!(
"50 servers failed to provide valid make_knock response, assuming no server can \
assist in knocking."
);
make_knock_response_and_server =
Err!(BadServerResponse("No server available to assist in knocking."));
return make_knock_response_and_server;
match make_knock_response
.and_then(|r| {
to_canonical_object(&r.event)
.map(|o| (o, r.room_version))
.map_err(Into::into)
})
.and_then(|(stub, room_version)| {
validate_remote_member_event_stub(
&MembershipState::Knock,
sender_user,
room_id,
&stub,
)
.map(|()| (stub, room_version))
}) {
| Ok((evt, room_version)) =>
return Ok((evt, room_version, remote_server.to_owned())),
| Err(e) => match e.kind() {
| ErrorKind::IncompatibleRoomVersion(IncompatibleRoomVersionErrorData {
room_version,
..
}) => {
warn!(
"{remote_server} reports the room we are trying to knock on is \
v{room_version}, which we do not support."
);
return Err(e);
},
| ErrorKind::Forbidden => {
warn!("{remote_server} refuses to let us knock: {e}.");
return Err(e);
},
| ErrorKind::NotFound => {
info!(
"{remote_server} does not know about {room_id}: {e}. Will continue \
trying."
);
},
| _ => {
info!("{remote_server} failed to make_knock: {e}. Will continue trying.");
},
},
}
}
make_knock_response_and_server
info!("All {} servers were unable to assist in knocking {room_id} :(", servers.len());
Err!(BadServerResponse("No server available to assist in knocking."))
}
+2 -8
View File
@@ -88,19 +88,13 @@ pub async fn leave_room(
.server_in_room(services.globals.server_name(), room_id)
.eq(&false);
let not_knocked = services
.rooms
.state_cache
.is_knocked(user_id, room_id)
.eq(&false);
pin_mut!(is_banned, is_disabled);
/*
there are three possible cases when leaving a room:
1. the room is banned or disabled, so we're not federating with it.
2. nobody on the homeserver is in the room, which can happen if the user is rejecting an invite
to a room that we don't have any members in.
or rescinding a knock for a room that we don't have any members in.
3. someone else on the homeserver is in the room. in this case we can leave like normal by sending a PDU over federation.
in cases 1 and 2, we have to update the state cache using `mark_as_left` directly.
@@ -113,7 +107,7 @@ pub async fn leave_room(
// case 1: the room is banned/disabled. we don't want to federate with
// another server to leave, so we can't create an outlier PDU.
None
} else if dont_have_room.and(not_knocked).await {
} else if dont_have_room.await {
// case 2: ask a remote server to assist us with leaving
// we always mark the room as left locally, regardless of if the
// federated leave failed
+2 -2
View File
@@ -29,7 +29,7 @@ pub(crate) async fn get_profile_route(
State(services): State<crate::State>,
body: Ruma<get_profile::v3::Request>,
) -> Result<get_profile::v3::Response> {
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
if body.identity.is_none() {
return Err!(Request(Unauthorized(
"This server requires authentication to access user profiles."
)));
@@ -46,7 +46,7 @@ pub(crate) async fn get_profile_field_route(
State(services): State<crate::State>,
body: Ruma<get_profile_field::v3::Request>,
) -> Result<get_profile_field::v3::Response> {
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
if body.identity.is_none() {
return Err!(Request(Unauthorized(
"This server requires authentication to access user profiles."
)));
+23 -9
View File
@@ -9,7 +9,7 @@ use service::Services;
use crate::{Ruma, router::ClientIdentity};
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous`
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous`
pub(crate) async fn discover_rendezvous_route(
State(services): State<crate::State>,
body: Ruma<discover_rendezvous::msc4388::Request>,
@@ -20,7 +20,7 @@ pub(crate) async fn discover_rendezvous_route(
)))
}
/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/`
/// `POST /_matrix/client/unstable/io.element.msc4388/rendezvous`
pub(crate) async fn create_rendezvous_session_route(
State(services): State<crate::State>,
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())
}
/// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}`
/// `PUT /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}/{txn_id}`
pub(crate) async fn update_rendezvous_session_route(
State(services): State<crate::State>,
body: Ruma<update_rendezvous_session::msc4388::Request>,
@@ -45,16 +45,30 @@ pub(crate) async fn update_rendezvous_session_route(
)
}
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
pub(crate) async fn get_rendezvous_session_route(
State(services): State<crate::State>,
headers: HeaderMap,
body: Ruma<get_rendezvous_session::msc4388::Request>,
) -> Result<get_rendezvous_session::msc4388::Response> {
if let Some(mode) = headers.get("Sec-Fetch-Mode")
&& let Ok(mode) = mode.to_str()
&& mode == "navigate"
{
let is_navigation_mode = headers
.get_all("Sec-Fetch-Mode")
.iter()
.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(
"Rendezvous sessions do not accept browser navigation requests."
)));
@@ -63,7 +77,7 @@ pub(crate) async fn get_rendezvous_session_route(
services.rendezvous.get_session(&body.id)
}
/// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
/// `DELETE /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
pub(crate) async fn delete_rendezvous_session_route(
State(services): State<crate::State>,
body: Ruma<delete_rendezvous_session::msc4388::Request>,
+3 -1
View File
@@ -4,10 +4,12 @@ mod event;
mod initial_sync;
mod stripped_state;
mod summary;
mod timestamp_to_event;
mod upgrade;
pub(crate) use self::{
aliases::get_room_aliases_route, create::create_room_route, event::get_room_event_route,
initial_sync::room_initial_sync_route, stripped_state::get_stripped_state_route,
summary::get_room_summary, upgrade::upgrade_room_route,
summary::get_room_summary, timestamp_to_event::get_event_by_timestamp_route,
upgrade::upgrade_room_route,
};
+61
View File
@@ -0,0 +1,61 @@
use axum::extract::State;
use conduwuit::{Err, Event, Result, utils::stream::TryIgnore};
use futures::{StreamExt, pin_mut};
use ruma::api::client::room::get_event_by_timestamp;
use crate::Ruma;
const MAX_CANDIDATES: usize = 20;
/// # `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event`
///
/// Gets the ID of the event closest to the given timestamp, in the direction
/// specified by `dir`.
pub(crate) async fn get_event_by_timestamp_route(
State(ref services): State<crate::State>,
body: Ruma<get_event_by_timestamp::v1::Request>,
) -> Result<get_event_by_timestamp::v1::Response> {
let sender_user = body.identity.expect_sender_user()?;
let room_id = &body.room_id;
if !services
.rooms
.state_accessor
.user_can_see_state_events(sender_user, room_id)
.await
{
return Err!(Request(Forbidden("You don't have permission to view this room.")));
}
if !services.rooms.timeline.timestamp_index_ready().await {
return Err!(FeatureDisabled("timestamp_to_event"));
}
let candidates = services
.rooms
.timeline
.pdus_by_timestamp(room_id, body.ts, body.dir)
.ignore_err()
.take(MAX_CANDIDATES);
pin_mut!(candidates);
while let Some((_, pdu)) = candidates.next().await {
if services
.rooms
.state_accessor
.user_can_see_event(sender_user, room_id, pdu.event_id())
.await
{
return Ok(get_event_by_timestamp::v1::Response::new(
pdu.event_id().to_owned(),
pdu.origin_server_ts(),
));
}
}
Err!(Request(NotFound(
"Unable to find event from {} in direction {:?}",
body.ts.get(),
body.dir
)))
}
+22 -11
View File
@@ -1,9 +1,12 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use ruma::{
api::client::discovery::{
discover_homeserver::{self, HomeserverInfo},
discover_policy_server, discover_support,
api::client::{
discovery::{
discover_homeserver::{self, HomeserverInfo},
discover_policy_server, discover_support,
},
rtc,
},
assign,
};
@@ -37,17 +40,25 @@ pub(crate) async fn well_known_client(
}
/// # `GET /_matrix/client/v1/rtc/transports`
/// # `GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports`
///
/// Returns the list of MatrixRTC foci (transports) configured for this
/// homeserver, implementing MSC4143.
/// Returns the list of MatrixRTC transports configured for this homeserver,
/// implementing the stable version of MSC4143.
pub(crate) async fn get_rtc_transports(
State(services): State<crate::State>,
_body: Ruma<ruma::api::client::rtc::transports::msc4143::Request>,
) -> Result<ruma::api::client::rtc::transports::msc4143::Response> {
Ok(ruma::api::client::rtc::transports::msc4143::Response::new(
services.config.matrix_rtc.foci.clone(),
))
_body: Ruma<rtc::transports::v1::Request>,
) -> Result<rtc::transports::v1::Response> {
Ok(rtc::transports::v1::Response::new(services.config.matrix_rtc.foci.clone()))
}
/// # `GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports`
///
/// Unstable version of [`get_rtc_transports`], which names the response field
/// `rtc_transports` instead of `transports`.
pub(crate) async fn get_rtc_transports_unstable(
State(services): State<crate::State>,
_body: Ruma<rtc::transports::msc4143::Request>,
) -> Result<rtc::transports::msc4143::Response> {
Ok(rtc::transports::msc4143::Response::new(services.config.matrix_rtc.foci.clone()))
}
/// # `GET /.well-known/matrix/support`
+25 -6
View File
@@ -52,6 +52,7 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::set_pushrule_actions_route)
.ruma_route(&client::delete_pushrule_route)
.ruma_route(&client::get_room_event_route)
.ruma_route(&client::get_event_by_timestamp_route)
.ruma_route(&client::get_room_aliases_route)
.ruma_route(&client::get_filter_route)
.ruma_route(&client::create_filter_route)
@@ -188,12 +189,25 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::well_known_client)
.ruma_route(&client::well_known_policy_server)
.ruma_route(&client::get_rtc_transports)
.ruma_route(&client::get_rtc_transports_unstable)
.ruma_route(&client::room_initial_sync_route)
.ruma_route(&client::discover_rendezvous_route)
.ruma_route(&client::create_rendezvous_session_route)
.ruma_route(&client::update_rendezvous_session_route)
.ruma_route(&client::get_rendezvous_session_route)
.ruma_route(&client::delete_rendezvous_session_route)
.merge(
Router::new()
.ruma_route(&client::discover_rendezvous_route)
.ruma_route(&client::create_rendezvous_session_route)
.ruma_route(&client::update_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)
.merge(client::oauth::router(state))
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
@@ -217,7 +231,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
if config.allow_federation {
router = router
.ruma_route(&server::get_server_version_route)
.route("/_matrix/key/v2/server", get(server::get_server_keys_route))
.ruma_route(&server::get_server_keys_route)
.ruma_route(&server::get_remote_server_keys_batch_route)
.ruma_route(&server::get_remote_server_keys_route)
.ruma_route(&server::get_public_rooms_route)
.ruma_route(&server::get_public_rooms_filtered_route)
.ruma_route(&server::send_transaction_message_route)
@@ -244,6 +260,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&server::get_content_route)
.ruma_route(&server::get_content_thumbnail_route)
.route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count));
if config.experiments.msc4556.is_enabled() {
router = router.ruma_route(&server::get_remote_server_keys_batch_v3_unstable_route);
}
if config.experiments.msc4560.is_enabled() {
router = router.ruma_route(&server::get_stripped_state_route);
}
+17 -3
View File
@@ -11,7 +11,11 @@ use axum::{
use conduwuit::{Error, Result, err, error};
use ruma::{
CanonicalJsonObject,
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
api::{
IncomingRequest, IncomingRequestExt,
auth_scheme::AuthScheme,
error::{DeserializationError, FromHttpRequestError},
},
};
use serde::Deserialize;
@@ -114,8 +118,18 @@ where
.await?;
// Deserialize the body
let body = R::try_from_http_request(request, &borrowed_path)
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
let body_is_empty = body.is_empty();
let body = R::try_from_http_request(request, &borrowed_path).map_err(|e| match 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 })
}
+24 -1
View File
@@ -194,6 +194,10 @@ impl CheckAuth for AccessTokenOptional {
authentication: Self::Output,
query: AuthQueryParams,
) -> 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 {
check_access_token(
services,
@@ -278,6 +282,11 @@ impl CheckAuth for NoAccessToken {
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 {
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
OAuthClientScope::ApiFullAccess,
@@ -285,7 +294,7 @@ impl CheckAuth for NoAccessToken {
.await
.map(Some)
} else {
if R::RATE_LIMITED {
if R::RATE_LIMITED && !is_rendezvous_session {
check_unauthenticated_request_ratelimiting(services, request_ip)?;
}
@@ -433,6 +442,20 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result<Regi
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<()> {
if services
.config
+92 -63
View File
@@ -12,8 +12,8 @@ use conduwuit::{
warn,
};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedUserId, ServerName,
UserId,
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId,
ServerName, UserId,
api::{
error::{ErrorKind, IncompatibleRoomVersionErrorData},
federation::membership::{RawStrippedState, create_invite},
@@ -22,6 +22,7 @@ use ruma::{
room_version_rules::RoomVersionRules,
};
use serde::Deserialize;
use service::Services;
use crate::{Ruma, server::utils::validate_any_membership_event};
@@ -45,7 +46,7 @@ pub(crate) async fn create_invite_route(
}
async fn create_invite(
services: &crate::State,
services: &Services,
body: Ruma<create_invite::v2::Request>,
) -> Result<create_invite::v2::Response> {
if !services.server.supported_room_version(&body.room_version) {
@@ -79,7 +80,7 @@ async fn create_invite(
via=?body.via,
"Validating invite room state for invite request"
);
let (create_event_id, state) = validate_invite_state(
let (create_event_id, state) = validate_partial_membership_state(
services,
&body.invite_room_state,
&room_version_rules,
@@ -260,7 +261,7 @@ async fn create_invite(
///
/// [spec]: https://spec.matrix.org/v1.19/server-server-api/#put_matrixfederationv2inviteroomideventid
async fn validate_invite_membership_event(
services: &crate::State,
services: &Services,
body: &serde_json::value::RawValue,
room_version_rules: &RoomVersionRules,
origin: &ServerName,
@@ -299,83 +300,111 @@ async fn validate_invite_membership_event(
Ok((pdu, sender_user, recipient_user))
}
/// Validates a single event from partial membership state (`invite_room_state`
/// or `knock_room_state`), returning its event ID, `(event_type, state_key)`,
/// and parsed canonical JSON.
pub(crate) async fn validate_partial_membership_event(
services: &Services,
event: &RawStrippedState,
room_version_rules: &RoomVersionRules,
room_id: &RoomId,
idx: usize,
) -> Result<(OwnedEventId, (StateEventType, StateKey), CanonicalJsonObject)> {
// Stripped state hasn't been sent over federation since v1.16.
let RawStrippedState::Pdu(raw_pdu) = event else {
debug!(%idx, "Partial membership state event is not a PDU");
return Err!(Request(InvalidParam(
"PDU in partial membership state (index {idx}) violates the room event format"
)));
};
let (state_event_room_id, state_event_id, state_event_json) = services
.rooms
.event_handler
.parse_incoming_pdu(raw_pdu, Some(room_version_rules))
.await
.map_err(|e| {
err!(Request(InvalidParam(debug_warn!(
"Invalid PDU in partial membership state: {e}"
))))
})?;
if state_event_room_id != room_id {
return Err!(Request(InvalidParam(debug_warn!(
%state_event_room_id,
%room_id,
"PDU in partial membership state ({state_event_id}) belongs to the wrong room"
))));
}
services
.server_keys
.verify_event_json(&state_event_json, room_version_rules)
.await
.map_err(|e| {
err!(Request(InvalidParam(
"Signature verification failed on partial membership state event: {e}"
)))
})?;
let Some(state_key) = state_event_json.get("state_key").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_info!(
"PDU in partial membership state ({state_event_id}) is not a state event"
))));
};
let Some(event_type) = state_event_json.get("type").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_warn!(
"PDU in partial membership state ({state_event_id}) is not an event?"
))));
};
let key = StateEventType::from(event_type).with_state_key(state_key);
if key.0 == StateEventType::RoomCreate {
// Ensure this is a legal create event.
let pdu_event = PduEvent::from_id_val(&state_event_id, state_event_json.clone())
.expect("must be able to create pdu event from event json");
debug!("Validating discovered create event in partial membership room state");
validate_invite_create_event(&pdu_event, room_version_rules).await?;
}
Ok((state_event_id, key, state_event_json))
}
/// Validates the *invite state* of an invite request, per the steps listed
/// under the endpoint's [spec].
///
/// Returns the create event's event ID, and the partial state map.
///
/// [spec]: https://spec.matrix.org/v1.19/server-server-api/#put_matrixfederationv2inviteroomideventid
async fn validate_invite_state(
services: &crate::State,
pub(crate) async fn validate_partial_membership_state(
services: &Services,
invite_state: &[RawStrippedState],
room_version_rules: &RoomVersionRules,
room_id: OwnedRoomId,
) -> Result<(OwnedEventId, HashMap<(StateEventType, StateKey), CanonicalJsonObject>)> {
trace!(?invite_state, "Raw invite state");
trace!(?invite_state, "Raw partial membership state");
let mut invite_state_map: HashMap<(StateEventType, StateKey), _> =
HashMap::with_capacity(invite_state.len());
let mut create_event_id: Option<OwnedEventId> = None;
for (idx, invite_state_event) in invite_state.iter().cloned().enumerate() {
trace!(%idx, ?invite_state_event, "Invite state event");
// Stripped state hasn't been sent over federation since v1.16.
let RawStrippedState::Pdu(raw_pdu) = invite_state_event else {
debug!(%idx, "Invite state event is not a PDU");
return Err!(Request(InvalidParam(
"PDU in invite state (index {idx}) violates the room event format"
)));
};
let (state_event_room_id, state_event_id, state_event_json) = services
.rooms
.event_handler
.parse_incoming_pdu(&raw_pdu, Some(room_version_rules))
.await
.map_err(|e| {
err!(Request(InvalidParam(debug_warn!("Invalid PDU in invite state: {e}"))))
})?;
for (idx, invite_state_event) in invite_state.iter().enumerate() {
trace!(%idx, ?invite_state_event, "Partial membership state event");
let (state_event_id, key, state_event_json) = validate_partial_membership_event(
services,
invite_state_event,
room_version_rules,
&room_id,
idx,
)
.await?;
if state_event_room_id != room_id {
return Err!(Request(InvalidParam(debug_warn!(
%state_event_room_id,
%room_id,
"PDU in invite state ({state_event_id}) belongs to the wrong room"
))));
}
services
.server_keys
.verify_event_json(&state_event_json, room_version_rules)
.await
.map_err(|e| {
err!(Request(InvalidParam("Signature verification failed on invite event: {e}")))
})?;
let Some(state_key) = state_event_json.get("state_key").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_info!(
"PDU in invite state ({state_event_id}) is not a state event"
))));
};
let Some(event_type) = state_event_json.get("type").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_warn!(
"PDU in invite state ({state_event_id}) is not an event?"
))));
};
let key = StateEventType::from(event_type).with_state_key(state_key);
match invite_state_map.entry(key) {
| Entry::Occupied(entry) =>
return Err!(Request(InvalidParam(
"Duplicate state events in invite state for state key: {:?}",
"Duplicate state events in partial membership state for state key: {:?}",
entry.key(),
))),
| Entry::Vacant(entry) => {
if entry.key().0 == StateEventType::RoomCreate {
// Ensure this is a legal create event.
let pdu_event =
PduEvent::from_id_val(&state_event_id, state_event_json.clone())
.expect("must be able to create pdu event from event json");
debug!("Validating discovered create event in invite room state");
validate_invite_create_event(&pdu_event, room_version_rules).await?;
create_event_id = Some(state_event_id);
}
entry.insert(state_event_json);
@@ -385,7 +414,7 @@ async fn validate_invite_state(
let Some(create_event_id) = create_event_id else {
return Err!(Request(InvalidParam(debug_warn!(
parsed_state=?invite_state_map,
"Invite state does not contain the m.room.create event"
"Partial membership state does not contain the m.room.create event"
))));
};
invite_state_map.iter().try_for_each(|(key, event_json)| {
@@ -396,7 +425,7 @@ async fn validate_invite_state(
)
.map_err(|e| {
err!(Request(InvalidParam(
"PDU in invite state for {key:?} violates the room event format: {e}"
"PDU in partial membership state for {key:?} violates the room event format: {e}"
)))
})
})?;
@@ -414,7 +443,7 @@ struct MFederate {
///
/// 1. It passes auth checks (aka is valid)
/// 2. The room is federated (there's no point persisting unfederated rooms)
async fn validate_invite_create_event(
pub(crate) async fn validate_invite_create_event(
pdu: &PduEvent,
room_version_rules: &RoomVersionRules,
) -> Result {
+288 -68
View File
@@ -1,89 +1,309 @@
use std::{collections::BTreeMap, mem::take, time::Duration};
use std::{
collections::{BTreeMap, HashSet},
sync::Arc,
time::Instant,
};
use axum::{Json, extract::State, response::IntoResponse};
use conduwuit::{Result, utils::timepoint_from_now};
use futures::StreamExt;
use axum::extract::State;
use conduwuit::{
Err, Result,
config::experiments::ToggledExperiment,
debug_info,
utils::{ReadyExt, stream::automatic_width},
};
use ruma::{
MilliSecondsSinceUnixEpoch,
api::{
OutgoingResponseExt,
federation::discovery::{OldVerifyKey, ServerSigningKeys, get_server_keys},
MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId,
api::federation::discovery::{
ServerSigningKeys, get_remote_server_keys, get_remote_server_keys_batch,
get_remote_server_keys_batch::v2::QueryCriteria, get_server_keys,
},
assign,
serde::Raw,
};
use service::{server_keys, server_keys::in_one_week};
use service::server_keys::{self, in_one_week};
use crate::router::Ruma;
/// # `GET /_matrix/key/v2/server`
///
/// Gets the public signing keys of this server.
pub(crate) async fn get_server_keys_route(
State(services): State<crate::State>,
) -> Result<impl IntoResponse> {
let server_name = services.globals.server_name();
let verify_keys = BTreeMap::from([services.server_keys.active_verify_key()]);
_body: Ruma<get_server_keys::v2::Request>,
) -> Result<get_server_keys::v2::Response> {
services
.server_keys
.build_server_keys_response()
.await
.map(get_server_keys::v2::Response::new)
}
let old_verify_keys = if let Some(k) = &services.config.old_verify_keys {
k.to_owned()
} else {
// We need to figure out any old signing keys we've acquired from
// notaries.
let mut keys = services.server_keys.signing_keys_for(server_name);
let mut old_keys = BTreeMap::new();
while let Some(resp) = keys.next().await {
// We need to verify that this response is still trusted based on
// the current configuration. It's possible we got this response
// from a notary who we no longer trust.
if resp.parsed.valid_until_ts > in_one_week() {
continue;
}
let trusted = services.config.trusted_servers.iter().any(|notary| {
server_keys::Service::verify_server_keys_response(
&resp,
Some((notary.server_name(), notary.verify_keys())),
)
.is_ok()
});
if !trusted {
continue;
}
for (old_key_id, old_key) in resp.parsed.old_verify_keys {
if old_key.expired_ts > resp.parsed.valid_until_ts {
// This key expired in the future which is probably illegal
continue;
}
old_keys
.entry(old_key_id)
.and_modify(|current_old_key: &mut OldVerifyKey| {
// Use the lowest expiry timestamp
if current_old_key.expired_ts > old_key.expired_ts {
*current_old_key = old_key.clone();
}
})
.or_insert(old_key);
}
const MAX_KEYS_PER_QUERY: usize = 16384;
const MAX_SERVERS_PER_QUERY: usize = 4096;
/// # `POST /_matrix/key/v2/query`
///
/// Fetches remote server signing keys in bulk, seeding from the local server's
/// database.
///
/// This route applies a semaphore to slow down requests that query more signing
/// keys than is allowed by [MSC4556].
///
/// [MSC4556]: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
pub(crate) async fn get_remote_server_keys_batch_route(
State(services): State<crate::State>,
body: Ruma<get_remote_server_keys_batch::v2::Request>,
) -> Result<get_remote_server_keys_batch::v2::Response> {
query_inner(&services, &body.server_keys, true)
.await
.map(get_remote_server_keys_batch::v2::Response::new)
}
/// # `POST /_matrix/key/unstable/org.continuwuity.msc4556/query`
/// ## `POST /_matrix/key/v3/query`
///
/// Fetches remote server signing keys in bulk, seeding from the local server's
/// database.
///
/// MSC4556: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
pub(crate) async fn get_remote_server_keys_batch_v3_unstable_route(
State(services): State<crate::State>,
body: Ruma<ruminuwuity::federation::notary::unstable::Request>,
) -> Result<ruminuwuity::federation::notary::unstable::Response> {
query_inner(&services, &body.server_keys, false)
.await
.map(ruminuwuity::federation::notary::unstable::Response::new)
}
/// Handles querying the server keys for `/_matrix/key/*/query`.
///
/// `v2` should be `true` if the request path is `/_matrix/key/v2/query` - this
/// will potentially apply a rate-limit to the request.
async fn query_inner(
services: &crate::State,
body: &BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
v2: bool,
) -> Result<Vec<Raw<ServerSigningKeys>>> {
let start = (Instant::now(), MilliSecondsSinceUnixEpoch::now());
// If the remote server isn't asking for any keys, we can return an empty
// array immediately.
if body.is_empty() {
return Ok(Vec::new());
}
// Count how many keys are being requested.
// Each server incurs a cost of at least one, and then the count of each key
// being queried per-server.
let total_queried_servers = body.len();
let total_queried_keys = body
.values()
.fold(0_usize, |acc, q| acc.saturating_add(q.len().max(1)));
if !v2 && services.config.experiments.msc4556.is_enabled() {
// If we're on the v3 endpoint, we can apply these limits explicitly.
if total_queried_servers > MAX_SERVERS_PER_QUERY {
return Err!(Request(TooLarge(
"Too many server keys requested ({total_queried_servers} > \
{MAX_SERVERS_PER_QUERY}",
)));
}
old_keys
if total_queried_keys > MAX_KEYS_PER_QUERY {
return Err!(Request(TooLarge(
"Too many keys requested ({total_queried_keys} > {MAX_KEYS_PER_QUERY})"
)));
}
}
let penalise =
total_queried_servers > MAX_SERVERS_PER_QUERY || total_queried_keys > MAX_KEYS_PER_QUERY;
debug_info!("Fetching {total_queried_keys} keys across {} servers", body.len());
let mut futs: tokio::task::JoinSet<_> = tokio::task::JoinSet::new();
// If we're on the v2 endpoint, we aren't allowed to reject the request.
// To avoid overloading the server, we'll apply a semaphore to limit how
// many futures can be active at a time.
let width = automatic_width();
let semaphore: Option<Arc<tokio::sync::Semaphore>> = if v2 && penalise {
Some(Arc::new(tokio::sync::Semaphore::new(width)))
} else {
None
};
let server_key = assign!(ServerSigningKeys::new(server_name.to_owned(), valid_until_ts()), {
verify_keys,
old_verify_keys,
});
for (server_name, queries) in body.clone() {
let server_keys = services.server_keys.clone();
let semaphore = semaphore.clone();
let server_key = Raw::new(&server_key)?;
let mut response = get_server_keys::v2::Response::new(server_key)
.try_into_http_response::<Vec<u8>>()
.map(|mut response| take(response.body_mut()))
.and_then(|body| serde_json::from_slice(&body).map_err(Into::into))?;
futs.spawn_on(
async move {
let _permit = if let Some(sem) = semaphore {
let cost = queries
.len()
.saturating_add(1)
.min(automatic_width())
.try_into()
.unwrap_or(u32::MAX);
services.server_keys.sign_json(&mut response)?;
sem.acquire_many_owned(cost).await.ok()
} else {
None
};
Ok(Json(response))
acquire_keys_as_notary(server_keys, server_name, queries, start.1).await
},
services.server.runtime(),
);
}
let mut response = Vec::with_capacity(total_queried_keys);
while let Some(Ok(v)) = futs.join_next().await {
response.extend(v);
}
debug_info!(
elapsed=?start.0.elapsed(),
%total_queried_servers,
%total_queried_keys,
"Fetched {} key responses",
response.len()
);
Ok(response)
}
fn valid_until_ts() -> MilliSecondsSinceUnixEpoch {
let dur = Duration::from_hours(12);
let timepoint = timepoint_from_now(dur).expect("SystemTime should not overflow");
MilliSecondsSinceUnixEpoch::from_system_time(timepoint).expect("UInt should not overflow")
/// `GET /_matrix/key/v2/query/{serverName}`
///
/// Fetches the latest keys for a specific server name.
pub(crate) async fn get_remote_server_keys_route(
State(services): State<crate::State>,
body: Ruma<get_remote_server_keys::v2::Request>,
) -> Result<get_remote_server_keys::v2::Response> {
let server_keys = acquire_keys_as_notary(
services.server_keys.clone(),
body.server_name.clone(),
BTreeMap::new(),
body.minimum_valid_until_ts,
)
.await;
Ok(get_remote_server_keys::v2::Response::new(server_keys))
}
#[tracing::instrument(skip(server_keys, queries, start))]
async fn acquire_keys_as_notary(
server_keys: Arc<server_keys::Service>,
remote: OwnedServerName,
queries: BTreeMap<OwnedServerSigningKeyId, QueryCriteria>,
start: MilliSecondsSinceUnixEpoch,
) -> Vec<Raw<ServerSigningKeys>> {
let mut candidate_remote_keys = Vec::with_capacity(queries.len().max(1));
// If we haven't contacted the origin recently, we need to do that now
// to update our caches, and we might as well use its response as a
// candidate.
if server_keys.origin_not_contacted_recently(&remote) {
if let Ok(remote_keys) = server_keys.origin_request(remote.clone(), start).await {
debug_info!("Considering keys from origin response");
candidate_remote_keys.push(remote_keys);
}
}
if queries.is_empty() {
// The querying server wants all of the origin's keys. If we decided to
// contact it earlier, we can safely assume its response already
// includes all of its keys. Otherwise, we'll add all of our cached
// responses as candidates.
if candidate_remote_keys.is_empty() {
debug_info!("Querying server wants all keys, considering all cached key responses");
server_keys
.signing_keys_for(&remote)
.ready_for_each(|remote_keys| candidate_remote_keys.push(remote_keys))
.await;
}
} else {
// The querying server is asking for specific key IDs.
for key_id in queries.keys() {
if let Some(remote_keys) = server_keys.get_signing_key(&remote, key_id).await {
debug_info!(?key_id, "Considering cached response containing key");
candidate_remote_keys.push(remote_keys);
} else {
debug_info!(?key_id, "No cached response contains key");
}
}
}
// Now we need to filter and sign the remote key responses.
// The signing key responses containing the keys the querying server wants.
let mut signed_remote_key_responses = Vec::with_capacity(queries.len().max(1));
// The key IDs we've already included in a response.
let mut signed_remote_key_ids = HashSet::with_capacity(queries.len().max(1));
for remote_keys in candidate_remote_keys {
// Skip this key response if all of its keys were already included
// in other key responses.
if remote_keys
.all_key_ids()
.all(|key_id| signed_remote_key_ids.contains(key_id))
{
continue;
}
// Skip this key response if it expires too far in the future.
if remote_keys.parsed.valid_until_ts > in_one_week() {
continue;
}
// Check query criteria (currently just the minimum expiry time) for
// each key included in this key response. We skip this response if
// _all_ of the keys in the response fail their criteria.
let all_verify_keys_expired = remote_keys.parsed.verify_keys.keys().all(|key_id| {
let minimum_valid_until_ts = queries
.get(key_id)
.and_then(|criterion| criterion.minimum_valid_until_ts)
.unwrap_or(start);
remote_keys.parsed.valid_until_ts < minimum_valid_until_ts
});
let all_old_verify_keys_too_old =
remote_keys
.parsed
.old_verify_keys
.iter()
.all(|(key_id, key)| {
if let Some(criterion) = queries.get(key_id)
&& let Some(minimum_valid_until_ts) = criterion.minimum_valid_until_ts
{
key.expired_ts < minimum_valid_until_ts
} else {
// If the querying server didn't explicitly set a
// minimum timestamp for an old verify key,
// we should treat it as valid.
false
}
});
if all_verify_keys_expired && all_old_verify_keys_too_old {
continue;
}
// This response is acceptable, let's sign and send it.
let signed_remote_keys = server_keys
.self_sign_signing_keys(&remote, &remote_keys.raw)
.expect("should be able to sign remote keys");
signed_remote_key_responses.push(signed_remote_keys);
for key_id in remote_keys.all_key_ids() {
signed_remote_key_ids.insert(key_id.to_owned());
}
}
signed_remote_key_responses
}
+1 -3
View File
@@ -63,7 +63,7 @@ pub(crate) async fn create_knock_event_v1_route(
return Err!(Request(Forbidden("Room version does not support knocking.")));
}
let (mut event, target_membership, sender, target) = validate_any_membership_event(
let (event, target_membership, sender, target) = validate_any_membership_event(
&services,
&body.pdu,
&room_version_rules,
@@ -83,8 +83,6 @@ pub(crate) async fn create_knock_event_v1_route(
return Err!(Request(InvalidParam("Sender does not match state key")));
}
event.insert("event_id".to_owned(), body.event_id.as_str().into());
let pdu = PduEvent::from_id_val(&body.event_id, event.clone())
.map_err(|e| err!(Request(InvalidParam("Invalid knock event PDU: {e}"))))?;
+1 -1
View File
@@ -84,7 +84,7 @@ impl AccessCheck<'_> {
///
/// A resulting tuple of (PDU JSON, target membership state, sender, recipient).
pub(crate) async fn validate_any_membership_event(
services: &crate::State,
services: &Services,
body: &serde_json::value::RawValue,
room_version_rules: &RoomVersionRules,
create_event_id: OwnedEventId,
+4 -4
View File
@@ -38,12 +38,12 @@ mimalloc = [
]
jemalloc_conf = []
jemalloc_prof = [
"tikv-jemalloc-sys/profiling",
"tikv-jemalloc-sys?/profiling",
]
jemalloc_stats = [
"tikv-jemalloc-sys/stats",
"tikv-jemalloc-ctl/stats",
"tikv-jemallocator/stats",
"tikv-jemalloc-sys?/stats",
"tikv-jemalloc-ctl?/stats",
"tikv-jemallocator?/stats",
]
perf_measurements = []
release_max_log_level = [
+16
View File
@@ -118,6 +118,22 @@ pub struct Experiments {
/// default: false
#[serde(default)]
pub msc4494: SimpleExperiment,
/// MSC4556: Notary request limits
///
/// Creates a new key notary server route that has stricter limits on how
/// many signing keys can be requested in one query, to avoid a resource
/// exhaustion exploit vector in the existing key notary endpoint.
///
/// Continuwuity mitigates the exploit vector in the old notary endpoint
/// anyway, so you do not need to enable this to be protected.
///
/// Requires that remote servers support this MSC before it does anything.
///
/// https://github.com/matrix-org/matrix-spec-proposals/pull/4556
///
/// default: false
#[serde(default)]
pub msc4556: SimpleExperiment,
/// MSC4560: Stripped state requests over federation
///
/// Implements a more efficient way for servers to acquire and serve
+37 -44
View File
@@ -920,19 +920,6 @@ pub struct Config {
#[serde(default)]
pub forget_forced_upon_leave: bool,
/// Set this to true to require authentication when looking up user profiles
/// through this server.
///
/// By default this is false, allowing tools such as matrix.to to access
/// profiles of users on this server and on other servers.
/// Setting this to true will block those tools, and may block automated
/// crawlers from scraping users' profiles, although it will not block
/// other homeservers from accessing users' profiles.
///
/// default: false
#[serde(default)]
pub require_auth_for_profile_requests: bool,
/// Set this to true to require authentication to create a rendezvous
/// session. Rendezvous sessions are used for QR code login.
///
@@ -1154,10 +1141,7 @@ pub struct Config {
/// (trusted key notary servers), as well as serve as trusted servers for
/// other operations like backfill and event fetching.
///
/// Currently, continuwuity doesn't support inbound key requests, so
/// this list should only contain other Synapse servers.
///
/// example: ["matrix.org", "starstruck.systems"]
/// example: ["continuwuity.org", "matrix.org"]
///
/// It is possible to restrict which signing keys trusted servers are
/// allowed to sign responses with. Without configuring this, all responses
@@ -1194,7 +1178,7 @@ pub struct Config {
/// empty list (`[]`) to operate without trusted server assistance, but this
/// is discouraged for performance and reliability reasons.
///
/// default: ["matrix.org"]
/// default: ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
#[serde(default = "default_trusted_servers")]
pub trusted_servers: Vec<TrustedServer>,
@@ -2823,10 +2807,12 @@ pub struct OidcConfig {
/// Additional scopes Continuwuity should request from the IDP. This may be
/// necessary to access certain claims. Continuwuity always requests the
/// `openid` scope.
/// `openid` scope, regardless of the contents of this option,
/// and will also request the `profile` scope by default if this option is
/// not set.
///
/// default: []
#[serde(default)]
/// default: ["profile"]
#[serde(default = "default_additional_scopes")]
pub additional_scopes: Vec<Scope>,
/// Additional trusted audiences that Continuwuity will accept in the `aud`
@@ -3002,6 +2988,7 @@ const DEPRECATED_KEYS: &[&str] = &[
"max_concurrent_requests",
"otlp_protocol",
"request_ip_source",
"require_auth_for_profile_requests",
"roomid_spacehierarchy_cache_capacity",
"unredacted_content_max_age_secs",
"well_known_client",
@@ -3141,41 +3128,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_cache_capacity_mb() -> f64 { 128.0 + parallelism_scaled_f64(64.0) }
fn default_db_cache_capacity_mb() -> f64 { 512.0 + parallelism_scaled_f64(512.0) }
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(10_000).saturating_add(100_000) }
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(50_000).saturating_add(100_000) }
fn default_cache_capacity_modifier() -> f64 { 1.0 }
fn default_auth_chain_cache_capacity() -> u32 {
parallelism_scaled_u32(10_000).saturating_add(100_000)
}
fn default_shorteventid_cache_capacity() -> u32 {
parallelism_scaled_u32(50_000).saturating_add(100_000)
}
fn default_shorteventid_cache_capacity() -> u32 {
parallelism_scaled_u32(100_000).saturating_add(100_000)
}
fn default_eventidshort_cache_capacity() -> u32 {
parallelism_scaled_u32(25_000).saturating_add(100_000)
parallelism_scaled_u32(50_000).saturating_add(100_000)
}
fn default_eventid_pdu_cache_capacity() -> u32 {
parallelism_scaled_u32(25_000).saturating_add(100_000)
parallelism_scaled_u32(50_000).saturating_add(100_000)
}
fn default_shortstatekey_cache_capacity() -> u32 {
parallelism_scaled_u32(10_000).saturating_add(100_000)
parallelism_scaled_u32(100_000).saturating_add(100_000)
}
fn default_statekeyshort_cache_capacity() -> u32 {
parallelism_scaled_u32(10_000).saturating_add(100_000)
parallelism_scaled_u32(50_000).saturating_add(100_000)
}
fn default_servernameevent_data_cache_capacity() -> u32 {
parallelism_scaled_u32(100_000).saturating_add(500_000)
parallelism_scaled_u32(100_000).saturating_add(100_000)
}
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(100) }
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(500).clamp(100, 12000) }
fn default_dns_cache_entries() -> u32 { 32768 }
@@ -3262,12 +3249,11 @@ fn default_otlp_filter() -> String {
fn default_tracing_flame_output_path() -> String { "./tracing.folded".to_owned() }
fn default_trusted_servers() -> Vec<TrustedServer> {
// TODO(nex): Once we can be a notary, add maintainer(?) homeservers here.
// Rationale: Users are already running our code, arguably that's a higher
// level of trust than is assigned to notaries in the first place.
// We should still remind everyone that notaries are evil and out to get you
// and to replace this list with servers they actually trust.
let trusted_servers = vec![ruma::owned_server_name!("matrix.org")];
let trusted_servers = vec![
ruma::owned_server_name!("continuwuity.org"),
ruma::owned_server_name!("continuwuity.rocks"),
ruma::owned_server_name!("matrix.org"),
];
trusted_servers
.into_iter()
.map(TrustedServer::Name)
@@ -3398,15 +3384,20 @@ fn default_admin_log_capture() -> String {
fn default_admin_room_tag() -> String { "m.server_notice".to_owned() }
#[must_use]
#[allow(clippy::as_conversions, clippy::cast_precision_loss)]
fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
pub fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
fn parallelism_scaled_u32(val: u32) -> u32 {
let val = val.try_into().expect("failed to cast u32 to usize");
parallelism_scaled(val).try_into().unwrap_or(u32::MAX)
#[must_use]
#[allow(clippy::as_conversions, clippy::cast_possible_truncation)]
pub fn parallelism_scaled_u32(val: u32) -> u32 {
val.saturating_mul(sys::available_parallelism() as u32)
}
fn parallelism_scaled(val: usize) -> usize { val.saturating_mul(sys::available_parallelism()) }
#[must_use]
pub fn parallelism_scaled(val: usize) -> usize {
val.saturating_mul(sys::available_parallelism())
}
fn default_db_pool_workers() -> usize {
sys::available_parallelism()
@@ -3446,6 +3437,8 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
}
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
// example config generator writes sections in macro expansion order, and the
// `global` section truncates the file, so declaring this module any earlier
+3 -1
View File
@@ -171,13 +171,14 @@ impl Error {
/// Returns the Matrix error code / error kind
#[inline]
pub fn kind(&self) -> ErrorKind {
use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
match self {
| Self::Federation(_, error) | Self::Ruma(error) =>
response::ruma_error_kind(error).clone(),
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
| Self::FeatureDisabled(..) => Unrecognized,
| Self::Path(_) | Self::Query(_) => InvalidParam,
| _ => Unknown,
}
}
@@ -194,6 +195,7 @@ impl Error {
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
| Self::Conflict(_) => StatusCode::CONFLICT,
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
| Self::Io(error) => response::io_error_code(error.kind()),
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
| _ => StatusCode::INTERNAL_SERVER_ERROR,
+3
View File
@@ -73,6 +73,9 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
// 413
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
// 409
| ConcurrentWrite => StatusCode::CONFLICT,
// 404
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
+2
View File
@@ -18,6 +18,7 @@ pub fn versions() -> Vec<String> {
"v1.3".to_owned(),
"v1.4".to_owned(),
"v1.5".to_owned(),
"v1.6".to_owned(),
"v1.8".to_owned(),
"v1.11".to_owned(),
"v1.12".to_owned(),
@@ -37,6 +38,7 @@ pub fn unstable_features(experiments: &Experiments) -> BTreeMap<String, bool> {
// MatrixRTC (https://github.com/matrix-org/matrix-spec-proposals/pull/4143)
// Expected for spec v1.20/v2.0
("org.matrix.msc4143".to_owned(), true),
("org.matrix.msc4143.stable".to_owned(), true),
// Simplified Sliding sync (https://github.com/matrix-org/matrix-spec-proposals/pull/4186)
// Expected for spec v1.20/v2.0
("org.matrix.simplified_msc3575".to_owned(), true),
+6
View File
@@ -21,6 +21,7 @@ pub struct Instruments {
pub sender_transaction_duration: Histogram<f64>,
pub sender_events: Counter<u64>,
pub sender_events_queued: Counter<u64>,
pub sender_panics: Counter<u64>,
pub media_write_size: Histogram<u64>,
pub media_read_size: Histogram<u64>,
@@ -116,6 +117,11 @@ impl Instruments {
.with_description("PDUs and EDUs queued for sending")
.with_unit("{event}")
.build(),
sender_panics: meter
.u64_counter("continuwuity.sender.panics")
.with_description("Panics caught in outgoing transactions and sender workers")
.with_unit("{panic}")
.build(),
media_write_size: size(
"continuwuity.media.write.size",
+79 -15
View File
@@ -1,10 +1,8 @@
//! Extended external extensions to futures::FutureExt
use std::marker::Unpin;
use futures::{
Future, FutureExt,
future::{select_ok, try_join, try_join_all, try_select},
future::{try_join, try_join_all},
};
pub trait BoolExt
@@ -18,8 +16,8 @@ where
fn or<B>(self, b: B) -> impl Future<Output = bool> + Send
where
B: Future<Output = bool> + Send + Unpin,
Self: Sized + Unpin;
B: Future<Output = bool> + Send,
Self: Sized;
}
impl<Fut> BoolExt for Fut
@@ -44,20 +42,20 @@ where
#[inline]
fn or<B>(self, b: B) -> impl Future<Output = bool> + Send
where
B: Future<Output = bool> + Send + Unpin,
Self: Sized + Unpin,
B: Future<Output = bool> + Send,
Self: Sized,
{
type Result = crate::Result<(), ()>;
let a = self.map(|a| a.then_some(()).ok_or(Result::Err(())));
let a = self.map(|a| (!a).then_some(()).ok_or(Result::Err(())));
let b = b.map(|b| b.then_some(()).ok_or(Result::Err(())));
let b = b.map(|b| (!b).then_some(()).ok_or(Result::Err(())));
try_select(a, b).map(|result| result.is_ok())
try_join(a, b).map(|result| result.is_err())
}
}
pub async fn and<I, F>(args: I) -> impl Future<Output = bool> + Send
pub fn and<I, F>(args: I) -> impl Future<Output = bool> + Send
where
I: Iterator<Item = F> + Send,
F: Future<Output = bool> + Send,
@@ -69,14 +67,80 @@ where
try_join_all(args).map(|result| result.is_ok())
}
pub async fn or<I, F>(args: I) -> impl Future<Output = bool> + Send
pub fn or<I, F>(args: I) -> impl Future<Output = bool> + Send
where
I: Iterator<Item = F> + Send,
F: Future<Output = bool> + Send + Unpin,
F: Future<Output = bool> + Send,
{
type Result = crate::Result<(), ()>;
let args = args.map(|a| a.map(|a| a.then_some(()).ok_or(Result::Err(()))));
let args = args.map(|a| a.map(|a| (!a).then_some(()).ok_or(Result::Err(()))));
select_ok(args).map(|result| result.is_ok())
try_join_all(args).map(|result| result.is_err())
}
#[cfg(test)]
mod tests {
use std::pin::pin;
use futures::future;
use super::{BoolExt, and, or};
#[tokio::test]
async fn bool_ext_truth_tables() {
for a in [false, true] {
for b in [false, true] {
assert_eq!(future::ready(a).and(future::ready(b)).await, a && b, "and({a}, {b})");
assert_eq!(future::ready(a).or(future::ready(b)).await, a || b, "or({a}, {b})");
}
}
assert!(
future::ready(false)
.or(future::ready(false))
.or(future::ready(true))
.await,
"chained or with trailing true must return true"
);
assert!(
!future::ready(false)
.or(future::ready(false))
.or(future::ready(false))
.await,
"chained or with all false must return false"
);
}
#[tokio::test]
async fn bool_ext_short_circuits() {
let pend = pin!(future::pending::<bool>());
assert!(
future::ready(true).or(pend).await,
"or must short-circuit on true without polling pending"
);
let pend = pin!(future::pending::<bool>());
assert!(
!future::ready(false).and(pend).await,
"and must short-circuit on false without polling pending"
);
}
#[tokio::test]
async fn free_and_or() {
assert!(and(std::iter::empty::<future::Ready<bool>>()).await, "empty and is true");
assert!(!or(std::iter::empty::<future::Ready<bool>>()).await, "empty or is false");
assert!(and([future::ready(true), future::ready(true)].into_iter()).await, "all true");
assert!(
!and([future::ready(true), future::ready(false)].into_iter()).await,
"and with false"
);
assert!(
or([future::ready(false), future::ready(true)].into_iter()).await,
"or with true"
);
assert!(!or([future::ready(false), future::ready(false)].into_iter()).await, "all false");
}
}
+3
View File
@@ -5,6 +5,7 @@ pub type DigestOut = [u8; 256 / 8];
/// Sha256 hash (input gather joined by 0xFF bytes)
#[must_use]
#[tracing::instrument(skip(inputs), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn delimited<'a, T, I>(mut inputs: I) -> DigestOut
where
I: Iterator<Item = T> + 'a,
@@ -25,6 +26,7 @@ where
/// Sha256 hash (input gather)
#[must_use]
#[tracing::instrument(skip(inputs), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn concat<'a, T, I>(inputs: I) -> DigestOut
where
I: Iterator<Item = T> + 'a,
@@ -43,6 +45,7 @@ where
#[inline]
#[must_use]
#[tracing::instrument(skip(input), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn hash<T>(input: T) -> DigestOut
where
T: AsRef<[u8]>,
+1 -1
View File
@@ -29,7 +29,7 @@ fn descriptor_cf_options(
let mut opts = set_table_options(opts, &desc, cache)?;
opts.set_min_write_buffer_number(1);
opts.set_max_write_buffer_number(2);
opts.set_max_write_buffer_number(3);
opts.set_write_buffer_size(desc.write_size);
opts.set_target_file_size_base(desc.file_size);
+4
View File
@@ -232,6 +232,10 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "roomsynctoken_shortstatehash",
..descriptor::DROPPED
},
Descriptor {
name: "roomts_pduid",
..descriptor::SEQUENTIAL_SMALL
},
Descriptor {
name: "roomuserdataid_accountdata",
..descriptor::RANDOM_SMALL
+29 -9
View File
@@ -48,6 +48,7 @@ assets = [
[features]
default = [
"standard",
"jemalloc",
"ring",
"bindgen-runtime", # replace with bindgen-static on alpine
]
@@ -57,7 +58,6 @@ standard = [
"element_hacks",
"gzip_compression",
"io_uring",
"jemalloc",
"jemalloc_conf",
"journald",
"media_thumbnail",
@@ -76,6 +76,7 @@ full = [
]
brotli_compression = [
"conduwuit-api/brotli_compression",
"conduwuit-core/brotli_compression",
"conduwuit-router/brotli_compression",
"conduwuit-service/brotli_compression",
@@ -87,30 +88,31 @@ direct_tls = [
"conduwuit-router/direct_tls"
]
element_hacks = [
"conduwuit-api/element_hacks",
"conduwuit-service/element_hacks",
"conduwuit-router/element_hacks",
]
gzip_compression = [
"conduwuit-api/gzip_compression",
"conduwuit-core/gzip_compression",
"conduwuit-router/gzip_compression",
"conduwuit-service/gzip_compression",
]
http3 = [
"conduwuit-service/http3"
"reqwest/http3"
]
ring = [
"rustls/ring",
"rustls/ring"
]
aws_lc_rs = [
"rustls/aws_lc_rs",
"dep:aws-lc-rs"
]
io_uring = [
"conduwuit-service/io_uring",
"conduwuit-database/io_uring",
]
jemalloc = [
"conduwuit-core/jemalloc",
"conduwuit-service/jemalloc",
"conduwuit-database/jemalloc",
]
mimalloc = [
"conduwuit-core/mimalloc",
@@ -142,13 +144,19 @@ perf_measurements = [
release_max_log_level = [
"tracing/max_level_trace",
"tracing/release_max_level_info",
"log/max_level_trace",
"log/release_max_level_info",
"conduwuit-admin/release_max_log_level",
"conduwuit-api/release_max_log_level",
"conduwuit-core/release_max_log_level",
"conduwuit-database/release_max_log_level",
"conduwuit-router/release_max_log_level",
"conduwuit-service/release_max_log_level",
]
sentry_telemetry = [
"dep:sentry",
"dep:sentry-tracing",
"dep:sentry-tower",
"conduwuit-core/sentry_telemetry",
"conduwuit-router/sentry_telemetry",
]
@@ -171,17 +179,19 @@ url_preview = [
"conduwuit-service/url_preview",
]
zstd_compression = [
"conduwuit-api/zstd_compression",
"conduwuit-core/zstd_compression",
"conduwuit-database/zstd_compression",
"conduwuit-router/zstd_compression",
"conduwuit-service/zstd_compression",
]
bindgen-static = [
# "bindgen/static"
# "clang-sys/static"
"conduwuit-service/bindgen-static"
"conduwuit-database/bindgen-static"
]
bindgen-runtime = [
"conduwuit-service/bindgen-runtime"
"conduwuit-database/bindgen-runtime"
]
[build-dependencies]
@@ -189,7 +199,10 @@ bindgen-runtime = [
# clang-sys = {version = "1", default-features = false}
[dependencies]
conduwuit-admin.workspace = true
conduwuit-api.workspace = true
conduwuit-core.workspace = true
conduwuit-database.workspace = true
conduwuit-router.workspace = true
conduwuit-service.workspace = true
conduwuit-build-metadata.workspace = true
@@ -201,6 +214,7 @@ dtor.workspace = true
console-subscriber.optional = true
console-subscriber.workspace = true
const-str.workspace = true
log.workspace = true
opentelemetry.workspace = true
opentelemetry-otlp.optional = true
opentelemetry-otlp.workspace = true
@@ -208,10 +222,14 @@ opentelemetry-prometheus.workspace = true
opentelemetry-semantic-conventions.workspace = true
opentelemetry_sdk.workspace = true
prometheus.workspace = true
sentry-tower.optional = true
sentry-tower.workspace = true
sentry-tracing.optional = true
sentry-tracing.workspace = true
sentry.optional = true
sentry.workspace = true
tokio-metrics.optional = true
tokio-metrics.workspace = true
tokio.workspace = true
tracing-flame.optional = true
tracing-flame.workspace = true
@@ -221,7 +239,9 @@ tracing-subscriber.workspace = true
tracing.workspace = true
tracing-journald = { workspace = true, optional = true }
parking_lot.workspace = true
reqwest = { workspace = true, default-features = false }
rustls = { workspace = true, default-features = false }
aws-lc-rs = { version = "1.19.0", default-features = false, optional = true }
[lints]
workspace = true
+5
View File
@@ -32,6 +32,11 @@ pub fn run() -> Result<()> {
pub fn run_with_args(args: &Args) -> Result<()> {
// Spawn deadlock detection thread
deadlock::spawn();
#[cfg(not(any(feature = "jemalloc", feature = "mimalloc")))]
conduwuit_core::warn!(
"Your build configuration does not have a non-system allocator enabled. This may result \
in decreased performance."
);
// Because we're not using rustls default-tls, we have to initialise a TLS
// provider
+4 -4
View File
@@ -8,7 +8,7 @@ use axum::{
extract::State,
response::{IntoResponse, Response},
};
use conduwuit::{Result, debug, debug_error, debug_warn, err, error, trace};
use conduwuit::{Result, debug_warn, err, error, info, trace};
use conduwuit_service::Services;
use futures::FutureExt;
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");
if status.is_server_error() {
error!(%method, %uri, "{code} {reason}");
info!(%method, %uri, "{code} {reason}");
} else if status.is_client_error() {
debug_error!(%method, %uri, "{code} {reason}");
info!(%method, %uri, "{code} {reason}");
} else if status.is_redirection() {
debug!(%method, %uri, "{code} {reason}");
trace!(%method, %uri, "{code} {reason}");
} else {
trace!(%method, %uri, "{code} {reason}");
}
+1
View File
@@ -0,0 +1 @@
pub mod notary;
+56
View File
@@ -0,0 +1,56 @@
//! `POST /_matrix/key/*/query`
//!
//! Endpoint to query signing keys through other (notary) servers.
pub mod unstable {
use std::collections::BTreeMap;
use ruma::{
OwnedServerName, OwnedServerSigningKeyId,
api::{
federation::{
authentication::ServerSignatures,
discovery::{ServerSigningKeys, get_remote_server_keys_batch::v2::QueryCriteria},
},
request, response,
},
metadata,
serde::Raw,
};
metadata! {
method: POST,
rate_limited: true,
authentication: ServerSignatures,
path: "/_matrix/key/unstable/org.continuwuity.msc4556/query",
}
#[request]
pub struct Request {
pub server_keys:
BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
}
#[response]
pub struct Response {
pub server_keys: Vec<Raw<ServerSigningKeys>>,
}
impl Request {
#[must_use]
pub fn new(
server_keys: BTreeMap<
OwnedServerName,
BTreeMap<OwnedServerSigningKeyId, QueryCriteria>,
>,
) -> Self {
Self { server_keys }
}
}
impl Response {
/// Creates a new `Response` with the given keys.
#[must_use]
pub fn new(server_keys: Vec<Raw<ServerSigningKeys>>) -> Self { Self { server_keys } }
}
}
+2
View File
@@ -6,3 +6,5 @@ pub mod invite_permission_config;
pub mod meowlnir_antispam;
pub mod policy;
pub mod pushers;
pub mod federation;
+1 -12
View File
@@ -16,12 +16,6 @@ crate-type = [
]
[features]
bindgen-runtime = [
"conduwuit-database/bindgen-runtime"
]
bindgen-static = [
"conduwuit-database/bindgen-static"
]
brotli_compression = [
"conduwuit-core/brotli_compression",
"reqwest/brotli",
@@ -35,9 +29,6 @@ gzip_compression = [
"conduwuit-core/gzip_compression",
"reqwest/gzip",
]
http3 = [
"reqwest/http3"
]
io_uring = [
"conduwuit-database/io_uring",
]
@@ -105,6 +96,7 @@ itertools.workspace = true
log.workspace = true
loole.workspace = true
lru-cache.workspace = true
mime.workspace = true
nonzero_ext.workspace = true
p256.workspace = true
regex.workspace = true
@@ -131,9 +123,6 @@ lettre.workspace = true
resolvematrix.workspace = true
serde_urlencoded.workspace = true
openidconnect.workspace = true
# We use this to set TLS backend features on the outdated reqwest bundled by openidconnect,
# which is necessary to call `danger_accept_invalid_certs`.
reqwest_0_12.workspace = true
rand.workspace = true
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
+1 -1
View File
@@ -111,7 +111,7 @@ impl crate::Service for Service {
.local_address(url_preview_bind_addr)
.timeout(Duration::from_secs(config.url_preview_timeout))
.redirect(redirect::Policy::limited(3))
.user_agent(url_preview_user_agent)
.user_agent(url_preview_user_agent.replace("<version>", conduwuit::version_ua()))
.build()?,
external_resource: base(config, reqwest_dns_resolver.clone())?
+7
View File
@@ -223,6 +223,8 @@ impl Data {
x => x,
};*/
// TODO(nex): Oh my god this is awful when can we kill it
let title = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
@@ -321,6 +323,11 @@ impl Data {
video_height,
audio,
audio_size,
..Default::default() /* TODO(nex,silversys): This weird manual field
* de/serialisation just needs replacing with JSON storage to
* avoid this mess. This is consequently intentionally
* dropping information added later (like image alt text).
* I'll do it later. */
})
}
}
+345 -90
View File
@@ -7,29 +7,79 @@
use std::time::SystemTime;
#[cfg(feature = "url_preview")]
use conduwuit::info;
use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt};
use ipaddress::IPAddress;
use mime::Mime;
use ruma::OwnedMxcUri;
use serde::Serialize;
use serde::{Serialize, Serializer};
use url::Url;
use super::Service;
use crate::media::mxc::Mxc;
#[derive(Serialize, Default)]
// serde `serialize_with` passes `&Option<T>` for `Option<T>` fields.
#[allow(clippy::ref_option)]
fn serialize_mime<S: Serializer>(mime: &Option<Mime>, serializer: S) -> Result<S::Ok, S::Error> {
match mime {
| Some(m) => serializer.serialize_str(m.as_ref()),
| None => serializer.serialize_none(),
}
}
#[derive(Serialize, Default, Debug)]
pub struct UrlPreviewData {
// From https://ogp.me/
/// The title of your object as it should appear within the graph
/// "The Rock".
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:title"))]
pub title: Option<String>,
/// The type of your object, e.g., "video.movie".
#[serde(skip_serializing_if = "String::is_empty", rename(serialize = "og:type"))]
pub site_type: String,
/// The canonical URL of your object that will be used as its permanent ID
/// in the graph.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:url"))]
pub url: Option<String>,
/// A one to two sentence description of your object.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:description"))]
pub description: Option<String>,
/// The word that appears before this object's title in a sentence.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:determiner"))]
pub determiner: Option<String>,
/// The locale these tags are marked up in
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:locale"))]
pub locale: Option<String>,
/// If your object is part of a larger web site, the name which should be
/// displayed for the overall site.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:site_name"))]
pub site_name: Option<String>,
/// An image URL which should represent your object within the graph.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image"))]
pub image: Option<String>,
/// A MIME type for this image.
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_mime",
rename(serialize = "og:image:type")
)]
pub image_type: Option<Mime>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:image:size"))]
pub image_size: Option<usize>,
/// The number of pixels wide.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:width"))]
pub image_width: Option<u32>,
/// The number of pixels high.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:height"))]
pub image_height: Option<u32>,
/// A description of what is in the image (not a caption).
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:alt"))]
pub image_alt: Option<String>,
/// A URL to a video file that complements this object.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video"))]
pub video: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:video:size"))]
@@ -38,6 +88,15 @@ pub struct UrlPreviewData {
pub video_width: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:height"))]
pub video_height: Option<u32>,
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_mime",
rename(serialize = "og:video:type")
)]
pub video_type: Option<Mime>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:alt"))]
pub video_alt: Option<String>,
/// A URL to an audio file to accompany this object.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:audio"))]
pub audio: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:audio:size"))]
@@ -78,43 +137,39 @@ impl Service {
}
async fn request_url_preview(&self, url: &Url) -> Result<UrlPreviewData> {
if let Ok(ip) = IPAddress::parse(url.host_str().expect("URL previously validated")) {
if !self.services.client.valid_cidr_range(&ip) {
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
}
}
self.check_url_ip(url.as_str())?;
let client = &self.services.client.url_preview;
let response = client.head(url.as_str()).send().await?;
debug!(%url, "URL preview response headers: {:?}", response.headers());
if let Some(remote_addr) = response.remote_addr() {
debug!(%url, "URL preview response remote address: {:?}", remote_addr);
if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) {
if !self.services.client.valid_cidr_range(&ip) {
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
}
}
self.check_response_ip(&response)?;
if !response.status().is_success() {
return Err!(Request(Unknown(
"URL preview request returned HTTP {}",
response.status()
)));
}
let Some(content_type) = response.headers().get(reqwest::header::CONTENT_TYPE) else {
return Err!(Request(Unknown("Unknown or invalid Content-Type header")));
return Err!(Request(Unknown(
"Response contains unknown, invalid, or missing Content-Type header"
)));
};
let content_type = content_type
let content_type: Mime = content_type
.to_str()
.map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))?
.parse()
.map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))?;
let data = match content_type {
| html if html.starts_with("text/html") => self.download_html(url.as_str()).await?,
| img if img.starts_with("image/") => self.download_image(url.as_str(), None).await?,
| video if video.starts_with("video/") =>
self.download_video(url.as_str(), None).await?,
| audio if audio.starts_with("audio/") =>
self.download_audio(url.as_str(), None).await?,
| _ => return Err!(Request(Unknown("Unsupported Content-Type"))),
let data = match (content_type.type_(), content_type.subtype()) {
| (mime::TEXT, mime::HTML) => self.download_html(url.as_str()).await?,
| (mime::IMAGE, _) => self.download_image(url.as_str()).await?,
| (mime::VIDEO, _) => self.download_video(url.as_str()).await?,
| (mime::AUDIO, _) => self.download_audio(url.as_str()).await?,
| _ => return Err!(Request(Unknown("Unsupported Content-Type: {content_type}"))),
};
self.set_url_preview(url.as_str(), &data).await?;
@@ -123,19 +178,16 @@ impl Service {
}
#[cfg(feature = "url_preview")]
pub async fn download_image(
&self,
url: &str,
preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
pub async fn download_image(&self, url: &str) -> Result<UrlPreviewData> {
use conduwuit::utils::random_string;
use image::ImageReader;
use crate::media::mxc::Mxc;
let mut preview_data = UrlPreviewData::default();
let mut preview_data = preview_data.unwrap_or_default();
self.check_url_ip(url)?;
let response = self.services.client.url_preview.get(url).send().await?;
self.check_response_ip(&response)?;
if !response.status().is_success() {
return Err!(Request(Unknown("Image download returned HTTP {}", response.status())));
}
@@ -157,13 +209,13 @@ impl Service {
.ok_or_else(|| err!(Request(Unknown("Downloaded file is not a supported image"))))?
.to_mime_type();
if preview_data.image_height.is_none() || preview_data.image_width.is_none() {
let (width, height) = reader.into_dimensions().map_err(|error| {
err!(Request(Unknown("Failed to read preview image dimensions: {error}")))
})?;
preview_data.image_width.get_or_insert(width);
preview_data.image_height.get_or_insert(height);
}
let (width, height) = reader.into_dimensions().map_err(|error| {
err!(Request(Unknown("Failed to read preview image dimensions: {error}")))
})?;
preview_data.image_width = Some(width);
preview_data.image_height = Some(height);
preview_data.image_size = Some(image.len());
preview_data.image_type = content_type.parse().ok();
let mxc = Mxc {
server_name: self.services.globals.server_name(),
@@ -179,12 +231,9 @@ impl Service {
}
#[cfg(feature = "url_preview")]
pub async fn download_video(
&self,
url: &str,
preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
let mut preview_data = preview_data.unwrap_or_default();
#[tracing::instrument(skip(self))]
pub async fn download_video(&self, url: &str) -> Result<UrlPreviewData> {
let mut preview_data = UrlPreviewData::default();
if self.services.globals.url_preview_allow_audio_video() {
let (url, size) = self.download_media(url).await?;
@@ -196,12 +245,9 @@ impl Service {
}
#[cfg(feature = "url_preview")]
pub async fn download_audio(
&self,
url: &str,
preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
let mut preview_data = preview_data.unwrap_or_default();
#[tracing::instrument(skip(self))]
pub async fn download_audio(&self, url: &str) -> Result<UrlPreviewData> {
let mut preview_data = UrlPreviewData::default();
if self.services.globals.url_preview_allow_audio_video() {
let (url, size) = self.download_media(url).await?;
@@ -212,11 +258,18 @@ impl Service {
Ok(preview_data)
}
#[tracing::instrument(skip(self))]
pub async fn download_media(&self, url: &str) -> Result<(OwnedMxcUri, usize)> {
use conduwuit::utils::random_string;
use http::header::CONTENT_TYPE;
self.check_url_ip(url)?;
let response = self.services.client.url_preview.get(url).send().await?;
self.check_response_ip(&response)?;
if !response.status().is_success() {
return Err!(Request(Unknown("Media download returned HTTP {}", response.status())));
}
let content_type = response.headers().get(CONTENT_TYPE).cloned();
let media = response
.limit_read(
@@ -242,41 +295,32 @@ impl Service {
}
#[cfg(not(feature = "url_preview"))]
pub async fn download_image(
&self,
_url: &str,
_preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
Err!(FeatureDisabled("url_preview"))
pub fn download_image(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
std::future::ready(Err!(FeatureDisabled("url_preview")))
}
#[cfg(not(feature = "url_preview"))]
pub async fn download_video(
&self,
_url: &str,
_preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
Err!(FeatureDisabled("url_preview"))
pub fn download_video(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
std::future::ready(Err!(FeatureDisabled("url_preview")))
}
#[cfg(not(feature = "url_preview"))]
pub async fn download_audio(
&self,
_url: &str,
_preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
Err!(FeatureDisabled("url_preview"))
pub fn download_audio(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
std::future::ready(Err!(FeatureDisabled("url_preview")))
}
#[cfg(feature = "url_preview")]
#[tracing::instrument(skip(self))]
async fn download_html(&self, url: &str) -> Result<UrlPreviewData> {
use webpage::HTML;
let client = &self.services.client.url_preview;
let body = client
.get(url)
.send()
.await?
let response = client.get(url).send().await?;
self.check_response_ip(&response)?;
if !response.status().is_success() {
return Err!(Request(Unknown("HTML download returned HTTP {}", response.status())));
}
let body = response
.limit_read_text(
self.services
.server
@@ -286,39 +330,138 @@ impl Service {
.expect("u64 should fit in usize"),
)
.await?;
let Ok(html) = HTML::from_string(body.clone(), Some(url.to_owned())) else {
let Ok(html) = HTML::from_string(body, Some(url.to_owned()))
.inspect_err(|e| debug!(error=?e, "Failed to parse HTML data"))
else {
return Err!(Request(Unknown("Failed to parse HTML")));
};
let mut preview_data = UrlPreviewData::default();
let mut preview_data = UrlPreviewData::from(&html.opengraph);
debug!(parsed=?preview_data, deserialised=?html.opengraph, "Parsed opengraph data");
if let Some(obj) = html.opengraph.images.first() {
preview_data = self.download_image(&obj.url, Some(preview_data)).await?;
let base_url = Url::parse(url).ok();
let resolve_asset_url = |asset_url: &str| -> String {
base_url
.as_ref()
.and_then(|base| base.join(asset_url).ok())
.map_or_else(|| asset_url.to_owned(), Into::into)
};
if let Some(obj) = html
.opengraph
.images
.first()
.filter(|obj| !obj.url.is_empty())
{
let asset_url = resolve_asset_url(&obj.url);
info!(%asset_url, "Downloading preview image");
if let Ok(image_data) = self.download_image(&asset_url).await.inspect_err(
|e| info!(error=?e, %asset_url, "Could not download URL preview image"),
) {
preview_data.image = image_data.image;
preview_data.image_size = image_data.image_size;
// Prioritise what the top-level site specified, falling back to
// detected params.
preview_data.image_width = preview_data.image_width.or(image_data.image_width);
preview_data.image_height = preview_data.image_height.or(image_data.image_height);
preview_data.image_type = preview_data.image_type.or(image_data.image_type);
}
}
if let Some(obj) = html.opengraph.videos.first() {
preview_data = self.download_video(&obj.url, Some(preview_data)).await?;
preview_data.video_width = obj.properties.get("width").and_then(|v| v.parse().ok());
preview_data.video_height = obj.properties.get("height").and_then(|v| v.parse().ok());
if let Some(obj) = html
.opengraph
.videos
.first()
.filter(|obj| !obj.url.is_empty())
{
let asset_url = resolve_asset_url(&obj.url);
info!(%asset_url, "Downloading preview video");
if let Ok(video_data) = self.download_video(&asset_url).await.inspect_err(
|e| info!(error=?e, %asset_url, "Could not download URL preview video"),
) {
preview_data.video = video_data.video;
preview_data.video_size = video_data.video_size;
}
}
if let Some(obj) = html.opengraph.audios.first() {
preview_data = self.download_audio(&obj.url, Some(preview_data)).await?;
if let Some(obj) = html
.opengraph
.audios
.first()
.filter(|obj| !obj.url.is_empty())
{
let asset_url = resolve_asset_url(&obj.url);
info!(%asset_url, "Downloading URL preview audio");
if let Ok(audio_data) = self.download_audio(&asset_url).await.inspect_err(
|e| info!(error=?e, %asset_url, "Could not download URL preview audio"),
) {
preview_data.audio = audio_data.audio;
preview_data.audio_size = audio_data.audio_size;
}
}
let props = html.opengraph.properties;
// Provide defaults for some params
preview_data.title = preview_data.title.or(html.title);
preview_data.description = preview_data.description.or(html.description);
preview_data.url = preview_data.url.or_else(|| Some(url.to_owned()));
/* use OpenGraph title/description, but fall back to HTML if not
* available */
preview_data.title = props.get("title").cloned().or(html.title);
preview_data.description = props.get("description").cloned().or(html.description);
// We remove og:image:*, og:video:*, and og:audio:* if their respective
// prior-level properties are not present.
// We do this here instead of in the From<> impl because we can't know
// if we'll be able to fetch the media to convert it to an mxc that
// point.
if preview_data.image.is_none() {
preview_data.image_type = None;
preview_data.image_alt = None;
preview_data.image_height = None;
preview_data.image_width = None;
preview_data.image_size = None;
}
if preview_data.video.is_none() {
preview_data.video_type = None;
preview_data.video_alt = None;
preview_data.video_height = None;
preview_data.video_width = None;
preview_data.video_size = None;
}
if preview_data.audio.is_none() {
preview_data.audio_size = None;
}
Ok(preview_data)
}
#[cfg(not(feature = "url_preview"))]
async fn download_html(&self, _url: &str) -> Result<UrlPreviewData> {
Err!(FeatureDisabled("url_preview"))
#[allow(clippy::unused_self)]
fn download_html(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
std::future::ready(Err!(FeatureDisabled("url_preview")))
}
fn check_url_ip(&self, url: &str) -> Result<()> {
let parsed = Url::parse(url)
.map_err(|e| err!(Request(InvalidParam("Requested URL is not valid: {e}"))))?;
let Some(host) = parsed.host_str() else {
return Err!(Request(InvalidParam("Requested URL does not have a host")));
};
if let Ok(ip) = IPAddress::parse(host) {
if !self.services.client.valid_cidr_range(&ip) {
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
}
}
Ok(())
}
fn check_response_ip(&self, response: &reqwest::Response) -> Result<()> {
if let Some(remote_addr) = response.remote_addr() {
debug!(url = %response.url(), "URL preview response remote address: {:?}", remote_addr);
if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) {
if !self.services.client.valid_cidr_range(&ip) {
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
}
}
}
Ok(())
}
pub fn url_preview_allowed(&self, url: &Url) -> bool {
@@ -443,3 +586,115 @@ impl Service {
false
}
}
#[cfg(feature = "url_preview")]
impl From<&webpage::Opengraph> for UrlPreviewData {
fn from(og: &webpage::Opengraph) -> Self {
Self {
title: og.properties.get("title").cloned(),
description: og.properties.get("description").cloned(),
site_type: og.og_type.clone(),
url: og.properties.get("url").cloned(),
determiner: og.properties.get("determiner").cloned(),
locale: og.properties.get("locale").cloned(),
site_name: og.properties.get("site_name").cloned(),
image_type: og
.images
.first()
.and_then(|img| img.properties.get("type").and_then(|t| t.parse().ok())),
image_width: og
.images
.first()
.and_then(|img| img.properties.get("width").and_then(|w| w.parse().ok())),
image_height: og
.images
.first()
.and_then(|img| img.properties.get("height").and_then(|h| h.parse().ok())),
image_alt: og
.images
.first()
.and_then(|img| img.properties.get("alt").cloned()),
video_type: og
.videos
.first()
.and_then(|vid| vid.properties.get("type"))
.and_then(|t| t.parse().ok()),
video_width: og
.videos
.first()
.and_then(|vid| vid.properties.get("width"))
.and_then(|w| w.parse().ok()),
video_height: og
.videos
.first()
.and_then(|vid| vid.properties.get("height"))
.and_then(|h| h.parse().ok()),
video_alt: og
.videos
.first()
.and_then(|vid| vid.properties.get("alt").cloned()),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "url_preview")]
#[test]
fn test_urlpreviewdata_parses_correctly() {
use webpage::HTML;
use super::UrlPreviewData;
let html = r#"
<html>
<head>
<meta property="og:title" content="Test Title" />
<meta property="og:description" content="Test Description" />
<meta property="og:image" content="https://example.com/image.png" />
<meta property="og:url" content="https://example.com/index.html" />
<meta property="og:type" content="org.continuwuity.other" />
<meta property="og:site_name" content="Example Site" />
<meta property="og:image:alt" content="An example image" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:height" content="69" />
<meta property="og:image:width" content="420" />
<meta property="og:video" content="https://example.com/video.mp4" />
<meta property="og:audio" content="https://example.com/audio.ogg" />
</head>
<body></body>
</html>
"#;
let parsed_html =
HTML::from_string(html.to_owned(), Some("https://example.com".to_owned()))
.expect("Failed to parse HTML");
let data = UrlPreviewData::from(&parsed_html.opengraph);
assert_eq!(data.title, Some("Test Title".to_owned()));
assert_eq!(data.description, Some("Test Description".to_owned()));
assert_eq!(
data.image, None,
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
);
assert_eq!(
data.video, None,
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
);
assert_eq!(
data.audio, None,
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
);
assert_eq!(data.url, Some("https://example.com/index.html".to_owned()));
assert_eq!(data.site_type, "org.continuwuity.other".to_owned());
assert_eq!(data.site_name, Some("Example Site".to_owned()));
assert_eq!(data.image_alt, Some("An example image".to_owned()));
assert_eq!(data.image_type, Some("image/png".parse().unwrap()));
assert_eq!(data.image_height, Some(69));
assert_eq!(data.image_width, Some(420));
assert_eq!(data.image_size, None, "*_size must be None when pulling from opengraph");
assert_eq!(data.video_size, None, "*_size must be None when pulling from opengraph");
assert_eq!(data.audio_size, None, "*_size must be None when pulling from opengraph");
}
}
+22
View File
@@ -18,6 +18,28 @@ impl Services {
},
);
self.gauge(
"continuwuity.sender.requests",
"Estimated outgoing requests stored as queued or in flight",
"{request}",
|services, observer| {
for (state, count) in services.sending.db.request_counts() {
if let Some(count) = count {
observer.observe(count, &[KeyValue::new("state", state)]);
}
}
},
);
self.gauge(
"continuwuity.sender.workers",
"Running sender workers",
"{worker}",
|services, observer| {
observe(observer, services.sending.workers_alive(), &[]);
},
);
self.gauge(
"continuwuity.federation.incoming.transactions.active",
"Incoming federation transactions currently being processed",
+69 -3
View File
@@ -18,11 +18,11 @@ use conduwuit::{
},
warn,
};
use database::{Deserialized, Ignore, Json};
use database::{Database, Deserialized, Ignore, Json};
use futures::{FutureExt, StreamExt, TryStreamExt};
use itertools::Itertools;
use ruma::{
OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, UserId,
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, UserId,
api::OAuthClientScope,
events::{
AnyStrippedStateEvent, GlobalAccountDataEventType, StateEventType,
@@ -32,9 +32,13 @@ use ruma::{
push::Ruleset,
serde::{Raw, from_raw_json_value},
};
use serde::Deserialize;
use serde_json::{Value, value::to_raw_value};
use crate::{Services, media, rooms, rooms::short::ShortStateHash};
use crate::{
Services, media, rooms,
rooms::{short::ShortStateHash, timeline::RawPduId},
};
type MigrationFn =
for<'a> fn(&'a Services) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
@@ -176,6 +180,36 @@ migration!(stringify!($name) => $name)
// This is backwards compatible because old versions never read the
// account data entries it removes.
migration!(remove_replaced_account_data),
// This is backwards compatible because old versions ignore the
// `roomts_pduid` keyspace.
Migration(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, |services| {
Box::pin(async {
let global = &services.db["global"];
if global
.exists(rooms::timeline::TIMESTAMP_INDEX_MIGRATION)
.await
.is_ok()
{
return Ok(());
}
let until = match global.get(ROOMTS_UNTIL).await.deserialized::<u64>() {
| Ok(until) => until,
| Err(_) => {
let until = services.globals.current_count()?;
global.insert(ROOMTS_UNTIL, until.to_be_bytes());
until
},
};
services
.server
.runtime()
.spawn(populate_roomts_pduid(services.db.clone(), until));
Ok(())
})
}),
]
};
@@ -961,6 +995,38 @@ async fn drop_server_signingkeys(services: &Services) -> Result<()> {
Ok(())
}
const ROOMTS_UNTIL: &str = "populate_roomts_pduid_until";
async fn populate_roomts_pduid(db: Arc<Database>, until: u64) {
#[derive(Deserialize)]
struct ExtractTs {
origin_server_ts: MilliSecondsSinceUnixEpoch,
}
info!("Starting background migration to index PDUs by timestamp.");
let start = Instant::now();
let roomts_pduid = db["roomts_pduid"].clone();
db["pduid_pdu"]
.raw_stream()
.ignore_err()
.ready_for_each(|(key, val)| {
let pdu_id = RawPduId::from(key);
if matches!(pdu_id.pdu_count(), PduCount::Normal(count) if count > until) {
return;
}
if let Ok(pdu) = serde_json::from_slice::<ExtractTs>(val) {
roomts_pduid
.insert(&rooms::timeline::roomts_key(&pdu_id, pdu.origin_server_ts), []);
}
})
.await;
db["global"].insert(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, []);
db["global"].remove(ROOMTS_UNTIL);
info!(elapsed = ?start.elapsed(), "Finished indexing PDUs by timestamp.");
}
async fn fix_oauth_scope_names(services: &Services) -> Result {
let db = &services.db;
let userdeviceid_oauthsessioninfo = db["userdeviceid_oauthsessioninfo"].clone();
+2
View File
@@ -13,6 +13,8 @@ mod migrations;
mod service;
pub mod services;
pub mod state;
#[cfg(test)]
mod test_utils;
pub mod account_data;
pub mod admin;
+93 -21
View File
@@ -1,25 +1,38 @@
use std::{
net::IpAddr,
sync::Arc,
time::{Duration, SystemTime},
time::{Duration, Instant},
};
use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils};
use conduwuit::{
Err, Error, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils,
};
use governor::{
DefaultKeyedRateLimiter, Quota, RateLimiter,
clock::{Clock, DefaultClock},
};
use lru_cache::LruCache;
use nonzero_ext::nonzero;
use ruma::{
OwnedTransactionId,
api::client::rendezvous::{
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
update_rendezvous_session,
api::{
client::rendezvous::{
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
update_rendezvous_session,
},
error::{ErrorKind, LimitExceededErrorData, RetryAfter},
},
};
pub struct Service {
sessions: SyncMutex<LruCache<String, Session>>,
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
}
struct Session {
data: String,
created_at: SystemTime,
created_at: Instant,
last_sequence_token: String,
transaction_sequences: LruCache<OwnedTransactionId, String>,
}
@@ -27,20 +40,31 @@ struct Session {
impl Session {
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
fn new(data: String, sequence_token: String) -> Self {
fn new(data: String, sequence_token: String, now: Instant) -> Self {
Self {
data,
created_at: SystemTime::now(),
created_at: now,
last_sequence_token: sequence_token,
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 {
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
Ok(Arc::new(Self {
sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)),
create_ratelimiter: RateLimiter::keyed(Self::CREATE_RATELIMIT),
session_ratelimiter: RateLimiter::keyed(Self::SESSION_RATELIMIT),
}))
}
@@ -48,25 +72,64 @@ impl crate::Service for Service {
}
impl Service {
const CREATE_RATELIMIT: Quota = Quota::per_minute(nonzero!(30_u32));
const MAX_DATA_SIZE_BYTES: usize = 4096;
const MAX_SESSIONS: usize = 256;
const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
const SESSION_RATELIMIT: Quota = Quota::per_minute(nonzero!(300_u32));
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 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.
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
// evict them over time
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
sessions
.get_mut(id)
.filter(|session| {
SystemTime::now()
.duration_since(session.created_at)
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
})
.filter(|session| !session.is_expired(now))
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
})
.map_err(at!(1))
@@ -86,7 +149,7 @@ impl Service {
self.sessions
.lock()
.insert(id.clone(), Session::new(data, sequence_token.clone()));
.insert(id.clone(), Session::new(data, sequence_token.clone(), Instant::now()));
Ok(create_rendezvous_session::msc4388::Response::new(
id,
@@ -103,6 +166,12 @@ impl Service {
sequence_token: String,
data: String,
) -> 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)?;
// If the provided transaction ID was used already, we have to return
@@ -137,13 +206,12 @@ impl Service {
/// Look up a rendezvous session by ID.
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
let session = self.lock_session(id)?;
let now = Instant::now();
let session = self.lock_session_at(id, now)?;
let session_age = SystemTime::now()
.duration_since(session.created_at)
.unwrap_or(Duration::MAX);
let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age);
let session_time_remaining = session
.time_remaining(now)
.unwrap_or_else(|| Duration::from_millis(1));
Ok(get_rendezvous_session::msc4388::Response::new(
session.last_sequence_token.clone(),
@@ -158,8 +226,12 @@ impl Service {
id: &str,
) -> Result<delete_rendezvous_session::msc4388::Response> {
let mut sessions = self.sessions.lock();
let now = Instant::now();
if sessions.remove(id).is_some() {
if sessions
.remove(id)
.is_some_and(|session| !session.is_expired(now))
{
Ok(delete_rendezvous_session::msc4388::Response::new())
} else {
Err!(Request(NotFound("Unknown session")))
@@ -1,14 +1,10 @@
use std::sync::Arc;
use conduwuit::{
Config, PduEvent, Server,
log::{Log, LogLevelReloadHandles},
metrics::Metrics,
};
use conduwuit::PduEvent;
use futures::StreamExt;
use ruma::{RoomId, RoomVersionId, events::StateEventType};
use serde_json::json;
use crate::test_utils::test_services;
#[tokio::test]
async fn admitted_joins_do_not_disappear_after_a_merge() {
use conduwuit::matrix::PartialPdu;
@@ -20,7 +16,7 @@ async fn admitted_joins_do_not_disappear_after_a_merge() {
},
};
let (services, path) = test_services().await;
let (services, path, _database) = test_services().await;
let alice = UserId::parse("@alice:test.example").unwrap();
let bob = UserId::parse("@bob:bob.example").unwrap();
let charlie = UserId::parse("@charlie:charlie.example").unwrap();
@@ -212,35 +208,6 @@ async fn admitted_joins_do_not_disappear_after_a_merge() {
assert_eq!(results, [true, true], "both joined users must be able to send messages");
}
async fn test_services() -> (Arc<crate::Services>, std::path::PathBuf) {
let _ = rustls::crypto::ring::default_provider().install_default();
let path = std::env::temp_dir()
.join(format!("continuwuity-shared-state-{:016x}", rand::random::<u64>()));
std::fs::create_dir(&path).unwrap();
let config: Config = serde_json::from_value(json!({
"server_name": "test.example",
"database_path": path,
"db_cache_capacity_mb": 16.0,
"rocksdb_write_buffer_capacity_mb": 4.0,
"allow_local_presence": false,
"dns_servers": ["127.0.0.1"],
"allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true
}))
.unwrap();
let runtime = tokio::runtime::Handle::current();
let server = Arc::new(Server::new(
config,
Some(runtime.clone()),
Log {
reload: LogLevelReloadHandles::default(),
capture: Arc::default(),
},
Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None),
));
let services = crate::Services::build(server).await.unwrap();
(services, path)
}
fn cache_key(
services: &crate::Services,
server: &ruma::ServerName,
+19 -19
View File
@@ -1,4 +1,4 @@
use std::{borrow::Borrow, fmt::Debug, mem::size_of_val, sync::Arc};
use std::{borrow::Borrow, collections::HashMap, fmt::Debug, mem::size_of_val, sync::Arc};
pub use conduwuit::matrix::pdu::{ShortEventId, ShortId, ShortRoomId, ShortStateKey};
use conduwuit::{
@@ -72,14 +72,22 @@ impl Service {
where
I: Iterator<Item = &'a EventId> + Clone + Debug + Send + 'a,
{
let mut created: HashMap<OwnedEventId, ShortEventId> = HashMap::new();
event_ids
.clone()
.stream()
.get(&self.db.eventid_shorteventid)
.zip(event_ids.into_iter().stream())
.map(|(result, event_id)| match result {
.map(move |(result, event_id)| match result {
| Ok(ref short) => utils::u64_from_u8(short),
| Err(_) => self.create_shorteventid(event_id),
| Err(_) =>
if let Some(&short) = created.get(event_id) {
short
} else {
let short = self.create_shorteventid(event_id);
created.insert(event_id.to_owned(), short);
short
},
})
}
@@ -217,32 +225,24 @@ impl Service {
.map(Deserialized::deserialized)
}
/// Gets or creates a short state hash ID. The boolean indicates whether a
/// new short ID was created.
pub async fn get_or_create_shortstatehash(
&self,
state_hash: &[u8],
) -> (ShortStateHash, bool) {
const BUFSIZE: usize = size_of::<ShortStateHash>();
if let Ok(shortstatehash) = self
.db
/// Gets an existing short state hash ID without creating one.
pub async fn get_shortstatehash(&self, state_hash: &[u8]) -> Result<ShortStateHash> {
self.db
.statehash_shortstatehash
.get(state_hash)
.await
.deserialized()
{
return (shortstatehash, true);
}
}
let shortstatehash = self.services.globals.next_count().unwrap();
/// Publishes the mapping from state hash to short state hash after the
/// corresponding state diff has been written.
pub fn set_shortstatehash(&self, state_hash: &[u8], shortstatehash: ShortStateHash) {
const BUFSIZE: usize = size_of::<ShortStateHash>();
debug_assert!(size_of_val(&shortstatehash) == BUFSIZE, "buffer requirement changed");
self.db
.statehash_shortstatehash
.raw_aput::<BUFSIZE, _, _>(state_hash, shortstatehash);
(shortstatehash, false)
}
/// Gets a short room ID.
+43 -40
View File
@@ -170,47 +170,50 @@ impl Service {
let state_hash = calculate_hash(state_ids_compressed.iter().map(|s| &s[..]));
let (shortstatehash, already_existed) = self
.services
.short
.get_or_create_shortstatehash(&state_hash)
.await;
if !already_existed {
let states_parents = match previous_shortstatehash {
| Ok(p) =>
self.services
.state_compressor
.load_shortstatehash_info(p)
.await?,
| _ => Vec::new(),
};
let (statediffnew, statediffremoved) =
if let Some(parent_stateinfo) = states_parents.last() {
let statediffnew: CompressedState = state_ids_compressed
.difference(&parent_stateinfo.full_state)
.copied()
.collect();
let statediffremoved: CompressedState = parent_stateinfo
.full_state
.difference(&state_ids_compressed)
.copied()
.collect();
(Arc::new(statediffnew), Arc::new(statediffremoved))
} else {
(state_ids_compressed, Arc::new(CompressedState::new()))
let shortstatehash =
if let Ok(existing) = self.services.short.get_shortstatehash(&state_hash).await {
existing
} else {
let states_parents = match previous_shortstatehash {
| Ok(p) =>
self.services
.state_compressor
.load_shortstatehash_info(p)
.await?,
| _ => Vec::new(),
};
self.services.state_compressor.save_state_from_diff(
shortstatehash,
statediffnew,
statediffremoved,
1_000_000, // high number because no state will be based on this one
states_parents,
)?;
}
let (statediffnew, statediffremoved) =
if let Some(parent_stateinfo) = states_parents.last() {
let statediffnew: CompressedState = state_ids_compressed
.difference(&parent_stateinfo.full_state)
.copied()
.collect();
let statediffremoved: CompressedState = parent_stateinfo
.full_state
.difference(&state_ids_compressed)
.copied()
.collect();
(Arc::new(statediffnew), Arc::new(statediffremoved))
} else {
(state_ids_compressed, Arc::new(CompressedState::new()))
};
let new_shortstatehash = self.services.globals.next_count()?;
self.services.state_compressor.save_state_from_diff(
new_shortstatehash,
statediffnew,
statediffremoved,
1_000_000, // high number because no state will be based on this one
states_parents,
)?;
self.services
.short
.set_shortstatehash(&state_hash, new_shortstatehash);
new_shortstatehash
};
self.db
.shorteventid_shortstatehash
+15 -5
View File
@@ -7,15 +7,13 @@ use ruma::{
OwnedServerName, RoomId, UserId,
api::federation::membership::RawStrippedState,
events::{
AnyStrippedStateEvent, GlobalAccountDataEventType, RoomAccountDataEventType,
StateEventType,
GlobalAccountDataEventType, RoomAccountDataEventType, StateEventType,
direct::DirectEvent,
room::{
create::RoomCreateEventContent,
member::{MembershipState, RoomMemberEventContent},
},
},
serde::Raw,
};
use ruminuwuity::invite_permission_config::FilterLevel;
@@ -123,6 +121,18 @@ impl super::Service {
self.mark_as_invited(user_id, room_id, pdu.sender(), invite_state, None)
.await?;
},
| MembershipState::Knock => {
let knocked_state = if is_local {
self.services
.state
.summary_stripped(pdu, room_id, user_id, false)
.await
} else {
vec![]
};
self.mark_as_knocked(user_id, room_id, knocked_state);
},
| MembershipState::Leave | MembershipState::Ban => {
self.mark_as_left(user_id, room_id, Some(pdu.clone())).await;
},
@@ -274,7 +284,7 @@ impl super::Service {
&self,
user_id: &UserId,
room_id: &RoomId,
knocked_state: Option<Vec<Raw<AnyStrippedStateEvent>>>,
knocked_state: Vec<RawStrippedState>,
) {
let userroom_id = (user_id, room_id);
let userroom_id = serialize_key(userroom_id).expect("failed to serialize userroom_id");
@@ -284,7 +294,7 @@ impl super::Service {
self.db
.userroomid_knockedstate
.raw_put(&userroom_id, Json(knocked_state.unwrap_or_default()));
.raw_put(&userroom_id, Json(knocked_state));
self.db
.roomuserid_knockedcount
.raw_aput::<8, _, _>(&roomuser_id, self.services.globals.next_count().unwrap());
+31 -15
View File
@@ -18,7 +18,7 @@ use lru_cache::LruCache;
use ruma::{EventId, RoomId};
use crate::{
Dep, rooms,
Dep, globals, rooms,
rooms::short::{ShortEventId, ShortId, ShortStateHash, ShortStateKey},
};
@@ -29,6 +29,7 @@ pub struct Service {
}
struct Services {
globals: Dep<globals::Service>,
short: Dep<rooms::short::Service>,
state: Dep<rooms::state::Service>,
}
@@ -78,6 +79,7 @@ impl crate::Service for Service {
shortstatehash_statediff: args.db["shortstatehash_statediff"].clone(),
},
services: Services {
globals: args.depend::<globals::Service>("globals"),
short: args.depend::<rooms::short::Service>("rooms::short"),
state: args.depend::<rooms::state::Service>("rooms::state"),
},
@@ -368,17 +370,17 @@ impl Service {
let state_hash =
utils::calculate_hash(new_state_ids_compressed.iter().map(|bytes| &bytes[..]));
let (new_shortstatehash, already_existed) = self
let existing = self
.services
.short
.get_or_create_shortstatehash(&state_hash)
.await;
.get_shortstatehash(&state_hash)
.await
.ok();
if Some(new_shortstatehash) == previous_shortstatehash {
return Ok(HashSetCompressStateEvent {
shortstatehash: new_shortstatehash,
..Default::default()
});
if let Some(shortstatehash) = existing
&& Some(shortstatehash) == previous_shortstatehash
{
return Ok(HashSetCompressStateEvent { shortstatehash, ..Default::default() });
}
let states_parents = if let Some(p) = previous_shortstatehash {
@@ -405,7 +407,10 @@ impl Service {
(new_state_ids_compressed, Arc::new(CompressedState::new()))
};
if !already_existed {
let new_shortstatehash = if let Some(existing) = existing {
existing
} else {
let new_shortstatehash = self.services.globals.next_count()?;
self.save_state_from_diff(
new_shortstatehash,
statediffnew.clone(),
@@ -413,7 +418,11 @@ impl Service {
2, // every state change is 2 event changes on average
states_parents,
)?;
}
self.services
.short
.set_shortstatehash(&state_hash, new_shortstatehash);
new_shortstatehash
};
Ok(HashSetCompressStateEvent {
shortstatehash: new_shortstatehash,
@@ -437,7 +446,10 @@ impl Service {
err!(Database("Failed to find StateDiff from short {shortstatehash:?}: {e}"))
})?;
let parent = utils::u64_from_bytes(&value[0..size_of::<u64>()])
let parent_bytes = value
.get(0..size_of::<u64>())
.ok_or_else(|| err!(Database("Truncated StateDiff for short {shortstatehash:?}")))?;
let parent = utils::u64_from_bytes(parent_bytes)
.ok()
.take_if(|parent| *parent != 0);
@@ -472,10 +484,14 @@ impl Service {
/// Stores a new state diff with a shortstatehash.
fn save_statediff(&self, shortstatehash: ShortStateHash, diff: &StateDiff) {
const STRIDE: usize = size_of::<ShortStateHash>();
let mut value = Vec::<u8>::with_capacity(
2_usize
.saturating_add(diff.added.len())
.saturating_add(diff.removed.len()),
1_usize
.saturating_add(usize::from(!diff.removed.is_empty()))
.saturating_add(diff.added.len().saturating_mul(2))
.saturating_add(diff.removed.len().saturating_mul(2))
.saturating_mul(STRIDE),
);
let parent = diff.parent.unwrap_or(0_u64);
+1 -1
View File
@@ -349,7 +349,7 @@ impl super::Service {
// Insert pdu
self.db
.append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2)
.append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2, pdu.origin_server_ts())
.await;
self.progress_extremities(pdu)
.await
+2 -1
View File
@@ -225,7 +225,8 @@ impl super::Service {
.into();
// Insert pdu
self.db.prepend_backfill_pdu(&pdu_id, &event_id, &value);
self.db
.prepend_backfill_pdu(&pdu_id, &event_id, &value, pdu.origin_server_ts());
drop(insert_lock);
if pdu.kind == TimelineEventType::RoomMessage {
+95 -1
View File
@@ -12,7 +12,9 @@ use database::{Database, Deserialized, Json, KeyVal, Map};
use futures::{
FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::select_ok, pin_mut,
};
use ruma::{CanonicalJsonObject, EventId, OwnedUserId, RoomId, api::Direction};
use ruma::{
CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedUserId, RoomId, api::Direction,
};
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue;
@@ -25,6 +27,7 @@ pub(super) struct Data {
pduid_pdu: Arc<Map>,
pduid_unredactedcontent: Arc<Map>,
roomid_lasttimelinecount: Arc<Map>,
roomts_pduid: Arc<Map>,
userroomid_highlightcount: Arc<Map>,
userroomid_notificationcount: Arc<Map>,
pub(super) db: Arc<Database>,
@@ -52,6 +55,7 @@ impl Data {
pduid_pdu: db["pduid_pdu"].clone(),
pduid_unredactedcontent: db["pduid_unredactedcontent"].clone(),
roomid_lasttimelinecount: db["roomid_lasttimelinecount"].clone(),
roomts_pduid: db["roomts_pduid"].clone(),
userroomid_highlightcount: db["userroomid_highlightcount"].clone(),
userroomid_notificationcount: db["userroomid_notificationcount"].clone(),
db: args.db.clone(),
@@ -213,10 +217,12 @@ impl Data {
room_id: &RoomId,
json: &CanonicalJsonObject,
count: PduCount,
index_ts: MilliSecondsSinceUnixEpoch,
) {
debug_assert!(matches!(count, PduCount::Normal(_)), "PduCount not Normal");
self.pduid_pdu.raw_put(pdu_id, Json(json));
self.roomts_pduid.insert(&roomts_key(pdu_id, index_ts), []);
self.eventid_pduid.insert(pdu.event_id.as_bytes(), pdu_id);
self.eventid_outlierpdu.remove(pdu.event_id.as_bytes());
self.roomid_lasttimelinecount
@@ -228,8 +234,10 @@ impl Data {
pdu_id: &RawPduId,
event_id: &EventId,
json: &CanonicalJsonObject,
index_ts: MilliSecondsSinceUnixEpoch,
) {
self.pduid_pdu.raw_put(pdu_id, Json(json));
self.roomts_pduid.insert(&roomts_key(pdu_id, index_ts), []);
self.eventid_pduid.insert(event_id, pdu_id);
self.eventid_outlierpdu.remove(event_id);
}
@@ -322,6 +330,49 @@ impl Data {
.try_flatten_stream()
}
pub(super) fn pdus_by_timestamp<'a>(
&'a self,
room_id: &'a RoomId,
timestamp: MilliSecondsSinceUnixEpoch,
dir: Direction,
) -> impl Stream<Item = Result<PdusIterItem>> + Send + 'a {
self.services
.short
.get_shortroomid(room_id)
.map_err(move |e| err!(Request(NotFound("Room {room_id:?} not found: {e:?}"))))
.map_ok(move |shortroomid| {
let seek = |shorteventid| {
roomts_key(&PduId { shortroomid, shorteventid }.into(), timestamp)
};
let keys = match dir {
| Direction::Forward => self
.roomts_pduid
.raw_keys_from(&seek(PduCount::min()))
.left_stream(),
| Direction::Backward => self
.roomts_pduid
.rev_raw_keys_from(&seek(PduCount::max()))
.right_stream(),
};
keys.ready_try_take_while(move |key| {
Ok(key.starts_with(&shortroomid.to_be_bytes()))
})
.map_ok(roomts_key_to_pdu_id)
.and_then(async move |pdu_id| {
Ok((pdu_id.pdu_count(), self.get_pdu_from_id(&pdu_id).await?))
})
})
.try_flatten_stream()
}
pub(super) async fn timestamp_index_ready(&self) -> bool {
self.db["global"]
.exists(TIMESTAMP_INDEX_MIGRATION)
.await
.is_ok()
}
fn from_json_slice((pdu_id, pdu): KeyVal<'_>) -> Result<PdusIterItem> {
let pdu_id: RawPduId = pdu_id.into();
@@ -376,9 +427,52 @@ impl Data {
}
}
pub const TIMESTAMP_INDEX_MIGRATION: &str = "populate_roomts_pduid";
#[must_use]
pub fn roomts_key(pdu_id: &RawPduId, ts: MilliSecondsSinceUnixEpoch) -> Vec<u8> {
let count = pdu_id.pdu_count().into_signed().cast_unsigned() ^ (1 << 63);
[pdu_id.shortroomid(), u64::from(ts.get()).to_be_bytes(), count.to_be_bytes()].concat()
}
fn roomts_key_to_pdu_id(key: &[u8]) -> RawPduId {
let shortroomid = u64::from_be_bytes(key[0..8].try_into().expect("roomts key shortroomid"));
let count = u64::from_be_bytes(key[16..24].try_into().expect("roomts key count")) ^ (1 << 63);
PduId {
shortroomid,
shorteventid: PduCount::from_signed(count.cast_signed()),
}
.into()
}
//TODO: this is an ABA
fn increment(db: &Arc<Map>, key: &[u8]) {
let old = db.get_blocking(key);
let new = utils::increment(old.ok().as_deref());
db.insert(key, new);
}
#[cfg(test)]
mod tests {
use ruma::uint;
use super::*;
#[test]
fn roomts_key_orders_by_ts_then_count() {
let ids = [
(PduCount::Normal(9), uint!(1)),
(PduCount::Backfilled(-5), uint!(2)),
(PduCount::Normal(3), uint!(2)),
(PduCount::Normal(1), uint!(3)),
]
.map(|(count, ts)| (RawPduId::from(PduId { shortroomid: 7, shorteventid: count }), ts));
let keys = ids.map(|(id, ts)| roomts_key(&id, MilliSecondsSinceUnixEpoch(ts)));
assert!(keys.is_sorted());
for ((id, _), key) in ids.iter().zip(&keys) {
assert_eq!(roomts_key_to_pdu_id(key), *id);
}
}
}
+17 -3
View File
@@ -21,8 +21,8 @@ use conduwuit_core::{
};
use futures::{Future, Stream, TryStreamExt, pin_mut};
use ruma::{
CanonicalJsonObject, EventId, OwnedEventId, OwnedRoomId, RoomId,
events::room::encrypted::Relation,
CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId,
api::Direction, events::room::encrypted::Relation,
};
use serde::Deserialize;
use serde_json::value::RawValue as RawJsonValue;
@@ -32,7 +32,10 @@ use tokio::{
};
use self::data::Data;
pub use self::{create::pdu_fits, data::PdusIterItem};
pub use self::{
create::pdu_fits,
data::{PdusIterItem, TIMESTAMP_INDEX_MIGRATION, roomts_key},
};
use crate::{
Dep, account_data, admin, appservice, config, globals, pusher, rooms, sending, server_keys,
sync, users,
@@ -307,6 +310,17 @@ impl Service {
self.pdus(room_id, None).ignore_err()
}
pub fn pdus_by_timestamp<'a>(
&'a self,
room_id: &'a RoomId,
timestamp: MilliSecondsSinceUnixEpoch,
dir: Direction,
) -> impl Stream<Item = Result<PdusIterItem>> + Send + 'a {
self.db.pdus_by_timestamp(room_id, timestamp, dir)
}
pub async fn timestamp_index_ready(&self) -> bool { self.db.timestamp_index_ready().await }
/// Reverse iteration starting after `until`.
#[tracing::instrument(skip(self), level = "debug")]
pub fn pdus_rev<'a>(
+73 -27
View File
@@ -3,6 +3,7 @@ use std::{fmt::Debug, sync::Arc};
use conduwuit::{
Error, Result, at, utils,
utils::{ReadyExt, stream::TryIgnore},
warn,
};
use database::{Database, Deserialized, Map};
use futures::{Stream, StreamExt};
@@ -169,6 +170,51 @@ impl Data {
})
}
/// Destinations with at least one queued request not yet in flight.
///
/// Seeks past each destination's key prefix so large per-destination
/// backlogs are skipped in O(destinations) seeks rather than scanning
/// every queued event.
pub(super) async fn queued_destinations(&self) -> Vec<Destination> {
let mut dests = Vec::new();
let mut cursor = Vec::new();
while let Some(key) = self
.servernameevent_data
.raw_keys_from(&cursor)
.ignore_err()
.next()
.await
{
match parse_destination(key) {
| Ok((dest, _)) => {
let prefix = dest.get_prefix();
dests.push(dest);
let Some(next) = next_prefix(&prefix) else {
break;
};
cursor = next;
},
| Err(e) => {
warn!(?key, "invalid queued request key: {e}");
cursor = key.to_vec();
cursor.push(0);
},
}
}
dests
}
/// Estimated number of requests waiting to be sent and in flight.
pub(crate) fn request_counts(&self) -> [(&'static str, Option<u64>); 2] {
[
("queued", &self.servernameevent_data),
("active", &self.servercurrentevent_data),
]
.map(|(state, map)| (state, map.property_integer(c"rocksdb.estimate-num-keys").ok()))
}
pub(super) fn set_latest_educount(&self, server_name: &ServerName, last_count: u64) {
self.servername_educount.raw_put(server_name, last_count);
}
@@ -182,9 +228,17 @@ impl Data {
}
}
fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> {
/// Smallest byte slice strictly greater than every key starting with `prefix`.
fn next_prefix(prefix: &[u8]) -> Option<Vec<u8>> {
let pos = prefix.iter().rposition(|&b| b < u8::MAX)?;
let mut next = prefix[..=pos].to_vec();
next[pos] = next[pos].saturating_add(1);
Some(next)
}
fn parse_destination(key: &[u8]) -> Result<(Destination, &[u8])> {
// Appservices start with a plus
Ok::<_, Error>(if key.starts_with(b"+") {
if key.starts_with(b"+") {
let mut parts = key[1..].splitn(2, |&b| b == 0xFF);
let server = parts.next().expect("splitn always returns one element");
@@ -196,14 +250,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se
Error::bad_database("Invalid server bytes in server_currenttransaction")
})?;
(
Destination::Appservice(server),
if value.is_empty() {
SendingEvent::Pdu(event.into())
} else {
SendingEvent::Edu(value.into())
},
)
Ok((Destination::Appservice(server), event))
} else if key.starts_with(b"$") {
let mut parts = key[1..].splitn(3, |&b| b == 0xFF);
@@ -223,15 +270,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se
.next()
.ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?;
(
Destination::Push(user_id, pushkey_string),
if value.is_empty() {
SendingEvent::Pdu(event.into())
} else {
// I'm pretty sure this should never be called
SendingEvent::Edu(value.into())
},
)
Ok((Destination::Push(user_id, pushkey_string), event))
} else {
let mut parts = key.splitn(2, |&b| b == 0xFF);
@@ -244,15 +283,22 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se
Error::bad_database("Invalid server bytes in server_currenttransaction")
})?;
(
Ok((
Destination::Federation(ServerName::parse(&server).map_err(|_| {
Error::bad_database("Invalid server string in server_currenttransaction")
})?),
if value.is_empty() {
SendingEvent::Pdu(event.into())
} else {
SendingEvent::Edu(value.into())
},
)
})
event,
))
}
}
fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> {
let (dest, event) = parse_destination(key)?;
let event = if value.is_empty() {
SendingEvent::Pdu(event.into())
} else {
SendingEvent::Edu(value.into())
};
Ok((dest, event))
}
+114 -24
View File
@@ -3,12 +3,19 @@ mod appservice;
mod data;
mod dest;
mod sender;
#[cfg(test)]
mod tests;
use std::{
collections::HashMap,
fmt::Debug,
hash::{DefaultHasher, Hash, Hasher},
iter::once,
sync::Arc,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::{Duration, Instant},
};
use async_trait::async_trait;
@@ -19,7 +26,7 @@ use conduwuit::{
utils::{ReadyExt, TryReadyExt, available_parallelism, math::usize_from_u64_truncated},
warn,
};
use futures::{FutureExt, Stream, StreamExt};
use futures::{FutureExt, Stream, StreamExt, stream::FuturesUnordered};
use ruma::{
OwnedServerName, RoomId, ServerName, UserId,
api::{
@@ -27,7 +34,7 @@ use ruma::{
federation::authentication::ServerSignatures, path_builder::PathBuilder,
},
};
use tokio::{task, task::JoinSet};
use tokio::{task, task::JoinSet, time::sleep};
use self::data::Data;
pub use self::{
@@ -49,6 +56,7 @@ pub struct Service {
server: Arc<Server>,
services: Services,
channels: Vec<(loole::Sender<Msg>, loole::Receiver<Msg>)>,
workers_alive: AtomicUsize,
}
struct Services {
@@ -87,6 +95,8 @@ pub type EduVec = SmallVec<[EduBuf; EDU_VEC_CAP]>;
const EDU_BUF_CAP: usize = 128;
const EDU_VEC_CAP: usize = 1;
const WORKER_RESTART_DELAY: Duration = Duration::from_millis(2500);
const WORKER_RESTART_DELAY_MAX: Duration = Duration::from_secs(30);
#[async_trait]
impl crate::Service for Service {
@@ -111,36 +121,67 @@ impl crate::Service for Service {
federation: args.depend::<federation::Service>("federation"),
},
channels: (0..num_senders).map(|_| loole::unbounded()).collect(),
workers_alive: AtomicUsize::new(0),
}))
}
async fn worker(self: Arc<Self>) -> Result {
let mut senders =
self.channels
.iter()
.enumerate()
.fold(JoinSet::new(), |mut joinset, (id, _)| {
let self_ = self.clone();
let worker = self_.sender(id);
let worker = if self.unconstrained() {
task::unconstrained(worker).boxed()
} else {
worker.boxed()
if self.server.config.startup_netburst {
self.dispatch_queued(None).await;
}
let num_senders = self.channels.len();
let mut senders = JoinSet::new();
let mut shards = HashMap::new();
let mut started = vec![Instant::now(); num_senders];
let mut failures = vec![0_u32; num_senders];
let mut restarts = FuturesUnordered::new();
for id in 0..num_senders {
self.spawn_sender(&mut senders, &mut shards, id, false);
}
loop {
tokio::select! {
Some(ret) = senders.join_next_with_id() => {
self.workers_alive.fetch_sub(1, Ordering::Relaxed);
let (task_id, panicked) = match &ret {
| Ok((task_id, _)) => (*task_id, false),
| Err(error) => (error.id(), error.is_panic()),
};
let shard = shards.remove(&task_id).expect("sender worker has a shard");
let runtime = self.server.runtime();
let _abort = joinset.spawn_on(worker, runtime);
joinset
});
if panicked {
self.server
.metrics
.instruments
.sender_panics
.add(1, &[KeyValue::new("scope", "worker")]);
}
while let Some(ret) = senders.join_next_with_id().await {
match ret {
| Ok((id, error)) => {
debug!(?id, ?error, "sender worker finished");
if self.channels[shard].1.is_closed() || !self.server.running() {
debug!(shard, ?ret, "sender worker finished");
continue;
}
// A worker that ran a while before failing starts over from
// the shortest delay.
failures[shard] = if started[shard].elapsed() > WORKER_RESTART_DELAY_MAX {
1
} else {
failures[shard].saturating_add(1)
};
let delay = restart_delay(failures[shard]);
error!(shard, ?ret, ?delay, "sender worker unexpectedly finished, restarting");
restarts.push(sleep(delay).map(move |()| shard));
},
| Err(error) => {
error!(id = ?error.id(), ?error, "sender worker failed");
Some(shard) = restarts.next() => {
if !self.channels[shard].1.is_closed() && self.server.running() {
started[shard] = Instant::now();
self.spawn_sender(&mut senders, &mut shards, shard, true);
}
},
() = self.server.until_shutdown(), if !restarts.is_empty() => restarts.clear(),
else => break,
}
}
@@ -161,6 +202,25 @@ impl crate::Service for Service {
}
impl Service {
fn spawn_sender(
self: &Arc<Self>,
senders: &mut JoinSet<Result>,
shards: &mut HashMap<task::Id, usize>,
id: usize,
restarted: bool,
) {
let worker = self.clone().sender(id, restarted);
let worker = if crate::Service::unconstrained(&**self) {
task::unconstrained(worker).boxed()
} else {
worker.boxed()
};
let handle = senders.spawn_on(worker, self.server.runtime());
shards.insert(handle.id(), id);
self.workers_alive.fetch_add(1, Ordering::Relaxed);
}
#[tracing::instrument(skip(self, pdu_id, user, pushkey), level = "debug")]
pub fn send_pdu_push(&self, pdu_id: &RawPduId, user: &UserId, pushkey: String) -> Result {
let dest = Destination::Push(user.to_owned(), pushkey);
@@ -480,10 +540,32 @@ impl Service {
sender.send(msg).map_err(|e| err!("{e}"))
}
/// Wakes workers for every destination that has unsent queued requests, so
/// a backlog with nothing in flight is drained without waiting for a new
/// event. Uses `SendingEvent::Flush` so a message racing with already-
/// buffered channel items cannot re-insert and duplicate a sent request.
async fn dispatch_queued(&self, shard: Option<usize>) {
for dest in self.db.queued_destinations().await {
let id = self.shard_id(&dest);
if shard.is_none_or(|shard| shard == id) {
self.channels[id]
.0
.send(Msg {
dest,
event: SendingEvent::Flush,
queue_id: Vec::new(),
})
.ok();
}
}
}
pub fn queue_depth(&self) -> usize {
self.channels.iter().map(|(sender, _)| sender.len()).sum()
}
pub fn workers_alive(&self) -> usize { self.workers_alive.load(Ordering::Relaxed) }
pub(super) fn shard_id(&self, dest: &Destination) -> usize {
if self.channels.len() <= 1 {
return 0;
@@ -519,3 +601,11 @@ fn num_senders(args: &crate::Args<'_>) -> usize {
worker_count.clamp(MIN_SENDERS, max_senders)
}
}
/// Delay before restarting a worker after its `failures`-th consecutive
/// failure, doubling each time.
fn restart_delay(failures: u32) -> Duration {
WORKER_RESTART_DELAY
.saturating_mul(2_u32.saturating_pow(failures.saturating_sub(1)))
.min(WORKER_RESTART_DELAY_MAX)
}
+177 -63
View File
@@ -1,6 +1,7 @@
use std::{
collections::{BTreeMap, HashMap, HashSet},
fmt::Debug,
panic::AssertUnwindSafe,
sync::{
Arc,
atomic::{AtomicU64, AtomicUsize, Ordering},
@@ -55,11 +56,17 @@ use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
use super::{Destination, EduBuf, EduVec, Msg, SendingEvent, Service, data::QueueItem};
#[cfg(test)]
mod tests;
#[derive(Debug)]
enum TransactionStatus {
Running,
Failed(u32, Instant), // number of times failed, time of last failure
Retrying(u32), // number of times failed
/// Number of times failed, time of last failure, and whether local backoff
/// applies even for federation destinations (e.g. after a local panic when
/// the remote was not marked unhealthy).
Failed(u32, Instant, bool),
Retrying(u32), // number of times failed
}
type SendingError = (Destination, Box<Error>);
@@ -78,12 +85,18 @@ pub const EDU_LIMIT: usize = 100;
impl Service {
#[tracing::instrument(skip(self), level = "debug")]
pub(super) async fn sender(self: Arc<Self>, id: usize) -> Result {
pub(super) async fn sender(self: Arc<Self>, id: usize, restarted: bool) -> Result {
let mut statuses: CurTransactionStatus = CurTransactionStatus::new();
let mut futures: SendingFutures<'_> = FuturesUnordered::new();
// The previous worker of this shard may have dropped requests it had
// taken from the channel.
if restarted {
self.dispatch_queued(Some(id)).await;
}
info!(shard = id, "Running startup netburst");
self.startup_netburst(id, &mut futures, &mut statuses)
self.startup_netburst(id, restarted, &mut futures, &mut statuses)
.boxed()
.await;
info!(shard = id, "Finished startup netburst");
@@ -142,7 +155,12 @@ impl Service {
) {
match response {
| Ok(dest) => self.handle_response_ok(&dest, futures, statuses).await,
// A bug on our side, not the remote's fault: retry with local
// backoff without marking the remote unhealthy.
| Err((dest, e)) if e.is_panic() =>
Self::handle_response_err(dest, statuses, &e, true),
| Err((dest, e)) => {
let mut local_backoff = false;
if let Destination::Federation(dest) = &dest {
if self.services.federation.should_mark_stale(&e)
|| e.status_code() == StatusCode::NOT_FOUND
@@ -153,22 +171,30 @@ impl Service {
} else if e.status_code() != StatusCode::OK {
debug!("{dest} is now unhealthy due to error response: {e:?}");
self.services.federation.hit_unhealthy(dest.clone(), None);
} else {
local_backoff = true;
}
}
Self::handle_response_err(dest, statuses, &e);
Self::handle_response_err(dest, statuses, &e, local_backoff);
},
}
}
/// Handles a response error, incrementing the backoff factor.
fn handle_response_err(dest: Destination, statuses: &mut CurTransactionStatus, er: &Error) {
fn handle_response_err(
dest: Destination,
statuses: &mut CurTransactionStatus,
er: &Error,
local_backoff: bool,
) {
debug!(dest = ?dest, "{er:?}");
let dest2 = dest.clone();
statuses.entry(dest).and_modify(|e| {
*e = match e {
| TransactionStatus::Running => TransactionStatus::Failed(1, Instant::now()),
| TransactionStatus::Running =>
TransactionStatus::Failed(1, Instant::now(), local_backoff),
| &mut TransactionStatus::Retrying(ref n) =>
TransactionStatus::Failed(n.saturating_add(1), Instant::now()),
TransactionStatus::Failed(n.saturating_add(1), Instant::now(), local_backoff),
| TransactionStatus::Failed(..) => {
panic!(
"Request to {dest2:?} that was not even running ({e:?}) failed: {er:?}"
@@ -274,7 +300,8 @@ impl Service {
}
/// Performs startup netburst, which sends any previously queued up but not
/// yet sent requests immediately.
/// yet sent requests immediately. A restarted worker always resends its
/// shard's requests in flight.
#[tracing::instrument(
name = "netburst",
level = "debug",
@@ -285,9 +312,11 @@ impl Service {
async fn startup_netburst<'a>(
&'a self,
id: usize,
restarted: bool,
futures: &mut SendingFutures<'a>,
statuses: &mut CurTransactionStatus,
) {
let delivering = restarted || self.server.config.startup_netburst;
let keep =
usize::try_from(self.server.config.startup_netburst_keep).unwrap_or(usize::MAX);
let mut txns = HashMap::<Destination, Vec<SendingEvent>>::new();
@@ -302,7 +331,7 @@ impl Service {
let over_budget =
self.server.config.startup_netburst_keep >= 0 && entry.len() >= keep;
if over_budget && !self.survives_netburst_trim(&event).await {
if over_budget && !self.survives_netburst_trim(&event, delivering).await {
warn!(
startup_netburst_keep = self.server.config.startup_netburst_keep,
queue_size = entry.len(),
@@ -315,8 +344,12 @@ impl Service {
}
}
if !delivering {
return;
}
for (dest, events) in txns {
if self.server.config.startup_netburst && !events.is_empty() {
if !events.is_empty() {
statuses.insert(dest.clone(), TransactionStatus::Running);
futures.push(self.send_events(dest, events));
}
@@ -324,10 +357,10 @@ impl Service {
}
/// Whether this event skips the netburst budget, which MSC4354 asks of
/// still-sticky events. Only netburst delivers this queue, so with it
/// disabled there is nothing to keep the event for.
async fn survives_netburst_trim(&self, event: &SendingEvent) -> bool {
if !self.server.config.startup_netburst {
/// still-sticky events. Only a delivering netburst drains this queue, so
/// when nothing will deliver it there is nothing to keep the event for.
async fn survives_netburst_trim(&self, event: &SendingEvent, delivering: bool) -> bool {
if !delivering {
return false;
}
@@ -425,12 +458,17 @@ impl Service {
allow = false; // already running
trace!("Transaction is already running for {dest:?}");
},
| TransactionStatus::Failed(tries, _) => {
if allow {
| TransactionStatus::Failed(tries, time, local_backoff) => {
if *local_backoff
&& time.elapsed() < self.server.config.sender_retry_backoff(*tries)
{
allow = false;
trace!("{dest:?} is in local backoff, refusing send");
} else {
*e = TransactionStatus::Retrying(*tries);
trace!("Previous transaction failed for {dest:?} ({e:?}), will retry");
retry = true;
}
retry = true;
},
});
@@ -449,7 +487,7 @@ impl Service {
statuses
.entry(dest.clone())
.and_modify(|e| match e {
| TransactionStatus::Failed(tries, time) => {
| TransactionStatus::Failed(tries, time, _) => {
let retry_after = self.server.config.sender_retry_backoff(*tries);
if time.elapsed() < retry_after {
debug_warn!("Not retrying destination for another {retry_after:?}");
@@ -484,13 +522,6 @@ impl Service {
let device_changes =
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
.server
.config
@@ -498,11 +529,20 @@ impl Service {
.then(|| self.select_edus_presence(server_name, batch, &max_edu_count))
.into();
let (device_changes, receipts, presence) = join!(device_changes, receipts, presence);
let (device_changes, presence) = join!(device_changes, presence);
let mut events = device_changes;
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
@@ -578,9 +618,11 @@ impl Service {
server_name: &ServerName,
since: (u64, u64),
max_edu_count: &AtomicU64,
) -> Option<EduBuf> {
edu_limit: usize,
) -> EduVec {
let num = AtomicUsize::new(0);
let receipts: BTreeMap<OwnedRoomId, ReceiptMap> = self
let deferred = AtomicU64::new(u64::MAX);
let rooms: Vec<_> = self
.services
.state_cache
.server_rooms(server_name)
@@ -589,33 +631,54 @@ impl Service {
return None;
}
let receipt_map = self
.select_edus_receipts_room(&room_id, since, max_edu_count, &num)
let maps = self
.select_edus_receipts_room(
&room_id,
since,
max_edu_count,
&num,
edu_limit,
&deferred,
)
.await;
(!receipt_map.read.is_empty()).then_some((room_id, receipt_map))
(!maps.is_empty()).then_some((room_id, maps))
})
.collect()
.await;
if receipts.is_empty() {
return None;
// the next transaction starts at the first receipt that did not fit
max_edu_count
.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));
}
}
let receipt_content = Edu::Receipt(ReceiptContent::new(receipts));
contents
.into_iter()
.map(|content| {
let edu = Edu::Receipt(ReceiptContent::new(content));
let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &receipt_content)
.expect("Failed to serialize Receipt EDU to JSON vec");
Some(buf)
let mut buf = EduBuf::new();
serde_json::to_writer(&mut buf, &edu)
.expect("Failed to serialize Receipt EDU to JSON vec");
buf
})
.collect()
}
/// Look for read receipts in this room
#[tracing::instrument(
name = "receipts",
level = "trace",
skip(self, since, max_edu_count, num)
skip(self, since, max_edu_count, num, deferred)
)]
async fn select_edus_receipts_room(
&self,
@@ -623,14 +686,16 @@ impl Service {
since: (u64, u64),
max_edu_count: &AtomicU64,
num: &AtomicUsize,
) -> ReceiptMap {
edu_limit: usize,
deferred: &AtomicU64,
) -> Vec<BTreeMap<OwnedUserId, ReceiptData>> {
let receipts = self
.services
.read_receipt
.readreceipts_since(room_id, Some(since.0));
pin_mut!(receipts);
let mut read = BTreeMap::<OwnedUserId, ReceiptData>::new();
let mut maps = Vec::new();
while let Some((user_id, count, read_receipt)) = receipts.next().await {
if count > since.1 {
break;
@@ -666,14 +731,20 @@ impl Service {
let receipt_data = ReceiptData::new(receipt, vec![event_id]);
if read.insert(user_id, receipt_data).is_none() {
if num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT {
break;
}
let Some(index) = add_receipt(&mut maps, user_id, receipt_data, edu_limit) else {
deferred.fetch_min(count, Ordering::Relaxed);
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;
}
}
ReceiptMap::new(read)
maps
}
/// Look for presence
@@ -772,6 +843,7 @@ impl Service {
});
let start = Instant::now();
let panic_dest = dest.clone();
let send = match dest {
| Destination::Federation(server) =>
self.send_events_dest_federation(server, events).boxed(),
@@ -780,24 +852,42 @@ impl Service {
self.send_events_dest_push(user_id, pushkey, events).boxed(),
};
send.inspect(move |result| {
let instruments = &self.server.metrics.instruments;
let outcome =
KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" });
instruments
.sender_transaction_duration
.record(start.elapsed().as_secs_f64(), &[destination.clone(), outcome.clone()]);
for (kind, count) in [("pdu", pdus), ("edu", edus)] {
if count > 0 {
instruments.sender_events.add(count, &[
AssertUnwindSafe(send)
.catch_unwind()
.map(move |result| {
result.unwrap_or_else(|panic| {
let error = Error::from_panic(panic);
error!(dest = ?panic_dest, ?error, "Panicked while sending transaction");
self.server
.metrics
.instruments
.sender_panics
.add(1, &[KeyValue::new("scope", "transaction")]);
Err((panic_dest, Box::new(error)))
})
})
.inspect(move |result| {
let instruments = &self.server.metrics.instruments;
let outcome =
KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" });
instruments
.sender_transaction_duration
.record(start.elapsed().as_secs_f64(), &[
destination.clone(),
KeyValue::new("kind", kind),
outcome.clone(),
]);
for (kind, count) in [("pdu", pdus), ("edu", edus)] {
if count > 0 {
instruments.sender_events.add(count, &[
destination.clone(),
KeyValue::new("kind", kind),
outcome.clone(),
]);
}
}
}
})
.boxed()
})
.boxed()
}
#[tracing::instrument(
@@ -1053,3 +1143,27 @@ 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)
}
+217
View File
@@ -0,0 +1,217 @@
use std::{collections::BTreeMap, iter::once};
use conduwuit::{
Error,
matrix::{PartialPdu, pdu::sticky},
};
use futures::{StreamExt, stream::FuturesUnordered};
use ruma::{
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 super::{CurTransactionStatus, TransactionStatus, add_receipt};
use crate::{
sending::{Destination, EduBuf, SendingEvent},
test_utils::{test_services, test_services_with},
};
#[tokio::test]
async fn panicked_transaction_is_kept_for_retry_without_blaming_the_remote() {
let (services, path, _database) = test_services().await;
let sending = &services.sending;
let server = server_name!("remote.example");
let dest = Destination::Federation(server.to_owned());
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
sending.db.queue_requests(once((&event, &dest)));
let in_flight: Vec<_> = sending.db.queued_requests(&dest).collect().await;
sending.db.mark_as_active(in_flight.iter());
let mut futures = FuturesUnordered::new();
let mut statuses = CurTransactionStatus::from([(dest.clone(), TransactionStatus::Running)]);
let panic = Error::from_panic(Box::new("boom"));
sending
.handle_response(Err((dest.clone(), Box::new(panic))), &mut futures, &mut statuses)
.await;
let active: Vec<_> = sending
.db
.active_requests_for(&dest)
.map(|(key, _)| key)
.collect()
.await;
let retry_after = sending.services.federation.retry_after(server);
let sending_next = futures.len();
let failed = matches!(statuses.get(&dest), Some(TransactionStatus::Failed(1, _, true)));
let immediate_retry = sending.should_attempt_send(&dest, &mut statuses).unwrap();
drop(futures);
drop(services);
std::fs::remove_dir_all(path).unwrap();
assert_eq!(
active,
in_flight
.into_iter()
.map(|(key, _)| key)
.collect::<Vec<_>>()
);
assert_eq!(sending_next, 0);
assert!(failed);
assert_eq!(immediate_retry, (false, false));
assert_eq!(retry_after, None);
}
#[tokio::test]
async fn restarted_worker_resends_trimmed_in_flight_requests() {
let (services, path, _database) =
test_services_with(json!({ "startup_netburst_keep": 1 })).await;
let sending = &services.sending;
let dest = Destination::Federation(server_name!("remote.example").to_owned());
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
for _ in 0..3 {
sending.db.queue_requests(once((&event, &dest)));
}
let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await;
sending.db.mark_as_active(queued.iter());
let id = sending.shard_id(&dest);
let mut futures = FuturesUnordered::new();
let mut statuses = CurTransactionStatus::new();
sending
.startup_netburst(id, true, &mut futures, &mut statuses)
.await;
let active = sending.db.active_requests_for(&dest).count().await;
let sending_now = futures.len();
drop(futures);
drop(services);
std::fs::remove_dir_all(path).unwrap();
assert_eq!(active, 1);
assert_eq!(sending_now, 1);
}
#[tokio::test]
async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled() {
let (services, path, _database) =
test_services_with(json!({ "startup_netburst": false, "startup_netburst_keep": 0 }))
.await;
let alice = UserId::parse("@alice:test.example").unwrap();
let bootstrap = services
.rooms
.state
.mutex
.lock("!bootstrap:test.example")
.await;
let create_id = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
event_type: "m.room.create".into(),
content: to_raw_value(&json!({ "room_version": "12" })).unwrap(),
state_key: Some("".into()),
..Default::default()
},
&alice,
None,
&bootstrap,
)
.await
.unwrap();
drop(bootstrap);
let room = RoomId::parse(create_id.as_str().replacen('$', "!", 1)).unwrap();
let lock = services.rooms.state.mutex.lock(&room).await;
services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
event_type: "m.room.member".into(),
content: to_raw_value(&json!({ "membership": "join" })).unwrap(),
state_key: Some(alice.as_str().into()),
..Default::default()
},
&alice,
Some(&room),
&lock,
)
.await
.unwrap();
let sticky_id = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
event_type: "m.room.message".into(),
content: to_raw_value(&json!({ "msgtype": "m.text", "body": "sticky" })).unwrap(),
sticky: Some(sticky::object(StickyDurationMs::new_clamped(600_000_u32))),
..Default::default()
},
&alice,
Some(&room),
&lock,
)
.await
.unwrap();
drop(lock);
let raw_pdu_id = services
.rooms
.timeline
.get_pdu_id(&sticky_id)
.await
.unwrap();
let sending = &services.sending;
let dest = Destination::Federation(server_name!("remote.example").to_owned());
let event = SendingEvent::Pdu(raw_pdu_id);
sending.db.queue_requests(once((&event, &dest)));
let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await;
sending.db.mark_as_active(queued.iter());
let id = sending.shard_id(&dest);
let mut futures = FuturesUnordered::new();
let mut statuses = CurTransactionStatus::new();
sending
.startup_netburst(id, true, &mut futures, &mut statuses)
.await;
let active_after_restart = sending.db.active_requests_for(&dest).count().await;
let sending_after_restart = futures.len();
drop(futures);
let mut futures = FuturesUnordered::new();
let mut statuses = CurTransactionStatus::new();
sending
.startup_netburst(id, false, &mut futures, &mut statuses)
.await;
let active_after_startup = sending.db.active_requests_for(&dest).count().await;
let sending_after_startup = futures.len();
drop(futures);
drop(services);
std::fs::remove_dir_all(path).unwrap();
assert_eq!(active_after_restart, 1);
assert_eq!(sending_after_restart, 1);
assert_eq!(active_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]);
}
+41
View File
@@ -0,0 +1,41 @@
use std::{iter::once, time::Duration};
use futures::StreamExt;
use ruma::server_name;
use super::{Destination, EduBuf, SendingEvent, restart_delay};
use crate::test_utils::test_services;
#[tokio::test]
async fn queued_destinations_lists_each_destination_with_unsent_requests() {
let (services, path, _database) = test_services().await;
let db = &services.sending.db;
let queued_sub = Destination::Federation(server_name!("queued.example.org").to_owned());
let queued = Destination::Federation(server_name!("queued.example").to_owned());
let appservice = Destination::Appservice("bridge".to_owned());
let active = Destination::Federation(server_name!("active.example").to_owned());
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
db.queue_requests(once((&event, &queued)));
db.queue_requests(once((&event, &queued)));
db.queue_requests(once((&event, &queued_sub)));
db.queue_requests(once((&event, &appservice)));
db.queue_requests(once((&event, &active)));
let in_flight: Vec<_> = db.queued_requests(&active).collect().await;
db.mark_as_active(in_flight.iter());
let dests = db.queued_destinations().await;
drop(services);
std::fs::remove_dir_all(path).unwrap();
assert_eq!(dests, [appservice, queued_sub, queued]);
}
#[test]
fn restart_delay_doubles_up_to_the_cap() {
assert_eq!(restart_delay(1), Duration::from_millis(2500));
assert_eq!(restart_delay(2), Duration::from_secs(5));
assert_eq!(restart_delay(4), Duration::from_secs(20));
assert_eq!(restart_delay(5), Duration::from_secs(30));
assert_eq!(restart_delay(u32::MAX), Duration::from_secs(30));
}
+2 -2
View File
@@ -158,7 +158,7 @@ impl super::Service {
if let Some(server_keys) = self.get_signing_key(origin, key_id).await
&& let Some(key) =
verify_key_from_response(key_id, &server_keys, min_valid_ts)
verify_key_from_response(key_id, &server_keys.parsed, min_valid_ts)
{
trace!(%origin, %key_id, ?min_valid_ts, "Verify key exists locally");
Self::track_one_result(
@@ -387,7 +387,7 @@ impl super::Service {
if let Some(vk) = self
.get_signing_key(origin, key_id)
.await
.and_then(|ssk| verify_key_from_response(key_id, &ssk, min_valid_ts))
.and_then(|ssk| verify_key_from_response(key_id, &ssk.parsed, min_valid_ts))
{
trace!("Found verify key locally");
return Some(vk);
+139 -9
View File
@@ -5,32 +5,43 @@ mod sign;
mod util;
mod verify;
use std::{collections::BTreeMap, sync::Arc};
use std::{
collections::{BTreeMap, HashMap},
sync::Arc,
time::{Duration, Instant},
};
use assign::assign;
use async_trait::async_trait;
use conduwuit::{
Result, Server,
utils::{IterStream, ReadyExt, stream::TryIgnore},
Result, Server, SyncRwLock, debug_info,
utils::{IterStream, ReadyExt, stream::TryIgnore, timepoint_from_now, to_canonical_object},
};
use database::{Deserialized, Ignore, Interfix, Json, Map};
use futures::{Stream, StreamExt};
pub use request::in_one_week;
use ruma::{
CanonicalJsonObject, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName,
ServerSigningKeyId,
api::federation::discovery::{ServerSigningKeys, VerifyKey},
CanonicalJsonObject, MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId,
ServerName, ServerSigningKeyId,
api::federation::discovery::{OldVerifyKey, ServerSigningKeys, VerifyKey},
room_version_rules::RoomVersionRules,
serde::Raw,
signatures::{Ed25519KeyPair, PublicKeyMap, PublicKeySet},
};
use serde_json::value::to_raw_value;
use verify::IncomingServerKeys;
pub use verify::strip_extraneous_signatures;
use crate::{Dep, globals, sending, server_keys::util::required_keys};
const VALID_UNTIL_TS_DURATION: Duration = Duration::from_hours(12);
pub struct Service {
keypair: Box<Ed25519KeyPair>,
verify_keys: VerifyKeys,
services: Services,
db: Data,
last_lookup: SyncRwLock<HashMap<OwnedServerName, Instant>>,
}
struct Services {
@@ -47,6 +58,7 @@ pub type VerifyKeys = BTreeMap<OwnedServerSigningKeyId, VerifyKey>;
pub type PubKeyMap = PublicKeyMap;
pub type PubKeys = PublicKeySet;
#[async_trait]
impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
let (keypair, verify_keys) = keypair::init(args.db)?;
@@ -63,9 +75,12 @@ impl crate::Service for Service {
db: Data {
servernamekeyid_response: args.db["servernamekeyid_response"].clone(),
},
last_lookup: SyncRwLock::new(HashMap::new()),
}))
}
async fn clear_cache(&self) { self.last_lookup.write().clear(); }
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
}
@@ -133,7 +148,9 @@ impl Service {
key_id: &ServerSigningKeyId,
minimum_valid_ts: MilliSecondsSinceUnixEpoch,
) -> bool {
let Some(keys) = self.get_signing_key(origin, key_id).await else {
let Some(IncomingServerKeys { parsed: keys, .. }) =
self.get_signing_key(origin, key_id).await
else {
// We have no keys for this server
return false;
};
@@ -161,12 +178,13 @@ impl Service {
&self,
origin: &ServerName,
key_id: &ServerSigningKeyId,
) -> Option<ServerSigningKeys> {
) -> Option<IncomingServerKeys> {
self.db
.servernamekeyid_response
.qry(&(origin.as_str(), key_id.as_str()))
.await
.deserialized::<ServerSigningKeys>()
.deserialized::<Raw<ServerSigningKeys>>()
.and_then(|r| r.try_into().map_err(Into::into))
.ok()
}
@@ -188,6 +206,8 @@ impl Service {
}
/// Returns the stored server signing keys responses for the origin.
///
/// Does not imply that the stored responses are still in-date.
pub fn signing_keys_for<'a>(
&'a self,
origin: &'a ServerName,
@@ -199,4 +219,114 @@ impl Service {
.map(|(_, v): (Ignore, Raw<ServerSigningKeys>)| v.try_into().map_err(Into::into))
.ignore_err()
}
/// Determines if the server may contact the origin server to fetch keys
/// when acting as a notary server. This limits origin lookups to once per
/// minute, which prevents amplification attacks.
#[must_use]
pub fn origin_not_contacted_recently(&self, server_name: &ServerName) -> bool {
if server_name == self.services.server.name {
// We always intercept origin requests to us with
// build_server_keys_response, so this is equivalent to
// calling `/_matrix/key/v2/server`.
return true;
}
self.last_lookup
.read()
.get(server_name)
.is_none_or(|last| last.elapsed() >= Duration::from_mins(1))
}
/// Generates a signing key response to serve to `/_matrix/key/v2/server`.
pub async fn build_server_keys_response(&self) -> Result<Raw<ServerSigningKeys>> {
let verify_keys = BTreeMap::from([self.active_verify_key()]);
let old_verify_keys = match &self.services.server.config.old_verify_keys {
| Some(old_verify_keys) => old_verify_keys.to_owned(),
| None => self.discover_old_signing_keys().await,
};
let valid_until_ts = timepoint_from_now(VALID_UNTIL_TS_DURATION)
.ok()
.and_then(MilliSecondsSinceUnixEpoch::from_system_time)
.expect("key validity period must be before the heat death of the universe");
let server_keys = assign!(
ServerSigningKeys::new(self.services.server.name.clone(), valid_until_ts),
{verify_keys, old_verify_keys}
);
let mut canonical_obj = to_canonical_object(&server_keys)?;
self.sign_json(&mut canonical_obj)
.and_then(|()| to_raw_value(&canonical_obj).map_err(Into::into))
.map(Raw::from_json)
}
async fn discover_old_signing_keys(&self) -> BTreeMap<OwnedServerSigningKeyId, OldVerifyKey> {
let now = MilliSecondsSinceUnixEpoch::now();
let mut keys = self.signing_keys_for(&self.services.server.name);
let mut old_keys = BTreeMap::new();
while let Some(resp) = keys.next().await {
// We need to verify that this response is still trusted based on
// the current configuration. It's possible we got this response
// from a notary who we no longer trust.
if resp.parsed.valid_until_ts > in_one_week() || resp.parsed.valid_until_ts < now {
continue;
}
let trusted = self
.services
.server
.config
.trusted_servers
.iter()
.any(|notary| {
Self::verify_server_keys_response(
&resp,
Some((notary.server_name(), notary.verify_keys())),
)
.is_ok()
});
if !trusted {
continue;
}
for (old_key_id, old_key) in resp.parsed.old_verify_keys {
if old_key.expired_ts > resp.parsed.valid_until_ts {
// This key expired in the future which is probably illegal
continue;
}
old_keys
.entry(old_key_id)
.and_modify(|current_old_key: &mut OldVerifyKey| {
// Use the lowest expiry timestamp
if current_old_key.expired_ts < old_key.expired_ts {
*current_old_key = old_key.clone();
}
})
.or_insert(old_key);
}
}
old_keys
}
/// Canonicalize and sign another server's signing keys.
pub fn self_sign_signing_keys(
&self,
remote_server: &ServerName,
remote_keys: &Raw<ServerSigningKeys>,
) -> Result<Raw<ServerSigningKeys>> {
let this_server = self.services.globals.server_name();
let mut canonical = to_canonical_object(remote_keys)?;
if remote_server == this_server {
debug_info!(
%remote_server,
object=?remote_keys,
"Refusing to sign our own signing keys response (should already be signed)"
);
} else {
self.sign_json(&mut canonical)?;
strip_extraneous_signatures(&mut canonical, remote_server, &[this_server]);
}
Ok(Raw::<ServerSigningKeys>::from_json(to_raw_value(&canonical)?))
}
}
+18 -1
View File
@@ -1,4 +1,4 @@
use std::collections::BTreeMap;
use std::{collections::BTreeMap, time::Instant};
use conduwuit::{Err, Result, trace, utils::millis_since_unix_epoch, warn};
use ruma::{
@@ -31,6 +31,23 @@ impl super::Service {
) -> Result<IncomingServerKeys> {
use get_server_keys::v2::Request;
if target == self.services.server.name {
return self
.build_server_keys_response()
.await
.and_then(|r| r.try_into().map_err(Into::into));
}
// N.B. The "last lookup" is written before the request is actually made
// to prevent concurrent notary requests from spawning... concurrent
// origin requests, especially if the origin is slow.
// This has the downside that, if the origin is temporarily unreachable
// (including if we're backing off from it), the notary might take an
// additional minute to recover compared to the rest of the server. This
// is deemed acceptable.
self.last_lookup
.write()
.insert(target.clone(), Instant::now());
let raw_server_key = self
.services
.sending
+35 -15
View File
@@ -2,7 +2,8 @@ use conduwuit::{
Err, Result, matrix::event::gen_event_id_canonical_json, trace, utils::to_canonical_object,
};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, ServerName, SigningKeyAlgorithm,
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, ServerName, ServerSigningKeyId,
SigningKeyAlgorithm,
api::federation::discovery::ServerSigningKeys,
room_version_rules::RoomVersionRules,
serde::{Base64, Raw, base64::Standard},
@@ -35,6 +36,17 @@ impl TryFrom<&Raw<ServerSigningKeys>> for IncomingServerKeys {
}
}
impl IncomingServerKeys {
/// Returns an iterator of every key ID in this key response.
pub fn all_key_ids(&self) -> impl Iterator<Item = &ServerSigningKeyId> {
self.parsed
.verify_keys
.keys()
.chain(self.parsed.old_verify_keys.keys())
.map(|key| &**key)
}
}
impl super::Service {
/// Validates the incoming event only using locally known verification keys.
/// Inserts the calculated event ID into the event_id field upon success.
@@ -107,7 +119,7 @@ impl super::Service {
pubkey_map.insert(incoming.parsed.server_name.to_string(), set);
let mut canonical = to_canonical_object(&incoming.raw)?;
Self::strip_extraneous_signatures(&mut canonical, &incoming.parsed.server_name, &[]);
strip_extraneous_signatures(&mut canonical, &incoming.parsed.server_name, &[]);
ruma::signatures::verify_json(&pubkey_map, &canonical).map_err(Into::into)
}
@@ -163,22 +175,30 @@ impl super::Service {
"No valid signature from {notary_name} present on signing keys response"
)))
}
}
fn strip_extraneous_signatures(
canonical: &mut CanonicalJsonObject,
origin: &ServerName,
notaries: &[&ServerName],
) {
canonical.entry("signatures".to_owned()).and_modify(|sigs| {
sigs.as_object_mut().map(|s| {
s.retain(|server_name, _| {
let Ok(server_name) = ServerName::parse(server_name) else { return false };
origin == server_name || notaries.iter().any(|ns| *ns == server_name)
});
Some(s)
/// Removes extraneous signatures from the signature map. This is done to avoid
/// leaking the signatures from notaries we've used, in case the response is
/// being forwarded to a third party. This also reduces the risk of accidentally
/// trusting a notary's signature as the origin's signature if `notaries` is
/// empty.
///
/// Infallible & mutates the original canonical JSON object. Signatures by
/// server names that cannot be parsed are always removed.
pub fn strip_extraneous_signatures(
canonical: &mut CanonicalJsonObject,
origin: &ServerName,
notaries: &[&ServerName],
) {
canonical.entry("signatures".to_owned()).and_modify(|sigs| {
sigs.as_object_mut().map(|s| {
s.retain(|server_name, _| {
let Ok(server_name) = ServerName::parse(server_name) else { return false };
origin == server_name || notaries.iter().any(|ns| *ns == server_name)
});
Some(s)
});
}
});
}
#[cfg(test)]
+52
View File
@@ -0,0 +1,52 @@
use std::{path::PathBuf, sync::Arc};
use conduwuit::{
Config, Server,
log::{Log, LogLevelReloadHandles},
metrics::Metrics,
};
use serde_json::json;
use tokio::sync::{Mutex, MutexGuard};
/// RocksDB's default `Env` is shared by the whole process and closing a
/// database stops its background threads, so tests must not keep databases
/// open in parallel. Hold the returned guard until the services are dropped.
static DATABASE: Mutex<()> = Mutex::const_new(());
type TestServices = (Arc<crate::Services>, PathBuf, MutexGuard<'static, ()>);
pub(crate) async fn test_services() -> TestServices { test_services_with(json!({})).await }
pub(crate) async fn test_services_with(overrides: serde_json::Value) -> TestServices {
let guard = DATABASE.lock().await;
let _ = rustls::crypto::ring::default_provider().install_default();
let path = std::env::temp_dir()
.join(format!("continuwuity-shared-state-{:016x}", rand::random::<u64>()));
std::fs::create_dir(&path).unwrap();
let mut config = json!({
"server_name": "test.example",
"database_path": path,
"db_cache_capacity_mb": 16.0,
"rocksdb_write_buffer_capacity_mb": 4.0,
"allow_local_presence": false,
"dns_servers": ["127.0.0.1"],
"allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true
});
config
.as_object_mut()
.unwrap()
.extend(overrides.as_object().unwrap().clone());
let config: Config = serde_json::from_value(config).unwrap();
let runtime = tokio::runtime::Handle::current();
let server = Arc::new(Server::new(
config,
Some(runtime.clone()),
Log {
reload: LogLevelReloadHandles::default(),
capture: Arc::default(),
},
Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None),
));
let services = crate::Services::build(server).await.unwrap();
(services, path, guard)
}
+2 -2
View File
@@ -348,8 +348,8 @@ impl Service {
.compatibility_mode()
.uiaa_available()
{
return Err!(Request(Unrecognized(
"User-interactive authentication is unavailable on this server"
return Err!(Request(Forbidden(
"User-interactive authentication is not available on this server."
)));
}