implement /login/get_token (MSC3882)

This commit is contained in:
Jade Ellis 2025-01-11 18:49:21 +00:00 committed by June Clementine Strawberry 🍓🦴
parent afe9e5536b
commit 2cc6ad8df3
7 changed files with 196 additions and 24 deletions

View file

@ -645,6 +645,22 @@
# #
#openid_token_ttl = 3600 #openid_token_ttl = 3600
# Allow an existing session to mint a login token for another client.
# This requires interactive authentication, but has security ramifications
# as a malicious client could use the mechanism to spawn more than one
# session.
# Enabled by default.
#
#login_via_existing_session = true
# Login token expiration/TTL in milliseconds.
#
# These are short-lived tokens for the m.login.token endpoint.
# This is used to allow existing sessions to create new sessions.
# see login_via_existing_session.
#
#login_token_ttl = 120000
# Static TURN username to provide the client if not using a shared secret # Static TURN username to provide the client if not using a shared secret
# ("turn_secret"), It is recommended to use a shared secret over static # ("turn_secret"), It is recommended to use a shared secret over static
# credentials. # credentials.

View file

@ -32,8 +32,9 @@ pub(crate) async fn get_capabilities_route(
// we do not implement 3PID stuff // we do not implement 3PID stuff
capabilities.thirdparty_id_changes = ThirdPartyIdChangesCapability { enabled: false }; capabilities.thirdparty_id_changes = ThirdPartyIdChangesCapability { enabled: false };
// we dont support generating tokens yet capabilities.get_login_token = GetLoginTokenCapability {
capabilities.get_login_token = GetLoginTokenCapability { enabled: false }; enabled: services.server.config.login_via_existing_session,
};
// MSC4133 capability // MSC4133 capability
capabilities capabilities

View file

@ -1,3 +1,5 @@
use std::time::Duration;
use axum::extract::State; use axum::extract::State;
use axum_client_ip::InsecureClientIp; use axum_client_ip::InsecureClientIp;
use conduwuit::{debug, err, info, utils::ReadyExt, warn, Err}; use conduwuit::{debug, err, info, utils::ReadyExt, warn, Err};
@ -6,9 +8,10 @@ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
session::{ session::{
get_login_token,
get_login_types::{ get_login_types::{
self, self,
v3::{ApplicationServiceLoginType, PasswordLoginType}, v3::{ApplicationServiceLoginType, PasswordLoginType, TokenLoginType},
}, },
login::{ login::{
self, self,
@ -16,10 +19,11 @@ use ruma::{
}, },
logout, logout_all, logout, logout_all,
}, },
uiaa::UserIdentifier, uiaa,
}, },
OwnedUserId, UserId, OwnedUserId, UserId,
}; };
use service::uiaa::SESSION_ID_LENGTH;
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH}; use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{utils, utils::hash, Error, Result, Ruma}; use crate::{utils, utils::hash, Error, Result, Ruma};
@ -30,12 +34,16 @@ use crate::{utils, utils::hash, Error, Result, Ruma};
/// the `type` field when logging in. /// the `type` field when logging in.
#[tracing::instrument(skip_all, fields(%client), name = "login")] #[tracing::instrument(skip_all, fields(%client), name = "login")]
pub(crate) async fn get_login_types_route( pub(crate) async fn get_login_types_route(
State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp, InsecureClientIp(client): InsecureClientIp,
_body: Ruma<get_login_types::v3::Request>, _body: Ruma<get_login_types::v3::Request>,
) -> Result<get_login_types::v3::Response> { ) -> Result<get_login_types::v3::Response> {
Ok(get_login_types::v3::Response::new(vec![ Ok(get_login_types::v3::Response::new(vec![
get_login_types::v3::LoginType::Password(PasswordLoginType::default()), get_login_types::v3::LoginType::Password(PasswordLoginType::default()),
get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()), get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()),
get_login_types::v3::LoginType::Token(TokenLoginType {
get_login_token: services.server.config.login_via_existing_session,
}),
])) ]))
} }
@ -70,7 +78,9 @@ pub(crate) async fn login_route(
.. ..
}) => { }) => {
debug!("Got password login type"); debug!("Got password login type");
let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier { let user_id = if let Some(uiaa::UserIdentifier::UserIdOrLocalpart(user_id)) =
identifier
{
UserId::parse_with_server_name( UserId::parse_with_server_name(
user_id.to_lowercase(), user_id.to_lowercase(),
services.globals.server_name(), services.globals.server_name(),
@ -99,11 +109,12 @@ pub(crate) async fn login_route(
user_id user_id
}, },
| login::v3::LoginInfo::Token(login::v3::Token { token: _ }) => { | login::v3::LoginInfo::Token(login::v3::Token { token }) => {
debug!("Got token login type"); debug!("Got token login type");
return Err!(Request(Unknown( if !services.server.config.login_via_existing_session {
"Token login is not supported." return Err!(Request(Unknown("Token login is not enabled.")));
))); }
services.users.find_from_login_token(token).await?
}, },
#[allow(deprecated)] #[allow(deprecated)]
| login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService { | login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService {
@ -111,21 +122,22 @@ pub(crate) async fn login_route(
user, user,
}) => { }) => {
debug!("Got appservice login type"); debug!("Got appservice login type");
let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier { let user_id =
UserId::parse_with_server_name( if let Some(uiaa::UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
user_id.to_lowercase(), UserId::parse_with_server_name(
services.globals.server_name(), user_id.to_lowercase(),
) services.globals.server_name(),
} else if let Some(user) = user { )
OwnedUserId::parse(user) } else if let Some(user) = user {
} else { OwnedUserId::parse(user)
warn!("Bad login type: {:?}", &body.login_info); } else {
return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type.")); warn!("Bad login type: {:?}", &body.login_info);
} return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type."));
.map_err(|e| { }
warn!("Failed to parse username from appservice logging in: {e}"); .map_err(|e| {
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") warn!("Failed to parse username from appservice logging in: {e}");
})?; Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;
if let Some(ref info) = body.appservice_info { if let Some(ref info) = body.appservice_info {
if !info.is_user_match(&user_id) { if !info.is_user_match(&user_id) {
@ -217,6 +229,74 @@ pub(crate) async fn login_route(
}) })
} }
/// # `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>
#[tracing::instrument(skip_all, fields(%client), name = "login_token")]
pub(crate) async fn login_token_route(
State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp,
body: Ruma<get_login_token::v1::Request>,
) -> Result<get_login_token::v1::Response> {
if !services.server.config.login_via_existing_session {
return Err!(Request(Unknown("Login via an existing session is not enabled")));
}
// Authentication for this endpoint was made optional, but we need
// authentication.
let sender_user = body
.sender_user
.as_ref()
.ok_or_else(|| Error::BadRequest(ErrorKind::MissingToken, "Missing access token."))?;
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
// This route SHOULD have UIA
// TODO: How do we make only UIA sessions that have not been used before valid?
let mut uiaainfo = uiaa::UiaaInfo {
flows: vec![uiaa::AuthFlow { stages: vec![uiaa::AuthType::Password] }],
completed: Vec::new(),
params: Box::default(),
session: None,
auth_error: None,
};
if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)
.await?;
if !worked {
return Err(Error::Uiaa(uiaainfo));
}
// Success!
} else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json);
return Err(Error::Uiaa(uiaainfo));
} else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
let login_token = utils::random_string(TOKEN_LENGTH);
let expires_in = services
.users
.create_login_token(sender_user, &login_token)?;
Ok(get_login_token::v1::Response {
expires_in: Duration::from_millis(expires_in),
login_token,
})
}
/// # `POST /_matrix/client/v3/logout` /// # `POST /_matrix/client/v3/logout`
/// ///
/// Log out the current device. /// Log out the current device.

View file

@ -34,6 +34,7 @@ pub fn build(router: Router<State>, server: &Server) -> Router<State> {
.ruma_route(&client::register_route) .ruma_route(&client::register_route)
.ruma_route(&client::get_login_types_route) .ruma_route(&client::get_login_types_route)
.ruma_route(&client::login_route) .ruma_route(&client::login_route)
.ruma_route(&client::login_token_route)
.ruma_route(&client::whoami_route) .ruma_route(&client::whoami_route)
.ruma_route(&client::logout_route) .ruma_route(&client::logout_route)
.ruma_route(&client::logout_all_route) .ruma_route(&client::logout_all_route)

View file

@ -767,6 +767,24 @@ pub struct Config {
#[serde(default = "default_openid_token_ttl")] #[serde(default = "default_openid_token_ttl")]
pub openid_token_ttl: u64, pub openid_token_ttl: u64,
/// Allow an existing session to mint a login token for another client.
/// This requires interactive authentication, but has security ramifications
/// as a malicious client could use the mechanism to spawn more than one
/// session.
/// Enabled by default.
#[serde(default = "true_fn")]
pub login_via_existing_session: bool,
/// Login token expiration/TTL in milliseconds.
///
/// These are short-lived tokens for the m.login.token endpoint.
/// This is used to allow existing sessions to create new sessions.
/// see login_via_existing_session.
///
/// default: 120000
#[serde(default = "default_login_token_ttl")]
pub login_token_ttl: u64,
/// Static TURN username to provide the client if not using a shared secret /// Static TURN username to provide the client if not using a shared secret
/// ("turn_secret"), It is recommended to use a shared secret over static /// ("turn_secret"), It is recommended to use a shared secret over static
/// credentials. /// credentials.
@ -2373,6 +2391,8 @@ fn default_notification_push_path() -> String { "/_matrix/push/v1/notify".to_own
fn default_openid_token_ttl() -> u64 { 60 * 60 } fn default_openid_token_ttl() -> u64 { 60 * 60 }
fn default_login_token_ttl() -> u64 { 2 * 60 * 1000 }
fn default_turn_ttl() -> u64 { 60 * 60 * 24 } fn default_turn_ttl() -> u64 { 60 * 60 * 24 }
fn default_presence_idle_timeout_s() -> u64 { 5 * 60 } fn default_presence_idle_timeout_s() -> u64 { 5 * 60 }

View file

@ -365,6 +365,10 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "openidtoken_expiresatuserid", name: "openidtoken_expiresatuserid",
..descriptor::RANDOM_SMALL ..descriptor::RANDOM_SMALL
}, },
Descriptor {
name: "logintoken_expiresatuserid",
..descriptor::RANDOM_SMALL
},
Descriptor { Descriptor {
name: "userroomid_highlightcount", name: "userroomid_highlightcount",
..descriptor::RANDOM ..descriptor::RANDOM

View file

@ -41,6 +41,7 @@ struct Data {
keyid_key: Arc<Map>, keyid_key: Arc<Map>,
onetimekeyid_onetimekeys: Arc<Map>, onetimekeyid_onetimekeys: Arc<Map>,
openidtoken_expiresatuserid: Arc<Map>, openidtoken_expiresatuserid: Arc<Map>,
logintoken_expiresatuserid: Arc<Map>,
todeviceid_events: Arc<Map>, todeviceid_events: Arc<Map>,
token_userdeviceid: Arc<Map>, token_userdeviceid: Arc<Map>,
userdeviceid_metadata: Arc<Map>, userdeviceid_metadata: Arc<Map>,
@ -76,6 +77,7 @@ impl crate::Service for Service {
keyid_key: args.db["keyid_key"].clone(), keyid_key: args.db["keyid_key"].clone(),
onetimekeyid_onetimekeys: args.db["onetimekeyid_onetimekeys"].clone(), onetimekeyid_onetimekeys: args.db["onetimekeyid_onetimekeys"].clone(),
openidtoken_expiresatuserid: args.db["openidtoken_expiresatuserid"].clone(), openidtoken_expiresatuserid: args.db["openidtoken_expiresatuserid"].clone(),
logintoken_expiresatuserid: args.db["logintoken_expiresatuserid"].clone(),
todeviceid_events: args.db["todeviceid_events"].clone(), todeviceid_events: args.db["todeviceid_events"].clone(),
token_userdeviceid: args.db["token_userdeviceid"].clone(), token_userdeviceid: args.db["token_userdeviceid"].clone(),
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(), userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
@ -941,6 +943,54 @@ impl Service {
.map_err(|e| err!(Database("User ID in openid_userid is invalid. {e}"))) .map_err(|e| err!(Database("User ID in openid_userid is invalid. {e}")))
} }
/// Creates a short-lived login token, which can be used to log in using the
/// `m.login.token` mechanism.
pub fn create_login_token(&self, user_id: &UserId, token: &str) -> Result<u64> {
use std::num::Saturating as Sat;
let expires_in = self.services.server.config.login_token_ttl;
let expires_at = Sat(utils::millis_since_unix_epoch()) + Sat(expires_in);
let mut value = expires_at.0.to_be_bytes().to_vec();
value.extend_from_slice(user_id.as_bytes());
self.db
.logintoken_expiresatuserid
.insert(token.as_bytes(), value.as_slice());
Ok(expires_in)
}
/// Find out which user a login token belongs to.
/// Removes the token to prevent double-use attacks.
pub async fn find_from_login_token(&self, token: &str) -> Result<OwnedUserId> {
let Ok(value) = self.db.logintoken_expiresatuserid.get(token).await else {
return Err!(Request(Unauthorized("Login token is unrecognised")));
};
let (expires_at_bytes, user_bytes) = value.split_at(0_u64.to_be_bytes().len());
let expires_at = u64::from_be_bytes(
expires_at_bytes
.try_into()
.map_err(|e| err!(Database("expires_at in login_userid is invalid u64. {e}")))?,
);
if expires_at < utils::millis_since_unix_epoch() {
debug_warn!("Login token is expired, removing");
self.db.openidtoken_expiresatuserid.remove(token.as_bytes());
return Err!(Request(Unauthorized("Login token is expired")));
}
self.db.openidtoken_expiresatuserid.remove(token.as_bytes());
let user_string = utils::string_from_bytes(user_bytes)
.map_err(|e| err!(Database("User ID in login_userid is invalid unicode. {e}")))?;
OwnedUserId::try_from(user_string)
.map_err(|e| err!(Database("User ID in login_userid is invalid. {e}")))
}
/// Gets a specific user profile key /// Gets a specific user profile key
pub async fn profile_key( pub async fn profile_key(
&self, &self,