mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-27 10:57:34 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9121910398 | ||
|
|
0730b7b251 | ||
|
|
8bda2d693b | ||
|
|
c63af7318a | ||
|
|
3c10b8c0a5 | ||
|
|
4db3440e15 | ||
|
|
b4d06e689e | ||
|
|
5214ce3295 | ||
|
|
17b5412955 | ||
|
|
e9d0baf762 | ||
|
|
5c5f07fda0 | ||
|
|
d7b88026ca | ||
|
|
94a1d6d5b8 |
No files matched your search
@@ -56,7 +56,7 @@ repos:
|
|||||||
hooks:
|
hooks:
|
||||||
- id: cargo-clippy
|
- id: cargo-clippy
|
||||||
name: cargo clippy
|
name: cargo clippy
|
||||||
entry: cargo clippy -- -D warnings
|
entry: cargo clippy --
|
||||||
language: system
|
language: system
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
types: [ rust ]
|
types: [ rust ]
|
||||||
|
|||||||
Generated
+63
-30
@@ -485,19 +485,20 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bindgen"
|
name = "bindgen"
|
||||||
version = "0.73.2"
|
version = "0.72.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa"
|
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags",
|
"bitflags",
|
||||||
"cexpr",
|
"cexpr",
|
||||||
"clang-sys",
|
"clang-sys",
|
||||||
|
"itertools 0.13.0",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"regex",
|
"regex",
|
||||||
"rustc-hash",
|
"rustc-hash",
|
||||||
"shlex",
|
"shlex 1.3.0",
|
||||||
"syn 3.0.10",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -683,7 +684,7 @@ dependencies = [
|
|||||||
"find-msvc-tools",
|
"find-msvc-tools",
|
||||||
"jobserver",
|
"jobserver",
|
||||||
"libc",
|
"libc",
|
||||||
"shlex",
|
"shlex 2.0.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -873,9 +874,13 @@ dependencies = [
|
|||||||
name = "conduwuit"
|
name = "conduwuit"
|
||||||
version = "26.11.0-alpha.2"
|
version = "26.11.0-alpha.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"aws-lc-rs",
|
||||||
"clap",
|
"clap",
|
||||||
|
"conduwuit_admin",
|
||||||
|
"conduwuit_api",
|
||||||
"conduwuit_build_metadata",
|
"conduwuit_build_metadata",
|
||||||
"conduwuit_core",
|
"conduwuit_core",
|
||||||
|
"conduwuit_database",
|
||||||
"conduwuit_macros",
|
"conduwuit_macros",
|
||||||
"conduwuit_router",
|
"conduwuit_router",
|
||||||
"conduwuit_service",
|
"conduwuit_service",
|
||||||
@@ -883,6 +888,7 @@ dependencies = [
|
|||||||
"const-str",
|
"const-str",
|
||||||
"ctor",
|
"ctor",
|
||||||
"dtor",
|
"dtor",
|
||||||
|
"log",
|
||||||
"opentelemetry",
|
"opentelemetry",
|
||||||
"opentelemetry-otlp",
|
"opentelemetry-otlp",
|
||||||
"opentelemetry-prometheus",
|
"opentelemetry-prometheus",
|
||||||
@@ -890,10 +896,13 @@ dependencies = [
|
|||||||
"opentelemetry_sdk",
|
"opentelemetry_sdk",
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
"prometheus",
|
"prometheus",
|
||||||
|
"reqwest 0.13.5",
|
||||||
"rustls",
|
"rustls",
|
||||||
"sentry",
|
"sentry",
|
||||||
|
"sentry-tower",
|
||||||
"sentry-tracing",
|
"sentry-tracing",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-metrics",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-flame",
|
"tracing-flame",
|
||||||
"tracing-journald",
|
"tracing-journald",
|
||||||
@@ -1134,7 +1143,6 @@ dependencies = [
|
|||||||
"p256 0.14.0",
|
"p256 0.14.0",
|
||||||
"rand 0.10.4",
|
"rand 0.10.4",
|
||||||
"regex",
|
"regex",
|
||||||
"reqwest 0.12.28",
|
|
||||||
"reqwest 0.13.5",
|
"reqwest 0.13.5",
|
||||||
"resolvematrix",
|
"resolvematrix",
|
||||||
"ruma",
|
"ruma",
|
||||||
@@ -2712,10 +2720,10 @@ dependencies = [
|
|||||||
"hyper",
|
"hyper",
|
||||||
"hyper-util",
|
"hyper-util",
|
||||||
"rustls",
|
"rustls",
|
||||||
"rustls-native-certs",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
|
"webpki-roots",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2989,6 +2997,15 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itertools"
|
||||||
|
version = "0.13.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
|
||||||
|
dependencies = [
|
||||||
|
"either",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itertools"
|
name = "itertools"
|
||||||
version = "0.14.0"
|
version = "0.14.0"
|
||||||
@@ -3259,9 +3276,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libz-sys"
|
name = "libz-sys"
|
||||||
version = "1.1.32"
|
version = "1.1.29"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "69965d2409bff8c8cea3829009fff66a86f05a0570656552ef70f616e8e4bd85"
|
checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
@@ -4180,6 +4197,12 @@ dependencies = [
|
|||||||
"phc",
|
"phc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "paste"
|
||||||
|
version = "1.0.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pear"
|
name = "pear"
|
||||||
version = "0.2.9"
|
version = "0.2.9"
|
||||||
@@ -4843,8 +4866,8 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
|
"quinn",
|
||||||
"rustls",
|
"rustls",
|
||||||
"rustls-native-certs",
|
|
||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -4859,6 +4882,7 @@ dependencies = [
|
|||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
"wasm-bindgen-futures",
|
"wasm-bindgen-futures",
|
||||||
"web-sys",
|
"web-sys",
|
||||||
|
"webpki-roots",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4914,9 +4938,9 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "resolvematrix"
|
name = "resolvematrix"
|
||||||
version = "1.5.0"
|
version = "1.6.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "39a1efc3c55274528f8b1a916eb0edf5c40a8364b4899fbc1283a57c8d0024db"
|
checksum = "8c7ff53b0a73edb760d7b851fa63c65070f0c05532122ef25e0feb13a7fbb3c7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cache_control",
|
"cache_control",
|
||||||
"hickory-resolver",
|
"hickory-resolver",
|
||||||
@@ -5197,8 +5221,8 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rust-librocksdb-sys"
|
name = "rust-librocksdb-sys"
|
||||||
version = "0.49.0+11.12.0"
|
version = "0.45.1+11.1.1"
|
||||||
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b"
|
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bindgen",
|
"bindgen",
|
||||||
"bzip2-sys",
|
"bzip2-sys",
|
||||||
@@ -5208,15 +5232,14 @@ dependencies = [
|
|||||||
"libz-sys",
|
"libz-sys",
|
||||||
"lz4-sys",
|
"lz4-sys",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
"rustflags",
|
|
||||||
"tikv-jemalloc-sys",
|
"tikv-jemalloc-sys",
|
||||||
"zstd-sys",
|
"zstd-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rust-rocksdb"
|
name = "rust-rocksdb"
|
||||||
version = "0.54.0"
|
version = "0.49.1"
|
||||||
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b"
|
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
@@ -5244,12 +5267,6 @@ dependencies = [
|
|||||||
"semver",
|
"semver",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rustflags"
|
|
||||||
version = "0.1.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a39e0e9135d7a7208ee80aa4e3e4b88f0f5ad7be92153ed70686c38a03db2e63"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustix"
|
name = "rustix"
|
||||||
version = "1.1.6"
|
version = "1.1.6"
|
||||||
@@ -5642,7 +5659,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9"
|
checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"annotate-snippets",
|
"annotate-snippets",
|
||||||
"base64 0.22.1",
|
"base64 0.23.1",
|
||||||
"encoding_rs_io",
|
"encoding_rs_io",
|
||||||
"granit-parser",
|
"granit-parser",
|
||||||
"nohash-hasher",
|
"nohash-hasher",
|
||||||
@@ -5877,6 +5894,12 @@ dependencies = [
|
|||||||
"lazy_static",
|
"lazy_static",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "shlex"
|
||||||
|
version = "1.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "shlex"
|
name = "shlex"
|
||||||
version = "2.0.1"
|
version = "2.0.1"
|
||||||
@@ -6236,17 +6259,18 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tikv-jemalloc-ctl"
|
name = "tikv-jemalloc-ctl"
|
||||||
version = "0.7.0"
|
version = "0.6.1"
|
||||||
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
|
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
|
"paste",
|
||||||
"tikv-jemalloc-sys",
|
"tikv-jemalloc-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tikv-jemalloc-sys"
|
name = "tikv-jemalloc-sys"
|
||||||
version = "0.7.0+5.4.0-0-g7a34f18502e7b222724097cdcd499b437d189acc"
|
version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7"
|
||||||
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
|
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
"libc",
|
"libc",
|
||||||
@@ -6254,8 +6278,8 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tikv-jemallocator"
|
name = "tikv-jemallocator"
|
||||||
version = "0.7.0"
|
version = "0.6.1"
|
||||||
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
|
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"tikv-jemalloc-sys",
|
"tikv-jemalloc-sys",
|
||||||
@@ -7113,6 +7137,15 @@ dependencies = [
|
|||||||
"rustls-pki-types",
|
"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]]
|
[[package]]
|
||||||
name = "weezl"
|
name = "weezl"
|
||||||
version = "0.1.12"
|
version = "0.1.12"
|
||||||
|
|||||||
+5
-16
@@ -166,15 +166,6 @@ features = [
|
|||||||
"form",
|
"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]
|
[workspace.dependencies.serde]
|
||||||
version = "1.0.229"
|
version = "1.0.229"
|
||||||
default-features = false
|
default-features = false
|
||||||
@@ -403,7 +394,7 @@ features = [
|
|||||||
|
|
||||||
[workspace.dependencies.rust-rocksdb]
|
[workspace.dependencies.rust-rocksdb]
|
||||||
git = "https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1"
|
git = "https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1"
|
||||||
rev = "85ded20348e3dab902c239967075795e9c6d101b"
|
rev = "0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"multi-threaded-cf",
|
"multi-threaded-cf",
|
||||||
@@ -423,8 +414,6 @@ default-features = false
|
|||||||
|
|
||||||
[workspace.dependencies.openidconnect]
|
[workspace.dependencies.openidconnect]
|
||||||
version = "4.1.0"
|
version = "4.1.0"
|
||||||
default-features = false
|
|
||||||
features = ["reqwest"]
|
|
||||||
|
|
||||||
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
|
||||||
[workspace.dependencies.opentelemetry]
|
[workspace.dependencies.opentelemetry]
|
||||||
@@ -487,7 +476,7 @@ version = "0.49.5"
|
|||||||
# jemalloc usage
|
# jemalloc usage
|
||||||
[workspace.dependencies.tikv-jemalloc-sys]
|
[workspace.dependencies.tikv-jemalloc-sys]
|
||||||
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
|
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
|
||||||
rev = "46e7821917b06636cdb5b203d312799970eaea92"
|
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"background_threads_runtime_support",
|
"background_threads_runtime_support",
|
||||||
@@ -495,7 +484,7 @@ features = [
|
|||||||
]
|
]
|
||||||
[workspace.dependencies.tikv-jemallocator]
|
[workspace.dependencies.tikv-jemallocator]
|
||||||
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
|
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
|
||||||
rev = "46e7821917b06636cdb5b203d312799970eaea92"
|
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = [
|
features = [
|
||||||
"background_threads_runtime_support",
|
"background_threads_runtime_support",
|
||||||
@@ -503,7 +492,7 @@ features = [
|
|||||||
]
|
]
|
||||||
[workspace.dependencies.tikv-jemalloc-ctl]
|
[workspace.dependencies.tikv-jemalloc-ctl]
|
||||||
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
|
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
|
||||||
rev = "46e7821917b06636cdb5b203d312799970eaea92"
|
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["use_std"]
|
features = ["use_std"]
|
||||||
|
|
||||||
@@ -595,7 +584,7 @@ version = "0.3.18"
|
|||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
|
|
||||||
[workspace.dependencies.resolvematrix]
|
[workspace.dependencies.resolvematrix]
|
||||||
version = "1.5.0"
|
version = "1.6.0"
|
||||||
features = ["unstable-msc4188"]
|
features = ["unstable-msc4188"]
|
||||||
|
|
||||||
[workspace.dependencies.serde_urlencoded]
|
[workspace.dependencies.serde_urlencoded]
|
||||||
|
|||||||
@@ -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 acting as a trusted server, meaning the `trusted_servers` list can consist of servers that are either Synapse OR continuwuity.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Network issues while refreshing an access token will no longer cause OAuth-compatible clients to be forcibly logged out. Contributed by @ginger.
|
||||||
+18
-17
@@ -813,18 +813,6 @@
|
|||||||
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
|
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
|
||||||
#forget_forced_upon_leave = false
|
#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
|
# Set this to true to require authentication to create a rendezvous
|
||||||
# session. Rendezvous sessions are used for QR code login.
|
# 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
|
# (trusted key notary servers), as well as serve as trusted servers for
|
||||||
# other operations like backfill and event fetching.
|
# other operations like backfill and event fetching.
|
||||||
#
|
#
|
||||||
# Currently, continuwuity doesn't support inbound key requests, so
|
# example: ["continuwuity.org", "matrix.org"]
|
||||||
# this list should only contain other Synapse servers.
|
|
||||||
#
|
|
||||||
# example: ["matrix.org", "starstruck.systems"]
|
|
||||||
#
|
#
|
||||||
# It is possible to restrict which signing keys trusted servers are
|
# It is possible to restrict which signing keys trusted servers are
|
||||||
# allowed to sign responses with. Without configuring this, all responses
|
# allowed to sign responses with. Without configuring this, all responses
|
||||||
@@ -1084,7 +1069,7 @@
|
|||||||
# is discouraged for performance and reliability reasons.
|
# is discouraged for performance and reliability reasons.
|
||||||
#
|
#
|
||||||
# env: CONTINUWUITY_TRUSTED_SERVERS
|
# 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.
|
# Whether to prioritise trusted server lookups over origin server lookups.
|
||||||
#
|
#
|
||||||
@@ -2783,6 +2768,22 @@
|
|||||||
# env: CONTINUWUITY_EXPERIMENTS__MSC4494
|
# env: CONTINUWUITY_EXPERIMENTS__MSC4494
|
||||||
#msc4494 = false
|
#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
|
# MSC4560: Stripped state requests over federation
|
||||||
#
|
#
|
||||||
# Implements a more efficient way for servers to acquire and serve
|
# Implements a more efficient way for servers to acquire and serve
|
||||||
|
|||||||
+46
@@ -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
|
||||||
@@ -29,7 +29,7 @@ pub(crate) async fn get_profile_route(
|
|||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<get_profile::v3::Request>,
|
body: Ruma<get_profile::v3::Request>,
|
||||||
) -> Result<get_profile::v3::Response> {
|
) -> 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(
|
return Err!(Request(Unauthorized(
|
||||||
"This server requires authentication to access user profiles."
|
"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>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<get_profile_field::v3::Request>,
|
body: Ruma<get_profile_field::v3::Request>,
|
||||||
) -> Result<get_profile_field::v3::Response> {
|
) -> 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(
|
return Err!(Request(Unauthorized(
|
||||||
"This server requires authentication to access user profiles."
|
"This server requires authentication to access user profiles."
|
||||||
)));
|
)));
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use service::Services;
|
|||||||
|
|
||||||
use crate::{Ruma, router::ClientIdentity};
|
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(
|
pub(crate) async fn discover_rendezvous_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<discover_rendezvous::msc4388::Request>,
|
body: Ruma<discover_rendezvous::msc4388::Request>,
|
||||||
@@ -20,7 +20,7 @@ pub(crate) async fn discover_rendezvous_route(
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/`
|
/// `POST /_matrix/client/unstable/io.element.msc4388/rendezvous`
|
||||||
pub(crate) async fn create_rendezvous_session_route(
|
pub(crate) async fn create_rendezvous_session_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<create_rendezvous_session::msc4388::Request>,
|
body: Ruma<create_rendezvous_session::msc4388::Request>,
|
||||||
@@ -32,7 +32,7 @@ pub(crate) async fn create_rendezvous_session_route(
|
|||||||
services.rendezvous.create_session(body.data.clone())
|
services.rendezvous.create_session(body.data.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `PUT /_matrix/client/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(
|
pub(crate) async fn update_rendezvous_session_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<update_rendezvous_session::msc4388::Request>,
|
body: Ruma<update_rendezvous_session::msc4388::Request>,
|
||||||
@@ -45,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(
|
pub(crate) async fn get_rendezvous_session_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
body: Ruma<get_rendezvous_session::msc4388::Request>,
|
body: Ruma<get_rendezvous_session::msc4388::Request>,
|
||||||
) -> Result<get_rendezvous_session::msc4388::Response> {
|
) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||||
if let Some(mode) = headers.get("Sec-Fetch-Mode")
|
let is_navigation_mode = headers
|
||||||
&& let Ok(mode) = mode.to_str()
|
.get_all("Sec-Fetch-Mode")
|
||||||
&& mode == "navigate"
|
.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(
|
return Err!(Request(Forbidden(
|
||||||
"Rendezvous sessions do not accept browser navigation requests."
|
"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)
|
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(
|
pub(crate) async fn delete_rendezvous_session_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
body: Ruma<delete_rendezvous_session::msc4388::Request>,
|
body: Ruma<delete_rendezvous_session::msc4388::Request>,
|
||||||
|
|||||||
+23
-6
@@ -191,11 +191,23 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
|||||||
.ruma_route(&client::get_rtc_transports)
|
.ruma_route(&client::get_rtc_transports)
|
||||||
.ruma_route(&client::get_rtc_transports_unstable)
|
.ruma_route(&client::get_rtc_transports_unstable)
|
||||||
.ruma_route(&client::room_initial_sync_route)
|
.ruma_route(&client::room_initial_sync_route)
|
||||||
.ruma_route(&client::discover_rendezvous_route)
|
.merge(
|
||||||
.ruma_route(&client::create_rendezvous_session_route)
|
Router::new()
|
||||||
.ruma_route(&client::update_rendezvous_session_route)
|
.ruma_route(&client::discover_rendezvous_route)
|
||||||
.ruma_route(&client::get_rendezvous_session_route)
|
.ruma_route(&client::create_rendezvous_session_route)
|
||||||
.ruma_route(&client::delete_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)
|
.ruma_route(&client::get_authorization_server_metadata_route)
|
||||||
.merge(client::oauth::router(state))
|
.merge(client::oauth::router(state))
|
||||||
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
|
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
|
||||||
@@ -219,7 +231,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
|||||||
if config.allow_federation {
|
if config.allow_federation {
|
||||||
router = router
|
router = router
|
||||||
.ruma_route(&server::get_server_version_route)
|
.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_route)
|
||||||
.ruma_route(&server::get_public_rooms_filtered_route)
|
.ruma_route(&server::get_public_rooms_filtered_route)
|
||||||
.ruma_route(&server::send_transaction_message_route)
|
.ruma_route(&server::send_transaction_message_route)
|
||||||
@@ -246,6 +260,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
|||||||
.ruma_route(&server::get_content_route)
|
.ruma_route(&server::get_content_route)
|
||||||
.ruma_route(&server::get_content_thumbnail_route)
|
.ruma_route(&server::get_content_thumbnail_route)
|
||||||
.route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count));
|
.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() {
|
if config.experiments.msc4560.is_enabled() {
|
||||||
router = router.ruma_route(&server::get_stripped_state_route);
|
router = router.ruma_route(&server::get_stripped_state_route);
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-3
@@ -11,7 +11,11 @@ use axum::{
|
|||||||
use conduwuit::{Error, Result, err, error};
|
use conduwuit::{Error, Result, err, error};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
CanonicalJsonObject,
|
CanonicalJsonObject,
|
||||||
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
|
api::{
|
||||||
|
IncomingRequest, IncomingRequestExt,
|
||||||
|
auth_scheme::AuthScheme,
|
||||||
|
error::{DeserializationError, FromHttpRequestError},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
@@ -114,8 +118,18 @@ where
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Deserialize the body
|
// Deserialize the body
|
||||||
let body = R::try_from_http_request(request, &borrowed_path)
|
let body_is_empty = body.is_empty();
|
||||||
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
|
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 })
|
Ok(Self { body, json_body, identity })
|
||||||
}
|
}
|
||||||
|
|||||||
+46
-7
@@ -194,6 +194,10 @@ impl CheckAuth for AccessTokenOptional {
|
|||||||
authentication: Self::Output,
|
authentication: Self::Output,
|
||||||
query: AuthQueryParams,
|
query: AuthQueryParams,
|
||||||
) -> Result<Self::Identity> {
|
) -> Result<Self::Identity> {
|
||||||
|
if R::RATE_LIMITED && is_rendezvous_create_route(TypeId::of::<R>()) {
|
||||||
|
services.rendezvous.check_create_ratelimit(request_ip)?;
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(authentication) = authentication {
|
if let Some(authentication) = authentication {
|
||||||
check_access_token(
|
check_access_token(
|
||||||
services,
|
services,
|
||||||
@@ -278,6 +282,11 @@ impl CheckAuth for NoAccessToken {
|
|||||||
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
|
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
let is_rendezvous_session = is_rendezvous_session_route(TypeId::of::<R>());
|
||||||
|
if R::RATE_LIMITED && is_rendezvous_session {
|
||||||
|
services.rendezvous.check_session_ratelimit(request_ip)?;
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(authentication) = authentication {
|
if let Some(authentication) = authentication {
|
||||||
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
|
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
|
||||||
OAuthClientScope::ApiFullAccess,
|
OAuthClientScope::ApiFullAccess,
|
||||||
@@ -285,7 +294,7 @@ impl CheckAuth for NoAccessToken {
|
|||||||
.await
|
.await
|
||||||
.map(Some)
|
.map(Some)
|
||||||
} else {
|
} else {
|
||||||
if R::RATE_LIMITED {
|
if R::RATE_LIMITED && !is_rendezvous_session {
|
||||||
check_unauthenticated_request_ratelimiting(services, request_ip)?;
|
check_unauthenticated_request_ratelimiting(services, request_ip)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -319,6 +328,19 @@ async fn check_access_token(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let session_info = services
|
||||||
|
.oauth
|
||||||
|
.get_session_info_for_device(&sender_user, &sender_device)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if let Some(session_info) = &session_info {
|
||||||
|
services.oauth.clear_previous_refresh_token(
|
||||||
|
&sender_user,
|
||||||
|
&sender_device,
|
||||||
|
session_info,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Locked users can only use /logout and /logout/all
|
// Locked users can only use /logout and /logout/all
|
||||||
if services
|
if services
|
||||||
.users
|
.users
|
||||||
@@ -333,12 +355,6 @@ async fn check_access_token(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let session_info = services
|
|
||||||
.oauth
|
|
||||||
.get_session_info_for_device(&sender_user, &sender_device)
|
|
||||||
.await
|
|
||||||
.map(Box::new);
|
|
||||||
|
|
||||||
// Make sure the user has the right scopes to use the route
|
// Make sure the user has the right scopes to use the route
|
||||||
let mut user_scopes = if let Some(session_info) = &session_info {
|
let mut user_scopes = if let Some(session_info) = &session_info {
|
||||||
session_info.scopes()
|
session_info.scopes()
|
||||||
@@ -416,6 +432,15 @@ async fn check_access_token(
|
|||||||
sender_device,
|
sender_device,
|
||||||
appservice_info: Box::new(appservice_info),
|
appservice_info: Box::new(appservice_info),
|
||||||
})
|
})
|
||||||
|
} else if services.users.is_previous_token(token).await {
|
||||||
|
// Return a soft-logout for previous tokens. This is necessary
|
||||||
|
// to make token refreshing idempotent.
|
||||||
|
|
||||||
|
Err(Error::Request(
|
||||||
|
ErrorKind::UnknownToken(assign!(UnknownTokenErrorData::new(), { soft_logout: true })),
|
||||||
|
"This token has expired".into(),
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
))
|
||||||
} else {
|
} else {
|
||||||
Err(Error::Request(
|
Err(Error::Request(
|
||||||
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
|
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
|
||||||
@@ -433,6 +458,20 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result<Regi
|
|||||||
Ok(appservice_info)
|
Ok(appservice_info)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_rendezvous_create_route(route: TypeId) -> bool {
|
||||||
|
route == TypeId::of::<client::rendezvous::discover_rendezvous::msc4388::Request>()
|
||||||
|
|| route
|
||||||
|
== TypeId::of::<client::rendezvous::create_rendezvous_session::msc4388::Request>()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_rendezvous_session_route(route: TypeId) -> bool {
|
||||||
|
route == TypeId::of::<client::rendezvous::get_rendezvous_session::msc4388::Request>()
|
||||||
|
|| route
|
||||||
|
== TypeId::of::<client::rendezvous::update_rendezvous_session::msc4388::Request>()
|
||||||
|
|| route
|
||||||
|
== TypeId::of::<client::rendezvous::delete_rendezvous_session::msc4388::Request>()
|
||||||
|
}
|
||||||
|
|
||||||
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
|
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
|
||||||
if services
|
if services
|
||||||
.config
|
.config
|
||||||
|
|||||||
+288
-68
@@ -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 axum::extract::State;
|
||||||
use conduwuit::{Result, utils::timepoint_from_now};
|
use conduwuit::{
|
||||||
use futures::StreamExt;
|
Err, Result,
|
||||||
|
config::experiments::ToggledExperiment,
|
||||||
|
debug_info,
|
||||||
|
utils::{ReadyExt, stream::automatic_width},
|
||||||
|
};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
MilliSecondsSinceUnixEpoch,
|
MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId,
|
||||||
api::{
|
api::federation::discovery::{
|
||||||
OutgoingResponseExt,
|
ServerSigningKeys, get_remote_server_keys, get_remote_server_keys_batch,
|
||||||
federation::discovery::{OldVerifyKey, ServerSigningKeys, get_server_keys},
|
get_remote_server_keys_batch::v2::QueryCriteria, get_server_keys,
|
||||||
},
|
},
|
||||||
assign,
|
|
||||||
serde::Raw,
|
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`
|
/// # `GET /_matrix/key/v2/server`
|
||||||
///
|
///
|
||||||
/// Gets the public signing keys of this server.
|
/// Gets the public signing keys of this server.
|
||||||
pub(crate) async fn get_server_keys_route(
|
pub(crate) async fn get_server_keys_route(
|
||||||
State(services): State<crate::State>,
|
State(services): State<crate::State>,
|
||||||
) -> Result<impl IntoResponse> {
|
_body: Ruma<get_server_keys::v2::Request>,
|
||||||
let server_name = services.globals.server_name();
|
) -> Result<get_server_keys::v2::Response> {
|
||||||
let verify_keys = BTreeMap::from([services.server_keys.active_verify_key()]);
|
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 {
|
const MAX_KEYS_PER_QUERY: usize = 16384;
|
||||||
k.to_owned()
|
const MAX_SERVERS_PER_QUERY: usize = 4096;
|
||||||
} else {
|
|
||||||
// We need to figure out any old signing keys we've acquired from
|
/// # `POST /_matrix/key/v2/query`
|
||||||
// notaries.
|
///
|
||||||
let mut keys = services.server_keys.signing_keys_for(server_name);
|
/// Fetches remote server signing keys in bulk, seeding from the local server's
|
||||||
let mut old_keys = BTreeMap::new();
|
/// database.
|
||||||
while let Some(resp) = keys.next().await {
|
///
|
||||||
// We need to verify that this response is still trusted based on
|
/// This route applies a semaphore to slow down requests that query more signing
|
||||||
// the current configuration. It's possible we got this response
|
/// keys than is allowed by [MSC4556].
|
||||||
// from a notary who we no longer trust.
|
///
|
||||||
if resp.parsed.valid_until_ts > in_one_week() {
|
/// [MSC4556]: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
|
||||||
continue;
|
pub(crate) async fn get_remote_server_keys_batch_route(
|
||||||
}
|
State(services): State<crate::State>,
|
||||||
let trusted = services.config.trusted_servers.iter().any(|notary| {
|
body: Ruma<get_remote_server_keys_batch::v2::Request>,
|
||||||
server_keys::Service::verify_server_keys_response(
|
) -> Result<get_remote_server_keys_batch::v2::Response> {
|
||||||
&resp,
|
query_inner(&services, &body.server_keys, true)
|
||||||
Some((notary.server_name(), notary.verify_keys())),
|
.await
|
||||||
)
|
.map(get_remote_server_keys_batch::v2::Response::new)
|
||||||
.is_ok()
|
}
|
||||||
});
|
|
||||||
if !trusted {
|
/// # `POST /_matrix/key/unstable/org.continuwuity.msc4556/query`
|
||||||
continue;
|
/// ## `POST /_matrix/key/v3/query`
|
||||||
}
|
///
|
||||||
for (old_key_id, old_key) in resp.parsed.old_verify_keys {
|
/// Fetches remote server signing keys in bulk, seeding from the local server's
|
||||||
if old_key.expired_ts > resp.parsed.valid_until_ts {
|
/// database.
|
||||||
// This key expired in the future which is probably illegal
|
///
|
||||||
continue;
|
/// MSC4556: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
|
||||||
}
|
pub(crate) async fn get_remote_server_keys_batch_v3_unstable_route(
|
||||||
old_keys
|
State(services): State<crate::State>,
|
||||||
.entry(old_key_id)
|
body: Ruma<ruminuwuity::federation::notary::unstable::Request>,
|
||||||
.and_modify(|current_old_key: &mut OldVerifyKey| {
|
) -> Result<ruminuwuity::federation::notary::unstable::Response> {
|
||||||
// Use the lowest expiry timestamp
|
query_inner(&services, &body.server_keys, false)
|
||||||
if current_old_key.expired_ts > old_key.expired_ts {
|
.await
|
||||||
*current_old_key = old_key.clone();
|
.map(ruminuwuity::federation::notary::unstable::Response::new)
|
||||||
}
|
}
|
||||||
})
|
|
||||||
.or_insert(old_key);
|
/// 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()), {
|
for (server_name, queries) in body.clone() {
|
||||||
verify_keys,
|
let server_keys = services.server_keys.clone();
|
||||||
old_verify_keys,
|
let semaphore = semaphore.clone();
|
||||||
});
|
|
||||||
|
|
||||||
let server_key = Raw::new(&server_key)?;
|
futs.spawn_on(
|
||||||
let mut response = get_server_keys::v2::Response::new(server_key)
|
async move {
|
||||||
.try_into_http_response::<Vec<u8>>()
|
let _permit = if let Some(sem) = semaphore {
|
||||||
.map(|mut response| take(response.body_mut()))
|
let cost = queries
|
||||||
.and_then(|body| serde_json::from_slice(&body).map_err(Into::into))?;
|
.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 {
|
/// `GET /_matrix/key/v2/query/{serverName}`
|
||||||
let dur = Duration::from_hours(12);
|
///
|
||||||
let timepoint = timepoint_from_now(dur).expect("SystemTime should not overflow");
|
/// Fetches the latest keys for a specific server name.
|
||||||
MilliSecondsSinceUnixEpoch::from_system_time(timepoint).expect("UInt should not overflow")
|
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
|
||||||
}
|
}
|
||||||
@@ -118,6 +118,22 @@ pub struct Experiments {
|
|||||||
/// default: false
|
/// default: false
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub msc4494: SimpleExperiment,
|
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
|
/// MSC4560: Stripped state requests over federation
|
||||||
///
|
///
|
||||||
/// Implements a more efficient way for servers to acquire and serve
|
/// Implements a more efficient way for servers to acquire and serve
|
||||||
|
|||||||
+30
-41
@@ -920,19 +920,6 @@ pub struct Config {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub forget_forced_upon_leave: bool,
|
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
|
/// Set this to true to require authentication to create a rendezvous
|
||||||
/// session. Rendezvous sessions are used for QR code login.
|
/// 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
|
/// (trusted key notary servers), as well as serve as trusted servers for
|
||||||
/// other operations like backfill and event fetching.
|
/// other operations like backfill and event fetching.
|
||||||
///
|
///
|
||||||
/// Currently, continuwuity doesn't support inbound key requests, so
|
/// example: ["continuwuity.org", "matrix.org"]
|
||||||
/// this list should only contain other Synapse servers.
|
|
||||||
///
|
|
||||||
/// example: ["matrix.org", "starstruck.systems"]
|
|
||||||
///
|
///
|
||||||
/// It is possible to restrict which signing keys trusted servers are
|
/// It is possible to restrict which signing keys trusted servers are
|
||||||
/// allowed to sign responses with. Without configuring this, all responses
|
/// 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
|
/// empty list (`[]`) to operate without trusted server assistance, but this
|
||||||
/// is discouraged for performance and reliability reasons.
|
/// is discouraged for performance and reliability reasons.
|
||||||
///
|
///
|
||||||
/// default: ["matrix.org"]
|
/// default: ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
|
||||||
#[serde(default = "default_trusted_servers")]
|
#[serde(default = "default_trusted_servers")]
|
||||||
pub trusted_servers: Vec<TrustedServer>,
|
pub trusted_servers: Vec<TrustedServer>,
|
||||||
|
|
||||||
@@ -3004,6 +2988,7 @@ const DEPRECATED_KEYS: &[&str] = &[
|
|||||||
"max_concurrent_requests",
|
"max_concurrent_requests",
|
||||||
"otlp_protocol",
|
"otlp_protocol",
|
||||||
"request_ip_source",
|
"request_ip_source",
|
||||||
|
"require_auth_for_profile_requests",
|
||||||
"roomid_spacehierarchy_cache_capacity",
|
"roomid_spacehierarchy_cache_capacity",
|
||||||
"unredacted_content_max_age_secs",
|
"unredacted_content_max_age_secs",
|
||||||
"well_known_client",
|
"well_known_client",
|
||||||
@@ -3143,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_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_cache_capacity_modifier() -> f64 { 1.0 }
|
||||||
|
|
||||||
fn default_auth_chain_cache_capacity() -> u32 {
|
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)
|
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 {
|
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 {
|
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 {
|
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 {
|
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 {
|
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 }
|
fn default_dns_cache_entries() -> u32 { 32768 }
|
||||||
|
|
||||||
@@ -3264,12 +3249,11 @@ fn default_otlp_filter() -> String {
|
|||||||
fn default_tracing_flame_output_path() -> String { "./tracing.folded".to_owned() }
|
fn default_tracing_flame_output_path() -> String { "./tracing.folded".to_owned() }
|
||||||
|
|
||||||
fn default_trusted_servers() -> Vec<TrustedServer> {
|
fn default_trusted_servers() -> Vec<TrustedServer> {
|
||||||
// TODO(nex): Once we can be a notary, add maintainer(?) homeservers here.
|
let trusted_servers = vec![
|
||||||
// Rationale: Users are already running our code, arguably that's a higher
|
ruma::owned_server_name!("continuwuity.org"),
|
||||||
// level of trust than is assigned to notaries in the first place.
|
ruma::owned_server_name!("continuwuity.rocks"),
|
||||||
// We should still remind everyone that notaries are evil and out to get you
|
ruma::owned_server_name!("matrix.org"),
|
||||||
// and to replace this list with servers they actually trust.
|
];
|
||||||
let trusted_servers = vec![ruma::owned_server_name!("matrix.org")];
|
|
||||||
trusted_servers
|
trusted_servers
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(TrustedServer::Name)
|
.map(TrustedServer::Name)
|
||||||
@@ -3400,15 +3384,20 @@ fn default_admin_log_capture() -> String {
|
|||||||
|
|
||||||
fn default_admin_room_tag() -> String { "m.server_notice".to_owned() }
|
fn default_admin_room_tag() -> String { "m.server_notice".to_owned() }
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
#[allow(clippy::as_conversions, clippy::cast_precision_loss)]
|
#[allow(clippy::as_conversions, clippy::cast_precision_loss)]
|
||||||
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 {
|
#[must_use]
|
||||||
let val = val.try_into().expect("failed to cast u32 to usize");
|
#[allow(clippy::as_conversions, clippy::cast_possible_truncation)]
|
||||||
parallelism_scaled(val).try_into().unwrap_or(u32::MAX)
|
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 {
|
fn default_db_pool_workers() -> usize {
|
||||||
sys::available_parallelism()
|
sys::available_parallelism()
|
||||||
|
|||||||
@@ -171,13 +171,14 @@ impl Error {
|
|||||||
/// Returns the Matrix error code / error kind
|
/// Returns the Matrix error code / error kind
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn kind(&self) -> ErrorKind {
|
pub fn kind(&self) -> ErrorKind {
|
||||||
use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
|
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
|
||||||
|
|
||||||
match self {
|
match self {
|
||||||
| Self::Federation(_, error) | Self::Ruma(error) =>
|
| Self::Federation(_, error) | Self::Ruma(error) =>
|
||||||
response::ruma_error_kind(error).clone(),
|
response::ruma_error_kind(error).clone(),
|
||||||
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
||||||
| Self::FeatureDisabled(..) => Unrecognized,
|
| Self::FeatureDisabled(..) => Unrecognized,
|
||||||
|
| Self::Path(_) | Self::Query(_) => InvalidParam,
|
||||||
| _ => Unknown,
|
| _ => Unknown,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -194,6 +195,7 @@ impl Error {
|
|||||||
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
|
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
|
||||||
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||||
| Self::Conflict(_) => StatusCode::CONFLICT,
|
| Self::Conflict(_) => StatusCode::CONFLICT,
|
||||||
|
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
|
||||||
| Self::Io(error) => response::io_error_code(error.kind()),
|
| Self::Io(error) => response::io_error_code(error.kind()),
|
||||||
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
|
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
|
||||||
| _ => StatusCode::INTERNAL_SERVER_ERROR,
|
| _ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
|||||||
@@ -73,6 +73,9 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
|
|||||||
// 413
|
// 413
|
||||||
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
|
||||||
|
// 409
|
||||||
|
| ConcurrentWrite => StatusCode::CONFLICT,
|
||||||
|
|
||||||
// 404
|
// 404
|
||||||
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
|
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ pub type DigestOut = [u8; 256 / 8];
|
|||||||
/// Sha256 hash (input gather joined by 0xFF bytes)
|
/// Sha256 hash (input gather joined by 0xFF bytes)
|
||||||
#[must_use]
|
#[must_use]
|
||||||
#[tracing::instrument(skip(inputs), level = "trace")]
|
#[tracing::instrument(skip(inputs), level = "trace")]
|
||||||
|
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||||
pub fn delimited<'a, T, I>(mut inputs: I) -> DigestOut
|
pub fn delimited<'a, T, I>(mut inputs: I) -> DigestOut
|
||||||
where
|
where
|
||||||
I: Iterator<Item = T> + 'a,
|
I: Iterator<Item = T> + 'a,
|
||||||
@@ -25,6 +26,7 @@ where
|
|||||||
/// Sha256 hash (input gather)
|
/// Sha256 hash (input gather)
|
||||||
#[must_use]
|
#[must_use]
|
||||||
#[tracing::instrument(skip(inputs), level = "trace")]
|
#[tracing::instrument(skip(inputs), level = "trace")]
|
||||||
|
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||||
pub fn concat<'a, T, I>(inputs: I) -> DigestOut
|
pub fn concat<'a, T, I>(inputs: I) -> DigestOut
|
||||||
where
|
where
|
||||||
I: Iterator<Item = T> + 'a,
|
I: Iterator<Item = T> + 'a,
|
||||||
@@ -43,6 +45,7 @@ where
|
|||||||
#[inline]
|
#[inline]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
#[tracing::instrument(skip(input), level = "trace")]
|
#[tracing::instrument(skip(input), level = "trace")]
|
||||||
|
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||||
pub fn hash<T>(input: T) -> DigestOut
|
pub fn hash<T>(input: T) -> DigestOut
|
||||||
where
|
where
|
||||||
T: AsRef<[u8]>,
|
T: AsRef<[u8]>,
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ fn descriptor_cf_options(
|
|||||||
let mut opts = set_table_options(opts, &desc, cache)?;
|
let mut opts = set_table_options(opts, &desc, cache)?;
|
||||||
|
|
||||||
opts.set_min_write_buffer_number(1);
|
opts.set_min_write_buffer_number(1);
|
||||||
opts.set_max_write_buffer_number(2);
|
opts.set_max_write_buffer_number(3);
|
||||||
opts.set_write_buffer_size(desc.write_size);
|
opts.set_write_buffer_size(desc.write_size);
|
||||||
|
|
||||||
opts.set_target_file_size_base(desc.file_size);
|
opts.set_target_file_size_base(desc.file_size);
|
||||||
|
|||||||
@@ -407,6 +407,10 @@ pub(super) static MAPS: &[Descriptor] = &[
|
|||||||
name: "userdeviceid_token",
|
name: "userdeviceid_token",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
},
|
},
|
||||||
|
Descriptor {
|
||||||
|
name: "userdeviceid_previoustoken",
|
||||||
|
..descriptor::RANDOM_SMALL
|
||||||
|
},
|
||||||
Descriptor {
|
Descriptor {
|
||||||
name: "userdevicesessionid_uiaainfo",
|
name: "userdevicesessionid_uiaainfo",
|
||||||
..descriptor::RANDOM_SMALL
|
..descriptor::RANDOM_SMALL
|
||||||
|
|||||||
+28
-8
@@ -76,6 +76,7 @@ full = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
brotli_compression = [
|
brotli_compression = [
|
||||||
|
"conduwuit-api/brotli_compression",
|
||||||
"conduwuit-core/brotli_compression",
|
"conduwuit-core/brotli_compression",
|
||||||
"conduwuit-router/brotli_compression",
|
"conduwuit-router/brotli_compression",
|
||||||
"conduwuit-service/brotli_compression",
|
"conduwuit-service/brotli_compression",
|
||||||
@@ -87,30 +88,31 @@ direct_tls = [
|
|||||||
"conduwuit-router/direct_tls"
|
"conduwuit-router/direct_tls"
|
||||||
]
|
]
|
||||||
element_hacks = [
|
element_hacks = [
|
||||||
|
"conduwuit-api/element_hacks",
|
||||||
"conduwuit-service/element_hacks",
|
"conduwuit-service/element_hacks",
|
||||||
"conduwuit-router/element_hacks",
|
|
||||||
]
|
]
|
||||||
gzip_compression = [
|
gzip_compression = [
|
||||||
|
"conduwuit-api/gzip_compression",
|
||||||
"conduwuit-core/gzip_compression",
|
"conduwuit-core/gzip_compression",
|
||||||
"conduwuit-router/gzip_compression",
|
"conduwuit-router/gzip_compression",
|
||||||
"conduwuit-service/gzip_compression",
|
"conduwuit-service/gzip_compression",
|
||||||
]
|
]
|
||||||
http3 = [
|
http3 = [
|
||||||
"conduwuit-service/http3"
|
"reqwest/http3"
|
||||||
]
|
]
|
||||||
ring = [
|
ring = [
|
||||||
"rustls/ring",
|
"rustls/ring"
|
||||||
]
|
]
|
||||||
|
|
||||||
aws_lc_rs = [
|
aws_lc_rs = [
|
||||||
"rustls/aws_lc_rs",
|
"rustls/aws_lc_rs",
|
||||||
|
"dep:aws-lc-rs"
|
||||||
]
|
]
|
||||||
io_uring = [
|
io_uring = [
|
||||||
"conduwuit-service/io_uring",
|
"conduwuit-database/io_uring",
|
||||||
]
|
]
|
||||||
jemalloc = [
|
jemalloc = [
|
||||||
"conduwuit-core/jemalloc",
|
"conduwuit-core/jemalloc",
|
||||||
"conduwuit-service/jemalloc",
|
"conduwuit-database/jemalloc",
|
||||||
]
|
]
|
||||||
mimalloc = [
|
mimalloc = [
|
||||||
"conduwuit-core/mimalloc",
|
"conduwuit-core/mimalloc",
|
||||||
@@ -142,13 +144,19 @@ perf_measurements = [
|
|||||||
release_max_log_level = [
|
release_max_log_level = [
|
||||||
"tracing/max_level_trace",
|
"tracing/max_level_trace",
|
||||||
"tracing/release_max_level_info",
|
"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-core/release_max_log_level",
|
||||||
|
"conduwuit-database/release_max_log_level",
|
||||||
"conduwuit-router/release_max_log_level",
|
"conduwuit-router/release_max_log_level",
|
||||||
"conduwuit-service/release_max_log_level",
|
"conduwuit-service/release_max_log_level",
|
||||||
]
|
]
|
||||||
sentry_telemetry = [
|
sentry_telemetry = [
|
||||||
"dep:sentry",
|
"dep:sentry",
|
||||||
"dep:sentry-tracing",
|
"dep:sentry-tracing",
|
||||||
|
"dep:sentry-tower",
|
||||||
"conduwuit-core/sentry_telemetry",
|
"conduwuit-core/sentry_telemetry",
|
||||||
"conduwuit-router/sentry_telemetry",
|
"conduwuit-router/sentry_telemetry",
|
||||||
]
|
]
|
||||||
@@ -171,17 +179,19 @@ url_preview = [
|
|||||||
"conduwuit-service/url_preview",
|
"conduwuit-service/url_preview",
|
||||||
]
|
]
|
||||||
zstd_compression = [
|
zstd_compression = [
|
||||||
|
"conduwuit-api/zstd_compression",
|
||||||
"conduwuit-core/zstd_compression",
|
"conduwuit-core/zstd_compression",
|
||||||
|
"conduwuit-database/zstd_compression",
|
||||||
"conduwuit-router/zstd_compression",
|
"conduwuit-router/zstd_compression",
|
||||||
"conduwuit-service/zstd_compression",
|
"conduwuit-service/zstd_compression",
|
||||||
]
|
]
|
||||||
bindgen-static = [
|
bindgen-static = [
|
||||||
# "bindgen/static"
|
# "bindgen/static"
|
||||||
# "clang-sys/static"
|
# "clang-sys/static"
|
||||||
"conduwuit-service/bindgen-static"
|
"conduwuit-database/bindgen-static"
|
||||||
]
|
]
|
||||||
bindgen-runtime = [
|
bindgen-runtime = [
|
||||||
"conduwuit-service/bindgen-runtime"
|
"conduwuit-database/bindgen-runtime"
|
||||||
]
|
]
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
@@ -189,7 +199,10 @@ bindgen-runtime = [
|
|||||||
# clang-sys = {version = "1", default-features = false}
|
# clang-sys = {version = "1", default-features = false}
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
conduwuit-admin.workspace = true
|
||||||
|
conduwuit-api.workspace = true
|
||||||
conduwuit-core.workspace = true
|
conduwuit-core.workspace = true
|
||||||
|
conduwuit-database.workspace = true
|
||||||
conduwuit-router.workspace = true
|
conduwuit-router.workspace = true
|
||||||
conduwuit-service.workspace = true
|
conduwuit-service.workspace = true
|
||||||
conduwuit-build-metadata.workspace = true
|
conduwuit-build-metadata.workspace = true
|
||||||
@@ -201,6 +214,7 @@ dtor.workspace = true
|
|||||||
console-subscriber.optional = true
|
console-subscriber.optional = true
|
||||||
console-subscriber.workspace = true
|
console-subscriber.workspace = true
|
||||||
const-str.workspace = true
|
const-str.workspace = true
|
||||||
|
log.workspace = true
|
||||||
opentelemetry.workspace = true
|
opentelemetry.workspace = true
|
||||||
opentelemetry-otlp.optional = true
|
opentelemetry-otlp.optional = true
|
||||||
opentelemetry-otlp.workspace = true
|
opentelemetry-otlp.workspace = true
|
||||||
@@ -208,10 +222,14 @@ opentelemetry-prometheus.workspace = true
|
|||||||
opentelemetry-semantic-conventions.workspace = true
|
opentelemetry-semantic-conventions.workspace = true
|
||||||
opentelemetry_sdk.workspace = true
|
opentelemetry_sdk.workspace = true
|
||||||
prometheus.workspace = true
|
prometheus.workspace = true
|
||||||
|
sentry-tower.optional = true
|
||||||
|
sentry-tower.workspace = true
|
||||||
sentry-tracing.optional = true
|
sentry-tracing.optional = true
|
||||||
sentry-tracing.workspace = true
|
sentry-tracing.workspace = true
|
||||||
sentry.optional = true
|
sentry.optional = true
|
||||||
sentry.workspace = true
|
sentry.workspace = true
|
||||||
|
tokio-metrics.optional = true
|
||||||
|
tokio-metrics.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tracing-flame.optional = true
|
tracing-flame.optional = true
|
||||||
tracing-flame.workspace = true
|
tracing-flame.workspace = true
|
||||||
@@ -221,7 +239,9 @@ tracing-subscriber.workspace = true
|
|||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
tracing-journald = { workspace = true, optional = true }
|
tracing-journald = { workspace = true, optional = true }
|
||||||
parking_lot.workspace = true
|
parking_lot.workspace = true
|
||||||
|
reqwest = { workspace = true, default-features = false }
|
||||||
rustls = { workspace = true, default-features = false }
|
rustls = { workspace = true, default-features = false }
|
||||||
|
aws-lc-rs = { version = "1.19.0", default-features = false, optional = true }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use axum::{
|
|||||||
extract::State,
|
extract::State,
|
||||||
response::{IntoResponse, Response},
|
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 conduwuit_service::Services;
|
||||||
use futures::FutureExt;
|
use futures::FutureExt;
|
||||||
use http::{Method, StatusCode, Uri};
|
use http::{Method, StatusCode, Uri};
|
||||||
@@ -106,11 +106,11 @@ fn handle_result(method: &Method, uri: &Uri, result: Response) -> Result<Respons
|
|||||||
let reason = status.canonical_reason().unwrap_or("Unknown Reason");
|
let reason = status.canonical_reason().unwrap_or("Unknown Reason");
|
||||||
|
|
||||||
if status.is_server_error() {
|
if status.is_server_error() {
|
||||||
error!(%method, %uri, "{code} {reason}");
|
info!(%method, %uri, "{code} {reason}");
|
||||||
} else if status.is_client_error() {
|
} else if status.is_client_error() {
|
||||||
debug_error!(%method, %uri, "{code} {reason}");
|
info!(%method, %uri, "{code} {reason}");
|
||||||
} else if status.is_redirection() {
|
} else if status.is_redirection() {
|
||||||
debug!(%method, %uri, "{code} {reason}");
|
trace!(%method, %uri, "{code} {reason}");
|
||||||
} else {
|
} else {
|
||||||
trace!(%method, %uri, "{code} {reason}");
|
trace!(%method, %uri, "{code} {reason}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
pub mod notary;
|
||||||
@@ -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 } }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,3 +6,5 @@ pub mod invite_permission_config;
|
|||||||
pub mod meowlnir_antispam;
|
pub mod meowlnir_antispam;
|
||||||
pub mod policy;
|
pub mod policy;
|
||||||
pub mod pushers;
|
pub mod pushers;
|
||||||
|
|
||||||
|
pub mod federation;
|
||||||
@@ -16,12 +16,6 @@ crate-type = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
bindgen-runtime = [
|
|
||||||
"conduwuit-database/bindgen-runtime"
|
|
||||||
]
|
|
||||||
bindgen-static = [
|
|
||||||
"conduwuit-database/bindgen-static"
|
|
||||||
]
|
|
||||||
brotli_compression = [
|
brotli_compression = [
|
||||||
"conduwuit-core/brotli_compression",
|
"conduwuit-core/brotli_compression",
|
||||||
"reqwest/brotli",
|
"reqwest/brotli",
|
||||||
@@ -35,9 +29,6 @@ gzip_compression = [
|
|||||||
"conduwuit-core/gzip_compression",
|
"conduwuit-core/gzip_compression",
|
||||||
"reqwest/gzip",
|
"reqwest/gzip",
|
||||||
]
|
]
|
||||||
http3 = [
|
|
||||||
"reqwest/http3"
|
|
||||||
]
|
|
||||||
io_uring = [
|
io_uring = [
|
||||||
"conduwuit-database/io_uring",
|
"conduwuit-database/io_uring",
|
||||||
]
|
]
|
||||||
@@ -132,9 +123,6 @@ lettre.workspace = true
|
|||||||
resolvematrix.workspace = true
|
resolvematrix.workspace = true
|
||||||
serde_urlencoded.workspace = true
|
serde_urlencoded.workspace = true
|
||||||
openidconnect.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
|
rand.workspace = true
|
||||||
|
|
||||||
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
||||||
|
|||||||
+77
-10
@@ -1,5 +1,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeSet, HashMap},
|
collections::{BTreeSet, HashMap},
|
||||||
|
fmt::Write,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
time::{Duration, SystemTime},
|
time::{Duration, SystemTime},
|
||||||
};
|
};
|
||||||
@@ -55,7 +56,7 @@ struct Services {
|
|||||||
config: Dep<config::Service>,
|
config: Dep<config::Service>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
pub struct SessionInfo {
|
pub struct SessionInfo {
|
||||||
pub client_id: String,
|
pub client_id: String,
|
||||||
#[serde(deserialize_with = "client_metadata::btreeset_skip_err")]
|
#[serde(deserialize_with = "client_metadata::btreeset_skip_err")]
|
||||||
@@ -64,6 +65,8 @@ pub struct SessionInfo {
|
|||||||
temporary_scopes: BTreeSet<OAuthClientScope>,
|
temporary_scopes: BTreeSet<OAuthClientScope>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
current_refresh_token: String,
|
current_refresh_token: String,
|
||||||
|
#[serde(default)]
|
||||||
|
previous_refresh_token: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SessionInfo {
|
impl SessionInfo {
|
||||||
@@ -71,6 +74,15 @@ impl SessionInfo {
|
|||||||
pub fn scopes(&self) -> BTreeSet<OAuthClientScope> {
|
pub fn scopes(&self) -> BTreeSet<OAuthClientScope> {
|
||||||
self.scopes.union(&self.temporary_scopes).cloned().collect()
|
self.scopes.union(&self.temporary_scopes).cloned().collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn scope_string(&self, device_id: &DeviceId) -> String {
|
||||||
|
let mut scopes = self.scopes().iter().join(" ");
|
||||||
|
|
||||||
|
let _ = write!(scopes, " urn:matrix:client:device:{device_id}");
|
||||||
|
|
||||||
|
scopes
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
@@ -246,6 +258,24 @@ impl Service {
|
|||||||
.ok()
|
.ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clear a session's previous refresh token, if it has one.
|
||||||
|
pub fn clear_previous_refresh_token(
|
||||||
|
&self,
|
||||||
|
user_id: &UserId,
|
||||||
|
device_id: &DeviceId,
|
||||||
|
session_info: &SessionInfo,
|
||||||
|
) {
|
||||||
|
if session_info.previous_refresh_token.is_some() {
|
||||||
|
let mut session_info = session_info.clone();
|
||||||
|
|
||||||
|
session_info.previous_refresh_token = None;
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.userdeviceid_oauthsessioninfo
|
||||||
|
.put((user_id, device_id), Json(session_info));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn request_authorization_code(
|
pub async fn request_authorization_code(
|
||||||
&self,
|
&self,
|
||||||
authorizing_user: OwnedUserId,
|
authorizing_user: OwnedUserId,
|
||||||
@@ -645,6 +675,7 @@ impl Service {
|
|||||||
SessionInfo {
|
SessionInfo {
|
||||||
client_id: client_id.clone(),
|
client_id: client_id.clone(),
|
||||||
current_refresh_token: Self::generate_token(),
|
current_refresh_token: Self::generate_token(),
|
||||||
|
previous_refresh_token: None,
|
||||||
scopes: requested_scopes.scopes,
|
scopes: requested_scopes.scopes,
|
||||||
temporary_scopes: BTreeSet::new(),
|
temporary_scopes: BTreeSet::new(),
|
||||||
}
|
}
|
||||||
@@ -702,15 +733,53 @@ impl Service {
|
|||||||
|
|
||||||
assert_eq!(&client_id, &session_info.client_id, "session info client id mismatch");
|
assert_eq!(&client_id, &session_info.client_id, "session info client id mismatch");
|
||||||
|
|
||||||
// TODO: this doesn't include the device ID "scope", do any clients rely
|
let new_refresh_token = Self::generate_token();
|
||||||
// on that?
|
|
||||||
let scope = session_info.scopes.iter().join(" ");
|
if refresh_token == session_info.current_refresh_token {
|
||||||
|
// The client is refreshing with their current refresh token.
|
||||||
|
// We need to generate a new refresh token and save this token as
|
||||||
|
// the previous one.
|
||||||
|
|
||||||
|
session_info
|
||||||
|
.current_refresh_token
|
||||||
|
.clone_from(&new_refresh_token);
|
||||||
|
|
||||||
|
// Remove the old previous token if it's set. This can only happen
|
||||||
|
// if the client decides to refresh twice in a row without using its
|
||||||
|
// new access token, since we'll also do this when the new access
|
||||||
|
// token is used for the first time.
|
||||||
|
if let Some(previous_refresh_token) = session_info.previous_refresh_token {
|
||||||
|
self.db
|
||||||
|
.refreshtoken_refreshtokeninfo
|
||||||
|
.remove(&previous_refresh_token);
|
||||||
|
}
|
||||||
|
|
||||||
|
session_info.previous_refresh_token = Some(refresh_token);
|
||||||
|
} else if Some(&refresh_token) == session_info.previous_refresh_token.as_ref() {
|
||||||
|
// The client is refreshing with their previous refresh token,
|
||||||
|
// probably because they didn't get the new one we made for them. We
|
||||||
|
// need to make a second new one, but we don't touch the existing
|
||||||
|
// previous one in case they don't get the second new one either.
|
||||||
|
|
||||||
|
// Wipe the current token, we're going to make a new one.
|
||||||
|
self.db
|
||||||
|
.refreshtoken_refreshtokeninfo
|
||||||
|
.remove(&session_info.current_refresh_token);
|
||||||
|
|
||||||
|
session_info
|
||||||
|
.current_refresh_token
|
||||||
|
.clone_from(&new_refresh_token);
|
||||||
|
} else {
|
||||||
|
// The client is trying to use a refresh token that isn't their
|
||||||
|
// current or previous one, but still has information in the
|
||||||
|
// database. This is definitely not a legal state, so we need to
|
||||||
|
// bail out.
|
||||||
|
panic!("refresh token is not current or previous for its session");
|
||||||
|
}
|
||||||
|
|
||||||
|
let scope = session_info.scope_string(&refresh_token_info.device_id);
|
||||||
|
|
||||||
let new_access_token = DeviceToken::new_random().with_max_age(Self::ACCESS_TOKEN_MAX_AGE);
|
let new_access_token = DeviceToken::new_random().with_max_age(Self::ACCESS_TOKEN_MAX_AGE);
|
||||||
let new_refresh_token = Self::generate_token();
|
|
||||||
session_info
|
|
||||||
.current_refresh_token
|
|
||||||
.clone_from(&new_refresh_token);
|
|
||||||
|
|
||||||
self.services
|
self.services
|
||||||
.users
|
.users
|
||||||
@@ -729,8 +798,6 @@ impl Service {
|
|||||||
Json(session_info),
|
Json(session_info),
|
||||||
);
|
);
|
||||||
|
|
||||||
self.db.refreshtoken_refreshtokeninfo.remove(&refresh_token);
|
|
||||||
drop(refresh_token);
|
|
||||||
self.db
|
self.db
|
||||||
.refreshtoken_refreshtokeninfo
|
.refreshtoken_refreshtokeninfo
|
||||||
.raw_put(&new_refresh_token, Json(refresh_token_info));
|
.raw_put(&new_refresh_token, Json(refresh_token_info));
|
||||||
|
|||||||
@@ -1,25 +1,38 @@
|
|||||||
use std::{
|
use std::{
|
||||||
|
net::IpAddr,
|
||||||
sync::Arc,
|
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 lru_cache::LruCache;
|
||||||
|
use nonzero_ext::nonzero;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
OwnedTransactionId,
|
OwnedTransactionId,
|
||||||
api::client::rendezvous::{
|
api::{
|
||||||
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
client::rendezvous::{
|
||||||
update_rendezvous_session,
|
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
||||||
|
update_rendezvous_session,
|
||||||
|
},
|
||||||
|
error::{ErrorKind, LimitExceededErrorData, RetryAfter},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub struct Service {
|
pub struct Service {
|
||||||
sessions: SyncMutex<LruCache<String, Session>>,
|
sessions: SyncMutex<LruCache<String, Session>>,
|
||||||
|
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||||
|
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Session {
|
struct Session {
|
||||||
data: String,
|
data: String,
|
||||||
created_at: SystemTime,
|
created_at: Instant,
|
||||||
last_sequence_token: String,
|
last_sequence_token: String,
|
||||||
transaction_sequences: LruCache<OwnedTransactionId, String>,
|
transaction_sequences: LruCache<OwnedTransactionId, String>,
|
||||||
}
|
}
|
||||||
@@ -27,20 +40,31 @@ struct Session {
|
|||||||
impl Session {
|
impl Session {
|
||||||
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
|
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
|
||||||
|
|
||||||
fn new(data: String, sequence_token: String) -> Self {
|
fn new(data: String, sequence_token: String, now: Instant) -> Self {
|
||||||
Self {
|
Self {
|
||||||
data,
|
data,
|
||||||
created_at: SystemTime::now(),
|
created_at: now,
|
||||||
last_sequence_token: sequence_token,
|
last_sequence_token: sequence_token,
|
||||||
transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES),
|
transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn time_remaining(&self, now: Instant) -> Option<Duration> {
|
||||||
|
let age = now.saturating_duration_since(self.created_at);
|
||||||
|
(age < Service::SESSION_MAX_AGE)
|
||||||
|
.then(|| Service::SESSION_MAX_AGE.saturating_sub(age))
|
||||||
|
.filter(|remaining| !remaining.is_zero())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_expired(&self, now: Instant) -> bool { self.time_remaining(now).is_none() }
|
||||||
}
|
}
|
||||||
|
|
||||||
impl crate::Service for Service {
|
impl crate::Service for Service {
|
||||||
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
|
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||||
Ok(Arc::new(Self {
|
Ok(Arc::new(Self {
|
||||||
sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)),
|
sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)),
|
||||||
|
create_ratelimiter: RateLimiter::keyed(Self::CREATE_RATELIMIT),
|
||||||
|
session_ratelimiter: RateLimiter::keyed(Self::SESSION_RATELIMIT),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,25 +72,64 @@ impl crate::Service for Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Service {
|
impl Service {
|
||||||
|
const CREATE_RATELIMIT: Quota = Quota::per_minute(nonzero!(30_u32));
|
||||||
const MAX_DATA_SIZE_BYTES: usize = 4096;
|
const MAX_DATA_SIZE_BYTES: usize = 4096;
|
||||||
const MAX_SESSIONS: usize = 256;
|
const MAX_SESSIONS: usize = 256;
|
||||||
const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
|
const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
|
||||||
|
const SESSION_RATELIMIT: Quota = Quota::per_minute(nonzero!(300_u32));
|
||||||
const TOKEN_LENGTH: usize = 32;
|
const TOKEN_LENGTH: usize = 32;
|
||||||
|
|
||||||
|
pub fn check_create_ratelimit(&self, ip: IpAddr) -> Result<()> {
|
||||||
|
Self::check_ratelimiter(&self.create_ratelimiter, ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_session_ratelimit(&self, ip: IpAddr) -> Result<()> {
|
||||||
|
Self::check_ratelimiter(&self.session_ratelimiter, ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_ratelimiter(
|
||||||
|
ratelimiter: &DefaultKeyedRateLimiter<IpAddr>,
|
||||||
|
ip: IpAddr,
|
||||||
|
) -> Result<()> {
|
||||||
|
if let Err(not_until) = ratelimiter.check_key(&ip) {
|
||||||
|
let wait_time = not_until.wait_time_from(DefaultClock::default().now());
|
||||||
|
let mut data = LimitExceededErrorData::new();
|
||||||
|
data.retry_after = Some(RetryAfter::Delay(wait_time));
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
ErrorKind::LimitExceeded(data),
|
||||||
|
"Rate limit exceeded.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) }
|
fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) }
|
||||||
|
|
||||||
|
fn is_valid_opaque_id(id: &str) -> bool {
|
||||||
|
!id.is_empty()
|
||||||
|
&& id.len() <= 255
|
||||||
|
&& id
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~'))
|
||||||
|
}
|
||||||
|
|
||||||
/// Lock and fetch an unexpired rendezvous session.
|
/// Lock and fetch an unexpired rendezvous session.
|
||||||
fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
||||||
|
self.lock_session_at(id, Instant::now())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock_session_at(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
now: Instant,
|
||||||
|
) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
||||||
// We don't clear out expired sessions manually, the LRU cache will
|
// We don't clear out expired sessions manually, the LRU cache will
|
||||||
// evict them over time
|
// evict them over time
|
||||||
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
|
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
|
||||||
sessions
|
sessions
|
||||||
.get_mut(id)
|
.get_mut(id)
|
||||||
.filter(|session| {
|
.filter(|session| !session.is_expired(now))
|
||||||
SystemTime::now()
|
|
||||||
.duration_since(session.created_at)
|
|
||||||
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
|
|
||||||
})
|
|
||||||
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
|
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
|
||||||
})
|
})
|
||||||
.map_err(at!(1))
|
.map_err(at!(1))
|
||||||
@@ -86,7 +149,7 @@ impl Service {
|
|||||||
|
|
||||||
self.sessions
|
self.sessions
|
||||||
.lock()
|
.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(
|
Ok(create_rendezvous_session::msc4388::Response::new(
|
||||||
id,
|
id,
|
||||||
@@ -103,6 +166,12 @@ impl Service {
|
|||||||
sequence_token: String,
|
sequence_token: String,
|
||||||
data: String,
|
data: String,
|
||||||
) -> Result<update_rendezvous_session::msc4388::Response> {
|
) -> Result<update_rendezvous_session::msc4388::Response> {
|
||||||
|
if !Self::is_valid_opaque_id(transaction.as_str()) {
|
||||||
|
return Err!(Request(InvalidParam(
|
||||||
|
"Transaction ID does not comply with the opaque identifier grammar"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
let mut session = self.lock_session(id)?;
|
let mut session = self.lock_session(id)?;
|
||||||
|
|
||||||
// If the provided transaction ID was used already, we have to return
|
// If the provided transaction ID was used already, we have to return
|
||||||
@@ -137,13 +206,12 @@ impl Service {
|
|||||||
|
|
||||||
/// Look up a rendezvous session by ID.
|
/// Look up a rendezvous session by ID.
|
||||||
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
|
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||||
let session = self.lock_session(id)?;
|
let now = Instant::now();
|
||||||
|
let session = self.lock_session_at(id, now)?;
|
||||||
|
|
||||||
let session_age = SystemTime::now()
|
let session_time_remaining = session
|
||||||
.duration_since(session.created_at)
|
.time_remaining(now)
|
||||||
.unwrap_or(Duration::MAX);
|
.unwrap_or_else(|| Duration::from_millis(1));
|
||||||
|
|
||||||
let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age);
|
|
||||||
|
|
||||||
Ok(get_rendezvous_session::msc4388::Response::new(
|
Ok(get_rendezvous_session::msc4388::Response::new(
|
||||||
session.last_sequence_token.clone(),
|
session.last_sequence_token.clone(),
|
||||||
@@ -158,8 +226,12 @@ impl Service {
|
|||||||
id: &str,
|
id: &str,
|
||||||
) -> Result<delete_rendezvous_session::msc4388::Response> {
|
) -> Result<delete_rendezvous_session::msc4388::Response> {
|
||||||
let mut sessions = self.sessions.lock();
|
let mut sessions = self.sessions.lock();
|
||||||
|
let now = Instant::now();
|
||||||
|
|
||||||
if sessions.remove(id).is_some() {
|
if sessions
|
||||||
|
.remove(id)
|
||||||
|
.is_some_and(|session| !session.is_expired(now))
|
||||||
|
{
|
||||||
Ok(delete_rendezvous_session::msc4388::Response::new())
|
Ok(delete_rendezvous_session::msc4388::Response::new())
|
||||||
} else {
|
} else {
|
||||||
Err!(Request(NotFound("Unknown session")))
|
Err!(Request(NotFound("Unknown session")))
|
||||||
|
|||||||
@@ -522,13 +522,6 @@ impl Service {
|
|||||||
let device_changes =
|
let device_changes =
|
||||||
self.select_edus_device_changes(server_name, batch, &max_edu_count, &events_len);
|
self.select_edus_device_changes(server_name, batch, &max_edu_count, &events_len);
|
||||||
|
|
||||||
let receipts: OptionFuture<_> = self
|
|
||||||
.server
|
|
||||||
.config
|
|
||||||
.allow_outgoing_read_receipts
|
|
||||||
.then(|| self.select_edus_receipts(server_name, batch, &max_edu_count))
|
|
||||||
.into();
|
|
||||||
|
|
||||||
let presence: OptionFuture<_> = self
|
let presence: OptionFuture<_> = self
|
||||||
.server
|
.server
|
||||||
.config
|
.config
|
||||||
@@ -536,11 +529,20 @@ impl Service {
|
|||||||
.then(|| self.select_edus_presence(server_name, batch, &max_edu_count))
|
.then(|| self.select_edus_presence(server_name, batch, &max_edu_count))
|
||||||
.into();
|
.into();
|
||||||
|
|
||||||
let (device_changes, receipts, presence) = join!(device_changes, receipts, presence);
|
let (device_changes, presence) = join!(device_changes, presence);
|
||||||
|
|
||||||
let mut events = device_changes;
|
let mut events = device_changes;
|
||||||
events.extend(presence.into_iter().flatten());
|
events.extend(presence.into_iter().flatten());
|
||||||
events.extend(receipts.into_iter().flatten());
|
|
||||||
|
// leave a slot for the queued event, but always allow one receipt EDU
|
||||||
|
let edu_limit = (EDU_LIMIT - 1).saturating_sub(events.len()).max(1);
|
||||||
|
if self.server.config.allow_outgoing_read_receipts {
|
||||||
|
// must be selected last, as it may lower max_edu_count
|
||||||
|
events.extend(
|
||||||
|
self.select_edus_receipts(server_name, batch, &max_edu_count, edu_limit)
|
||||||
|
.await,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// TODO(nex): some EDUs like typing need flattening
|
// TODO(nex): some EDUs like typing need flattening
|
||||||
|
|
||||||
@@ -616,9 +618,11 @@ impl Service {
|
|||||||
server_name: &ServerName,
|
server_name: &ServerName,
|
||||||
since: (u64, u64),
|
since: (u64, u64),
|
||||||
max_edu_count: &AtomicU64,
|
max_edu_count: &AtomicU64,
|
||||||
) -> Option<EduBuf> {
|
edu_limit: usize,
|
||||||
|
) -> EduVec {
|
||||||
let num = AtomicUsize::new(0);
|
let num = AtomicUsize::new(0);
|
||||||
let receipts: BTreeMap<OwnedRoomId, ReceiptMap> = self
|
let deferred = AtomicU64::new(u64::MAX);
|
||||||
|
let rooms: Vec<_> = self
|
||||||
.services
|
.services
|
||||||
.state_cache
|
.state_cache
|
||||||
.server_rooms(server_name)
|
.server_rooms(server_name)
|
||||||
@@ -627,33 +631,54 @@ impl Service {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let receipt_map = self
|
let maps = self
|
||||||
.select_edus_receipts_room(&room_id, since, max_edu_count, &num)
|
.select_edus_receipts_room(
|
||||||
|
&room_id,
|
||||||
|
since,
|
||||||
|
max_edu_count,
|
||||||
|
&num,
|
||||||
|
edu_limit,
|
||||||
|
&deferred,
|
||||||
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
(!receipt_map.read.is_empty()).then_some((room_id, receipt_map))
|
(!maps.is_empty()).then_some((room_id, maps))
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
if receipts.is_empty() {
|
// the next transaction starts at the first receipt that did not fit
|
||||||
return None;
|
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();
|
let mut buf = EduBuf::new();
|
||||||
serde_json::to_writer(&mut buf, &receipt_content)
|
serde_json::to_writer(&mut buf, &edu)
|
||||||
.expect("Failed to serialize Receipt EDU to JSON vec");
|
.expect("Failed to serialize Receipt EDU to JSON vec");
|
||||||
|
buf
|
||||||
Some(buf)
|
})
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Look for read receipts in this room
|
/// Look for read receipts in this room
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
name = "receipts",
|
name = "receipts",
|
||||||
level = "trace",
|
level = "trace",
|
||||||
skip(self, since, max_edu_count, num)
|
skip(self, since, max_edu_count, num, deferred)
|
||||||
)]
|
)]
|
||||||
async fn select_edus_receipts_room(
|
async fn select_edus_receipts_room(
|
||||||
&self,
|
&self,
|
||||||
@@ -661,14 +686,16 @@ impl Service {
|
|||||||
since: (u64, u64),
|
since: (u64, u64),
|
||||||
max_edu_count: &AtomicU64,
|
max_edu_count: &AtomicU64,
|
||||||
num: &AtomicUsize,
|
num: &AtomicUsize,
|
||||||
) -> ReceiptMap {
|
edu_limit: usize,
|
||||||
|
deferred: &AtomicU64,
|
||||||
|
) -> Vec<BTreeMap<OwnedUserId, ReceiptData>> {
|
||||||
let receipts = self
|
let receipts = self
|
||||||
.services
|
.services
|
||||||
.read_receipt
|
.read_receipt
|
||||||
.readreceipts_since(room_id, Some(since.0));
|
.readreceipts_since(room_id, Some(since.0));
|
||||||
|
|
||||||
pin_mut!(receipts);
|
pin_mut!(receipts);
|
||||||
let mut read = BTreeMap::<OwnedUserId, ReceiptData>::new();
|
let mut maps = Vec::new();
|
||||||
while let Some((user_id, count, read_receipt)) = receipts.next().await {
|
while let Some((user_id, count, read_receipt)) = receipts.next().await {
|
||||||
if count > since.1 {
|
if count > since.1 {
|
||||||
break;
|
break;
|
||||||
@@ -704,14 +731,20 @@ impl Service {
|
|||||||
|
|
||||||
let receipt_data = ReceiptData::new(receipt, vec![event_id]);
|
let receipt_data = ReceiptData::new(receipt, vec![event_id]);
|
||||||
|
|
||||||
if read.insert(user_id, receipt_data).is_none() {
|
let Some(index) = add_receipt(&mut maps, user_id, receipt_data, edu_limit) else {
|
||||||
if num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT {
|
deferred.fetch_min(count, Ordering::Relaxed);
|
||||||
break;
|
break;
|
||||||
}
|
};
|
||||||
|
|
||||||
|
// only a user's first receipt counts towards the limit
|
||||||
|
if index == 0
|
||||||
|
&& num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT
|
||||||
|
{
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ReceiptMap::new(read)
|
maps
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Look for presence
|
/// Look for presence
|
||||||
@@ -1110,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)
|
||||||
|
}
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
use std::iter::once;
|
use std::{collections::BTreeMap, iter::once};
|
||||||
|
|
||||||
use conduwuit::{
|
use conduwuit::{
|
||||||
Error,
|
Error,
|
||||||
matrix::{PartialPdu, pdu::sticky},
|
matrix::{PartialPdu, pdu::sticky},
|
||||||
};
|
};
|
||||||
use futures::{StreamExt, stream::FuturesUnordered};
|
use futures::{StreamExt, stream::FuturesUnordered};
|
||||||
use ruma::{RoomId, UserId, events::sticky::StickyDurationMs, server_name};
|
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 serde_json::{json, value::to_raw_value};
|
||||||
|
|
||||||
use super::{CurTransactionStatus, TransactionStatus};
|
use super::{CurTransactionStatus, TransactionStatus, add_receipt};
|
||||||
use crate::{
|
use crate::{
|
||||||
sending::{Destination, EduBuf, SendingEvent},
|
sending::{Destination, EduBuf, SendingEvent},
|
||||||
test_utils::{test_services, test_services_with},
|
test_utils::{test_services, test_services_with},
|
||||||
@@ -196,3 +201,17 @@ async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled(
|
|||||||
assert_eq!(active_after_startup, 0);
|
assert_eq!(active_after_startup, 0);
|
||||||
assert_eq!(sending_after_startup, 0);
|
assert_eq!(sending_after_startup, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_receipt_separates_receipts_of_one_user() {
|
||||||
|
let alice = user_id!("@alice:example.org");
|
||||||
|
let bob = user_id!("@bob:example.org");
|
||||||
|
let receipt = || ReceiptData::new(Receipt::default(), vec![]);
|
||||||
|
let mut maps = Vec::new();
|
||||||
|
|
||||||
|
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), Some(0));
|
||||||
|
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), Some(1));
|
||||||
|
assert_eq!(add_receipt(&mut maps, bob.to_owned(), receipt(), 2), Some(0));
|
||||||
|
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), None);
|
||||||
|
assert_eq!(maps.iter().map(BTreeMap::len).collect::<Vec<_>>(), [2, 1]);
|
||||||
|
}
|
||||||
@@ -158,7 +158,7 @@ impl super::Service {
|
|||||||
|
|
||||||
if let Some(server_keys) = self.get_signing_key(origin, key_id).await
|
if let Some(server_keys) = self.get_signing_key(origin, key_id).await
|
||||||
&& let Some(key) =
|
&& 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");
|
trace!(%origin, %key_id, ?min_valid_ts, "Verify key exists locally");
|
||||||
Self::track_one_result(
|
Self::track_one_result(
|
||||||
@@ -387,7 +387,7 @@ impl super::Service {
|
|||||||
if let Some(vk) = self
|
if let Some(vk) = self
|
||||||
.get_signing_key(origin, key_id)
|
.get_signing_key(origin, key_id)
|
||||||
.await
|
.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");
|
trace!("Found verify key locally");
|
||||||
return Some(vk);
|
return Some(vk);
|
||||||
|
|||||||
@@ -5,32 +5,43 @@ mod sign;
|
|||||||
mod util;
|
mod util;
|
||||||
mod verify;
|
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::{
|
use conduwuit::{
|
||||||
Result, Server,
|
Result, Server, SyncRwLock, debug_info,
|
||||||
utils::{IterStream, ReadyExt, stream::TryIgnore},
|
utils::{IterStream, ReadyExt, stream::TryIgnore, timepoint_from_now, to_canonical_object},
|
||||||
};
|
};
|
||||||
use database::{Deserialized, Ignore, Interfix, Json, Map};
|
use database::{Deserialized, Ignore, Interfix, Json, Map};
|
||||||
use futures::{Stream, StreamExt};
|
use futures::{Stream, StreamExt};
|
||||||
pub use request::in_one_week;
|
pub use request::in_one_week;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
CanonicalJsonObject, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName,
|
CanonicalJsonObject, MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId,
|
||||||
ServerSigningKeyId,
|
ServerName, ServerSigningKeyId,
|
||||||
api::federation::discovery::{ServerSigningKeys, VerifyKey},
|
api::federation::discovery::{OldVerifyKey, ServerSigningKeys, VerifyKey},
|
||||||
room_version_rules::RoomVersionRules,
|
room_version_rules::RoomVersionRules,
|
||||||
serde::Raw,
|
serde::Raw,
|
||||||
signatures::{Ed25519KeyPair, PublicKeyMap, PublicKeySet},
|
signatures::{Ed25519KeyPair, PublicKeyMap, PublicKeySet},
|
||||||
};
|
};
|
||||||
|
use serde_json::value::to_raw_value;
|
||||||
use verify::IncomingServerKeys;
|
use verify::IncomingServerKeys;
|
||||||
|
pub use verify::strip_extraneous_signatures;
|
||||||
|
|
||||||
use crate::{Dep, globals, sending, server_keys::util::required_keys};
|
use crate::{Dep, globals, sending, server_keys::util::required_keys};
|
||||||
|
|
||||||
|
const VALID_UNTIL_TS_DURATION: Duration = Duration::from_hours(12);
|
||||||
|
|
||||||
pub struct Service {
|
pub struct Service {
|
||||||
keypair: Box<Ed25519KeyPair>,
|
keypair: Box<Ed25519KeyPair>,
|
||||||
verify_keys: VerifyKeys,
|
verify_keys: VerifyKeys,
|
||||||
services: Services,
|
services: Services,
|
||||||
db: Data,
|
db: Data,
|
||||||
|
last_lookup: SyncRwLock<HashMap<OwnedServerName, Instant>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Services {
|
struct Services {
|
||||||
@@ -47,6 +58,7 @@ pub type VerifyKeys = BTreeMap<OwnedServerSigningKeyId, VerifyKey>;
|
|||||||
pub type PubKeyMap = PublicKeyMap;
|
pub type PubKeyMap = PublicKeyMap;
|
||||||
pub type PubKeys = PublicKeySet;
|
pub type PubKeys = PublicKeySet;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
impl crate::Service for Service {
|
impl crate::Service for Service {
|
||||||
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||||
let (keypair, verify_keys) = keypair::init(args.db)?;
|
let (keypair, verify_keys) = keypair::init(args.db)?;
|
||||||
@@ -63,9 +75,12 @@ impl crate::Service for Service {
|
|||||||
db: Data {
|
db: Data {
|
||||||
servernamekeyid_response: args.db["servernamekeyid_response"].clone(),
|
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!()) }
|
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,7 +148,9 @@ impl Service {
|
|||||||
key_id: &ServerSigningKeyId,
|
key_id: &ServerSigningKeyId,
|
||||||
minimum_valid_ts: MilliSecondsSinceUnixEpoch,
|
minimum_valid_ts: MilliSecondsSinceUnixEpoch,
|
||||||
) -> bool {
|
) -> 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
|
// We have no keys for this server
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
@@ -161,12 +178,13 @@ impl Service {
|
|||||||
&self,
|
&self,
|
||||||
origin: &ServerName,
|
origin: &ServerName,
|
||||||
key_id: &ServerSigningKeyId,
|
key_id: &ServerSigningKeyId,
|
||||||
) -> Option<ServerSigningKeys> {
|
) -> Option<IncomingServerKeys> {
|
||||||
self.db
|
self.db
|
||||||
.servernamekeyid_response
|
.servernamekeyid_response
|
||||||
.qry(&(origin.as_str(), key_id.as_str()))
|
.qry(&(origin.as_str(), key_id.as_str()))
|
||||||
.await
|
.await
|
||||||
.deserialized::<ServerSigningKeys>()
|
.deserialized::<Raw<ServerSigningKeys>>()
|
||||||
|
.and_then(|r| r.try_into().map_err(Into::into))
|
||||||
.ok()
|
.ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,6 +206,8 @@ impl Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the stored server signing keys responses for the origin.
|
/// 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>(
|
pub fn signing_keys_for<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
origin: &'a ServerName,
|
origin: &'a ServerName,
|
||||||
@@ -199,4 +219,114 @@ impl Service {
|
|||||||
.map(|(_, v): (Ignore, Raw<ServerSigningKeys>)| v.try_into().map_err(Into::into))
|
.map(|(_, v): (Ignore, Raw<ServerSigningKeys>)| v.try_into().map_err(Into::into))
|
||||||
.ignore_err()
|
.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)?))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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 conduwuit::{Err, Result, trace, utils::millis_since_unix_epoch, warn};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
@@ -31,6 +31,23 @@ impl super::Service {
|
|||||||
) -> Result<IncomingServerKeys> {
|
) -> Result<IncomingServerKeys> {
|
||||||
use get_server_keys::v2::Request;
|
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
|
let raw_server_key = self
|
||||||
.services
|
.services
|
||||||
.sending
|
.sending
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ use conduwuit::{
|
|||||||
Err, Result, matrix::event::gen_event_id_canonical_json, trace, utils::to_canonical_object,
|
Err, Result, matrix::event::gen_event_id_canonical_json, trace, utils::to_canonical_object,
|
||||||
};
|
};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, ServerName, SigningKeyAlgorithm,
|
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, ServerName, ServerSigningKeyId,
|
||||||
|
SigningKeyAlgorithm,
|
||||||
api::federation::discovery::ServerSigningKeys,
|
api::federation::discovery::ServerSigningKeys,
|
||||||
room_version_rules::RoomVersionRules,
|
room_version_rules::RoomVersionRules,
|
||||||
serde::{Base64, Raw, base64::Standard},
|
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 {
|
impl super::Service {
|
||||||
/// Validates the incoming event only using locally known verification keys.
|
/// Validates the incoming event only using locally known verification keys.
|
||||||
/// Inserts the calculated event ID into the event_id field upon success.
|
/// 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);
|
pubkey_map.insert(incoming.parsed.server_name.to_string(), set);
|
||||||
|
|
||||||
let mut canonical = to_canonical_object(&incoming.raw)?;
|
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)
|
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"
|
"No valid signature from {notary_name} present on signing keys response"
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn strip_extraneous_signatures(
|
/// Removes extraneous signatures from the signature map. This is done to avoid
|
||||||
canonical: &mut CanonicalJsonObject,
|
/// leaking the signatures from notaries we've used, in case the response is
|
||||||
origin: &ServerName,
|
/// being forwarded to a third party. This also reduces the risk of accidentally
|
||||||
notaries: &[&ServerName],
|
/// trusting a notary's signature as the origin's signature if `notaries` is
|
||||||
) {
|
/// empty.
|
||||||
canonical.entry("signatures".to_owned()).and_modify(|sigs| {
|
///
|
||||||
sigs.as_object_mut().map(|s| {
|
/// Infallible & mutates the original canonical JSON object. Signatures by
|
||||||
s.retain(|server_name, _| {
|
/// server names that cannot be parsed are always removed.
|
||||||
let Ok(server_name) = ServerName::parse(server_name) else { return false };
|
pub fn strip_extraneous_signatures(
|
||||||
origin == server_name || notaries.iter().any(|ns| *ns == server_name)
|
canonical: &mut CanonicalJsonObject,
|
||||||
});
|
origin: &ServerName,
|
||||||
Some(s)
|
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)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -632,6 +632,12 @@ impl super::Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Discard this device's previous token entry if the current token
|
||||||
|
// isn't expired.
|
||||||
|
self.db
|
||||||
|
.userdeviceid_previoustoken
|
||||||
|
.del((&user_id, &device_id));
|
||||||
|
|
||||||
Some((user_id, device_id, AccessTokenStatus::Valid))
|
Some((user_id, device_id, AccessTokenStatus::Valid))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -184,8 +184,13 @@ impl super::Service {
|
|||||||
// Remove old token
|
// Remove old token
|
||||||
if let Ok(old_token) = self.db.userdeviceid_token.qry(&key).await {
|
if let Ok(old_token) = self.db.userdeviceid_token.qry(&key).await {
|
||||||
self.db.token_userdeviceid.remove(&old_token);
|
self.db.token_userdeviceid.remove(&old_token);
|
||||||
self.db.userdeviceid_tokenexpires.remove(&old_token);
|
|
||||||
// It will be removed from userdeviceid_token by the insert later
|
// It will be removed from userdeviceid_token by the insert later
|
||||||
|
|
||||||
|
// Save the previous token only if we don't already have one saved
|
||||||
|
// for this device.
|
||||||
|
if !self.db.userdeviceid_previoustoken.contains(&key).await {
|
||||||
|
self.db.userdeviceid_previoustoken.put_raw(key, &old_token);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assign token to user device combination
|
// Assign token to user device combination
|
||||||
@@ -207,6 +212,17 @@ impl super::Service {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns whether the provided token was previously used by a device
|
||||||
|
/// before a token refresh, and therefore should cause a soft-logout.
|
||||||
|
pub async fn is_previous_token(&self, token: &str) -> bool {
|
||||||
|
self.db
|
||||||
|
.userdeviceid_previoustoken
|
||||||
|
.stream::<Ignore, String>()
|
||||||
|
.ignore_err()
|
||||||
|
.ready_any(|(_, previous_token)| previous_token == token)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
/// Pushes a new to-device event into a device's inbox.
|
/// Pushes a new to-device event into a device's inbox.
|
||||||
pub async fn add_to_device_event(
|
pub async fn add_to_device_event(
|
||||||
&self,
|
&self,
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ struct Data {
|
|||||||
userdeviceid_tokenexpires: Arc<Map>,
|
userdeviceid_tokenexpires: Arc<Map>,
|
||||||
userdeviceid_metadata: Arc<Map>,
|
userdeviceid_metadata: Arc<Map>,
|
||||||
userdeviceid_token: Arc<Map>,
|
userdeviceid_token: Arc<Map>,
|
||||||
|
userdeviceid_previoustoken: Arc<Map>,
|
||||||
userfilterid_filter: Arc<Map>,
|
userfilterid_filter: Arc<Map>,
|
||||||
userid_avatarurl: Arc<Map>,
|
userid_avatarurl: Arc<Map>,
|
||||||
userid_deactivated: Arc<Map>,
|
userid_deactivated: Arc<Map>,
|
||||||
@@ -134,6 +135,7 @@ impl crate::Service for Service {
|
|||||||
remoteuserid_remoteuser: args.db["remoteuserid_remoteuser"].clone(),
|
remoteuserid_remoteuser: args.db["remoteuserid_remoteuser"].clone(),
|
||||||
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
|
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
|
||||||
userdeviceid_token: args.db["userdeviceid_token"].clone(),
|
userdeviceid_token: args.db["userdeviceid_token"].clone(),
|
||||||
|
userdeviceid_previoustoken: args.db["userdeviceid_previoustoken"].clone(),
|
||||||
userfilterid_filter: args.db["userfilterid_filter"].clone(),
|
userfilterid_filter: args.db["userfilterid_filter"].clone(),
|
||||||
userid_avatarurl: args.db["userid_avatarurl"].clone(),
|
userid_avatarurl: args.db["userid_avatarurl"].clone(),
|
||||||
userid_deactivated: args.db["userid_deactivated"].clone(),
|
userid_deactivated: args.db["userid_deactivated"].clone(),
|
||||||
|
|||||||
Reference in new issue
Block a user