Skip to content

Commit

Permalink
cleanup+fix login get_token code, use db ser/deser instead
Browse files Browse the repository at this point in the history
Signed-off-by: strawberry <[email protected]>
  • Loading branch information
girlbossceo committed Jan 17, 2025
1 parent 069b3b9 commit 075feb5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 42 deletions.
23 changes: 8 additions & 15 deletions src/api/client/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,15 +242,11 @@ pub(crate) async fn login_token_route(
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")));
return Err!(Request(Forbidden("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");

let sender_user = body.sender_user();
let sender_device = body.sender_device();

// This route SHOULD have UIA
// TODO: How do we make only UIA sessions that have not been used before valid?
Expand All @@ -274,22 +270,19 @@ pub(crate) async fn login_token_route(
}

// Success!
} else if let Some(json) = body.json_body {
} else if let Some(json) = body.json_body.as_ref() {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json);
.create(sender_user, sender_device, &uiaainfo, json);

return Err(Error::Uiaa(uiaainfo));
} else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
return Err!(Request(NotJson("No JSON body was sent when required.")));
}

let login_token = utils::random_string(TOKEN_LENGTH);

let expires_in = services
.users
.create_login_token(sender_user, &login_token)?;
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),
Expand Down
41 changes: 14 additions & 27 deletions src/service/users/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::{collections::BTreeMap, mem, mem::size_of, sync::Arc};

use conduwuit::{
debug_warn, err, utils,
utils::{stream::TryIgnore, string::Unquoted, ReadyExt},
debug_info, debug_warn, err, trace,
utils::{self, stream::TryIgnore, string::Unquoted, ReadyExt},
Err, Error, Result, Server,
};
use database::{Database, Deserialized, Ignore, Interfix, Json, Map};
Expand Down Expand Up @@ -945,50 +945,37 @@ impl Service {

/// 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> {
pub fn create_login_token(&self, user_id: &UserId, token: &str) -> 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());
let value = (expires_at.0, user_id);
self.db.logintoken_expiresatuserid.raw_put(token, value);

self.db
.logintoken_expiresatuserid
.insert(token.as_bytes(), value.as_slice());

Ok(expires_in)
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")));
return Err!(Request(Forbidden("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}")))?,
);
let (expires_at, user_id): (u64, OwnedUserId) = value.deserialized()?;

if expires_at < utils::millis_since_unix_epoch() {
debug_warn!("Login token is expired, removing");
self.db.openidtoken_expiresatuserid.remove(token.as_bytes());
trace!(?user_id, ?token, "Removing expired login token");

return Err!(Request(Unauthorized("Login token is expired")));
}
self.db.logintoken_expiresatuserid.remove(token);

self.db.openidtoken_expiresatuserid.remove(token.as_bytes());
return Err!(Request(Forbidden("Login token is expired")));
}

let user_string = utils::string_from_bytes(user_bytes)
.map_err(|e| err!(Database("User ID in login_userid is invalid unicode. {e}")))?;
self.db.logintoken_expiresatuserid.remove(token);

OwnedUserId::try_from(user_string)
.map_err(|e| err!(Database("User ID in login_userid is invalid. {e}")))
Ok(user_id)
}

/// Gets a specific user profile key
Expand Down

0 comments on commit 075feb5

Please sign in to comment.