1
0
Fork 0
mirror of https://gitlab.com/famedly/conduit.git synced 2025-06-27 16:35:59 +00:00
conduit/src/api/client_server/session.rs

319 lines
11 KiB
Rust
Raw Normal View History

2021-07-14 07:07:08 +00:00
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
2024-07-10 08:19:39 +02:00
use crate::{service::sso::LoginToken, services, utils, Error, Result, Ruma};
2020-07-30 18:14:47 +02:00
use ruma::{
api::client::{
error::ErrorKind,
2022-02-18 15:33:14 +01:00
session::{get_login_types, login, logout, logout_all},
2022-12-14 13:09:10 +01:00
uiaa::UserIdentifier,
2020-07-30 18:14:47 +02:00
},
UserId,
};
2021-02-07 17:38:45 +01:00
use serde::Deserialize;
use tracing::{info, warn};
2021-02-07 17:38:45 +01:00
#[derive(Debug, Deserialize)]
struct Claims {
sub: String,
2022-02-19 12:53:11 +01:00
//exp: usize,
2021-02-07 17:38:45 +01:00
}
2020-07-30 18:14:47 +02:00
2020-07-31 14:40:28 +02:00
/// # `GET /_matrix/client/r0/login`
///
2021-08-31 19:14:37 +02:00
/// Get the supported login types of this server. One of these should be used as the `type` field
2020-07-31 14:40:28 +02:00
/// when logging in.
2022-01-20 11:51:31 +01:00
pub async fn get_login_types_route(
2022-12-14 13:09:10 +01:00
_body: Ruma<get_login_types::v3::Request>,
2022-02-18 15:33:14 +01:00
) -> Result<get_login_types::v3::Response> {
2024-07-10 08:19:39 +02:00
let mut flows = vec![
2022-02-18 15:33:14 +01:00
get_login_types::v3::LoginType::Password(Default::default()),
get_login_types::v3::LoginType::ApplicationService(Default::default()),
2024-07-10 08:19:39 +02:00
];
if let v @ [_, ..] = &*services().sso.flows() {
let flow = get_login_types::v3::SsoLoginType {
identity_providers: v.to_owned(),
};
flows.push(get_login_types::v3::LoginType::Sso(flow));
}
Ok(get_login_types::v3::Response::new(flows))
2020-07-30 18:14:47 +02:00
}
2020-07-31 14:40:28 +02:00
/// # `POST /_matrix/client/r0/login`
///
/// 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.
2022-12-14 13:09:10 +01:00
pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Response> {
// To allow deprecated login methods
#![allow(deprecated)]
2020-07-30 18:14:47 +02:00
// Validate login method
2021-02-07 17:38:45 +01:00
// TODO: Other login methods
let user_id = match &body.login_info {
2022-12-14 13:09:10 +01:00
login::v3::LoginInfo::Password(login::v3::Password {
2021-03-18 19:38:08 +01:00
identifier,
password,
user,
address: _,
medium: _,
}) => {
let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
UserId::parse_with_server_name(
user_id.to_lowercase(),
services().globals.server_name(),
)
} else if let Some(user) = user {
UserId::parse(user)
2021-02-07 17:38:45 +01:00
} else {
warn!("Bad login type: {:?}", &body.login_info);
2024-04-07 20:46:18 +01:00
return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type."));
}
.map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
if services().appservice.is_exclusive_user_id(&user_id).await {
return Err(Error::BadRequest(
ErrorKind::Exclusive,
"User id reserved by appservice.",
));
}
2022-10-05 20:34:31 +02:00
let hash = services()
.users
.password_hash(&user_id)?
.ok_or(Error::BadRequest(
2024-04-07 20:46:18 +01:00
ErrorKind::forbidden(),
2022-10-05 20:34:31 +02:00
"Wrong username or password.",
))?;
2020-07-30 18:14:47 +02:00
if hash.is_empty() {
return Err(Error::BadRequest(
ErrorKind::UserDeactivated,
2021-02-07 17:38:45 +01:00
"The user has been deactivated",
2020-07-30 18:14:47 +02:00
));
}
2021-02-07 17:38:45 +01:00
let hash_matches = argon2::verify_encoded(&hash, password.as_bytes()).unwrap_or(false);
2020-07-30 18:14:47 +02:00
if !hash_matches {
2021-02-07 17:38:45 +01:00
return Err(Error::BadRequest(
2024-04-07 20:46:18 +01:00
ErrorKind::forbidden(),
2021-02-07 17:38:45 +01:00
"Wrong username or password.",
));
2020-07-30 18:14:47 +02:00
}
user_id
2021-02-07 17:38:45 +01:00
}
2022-12-14 13:09:10 +01:00
login::v3::LoginInfo::Token(login::v3::Token { token }) => {
2024-07-10 08:19:39 +02:00
match (
services().globals.jwt_decoding_key(),
&services().sso.providers().is_empty(),
) {
(_, false) => {
let mut validation =
jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::HS256);
validation.validate_nbf = false;
validation.set_required_spec_claims(&["sub", "exp", "aud", "iss"]);
let login_token = services()
.globals
.validate_claims::<LoginToken>(token, Some(validation))
.map_err(|_| {
2024-07-10 08:19:39 +02:00
Error::BadRequest(ErrorKind::InvalidParam, "Invalid token.")
})?;
2024-07-10 08:19:39 +02:00
login_token.audience().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Invalid token audience.")
})?
}
(Some(jwt_decoding_key), _) => {
let token = jsonwebtoken::decode::<Claims>(
token,
jwt_decoding_key,
&jsonwebtoken::Validation::default(),
)
.map_err(|_| {
Error::BadRequest(ErrorKind::InvalidUsername, "Token is invalid.")
})?;
let username = token.claims.sub.to_lowercase();
let user_id =
UserId::parse_with_server_name(username, services().globals.server_name())
.map_err(|_| {
Error::BadRequest(
ErrorKind::InvalidUsername,
"Username is invalid.",
)
})?;
if services().appservice.is_exclusive_user_id(&user_id).await {
return Err(Error::BadRequest(
ErrorKind::Exclusive,
"User id reserved by appservice.",
));
}
user_id
}
(None, _) => {
return Err(Error::BadRequest(
2024-07-10 08:19:39 +02:00
ErrorKind::Unknown,
"Token login is not supported (server has no jwt decoding key).",
));
}
2021-02-07 17:38:45 +01:00
}
}
2024-07-10 08:19:39 +02:00
login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService {
identifier,
user,
}) => {
let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
UserId::parse_with_server_name(
user_id.to_lowercase(),
services().globals.server_name(),
)
} else if let Some(user) = user {
UserId::parse(user)
} else {
warn!("Bad login type: {:?}", &body.login_info);
2024-04-07 20:46:18 +01:00
return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type."));
}
.map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
if let Some(ref info) = body.appservice_info {
if !info.is_user_match(&user_id) {
return Err(Error::BadRequest(
ErrorKind::Exclusive,
"User is not in namespace.",
));
}
} else {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing appservice token.",
));
}
user_id
}
_ => {
warn!("Unsupported or unknown login type: {:?}", &body.login_info);
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Unsupported login type.",
));
}
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
let device_id = body
.device_id
.clone()
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
// Generate a new token for the device
let token = utils::random_string(TOKEN_LENGTH);
// Determine if device_id was provided and exists in the db for this user
let device_exists = body.device_id.as_ref().map_or(false, |device_id| {
2022-10-05 20:34:31 +02:00
services()
.users
.all_device_ids(&user_id)
.any(|x| x.as_ref().map_or(false, |v| v == device_id))
});
if device_exists {
services().users.set_token(&user_id, &device_id, &token)?;
} else {
services().users.create_device(
&user_id,
&device_id,
&token,
body.initial_device_display_name.clone(),
)?;
}
2020-07-30 18:14:47 +02:00
2020-11-15 12:17:21 +01:00
info!("{} logged in", user_id);
2023-12-23 19:34:27 -08:00
// Homeservers are still required to send the `home_server` field
#[allow(deprecated)]
2022-02-18 15:33:14 +01:00
Ok(login::v3::Response {
2020-07-30 18:14:47 +02:00
user_id,
access_token: token,
home_server: Some(services().globals.server_name().to_owned()),
2020-07-30 18:14:47 +02:00
device_id,
well_known: None,
2022-10-09 17:25:06 +02:00
refresh_token: None,
expires_in: None,
})
2020-07-30 18:14:47 +02:00
}
2020-07-31 14:40:28 +02:00
/// # `POST /_matrix/client/r0/logout`
///
/// 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
2022-10-05 20:34:31 +02:00
pub async fn logout_route(body: Ruma<logout::v3::Request>) -> Result<logout::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
2020-07-30 18:14:47 +02:00
if let Some(ref info) = body.appservice_info {
if !info.is_user_match(sender_user) {
return Err(Error::BadRequest(
ErrorKind::Exclusive,
"User is not in namespace.",
));
}
}
services().users.remove_device(sender_user, sender_device)?;
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.
pub async fn logout_all_route(
2022-02-18 15:33:14 +01:00
body: Ruma<logout_all::v3::Request>,
) -> Result<logout_all::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
2020-07-30 18:14:47 +02:00
if let Some(ref info) = body.appservice_info {
if !info.is_user_match(sender_user) {
return Err(Error::BadRequest(
ErrorKind::Exclusive,
"User is not in namespace.",
));
}
} else {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing appservice token.",
));
}
for device_id in services().users.all_device_ids(sender_user).flatten() {
services().users.remove_device(sender_user, &device_id)?;
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
}