Files
continuwuity/src/api/router/auth.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

450 lines
12 KiB
Rust
Raw Normal View History

2026-08-26 14:12:40 -04:00
use std::{
any::{Any, TypeId},
collections::BTreeSet,
2026-11-02 15:22:47 -05:00
net::IpAddr,
2026-08-26 14:12:40 -04:00
};
2026-04-13 16:20:47 -04:00
2026-09-28 02:00:37 +01:00
use conduwuit::{
2026-11-15 13:16:21 +00:00
Err, Error, Result,
config::experiments::ToggledExperiment,
err,
2026-09-28 02:00:37 +01:00
utils::{IterStream, millis_since_unix_epoch},
};
use http::StatusCode;
2024-05-23 18:44:19 +00:00
use ruma::{
2026-09-28 02:00:37 +01:00
DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedServerName, OwnedUserId, UInt,
UserId,
api::{
2026-08-26 14:12:40 -04:00
IncomingRequest, OAuthClientScope,
2026-04-13 16:20:47 -04:00
auth_scheme::{
AccessToken, AccessTokenOptional, AppserviceToken, AppserviceTokenOptional,
AuthScheme, NoAccessToken, NoAuthentication,
},
client,
2026-11-02 15:22:47 -05:00
error::{
ErrorKind, InsufficientUserAuthenticationErrorData, LimitExceededErrorData,
UnknownTokenErrorData,
},
2026-04-13 16:20:47 -04:00
federation::authentication::ServerSignatures,
},
assign,
};
use service::{
Services,
server_keys::{PubKeyMap, PubKeys},
users::AccessTokenStatus,
2024-05-23 18:44:19 +00:00
};
2026-04-13 16:20:47 -04:00
use crate::{router::args::AuthQueryParams, service::appservice::RegistrationInfo};
2024-05-23 18:44:19 +00:00
pub(crate) enum ClientIdentity {
User {
sender_user: OwnedUserId,
sender_device: OwnedDeviceId,
},
Appservice {
sender_user: OwnedUserId,
sender_device: Option<OwnedDeviceId>,
2026-05-26 13:49:17 -04:00
appservice_info: Box<RegistrationInfo>,
},
2024-05-23 18:44:19 +00:00
}
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;
2026-08-26 14:12:40 -04:00
fn check<R: IncomingRequest<Authentication = Self> + Any>(
2026-04-13 16:20:47 -04:00
services: &Services,
2026-08-26 13:15:32 -04:00
incoming_request: &hyper::Request<&[u8]>,
2026-11-02 15:22:47 -05:00
request_ip: IpAddr,
2026-08-26 13:15:32 -04:00
authentication: Self::Output,
2026-04-13 16:20:47 -04:00
query: AuthQueryParams,
) -> impl Future<Output = Result<Self::Identity>> + Send;
2026-04-13 16:20:47 -04:00
}
impl CheckAuth for ServerSignatures {
type Identity = OwnedServerName;
2026-08-26 14:12:40 -04:00
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
2026-04-13 16:20:47 -04:00
services: &Services,
2026-08-26 13:15:32 -04:00
incoming_request: &hyper::Request<&[u8]>,
2026-11-02 15:22:47 -05:00
_request_ip: IpAddr,
2026-08-26 13:15:32 -04:00
authentication: Self::Output,
2026-04-13 16:20:47 -04:00
_query: AuthQueryParams,
) -> Result<Self::Identity> {
2026-09-28 02:00:37 +01:00
let min_valid_ts =
MilliSecondsSinceUnixEpoch(UInt::new_saturating(millis_since_unix_epoch()));
2026-08-26 13:15:32 -04:00
2026-04-13 16:20:47 -04:00
let key = services
.server_keys
2026-08-26 13:15:32 -04:00
.get_single_verify_key(&authentication.origin, &authentication.key, min_valid_ts)
2026-04-13 16:20:47 -04:00
.await
2026-09-28 02:00:37 +01:00
.ok_or_else(|| {
err!(Request(Unauthorized(debug_warn!(
2026-08-26 13:15:32 -04:00
origin=%authentication.origin,
2026-09-28 02:00:37 +01:00
"Unable to acquire your signing key (ID: {})",
2026-08-26 13:15:32 -04:00
authentication.key
2026-09-28 02:00:37 +01:00
))))
})?;
2026-04-13 16:20:47 -04:00
2026-08-26 13:15:32 -04:00
let keys: PubKeys = [(authentication.key.to_string(), key.key)].into();
let keys: PubKeyMap = [(authentication.origin.as_str().into(), keys)].into();
2026-04-13 16:20:47 -04:00
2026-08-26 13:15:32 -04:00
match authentication.verify_http_request(
incoming_request,
services.globals.server_name(),
&keys,
) {
| Ok(()) => {
if services
.moderation
2026-08-26 13:15:32 -04:00
.is_remote_server_forbidden(&authentication.origin)
{
2026-05-20 12:57:46 -04:00
return Err!(Request(Forbidden(
"You are blocked from federating with this server."
)));
}
// Ping the server as healthy
2026-08-26 13:15:32 -04:00
if services.federation.mark_healthy(&authentication.origin) {
2026-08-19 14:34:15 +01:00
services
.sending
2026-08-26 13:15:32 -04:00
.flush_servers([authentication.origin.clone()].stream())
2026-08-19 14:34:15 +01:00
.await
.ok();
}
2026-08-26 13:15:32 -04:00
Ok(authentication.origin)
},
2026-09-28 02:00:37 +01:00
| Err(err) => Err!(Request(Unauthorized(debug_warn!(
"Failed to verify X-Matrix header: {err}"
)))),
2026-04-13 16:20:47 -04:00
}
2024-05-23 18:44:19 +00:00
}
}
2026-04-13 16:20:47 -04:00
impl CheckAuth for AccessToken {
type Identity = ClientIdentity;
2026-08-26 14:12:40 -04:00
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
2026-04-13 16:20:47 -04:00
services: &Services,
2026-08-26 13:15:32 -04:00
_incoming_request: &hyper::Request<&[u8]>,
2026-11-02 15:22:47 -05:00
_request_ip: IpAddr,
2026-08-26 13:15:32 -04:00
authentication: Self::Output,
2026-04-29 09:09:09 -04:00
query: AuthQueryParams,
) -> Result<Self::Identity> {
2026-08-26 14:12:40 -04:00
check_access_token(
services,
&authentication,
query,
TypeId::of::<R>(),
R::required_client_scopes(),
)
.await
2026-04-13 16:20:47 -04:00
}
2024-05-23 18:44:19 +00:00
}
2026-04-13 16:20:47 -04:00
impl CheckAuth for AccessTokenOptional {
type Identity = Option<ClientIdentity>;
2026-08-26 14:12:40 -04:00
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
2026-04-13 16:20:47 -04:00
services: &Services,
2026-08-26 13:15:32 -04:00
_incoming_request: &hyper::Request<&[u8]>,
2026-11-02 15:22:47 -05:00
request_ip: IpAddr,
2026-08-26 13:15:32 -04:00
authentication: Self::Output,
2026-04-13 16:20:47 -04:00
query: AuthQueryParams,
) -> Result<Self::Identity> {
2026-08-26 13:15:32 -04:00
if let Some(authentication) = authentication {
2026-08-26 14:12:40 -04:00
check_access_token(
services,
&authentication,
query,
TypeId::of::<R>(),
R::required_client_scopes(),
)
.await
.map(Some)
2026-08-26 13:15:32 -04:00
} else {
2026-11-02 15:22:47 -05:00
if R::RATE_LIMITED {
check_unauthenticated_request_ratelimiting(services, request_ip)?;
}
2026-08-26 13:15:32 -04:00
Ok(None)
2026-04-13 16:20:47 -04:00
}
}
}
2026-04-13 16:20:47 -04:00
impl CheckAuth for AppserviceToken {
type Identity = RegistrationInfo;
2026-08-26 13:15:32 -04:00
async fn check<R: IncomingRequest + Any>(
2026-04-13 16:20:47 -04:00
services: &Services,
2026-08-26 13:15:32 -04:00
_incoming_request: &hyper::Request<&[u8]>,
2026-11-02 15:22:47 -05:00
_request_ip: IpAddr,
2026-08-26 13:15:32 -04:00
authentication: Self::Output,
2026-04-29 09:09:09 -04:00
_query: AuthQueryParams,
) -> Result<Self::Identity> {
2026-08-26 13:15:32 -04:00
check_appservice_token(services, &authentication).await
2026-04-13 16:20:47 -04:00
}
}
2026-04-13 16:20:47 -04:00
impl CheckAuth for AppserviceTokenOptional {
type Identity = Option<RegistrationInfo>;
2026-08-26 14:12:40 -04:00
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
2026-04-13 16:20:47 -04:00
services: &Services,
2026-08-26 13:15:32 -04:00
_incoming_request: &hyper::Request<&[u8]>,
2026-11-02 15:22:47 -05:00
_request_ip: IpAddr,
2026-08-26 13:15:32 -04:00
authentication: Self::Output,
_query: AuthQueryParams,
) -> Result<Self::Identity> {
2026-08-26 13:15:32 -04:00
if let Some(authentication) = authentication {
check_appservice_token(services, &authentication)
.await
.map(Some)
} else {
Ok(None)
2026-04-13 16:20:47 -04:00
}
2024-05-23 18:44:19 +00:00
}
}
2026-04-13 16:20:47 -04:00
impl CheckAuth for NoAuthentication {
type Identity = ();
2026-08-26 14:12:40 -04:00
fn check<R: IncomingRequest<Authentication = Self> + Any>(
2026-04-13 16:20:47 -04:00
_services: &Services,
2026-08-26 13:15:32 -04:00
_incoming_request: &hyper::Request<&[u8]>,
2026-11-02 15:22:47 -05:00
_request_ip: IpAddr,
2026-08-26 13:15:32 -04:00
_authentication: Self::Output,
2026-04-13 16:20:47 -04:00
_query: AuthQueryParams,
2026-08-26 13:15:32 -04:00
) -> impl Future<Output = Result<Self::Identity>> + Send {
2026-08-25 12:37:13 -04:00
std::future::ready(Ok(()))
2026-04-13 16:20:47 -04:00
}
}
2026-04-13 16:20:47 -04:00
impl CheckAuth for NoAccessToken {
type Identity = Option<ClientIdentity>;
2026-08-26 14:12:40 -04:00
async fn check<R: IncomingRequest<Authentication = Self> + Any>(
2026-04-13 16:20:47 -04:00
services: &Services,
2026-08-26 13:15:32 -04:00
incoming_request: &hyper::Request<&[u8]>,
2026-11-02 15:22:47 -05:00
request_ip: IpAddr,
2026-08-26 13:15:32 -04:00
_authentication: Self::Output,
2026-04-13 16:20:47 -04:00
query: AuthQueryParams,
) -> Result<Self::Identity> {
2026-04-13 16:20:47 -04:00
// We handle these the same as AccessTokenOptional
2026-08-26 13:15:32 -04:00
let authentication = AccessTokenOptional::extract_authentication(incoming_request)
.map_err(|err| {
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
})?;
2026-08-26 13:15:32 -04:00
if let Some(authentication) = authentication {
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
OAuthClientScope::ApiFullAccess,
])
.await
.map(Some)
2026-08-26 13:15:32 -04:00
} else {
2026-11-02 15:22:47 -05:00
if R::RATE_LIMITED {
check_unauthenticated_request_ratelimiting(services, request_ip)?;
}
2026-08-26 13:15:32 -04:00
Ok(None)
}
}
}
2026-08-26 13:15:32 -04:00
async fn check_access_token(
services: &Services,
token: &str,
query: AuthQueryParams,
route: TypeId,
2026-08-26 14:12:40 -04:00
required_scopes: &[OAuthClientScope],
2026-08-26 13:15:32 -04:00
) -> 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.")));
}
}
2026-09-10 13:11:07 -04:00
let session_info = services
2026-08-26 14:12:40 -04:00
.oauth
.get_session_info_for_device(&sender_user, &sender_device)
.await
2026-09-10 13:11:07 -04:00
.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 {
2026-09-08 18:45:04 -04:00
session_info.scopes()
2026-08-26 14:12:40 -04:00
} else {
BTreeSet::from_iter([OAuthClientScope::ApiFullAccess])
2026-08-26 14:12:40 -04:00
};
if (!services.config.experiments.msc4484.is_enabled() || session_info.is_none())
&& services.admin.user_is_admin(&sender_user).await
{
// This is required to make sure admin APIs still work when msc4484
// is disabled.
// https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2533#issuecomment-40042
user_scopes.insert(OAuthClientScope::ServerAdministration);
}
2026-08-26 14:12:40 -04:00
if !required_scopes
.iter()
.any(|scope| user_scopes.contains(scope))
{
2026-09-08 18:45:04 -04:00
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,
));
2026-08-26 14:12:40 -04:00
}
2026-08-26 13:15:32 -04:00
Ok(ClientIdentity::User { sender_user, sender_device })
} else if let Ok(appservice_info) = services.appservice.find_from_token(token) {
2026-08-26 13:15:32 -04:00
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(UnknownDevice("Device does not exist for this user.")));
2026-08-26 13:15:32 -04:00
}
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 {
2026-08-26 13:15:32 -04:00
return Err!(Request(Unauthorized("Invalid appservice token.")));
};
Ok(appservice_info)
}
2026-11-02 15:22:47 -05:00
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
if services
.config
.unauthenticated_request_ratelimit
.check_key(&ip)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::LimitExceeded(LimitExceededErrorData::new()),
"Rate limit exceeded.",
));
}
Ok(())
}