mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-26 02:17:34 +00:00
Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
473d456d8b | ||
|
|
975273afa0 | ||
|
|
cdeb63ebe5 | ||
|
|
a5a887d556 | ||
|
|
5f183b2849 | ||
|
|
1d50422e30 | ||
|
|
522065db6a | ||
|
|
afc2a99a45 | ||
|
|
c9f9f02590 | ||
|
|
a267a94b55 | ||
|
|
159f547e4c | ||
|
|
304d3ea242 | ||
|
|
4dc2c1c63d | ||
|
|
98d78dfdf1 | ||
|
|
298113c0a6 | ||
|
|
62de19970e | ||
|
|
6b532eb7d0 | ||
|
|
b541aadc2b | ||
|
|
c1f6a7c082 | ||
|
|
3508b1a5e3 | ||
|
|
9867e99bb2 | ||
|
|
7b180667e8 | ||
|
|
e001e4a68a | ||
|
|
75383af35c | ||
|
|
c486eeac06 | ||
|
|
1ded0b4e97 | ||
|
|
cd94a0d3ab | ||
|
|
08307970a1 | ||
|
|
ebf7c9920a | ||
|
|
a15905e8c9 | ||
|
|
19bc5d2016 | ||
|
|
6bbebd8b54 | ||
|
|
4e1fb09bfb | ||
|
|
39cd151ca3 | ||
|
|
a5a7905494 | ||
|
|
a05d7a8cf3 | ||
|
|
af8ca8580e | ||
|
|
7050ea84e3 | ||
|
|
441ab78c4e |
No files matched your search
@@ -0,0 +1 @@
|
||||
Added support for acting as a trusted server, meaning the `trusted_servers` list can consist of servers that are either Synapse OR continuwuity.
|
||||
@@ -1 +0,0 @@
|
||||
Continuwuity will now request the `profile` OIDC scope from identity providers by default to improve compatibility with identity providers that require it to access users' profile claims, as recommended by the OIDC specification. Contributed by @ginger.
|
||||
@@ -1 +0,0 @@
|
||||
Attempting to start a UIAA session on a homeserver with UIAA disabled will now return `403 M_UNAUTHORIZED` instead of `404 M_UNSUPPORTED`. Contributed by @ginger.
|
||||
+20
-9
@@ -1043,10 +1043,7 @@
|
||||
# (trusted key notary servers), as well as serve as trusted servers for
|
||||
# other operations like backfill and event fetching.
|
||||
#
|
||||
# Currently, continuwuity doesn't support inbound key requests, so
|
||||
# this list should only contain other Synapse servers.
|
||||
#
|
||||
# example: ["matrix.org", "starstruck.systems"]
|
||||
# example: ["continuwuity.org", "matrix.org"]
|
||||
#
|
||||
# It is possible to restrict which signing keys trusted servers are
|
||||
# allowed to sign responses with. Without configuring this, all responses
|
||||
@@ -1084,7 +1081,7 @@
|
||||
# is discouraged for performance and reliability reasons.
|
||||
#
|
||||
# env: CONTINUWUITY_TRUSTED_SERVERS
|
||||
#trusted_servers = ["matrix.org"]
|
||||
#trusted_servers = ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
|
||||
|
||||
# Whether to prioritise trusted server lookups over origin server lookups.
|
||||
#
|
||||
@@ -2582,12 +2579,10 @@
|
||||
|
||||
# Additional scopes Continuwuity should request from the IDP. This may be
|
||||
# necessary to access certain claims. Continuwuity always requests the
|
||||
# `openid` scope, regardless of the contents of this option,
|
||||
# and will also request the `profile` scope by default if this option is
|
||||
# not set.
|
||||
# `openid` scope.
|
||||
#
|
||||
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES
|
||||
#additional_scopes = ["profile"]
|
||||
#additional_scopes = []
|
||||
|
||||
# Additional trusted audiences that Continuwuity will accept in the `aud`
|
||||
# claim of the OIDC token returned by the IDP. If your identity
|
||||
@@ -2783,6 +2778,22 @@
|
||||
# env: CONTINUWUITY_EXPERIMENTS__MSC4494
|
||||
#msc4494 = false
|
||||
|
||||
# MSC4556: Notary request limits
|
||||
#
|
||||
# Creates a new key notary server route that has stricter limits on how
|
||||
# many signing keys can be requested in one query, to avoid a resource
|
||||
# exhaustion exploit vector in the existing key notary endpoint.
|
||||
#
|
||||
# Continuwuity mitigates the exploit vector in the old notary endpoint
|
||||
# anyway, so you do not need to enable this to be protected.
|
||||
#
|
||||
# Requires that remote servers support this MSC before it does anything.
|
||||
#
|
||||
# https://github.com/matrix-org/matrix-spec-proposals/pull/4556
|
||||
#
|
||||
# env: CONTINUWUITY_EXPERIMENTS__MSC4556
|
||||
#msc4556 = false
|
||||
|
||||
# MSC4560: Stripped state requests over federation
|
||||
#
|
||||
# Implements a more efficient way for servers to acquire and serve
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
LD_LIBRARY_PATH = lib.makeLibraryPath (
|
||||
[
|
||||
pkgs.stdenv.cc.cc.lib
|
||||
pkgs.llvmPackages.libclang.lib
|
||||
]
|
||||
++ lib.optionals pkgs.stdenv.hostPlatform.isLinux [
|
||||
pkgs.liburing
|
||||
|
||||
@@ -9,7 +9,7 @@ use service::Services;
|
||||
|
||||
use crate::{Ruma, router::ClientIdentity};
|
||||
|
||||
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous`
|
||||
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous`
|
||||
pub(crate) async fn discover_rendezvous_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<discover_rendezvous::msc4388::Request>,
|
||||
@@ -20,7 +20,7 @@ pub(crate) async fn discover_rendezvous_route(
|
||||
)))
|
||||
}
|
||||
|
||||
/// `POST /_matrix/client/unstable/io.element.msc4388/rendezvous`
|
||||
/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/`
|
||||
pub(crate) async fn create_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<create_rendezvous_session::msc4388::Request>,
|
||||
@@ -32,7 +32,7 @@ pub(crate) async fn create_rendezvous_session_route(
|
||||
services.rendezvous.create_session(body.data.clone())
|
||||
}
|
||||
|
||||
/// `PUT /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}/{txn_id}`
|
||||
/// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}`
|
||||
pub(crate) async fn update_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<update_rendezvous_session::msc4388::Request>,
|
||||
@@ -45,30 +45,16 @@ pub(crate) async fn update_rendezvous_session_route(
|
||||
)
|
||||
}
|
||||
|
||||
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
|
||||
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
|
||||
pub(crate) async fn get_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
body: Ruma<get_rendezvous_session::msc4388::Request>,
|
||||
) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||
let is_navigation_mode = headers
|
||||
.get_all("Sec-Fetch-Mode")
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.any(|mode| {
|
||||
mode.eq_ignore_ascii_case("navigate") || mode.eq_ignore_ascii_case("nested-navigate")
|
||||
});
|
||||
let is_navigation_dest = headers
|
||||
.get_all("Sec-Fetch-Dest")
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.any(|dest| {
|
||||
matches!(
|
||||
dest.to_ascii_lowercase().as_str(),
|
||||
"document" | "iframe" | "frame" | "object" | "embed" | "fencedframe"
|
||||
)
|
||||
});
|
||||
if is_navigation_mode || is_navigation_dest {
|
||||
if let Some(mode) = headers.get("Sec-Fetch-Mode")
|
||||
&& let Ok(mode) = mode.to_str()
|
||||
&& mode == "navigate"
|
||||
{
|
||||
return Err!(Request(Forbidden(
|
||||
"Rendezvous sessions do not accept browser navigation requests."
|
||||
)));
|
||||
@@ -77,7 +63,7 @@ pub(crate) async fn get_rendezvous_session_route(
|
||||
services.rendezvous.get_session(&body.id)
|
||||
}
|
||||
|
||||
/// `DELETE /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
|
||||
/// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
|
||||
pub(crate) async fn delete_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<delete_rendezvous_session::msc4388::Request>,
|
||||
|
||||
+11
-18
@@ -190,23 +190,11 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&client::well_known_policy_server)
|
||||
.ruma_route(&client::get_rtc_transports)
|
||||
.ruma_route(&client::room_initial_sync_route)
|
||||
.merge(
|
||||
Router::new()
|
||||
.ruma_route(&client::discover_rendezvous_route)
|
||||
.ruma_route(&client::create_rendezvous_session_route)
|
||||
.ruma_route(&client::update_rendezvous_session_route)
|
||||
.ruma_route(&client::get_rendezvous_session_route)
|
||||
.ruma_route(&client::delete_rendezvous_session_route)
|
||||
.layer(axum::middleware::map_response(
|
||||
async |mut response: axum::response::Response| {
|
||||
response.headers_mut().insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
http::HeaderValue::from_static("no-store"),
|
||||
);
|
||||
response
|
||||
},
|
||||
)),
|
||||
)
|
||||
.ruma_route(&client::discover_rendezvous_route)
|
||||
.ruma_route(&client::create_rendezvous_session_route)
|
||||
.ruma_route(&client::update_rendezvous_session_route)
|
||||
.ruma_route(&client::get_rendezvous_session_route)
|
||||
.ruma_route(&client::delete_rendezvous_session_route)
|
||||
.ruma_route(&client::get_authorization_server_metadata_route)
|
||||
.merge(client::oauth::router(state))
|
||||
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
|
||||
@@ -230,7 +218,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
if config.allow_federation {
|
||||
router = router
|
||||
.ruma_route(&server::get_server_version_route)
|
||||
.route("/_matrix/key/v2/server", get(server::get_server_keys_route))
|
||||
.ruma_route(&server::get_server_keys_route)
|
||||
.ruma_route(&server::get_remote_server_keys_batch_route)
|
||||
.ruma_route(&server::get_remote_server_keys_route)
|
||||
.ruma_route(&server::get_public_rooms_route)
|
||||
.ruma_route(&server::get_public_rooms_filtered_route)
|
||||
.ruma_route(&server::send_transaction_message_route)
|
||||
@@ -257,6 +247,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&server::get_content_route)
|
||||
.ruma_route(&server::get_content_thumbnail_route)
|
||||
.route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count));
|
||||
if config.experiments.msc4556.is_enabled() {
|
||||
router = router.ruma_route(&server::get_remote_server_keys_batch_v3_unstable_route);
|
||||
}
|
||||
if config.experiments.msc4560.is_enabled() {
|
||||
router = router.ruma_route(&server::get_stripped_state_route);
|
||||
}
|
||||
|
||||
+3
-17
@@ -11,11 +11,7 @@ use axum::{
|
||||
use conduwuit::{Error, Result, err, error};
|
||||
use ruma::{
|
||||
CanonicalJsonObject,
|
||||
api::{
|
||||
IncomingRequest, IncomingRequestExt,
|
||||
auth_scheme::AuthScheme,
|
||||
error::{DeserializationError, FromHttpRequestError},
|
||||
},
|
||||
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
@@ -118,18 +114,8 @@ where
|
||||
.await?;
|
||||
|
||||
// Deserialize the body
|
||||
let body_is_empty = body.is_empty();
|
||||
let body = R::try_from_http_request(request, &borrowed_path).map_err(|e| match e {
|
||||
| FromHttpRequestError::Deserialization(DeserializationError::Json(ref json_err))
|
||||
if body_is_empty || json_err.is_syntax() || json_err.is_eof() =>
|
||||
err!(Request(NotJson(debug_warn!("{e}")))),
|
||||
| FromHttpRequestError::Deserialization(DeserializationError::Utf8(_)) =>
|
||||
err!(Request(NotJson(debug_warn!("{e}")))),
|
||||
| FromHttpRequestError::Deserialization(
|
||||
DeserializationError::Ident(_) | DeserializationError::Query(_),
|
||||
) => err!(Request(InvalidParam(debug_warn!("{e}")))),
|
||||
| _ => err!(Request(BadJson(debug_warn!("{e}")))),
|
||||
})?;
|
||||
let body = R::try_from_http_request(request, &borrowed_path)
|
||||
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
|
||||
|
||||
Ok(Self { body, json_body, identity })
|
||||
}
|
||||
|
||||
+1
-24
@@ -194,10 +194,6 @@ impl CheckAuth for AccessTokenOptional {
|
||||
authentication: Self::Output,
|
||||
query: AuthQueryParams,
|
||||
) -> Result<Self::Identity> {
|
||||
if R::RATE_LIMITED && is_rendezvous_create_route(TypeId::of::<R>()) {
|
||||
services.rendezvous.check_create_ratelimit(request_ip)?;
|
||||
}
|
||||
|
||||
if let Some(authentication) = authentication {
|
||||
check_access_token(
|
||||
services,
|
||||
@@ -282,11 +278,6 @@ impl CheckAuth for NoAccessToken {
|
||||
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
|
||||
})?;
|
||||
|
||||
let is_rendezvous_session = is_rendezvous_session_route(TypeId::of::<R>());
|
||||
if R::RATE_LIMITED && is_rendezvous_session {
|
||||
services.rendezvous.check_session_ratelimit(request_ip)?;
|
||||
}
|
||||
|
||||
if let Some(authentication) = authentication {
|
||||
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
|
||||
OAuthClientScope::ApiFullAccess,
|
||||
@@ -294,7 +285,7 @@ impl CheckAuth for NoAccessToken {
|
||||
.await
|
||||
.map(Some)
|
||||
} else {
|
||||
if R::RATE_LIMITED && !is_rendezvous_session {
|
||||
if R::RATE_LIMITED {
|
||||
check_unauthenticated_request_ratelimiting(services, request_ip)?;
|
||||
}
|
||||
|
||||
@@ -442,20 +433,6 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result<Regi
|
||||
Ok(appservice_info)
|
||||
}
|
||||
|
||||
fn is_rendezvous_create_route(route: TypeId) -> bool {
|
||||
route == TypeId::of::<client::rendezvous::discover_rendezvous::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::create_rendezvous_session::msc4388::Request>()
|
||||
}
|
||||
|
||||
fn is_rendezvous_session_route(route: TypeId) -> bool {
|
||||
route == TypeId::of::<client::rendezvous::get_rendezvous_session::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::update_rendezvous_session::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::delete_rendezvous_session::msc4388::Request>()
|
||||
}
|
||||
|
||||
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
|
||||
if services
|
||||
.config
|
||||
|
||||
+295
-68
@@ -1,89 +1,316 @@
|
||||
use std::{collections::BTreeMap, mem::take, time::Duration};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
sync::Arc,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use axum::{Json, extract::State, response::IntoResponse};
|
||||
use conduwuit::{Result, utils::timepoint_from_now};
|
||||
use futures::StreamExt;
|
||||
use axum::extract::State;
|
||||
use conduwuit::{
|
||||
Err, Result,
|
||||
config::experiments::ToggledExperiment,
|
||||
debug_info,
|
||||
utils::{ReadyExt, stream::automatic_width},
|
||||
};
|
||||
use ruma::{
|
||||
MilliSecondsSinceUnixEpoch,
|
||||
api::{
|
||||
OutgoingResponseExt,
|
||||
federation::discovery::{OldVerifyKey, ServerSigningKeys, get_server_keys},
|
||||
MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId,
|
||||
api::federation::discovery::{
|
||||
ServerSigningKeys, get_remote_server_keys, get_remote_server_keys_batch,
|
||||
get_remote_server_keys_batch::v2::QueryCriteria, get_server_keys,
|
||||
},
|
||||
assign,
|
||||
serde::Raw,
|
||||
};
|
||||
use service::{server_keys, server_keys::in_one_week};
|
||||
use service::server_keys::{self, in_one_week};
|
||||
|
||||
use crate::router::Ruma;
|
||||
|
||||
/// # `GET /_matrix/key/v2/server`
|
||||
///
|
||||
/// Gets the public signing keys of this server.
|
||||
pub(crate) async fn get_server_keys_route(
|
||||
State(services): State<crate::State>,
|
||||
) -> Result<impl IntoResponse> {
|
||||
let server_name = services.globals.server_name();
|
||||
let verify_keys = BTreeMap::from([services.server_keys.active_verify_key()]);
|
||||
_body: Ruma<get_server_keys::v2::Request>,
|
||||
) -> Result<get_server_keys::v2::Response> {
|
||||
services
|
||||
.server_keys
|
||||
.build_server_keys_response()
|
||||
.await
|
||||
.map(get_server_keys::v2::Response::new)
|
||||
}
|
||||
|
||||
let old_verify_keys = if let Some(k) = &services.config.old_verify_keys {
|
||||
k.to_owned()
|
||||
} else {
|
||||
// We need to figure out any old signing keys we've acquired from
|
||||
// notaries.
|
||||
let mut keys = services.server_keys.signing_keys_for(server_name);
|
||||
let mut old_keys = BTreeMap::new();
|
||||
while let Some(resp) = keys.next().await {
|
||||
// We need to verify that this response is still trusted based on
|
||||
// the current configuration. It's possible we got this response
|
||||
// from a notary who we no longer trust.
|
||||
if resp.parsed.valid_until_ts > in_one_week() {
|
||||
continue;
|
||||
}
|
||||
let trusted = services.config.trusted_servers.iter().any(|notary| {
|
||||
server_keys::Service::verify_server_keys_response(
|
||||
&resp,
|
||||
Some((notary.server_name(), notary.verify_keys())),
|
||||
)
|
||||
.is_ok()
|
||||
});
|
||||
if !trusted {
|
||||
continue;
|
||||
}
|
||||
for (old_key_id, old_key) in resp.parsed.old_verify_keys {
|
||||
if old_key.expired_ts > resp.parsed.valid_until_ts {
|
||||
// This key expired in the future which is probably illegal
|
||||
continue;
|
||||
}
|
||||
old_keys
|
||||
.entry(old_key_id)
|
||||
.and_modify(|current_old_key: &mut OldVerifyKey| {
|
||||
// Use the lowest expiry timestamp
|
||||
if current_old_key.expired_ts > old_key.expired_ts {
|
||||
*current_old_key = old_key.clone();
|
||||
}
|
||||
})
|
||||
.or_insert(old_key);
|
||||
}
|
||||
const MAX_KEYS_PER_QUERY: usize = 16384;
|
||||
const MAX_SERVERS_PER_QUERY: usize = 4096;
|
||||
|
||||
/// # `POST /_matrix/key/v2/query`
|
||||
///
|
||||
/// Fetches remote server signing keys in bulk, seeding from the local server's
|
||||
/// database.
|
||||
///
|
||||
/// This route applies a semaphore to slow down requests that query more signing
|
||||
/// keys than is allowed by [MSC4556].
|
||||
///
|
||||
/// [MSC4556]: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
|
||||
pub(crate) async fn get_remote_server_keys_batch_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_remote_server_keys_batch::v2::Request>,
|
||||
) -> Result<get_remote_server_keys_batch::v2::Response> {
|
||||
query_inner(&services, body.body.server_keys, true)
|
||||
.await
|
||||
.map(get_remote_server_keys_batch::v2::Response::new)
|
||||
}
|
||||
|
||||
/// # `POST /_matrix/key/unstable/org.continuwuity.msc4556/query`
|
||||
/// ## `POST /_matrix/key/v3/query`
|
||||
///
|
||||
/// Fetches remote server signing keys in bulk, seeding from the local server's
|
||||
/// database.
|
||||
///
|
||||
/// MSC4556: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
|
||||
pub(crate) async fn get_remote_server_keys_batch_v3_unstable_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<ruminuwuity::federation::notary::unstable::Request>,
|
||||
) -> Result<ruminuwuity::federation::notary::unstable::Response> {
|
||||
query_inner(&services, body.body.server_keys, false)
|
||||
.await
|
||||
.map(ruminuwuity::federation::notary::unstable::Response::new)
|
||||
}
|
||||
|
||||
/// Handles querying the server keys for `/_matrix/key/*/query`.
|
||||
///
|
||||
/// `v2` should be `true` if the request path is `/_matrix/key/v2/query` - this
|
||||
/// will potentially apply a rate-limit to the request.
|
||||
async fn query_inner(
|
||||
services: &crate::State,
|
||||
body: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
|
||||
v2: bool,
|
||||
) -> Result<Vec<Raw<ServerSigningKeys>>> {
|
||||
let start = (Instant::now(), MilliSecondsSinceUnixEpoch::now());
|
||||
// If the remote server isn't asking for any keys, we can return an empty
|
||||
// array immediately.
|
||||
if body.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// Count how many keys are being requested.
|
||||
// Each server incurs a cost of at least one, and then the count of each key
|
||||
// being queried per-server.
|
||||
let total_queried_servers = body.len();
|
||||
let total_queried_keys = body
|
||||
.values()
|
||||
.fold(0_usize, |acc, q| acc.saturating_add(q.len().max(1)));
|
||||
|
||||
if !v2 && services.config.experiments.msc4556.is_enabled() {
|
||||
// If we're on the v3 endpoint, we can apply these limits explicitly.
|
||||
if total_queried_servers > MAX_SERVERS_PER_QUERY {
|
||||
return Err!(Request(TooLarge(
|
||||
"Too many server keys requested ({total_queried_servers} > \
|
||||
{MAX_SERVERS_PER_QUERY})",
|
||||
)));
|
||||
}
|
||||
old_keys
|
||||
if total_queried_keys > MAX_KEYS_PER_QUERY {
|
||||
return Err!(Request(TooLarge(
|
||||
"Too many keys requested ({total_queried_keys} > {MAX_KEYS_PER_QUERY})"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let penalise =
|
||||
total_queried_servers > MAX_SERVERS_PER_QUERY || total_queried_keys > MAX_KEYS_PER_QUERY;
|
||||
|
||||
debug_info!("Fetching {total_queried_keys} keys across {} servers", body.len());
|
||||
let mut futs: tokio::task::JoinSet<_> = tokio::task::JoinSet::new();
|
||||
|
||||
// If we're on the v2 endpoint, we aren't allowed to reject the request.
|
||||
// To avoid overloading the server, we'll apply a semaphore to limit how
|
||||
// many futures can be active at a time.
|
||||
let width = automatic_width();
|
||||
|
||||
let semaphore: Option<Arc<tokio::sync::Semaphore>> = if v2 && penalise {
|
||||
Some(Arc::new(tokio::sync::Semaphore::new(width)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let server_key = assign!(ServerSigningKeys::new(server_name.to_owned(), valid_until_ts()), {
|
||||
verify_keys,
|
||||
old_verify_keys,
|
||||
});
|
||||
for (server_name, queries) in body {
|
||||
let server_keys = services.server_keys.clone();
|
||||
let semaphore = semaphore.clone();
|
||||
|
||||
let server_key = Raw::new(&server_key)?;
|
||||
let mut response = get_server_keys::v2::Response::new(server_key)
|
||||
.try_into_http_response::<Vec<u8>>()
|
||||
.map(|mut response| take(response.body_mut()))
|
||||
.and_then(|body| serde_json::from_slice(&body).map_err(Into::into))?;
|
||||
futs.spawn_on(
|
||||
async move {
|
||||
let _permit = if let Some(sem) = semaphore {
|
||||
let cost = queries
|
||||
.len()
|
||||
.saturating_add(1)
|
||||
.min(automatic_width())
|
||||
.try_into()
|
||||
.unwrap_or(u32::MAX);
|
||||
|
||||
services.server_keys.sign_json(&mut response)?;
|
||||
sem.acquire_many_owned(cost).await.ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(Json(response))
|
||||
acquire_keys_as_notary(server_keys, server_name, queries, start.1).await
|
||||
},
|
||||
services.server.runtime(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut response = Vec::with_capacity(total_queried_keys);
|
||||
|
||||
while let Some(Ok(v)) = futs.join_next().await {
|
||||
response.extend(v);
|
||||
}
|
||||
|
||||
debug_info!(
|
||||
elapsed=?start.0.elapsed(),
|
||||
%total_queried_servers,
|
||||
%total_queried_keys,
|
||||
"Fetched {} key responses",
|
||||
response.len()
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn valid_until_ts() -> MilliSecondsSinceUnixEpoch {
|
||||
let dur = Duration::from_hours(12);
|
||||
let timepoint = timepoint_from_now(dur).expect("SystemTime should not overflow");
|
||||
MilliSecondsSinceUnixEpoch::from_system_time(timepoint).expect("UInt should not overflow")
|
||||
/// `GET /_matrix/key/v2/query/{serverName}`
|
||||
///
|
||||
/// Fetches the latest keys for a specific server name.
|
||||
pub(crate) async fn get_remote_server_keys_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_remote_server_keys::v2::Request>,
|
||||
) -> Result<get_remote_server_keys::v2::Response> {
|
||||
let server_keys = acquire_keys_as_notary(
|
||||
services.server_keys.clone(),
|
||||
body.server_name.clone(),
|
||||
BTreeMap::new(),
|
||||
body.minimum_valid_until_ts,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(get_remote_server_keys::v2::Response::new(server_keys))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(server_keys, queries, start))]
|
||||
async fn acquire_keys_as_notary(
|
||||
server_keys: Arc<server_keys::Service>,
|
||||
remote: OwnedServerName,
|
||||
queries: BTreeMap<OwnedServerSigningKeyId, QueryCriteria>,
|
||||
start: MilliSecondsSinceUnixEpoch,
|
||||
) -> Vec<Raw<ServerSigningKeys>> {
|
||||
let mut candidate_remote_keys = Vec::with_capacity(queries.len().max(1));
|
||||
|
||||
// If we haven't contacted the origin recently, we need to do that now
|
||||
// to update our caches, and we might as well use its response as a
|
||||
// candidate.
|
||||
if server_keys.origin_not_contacted_recently(&remote) {
|
||||
let min_valid_ts = queries
|
||||
.values()
|
||||
.map(|criterion| criterion.minimum_valid_until_ts.unwrap_or(start))
|
||||
.min()
|
||||
.unwrap_or(start);
|
||||
|
||||
if let Ok(remote_keys) = server_keys
|
||||
.origin_request(remote.clone(), min_valid_ts)
|
||||
.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 it expires too far in the future.
|
||||
if remote_keys.parsed.valid_until_ts > in_one_week() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Determine which requested keys (or all keys when no specific keys
|
||||
// were requested) are newly satisfied by this response.
|
||||
let newly_satisfied: Vec<OwnedServerSigningKeyId> = if queries.is_empty() {
|
||||
if remote_keys.parsed.valid_until_ts < start {
|
||||
continue;
|
||||
}
|
||||
|
||||
remote_keys
|
||||
.all_key_ids()
|
||||
.filter(|key_id| !signed_remote_key_ids.contains(*key_id))
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
} else {
|
||||
queries
|
||||
.iter()
|
||||
.filter_map(|(key_id, criterion)| {
|
||||
if signed_remote_key_ids.contains(key_id) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let minimum_valid_until_ts =
|
||||
criterion.minimum_valid_until_ts.unwrap_or(start);
|
||||
|
||||
if remote_keys.parsed.valid_until_ts < minimum_valid_until_ts {
|
||||
return None;
|
||||
}
|
||||
|
||||
let satisfied = remote_keys.parsed.verify_keys.contains_key(key_id)
|
||||
|| remote_keys.parsed.old_verify_keys.get(key_id).is_some_and(
|
||||
|old_key| {
|
||||
criterion
|
||||
.minimum_valid_until_ts
|
||||
.is_none_or(|min_ts| old_key.expired_ts >= min_ts)
|
||||
},
|
||||
);
|
||||
|
||||
satisfied.then(|| key_id.to_owned())
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
if newly_satisfied.is_empty() {
|
||||
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);
|
||||
signed_remote_key_ids.extend(newly_satisfied);
|
||||
}
|
||||
|
||||
signed_remote_key_responses
|
||||
}
|
||||
@@ -118,6 +118,22 @@ pub struct Experiments {
|
||||
/// default: false
|
||||
#[serde(default)]
|
||||
pub msc4494: SimpleExperiment,
|
||||
/// MSC4556: Notary request limits
|
||||
///
|
||||
/// Creates a new key notary server route that has stricter limits on how
|
||||
/// many signing keys can be requested in one query, to avoid a resource
|
||||
/// exhaustion exploit vector in the existing key notary endpoint.
|
||||
///
|
||||
/// Continuwuity mitigates the exploit vector in the old notary endpoint
|
||||
/// anyway, so you do not need to enable this to be protected.
|
||||
///
|
||||
/// Requires that remote servers support this MSC before it does anything.
|
||||
///
|
||||
/// https://github.com/matrix-org/matrix-spec-proposals/pull/4556
|
||||
///
|
||||
/// default: false
|
||||
#[serde(default)]
|
||||
pub msc4556: SimpleExperiment,
|
||||
/// MSC4560: Stripped state requests over federation
|
||||
///
|
||||
/// Implements a more efficient way for servers to acquire and serve
|
||||
|
||||
+10
-18
@@ -1154,10 +1154,7 @@ pub struct Config {
|
||||
/// (trusted key notary servers), as well as serve as trusted servers for
|
||||
/// other operations like backfill and event fetching.
|
||||
///
|
||||
/// Currently, continuwuity doesn't support inbound key requests, so
|
||||
/// this list should only contain other Synapse servers.
|
||||
///
|
||||
/// example: ["matrix.org", "starstruck.systems"]
|
||||
/// example: ["continuwuity.org", "matrix.org"]
|
||||
///
|
||||
/// It is possible to restrict which signing keys trusted servers are
|
||||
/// allowed to sign responses with. Without configuring this, all responses
|
||||
@@ -1194,7 +1191,7 @@ pub struct Config {
|
||||
/// empty list (`[]`) to operate without trusted server assistance, but this
|
||||
/// is discouraged for performance and reliability reasons.
|
||||
///
|
||||
/// default: ["matrix.org"]
|
||||
/// default: ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
|
||||
#[serde(default = "default_trusted_servers")]
|
||||
pub trusted_servers: Vec<TrustedServer>,
|
||||
|
||||
@@ -2823,12 +2820,10 @@ pub struct OidcConfig {
|
||||
|
||||
/// Additional scopes Continuwuity should request from the IDP. This may be
|
||||
/// necessary to access certain claims. Continuwuity always requests the
|
||||
/// `openid` scope, regardless of the contents of this option,
|
||||
/// and will also request the `profile` scope by default if this option is
|
||||
/// not set.
|
||||
/// `openid` scope.
|
||||
///
|
||||
/// default: ["profile"]
|
||||
#[serde(default = "default_additional_scopes")]
|
||||
/// default: []
|
||||
#[serde(default)]
|
||||
pub additional_scopes: Vec<Scope>,
|
||||
|
||||
/// Additional trusted audiences that Continuwuity will accept in the `aud`
|
||||
@@ -3264,12 +3259,11 @@ fn default_otlp_filter() -> String {
|
||||
fn default_tracing_flame_output_path() -> String { "./tracing.folded".to_owned() }
|
||||
|
||||
fn default_trusted_servers() -> Vec<TrustedServer> {
|
||||
// TODO(nex): Once we can be a notary, add maintainer(?) homeservers here.
|
||||
// Rationale: Users are already running our code, arguably that's a higher
|
||||
// level of trust than is assigned to notaries in the first place.
|
||||
// We should still remind everyone that notaries are evil and out to get you
|
||||
// and to replace this list with servers they actually trust.
|
||||
let trusted_servers = vec![ruma::owned_server_name!("matrix.org")];
|
||||
let trusted_servers = vec![
|
||||
ruma::owned_server_name!("continuwuity.org"),
|
||||
ruma::owned_server_name!("continuwuity.rocks"),
|
||||
ruma::owned_server_name!("matrix.org"),
|
||||
];
|
||||
trusted_servers
|
||||
.into_iter()
|
||||
.map(TrustedServer::Name)
|
||||
@@ -3448,8 +3442,6 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
|
||||
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
|
||||
}
|
||||
|
||||
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
|
||||
|
||||
// NOTE: This must be declared *after* every config struct in this file. The
|
||||
// example config generator writes sections in macro expansion order, and the
|
||||
// `global` section truncates the file, so declaring this module any earlier
|
||||
|
||||
@@ -171,14 +171,13 @@ impl Error {
|
||||
/// Returns the Matrix error code / error kind
|
||||
#[inline]
|
||||
pub fn kind(&self) -> ErrorKind {
|
||||
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
|
||||
use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
|
||||
|
||||
match self {
|
||||
| Self::Federation(_, error) | Self::Ruma(error) =>
|
||||
response::ruma_error_kind(error).clone(),
|
||||
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
||||
| Self::FeatureDisabled(..) => Unrecognized,
|
||||
| Self::Path(_) | Self::Query(_) => InvalidParam,
|
||||
| _ => Unknown,
|
||||
}
|
||||
}
|
||||
@@ -195,7 +194,6 @@ impl Error {
|
||||
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
|
||||
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
| Self::Conflict(_) => StatusCode::CONFLICT,
|
||||
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
|
||||
| Self::Io(error) => response::io_error_code(error.kind()),
|
||||
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
|
||||
| _ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
|
||||
@@ -73,9 +73,6 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
|
||||
// 413
|
||||
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
|
||||
// 409
|
||||
| ConcurrentWrite => StatusCode::CONFLICT,
|
||||
|
||||
// 404
|
||||
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
|
||||
|
||||
|
||||
@@ -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 policy;
|
||||
pub mod pushers;
|
||||
|
||||
pub mod federation;
|
||||
@@ -1,38 +1,25 @@
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
use conduwuit::{
|
||||
Err, Error, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils,
|
||||
};
|
||||
use governor::{
|
||||
DefaultKeyedRateLimiter, Quota, RateLimiter,
|
||||
clock::{Clock, DefaultClock},
|
||||
};
|
||||
use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils};
|
||||
use lru_cache::LruCache;
|
||||
use nonzero_ext::nonzero;
|
||||
use ruma::{
|
||||
OwnedTransactionId,
|
||||
api::{
|
||||
client::rendezvous::{
|
||||
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
||||
update_rendezvous_session,
|
||||
},
|
||||
error::{ErrorKind, LimitExceededErrorData, RetryAfter},
|
||||
api::client::rendezvous::{
|
||||
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
||||
update_rendezvous_session,
|
||||
},
|
||||
};
|
||||
|
||||
pub struct Service {
|
||||
sessions: SyncMutex<LruCache<String, Session>>,
|
||||
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||
}
|
||||
|
||||
struct Session {
|
||||
data: String,
|
||||
created_at: Instant,
|
||||
created_at: SystemTime,
|
||||
last_sequence_token: String,
|
||||
transaction_sequences: LruCache<OwnedTransactionId, String>,
|
||||
}
|
||||
@@ -40,31 +27,20 @@ struct Session {
|
||||
impl Session {
|
||||
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
|
||||
|
||||
fn new(data: String, sequence_token: String, now: Instant) -> Self {
|
||||
fn new(data: String, sequence_token: String) -> Self {
|
||||
Self {
|
||||
data,
|
||||
created_at: now,
|
||||
created_at: SystemTime::now(),
|
||||
last_sequence_token: sequence_token,
|
||||
transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES),
|
||||
}
|
||||
}
|
||||
|
||||
fn time_remaining(&self, now: Instant) -> Option<Duration> {
|
||||
let age = now.saturating_duration_since(self.created_at);
|
||||
(age < Service::SESSION_MAX_AGE)
|
||||
.then(|| Service::SESSION_MAX_AGE.saturating_sub(age))
|
||||
.filter(|remaining| !remaining.is_zero())
|
||||
}
|
||||
|
||||
fn is_expired(&self, now: Instant) -> bool { self.time_remaining(now).is_none() }
|
||||
}
|
||||
|
||||
impl crate::Service for Service {
|
||||
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
Ok(Arc::new(Self {
|
||||
sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)),
|
||||
create_ratelimiter: RateLimiter::keyed(Self::CREATE_RATELIMIT),
|
||||
session_ratelimiter: RateLimiter::keyed(Self::SESSION_RATELIMIT),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -72,64 +48,25 @@ impl crate::Service for Service {
|
||||
}
|
||||
|
||||
impl Service {
|
||||
const CREATE_RATELIMIT: Quota = Quota::per_minute(nonzero!(30_u32));
|
||||
const MAX_DATA_SIZE_BYTES: usize = 4096;
|
||||
const MAX_SESSIONS: usize = 256;
|
||||
const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
|
||||
const SESSION_RATELIMIT: Quota = Quota::per_minute(nonzero!(300_u32));
|
||||
const TOKEN_LENGTH: usize = 32;
|
||||
|
||||
pub fn check_create_ratelimit(&self, ip: IpAddr) -> Result<()> {
|
||||
Self::check_ratelimiter(&self.create_ratelimiter, ip)
|
||||
}
|
||||
|
||||
pub fn check_session_ratelimit(&self, ip: IpAddr) -> Result<()> {
|
||||
Self::check_ratelimiter(&self.session_ratelimiter, ip)
|
||||
}
|
||||
|
||||
fn check_ratelimiter(
|
||||
ratelimiter: &DefaultKeyedRateLimiter<IpAddr>,
|
||||
ip: IpAddr,
|
||||
) -> Result<()> {
|
||||
if let Err(not_until) = ratelimiter.check_key(&ip) {
|
||||
let wait_time = not_until.wait_time_from(DefaultClock::default().now());
|
||||
let mut data = LimitExceededErrorData::new();
|
||||
data.retry_after = Some(RetryAfter::Delay(wait_time));
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::LimitExceeded(data),
|
||||
"Rate limit exceeded.",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) }
|
||||
|
||||
fn is_valid_opaque_id(id: &str) -> bool {
|
||||
!id.is_empty()
|
||||
&& id.len() <= 255
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~'))
|
||||
}
|
||||
|
||||
/// Lock and fetch an unexpired rendezvous session.
|
||||
fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
||||
self.lock_session_at(id, Instant::now())
|
||||
}
|
||||
|
||||
fn lock_session_at(
|
||||
&self,
|
||||
id: &str,
|
||||
now: Instant,
|
||||
) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
||||
// We don't clear out expired sessions manually, the LRU cache will
|
||||
// evict them over time
|
||||
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
|
||||
sessions
|
||||
.get_mut(id)
|
||||
.filter(|session| !session.is_expired(now))
|
||||
.filter(|session| {
|
||||
SystemTime::now()
|
||||
.duration_since(session.created_at)
|
||||
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
|
||||
})
|
||||
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
|
||||
})
|
||||
.map_err(at!(1))
|
||||
@@ -149,7 +86,7 @@ impl Service {
|
||||
|
||||
self.sessions
|
||||
.lock()
|
||||
.insert(id.clone(), Session::new(data, sequence_token.clone(), Instant::now()));
|
||||
.insert(id.clone(), Session::new(data, sequence_token.clone()));
|
||||
|
||||
Ok(create_rendezvous_session::msc4388::Response::new(
|
||||
id,
|
||||
@@ -166,12 +103,6 @@ impl Service {
|
||||
sequence_token: String,
|
||||
data: String,
|
||||
) -> Result<update_rendezvous_session::msc4388::Response> {
|
||||
if !Self::is_valid_opaque_id(transaction.as_str()) {
|
||||
return Err!(Request(InvalidParam(
|
||||
"Transaction ID does not comply with the opaque identifier grammar"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut session = self.lock_session(id)?;
|
||||
|
||||
// If the provided transaction ID was used already, we have to return
|
||||
@@ -206,12 +137,13 @@ impl Service {
|
||||
|
||||
/// Look up a rendezvous session by ID.
|
||||
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||
let now = Instant::now();
|
||||
let session = self.lock_session_at(id, now)?;
|
||||
let session = self.lock_session(id)?;
|
||||
|
||||
let session_time_remaining = session
|
||||
.time_remaining(now)
|
||||
.unwrap_or_else(|| Duration::from_millis(1));
|
||||
let session_age = SystemTime::now()
|
||||
.duration_since(session.created_at)
|
||||
.unwrap_or(Duration::MAX);
|
||||
|
||||
let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age);
|
||||
|
||||
Ok(get_rendezvous_session::msc4388::Response::new(
|
||||
session.last_sequence_token.clone(),
|
||||
@@ -226,12 +158,8 @@ impl Service {
|
||||
id: &str,
|
||||
) -> Result<delete_rendezvous_session::msc4388::Response> {
|
||||
let mut sessions = self.sessions.lock();
|
||||
let now = Instant::now();
|
||||
|
||||
if sessions
|
||||
.remove(id)
|
||||
.is_some_and(|session| !session.is_expired(now))
|
||||
{
|
||||
if sessions.remove(id).is_some() {
|
||||
Ok(delete_rendezvous_session::msc4388::Response::new())
|
||||
} else {
|
||||
Err!(Request(NotFound("Unknown session")))
|
||||
|
||||
@@ -158,7 +158,7 @@ impl super::Service {
|
||||
|
||||
if let Some(server_keys) = self.get_signing_key(origin, key_id).await
|
||||
&& let Some(key) =
|
||||
verify_key_from_response(key_id, &server_keys, min_valid_ts)
|
||||
verify_key_from_response(key_id, &server_keys.parsed, min_valid_ts)
|
||||
{
|
||||
trace!(%origin, %key_id, ?min_valid_ts, "Verify key exists locally");
|
||||
Self::track_one_result(
|
||||
@@ -242,7 +242,6 @@ impl super::Service {
|
||||
}
|
||||
};
|
||||
trace!(?origin_response.raw, "Got signing key response from origin");
|
||||
self.add_signing_keys(&origin_response);
|
||||
Self::track_result(&mut result, &mut still_missing, &origin_response.parsed);
|
||||
if still_missing.is_empty() {
|
||||
break;
|
||||
@@ -301,7 +300,6 @@ impl super::Service {
|
||||
continue;
|
||||
};
|
||||
trace!(response=?res.raw, "Got signing key response from origin");
|
||||
self.add_signing_keys(&res);
|
||||
Self::track_result(&mut result, &mut still_missing, &res.parsed);
|
||||
if still_missing.is_empty() {
|
||||
break;
|
||||
@@ -387,7 +385,7 @@ impl super::Service {
|
||||
if let Some(vk) = self
|
||||
.get_signing_key(origin, key_id)
|
||||
.await
|
||||
.and_then(|ssk| verify_key_from_response(key_id, &ssk, min_valid_ts))
|
||||
.and_then(|ssk| verify_key_from_response(key_id, &ssk.parsed, min_valid_ts))
|
||||
{
|
||||
trace!("Found verify key locally");
|
||||
return Some(vk);
|
||||
@@ -401,7 +399,6 @@ impl super::Service {
|
||||
.ok()?;
|
||||
|
||||
verify_key_from_response(key_id, &response.parsed, min_valid_ts)
|
||||
.inspect(|_| self.add_signing_keys(&response))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,32 +5,43 @@ mod sign;
|
||||
mod util;
|
||||
mod verify;
|
||||
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use assign::assign;
|
||||
use async_trait::async_trait;
|
||||
use conduwuit::{
|
||||
Result, Server,
|
||||
utils::{IterStream, ReadyExt, stream::TryIgnore},
|
||||
Result, Server, SyncRwLock, debug_info,
|
||||
utils::{IterStream, ReadyExt, stream::TryIgnore, timepoint_from_now, to_canonical_object},
|
||||
};
|
||||
use database::{Deserialized, Ignore, Interfix, Json, Map};
|
||||
use futures::{Stream, StreamExt};
|
||||
pub use request::in_one_week;
|
||||
use ruma::{
|
||||
CanonicalJsonObject, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName,
|
||||
ServerSigningKeyId,
|
||||
api::federation::discovery::{ServerSigningKeys, VerifyKey},
|
||||
CanonicalJsonObject, MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId,
|
||||
ServerName, ServerSigningKeyId,
|
||||
api::federation::discovery::{OldVerifyKey, ServerSigningKeys, VerifyKey},
|
||||
room_version_rules::RoomVersionRules,
|
||||
serde::Raw,
|
||||
signatures::{Ed25519KeyPair, PublicKeyMap, PublicKeySet},
|
||||
};
|
||||
use serde_json::value::to_raw_value;
|
||||
use verify::IncomingServerKeys;
|
||||
pub use verify::strip_extraneous_signatures;
|
||||
|
||||
use crate::{Dep, globals, sending, server_keys::util::required_keys};
|
||||
|
||||
const VALID_UNTIL_TS_DURATION: Duration = Duration::from_hours(12);
|
||||
|
||||
pub struct Service {
|
||||
keypair: Box<Ed25519KeyPair>,
|
||||
verify_keys: VerifyKeys,
|
||||
services: Services,
|
||||
db: Data,
|
||||
last_lookup: SyncRwLock<HashMap<OwnedServerName, Instant>>,
|
||||
}
|
||||
|
||||
struct Services {
|
||||
@@ -47,6 +58,7 @@ pub type VerifyKeys = BTreeMap<OwnedServerSigningKeyId, VerifyKey>;
|
||||
pub type PubKeyMap = PublicKeyMap;
|
||||
pub type PubKeys = PublicKeySet;
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Service for Service {
|
||||
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
let (keypair, verify_keys) = keypair::init(args.db)?;
|
||||
@@ -63,9 +75,12 @@ impl crate::Service for Service {
|
||||
db: Data {
|
||||
servernamekeyid_response: args.db["servernamekeyid_response"].clone(),
|
||||
},
|
||||
last_lookup: SyncRwLock::new(HashMap::new()),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn clear_cache(&self) { self.last_lookup.write().clear(); }
|
||||
|
||||
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
|
||||
}
|
||||
|
||||
@@ -133,7 +148,9 @@ impl Service {
|
||||
key_id: &ServerSigningKeyId,
|
||||
minimum_valid_ts: MilliSecondsSinceUnixEpoch,
|
||||
) -> bool {
|
||||
let Some(keys) = self.get_signing_key(origin, key_id).await else {
|
||||
let Some(IncomingServerKeys { parsed: keys, .. }) =
|
||||
self.get_signing_key(origin, key_id).await
|
||||
else {
|
||||
// We have no keys for this server
|
||||
return false;
|
||||
};
|
||||
@@ -161,12 +178,13 @@ impl Service {
|
||||
&self,
|
||||
origin: &ServerName,
|
||||
key_id: &ServerSigningKeyId,
|
||||
) -> Option<ServerSigningKeys> {
|
||||
) -> Option<IncomingServerKeys> {
|
||||
self.db
|
||||
.servernamekeyid_response
|
||||
.qry(&(origin.as_str(), key_id.as_str()))
|
||||
.await
|
||||
.deserialized::<ServerSigningKeys>()
|
||||
.deserialized::<Raw<ServerSigningKeys>>()
|
||||
.and_then(|r| r.try_into().map_err(Into::into))
|
||||
.ok()
|
||||
}
|
||||
|
||||
@@ -188,6 +206,8 @@ impl Service {
|
||||
}
|
||||
|
||||
/// Returns the stored server signing keys responses for the origin.
|
||||
///
|
||||
/// Does not imply that the stored responses are still in-date.
|
||||
pub fn signing_keys_for<'a>(
|
||||
&'a self,
|
||||
origin: &'a ServerName,
|
||||
@@ -199,4 +219,114 @@ impl Service {
|
||||
.map(|(_, v): (Ignore, Raw<ServerSigningKeys>)| v.try_into().map_err(Into::into))
|
||||
.ignore_err()
|
||||
}
|
||||
|
||||
/// Determines if the server may contact the origin server to fetch keys
|
||||
/// when acting as a notary server. This limits origin lookups to once per
|
||||
/// minute, which prevents amplification attacks.
|
||||
#[must_use]
|
||||
pub fn origin_not_contacted_recently(&self, server_name: &ServerName) -> bool {
|
||||
if server_name == self.services.server.name {
|
||||
// We always intercept origin requests to us with
|
||||
// build_server_keys_response, so this is equivalent to
|
||||
// calling `/_matrix/key/v2/server`.
|
||||
return true;
|
||||
}
|
||||
self.last_lookup
|
||||
.read()
|
||||
.get(server_name)
|
||||
.is_none_or(|last| last.elapsed() >= Duration::from_mins(1))
|
||||
}
|
||||
|
||||
/// Generates a signing key response to serve to `/_matrix/key/v2/server`.
|
||||
pub async fn build_server_keys_response(&self) -> Result<Raw<ServerSigningKeys>> {
|
||||
let verify_keys = BTreeMap::from([self.active_verify_key()]);
|
||||
let old_verify_keys = match &self.services.server.config.old_verify_keys {
|
||||
| Some(old_verify_keys) => old_verify_keys.to_owned(),
|
||||
| None => self.discover_old_signing_keys().await,
|
||||
};
|
||||
let valid_until_ts = timepoint_from_now(VALID_UNTIL_TS_DURATION)
|
||||
.ok()
|
||||
.and_then(MilliSecondsSinceUnixEpoch::from_system_time)
|
||||
.expect("key validity period must be before the heat death of the universe");
|
||||
let server_keys = assign!(
|
||||
ServerSigningKeys::new(self.services.server.name.clone(), valid_until_ts),
|
||||
{verify_keys, old_verify_keys}
|
||||
);
|
||||
let mut canonical_obj = to_canonical_object(&server_keys)?;
|
||||
self.sign_json(&mut canonical_obj)
|
||||
.and_then(|()| to_raw_value(&canonical_obj).map_err(Into::into))
|
||||
.map(Raw::from_json)
|
||||
}
|
||||
|
||||
async fn discover_old_signing_keys(&self) -> BTreeMap<OwnedServerSigningKeyId, OldVerifyKey> {
|
||||
let now = MilliSecondsSinceUnixEpoch::now();
|
||||
let mut keys = self.signing_keys_for(&self.services.server.name);
|
||||
let mut old_keys = BTreeMap::new();
|
||||
while let Some(resp) = keys.next().await {
|
||||
// We need to verify that this response is still trusted based on
|
||||
// the current configuration. It's possible we got this response
|
||||
// from a notary who we no longer trust.
|
||||
if resp.parsed.valid_until_ts > in_one_week() || resp.parsed.valid_until_ts < now {
|
||||
continue;
|
||||
}
|
||||
let trusted = self
|
||||
.services
|
||||
.server
|
||||
.config
|
||||
.trusted_servers
|
||||
.iter()
|
||||
.any(|notary| {
|
||||
Self::verify_server_keys_response(
|
||||
&resp,
|
||||
Some((notary.server_name(), notary.verify_keys())),
|
||||
)
|
||||
.is_ok()
|
||||
});
|
||||
if !trusted {
|
||||
continue;
|
||||
}
|
||||
for (old_key_id, old_key) in resp.parsed.old_verify_keys {
|
||||
if old_key.expired_ts > resp.parsed.valid_until_ts {
|
||||
// This key expired in the future which is probably illegal
|
||||
continue;
|
||||
}
|
||||
old_keys
|
||||
.entry(old_key_id)
|
||||
.and_modify(|current_old_key: &mut OldVerifyKey| {
|
||||
// Use the lowest expiry timestamp
|
||||
if current_old_key.expired_ts > old_key.expired_ts {
|
||||
*current_old_key = old_key.clone();
|
||||
}
|
||||
})
|
||||
.or_insert(old_key);
|
||||
}
|
||||
}
|
||||
|
||||
old_keys
|
||||
}
|
||||
|
||||
/// Canonicalize and sign another server's signing keys.
|
||||
pub fn self_sign_signing_keys(
|
||||
&self,
|
||||
remote_server: &ServerName,
|
||||
remote_keys: &Raw<ServerSigningKeys>,
|
||||
) -> Result<Raw<ServerSigningKeys>> {
|
||||
let this_server = self.services.globals.server_name();
|
||||
|
||||
let mut canonical = to_canonical_object(remote_keys)?;
|
||||
|
||||
if remote_server == this_server {
|
||||
debug_info!(
|
||||
%remote_server,
|
||||
object=?remote_keys,
|
||||
"Refusing to sign our own signing keys response (should already be signed)"
|
||||
);
|
||||
} else {
|
||||
self.sign_json(&mut canonical)?;
|
||||
|
||||
strip_extraneous_signatures(&mut canonical, remote_server, &[this_server]);
|
||||
}
|
||||
|
||||
Ok(Raw::<ServerSigningKeys>::from_json(to_raw_value(&canonical)?))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::{collections::BTreeMap, time::Instant};
|
||||
|
||||
use conduwuit::{Err, Result, trace, utils::millis_since_unix_epoch, warn};
|
||||
use ruma::{
|
||||
@@ -31,6 +31,23 @@ impl super::Service {
|
||||
) -> Result<IncomingServerKeys> {
|
||||
use get_server_keys::v2::Request;
|
||||
|
||||
if target == self.services.server.name {
|
||||
return self
|
||||
.build_server_keys_response()
|
||||
.await
|
||||
.and_then(|r| r.try_into().map_err(Into::into));
|
||||
}
|
||||
|
||||
// N.B. The "last lookup" is written before the request is actually made
|
||||
// to prevent concurrent notary requests from spawning... concurrent
|
||||
// origin requests, especially if the origin is slow.
|
||||
// This has the downside that, if the origin is temporarily unreachable
|
||||
// (including if we're backing off from it), the notary might take an
|
||||
// additional minute to recover compared to the rest of the server. This
|
||||
// is deemed acceptable.
|
||||
self.last_lookup
|
||||
.write()
|
||||
.insert(target.clone(), Instant::now());
|
||||
let raw_server_key = self
|
||||
.services
|
||||
.sending
|
||||
@@ -66,6 +83,8 @@ impl super::Service {
|
||||
)));
|
||||
}
|
||||
|
||||
self.add_signing_keys(&server_signing_key);
|
||||
|
||||
Ok(server_signing_key)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ use conduwuit::{
|
||||
Err, Result, matrix::event::gen_event_id_canonical_json, trace, utils::to_canonical_object,
|
||||
};
|
||||
use ruma::{
|
||||
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, ServerName, SigningKeyAlgorithm,
|
||||
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, ServerName, ServerSigningKeyId,
|
||||
SigningKeyAlgorithm,
|
||||
api::federation::discovery::ServerSigningKeys,
|
||||
room_version_rules::RoomVersionRules,
|
||||
serde::{Base64, Raw, base64::Standard},
|
||||
@@ -35,6 +36,17 @@ impl TryFrom<&Raw<ServerSigningKeys>> for IncomingServerKeys {
|
||||
}
|
||||
}
|
||||
|
||||
impl IncomingServerKeys {
|
||||
/// Returns an iterator of every key ID in this key response.
|
||||
pub fn all_key_ids(&self) -> impl Iterator<Item = &ServerSigningKeyId> {
|
||||
self.parsed
|
||||
.verify_keys
|
||||
.keys()
|
||||
.chain(self.parsed.old_verify_keys.keys())
|
||||
.map(|key| &**key)
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Service {
|
||||
/// Validates the incoming event only using locally known verification keys.
|
||||
/// Inserts the calculated event ID into the event_id field upon success.
|
||||
@@ -107,7 +119,7 @@ impl super::Service {
|
||||
pubkey_map.insert(incoming.parsed.server_name.to_string(), set);
|
||||
|
||||
let mut canonical = to_canonical_object(&incoming.raw)?;
|
||||
Self::strip_extraneous_signatures(&mut canonical, &incoming.parsed.server_name, &[]);
|
||||
strip_extraneous_signatures(&mut canonical, &incoming.parsed.server_name, &[]);
|
||||
ruma::signatures::verify_json(&pubkey_map, &canonical).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -163,22 +175,30 @@ impl super::Service {
|
||||
"No valid signature from {notary_name} present on signing keys response"
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn strip_extraneous_signatures(
|
||||
canonical: &mut CanonicalJsonObject,
|
||||
origin: &ServerName,
|
||||
notaries: &[&ServerName],
|
||||
) {
|
||||
canonical.entry("signatures".to_owned()).and_modify(|sigs| {
|
||||
sigs.as_object_mut().map(|s| {
|
||||
s.retain(|server_name, _| {
|
||||
let Ok(server_name) = ServerName::parse(server_name) else { return false };
|
||||
origin == server_name || notaries.iter().any(|ns| *ns == server_name)
|
||||
});
|
||||
Some(s)
|
||||
/// Removes extraneous signatures from the signature map. This is done to avoid
|
||||
/// leaking the signatures from notaries we've used, in case the response is
|
||||
/// being forwarded to a third party. This also reduces the risk of accidentally
|
||||
/// trusting a notary's signature as the origin's signature if `notaries` is
|
||||
/// empty.
|
||||
///
|
||||
/// Infallible & mutates the original canonical JSON object. Signatures by
|
||||
/// server names that cannot be parsed are always removed.
|
||||
pub fn strip_extraneous_signatures(
|
||||
canonical: &mut CanonicalJsonObject,
|
||||
origin: &ServerName,
|
||||
notaries: &[&ServerName],
|
||||
) {
|
||||
canonical.entry("signatures".to_owned()).and_modify(|sigs| {
|
||||
sigs.as_object_mut().map(|s| {
|
||||
s.retain(|server_name, _| {
|
||||
let Ok(server_name) = ServerName::parse(server_name) else { return false };
|
||||
origin == server_name || notaries.iter().any(|ns| *ns == server_name)
|
||||
});
|
||||
Some(s)
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -348,8 +348,8 @@ impl Service {
|
||||
.compatibility_mode()
|
||||
.uiaa_available()
|
||||
{
|
||||
return Err!(Request(Forbidden(
|
||||
"User-interactive authentication is not available on this server."
|
||||
return Err!(Request(Unrecognized(
|
||||
"User-interactive authentication is unavailable on this server"
|
||||
)));
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user