Files
continuwuity/src/service/uiaa/mod.rs
T

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

350 lines
8.7 KiB
Rust
Raw Normal View History

2026-01-05 17:27:00 -05:00
use std::{collections::BTreeMap, sync::Arc};
2024-05-09 15:59:08 -07:00
2024-12-14 21:58:01 -05:00
use conduwuit::{
Err, Error, Result, SyncRwLock, err, error, implement, utils,
2024-08-08 17:18:30 +00:00
utils::{hash, string::EMPTY},
};
2024-10-07 17:54:27 +00:00
use database::{Deserialized, Json, Map};
2022-10-05 20:34:31 +02:00
use ruma::{
CanonicalJsonValue, DeviceId, OwnedDeviceId, OwnedUserId, UserId,
2022-10-05 20:34:31 +02:00
api::client::{
2025-12-14 01:21:38 +00:00
error::{ErrorKind, StandardErrorBody},
2022-12-14 13:09:10 +01:00
uiaa::{AuthData, AuthType, Password, UiaaInfo, UserIdentifier},
2022-10-05 20:34:31 +02:00
},
};
2021-06-08 18:10:00 +02:00
2026-01-05 17:27:00 -05:00
use crate::{Dep, config, globals, registration_tokens, users};
2024-05-09 15:59:08 -07:00
pub struct Service {
userdevicesessionid_uiaarequest: SyncRwLock<RequestMap>,
2024-08-08 17:18:30 +00:00
db: Data,
2024-07-18 06:37:47 +00:00
services: Services,
2020-06-06 18:44:50 +02:00
}
2024-07-18 06:37:47 +00:00
struct Services {
globals: Dep<globals::Service>,
users: Dep<users::Service>,
config: Dep<config::Service>,
2026-01-05 17:27:00 -05:00
registration_tokens: Dep<registration_tokens::Service>,
2024-07-18 06:37:47 +00:00
}
2024-08-08 17:18:30 +00:00
struct Data {
userdevicesessionid_uiaainfo: Arc<Map>,
}
type RequestMap = BTreeMap<RequestKey, CanonicalJsonValue>;
type RequestKey = (OwnedUserId, OwnedDeviceId, String);
pub const SESSION_ID_LENGTH: usize = 32;
2024-07-04 03:26:19 +00:00
impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
Ok(Arc::new(Self {
userdevicesessionid_uiaarequest: SyncRwLock::new(RequestMap::new()),
2024-08-08 17:18:30 +00:00
db: Data {
userdevicesessionid_uiaainfo: args.db["userdevicesessionid_uiaainfo"].clone(),
},
2024-07-18 06:37:47 +00:00
services: Services {
globals: args.depend::<globals::Service>("globals"),
users: args.depend::<users::Service>("users"),
config: args.depend::<config::Service>("config"),
2026-01-05 17:27:00 -05:00
registration_tokens: args
.depend::<registration_tokens::Service>("registration_tokens"),
2024-07-18 06:37:47 +00:00
},
2024-07-04 03:26:19 +00:00
}))
2024-05-27 03:17:20 +00:00
}
2024-07-04 03:26:19 +00:00
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
}
2024-08-08 17:18:30 +00:00
/// Creates a new Uiaa session. Make sure the session token is unique.
#[implement(Service)]
pub fn create(
&self,
user_id: &UserId,
device_id: &DeviceId,
uiaainfo: &UiaaInfo,
json_body: &CanonicalJsonValue,
) {
2024-08-08 17:18:30 +00:00
// TODO: better session error handling (why is uiaainfo.session optional in
// ruma?)
self.set_uiaa_request(
user_id,
device_id,
uiaainfo.session.as_ref().expect("session should be set"),
json_body,
);
self.update_uiaa_session(
user_id,
device_id,
uiaainfo.session.as_ref().expect("session should be set"),
Some(uiaainfo),
);
}
2024-03-05 19:48:54 -05:00
2024-08-08 17:18:30 +00:00
#[implement(Service)]
2025-12-14 01:21:38 +00:00
#[allow(clippy::useless_let_if_seq)]
2024-08-08 17:18:30 +00:00
pub async fn try_auth(
&self,
user_id: &UserId,
device_id: &DeviceId,
auth: &AuthData,
uiaainfo: &UiaaInfo,
2024-08-08 17:18:30 +00:00
) -> Result<(bool, UiaaInfo)> {
let mut uiaainfo = if let Some(session) = auth.session() {
self.get_uiaa_session(user_id, device_id, session).await?
} else {
uiaainfo.clone()
};
if uiaainfo.session.is_none() {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
}
2024-03-05 19:48:54 -05:00
2024-08-08 17:18:30 +00:00
match auth {
// Find out what the user completed
| AuthData::Password(Password {
2024-08-08 17:18:30 +00:00
identifier,
password,
#[cfg(feature = "element_hacks")]
user,
..
}) => {
#[cfg(feature = "element_hacks")]
let username = if let Some(UserIdentifier::UserIdOrLocalpart(username)) = identifier {
username
} else if let Some(username) = user {
username
} else {
return Err(Error::BadRequest(
ErrorKind::Unrecognized,
"Identifier type not recognized.",
));
2024-08-08 17:18:30 +00:00
};
#[cfg(not(feature = "element_hacks"))]
let Some(UserIdentifier::UserIdOrLocalpart(username)) = identifier else {
return Err(Error::BadRequest(
ErrorKind::Unrecognized,
"Identifier type not recognized.",
));
2024-08-08 17:18:30 +00:00
};
let user_id_from_username = UserId::parse_with_server_name(
username.clone(),
self.services.globals.server_name(),
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "User ID is invalid."))?;
2024-08-08 17:18:30 +00:00
// Check if the access token being used matches the credentials used for UIAA
if user_id.localpart() != user_id_from_username.localpart() {
return Err!(Request(Forbidden("User ID and access token mismatch.")));
}
let user_id = user_id_from_username;
2024-08-08 17:18:30 +00:00
// Check if password is correct
2025-12-14 01:21:38 +00:00
let mut password_verified = false;
// First try local password hash verification
2024-08-08 17:18:30 +00:00
if let Ok(hash) = self.services.users.password_hash(&user_id).await {
2025-12-14 01:21:38 +00:00
password_verified = hash::verify_password(password, &hash).is_ok();
}
// If local password verification failed, try LDAP authentication
#[cfg(feature = "ldap")]
if !password_verified && self.services.config.ldap.enable {
// Search for user in LDAP to get their DN
if let Ok(dns) = self.services.users.search_ldap(&user_id).await {
if let Some((user_dn, _is_admin)) = dns.first() {
// Try to authenticate with LDAP
password_verified = self
.services
.users
.auth_ldap(user_dn, password)
.await
.is_ok();
}
2023-08-09 18:27:30 +02:00
}
2024-08-08 17:18:30 +00:00
}
2024-03-05 19:48:54 -05:00
2025-12-14 01:21:38 +00:00
if !password_verified {
uiaainfo.auth_error = Some(StandardErrorBody {
kind: ErrorKind::forbidden(),
message: "Invalid username or password.".to_owned(),
});
return Ok((false, uiaainfo));
}
2024-08-08 17:18:30 +00:00
// Password was correct! Let's add it to `completed`
uiaainfo.completed.push(AuthType::Password);
},
2025-07-08 18:58:05 +01:00
| AuthData::ReCaptcha(r) => {
if self.services.config.recaptcha_private_site_key.is_none() {
return Err!(Request(Forbidden("ReCaptcha is not configured.")));
}
match recaptcha_verify::verify(
self.services
.config
.recaptcha_private_site_key
.as_ref()
.unwrap(),
r.response.as_str(),
None,
)
.await
{
| Ok(()) => {
2025-07-08 18:58:05 +01:00
uiaainfo.completed.push(AuthType::ReCaptcha);
},
| Err(e) => {
error!("ReCaptcha verification failed: {e:?}");
2025-12-14 01:21:38 +00:00
uiaainfo.auth_error = Some(StandardErrorBody {
2025-07-08 18:58:05 +01:00
kind: ErrorKind::forbidden(),
message: "ReCaptcha verification failed.".to_owned(),
});
return Ok((false, uiaainfo));
},
}
},
| AuthData::RegistrationToken(t) => {
let token = t.token.trim().to_owned();
2026-01-05 17:27:00 -05:00
if let Some(valid_token) = self
.services
.registration_tokens
.validate_token(token)
.await
{
self.services
.registration_tokens
.mark_token_as_used(valid_token);
2024-08-08 17:18:30 +00:00
uiaainfo.completed.push(AuthType::RegistrationToken);
} else {
2025-12-14 01:21:38 +00:00
uiaainfo.auth_error = Some(StandardErrorBody {
2024-08-08 17:18:30 +00:00
kind: ErrorKind::forbidden(),
message: "Invalid registration token.".to_owned(),
});
return Ok((false, uiaainfo));
}
2024-08-08 17:18:30 +00:00
},
| AuthData::Dummy(_) => {
2024-08-08 17:18:30 +00:00
uiaainfo.completed.push(AuthType::Dummy);
},
| AuthData::FallbackAcknowledgement(_) => {
// The client is checking if authentication has succeeded out-of-band. This is
// possible if the client is using "fallback auth" (see spec section
// 4.9.1.4), which we don't support (and probably never will, because it's a
// disgusting hack).
// Return early to tell the client that no, authentication did not succeed while
// it wasn't looking.
return Ok((false, uiaainfo));
},
| k => error!("type not supported: {:?}", k),
2024-08-08 17:18:30 +00:00
}
2024-03-05 19:48:54 -05:00
2024-08-08 17:18:30 +00:00
// Check if a flow now succeeds
let mut completed = false;
'flows: for flow in &mut uiaainfo.flows {
for stage in &flow.stages {
if !uiaainfo.completed.contains(stage) {
continue 'flows;
}
2020-06-06 18:44:50 +02:00
}
2024-08-08 17:18:30 +00:00
// We didn't break, so this flow succeeded!
completed = true;
}
2024-03-05 19:48:54 -05:00
2024-08-08 17:18:30 +00:00
if !completed {
self.update_uiaa_session(
user_id,
device_id,
uiaainfo.session.as_ref().expect("session is always set"),
2024-08-08 17:18:30 +00:00
Some(&uiaainfo),
);
return Ok((false, uiaainfo));
2020-06-06 18:44:50 +02:00
}
2024-03-05 19:48:54 -05:00
2024-08-08 17:18:30 +00:00
// UIAA was successful! Remove this session and return true
self.update_uiaa_session(
user_id,
device_id,
uiaainfo.session.as_ref().expect("session is always set"),
None,
);
Ok((true, uiaainfo))
}
#[implement(Service)]
fn set_uiaa_request(
&self,
user_id: &UserId,
device_id: &DeviceId,
session: &str,
request: &CanonicalJsonValue,
) {
2024-08-08 17:18:30 +00:00
let key = (user_id.to_owned(), device_id.to_owned(), session.to_owned());
self.userdevicesessionid_uiaarequest
.write()
.insert(key, request.to_owned());
}
#[implement(Service)]
pub fn get_uiaa_request(
&self,
user_id: &UserId,
device_id: Option<&DeviceId>,
session: &str,
2024-08-08 17:18:30 +00:00
) -> Option<CanonicalJsonValue> {
let key = (
user_id.to_owned(),
device_id.unwrap_or_else(|| EMPTY.into()).to_owned(),
session.to_owned(),
);
self.userdevicesessionid_uiaarequest
.read()
.get(&key)
.cloned()
}
#[implement(Service)]
fn update_uiaa_session(
&self,
user_id: &UserId,
device_id: &DeviceId,
session: &str,
uiaainfo: Option<&UiaaInfo>,
) {
2024-10-07 17:54:27 +00:00
let key = (user_id, device_id, session);
2024-08-08 17:18:30 +00:00
if let Some(uiaainfo) = uiaainfo {
self.db
.userdevicesessionid_uiaainfo
2024-10-07 17:54:27 +00:00
.put(key, Json(uiaainfo));
} else {
self.db.userdevicesessionid_uiaainfo.del(key);
2021-05-04 19:03:18 +02:00
}
2020-06-06 18:44:50 +02:00
}
2024-08-08 17:18:30 +00:00
#[implement(Service)]
async fn get_uiaa_session(
&self,
user_id: &UserId,
device_id: &DeviceId,
session: &str,
) -> Result<UiaaInfo> {
2024-08-08 17:18:30 +00:00
let key = (user_id, device_id, session);
self.db
.userdevicesessionid_uiaainfo
.qry(&key)
.await
2024-09-28 15:14:48 +00:00
.deserialized()
2024-08-08 17:18:30 +00:00
.map_err(|_| err!(Request(Forbidden("UIAA session does not exist."))))
}