Compare commits

..
20 changed files with 241 additions and 657 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
Added support for acting as a trusted server, meaning the `trusted_servers` list can consist of servers that are either Synapse OR continuwuity.
+1
View File
@@ -0,0 +1 @@
Network issues while refreshing an access token will no longer cause OAuth-compatible clients to be forcibly logged out. Contributed by @ginger.
+5 -18
View File
@@ -1043,7 +1043,10 @@
# (trusted key notary servers), as well as serve as trusted servers for
# other operations like backfill and event fetching.
#
# example: ["continuwuity.org", "matrix.org"]
# Currently, continuwuity doesn't support inbound key requests, so
# this list should only contain other Synapse servers.
#
# example: ["matrix.org", "starstruck.systems"]
#
# It is possible to restrict which signing keys trusted servers are
# allowed to sign responses with. Without configuring this, all responses
@@ -1081,7 +1084,7 @@
# is discouraged for performance and reliability reasons.
#
# env: CONTINUWUITY_TRUSTED_SERVERS
#trusted_servers = ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
#trusted_servers = ["matrix.org"]
# Whether to prioritise trusted server lookups over origin server lookups.
#
@@ -2778,22 +2781,6 @@
# 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
+1 -6
View File
@@ -218,9 +218,7 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
if config.allow_federation {
router = router
.ruma_route(&server::get_server_version_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)
.route("/_matrix/key/v2/server", get(server::get_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)
@@ -247,9 +245,6 @@ 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);
}
+22 -6
View File
@@ -319,6 +319,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
if services
.users
@@ -333,12 +346,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
let mut user_scopes = if let Some(session_info) = &session_info {
session_info.scopes()
@@ -416,6 +423,15 @@ async fn check_access_token(
sender_device,
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 {
Err(Error::Request(
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
+69 -377
View File
@@ -1,397 +1,89 @@
use std::{
collections::{BTreeMap, HashMap, HashSet},
ops::Index,
sync::Arc,
time::Instant,
};
use std::{collections::BTreeMap, mem::take, time::Duration};
use axum::extract::State;
use conduwuit::{
Err, Result,
config::experiments::ToggledExperiment,
debug, debug_info, error,
utils::{
ReadyExt,
stream::{BroadbandExt, automatic_width},
to_canonical_object,
},
};
use axum::{Json, extract::State, response::IntoResponse};
use conduwuit::{Result, utils::timepoint_from_now};
use futures::StreamExt;
use ruma::{
MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId, ServerName,
api::federation::discovery::{
ServerSigningKeys, get_remote_server_keys, get_remote_server_keys_batch,
get_remote_server_keys_batch::v2::QueryCriteria, get_server_keys,
MilliSecondsSinceUnixEpoch,
api::{
OutgoingResponseExt,
federation::discovery::{OldVerifyKey, ServerSigningKeys, get_server_keys},
},
assign,
serde::Raw,
};
use serde_json::value::to_raw_value;
use service::{server_keys, server_keys::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>,
_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)
}
) -> Result<impl IntoResponse> {
let server_name = services.globals.server_name();
let verify_keys = BTreeMap::from([services.server_keys.active_verify_key()]);
const MAX_KEYS_PER_QUERY: usize = 16384;
const MAX_SERVERS_PER_QUERY: usize = 4096;
/// # `POST /_matrix/key/v2/query`
///
/// Fetches remote server signing keys in bulk, seeding from the local server's
/// database.
///
/// This route applies a semaphore to slow down requests that query more signing
/// keys than is allowed by [MSC4556].
///
/// [MSC4556]: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
pub(crate) async fn get_remote_server_keys_batch_route(
State(services): State<crate::State>,
body: Ruma<get_remote_server_keys_batch::v2::Request>,
) -> Result<get_remote_server_keys_batch::v2::Response> {
query_inner(&services, &body.server_keys, true)
.await
.map(get_remote_server_keys_batch::v2::Response::new)
}
/// # `POST /_matrix/key/unstable/org.continuwuity.msc4556/query`
/// ## `POST /_matrix/key/v3/query`
///
/// Fetches remote server signing keys in bulk, seeding from the local server's
/// database.
///
/// MSC4556: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
pub(crate) async fn get_remote_server_keys_batch_v3_unstable_route(
State(services): State<crate::State>,
body: Ruma<ruminuwuity::federation::notary::unstable::Request>,
) -> Result<ruminuwuity::federation::notary::unstable::Response> {
query_inner(&services, &body.server_keys, false)
.await
.map(ruminuwuity::federation::notary::unstable::Response::new)
}
/// Handles querying the server keys for `/_matrix/key/*/query`.
///
/// `v2` should be `true` if the request path is `/_matrix/key/v2/query` - this
/// will potentially apply a rate-limit to the request.
async fn query_inner(
services: &crate::State,
body: &BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
v2: bool,
) -> Result<Vec<Raw<ServerSigningKeys>>> {
let start = (Instant::now(), MilliSecondsSinceUnixEpoch::now());
// If the remote server isn't asking for any keys, we can return an empty
// array immediately.
if body.is_empty() {
return Ok(Vec::new());
}
// Count how many keys are being requested.
// Each server incurs a cost of at least one, and then the count of each key
// being queried per-server.
let total_queried_servers = body.len();
let total_queried_keys = body
.values()
.fold(0_usize, |acc, q| acc.saturating_add(q.len().max(1)));
if !v2 && services.config.experiments.msc4556.is_enabled() {
// If we're on the v3 endpoint, we can apply these limits explicitly.
if total_queried_servers > MAX_SERVERS_PER_QUERY {
return Err!(Request(TooLarge(
"Too many server keys requested ({total_queried_servers} > \
{MAX_SERVERS_PER_QUERY}",
)));
}
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 sem = if v2 && penalise {
Some(Arc::new(tokio::sync::Semaphore::new(width)))
let old_verify_keys = if let Some(k) = &services.config.old_verify_keys {
k.to_owned()
} else {
None
};
for (server_name, queries) in body.clone() {
futs.spawn_on(
acquire_keys_as_notary(
services.server_keys.clone(),
services.globals.server_name().to_owned(),
server_name,
queries,
start.1,
sem.clone(),
),
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)
}
async fn sign_ssk(
server_keys: &server_keys::Service,
ssk: &Raw<ServerSigningKeys>,
server_name: &ServerName,
our_name: &ServerName,
) -> Result<Raw<ServerSigningKeys>> {
if server_name == our_name {
// Should already be signed by us if we got this far.
debug_info!(
object=?ssk,
%server_name,
%our_name,
"Refusing to sign our own signing keys response (should already be signed)"
);
return to_raw_value(ssk)
.map(Raw::<ServerSigningKeys>::from_json)
.map_err(Into::into);
}
let mut canonical = to_canonical_object(ssk)?;
server_keys.sign_json(&mut canonical)?;
server_keys::strip_extraneous_signatures(&mut canonical, server_name, &[our_name]);
to_raw_value(&canonical)
.map(Raw::<ServerSigningKeys>::from_json)
.map_err(Into::into)
}
#[tracing::instrument(skip(server_keys, my_name, queries, start, semaphore))]
async fn acquire_keys_as_notary(
server_keys: Arc<server_keys::Service>,
my_name: OwnedServerName,
remote: OwnedServerName,
mut queries: BTreeMap<OwnedServerSigningKeyId, QueryCriteria>,
start: MilliSecondsSinceUnixEpoch,
semaphore: Option<Arc<tokio::sync::Semaphore>>,
) -> Vec<Raw<ServerSigningKeys>> {
let cost = queries
.len()
.saturating_add(1)
.min(automatic_width())
.try_into()
.unwrap_or(u32::MAX);
let _permit = if let Some(sem) = semaphore {
sem.acquire_many_owned(cost).await.ok()
} else {
None
};
let fetch_all = queries.is_empty();
let mut results = Vec::with_capacity(queries.len().max(1));
let mut keymap = HashMap::with_capacity(queries.len().max(1));
// First contact the origin (if we're allowed to)
if server_keys.notary_may_contact_origin(&remote) {
debug_info!("Asking remote directly for verify keys");
if let Ok(res) = server_keys.origin_request(remote.clone(), start).await
&& let Ok(ssk) = sign_ssk(&server_keys, &res.raw, &remote, &my_name).await
{
let index = results.len();
results.push(ssk);
for key_id in res
.parsed
.verify_keys
.keys()
.chain(res.parsed.old_verify_keys.keys())
{
if fetch_all
|| queries.get(key_id).is_some_and(|c| {
c.minimum_valid_until_ts
.is_none_or(|m| res.parsed.valid_until_ts >= m)
}) {
queries.remove(key_id);
keymap.insert(key_id.to_owned(), index);
}
}
}
} else {
debug!("Not asking remote for keys (already asked recently)");
}
debug!(keys=?keymap.keys(), "Live verify keys");
if fetch_all && keymap.is_empty() {
// If the server asked for all keys, AND we didn't get anything from the
// origin, just fetch any fresh responses we have.
server_keys
.signing_keys_for(&remote)
.broad_filter_map(|ssk| {
let server_name = &remote;
let my_name = &my_name;
let server_keys = &server_keys;
async move {
if ssk.parsed.valid_until_ts > in_one_week()
|| ssk.parsed.valid_until_ts < start
{
return None;
}
sign_ssk(server_keys, &ssk.raw, server_name, my_name)
.await
.map(|signed_ssk| (ssk, signed_ssk))
.ok()
}
})
.ready_for_each(|(ssk, signed_ssk)| {
let idx = results.len();
results.push(signed_ssk);
for key_id in ssk
.parsed
.verify_keys
.keys()
.chain(ssk.parsed.old_verify_keys.keys())
{
keymap.insert(key_id.to_owned(), idx);
}
})
.await;
}
// If we're still missing some keys, fetch them from the local cache
for (key_id, criteria) in queries {
debug!(%key_id, "Fetching verify key from local repository");
if keymap.contains_key(&key_id) {
debug!(%key_id, "Already found key");
continue;
}
let minimum_valid_until_ts = criteria.clone().minimum_valid_until_ts.unwrap_or(start);
let Some(ssk) = server_keys.get_signing_key(&remote, &key_id).await else {
debug!(%remote, %key_id, "Could not find a matching signing key locally.");
continue;
};
if ssk.parsed.valid_until_ts < minimum_valid_until_ts
|| ssk.parsed.valid_until_ts > in_one_week()
{
debug!(
%key_id,
valid_until_ts=?ssk.parsed.valid_until_ts,
?minimum_valid_until_ts,
"Stored verify key does not satisfy query criteria"
);
continue;
}
if let Some(old_verify_key) = ssk.parsed.old_verify_keys.get(&key_id) {
if old_verify_key.expired_ts < minimum_valid_until_ts {
debug!(
%key_id,
expired_ts=?old_verify_key.expired_ts,
?minimum_valid_until_ts,
"Stored old verify key does not satisfy query criteria"
);
// 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;
}
}
debug!(%key_id, ?ssk.parsed, "Found key locally");
let rep_key_ids = ssk.parsed.verify_keys.keys().cloned().collect::<Vec<_>>();
let Ok(signed_ssk) = sign_ssk(&server_keys, &ssk.raw, &remote, &my_name)
.await
.inspect_err(
|e| error!(%key_id, %remote, "Failed to sign signing keys chunk: {e:?}"),
)
else {
continue;
};
let idx = results.len();
results.push(signed_ssk);
keymap.insert(key_id, idx);
for key_id in rep_key_ids {
keymap.insert(key_id, idx);
}
}
keymap
.into_values()
.collect::<HashSet<_>>()
.into_iter()
.map(|idx| results.index(idx).to_owned())
.collect()
}
/// `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 min_valid_ts = body.minimum_valid_until_ts;
if services
.server_keys
.notary_may_contact_origin(&body.server_name)
&& let Ok(response) = services
.server_keys
.origin_request(body.server_name.clone(), min_valid_ts)
.await
{
return sign_ssk(
&services.server_keys,
&response.raw,
&body.server_name,
services.globals.server_name(),
)
.await
.map(|r| Ok(get_remote_server_keys::v2::Response::new(vec![r])))?;
}
let response = services
.server_keys
.signing_keys_for(&body.server_name)
.broad_filter_map(|ssk| {
let server_name = body.server_name.clone();
async move {
if ssk.parsed.valid_until_ts > in_one_week()
|| ssk.parsed.valid_until_ts < min_valid_ts
{
return None;
}
sign_ssk(
&services.server_keys,
&ssk.raw,
server_name.as_ref(),
services.globals.server_name(),
let trusted = services.config.trusted_servers.iter().any(|notary| {
server_keys::Service::verify_server_keys_response(
&resp,
Some((notary.server_name(), notary.verify_keys())),
)
.await
.ok()
.is_ok()
});
if !trusted {
continue;
}
})
.collect::<Vec<_>>()
.await;
Ok(get_remote_server_keys::v2::Response::new(response))
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
};
let server_key = assign!(ServerSigningKeys::new(server_name.to_owned(), valid_until_ts()), {
verify_keys,
old_verify_keys,
});
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))?;
services.server_keys.sign_json(&mut response)?;
Ok(Json(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")
}
-16
View File
@@ -118,22 +118,6 @@ 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
+11 -7
View File
@@ -1154,7 +1154,10 @@ pub struct Config {
/// (trusted key notary servers), as well as serve as trusted servers for
/// other operations like backfill and event fetching.
///
/// example: ["continuwuity.org", "matrix.org"]
/// Currently, continuwuity doesn't support inbound key requests, so
/// this list should only contain other Synapse servers.
///
/// example: ["matrix.org", "starstruck.systems"]
///
/// It is possible to restrict which signing keys trusted servers are
/// allowed to sign responses with. Without configuring this, all responses
@@ -1191,7 +1194,7 @@ pub struct Config {
/// empty list (`[]`) to operate without trusted server assistance, but this
/// is discouraged for performance and reliability reasons.
///
/// default: ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
/// default: ["matrix.org"]
#[serde(default = "default_trusted_servers")]
pub trusted_servers: Vec<TrustedServer>,
@@ -3259,11 +3262,12 @@ fn default_otlp_filter() -> String {
fn default_tracing_flame_output_path() -> String { "./tracing.folded".to_owned() }
fn default_trusted_servers() -> Vec<TrustedServer> {
let trusted_servers = vec![
ruma::owned_server_name!("continuwuity.org"),
ruma::owned_server_name!("continuwuity.rocks"),
ruma::owned_server_name!("matrix.org"),
];
// 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")];
trusted_servers
.into_iter()
.map(TrustedServer::Name)
+4
View File
@@ -407,6 +407,10 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "userdeviceid_token",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userdeviceid_previoustoken",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userdevicesessionid_uiaainfo",
..descriptor::RANDOM_SMALL
-1
View File
@@ -1 +0,0 @@
pub mod notary;
-56
View File
@@ -1,56 +0,0 @@
//! `POST /_matrix/key/*/query`
//!
//! Endpoint to query signing keys through other (notary) servers.
pub mod unstable {
use std::collections::BTreeMap;
use ruma::{
OwnedServerName, OwnedServerSigningKeyId,
api::{
federation::{
authentication::ServerSignatures,
discovery::{ServerSigningKeys, get_remote_server_keys_batch::v2::QueryCriteria},
},
request, response,
},
metadata,
serde::Raw,
};
metadata! {
method: POST,
rate_limited: true,
authentication: ServerSignatures,
path: "/_matrix/key/unstable/org.continuwuity.msc4556/query",
}
#[request]
pub struct Request {
pub server_keys:
BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
}
#[response]
pub struct Response {
pub server_keys: Vec<Raw<ServerSigningKeys>>,
}
impl Request {
#[must_use]
pub fn new(
server_keys: BTreeMap<
OwnedServerName,
BTreeMap<OwnedServerSigningKeyId, QueryCriteria>,
>,
) -> Self {
Self { server_keys }
}
}
impl Response {
/// Creates a new `Response` with the given keys.
#[must_use]
pub fn new(server_keys: Vec<Raw<ServerSigningKeys>>) -> Self { Self { server_keys } }
}
}
-2
View File
@@ -6,5 +6,3 @@ pub mod invite_permission_config;
pub mod meowlnir_antispam;
pub mod policy;
pub mod pushers;
pub mod federation;
+77 -10
View File
@@ -1,5 +1,6 @@
use std::{
collections::{BTreeSet, HashMap},
fmt::Write,
sync::Arc,
time::{Duration, SystemTime},
};
@@ -55,7 +56,7 @@ struct Services {
config: Dep<config::Service>,
}
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SessionInfo {
pub client_id: String,
#[serde(deserialize_with = "client_metadata::btreeset_skip_err")]
@@ -64,6 +65,8 @@ pub struct SessionInfo {
temporary_scopes: BTreeSet<OAuthClientScope>,
#[serde(default)]
current_refresh_token: String,
#[serde(default)]
previous_refresh_token: Option<String>,
}
impl SessionInfo {
@@ -71,6 +74,15 @@ impl SessionInfo {
pub fn scopes(&self) -> BTreeSet<OAuthClientScope> {
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)]
@@ -246,6 +258,24 @@ impl Service {
.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(
&self,
authorizing_user: OwnedUserId,
@@ -645,6 +675,7 @@ impl Service {
SessionInfo {
client_id: client_id.clone(),
current_refresh_token: Self::generate_token(),
previous_refresh_token: None,
scopes: requested_scopes.scopes,
temporary_scopes: BTreeSet::new(),
}
@@ -702,15 +733,53 @@ impl Service {
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
// on that?
let scope = session_info.scopes.iter().join(" ");
let new_refresh_token = Self::generate_token();
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_refresh_token = Self::generate_token();
session_info
.current_refresh_token
.clone_from(&new_refresh_token);
self.services
.users
@@ -729,8 +798,6 @@ impl Service {
Json(session_info),
);
self.db.refreshtoken_refreshtokeninfo.remove(&refresh_token);
drop(refresh_token);
self.db
.refreshtoken_refreshtokeninfo
.raw_put(&new_refresh_token, Json(refresh_token_info));
+2 -2
View File
@@ -158,7 +158,7 @@ impl super::Service {
if let Some(server_keys) = self.get_signing_key(origin, key_id).await
&& let Some(key) =
verify_key_from_response(key_id, &server_keys.parsed, min_valid_ts)
verify_key_from_response(key_id, &server_keys, min_valid_ts)
{
trace!(%origin, %key_id, ?min_valid_ts, "Verify key exists locally");
Self::track_one_result(
@@ -387,7 +387,7 @@ impl super::Service {
if let Some(vk) = self
.get_signing_key(origin, key_id)
.await
.and_then(|ssk| verify_key_from_response(key_id, &ssk.parsed, min_valid_ts))
.and_then(|ssk| verify_key_from_response(key_id, &ssk, min_valid_ts))
{
trace!("Found verify key locally");
return Some(vk);
+9 -114
View File
@@ -5,43 +5,32 @@ mod sign;
mod util;
mod verify;
use std::{
collections::{BTreeMap, HashMap},
sync::Arc,
time::{Duration, Instant},
};
use std::{collections::BTreeMap, sync::Arc};
use assign::assign;
use async_trait::async_trait;
use conduwuit::{
Result, Server, SyncRwLock,
utils::{IterStream, ReadyExt, stream::TryIgnore, timepoint_from_now, to_canonical_object},
Result, Server,
utils::{IterStream, ReadyExt, stream::TryIgnore},
};
use database::{Deserialized, Ignore, Interfix, Json, Map};
use futures::{Stream, StreamExt};
pub use request::in_one_week;
use ruma::{
CanonicalJsonObject, MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId,
ServerName, ServerSigningKeyId,
api::federation::discovery::{OldVerifyKey, ServerSigningKeys, VerifyKey},
CanonicalJsonObject, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName,
ServerSigningKeyId,
api::federation::discovery::{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 {
@@ -58,7 +47,6 @@ 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)?;
@@ -75,12 +63,9 @@ 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!()) }
}
@@ -148,9 +133,7 @@ impl Service {
key_id: &ServerSigningKeyId,
minimum_valid_ts: MilliSecondsSinceUnixEpoch,
) -> bool {
let Some(IncomingServerKeys { parsed: keys, .. }) =
self.get_signing_key(origin, key_id).await
else {
let Some(keys) = self.get_signing_key(origin, key_id).await else {
// We have no keys for this server
return false;
};
@@ -178,13 +161,12 @@ impl Service {
&self,
origin: &ServerName,
key_id: &ServerSigningKeyId,
) -> Option<IncomingServerKeys> {
) -> Option<ServerSigningKeys> {
self.db
.servernamekeyid_response
.qry(&(origin.as_str(), key_id.as_str()))
.await
.deserialized::<Raw<ServerSigningKeys>>()
.and_then(|r| r.try_into().map_err(Into::into))
.deserialized::<ServerSigningKeys>()
.ok()
}
@@ -206,8 +188,6 @@ 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,
@@ -219,89 +199,4 @@ 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 notary_may_contact_origin(&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
}
}
+1 -18
View File
@@ -1,4 +1,4 @@
use std::{collections::BTreeMap, time::Instant};
use std::collections::BTreeMap;
use conduwuit::{Err, Result, trace, utils::millis_since_unix_epoch, warn};
use ruma::{
@@ -31,23 +31,6 @@ 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
+14 -22
View File
@@ -107,7 +107,7 @@ impl super::Service {
pubkey_map.insert(incoming.parsed.server_name.to_string(), set);
let mut canonical = to_canonical_object(&incoming.raw)?;
strip_extraneous_signatures(&mut canonical, &incoming.parsed.server_name, &[]);
Self::strip_extraneous_signatures(&mut canonical, &incoming.parsed.server_name, &[]);
ruma::signatures::verify_json(&pubkey_map, &canonical).map_err(Into::into)
}
@@ -163,30 +163,22 @@ impl super::Service {
"No valid signature from {notary_name} present on signing keys response"
)))
}
}
/// 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)
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)
});
Some(s)
});
});
}
}
#[cfg(test)]
+6
View File
@@ -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))
}
+17 -1
View File
@@ -184,8 +184,13 @@ impl super::Service {
// Remove old token
if let Ok(old_token) = self.db.userdeviceid_token.qry(&key).await {
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
// 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
@@ -207,6 +212,17 @@ impl super::Service {
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.
pub async fn add_to_device_event(
&self,
+2
View File
@@ -83,6 +83,7 @@ struct Data {
userdeviceid_tokenexpires: Arc<Map>,
userdeviceid_metadata: Arc<Map>,
userdeviceid_token: Arc<Map>,
userdeviceid_previoustoken: Arc<Map>,
userfilterid_filter: Arc<Map>,
userid_avatarurl: Arc<Map>,
userid_deactivated: Arc<Map>,
@@ -134,6 +135,7 @@ impl crate::Service for Service {
remoteuserid_remoteuser: args.db["remoteuserid_remoteuser"].clone(),
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
userdeviceid_token: args.db["userdeviceid_token"].clone(),
userdeviceid_previoustoken: args.db["userdeviceid_previoustoken"].clone(),
userfilterid_filter: args.db["userfilterid_filter"].clone(),
userid_avatarurl: args.db["userid_avatarurl"].clone(),
userid_deactivated: args.db["userid_deactivated"].clone(),