mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-25 01:47:32 +00:00
Convert in-memory data structures in appservice, rooms::typing, and sync wakers to use SyncRwLock and SyncMutex. Drop appservice locks before making outbound network requests in room alias queries and federation invites.
414 lines
11 KiB
Rust
414 lines
11 KiB
Rust
use std::{
|
|
any::{Any, TypeId},
|
|
collections::BTreeSet,
|
|
};
|
|
|
|
use conduwuit::{
|
|
Err, Error, Result, err,
|
|
utils::{IterStream, millis_since_unix_epoch},
|
|
};
|
|
use http::StatusCode;
|
|
use ruma::{
|
|
DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedServerName, OwnedUserId, UInt,
|
|
UserId,
|
|
api::{
|
|
IncomingRequest, OAuthClientScope,
|
|
auth_scheme::{
|
|
AccessToken, AccessTokenOptional, AppserviceToken, AppserviceTokenOptional,
|
|
AuthScheme, NoAccessToken, NoAuthentication,
|
|
},
|
|
client,
|
|
error::{ErrorKind, InsufficientUserAuthenticationErrorData, UnknownTokenErrorData},
|
|
federation::authentication::ServerSignatures,
|
|
},
|
|
assign,
|
|
};
|
|
use service::{
|
|
Services,
|
|
server_keys::{PubKeyMap, PubKeys},
|
|
users::AccessTokenStatus,
|
|
};
|
|
|
|
use crate::{router::args::AuthQueryParams, service::appservice::RegistrationInfo};
|
|
|
|
pub(crate) enum ClientIdentity {
|
|
User {
|
|
sender_user: OwnedUserId,
|
|
sender_device: OwnedDeviceId,
|
|
},
|
|
Appservice {
|
|
sender_user: OwnedUserId,
|
|
sender_device: Option<OwnedDeviceId>,
|
|
appservice_info: Box<RegistrationInfo>,
|
|
},
|
|
}
|
|
|
|
impl ClientIdentity {
|
|
pub(crate) fn sender_user(&self) -> Option<&UserId> {
|
|
match self {
|
|
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
|
|
Some(sender_user),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn expect_sender_user(&self) -> Result<&UserId> {
|
|
match self {
|
|
| Self::User { sender_user, .. } | Self::Appservice { sender_user, .. } =>
|
|
Ok(sender_user),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn sender_device(&self) -> Option<&DeviceId> {
|
|
match self {
|
|
| Self::User { sender_device, .. } => Some(sender_device),
|
|
| Self::Appservice { sender_device, .. } => sender_device.as_deref(),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn expect_sender_device(&self) -> Result<&DeviceId> {
|
|
match self {
|
|
| Self::User { sender_device, .. }
|
|
| Self::Appservice { sender_device: Some(sender_device), .. } => Ok(sender_device),
|
|
| Self::Appservice { sender_device: None, .. } =>
|
|
Err!(Request(Forbidden("Appservices must masquerade to use this endpoint."))),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn appservice_info(&self) -> Option<&RegistrationInfo> {
|
|
match self {
|
|
| Self::User { .. } => None,
|
|
| Self::Appservice { appservice_info, .. } => Some(appservice_info),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn is_appservice(&self) -> bool { matches!(self, Self::Appservice { .. }) }
|
|
}
|
|
|
|
pub(crate) trait CheckAuth: AuthScheme {
|
|
type Identity: Send;
|
|
|
|
fn check<R: IncomingRequest<Authentication = Self> + Any>(
|
|
services: &Services,
|
|
incoming_request: &hyper::Request<&[u8]>,
|
|
authentication: Self::Output,
|
|
query: AuthQueryParams,
|
|
) -> impl Future<Output = Result<Self::Identity>> + Send;
|
|
}
|
|
|
|
impl CheckAuth for ServerSignatures {
|
|
type Identity = OwnedServerName;
|
|
|
|
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
|
|
services: &Services,
|
|
incoming_request: &hyper::Request<&[u8]>,
|
|
authentication: Self::Output,
|
|
_query: AuthQueryParams,
|
|
) -> Result<Self::Identity> {
|
|
let min_valid_ts =
|
|
MilliSecondsSinceUnixEpoch(UInt::new_saturating(millis_since_unix_epoch()));
|
|
|
|
let key = services
|
|
.server_keys
|
|
.get_single_verify_key(&authentication.origin, &authentication.key, min_valid_ts)
|
|
.await
|
|
.ok_or_else(|| {
|
|
err!(Request(Unauthorized(debug_warn!(
|
|
origin=%authentication.origin,
|
|
"Unable to acquire your signing key (ID: {})",
|
|
authentication.key
|
|
))))
|
|
})?;
|
|
|
|
let keys: PubKeys = [(authentication.key.to_string(), key.key)].into();
|
|
let keys: PubKeyMap = [(authentication.origin.as_str().into(), keys)].into();
|
|
|
|
match authentication.verify_http_request(
|
|
incoming_request,
|
|
services.globals.server_name(),
|
|
&keys,
|
|
) {
|
|
| Ok(()) => {
|
|
if services
|
|
.moderation
|
|
.is_remote_server_forbidden(&authentication.origin)
|
|
{
|
|
return Err!(Request(Forbidden(
|
|
"You are blocked from federating with this server."
|
|
)));
|
|
}
|
|
|
|
// Ping the server as healthy
|
|
if services.federation.mark_healthy(&authentication.origin) {
|
|
services
|
|
.sending
|
|
.flush_servers([authentication.origin.clone()].stream())
|
|
.await
|
|
.ok();
|
|
}
|
|
|
|
Ok(authentication.origin)
|
|
},
|
|
| Err(err) => Err!(Request(Unauthorized(debug_warn!(
|
|
"Failed to verify X-Matrix header: {err}"
|
|
)))),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl CheckAuth for AccessToken {
|
|
type Identity = ClientIdentity;
|
|
|
|
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
|
|
services: &Services,
|
|
_incoming_request: &hyper::Request<&[u8]>,
|
|
authentication: Self::Output,
|
|
query: AuthQueryParams,
|
|
) -> Result<Self::Identity> {
|
|
check_access_token(
|
|
services,
|
|
&authentication,
|
|
query,
|
|
TypeId::of::<R>(),
|
|
R::required_client_scopes(),
|
|
)
|
|
.await
|
|
}
|
|
}
|
|
|
|
impl CheckAuth for AccessTokenOptional {
|
|
type Identity = Option<ClientIdentity>;
|
|
|
|
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
|
|
services: &Services,
|
|
_incoming_request: &hyper::Request<&[u8]>,
|
|
authentication: Self::Output,
|
|
query: AuthQueryParams,
|
|
) -> Result<Self::Identity> {
|
|
if let Some(authentication) = authentication {
|
|
check_access_token(
|
|
services,
|
|
&authentication,
|
|
query,
|
|
TypeId::of::<R>(),
|
|
R::required_client_scopes(),
|
|
)
|
|
.await
|
|
.map(Some)
|
|
} else {
|
|
Ok(None)
|
|
}
|
|
}
|
|
}
|
|
|
|
impl CheckAuth for AppserviceToken {
|
|
type Identity = RegistrationInfo;
|
|
|
|
async fn check<R: IncomingRequest + Any>(
|
|
services: &Services,
|
|
_incoming_request: &hyper::Request<&[u8]>,
|
|
authentication: Self::Output,
|
|
_query: AuthQueryParams,
|
|
) -> Result<Self::Identity> {
|
|
check_appservice_token(services, &authentication).await
|
|
}
|
|
}
|
|
|
|
impl CheckAuth for AppserviceTokenOptional {
|
|
type Identity = Option<RegistrationInfo>;
|
|
|
|
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
|
|
services: &Services,
|
|
_incoming_request: &hyper::Request<&[u8]>,
|
|
authentication: Self::Output,
|
|
_query: AuthQueryParams,
|
|
) -> Result<Self::Identity> {
|
|
if let Some(authentication) = authentication {
|
|
check_appservice_token(services, &authentication)
|
|
.await
|
|
.map(Some)
|
|
} else {
|
|
Ok(None)
|
|
}
|
|
}
|
|
}
|
|
|
|
impl CheckAuth for NoAuthentication {
|
|
type Identity = ();
|
|
|
|
fn check<R: IncomingRequest<Authentication = Self> + Any>(
|
|
_services: &Services,
|
|
_incoming_request: &hyper::Request<&[u8]>,
|
|
_authentication: Self::Output,
|
|
_query: AuthQueryParams,
|
|
) -> impl Future<Output = Result<Self::Identity>> + Send {
|
|
std::future::ready(Ok(()))
|
|
}
|
|
}
|
|
|
|
impl CheckAuth for NoAccessToken {
|
|
type Identity = Option<ClientIdentity>;
|
|
|
|
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
|
|
services: &Services,
|
|
incoming_request: &hyper::Request<&[u8]>,
|
|
_authentication: Self::Output,
|
|
query: AuthQueryParams,
|
|
) -> Result<Self::Identity> {
|
|
// We handle these the same as AccessTokenOptional
|
|
let authentication = AccessTokenOptional::extract_authentication(incoming_request)
|
|
.map_err(|err| {
|
|
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
|
|
})?;
|
|
|
|
if let Some(authentication) = authentication {
|
|
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
|
|
OAuthClientScope::ApiFullAccess,
|
|
])
|
|
.await
|
|
.map(Some)
|
|
} else {
|
|
Ok(None)
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn check_access_token(
|
|
services: &Services,
|
|
token: &str,
|
|
query: AuthQueryParams,
|
|
route: TypeId,
|
|
required_scopes: &[OAuthClientScope],
|
|
) -> Result<ClientIdentity> {
|
|
if token.is_empty() {
|
|
return Err!(Request(Unauthorized("Empty access token.")));
|
|
}
|
|
|
|
if let Some((sender_user, sender_device, status)) =
|
|
services.users.find_from_token(token).await
|
|
{
|
|
// If the token is expired we return a soft logout
|
|
if matches!(status, AccessTokenStatus::Expired) {
|
|
return Err(Error::Request(
|
|
ErrorKind::UnknownToken(
|
|
assign!(UnknownTokenErrorData::new(), { soft_logout: true }),
|
|
),
|
|
"This token has expired".into(),
|
|
StatusCode::UNAUTHORIZED,
|
|
));
|
|
}
|
|
|
|
// Locked users can only use /logout and /logout/all
|
|
if services
|
|
.users
|
|
.is_locked(&sender_user)
|
|
.await
|
|
.is_ok_and(std::convert::identity)
|
|
{
|
|
if !(route == TypeId::of::<client::session::logout::v3::Request>()
|
|
|| route == TypeId::of::<client::session::logout_all::v3::Request>())
|
|
{
|
|
return Err!(Request(UserLocked("Your account is locked.")));
|
|
}
|
|
}
|
|
|
|
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 user_scopes = if let Some(session_info) = &session_info {
|
|
session_info.scopes()
|
|
} else {
|
|
let mut scopes = BTreeSet::from_iter([OAuthClientScope::ApiFullAccess]);
|
|
|
|
if services.admin.user_is_admin(&sender_user).await {
|
|
scopes.insert(OAuthClientScope::ServerAdministration);
|
|
}
|
|
|
|
scopes
|
|
};
|
|
|
|
if !required_scopes
|
|
.iter()
|
|
.any(|scope| user_scopes.contains(scope))
|
|
{
|
|
return Err(Error::Request(
|
|
ErrorKind::InsufficientUserAuthentication(Box::new(
|
|
assign!(InsufficientUserAuthenticationErrorData::new(), {
|
|
scope: required_scopes.iter().cloned().collect()
|
|
}),
|
|
)),
|
|
"You do not have permission to access this endpoint.".into(),
|
|
StatusCode::UNAUTHORIZED,
|
|
));
|
|
}
|
|
|
|
Ok(ClientIdentity::User { sender_user, sender_device })
|
|
} else if let Ok(appservice_info) = services.appservice.find_from_token(token) {
|
|
let Ok(sender_user) = query.user_id.clone().map_or_else(
|
|
|| {
|
|
UserId::parse_with_server_name(
|
|
appservice_info.registration.sender_localpart.as_str(),
|
|
services.globals.server_name(),
|
|
)
|
|
},
|
|
UserId::parse,
|
|
) else {
|
|
return Err!(Request(InvalidUsername("Username is invalid.")));
|
|
};
|
|
|
|
if !appservice_info.is_user_match(&sender_user) {
|
|
return Err!(Request(Exclusive("User is not in namespace.")));
|
|
}
|
|
|
|
// MSC3202/MSC4190: Handle device_id masquerading for appservices.
|
|
// The device_id can be provided via `device_id` or
|
|
// `org.matrix.msc3202.device_id` query parameter.
|
|
let sender_device = if let Some(device_id) = query
|
|
.device_id
|
|
.or(query.legacy_device_id)
|
|
.as_deref()
|
|
.map(Into::into)
|
|
{
|
|
// Verify the device exists for this user
|
|
if services
|
|
.users
|
|
.get_device_metadata(&sender_user, device_id)
|
|
.await
|
|
.is_err()
|
|
{
|
|
return Err!(Request(Forbidden(
|
|
"Device does not exist for user or appservice cannot masquerade as this \
|
|
device."
|
|
)));
|
|
}
|
|
|
|
Some(device_id.to_owned())
|
|
} else {
|
|
None
|
|
};
|
|
|
|
Ok(ClientIdentity::Appservice {
|
|
sender_user,
|
|
sender_device,
|
|
appservice_info: Box::new(appservice_info),
|
|
})
|
|
} else {
|
|
Err(Error::Request(
|
|
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
|
|
"Invalid token".into(),
|
|
StatusCode::UNAUTHORIZED,
|
|
))
|
|
}
|
|
}
|
|
|
|
async fn check_appservice_token(services: &Services, token: &str) -> Result<RegistrationInfo> {
|
|
let Ok(appservice_info) = services.appservice.find_from_token(token) else {
|
|
return Err!(Request(Unauthorized("Invalid appservice token.")));
|
|
};
|
|
|
|
Ok(appservice_info)
|
|
}
|