Skip to content

Commit

Permalink
implement /login/get_token (MSC3882)
Browse files Browse the repository at this point in the history
  • Loading branch information
JadedBlueEyes authored and girlbossceo committed Jan 17, 2025
1 parent 77f18f5 commit 069b3b9
Show file tree
Hide file tree
Showing 7 changed files with 196 additions and 24 deletions.
16 changes: 16 additions & 0 deletions conduwuit-example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,22 @@
#
#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
# ("turn_secret"), It is recommended to use a shared secret over static
# credentials.
Expand Down
5 changes: 3 additions & 2 deletions src/api/client/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ pub(crate) async fn get_capabilities_route(
// we do not implement 3PID stuff
capabilities.thirdparty_id_changes = ThirdPartyIdChangesCapability { enabled: false };

// we dont support generating tokens yet
capabilities.get_login_token = GetLoginTokenCapability { enabled: false };
capabilities.get_login_token = GetLoginTokenCapability {
enabled: services.server.config.login_via_existing_session,
};

// MSC4133 capability
capabilities
Expand Down
124 changes: 102 additions & 22 deletions src/api/client/session.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::time::Duration;

use axum::extract::State;
use axum_client_ip::InsecureClientIp;
use conduwuit::{debug, err, info, utils::ReadyExt, warn, Err};
Expand All @@ -6,20 +8,22 @@ use ruma::{
api::client::{
error::ErrorKind,
session::{
get_login_token,
get_login_types::{
self,
v3::{ApplicationServiceLoginType, PasswordLoginType},
v3::{ApplicationServiceLoginType, PasswordLoginType, TokenLoginType},
},
login::{
self,
v3::{DiscoveryInfo, HomeserverInfo},
},
logout, logout_all,
},
uiaa::UserIdentifier,
uiaa,
},
OwnedUserId, UserId,
};
use service::uiaa::SESSION_ID_LENGTH;

use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{utils, utils::hash, Error, Result, Ruma};
Expand All @@ -30,12 +34,16 @@ use crate::{utils, utils::hash, Error, Result, Ruma};
/// the `type` field when logging in.
#[tracing::instrument(skip_all, fields(%client), name = "login")]
pub(crate) async fn get_login_types_route(
State(services): State<crate::State>,
InsecureClientIp(client): InsecureClientIp,
_body: Ruma<get_login_types::v3::Request>,
) -> Result<get_login_types::v3::Response> {
Ok(get_login_types::v3::Response::new(vec![
get_login_types::v3::LoginType::Password(PasswordLoginType::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,
}),
]))
}

Expand Down Expand Up @@ -70,7 +78,9 @@ pub(crate) async fn login_route(
..
}) => {
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(
user_id.to_lowercase(),
services.globals.server_name(),
Expand Down Expand Up @@ -99,33 +109,35 @@ pub(crate) async fn login_route(

user_id
},
| login::v3::LoginInfo::Token(login::v3::Token { token: _ }) => {
| login::v3::LoginInfo::Token(login::v3::Token { token }) => {
debug!("Got token login type");
return Err!(Request(Unknown(
"Token login is not supported."
)));
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?
},
#[allow(deprecated)]
| login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService {
identifier,
user,
}) => {
debug!("Got appservice login type");
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 {
OwnedUserId::parse(user)
} else {
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}");
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;
let user_id =
if let Some(uiaa::UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
UserId::parse_with_server_name(
user_id.to_lowercase(),
services.globals.server_name(),
)
} else if let Some(user) = user {
OwnedUserId::parse(user)
} else {
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}");
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;

if let Some(ref info) = body.appservice_info {
if !info.is_user_match(&user_id) {
Expand Down Expand Up @@ -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`
///
/// Log out the current device.
Expand Down
1 change: 1 addition & 0 deletions src/api/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub fn build(router: Router<State>, server: &Server) -> Router<State> {
.ruma_route(&client::register_route)
.ruma_route(&client::get_login_types_route)
.ruma_route(&client::login_route)
.ruma_route(&client::login_token_route)
.ruma_route(&client::whoami_route)
.ruma_route(&client::logout_route)
.ruma_route(&client::logout_all_route)
Expand Down
20 changes: 20 additions & 0 deletions src/core/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,24 @@ pub struct Config {
#[serde(default = "default_openid_token_ttl")]
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
/// ("turn_secret"), It is recommended to use a shared secret over static
/// credentials.
Expand Down Expand Up @@ -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_login_token_ttl() -> u64 { 2 * 60 * 1000 }

fn default_turn_ttl() -> u64 { 60 * 60 * 24 }

fn default_presence_idle_timeout_s() -> u64 { 5 * 60 }
Expand Down
4 changes: 4 additions & 0 deletions src/database/maps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,10 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "openidtoken_expiresatuserid",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "logintoken_expiresatuserid",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userroomid_highlightcount",
..descriptor::RANDOM
Expand Down
50 changes: 50 additions & 0 deletions src/service/users/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ struct Data {
keyid_key: Arc<Map>,
onetimekeyid_onetimekeys: Arc<Map>,
openidtoken_expiresatuserid: Arc<Map>,
logintoken_expiresatuserid: Arc<Map>,
todeviceid_events: Arc<Map>,
token_userdeviceid: Arc<Map>,
userdeviceid_metadata: Arc<Map>,
Expand Down Expand Up @@ -76,6 +77,7 @@ impl crate::Service for Service {
keyid_key: args.db["keyid_key"].clone(),
onetimekeyid_onetimekeys: args.db["onetimekeyid_onetimekeys"].clone(),
openidtoken_expiresatuserid: args.db["openidtoken_expiresatuserid"].clone(),
logintoken_expiresatuserid: args.db["logintoken_expiresatuserid"].clone(),
todeviceid_events: args.db["todeviceid_events"].clone(),
token_userdeviceid: args.db["token_userdeviceid"].clone(),
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
Expand Down Expand Up @@ -941,6 +943,54 @@ impl Service {
.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
pub async fn profile_key(
&self,
Expand Down

0 comments on commit 069b3b9

Please sign in to comment.