mirror of
https://github.com/dani-garcia/vaultwarden.wiki.git
synced 2026-11-19 18:05:57 +02:00
Modernize Rust code and Fixes (#7971)
* Modernize Rust code and fix input handling - Adopt newer std APIs, reduce allocations, and consolidate caching on Moka. - Update the Rust toolchain and most dependencies, tighten lints, and expand test coverage. - Fix favicon ranking for URLs with query strings or fragments, and try the next icon when SVG sanitization fails. - Prevent panics when masking 2FA email addresses containing Unicode or missing an @. - Prevent panics on Unicode database paths and recognize short postgres: URLs. - Treat whitespace-only collection and member external IDs as absent and avoid redundant membership updates. - Align stable builds’ global IP classification with Rust’s standard library. Signed-off-by: BlackDex <black.dex@gmail.com> * Update crates and some fixes - Bump Rocket, rocket_ws, Diesel, SQLite bindings, and html5gum. - Reuse WebSocket payload buffers and detect upgrades from the response. - Match favicon rel tokens case-insensitively, honor the first base href, and stop scanning at the end of the head or the start of the body. Signed-off-by: BlackDex <black.dex@gmail.com> --------- Signed-off-by: BlackDex <black.dex@gmail.com>
This commit is contained in:
1 parent
4051a4d3a6
commit
4a0acc3314
51 files changed
+1219
-1569
No files matched your search
+15
-22
@@ -166,8 +166,8 @@ impl RegisterDataCompat {
|
||||
fcu: impl FnOnce(&'a RegisterDataCur) -> &'a T,
|
||||
) -> &'a T {
|
||||
match self {
|
||||
RegisterDataCompat::RegisterDataOld(rdc) => fct(rdc),
|
||||
RegisterDataCompat::RegisterDataCur(rdcu) => fcu(rdcu),
|
||||
Self::RegisterDataOld(rdc) => fct(rdc),
|
||||
Self::RegisterDataCur(rdcu) => fcu(rdcu),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,8 +186,8 @@ impl RegisterDataCompat {
|
||||
/// The id of the user key, which only the current format carries.
|
||||
fn key_id(&self) -> Option<KeyId> {
|
||||
match self {
|
||||
RegisterDataCompat::RegisterDataOld(_) => None,
|
||||
RegisterDataCompat::RegisterDataCur(rdcu) => rdcu.master_password_unlock.contained_key_id.clone(),
|
||||
Self::RegisterDataOld(_) => None,
|
||||
Self::RegisterDataCur(rdcu) => rdcu.master_password_unlock.contained_key_id.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,7 +299,7 @@ impl AccountKeysData {
|
||||
}
|
||||
if let Some(security_state) = &self.security_state {
|
||||
required(Some(security_state.security_state.clone()), "SecurityState")?;
|
||||
if security_state.security_state.encode_utf16().count() > 10_000 {
|
||||
if security_state.security_state.encode_utf16().nth(10_000).is_some() {
|
||||
err!("The field SecurityState must be a string with a maximum length of 10000.")
|
||||
}
|
||||
}
|
||||
@@ -709,7 +709,7 @@ async fn post_set_password(data: Json<Value>, headers: Headers, conn: DbConn) ->
|
||||
let Ok(data) = serde_json::from_value::<SetPasswordData>(data) else {
|
||||
err_code!("Unexpected SetPasswordData format", Status::UnprocessableEntity.code)
|
||||
};
|
||||
if data.master_password_hint.as_ref().is_some_and(|h| h.encode_utf16().count() > 50) {
|
||||
if data.master_password_hint.as_ref().is_some_and(|h| h.encode_utf16().nth(50).is_some()) {
|
||||
err!("The field MasterPasswordHint must be a string with a maximum length of 50.")
|
||||
}
|
||||
let mut user = headers.user;
|
||||
@@ -1373,7 +1373,6 @@ fn validate_rotation_data(
|
||||
existing_sends: &[Send],
|
||||
) -> EmptyResult {
|
||||
// Check that we're correctly rotating all the user's ciphers
|
||||
let existing_cipher_ids = existing_ciphers.iter().map(|c| &c.uuid).collect::<HashSet<&CipherId>>();
|
||||
let provided_cipher_ids = data
|
||||
.account_data
|
||||
.ciphers
|
||||
@@ -1381,44 +1380,38 @@ fn validate_rotation_data(
|
||||
.filter(|c| c.organization_id.is_none())
|
||||
.filter_map(|c| c.id.as_ref())
|
||||
.collect::<HashSet<&CipherId>>();
|
||||
if !provided_cipher_ids.is_superset(&existing_cipher_ids) {
|
||||
if existing_ciphers.iter().any(|c| !provided_cipher_ids.contains(&c.uuid)) {
|
||||
err!("All existing ciphers must be included in the rotation")
|
||||
}
|
||||
|
||||
// Check that we're correctly rotating all the user's folders
|
||||
let existing_folder_ids = existing_folders.iter().map(|f| &f.uuid).collect::<HashSet<&FolderId>>();
|
||||
let provided_folder_ids =
|
||||
data.account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>();
|
||||
if !provided_folder_ids.is_superset(&existing_folder_ids) {
|
||||
if existing_folders.iter().any(|f| !provided_folder_ids.contains(&f.uuid)) {
|
||||
err!("All existing folders must be included in the rotation")
|
||||
}
|
||||
|
||||
// Check that we're correctly rotating all the user's emergency access keys
|
||||
let existing_emergency_access_ids =
|
||||
existing_emergency_access.iter().map(|ea| &ea.uuid).collect::<HashSet<&EmergencyAccessId>>();
|
||||
let provided_emergency_access_ids =
|
||||
data.unlock_data.emergency_access_unlock_data.iter().map(|ea| &ea.id).collect::<HashSet<&EmergencyAccessId>>();
|
||||
if !provided_emergency_access_ids.is_superset(&existing_emergency_access_ids) {
|
||||
if existing_emergency_access.iter().any(|ea| !provided_emergency_access_ids.contains(&ea.uuid)) {
|
||||
err!("All existing emergency access keys must be included in the rotation")
|
||||
}
|
||||
|
||||
// Check that we're correctly rotating all the user's reset password keys
|
||||
let existing_reset_password_ids =
|
||||
existing_memberships.iter().map(|m| &m.org_uuid).collect::<HashSet<&OrganizationId>>();
|
||||
let provided_reset_password_ids = data
|
||||
.unlock_data
|
||||
.organization_account_recovery_unlock_data
|
||||
.iter()
|
||||
.map(|rp| &rp.organization_id)
|
||||
.collect::<HashSet<&OrganizationId>>();
|
||||
if !provided_reset_password_ids.is_superset(&existing_reset_password_ids) {
|
||||
if existing_memberships.iter().any(|m| !provided_reset_password_ids.contains(&m.org_uuid)) {
|
||||
err!("All existing reset password keys must be included in the rotation")
|
||||
}
|
||||
|
||||
// Check that we're correctly rotating all the user's sends
|
||||
let existing_send_ids = existing_sends.iter().map(|s| &s.uuid).collect::<HashSet<&SendId>>();
|
||||
let provided_send_ids = data.account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::<HashSet<&SendId>>();
|
||||
if !provided_send_ids.is_superset(&existing_send_ids) {
|
||||
if existing_sends.iter().any(|s| !provided_send_ids.contains(&s.uuid)) {
|
||||
err!("All existing sends must be included in the rotation")
|
||||
}
|
||||
|
||||
@@ -1503,7 +1496,7 @@ struct RotateData {
|
||||
|
||||
/// Upstream's `[StringLength(max)]`, which counts UTF-16 code units.
|
||||
fn validate_max_length(value: &str, max: usize, field: &str) -> EmptyResult {
|
||||
if value.encode_utf16().count() > max {
|
||||
if value.encode_utf16().nth(max).is_some() {
|
||||
err!(format!("The field {field} must be a string with a maximum length of {max}."))
|
||||
}
|
||||
Ok(())
|
||||
@@ -1544,7 +1537,7 @@ impl MasterPasswordUnlockData {
|
||||
if let Some(hint) = &self.master_password_hint {
|
||||
validate_max_length(hint, 50, "MasterPasswordHint")?;
|
||||
}
|
||||
if self.master_password_salt.as_ref().is_some_and(|salt| salt.encode_utf16().count() > 256) {
|
||||
if self.master_password_salt.as_ref().is_some_and(|salt| salt.encode_utf16().nth(256).is_some()) {
|
||||
err!("The field MasterPasswordSalt must be a string or array type with a maximum length of '256'.")
|
||||
}
|
||||
Ok(())
|
||||
@@ -2194,7 +2187,7 @@ async fn password_hint(data: Json<PasswordHintData>, ip: ClientIp, conn: DbConn)
|
||||
use rand::{RngExt, rngs::SmallRng};
|
||||
let mut rng: SmallRng = rand::make_rng();
|
||||
let sleep_ms: u64 = rng.random_range(900..=1100);
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(sleep_ms)).await;
|
||||
tokio::time::sleep(std::time::Duration::from_millis(sleep_ms)).await;
|
||||
Ok(())
|
||||
} else {
|
||||
err!(NO_HINT);
|
||||
@@ -2371,7 +2364,7 @@ impl<'r> FromRequest<'r> for KnownDevice {
|
||||
return Outcome::Error((Status::BadRequest, "X-Device-Identifier value is required"));
|
||||
};
|
||||
|
||||
Outcome::Success(KnownDevice {
|
||||
Outcome::Success(Self {
|
||||
email,
|
||||
uuid,
|
||||
})
|
||||
|
||||
+10
-18
@@ -1,7 +1,6 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use chrono::{NaiveDateTime, Utc};
|
||||
use num_traits::ToPrimitive;
|
||||
use rocket::{
|
||||
Route,
|
||||
form::{Form, FromForm},
|
||||
@@ -129,12 +128,10 @@ async fn sync(data: SyncData, headers: Headers, client_version: Option<ClientVer
|
||||
let mut ciphers = Cipher::find_by_user_visible(&headers.user.uuid, &conn).await;
|
||||
|
||||
// Filter out SSH keys if the client version is less than 2024.12.0
|
||||
let show_ssh_keys = if let Some(client_version) = client_version {
|
||||
let show_ssh_keys = client_version.is_some_and(|v| {
|
||||
let ver_match = semver::VersionReq::parse(">=2024.12.0").unwrap();
|
||||
ver_match.matches(&client_version.0)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
ver_match.matches(&v.0)
|
||||
});
|
||||
if !show_ssh_keys {
|
||||
ciphers.retain(|c| c.atype != 5);
|
||||
}
|
||||
@@ -287,7 +284,7 @@ async fn cipher_json_for_scope(
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CipherData {
|
||||
// Id is optional as it is included only in bulk share
|
||||
@@ -341,8 +338,7 @@ pub struct CipherData {
|
||||
pub password_history: Option<Value>,
|
||||
|
||||
// These are used during key rotation
|
||||
// 'Attachments' is unused, contains map of {id: filename}
|
||||
#[allow(dead_code)]
|
||||
#[cfg_attr(not(feature = "unsafe_test_mode"), expect(unused, reason = "Only read by the unsafe test seeder"))]
|
||||
attachments: Option<Value>,
|
||||
attachments2: Option<HashMap<AttachmentId, Attachments2Data>>,
|
||||
|
||||
@@ -553,7 +549,7 @@ async fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn, nt
|
||||
///
|
||||
/// Ref: https://bitwarden.com/help/article/policies/#personal-ownership
|
||||
async fn enforce_personal_ownership_policy(data: Option<&CipherData>, headers: &Headers, conn: &DbConn) -> EmptyResult {
|
||||
if data.is_none() || data.unwrap().organization_id.is_none() {
|
||||
if data.is_none_or(|d| d.organization_id.is_none()) {
|
||||
let user_id = &headers.user.uuid;
|
||||
let policy_type = OrgPolicyType::PersonalOwnership;
|
||||
if OrgPolicy::is_applicable_to_user(user_id, policy_type, None, conn).await {
|
||||
@@ -1382,7 +1378,7 @@ async fn put_cipher_share_selected(
|
||||
if data.ciphers.iter().any(|c| c.id.is_none() || c.organization_id.is_none()) {
|
||||
err!("All Ciphers must have an Id and OrganizationId.")
|
||||
}
|
||||
if data.ciphers.iter().map(|c| &c.organization_id).collect::<HashSet<_>>().len() != 1 {
|
||||
if data.ciphers.array_windows::<2>().any(|[a, b]| a.organization_id != b.organization_id) {
|
||||
err!("All ciphers must be for the same organization.")
|
||||
}
|
||||
if data.collection_ids.is_empty() {
|
||||
@@ -1744,7 +1740,7 @@ async fn save_attachment(
|
||||
) -> Result<(Cipher, DbConn), crate::error::Error> {
|
||||
let data = data.into_inner();
|
||||
|
||||
let Some(size) = data.data.len().to_i64() else {
|
||||
let Ok(size) = i64::try_from(data.data.len()) else {
|
||||
err!("Attachment data size overflow");
|
||||
};
|
||||
if size < 0 {
|
||||
@@ -1791,7 +1787,7 @@ async fn save_attachment(
|
||||
err!("Invalid attachment size min")
|
||||
};
|
||||
|
||||
if min_size <= size && size <= max_size {
|
||||
if (min_size..=max_size).contains(&size) {
|
||||
if size != attachment.file_size {
|
||||
// Update the attachment with the actual file size.
|
||||
attachment.file_size = size;
|
||||
@@ -1799,7 +1795,6 @@ async fn save_attachment(
|
||||
}
|
||||
} else {
|
||||
attachment.delete(&conn).await.ok();
|
||||
|
||||
err!(format!("Attachment size mismatch (expected within [{min_size}, {max_size}], got {size})"));
|
||||
}
|
||||
} else {
|
||||
@@ -2844,10 +2839,7 @@ mod custom_role_tests {
|
||||
use crate::{
|
||||
api::notifications::{WS_USERS, WebSocketUsers},
|
||||
auth::ClientIp,
|
||||
db::{
|
||||
models::{CustomPermission, Device, User},
|
||||
test_db,
|
||||
},
|
||||
db::{models::Device, test_db},
|
||||
};
|
||||
use chrono::Datelike;
|
||||
use diesel::connection::SimpleConnection;
|
||||
|
||||
@@ -793,8 +793,7 @@ fn is_valid_request(
|
||||
requesting_user_id: &UserId,
|
||||
requested_access_type: EmergencyAccessType,
|
||||
) -> bool {
|
||||
emergency_access.grantee_uuid.is_some()
|
||||
&& emergency_access.grantee_uuid.as_ref().unwrap() == requesting_user_id
|
||||
emergency_access.grantee_uuid.as_ref().is_some_and(|u| u == requesting_user_id)
|
||||
&& emergency_access.status == EmergencyAccessStatus::RecoveryApproved as i32
|
||||
&& emergency_access.atype == requested_access_type as i32
|
||||
}
|
||||
@@ -911,7 +910,7 @@ pub async fn emergency_notification_reminder_job(pool: DbPool) {
|
||||
};
|
||||
|
||||
// Only send reminders during the last 24 hours, else continue
|
||||
if now < final_reminder_at || now >= deadline_at {
|
||||
if !(final_reminder_at..deadline_at).contains(&now) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -140,12 +140,10 @@ fn get_continuation_token(events_json: &[Value]) -> Option<&str> {
|
||||
// When the length of the vec equals the max page_size there probably is more data
|
||||
// When it is less, then all events are loaded.
|
||||
#[expect(clippy::cast_possible_truncation, reason = "PAGE_SIZE fits within usize")]
|
||||
if events_json.len() == Event::PAGE_SIZE as usize {
|
||||
if let Some(last_event) = events_json.last() {
|
||||
last_event["date"].as_str()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
if events_json.len() == Event::PAGE_SIZE as usize
|
||||
&& let Some(last_event) = events_json.last()
|
||||
{
|
||||
last_event["date"].as_str()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -116,8 +116,8 @@ struct OrgData {
|
||||
key: String,
|
||||
name: String,
|
||||
keys: Option<OrgKeyData>,
|
||||
#[allow(dead_code)]
|
||||
plan_type: NumberOrString, // Ignored, always use the same plan
|
||||
#[expect(unused, reason = "Ignored, always use the same plan")]
|
||||
plan_type: NumberOrString,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
@@ -592,10 +592,11 @@ async fn post_bulk_access_collections(
|
||||
|
||||
// As in Bitwarden, missing, repeated or unmanageable collections are Not Found. Invalid groups and members are
|
||||
// checked after them and are a Bad Request.
|
||||
if data.collection_ids.is_empty()
|
||||
|| data.collection_ids.iter().collect::<HashSet<_>>().len() != data.collection_ids.len()
|
||||
{
|
||||
err_code!("One or more collections not found.", Status::NotFound.code)
|
||||
let mut seen = HashSet::new();
|
||||
if data.collection_ids.is_empty() || data.collection_ids.iter().any(|id| !seen.insert(id)) {
|
||||
err_code!("One or more collections not found.", Status::NotFound.code)
|
||||
}
|
||||
}
|
||||
|
||||
let mut collections = Vec::with_capacity(data.collection_ids.len());
|
||||
@@ -694,11 +695,7 @@ async fn put_organization_collection_update(
|
||||
};
|
||||
|
||||
collection.name = data.name;
|
||||
collection.external_id = match data.external_id {
|
||||
Some(external_id) if !external_id.trim().is_empty() => Some(external_id),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
collection.external_id = data.external_id.filter(|e| !e.trim().is_empty());
|
||||
collection.save(&conn).await?;
|
||||
|
||||
log_event(
|
||||
@@ -1317,7 +1314,7 @@ async fn send_invite(
|
||||
if Group::find_by_uuid_and_org(group_id, &org_id, &conn).await.is_none() {
|
||||
err!("Group not found in Organization")
|
||||
}
|
||||
let mut group_entry = GroupUser::new(group_id.clone(), new_member.uuid.clone());
|
||||
let group_entry = GroupUser::new(group_id.clone(), new_member.uuid.clone());
|
||||
group_entry.save(&conn).await?;
|
||||
}
|
||||
}
|
||||
@@ -1797,7 +1794,7 @@ async fn edit_member(
|
||||
if Group::find_by_uuid_and_org(group_id, &org_id, &conn).await.is_none() {
|
||||
err!("Group not found in Organization")
|
||||
}
|
||||
let mut group_entry = GroupUser::new(group_id.clone(), member_to_edit.uuid.clone());
|
||||
let group_entry = GroupUser::new(group_id.clone(), member_to_edit.uuid.clone());
|
||||
group_entry.save(&conn).await?;
|
||||
}
|
||||
|
||||
@@ -2279,13 +2276,7 @@ async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers
|
||||
};
|
||||
let user_collections: HashMap<CollectionId, Collection> = collections
|
||||
.into_iter()
|
||||
.filter_map(|c| {
|
||||
if data.collection_ids.contains(&c.uuid) {
|
||||
Some((c.uuid.clone(), c))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.filter_map(|c| data.collection_ids.contains(&c.uuid).then(|| (c.uuid.clone(), c)))
|
||||
.collect();
|
||||
|
||||
// Verify if all the collections requested exists and are writable for the user, else abort
|
||||
@@ -2396,10 +2387,9 @@ async fn get_policy(org_id: OrganizationId, pol_type: i32, headers: ManagePolici
|
||||
err!("Invalid or unsupported policy type")
|
||||
};
|
||||
|
||||
let policy = match OrgPolicy::find_by_org_and_type(&org_id, pol_type_enum, &conn).await {
|
||||
Some(p) => p,
|
||||
None => OrgPolicy::new(org_id.clone(), pol_type_enum, false, "null".to_owned()),
|
||||
};
|
||||
let policy = OrgPolicy::find_by_org_and_type(&org_id, pol_type_enum, &conn)
|
||||
.await
|
||||
.unwrap_or_else(|| OrgPolicy::new(org_id.clone(), pol_type_enum, false, "null".to_owned()));
|
||||
|
||||
Ok(Json(policy.to_json()))
|
||||
}
|
||||
@@ -2466,11 +2456,9 @@ async fn put_policy(
|
||||
// Maybe we want to enable this by default in the future, but currently it is disabled by default.
|
||||
if CONFIG.enforce_single_org_with_reset_pw_policy() {
|
||||
if pol_type_enum == OrgPolicyType::ResetPassword && data.enabled {
|
||||
let single_org_policy_enabled =
|
||||
match OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn).await {
|
||||
Some(p) => p.enabled,
|
||||
None => false,
|
||||
};
|
||||
let single_org_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn)
|
||||
.await
|
||||
.is_some_and(|p| p.enabled);
|
||||
|
||||
if !single_org_policy_enabled {
|
||||
err!("Single Organization policy is not enabled. It is mandatory for this policy to be enabled.")
|
||||
@@ -2479,11 +2467,9 @@ async fn put_policy(
|
||||
|
||||
// Also prevent the Single Org Policy to be disabled if the Reset Password policy is enabled
|
||||
if pol_type_enum == OrgPolicyType::SingleOrg && !data.enabled {
|
||||
let reset_pw_policy_enabled =
|
||||
match OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::ResetPassword, &conn).await {
|
||||
Some(p) => p.enabled,
|
||||
None => false,
|
||||
};
|
||||
let reset_pw_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::ResetPassword, &conn)
|
||||
.await
|
||||
.is_some_and(|p| p.enabled);
|
||||
|
||||
if reset_pw_policy_enabled {
|
||||
err!("Account recovery policy is enabled. It is not allowed to disable this policy.")
|
||||
@@ -3097,12 +3083,12 @@ async fn add_update_group(
|
||||
group.save(conn).await?;
|
||||
|
||||
for col_selection in collections {
|
||||
let mut collection_group = col_selection.to_collection_group(group.uuid.clone());
|
||||
let collection_group = col_selection.to_collection_group(group.uuid.clone());
|
||||
collection_group.save(&org_id, conn).await?;
|
||||
}
|
||||
|
||||
for assigned_member in members {
|
||||
let mut user_entry = GroupUser::new(group.uuid.clone(), assigned_member.clone());
|
||||
let user_entry = GroupUser::new(group.uuid.clone(), assigned_member.clone());
|
||||
user_entry.save(conn).await?;
|
||||
|
||||
log_event(
|
||||
@@ -3251,8 +3237,8 @@ async fn get_group_members(
|
||||
|
||||
let group_members: Vec<MembershipId> = GroupUser::find_by_group(&group_id, &org_id, &conn)
|
||||
.await
|
||||
.iter()
|
||||
.map(|entry| entry.users_organizations_uuid.clone())
|
||||
.into_iter()
|
||||
.map(|entry| entry.users_organizations_uuid)
|
||||
.collect();
|
||||
|
||||
Ok(Json(json!(group_members)))
|
||||
@@ -3731,12 +3717,7 @@ async fn put_reset_password_enrollment(
|
||||
|
||||
let reset_request = data.into_inner();
|
||||
|
||||
let reset_password_key = match reset_request.reset_password_key {
|
||||
None => None,
|
||||
Some(ref key) if key.is_empty() => None,
|
||||
Some(key) => Some(key),
|
||||
};
|
||||
|
||||
let reset_password_key = reset_request.reset_password_key.filter(|k| !k.is_empty());
|
||||
if reset_password_key.is_none() && OrgPolicy::org_is_reset_password_auto_enroll(&org_id, &conn).await {
|
||||
err!("Reset password can't be withdrawn due to an enterprise policy");
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ async fn ldap_import(data: Json<OrgImportData>, token: PublicToken, conn: DbConn
|
||||
|
||||
for ext_id in &group_data.member_external_ids {
|
||||
if let Some(member) = Membership::find_by_external_id_and_org(ext_id, &org_id, &conn).await {
|
||||
let mut group_user = GroupUser::new(group_uuid.clone(), member.uuid.clone());
|
||||
let group_user = GroupUser::new(group_uuid.clone(), member.uuid.clone());
|
||||
group_user.save(&conn).await?;
|
||||
}
|
||||
}
|
||||
@@ -237,6 +237,6 @@ impl<'r> FromRequest<'r> for PublicToken {
|
||||
err_handler!("Token not issued for this client");
|
||||
}
|
||||
|
||||
Outcome::Success(PublicToken(claims.client_sub))
|
||||
Outcome::Success(Self(claims.client_sub))
|
||||
}
|
||||
}
|
||||
+4
-14
@@ -1,7 +1,6 @@
|
||||
use std::{path::Path, sync::LazyLock, time::Duration};
|
||||
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use num_traits::ToPrimitive;
|
||||
use rocket::{
|
||||
form::Form,
|
||||
fs::{NamedFile, TempFile},
|
||||
@@ -172,10 +171,7 @@ fn create_send(data: SendData, user_id: UserId) -> ApiResult<Send> {
|
||||
let mut send = Send::new(data.r#type, data.name, data_str, data.key, data.deletion_date.naive_utc());
|
||||
send.user_uuid = Some(user_id);
|
||||
send.notes = data.notes;
|
||||
send.max_access_count = match data.max_access_count {
|
||||
Some(m) => Some(m.into_i32()?),
|
||||
_ => None,
|
||||
};
|
||||
send.max_access_count = data.max_access_count.map(|m| m.into_i32()).transpose()?;
|
||||
send.expiration_date = data.expiration_date.map(|d| d.naive_utc());
|
||||
send.disabled = data.disabled;
|
||||
send.hide_email = data.hide_email;
|
||||
@@ -303,7 +299,7 @@ async fn post_send_file_v2(data: Json<SendData>, headers: Headers, conn: DbConn)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(non_snake_case)]
|
||||
#[expect(non_snake_case, reason = "Bitwarden clients use this format")]
|
||||
pub struct SendFileData {
|
||||
id: SendFileId,
|
||||
size: u64,
|
||||
@@ -357,10 +353,7 @@ async fn post_send_file_v2_data(
|
||||
err!("Send file does not match send data.", format!("Expected id {} got {file_id}", send_data.id));
|
||||
}
|
||||
|
||||
let Some(size) = data.data.len().to_u64() else {
|
||||
err!("Send file size overflow.");
|
||||
};
|
||||
|
||||
let size = data.data.len();
|
||||
if size != send_data.size {
|
||||
err!("Send file size does not match.", format!("Expected a file size of {} got {size}", send_data.size));
|
||||
}
|
||||
@@ -538,10 +531,7 @@ async fn update_send_from_data(
|
||||
send.akey = data.key;
|
||||
send.deletion_date = data.deletion_date.naive_utc();
|
||||
send.notes = data.notes;
|
||||
send.max_access_count = match data.max_access_count {
|
||||
Some(m) => Some(m.into_i32()?),
|
||||
_ => None,
|
||||
};
|
||||
send.max_access_count = data.max_access_count.map(|m| m.into_i32()).transpose()?;
|
||||
send.expiration_date = data.expiration_date.map(|d| d.naive_utc());
|
||||
send.hide_email = data.hide_email;
|
||||
send.disabled = data.disabled;
|
||||
|
||||
@@ -116,10 +116,9 @@ pub async fn validate_totp_code(
|
||||
err!("Invalid TOTP secret")
|
||||
};
|
||||
|
||||
let mut twofactor = match TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Authenticator, conn).await {
|
||||
Some(tf) => tf,
|
||||
_ => TwoFactor::new(user_id.clone(), TwoFactorType::Authenticator, secret.to_owned()),
|
||||
};
|
||||
let mut twofactor = TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Authenticator, conn)
|
||||
.await
|
||||
.unwrap_or_else(|| TwoFactor::new(user_id.clone(), TwoFactorType::Authenticator, secret.to_owned()));
|
||||
|
||||
// The amount of steps back and forward in time
|
||||
// Also check if we need to disable time drifted TOTP codes.
|
||||
|
||||
@@ -32,8 +32,8 @@ enum DuoStatus {
|
||||
impl DuoStatus {
|
||||
fn data(self) -> Option<DuoData> {
|
||||
match self {
|
||||
DuoStatus::Global(data) | DuoStatus::User(data) => Some(data),
|
||||
DuoStatus::Disabled(_) => None,
|
||||
Self::Global(data) | Self::User(data) => Some(data),
|
||||
Self::Disabled(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,8 +108,8 @@ struct DuoClient {
|
||||
|
||||
impl DuoClient {
|
||||
// Construct a new DuoClient
|
||||
fn new(client_id: String, client_secret: String, api_host: String, redirect_uri: String) -> DuoClient {
|
||||
DuoClient {
|
||||
fn new(client_id: String, client_secret: String, api_host: String, redirect_uri: String) -> Self {
|
||||
Self {
|
||||
client_id,
|
||||
client_secret,
|
||||
api_host,
|
||||
@@ -137,7 +137,7 @@ impl DuoClient {
|
||||
match jsonwebtoken::encode(
|
||||
&Header::new(JWT_SIGNATURE_ALG),
|
||||
&jwt_payload,
|
||||
&EncodingKey::from_secret(self.client_secret.as_bytes()),
|
||||
&EncodingKey::from_secret(self.client_secret.as_bytes())?,
|
||||
) {
|
||||
Ok(token) => Ok(token),
|
||||
Err(e) => err!(format!("Error encoding Duo JWT: {e:?}")),
|
||||
@@ -157,10 +157,7 @@ impl DuoClient {
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
let mut post_body = HashMap::new();
|
||||
post_body.insert("client_assertion", token);
|
||||
post_body.insert("client_id", self.client_id.clone());
|
||||
|
||||
let post_body = HashMap::from([("client_assertion", token), ("client_id", self.client_id.clone())]);
|
||||
let res = match make_http_request(reqwest::Method::POST, &health_check_url)?
|
||||
.header(header::USER_AGENT, "vaultwarden:Duo/2.0 (Rust)")
|
||||
.form(&post_body)
|
||||
@@ -253,16 +250,14 @@ impl DuoClient {
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
let mut post_body = HashMap::new();
|
||||
post_body.insert("grant_type", String::from("authorization_code"));
|
||||
post_body.insert("code", String::from(duo_code));
|
||||
|
||||
// Must be the same URL that was supplied in the authorization request for the supplied duo_code
|
||||
post_body.insert("redirect_uri", self.redirect_uri.clone());
|
||||
|
||||
post_body
|
||||
.insert("client_assertion_type", String::from("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
|
||||
post_body.insert("client_assertion", token);
|
||||
let post_body = HashMap::from([
|
||||
("grant_type", String::from("authorization_code")),
|
||||
("code", String::from(duo_code)),
|
||||
// Must be the same URL that was supplied in the authorization request for the supplied duo_code
|
||||
("redirect_uri", self.redirect_uri.clone()),
|
||||
("client_assertion_type", String::from("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")),
|
||||
("client_assertion", token),
|
||||
]);
|
||||
|
||||
let res = match make_http_request(reqwest::Method::POST, &token_url)?
|
||||
.header(header::USER_AGENT, "vaultwarden:Duo/2.0 (Rust)")
|
||||
@@ -291,7 +286,7 @@ impl DuoClient {
|
||||
|
||||
let token_data = match jsonwebtoken::decode::<IdTokenClaims>(
|
||||
&response.id_token,
|
||||
&DecodingKey::from_secret(self.client_secret.as_bytes()),
|
||||
&DecodingKey::from_secret(self.client_secret.as_bytes())?,
|
||||
&validation,
|
||||
) {
|
||||
Ok(c) => c,
|
||||
@@ -422,18 +417,14 @@ pub async fn validate_duo_login(
|
||||
conn: &DbConn,
|
||||
) -> EmptyResult {
|
||||
// Result supplied to us by clients in the form "<authz code>|<state>"
|
||||
let split: Vec<&str> = two_factor_token.split('|').collect();
|
||||
if split.len() != 2 {
|
||||
let Some((code, state)) = two_factor_token.split_once('|').filter(|(_, state)| !state.contains('|')) else {
|
||||
err!(
|
||||
"Invalid response length",
|
||||
ErrorEvent {
|
||||
event: EventType::UserFailedLogIn2fa
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let code = split[0];
|
||||
let state = split[1];
|
||||
};
|
||||
|
||||
let (ik, sk, host) = get_duo_keys_email(email, conn).await?;
|
||||
|
||||
|
||||
@@ -54,18 +54,9 @@ async fn send_email_login(data: Json<SendEmailLoginData>, client_headers: Client
|
||||
crate::ratelimit::check_limit_login(&client_headers.ip.ip)?;
|
||||
|
||||
// Get the user
|
||||
let email = match &data.email {
|
||||
Some(email) if !email.is_empty() => Some(email),
|
||||
_ => None,
|
||||
};
|
||||
let master_password_hash = match &data.master_password_hash {
|
||||
Some(password_hash) if !password_hash.is_empty() => Some(password_hash),
|
||||
_ => None,
|
||||
};
|
||||
let auth_request_id = match &data.auth_request_id {
|
||||
Some(auth_request_id) if !auth_request_id.is_empty() => Some(auth_request_id),
|
||||
_ => None,
|
||||
};
|
||||
let email = data.email.as_ref().filter(|e| !e.is_empty());
|
||||
let master_password_hash = data.master_password_hash.as_ref().filter(|h| !h.is_empty());
|
||||
let auth_request_id = data.auth_request_id.as_ref().filter(|a| !a.is_empty());
|
||||
|
||||
let user = if let Some(email) = email {
|
||||
let Some(user) = User::find_by_mail(email, &conn).await else {
|
||||
@@ -349,8 +340,8 @@ pub struct EmailTokenData {
|
||||
}
|
||||
|
||||
impl EmailTokenData {
|
||||
pub fn new(email: String, token: Option<String>) -> EmailTokenData {
|
||||
EmailTokenData {
|
||||
pub fn new(email: String, token: Option<String>) -> Self {
|
||||
Self {
|
||||
email,
|
||||
last_token: token,
|
||||
token_sent: Utc::now().timestamp(),
|
||||
@@ -376,8 +367,8 @@ impl EmailTokenData {
|
||||
serde_json::to_string(&self).unwrap()
|
||||
}
|
||||
|
||||
pub fn from_json(string: &str) -> Result<EmailTokenData, Error> {
|
||||
let res: Result<EmailTokenData, serde_json::Error> = serde_json::from_str(string);
|
||||
pub fn from_json(string: &str) -> Result<Self, Error> {
|
||||
let res: Result<Self, serde_json::Error> = serde_json::from_str(string);
|
||||
if let Ok(x) = res {
|
||||
Ok(x)
|
||||
} else {
|
||||
@@ -398,22 +389,21 @@ pub async fn activate_email_2fa(user: &User, conn: &DbConn) -> EmptyResult {
|
||||
|
||||
/// Takes an email address and obscures it by replacing it with asterisks except two characters.
|
||||
pub fn obscure_email(email: &str) -> String {
|
||||
let split: Vec<&str> = email.rsplitn(2, '@').collect();
|
||||
|
||||
let mut name = split[1].to_owned();
|
||||
let domain = &split[0];
|
||||
|
||||
let name_size = name.chars().count();
|
||||
|
||||
let new_name = if let 1..=3 = name_size {
|
||||
"*".repeat(name_size)
|
||||
} else {
|
||||
let stars = "*".repeat(name_size - 2);
|
||||
name.truncate(2);
|
||||
format!("{name}{stars}")
|
||||
let Some((name, domain)) = email.rsplit_once('@') else {
|
||||
return "*".repeat(email.chars().count());
|
||||
};
|
||||
|
||||
format!("{new_name}@{domain}")
|
||||
let len = name.chars().count();
|
||||
let keep = if len > 3 {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
// Byte offset after the first `keep` chars (UTF-8 safe).
|
||||
let end = name.char_indices().nth(keep).map_or(name.len(), |(i, _)| i);
|
||||
|
||||
format!("{}{}@{domain}", &name[..end], "*".repeat(len - keep))
|
||||
}
|
||||
|
||||
pub async fn find_and_activate_email_2fa(user_id: &UserId, conn: &DbConn) -> EmptyResult {
|
||||
@@ -431,7 +421,6 @@ mod tests {
|
||||
#[test]
|
||||
fn test_obscure_email_long() {
|
||||
let email = "bytes@example.ext";
|
||||
|
||||
let result = obscure_email(email);
|
||||
|
||||
// Only first two characters should be visible.
|
||||
@@ -441,10 +430,37 @@ mod tests {
|
||||
#[test]
|
||||
fn test_obscure_email_short() {
|
||||
let email = "byt@example.ext";
|
||||
|
||||
let result = obscure_email(email);
|
||||
|
||||
// If it's smaller than 3 characters it should only show asterisks.
|
||||
assert_eq!(result, "***@example.ext");
|
||||
}
|
||||
|
||||
// Test unicode email address, as that might cut a unicode char in half and cause a panic
|
||||
#[test]
|
||||
fn test_obscure_email_unicode_long() {
|
||||
let email = "bɏtes@example.ext";
|
||||
let result = obscure_email(email);
|
||||
|
||||
// Only first two characters should be visible.
|
||||
assert_eq!(result, "bɏ***@example.ext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_obscure_email_unicode_short() {
|
||||
let email = "bɏt@example.ext";
|
||||
let result = obscure_email(email);
|
||||
|
||||
// If it's smaller than 3 characters it should only show asterisks.
|
||||
assert_eq!(result, "***@example.ext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_missing_at() {
|
||||
let email = "bɏt_at_example.ext";
|
||||
let result = obscure_email(email);
|
||||
|
||||
// With a missing `@` the whole string should show asterisks
|
||||
assert_eq!(result, "******************");
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ use crate::{
|
||||
static WEBAUTHN: LazyLock<Webauthn> = LazyLock::new(|| {
|
||||
let domain = CONFIG.domain();
|
||||
let domain_origin = CONFIG.domain_origin();
|
||||
let rp_id = Url::parse(&domain).map(|u| u.domain().map(str::to_owned)).ok().flatten().unwrap_or_default();
|
||||
let rp_id = Url::parse(&domain).map_or_default(|u| u.domain().map_or_default(str::to_owned));
|
||||
let rp_origin = Url::parse(&domain_origin).unwrap();
|
||||
|
||||
let webauthn = WebauthnBuilder::new(&rp_id, &rp_origin)
|
||||
@@ -355,13 +355,9 @@ async fn inner_delete_webauthns(
|
||||
let mut removed: HashSet<Vec<u8>> = HashSet::new();
|
||||
let mut migrated = false;
|
||||
|
||||
keys.retain(|key| {
|
||||
let retained = retain(key);
|
||||
if !retained {
|
||||
removed.insert(key.credential.cred_id().to_vec());
|
||||
migrated = migrated || key.migrated;
|
||||
}
|
||||
retained
|
||||
keys.extract_if(.., |key| !retain(key)).for_each(|key| {
|
||||
removed.insert(key.credential.cred_id().to_vec());
|
||||
migrated |= key.migrated;
|
||||
});
|
||||
|
||||
if removed.is_empty() {
|
||||
|
||||
Reference in new issue
Block a user