Files
continuwuity/src/api/client/session.rs
T

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

364 lines
11 KiB
Rust
Raw Normal View History

2025-01-11 18:49:21 +00:00
use std::time::Duration;
2024-07-16 08:05:25 +00:00
use axum::extract::State;
2026-04-23 20:02:48 +01:00
use axum_client_ip::ClientIp;
use conduwuit::{
Err, Result, debug, err, info,
utils::{self, ReadyExt, stream::BroadbandExt},
warn,
};
use conduwuit_service::Services;
use futures::StreamExt;
use lettre::Address;
2020-07-30 18:14:47 +02:00
use ruma::{
2025-08-09 15:06:48 +02:00
OwnedUserId, UserId,
2020-07-30 18:14:47 +02:00
api::client::{
session::{
2025-01-11 18:49:21 +00:00
get_login_token,
2024-03-02 20:55:02 -05:00
get_login_types::{
self,
2025-01-11 18:49:21 +00:00
v3::{ApplicationServiceLoginType, PasswordLoginType, TokenLoginType},
2024-03-02 20:55:02 -05:00
},
login::{
self,
v3::{DiscoveryInfo, HomeserverInfo},
},
logout, logout_all,
},
uiaa::{EmailUserIdentifier, MatrixUserIdentifier, UserIdentifier},
2020-07-30 18:14:47 +02:00
},
assign,
2020-07-30 18:14:47 +02:00
};
2021-02-07 17:38:45 +01:00
2021-07-14 07:07:08 +00:00
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::Ruma;
2024-03-05 19:48:54 -05:00
/// # `GET /_matrix/client/v3/login`
2020-07-31 14:40:28 +02:00
///
2021-08-31 19:14:37 +02:00
/// Get the supported login types of this server. One of these should be used as
2020-07-31 14:40:28 +02:00
/// the `type` field when logging in.
2026-01-04 03:04:37 +00:00
#[tracing::instrument(skip_all, fields(%client), name = "login", level = "info")]
2024-04-22 23:48:57 -04:00
pub(crate) async fn get_login_types_route(
2025-01-11 18:49:21 +00:00
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
_body: Ruma<get_login_types::v3::Request>,
2024-04-22 23:48:57 -04:00
) -> Result<get_login_types::v3::Response> {
if !services.config.oauth.compatibility_mode.uiaa_available() {
return Err!(Request(Unrecognized(
"User-interactive authentication is not available on this server."
)));
}
2022-02-18 15:33:14 +01:00
Ok(get_login_types::v3::Response::new(vec![
2024-03-02 20:55:02 -05:00
get_login_types::v3::LoginType::Password(PasswordLoginType::default()),
get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()),
get_login_types::v3::LoginType::Token(assign!(TokenLoginType::new(), {
2025-01-11 18:49:21 +00:00
get_login_token: services.server.config.login_via_existing_session,
})),
2022-01-22 16:58:32 +01:00
]))
2020-07-30 18:14:47 +02:00
}
pub async fn handle_login(
2025-08-09 15:06:48 +02:00
services: &Services,
identifier: Option<&UserIdentifier>,
2025-08-09 15:06:48 +02:00
password: &str,
2025-08-10 12:50:19 +02:00
user: Option<&String>,
2025-08-09 15:06:48 +02:00
) -> Result<OwnedUserId> {
debug!("Got password login type");
let user_id_or_localpart = match (identifier, user) {
2026-04-13 18:31:16 -04:00
| (Some(UserIdentifier::Matrix(MatrixUserIdentifier { user, .. })), _)
| (None, Some(user)) => user,
| (Some(UserIdentifier::Email(EmailUserIdentifier { address, .. })), _) => {
let email = Address::try_from(address.to_owned())
.map_err(|_| err!(Request(InvalidParam("Email is malformed"))))?;
&services
.threepid
.get_localpart_for_email(&email)
.await
.ok_or_else(|| err!(Request(Forbidden("Invalid identifier or password"))))?
},
| _ => {
return Err!(Request(InvalidParam("Identifier type not recognized")));
},
};
2025-08-09 15:06:48 +02:00
let user_id =
UserId::parse_with_server_name(user_id_or_localpart, &services.config.server_name)
.map_err(|_| err!(Request(InvalidUsername("User ID is malformed"))))?;
2025-08-09 15:06:48 +02:00
if !services.globals.user_is_local(&user_id) {
return Err!(Request(InvalidParam("User ID does not belong to this homeserver")));
2025-08-09 15:06:48 +02:00
}
2026-01-06 21:54:29 +00:00
if services.users.is_locked(&user_id).await? {
return Err!(Request(UserLocked("This account has been locked.")));
}
if services.users.is_login_disabled(&user_id).await {
warn!(%user_id, "user attempted to log in with a login-disabled account");
return Err!(Request(Forbidden("This account is not permitted to log in.")));
}
services.users.check_password(&user_id, password).await
2025-08-09 15:06:48 +02:00
}
/// # `POST /_matrix/client/v3/login`
2020-07-31 14:40:28 +02:00
///
/// Authenticates the user and returns an access token it can use in subsequent
/// requests.
///
2021-08-31 19:14:37 +02:00
/// - The user needs to authenticate using their password (or if enabled using a
/// json web token)
/// - If `device_id` is known: invalidates old access token of that device
/// - If `device_id` is unknown: creates a new device
/// - Returns access token that is associated with the user and device
2020-07-31 14:40:28 +02:00
///
/// Note: You can use [`GET
/// /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see
/// supported login types.
2026-01-04 03:04:37 +00:00
#[tracing::instrument(skip_all, fields(%client), name = "login", level = "info")]
2024-07-16 08:05:25 +00:00
pub(crate) async fn login_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
body: Ruma<login::v3::Request>,
2024-07-16 08:05:25 +00:00
) -> Result<login::v3::Response> {
if !services.config.oauth.compatibility_mode.uiaa_available() {
return Err!(Request(Unrecognized(
"User-interactive authentication is not available on this server."
)));
}
let emergency_mode_enabled = services.config.emergency_password.is_some();
2020-07-30 18:14:47 +02:00
// Validate login method
2021-02-07 17:38:45 +01:00
let user_id = match &body.login_info {
#[allow(deprecated)]
| login::v3::LoginInfo::Password(login::v3::Password {
2021-03-18 19:38:08 +01:00
identifier,
password,
user,
..
}) => handle_login(&services, identifier.as_ref(), password, user.as_ref()).await?,
| login::v3::LoginInfo::Token(login::v3::Token { token, .. }) => {
debug!("Got token login type");
2025-01-11 18:49:21 +00:00
if !services.server.config.login_via_existing_session {
return Err!(Request(Unknown("Token login is not enabled.")));
}
services.users.find_from_login_token(token).await?
2021-02-07 17:38:45 +01:00
},
#[allow(deprecated)]
| login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService {
identifier,
user,
..
}) => {
debug!("Got appservice login type");
let Some(ref info) = body.identity else {
return Err!(Request(MissingToken("Missing appservice token.")));
};
2025-01-11 18:49:21 +00:00
let user_id =
if let Some(UserIdentifier::Matrix(MatrixUserIdentifier { user, .. })) = identifier {
UserId::parse_with_server_name(user, &services.config.server_name)
2025-01-11 18:49:21 +00:00
} else if let Some(user) = user {
UserId::parse_with_server_name(user, &services.config.server_name)
2025-01-11 18:49:21 +00:00
} else {
return Err!(Request(Unknown(
debug_warn!(?body.login_info, "Valid identifier or username was not provided (invalid or unsupported login type?)")
)));
2025-01-11 18:49:21 +00:00
}
.map_err(|_| err!(Request(InvalidUsername(warn!("User ID is malformed")))))?;
if !services.globals.user_is_local(&user_id) {
return Err!(Request(Unknown("User ID does not belong to this homeserver")));
}
if !info.is_user_match(&user_id) && !emergency_mode_enabled {
return Err!(Request(Exclusive("Username is not in an appservice namespace.")));
}
user_id
},
| _ => {
debug!("/login json_body: {:?}", &body.json_body);
return Err!(Request(Unknown(
debug_warn!(?body.login_info, "Invalid or unsupported login type")
)));
2021-10-13 10:16:45 +02:00
},
2021-02-07 17:38:45 +01:00
};
2020-07-30 18:14:47 +02:00
// Generate new device id if the user didn't specify one
2024-03-25 17:05:11 -04:00
let device_id = body
.device_id
.clone()
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
2020-07-30 18:14:47 +02:00
// Generate a new token for the device (ensuring no collisions)
let token = services.users.generate_unique_token().await;
2020-07-30 18:14:47 +02:00
2021-01-17 08:39:47 -07:00
// Determine if device_id was provided and exists in the db for this user
2024-08-08 17:18:30 +00:00
let device_exists = if body.device_id.is_some() {
2024-07-16 08:05:25 +00:00
services
2024-03-25 17:05:11 -04:00
.users
.all_device_ids(&user_id)
2024-08-08 17:18:30 +00:00
.ready_any(|v| v == device_id)
.await
} else {
false
};
2021-01-17 08:39:47 -07:00
if device_exists {
2024-08-08 17:18:30 +00:00
services
.users
.set_token(&user_id, &device_id, &token, None)
2024-08-08 17:18:30 +00:00
.await?;
2021-01-17 08:39:47 -07:00
} else {
2024-08-08 17:18:30 +00:00
services
.users
.create_device(
&user_id,
&device_id,
&token,
None,
2024-08-08 17:18:30 +00:00
body.initial_device_display_name.clone(),
Some(client.to_string()),
)
.await?;
}
2020-07-30 18:14:47 +02:00
// send client well-known if specified so the client knows to reconfigure itself
2024-07-16 08:05:25 +00:00
let client_discovery_info: Option<DiscoveryInfo> = services
2024-11-24 00:19:55 +00:00
.server
.config
.well_known
.client
.as_ref()
.map(|server| DiscoveryInfo::new(HomeserverInfo::new(server.to_string())));
info!("{user_id} logged in");
2020-11-15 12:17:21 +01:00
#[allow(deprecated)]
Ok(assign!(login::v3::Response::new(user_id, token, device_id), {
well_known: client_discovery_info,
expires_in: None,
home_server: Some(services.config.server_name.clone()),
refresh_token: None,
}))
2020-07-30 18:14:47 +02:00
}
2025-01-11 18:49:21 +00:00
/// # `POST /_matrix/client/v1/login/get_token`
///
/// Allows a logged-in user to get a short-lived token which can be used
/// to log in with the m.login.token flow.
///
/// <https://spec.matrix.org/v1.13/client-server-api/#post_matrixclientv1loginget_token>
2026-01-04 03:04:37 +00:00
#[tracing::instrument(skip_all, fields(%client), name = "login_token", level = "info")]
2025-01-11 18:49:21 +00:00
pub(crate) async fn login_token_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
2025-01-11 18:49:21 +00:00
body: Ruma<get_login_token::v1::Request>,
) -> Result<get_login_token::v1::Response> {
if !services.server.config.login_via_existing_session {
return Err!(Request(Forbidden("Login via an existing session is not enabled")));
2025-01-11 18:49:21 +00:00
}
let sender_user = body.identity.sender_user();
2025-01-11 18:49:21 +00:00
// Prompt the user to confirm with their password using UIAA
let _ = services
.uiaa
.authenticate_password(&body.auth, sender_user, body.identity.sender_device(), None)
.await?;
2025-01-11 18:49:21 +00:00
let login_token = utils::random_string(TOKEN_LENGTH);
let expires_in = services.users.create_login_token(sender_user, &login_token);
2025-01-11 18:49:21 +00:00
Ok(get_login_token::v1::Response::new(
Duration::from_millis(expires_in),
2025-01-11 18:49:21 +00:00
login_token,
))
2025-01-11 18:49:21 +00:00
}
/// # `POST /_matrix/client/v3/logout`
2020-07-31 14:40:28 +02:00
///
/// Log out the current device.
///
2021-08-31 19:14:37 +02:00
/// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip,
/// last seen ts)
/// - Forgets to-device events
/// - Triggers device list updates
2026-01-04 03:04:37 +00:00
#[tracing::instrument(skip_all, fields(%client), name = "logout", level = "info")]
2024-07-16 08:05:25 +00:00
pub(crate) async fn logout_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
body: Ruma<logout::v3::Request>,
2024-07-16 08:05:25 +00:00
) -> Result<logout::v3::Response> {
let sender_user = body.identity.sender_user();
let sender_device = body.identity.expect_sender_device()?;
2024-08-08 17:18:30 +00:00
services
.users
2026-04-05 20:48:03 +01:00
.remove_device(sender_user, sender_device)
.await;
services
.pusher
.get_pushkeys(sender_user)
.map(ToOwned::to_owned)
.broad_filter_map(async |pushkey| {
services
.pusher
.get_pusher_device(&pushkey)
.await
.ok()
.as_ref()
.is_some_and(|pusher_device| pusher_device == sender_device)
.then_some(pushkey)
})
.for_each(async |pushkey| {
services.pusher.delete_pusher(sender_user, &pushkey).await;
})
2024-08-08 17:18:30 +00:00
.await;
2022-02-18 15:33:14 +01:00
Ok(logout::v3::Response::new())
2020-07-30 18:14:47 +02:00
}
2020-07-31 14:40:28 +02:00
/// # `POST /_matrix/client/r0/logout/all`
///
/// Log out all devices of this user.
///
/// - Invalidates all access tokens
2021-08-31 19:14:37 +02:00
/// - Deletes all device metadata (device id, device display name, last seen ip,
/// last seen ts)
/// - Forgets all to-device events
/// - Triggers device list updates
2020-07-31 14:40:28 +02:00
///
/// Note: This is equivalent to calling [`GET
/// /_matrix/client/r0/logout`](fn.logout_route.html) from each device of this
/// user.
2026-01-04 03:04:37 +00:00
#[tracing::instrument(skip_all, fields(%client), name = "logout", level = "info")]
2024-07-16 08:05:25 +00:00
pub(crate) async fn logout_all_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
body: Ruma<logout_all::v3::Request>,
2024-07-16 08:05:25 +00:00
) -> Result<logout_all::v3::Response> {
let sender_user = body.identity.sender_user();
2024-08-08 17:18:30 +00:00
services
.users
2026-04-05 20:48:03 +01:00
.all_device_ids(sender_user)
.for_each(async |device_id| services.users.remove_device(sender_user, &device_id).await)
2026-04-05 20:48:03 +01:00
.await;
services
.pusher
.get_pushkeys(sender_user)
.for_each(async |pushkey| {
services.pusher.delete_pusher(sender_user, pushkey).await;
})
2024-08-08 17:18:30 +00:00
.await;
2020-07-30 18:14:47 +02:00
2022-02-18 15:33:14 +01:00
Ok(logout_all::v3::Response::new())
2020-07-30 18:14:47 +02:00
}