use std::{ any::{Any, TypeId}, collections::BTreeSet, net::IpAddr, }; use conduwuit::{ Err, Error, Result, config::experiments::ToggledExperiment, 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, LimitExceededErrorData, 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, appservice_info: Box, }, } 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 + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> impl Future> + Send; } impl CheckAuth for ServerSignatures { type Identity = OwnedServerName; async fn check + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { 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 + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, _request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> Result { check_access_token( services, &authentication, query, TypeId::of::(), R::required_client_scopes(), ) .await } } impl CheckAuth for AccessTokenOptional { type Identity = Option; async fn check + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> Result { if let Some(authentication) = authentication { check_access_token( services, &authentication, query, TypeId::of::(), R::required_client_scopes(), ) .await .map(Some) } else { if R::RATE_LIMITED { check_unauthenticated_request_ratelimiting(services, request_ip)?; } Ok(None) } } } impl CheckAuth for AppserviceToken { type Identity = RegistrationInfo; async fn check( services: &Services, _incoming_request: &hyper::Request<&[u8]>, _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { check_appservice_token(services, &authentication).await } } impl CheckAuth for AppserviceTokenOptional { type Identity = Option; async fn check + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { if let Some(authentication) = authentication { check_appservice_token(services, &authentication) .await .map(Some) } else { Ok(None) } } } impl CheckAuth for NoAuthentication { type Identity = (); fn check + Any>( _services: &Services, _incoming_request: &hyper::Request<&[u8]>, _request_ip: IpAddr, _authentication: Self::Output, _query: AuthQueryParams, ) -> impl Future> + Send { std::future::ready(Ok(())) } } impl CheckAuth for NoAccessToken { type Identity = Option; async fn check + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, request_ip: IpAddr, _authentication: Self::Output, query: AuthQueryParams, ) -> Result { // 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::(), &[ OAuthClientScope::ApiFullAccess, ]) .await .map(Some) } else { if R::RATE_LIMITED { check_unauthenticated_request_ratelimiting(services, request_ip)?; } Ok(None) } } } async fn check_access_token( services: &Services, token: &str, query: AuthQueryParams, route: TypeId, required_scopes: &[OAuthClientScope], ) -> Result { 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::() || route == TypeId::of::()) { 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 mut user_scopes = if let Some(session_info) = &session_info { session_info.scopes() } else { BTreeSet::from_iter([OAuthClientScope::ApiFullAccess]) }; 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); } 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(UnknownDevice("Device does not exist for this user."))); } 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 { let Ok(appservice_info) = services.appservice.find_from_token(token) else { return Err!(Request(Unauthorized("Invalid appservice token."))); }; Ok(appservice_info) } 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(()) }