mirror of
https://github.com/dani-garcia/vaultwarden.wiki.git
synced 2026-11-23 17:49:40 +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
+17
-11
@@ -1,7 +1,6 @@
|
||||
mod query_logger;
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
sync::{
|
||||
Arc, OnceLock,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
@@ -237,7 +236,7 @@ impl DbPool {
|
||||
error!("Tried to set the active database connection type more than once.");
|
||||
}
|
||||
|
||||
Ok(DbPool {
|
||||
Ok(Self {
|
||||
pool: Some(pool),
|
||||
semaphore: Arc::new(Semaphore::new(max_conns as usize)),
|
||||
})
|
||||
@@ -268,25 +267,25 @@ impl DbPool {
|
||||
impl DbConnType {
|
||||
pub fn from_url(url: &str) -> Result<Self, Error> {
|
||||
// Mysql
|
||||
if url.len() > 6 && &url[..6] == "mysql:" {
|
||||
if url.starts_with("mysql:") {
|
||||
#[cfg(mysql)]
|
||||
return Ok(DbConnType::Mysql);
|
||||
return Ok(Self::Mysql);
|
||||
|
||||
#[cfg(not(mysql))]
|
||||
err!("`DATABASE_URL` is a MySQL URL, but the 'mysql' feature is not enabled")
|
||||
|
||||
// Postgresql
|
||||
} else if url.len() > 11 && (&url[..11] == "postgresql:" || &url[..9] == "postgres:") {
|
||||
} else if url.starts_with("postgresql:") || url.starts_with("postgres:") {
|
||||
#[cfg(postgresql)]
|
||||
return Ok(DbConnType::Postgresql);
|
||||
return Ok(Self::Postgresql);
|
||||
|
||||
#[cfg(not(postgresql))]
|
||||
err!("`DATABASE_URL` is a PostgreSQL URL, but the 'postgresql' feature is not enabled")
|
||||
|
||||
// Sqlite (explicit)
|
||||
} else if url.len() > 7 && &url[..7] == "sqlite:" {
|
||||
} else if url.starts_with("sqlite:") {
|
||||
#[cfg(sqlite)]
|
||||
return Ok(DbConnType::Sqlite);
|
||||
return Ok(Self::Sqlite);
|
||||
|
||||
#[cfg(not(sqlite))]
|
||||
err!("`DATABASE_URL` is a SQLite URL, but the 'sqlite' feature is not enabled")
|
||||
@@ -297,7 +296,7 @@ impl DbConnType {
|
||||
#[cfg(sqlite)]
|
||||
{
|
||||
if std::path::Path::new(url).exists() {
|
||||
return Ok(DbConnType::Sqlite);
|
||||
return Ok(Self::Sqlite);
|
||||
}
|
||||
err!(format!(
|
||||
"`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://) \
|
||||
@@ -438,8 +437,6 @@ pub mod models;
|
||||
/// MySQL/MariaDB and PostgreSQL are not supported.
|
||||
#[cfg(sqlite)]
|
||||
pub fn backup_sqlite() -> Result<String, Error> {
|
||||
use diesel::Connection;
|
||||
|
||||
let db_url = CONFIG.database_url();
|
||||
if DbConnType::from_url(&CONFIG.database_url()).is_ok_and(|t| t == DbConnType::Sqlite) {
|
||||
// Strip the sqlite:// prefix if present to get the raw file path
|
||||
@@ -614,6 +611,15 @@ pub mod test_db {
|
||||
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
|
||||
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
|
||||
.env("DATABASE_URL", "sqlite://:memory:")
|
||||
// Keep a local `.env` out of the tests, such as SMTP settings that would send mail
|
||||
.env(
|
||||
"ENV_FILE",
|
||||
if cfg!(windows) {
|
||||
"NUL"
|
||||
} else {
|
||||
"/dev/null"
|
||||
},
|
||||
)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
|
||||
@@ -146,7 +146,7 @@ impl Attachment {
|
||||
}
|
||||
|
||||
pub async fn delete_all_by_cipher(cipher_uuid: &CipherId, conn: &DbConn) -> EmptyResult {
|
||||
for attachment in Attachment::find_by_cipher(cipher_uuid, conn).await {
|
||||
for attachment in Self::find_by_cipher(cipher_uuid, conn).await {
|
||||
attachment.delete(conn).await?;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
+19
-27
@@ -97,8 +97,8 @@ impl CipherAccessScope {
|
||||
/// Whether `member` reaches every cipher of their organization with this access.
|
||||
fn reaches_all_ciphers(self, member: &Membership) -> bool {
|
||||
match self {
|
||||
CipherAccessScope::User => member.has_full_access(),
|
||||
CipherAccessScope::OrganizationAdmin => member.can_edit_any_collection(),
|
||||
Self::User => member.has_full_access(),
|
||||
Self::OrganizationAdmin => member.can_edit_any_collection(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,18 +106,18 @@ impl CipherAccessScope {
|
||||
/// administrative one still needs a member who may edit any collection.
|
||||
pub fn requested(admin_request: Option<bool>) -> Self {
|
||||
if admin_request == Some(true) {
|
||||
CipherAccessScope::OrganizationAdmin
|
||||
Self::OrganizationAdmin
|
||||
} else {
|
||||
CipherAccessScope::User
|
||||
Self::User
|
||||
}
|
||||
}
|
||||
|
||||
/// The access for a route that does not tell which one it is, from the member's own membership.
|
||||
pub fn for_member(member: Option<&Membership>) -> Self {
|
||||
if member.is_some_and(Membership::can_edit_any_collection) {
|
||||
CipherAccessScope::OrganizationAdmin
|
||||
Self::OrganizationAdmin
|
||||
} else {
|
||||
CipherAccessScope::User
|
||||
Self::User
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -306,7 +306,7 @@ impl Cipher {
|
||||
.inspect_err(|e| warn!("Error parsing fields {e:?} for {}", self.uuid))
|
||||
.ok()
|
||||
})
|
||||
.map(|d| {
|
||||
.map_or_default(|d| {
|
||||
d.into_iter()
|
||||
.map(|mut f| {
|
||||
// Check if the `type` key is a number, strings break some clients
|
||||
@@ -326,8 +326,7 @@ impl Cipher {
|
||||
f.data
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
});
|
||||
|
||||
let password_history_json: Vec<_> = self
|
||||
.password_history
|
||||
@@ -337,7 +336,7 @@ impl Cipher {
|
||||
.inspect_err(|e| warn!("Error parsing password history {e:?} for {}", self.uuid))
|
||||
.ok()
|
||||
})
|
||||
.map(|d| {
|
||||
.map_or_default(|d| {
|
||||
// Check every password history item if they are valid and return it.
|
||||
// If a password field has the type `null` skip it, it breaks newer Bitwarden clients
|
||||
// A second check is done to verify the lastUsedDate exists and is a valid DateTime string, if not the epoch start time will be used
|
||||
@@ -356,19 +355,14 @@ impl Cipher {
|
||||
d
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
});
|
||||
|
||||
// Like upstream, fields and password history stored as NULL are sent as null, not `[]`
|
||||
let fields_json = self.fields.is_some().then_some(fields_json);
|
||||
let password_history_json = self.password_history.is_some().then_some(password_history_json);
|
||||
|
||||
let collection_ids = if let Some(cipher_sync_data) = cipher_sync_data {
|
||||
if let Some(cipher_collections) = cipher_sync_data.cipher_collections.get(&self.uuid) {
|
||||
Cow::from(cipher_collections)
|
||||
} else {
|
||||
Cow::from(Vec::new())
|
||||
}
|
||||
cipher_sync_data.cipher_collections.get(&self.uuid).map_or_default(Cow::from)
|
||||
} else {
|
||||
Cow::from(self.get_admin_collections(user_uuid.clone(), scope, conn).await)
|
||||
};
|
||||
@@ -688,7 +682,7 @@ impl Cipher {
|
||||
|
||||
/// Returns whether this cipher is directly owned by the user.
|
||||
pub fn is_owned_by_user(&self, user_uuid: &UserId) -> bool {
|
||||
self.user_uuid.is_some() && self.user_uuid.as_ref().unwrap() == user_uuid
|
||||
self.user_uuid.as_ref().is_some_and(|u| u == user_uuid)
|
||||
}
|
||||
|
||||
/// Returns whether this cipher is owned by an org in which the user reaches every cipher with `scope`.
|
||||
@@ -875,10 +869,9 @@ impl Cipher {
|
||||
scope: CipherAccessScope,
|
||||
conn: &DbConn,
|
||||
) -> bool {
|
||||
match self.get_access_restrictions(user_uuid, scope, None, conn).await {
|
||||
Some((read_only, _hide_passwords, manage)) => !read_only || manage,
|
||||
None => false,
|
||||
}
|
||||
self.get_access_restrictions(user_uuid, scope, None, conn)
|
||||
.await
|
||||
.is_some_and(|(read_only, _hide_passwords, manage)| !read_only || manage)
|
||||
}
|
||||
|
||||
// used for checking if collection can be edited (only if user has access to a collection they
|
||||
@@ -889,10 +882,9 @@ impl Cipher {
|
||||
scope: CipherAccessScope,
|
||||
conn: &DbConn,
|
||||
) -> bool {
|
||||
match self.get_access_restrictions(user_uuid, scope, None, conn).await {
|
||||
Some((read_only, hide_passwords, manage)) => (!read_only && !hide_passwords) || manage,
|
||||
None => false,
|
||||
}
|
||||
self.get_access_restrictions(user_uuid, scope, None, conn)
|
||||
.await
|
||||
.is_some_and(|(read_only, hide_passwords, manage)| (!read_only && !hide_passwords) || manage)
|
||||
}
|
||||
|
||||
pub async fn is_accessible_to_user(&self, user_uuid: &UserId, scope: CipherAccessScope, conn: &DbConn) -> bool {
|
||||
@@ -1373,7 +1365,7 @@ impl Cipher {
|
||||
return (assigned, Vec::new());
|
||||
}
|
||||
|
||||
let listed: HashSet<CipherId> = assigned.iter().map(|cipher| cipher.uuid.clone()).collect();
|
||||
let listed: HashSet<&CipherId> = assigned.iter().map(|cipher| &cipher.uuid).collect();
|
||||
let in_collections: HashSet<CipherId> =
|
||||
Self::get_collections_with_cipher_by_organization(&member.org_uuid, conn)
|
||||
.await
|
||||
|
||||
@@ -82,18 +82,8 @@ impl Collection {
|
||||
}
|
||||
|
||||
pub fn set_external_id(&mut self, external_id: Option<String>) {
|
||||
//Check if external id is empty. We don't want to have
|
||||
//empty strings in the database
|
||||
match external_id {
|
||||
Some(external_id) => {
|
||||
if external_id.is_empty() {
|
||||
self.external_id = None;
|
||||
} else {
|
||||
self.external_id = Some(external_id);
|
||||
}
|
||||
}
|
||||
None => self.external_id = None,
|
||||
}
|
||||
// Check if external id is empty. We don't want to have empty strings in the database
|
||||
self.external_id = external_id.filter(|e| !e.trim().is_empty());
|
||||
}
|
||||
|
||||
pub async fn to_json_details(
|
||||
@@ -878,7 +868,7 @@ impl CollectionUser {
|
||||
}
|
||||
|
||||
pub async fn delete_all_by_collection(collection_uuid: &CollectionId, conn: &DbConn) -> EmptyResult {
|
||||
for collection in &CollectionUser::find_by_collection(collection_uuid, conn).await {
|
||||
for collection in &Self::find_by_collection(collection_uuid, conn).await {
|
||||
User::update_uuid_revision(&collection.user_uuid, conn).await;
|
||||
}
|
||||
|
||||
|
||||
+31
-31
@@ -51,7 +51,7 @@ impl Device {
|
||||
|
||||
push_uuid: Some(PushId(get_uuid())),
|
||||
push_token: None,
|
||||
refresh_token: Device::generate_refresh_token(),
|
||||
refresh_token: Self::generate_refresh_token(),
|
||||
twofactor_remember: None,
|
||||
}
|
||||
}
|
||||
@@ -268,7 +268,7 @@ impl Device {
|
||||
// We cannot do a single UPDATE with one value because each device needs a unique token.
|
||||
let devices = Self::find_by_user(user_uuid, conn).await;
|
||||
for mut device in devices {
|
||||
device.refresh_token = Device::generate_refresh_token();
|
||||
device.refresh_token = Self::generate_refresh_token();
|
||||
device.twofactor_remember = None;
|
||||
device.save(false, conn).await?;
|
||||
}
|
||||
@@ -347,36 +347,36 @@ pub enum DeviceType {
|
||||
|
||||
impl DeviceType {
|
||||
#[expect(clippy::match_same_arms, reason = "Specifically define 14 and have a fallback for new types")]
|
||||
pub fn from_i32(value: i32) -> DeviceType {
|
||||
pub fn from_i32(value: i32) -> Self {
|
||||
match value {
|
||||
0 => DeviceType::Android,
|
||||
1 => DeviceType::Ios,
|
||||
2 => DeviceType::ChromeExtension,
|
||||
3 => DeviceType::FirefoxExtension,
|
||||
4 => DeviceType::OperaExtension,
|
||||
5 => DeviceType::EdgeExtension,
|
||||
6 => DeviceType::WindowsDesktop,
|
||||
7 => DeviceType::MacOsDesktop,
|
||||
8 => DeviceType::LinuxDesktop,
|
||||
9 => DeviceType::ChromeBrowser,
|
||||
10 => DeviceType::FirefoxBrowser,
|
||||
11 => DeviceType::OperaBrowser,
|
||||
12 => DeviceType::EdgeBrowser,
|
||||
13 => DeviceType::IEBrowser,
|
||||
14 => DeviceType::UnknownBrowser,
|
||||
15 => DeviceType::AndroidAmazon,
|
||||
16 => DeviceType::Uwp,
|
||||
17 => DeviceType::SafariBrowser,
|
||||
18 => DeviceType::VivaldiBrowser,
|
||||
19 => DeviceType::VivaldiExtension,
|
||||
20 => DeviceType::SafariExtension,
|
||||
21 => DeviceType::Sdk,
|
||||
22 => DeviceType::Server,
|
||||
23 => DeviceType::WindowsCLI,
|
||||
24 => DeviceType::MacOsCLI,
|
||||
25 => DeviceType::LinuxCLI,
|
||||
26 => DeviceType::DuckDuckGoBrowser,
|
||||
_ => DeviceType::UnknownBrowser,
|
||||
0 => Self::Android,
|
||||
1 => Self::Ios,
|
||||
2 => Self::ChromeExtension,
|
||||
3 => Self::FirefoxExtension,
|
||||
4 => Self::OperaExtension,
|
||||
5 => Self::EdgeExtension,
|
||||
6 => Self::WindowsDesktop,
|
||||
7 => Self::MacOsDesktop,
|
||||
8 => Self::LinuxDesktop,
|
||||
9 => Self::ChromeBrowser,
|
||||
10 => Self::FirefoxBrowser,
|
||||
11 => Self::OperaBrowser,
|
||||
12 => Self::EdgeBrowser,
|
||||
13 => Self::IEBrowser,
|
||||
14 => Self::UnknownBrowser,
|
||||
15 => Self::AndroidAmazon,
|
||||
16 => Self::Uwp,
|
||||
17 => Self::SafariBrowser,
|
||||
18 => Self::VivaldiBrowser,
|
||||
19 => Self::VivaldiExtension,
|
||||
20 => Self::SafariExtension,
|
||||
21 => Self::Sdk,
|
||||
22 => Self::Server,
|
||||
23 => Self::WindowsCLI,
|
||||
24 => Self::MacOsCLI,
|
||||
25 => Self::LinuxCLI,
|
||||
26 => Self::DuckDuckGoBrowser,
|
||||
_ => Self::UnknownBrowser,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,8 +141,8 @@ pub enum EmergencyAccessType {
|
||||
impl EmergencyAccessType {
|
||||
pub fn from_str(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"0" | "View" => Some(EmergencyAccessType::View),
|
||||
"1" | "Takeover" => Some(EmergencyAccessType::Takeover),
|
||||
"0" | "View" => Some(Self::View),
|
||||
"1" | "Takeover" => Some(Self::Takeover),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -397,7 +397,7 @@ impl EmergencyAccess {
|
||||
}
|
||||
|
||||
pub async fn accept_invite(&mut self, grantee_uuid: &UserId, grantee_email: &str, conn: &DbConn) -> EmptyResult {
|
||||
if self.email.is_none() || self.email.as_ref().unwrap() != grantee_email {
|
||||
if self.email.as_ref().is_none_or(|e| e != grantee_email) {
|
||||
err!("User email does not match invite.");
|
||||
}
|
||||
|
||||
|
||||
@@ -151,11 +151,7 @@ pub enum EventType {
|
||||
/// Local methods
|
||||
impl Event {
|
||||
pub fn new(event_type: i32, event_date: Option<NaiveDateTime>) -> Self {
|
||||
let event_date = match event_date {
|
||||
Some(d) => d,
|
||||
None => Utc::now().naive_utc(),
|
||||
};
|
||||
|
||||
let event_date = event_date.unwrap_or_else(|| Utc::now().naive_utc());
|
||||
Self {
|
||||
uuid: EventId(crate::util::get_uuid()),
|
||||
event_type,
|
||||
@@ -230,7 +226,7 @@ impl Event {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn save_user_event(events: Vec<Event>, conn: &DbConn) -> EmptyResult {
|
||||
pub async fn save_user_event(events: Vec<Self>, conn: &DbConn) -> EmptyResult {
|
||||
// Special save function which is able to handle multiple events.
|
||||
// SQLite doesn't support the DEFAULT argument, and does not support inserting multiple values at the same time.
|
||||
// MySQL and PostgreSQL do.
|
||||
|
||||
@@ -112,10 +112,7 @@ impl Group {
|
||||
|
||||
pub fn set_external_id(&mut self, external_id: Option<String>) {
|
||||
// Check if external_id is empty. We do not want to have empty strings in the database
|
||||
self.external_id = match external_id {
|
||||
Some(external_id) if !external_id.trim().is_empty() => Some(external_id),
|
||||
_ => None,
|
||||
};
|
||||
self.external_id = external_id.filter(|e| !e.trim().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,7 +312,7 @@ impl Group {
|
||||
}
|
||||
|
||||
impl CollectionGroup {
|
||||
pub async fn save(&mut self, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult {
|
||||
pub async fn save(&self, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult {
|
||||
let group_users = GroupUser::find_by_group(&self.groups_uuid, org_uuid, conn).await;
|
||||
for group_user in group_users {
|
||||
group_user.update_user_revision(conn).await;
|
||||
@@ -448,7 +445,7 @@ impl CollectionGroup {
|
||||
org_uuid: &OrganizationId,
|
||||
conn: &DbConn,
|
||||
) -> EmptyResult {
|
||||
let collection_assigned_to_groups = CollectionGroup::find_by_collection(collection_uuid, conn).await;
|
||||
let collection_assigned_to_groups = Self::find_by_collection(collection_uuid, conn).await;
|
||||
for collection_assigned_to_group in collection_assigned_to_groups {
|
||||
let group_users = GroupUser::find_by_group(&collection_assigned_to_group.groups_uuid, org_uuid, conn).await;
|
||||
for group_user in group_users {
|
||||
@@ -467,7 +464,7 @@ impl CollectionGroup {
|
||||
}
|
||||
|
||||
impl GroupUser {
|
||||
pub async fn save(&mut self, conn: &DbConn) -> EmptyResult {
|
||||
pub async fn save(&self, conn: &DbConn) -> EmptyResult {
|
||||
self.update_user_revision(conn).await;
|
||||
|
||||
let values = (
|
||||
@@ -574,7 +571,7 @@ impl GroupUser {
|
||||
}
|
||||
|
||||
pub async fn delete_all_by_group(group_uuid: &GroupId, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult {
|
||||
let group_users = GroupUser::find_by_group(group_uuid, org_uuid, conn).await;
|
||||
let group_users = Self::find_by_group(group_uuid, org_uuid, conn).await;
|
||||
for group_user in group_users {
|
||||
group_user.update_user_revision(conn).await;
|
||||
}
|
||||
|
||||
@@ -301,11 +301,9 @@ impl OrgPolicy {
|
||||
exclude_org_uuid: Option<&OrganizationId>,
|
||||
conn: &DbConn,
|
||||
) -> bool {
|
||||
for policy in
|
||||
OrgPolicy::find_accepted_and_confirmed_by_user_and_active_policy(user_uuid, policy_type, conn).await
|
||||
{
|
||||
for policy in Self::find_accepted_and_confirmed_by_user_and_active_policy(user_uuid, policy_type, conn).await {
|
||||
// Check if we need to skip this organization.
|
||||
if exclude_org_uuid.is_some() && *exclude_org_uuid.unwrap() == policy.org_uuid {
|
||||
if exclude_org_uuid.is_some_and(|u| u == &policy.org_uuid) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -370,7 +368,7 @@ impl OrgPolicy {
|
||||
return false;
|
||||
}
|
||||
|
||||
match OrgPolicy::find_by_org_and_type(org_uuid, OrgPolicyType::ResetPassword, conn).await {
|
||||
match Self::find_by_org_and_type(org_uuid, OrgPolicyType::ResetPassword, conn).await {
|
||||
Some(policy) => match serde_json::from_str::<ResetPasswordDataModel>(&policy.data) {
|
||||
Ok(opts) => {
|
||||
return policy.enabled && opts.auto_enroll_enabled;
|
||||
@@ -386,8 +384,7 @@ impl OrgPolicy {
|
||||
/// Returns true if the user belongs to an org that has enabled the `DisableHideEmail`
|
||||
/// option of the `Send Options` policy, and the user is not an owner or admin of that org.
|
||||
pub async fn is_hide_email_disabled(user_uuid: &UserId, conn: &DbConn) -> bool {
|
||||
for policy in
|
||||
OrgPolicy::find_confirmed_by_user_and_active_policy(user_uuid, OrgPolicyType::SendOptions, conn).await
|
||||
for policy in Self::find_confirmed_by_user_and_active_policy(user_uuid, OrgPolicyType::SendOptions, conn).await
|
||||
{
|
||||
if let Some(user) = Membership::find_confirmed_by_user_and_org(user_uuid, &policy.org_uuid, conn).await
|
||||
&& user.atype < MembershipType::Admin
|
||||
@@ -407,7 +404,7 @@ impl OrgPolicy {
|
||||
|
||||
pub async fn is_enabled_for_member(member_uuid: &MembershipId, policy_type: OrgPolicyType, conn: &DbConn) -> bool {
|
||||
if let Some(member) = Membership::find_by_uuid(member_uuid, conn).await
|
||||
&& let Some(policy) = OrgPolicy::find_by_org_and_type(&member.org_uuid, policy_type, conn).await
|
||||
&& let Some(policy) = Self::find_by_org_and_type(&member.org_uuid, policy_type, conn).await
|
||||
{
|
||||
return policy.enabled;
|
||||
}
|
||||
|
||||
+153
-72
@@ -134,11 +134,11 @@ pub enum MembershipType {
|
||||
impl MembershipType {
|
||||
pub fn from_str(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"0" | "Owner" => Some(MembershipType::Owner),
|
||||
"1" | "Admin" => Some(MembershipType::Admin),
|
||||
"2" | "User" => Some(MembershipType::User),
|
||||
"3" | "Manager" => Some(MembershipType::Manager),
|
||||
"4" | "Custom" => Some(MembershipType::Custom),
|
||||
"0" | "Owner" => Some(Self::Owner),
|
||||
"1" | "Admin" => Some(Self::Admin),
|
||||
"2" | "User" => Some(Self::User),
|
||||
"3" | "Manager" => Some(Self::Manager),
|
||||
"4" | "Custom" => Some(Self::Custom),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -152,23 +152,23 @@ impl MembershipType {
|
||||
/// keeps their role when the request repeats it, so an unrelated edit never turns one into the other. A
|
||||
/// Manager only becomes a Custom member when the permissions they are shown with are changed.
|
||||
pub fn requested(
|
||||
requested: MembershipType,
|
||||
requested: Self,
|
||||
current: Option<&Membership>,
|
||||
custom_permissions: Option<&HashSet<CustomPermission>>,
|
||||
) -> MembershipType {
|
||||
if requested != MembershipType::Custom {
|
||||
) -> Self {
|
||||
if requested != Self::Custom {
|
||||
return requested;
|
||||
}
|
||||
match (current, custom_permissions) {
|
||||
(Some(member), _) if member.has_type(MembershipType::Custom) => MembershipType::Custom,
|
||||
(Some(member), _) if member.has_type(Self::Custom) => Self::Custom,
|
||||
(Some(member), Some(permissions))
|
||||
if member.has_type(MembershipType::Manager) && *permissions != member.legacy_manager_permissions() =>
|
||||
if member.has_type(Self::Manager) && *permissions != member.legacy_manager_permissions() =>
|
||||
{
|
||||
MembershipType::Custom
|
||||
Self::Custom
|
||||
}
|
||||
(Some(member), _) if member.has_type(MembershipType::Manager) => MembershipType::Manager,
|
||||
(_, Some(_)) => MembershipType::Custom,
|
||||
(_, None) => MembershipType::Manager,
|
||||
(Some(member), _) if member.has_type(Self::Manager) => Self::Manager,
|
||||
(_, Some(_)) => Self::Custom,
|
||||
(_, None) => Self::Manager,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,23 +176,23 @@ impl MembershipType {
|
||||
/// its permissions, never from its role, so the role itself ranks right above User and below Manager.
|
||||
const fn rank(self) -> u8 {
|
||||
match self {
|
||||
MembershipType::User => 0,
|
||||
MembershipType::Custom => 1,
|
||||
MembershipType::Manager => 2,
|
||||
MembershipType::Admin => 3,
|
||||
MembershipType::Owner => 4,
|
||||
Self::User => 0,
|
||||
Self::Custom => 1,
|
||||
Self::Manager => 2,
|
||||
Self::Admin => 3,
|
||||
Self::Owner => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for MembershipType {
|
||||
fn cmp(&self, other: &MembershipType) -> Ordering {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
self.rank().cmp(&other.rank())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for MembershipType {
|
||||
fn partial_cmp(&self, other: &MembershipType) -> Option<Ordering> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
@@ -212,17 +212,17 @@ impl PartialOrd<i32> for MembershipType {
|
||||
}
|
||||
|
||||
fn gt(&self, other: &i32) -> bool {
|
||||
matches!(self.partial_cmp(other), Some(Ordering::Greater))
|
||||
self.partial_cmp(other).is_some_and(Ordering::is_gt)
|
||||
}
|
||||
|
||||
fn ge(&self, other: &i32) -> bool {
|
||||
matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
|
||||
self.partial_cmp(other).is_some_and(Ordering::is_ge)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<MembershipType> for i32 {
|
||||
fn eq(&self, other: &MembershipType) -> bool {
|
||||
*self == *other as i32
|
||||
*self == *other as Self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,11 +235,11 @@ impl PartialOrd<MembershipType> for i32 {
|
||||
}
|
||||
|
||||
fn lt(&self, other: &MembershipType) -> bool {
|
||||
matches!(self.partial_cmp(other), Some(Ordering::Less) | None)
|
||||
self.partial_cmp(other).is_none_or(Ordering::is_lt)
|
||||
}
|
||||
|
||||
fn le(&self, other: &MembershipType) -> bool {
|
||||
matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal) | None)
|
||||
self.partial_cmp(other).is_none_or(Ordering::is_le)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,32 +275,32 @@ const SUPPORTED_CUSTOM_PERMISSIONS: &[CustomPermission] = &[
|
||||
];
|
||||
|
||||
impl CustomPermission {
|
||||
pub const ALL: [CustomPermission; 10] = [
|
||||
CustomPermission::ManageUsers,
|
||||
CustomPermission::ManageGroups,
|
||||
CustomPermission::ManagePolicies,
|
||||
CustomPermission::CreateNewCollections,
|
||||
CustomPermission::EditAnyCollection,
|
||||
CustomPermission::DeleteAnyCollection,
|
||||
CustomPermission::AccessEventLogs,
|
||||
CustomPermission::AccessImportExport,
|
||||
CustomPermission::AccessReports,
|
||||
CustomPermission::ManageResetPassword,
|
||||
pub const ALL: [Self; 10] = [
|
||||
Self::ManageUsers,
|
||||
Self::ManageGroups,
|
||||
Self::ManagePolicies,
|
||||
Self::CreateNewCollections,
|
||||
Self::EditAnyCollection,
|
||||
Self::DeleteAnyCollection,
|
||||
Self::AccessEventLogs,
|
||||
Self::AccessImportExport,
|
||||
Self::AccessReports,
|
||||
Self::ManageResetPassword,
|
||||
];
|
||||
|
||||
/// The key of the permission in the `permissions` object of the Bitwarden clients.
|
||||
pub const fn json_key(self) -> &'static str {
|
||||
match self {
|
||||
CustomPermission::ManageUsers => "manageUsers",
|
||||
CustomPermission::ManageGroups => "manageGroups",
|
||||
CustomPermission::ManagePolicies => "managePolicies",
|
||||
CustomPermission::CreateNewCollections => "createNewCollections",
|
||||
CustomPermission::EditAnyCollection => "editAnyCollection",
|
||||
CustomPermission::DeleteAnyCollection => "deleteAnyCollection",
|
||||
CustomPermission::AccessEventLogs => "accessEventLogs",
|
||||
CustomPermission::AccessImportExport => "accessImportExport",
|
||||
CustomPermission::AccessReports => "accessReports",
|
||||
CustomPermission::ManageResetPassword => "manageResetPassword",
|
||||
Self::ManageUsers => "manageUsers",
|
||||
Self::ManageGroups => "manageGroups",
|
||||
Self::ManagePolicies => "managePolicies",
|
||||
Self::CreateNewCollections => "createNewCollections",
|
||||
Self::EditAnyCollection => "editAnyCollection",
|
||||
Self::DeleteAnyCollection => "deleteAnyCollection",
|
||||
Self::AccessEventLogs => "accessEventLogs",
|
||||
Self::AccessImportExport => "accessImportExport",
|
||||
Self::AccessReports => "accessReports",
|
||||
Self::ManageResetPassword => "manageResetPassword",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,9 +314,9 @@ impl CustomPermission {
|
||||
/// replaces the member's permissions, so a malformed value must not silently remove one. Granting a
|
||||
/// permission this version does not enforce is rejected as well. The clients also send permissions
|
||||
/// Vaultwarden does not know at all, like `manageSso`, those are ignored.
|
||||
pub fn requested(permissions: &HashMap<String, Value>) -> Result<HashSet<CustomPermission>, Error> {
|
||||
pub fn requested(permissions: &HashMap<String, Value>) -> Result<HashSet<Self>, Error> {
|
||||
let mut granted = HashSet::new();
|
||||
for permission in CustomPermission::ALL {
|
||||
for permission in Self::ALL {
|
||||
match permissions.get(permission.json_key()) {
|
||||
None | Some(Value::Bool(false)) => {}
|
||||
Some(Value::Bool(true)) if permission.is_supported() => {
|
||||
@@ -581,7 +581,7 @@ impl Membership {
|
||||
|
||||
/// Whether this member may act with every Custom role permission stored for `other`, as Bitwarden's
|
||||
/// `Permissions.Includes`.
|
||||
pub fn has_custom_permissions_of(&self, other: &Membership) -> bool {
|
||||
pub fn has_custom_permissions_of(&self, other: &Self) -> bool {
|
||||
CustomPermission::ALL.into_iter().all(|p| !other.custom_permission(p) || self.has_custom_permission(p))
|
||||
}
|
||||
|
||||
@@ -644,16 +644,15 @@ impl Membership {
|
||||
}
|
||||
|
||||
pub fn set_external_id(&mut self, external_id: Option<String>) -> bool {
|
||||
//Check if external id is empty. We don't want to have
|
||||
//empty strings in the database
|
||||
if self.external_id != external_id {
|
||||
self.external_id = match external_id {
|
||||
Some(external_id) if !external_id.is_empty() => Some(external_id),
|
||||
_ => None,
|
||||
};
|
||||
return true;
|
||||
// Check if external id is empty. We don't want to have empty strings in the database
|
||||
let external_id = external_id.filter(|e| !e.trim().is_empty());
|
||||
|
||||
if self.external_id == external_id {
|
||||
return false;
|
||||
}
|
||||
false
|
||||
|
||||
self.external_id = external_id;
|
||||
true
|
||||
}
|
||||
|
||||
/// HACK: Convert the manager type to a custom type
|
||||
@@ -882,7 +881,7 @@ impl Membership {
|
||||
let twofactor_enabled = !TwoFactor::find_by_user(&user.uuid, conn).await.is_empty();
|
||||
|
||||
let groups: Vec<GroupId> = if include_groups && CONFIG.org_groups_enabled() {
|
||||
GroupUser::find_by_member(&self.uuid, conn).await.iter().map(|gu| gu.groups_uuid.clone()).collect()
|
||||
GroupUser::find_by_member(&self.uuid, conn).await.into_iter().map(|gu| gu.groups_uuid).collect()
|
||||
} else {
|
||||
// The Bitwarden clients seem to call this API regardless of whether groups are enabled,
|
||||
// so just act as if there are no groups.
|
||||
@@ -928,7 +927,7 @@ impl Membership {
|
||||
json!({
|
||||
"id": self.uuid,
|
||||
"userId": self.user_uuid,
|
||||
"name": if self.get_unrevoked_status() >= MembershipStatus::Accepted as i32 { Some(user.name) } else { None },
|
||||
"name": (self.get_unrevoked_status() >= MembershipStatus::Accepted as i32).then_some(user.name),
|
||||
"email": user.email,
|
||||
"externalId": self.external_id,
|
||||
"avatarColor": user.avatar_color,
|
||||
@@ -1081,9 +1080,9 @@ impl Membership {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn find_by_email_and_org(email: &str, org_uuid: &OrganizationId, conn: &DbConn) -> Option<Membership> {
|
||||
pub async fn find_by_email_and_org(email: &str, org_uuid: &OrganizationId, conn: &DbConn) -> Option<Self> {
|
||||
if let Some(user) = User::find_by_mail(email, conn).await
|
||||
&& let Some(member) = Membership::find_by_user_and_org(&user.uuid, org_uuid, conn).await
|
||||
&& let Some(member) = Self::find_by_user_and_org(&user.uuid, org_uuid, conn).await
|
||||
{
|
||||
return Some(member);
|
||||
}
|
||||
@@ -1285,11 +1284,9 @@ impl Membership {
|
||||
.filter(users_organizations::org_uuid.eq(org_uuid))
|
||||
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
|
||||
.filter(
|
||||
users_organizations::atype
|
||||
.eq_any(vec![MembershipType::Owner as i32, MembershipType::Admin as i32])
|
||||
.or(users_organizations::atype
|
||||
.eq(MembershipType::Manager as i32)
|
||||
.and(users_organizations::access_all.eq(true))),
|
||||
users_organizations::atype.eq_any(ORG_ADMIN_ATYPES).or(users_organizations::atype
|
||||
.eq(MembershipType::Manager as i32)
|
||||
.and(users_organizations::access_all.eq(true))),
|
||||
)
|
||||
.load::<Self>(conn)
|
||||
.unwrap_or_default()
|
||||
@@ -1669,6 +1666,18 @@ mod tests {
|
||||
use CustomPermission::*;
|
||||
use MembershipType::{Admin, Custom, Manager, Owner, User};
|
||||
|
||||
/// Every role, from the least to the most authority.
|
||||
const AUTHORITY: [MembershipType; 5] = [User, Custom, Manager, Admin, Owner];
|
||||
/// Stored roles no `MembershipType` exists for, like one written by a newer version.
|
||||
const UNKNOWN_ROLES: [i32; 5] = [i32::MIN, -1, 5, 99, i32::MAX];
|
||||
/// `[<, <=, >, >=, ==, !=]`, through the trait methods those operators call for `A` and `B`.
|
||||
fn compare<A: PartialOrd<B>, B>(a: &A, b: &B) -> [bool; 6] {
|
||||
[a.lt(b), a.le(b), a.gt(b), a.ge(b), a.eq(b), a.ne(b)]
|
||||
}
|
||||
fn expected(ordering: Ordering) -> [bool; 6] {
|
||||
[ordering.is_lt(), ordering.is_le(), ordering.is_gt(), ordering.is_ge(), ordering.is_eq(), ordering.is_ne()]
|
||||
}
|
||||
|
||||
fn member(role: MembershipType) -> Membership {
|
||||
let mut member = Membership::new("user".into(), "org".into(), None);
|
||||
member.atype = role as i32;
|
||||
@@ -1678,22 +1687,94 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn membership_type_authority() {
|
||||
assert!(Owner > Admin && Admin > Manager && Manager > Custom && Custom > User);
|
||||
assert!((Custom as i32) >= User && (Custom as i32) < Manager && (Custom as i32) < Admin);
|
||||
for raw in [99, -1] {
|
||||
assert_eq!((raw >= User, raw >= Manager, raw >= Admin, raw < Admin), (false, false, false, true));
|
||||
// Roles compare by authority, never by their stored number, whichever side the raw `i32` is on
|
||||
for (i, role) in AUTHORITY.into_iter().enumerate() {
|
||||
for (j, other) in AUTHORITY.into_iter().enumerate() {
|
||||
let ordering = i.cmp(&j);
|
||||
let (raw, raw_other) = (role as i32, other as i32);
|
||||
assert_eq!(role.cmp(&other), ordering, "{role:?} {other:?}");
|
||||
assert_eq!(role.partial_cmp(&raw_other), Some(ordering), "{role:?} {raw_other}");
|
||||
assert_eq!(raw.partial_cmp(&other), Some(ordering), "{raw} {other:?}");
|
||||
assert_eq!(compare(&role, &other), expected(ordering), "{role:?} {other:?}");
|
||||
assert_eq!(compare(&role, &raw_other), expected(ordering), "{role:?} {raw_other}");
|
||||
assert_eq!(compare(&raw, &other), expected(ordering), "{raw} {other:?}");
|
||||
}
|
||||
}
|
||||
|
||||
for (value, expected) in [
|
||||
("0", Some(Owner)),
|
||||
("Owner", Some(Owner)),
|
||||
("1", Some(Admin)),
|
||||
("Admin", Some(Admin)),
|
||||
("2", Some(User)),
|
||||
("User", Some(User)),
|
||||
("3", Some(Manager)),
|
||||
("Manager", Some(Manager)),
|
||||
("4", Some(Custom)),
|
||||
("Custom", Some(Custom)),
|
||||
("5", None),
|
||||
("Invalid", None),
|
||||
] {
|
||||
assert_eq!(MembershipType::from_str(value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_raw_roles_fail_closed() {
|
||||
for raw in UNKNOWN_ROLES {
|
||||
assert_eq!(MembershipType::from_i32(raw), None);
|
||||
for role in AUTHORITY {
|
||||
// An unknown stored role ranks below every role, so it never passes an authority check and every
|
||||
// `atype < Admin` restriction applies to it
|
||||
assert_eq!(raw.partial_cmp(&role), None);
|
||||
assert_eq!(compare(&raw, &role), [true, true, false, false, false, true], "{raw} {role:?}");
|
||||
// The other way around nothing holds, which no check relies on
|
||||
assert_eq!(role.partial_cmp(&raw), None);
|
||||
assert_eq!(compare(&role, &raw), [false, false, false, false, false, true], "{role:?} {raw}");
|
||||
}
|
||||
let mut unknown = member(User);
|
||||
unknown.atype = raw;
|
||||
assert!(!unknown.has_full_access());
|
||||
assert!(AUTHORITY.into_iter().all(|role| !unknown.has_type(role)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revoke_and_restore_round_trip() {
|
||||
// The revoked statuses are stored and queried for, so they are pinned rather than derived
|
||||
for (status, revoked) in
|
||||
[(MembershipStatus::Invited, -128), (MembershipStatus::Accepted, -127), (MembershipStatus::Confirmed, -126)]
|
||||
{
|
||||
let status = status as i32;
|
||||
for role in AUTHORITY {
|
||||
let mut m = member(role);
|
||||
m.status = status;
|
||||
let full_access = m.has_full_access();
|
||||
|
||||
assert_eq!(full_access, role >= Admin && status == MembershipStatus::Confirmed as i32);
|
||||
assert!(!m.restore(), "{role:?} {status}: only a revoked member can be restored");
|
||||
assert_eq!((m.status, m.get_unrevoked_status()), (status, status));
|
||||
|
||||
assert!(m.revoke(), "{role:?} {status}");
|
||||
assert_eq!((m.status, m.get_unrevoked_status()), (revoked, status));
|
||||
assert!(MembershipStatus::from_i32(m.status).is_none());
|
||||
assert!(!m.has_status(MembershipStatus::Confirmed) && !m.has_full_access());
|
||||
assert!(m.has_type(role));
|
||||
assert_eq!(m.atype.partial_cmp(&role), Some(Ordering::Equal));
|
||||
|
||||
assert!(!m.revoke(), "{role:?} {status}: a revoked member can't be revoked again");
|
||||
assert_eq!(m.status, revoked);
|
||||
|
||||
assert!(m.restore(), "{role:?} {status}");
|
||||
assert_eq!((m.status, m.get_unrevoked_status()), (status, status));
|
||||
assert_eq!((m.atype, m.has_full_access()), (role as i32, full_access));
|
||||
|
||||
assert!(!m.restore(), "{role:?} {status}: a restored member can't be restored again");
|
||||
assert_eq!(m.status, status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requested_membership_type() {
|
||||
let none = HashSet::new();
|
||||
|
||||
@@ -58,9 +58,9 @@ pub enum SendType {
|
||||
}
|
||||
|
||||
enum SendAuthType {
|
||||
#[allow(dead_code)]
|
||||
#[expect(unused, reason = "Not yet supported")]
|
||||
// Send requires email OTP verification
|
||||
Email = 0, // Not yet supported by Vaultwarden
|
||||
Email = 0,
|
||||
// Send requires a password
|
||||
Password = 1,
|
||||
// Send requires no auth
|
||||
@@ -145,7 +145,7 @@ impl Send {
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
let mut data = serde_json::from_str::<LowerCase<Value>>(&self.data).map(|d| d.data).unwrap_or_default();
|
||||
let mut data = serde_json::from_str::<LowerCase<Value>>(&self.data).map_or_default(|d| d.data);
|
||||
|
||||
// Mobile clients expect size to be a string instead of a number
|
||||
if let Some(size) = data.get("size").and_then(Value::as_i64) {
|
||||
@@ -159,8 +159,8 @@ impl Send {
|
||||
|
||||
"name": self.name,
|
||||
"notes": self.notes,
|
||||
"text": if self.atype == SendType::Text as i32 { Some(&data) } else { None },
|
||||
"file": if self.atype == SendType::File as i32 { Some(&data) } else { None },
|
||||
"text": (self.atype == SendType::Text as i32).then_some(&data),
|
||||
"file": (self.atype == SendType::File as i32).then_some(&data),
|
||||
|
||||
"key": self.akey,
|
||||
"maxAccessCount": self.max_access_count,
|
||||
@@ -178,7 +178,7 @@ impl Send {
|
||||
}
|
||||
|
||||
pub async fn to_json_access(&self, conn: &DbConn) -> Value {
|
||||
let mut data = serde_json::from_str::<LowerCase<Value>>(&self.data).map(|d| d.data).unwrap_or_default();
|
||||
let mut data = serde_json::from_str::<LowerCase<Value>>(&self.data).map_or_default(|d| d.data);
|
||||
|
||||
// Mobile clients expect size to be a string instead of a number
|
||||
if let Some(size) = data.get("size").and_then(Value::as_i64) {
|
||||
@@ -190,8 +190,8 @@ impl Send {
|
||||
"type": self.atype,
|
||||
|
||||
"name": self.name,
|
||||
"text": if self.atype == SendType::Text as i32 { Some(&data) } else { None },
|
||||
"file": if self.atype == SendType::File as i32 { Some(&data) } else { None },
|
||||
"text": (self.atype == SendType::Text as i32).then_some(&data),
|
||||
"file": (self.atype == SendType::File as i32).then_some(&data),
|
||||
|
||||
"expirationDate": self.expiration_date.as_ref().map(format_date),
|
||||
"creatorIdentifier": self.creator_identifier(conn).await,
|
||||
|
||||
@@ -67,7 +67,7 @@ impl SsoAuth {
|
||||
) -> Self {
|
||||
let now = Utc::now().naive_utc();
|
||||
|
||||
SsoAuth {
|
||||
Self {
|
||||
state,
|
||||
client_challenge,
|
||||
nonce,
|
||||
|
||||
@@ -174,7 +174,7 @@ impl TwoFactor {
|
||||
for mut u2f in u2f_factors {
|
||||
let mut regs: Vec<U2FRegistration> = serde_json::from_str(&u2f.data)?;
|
||||
// If there are no registrations or they are migrated (we do the migration in batch so we can consider them all migrated when the first one is)
|
||||
if regs.is_empty() || regs[0].migrated == Some(true) {
|
||||
if regs.first().is_none_or(|reg| reg.migrated == Some(true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -227,7 +227,7 @@ impl TwoFactor {
|
||||
u2f.data = serde_json::to_string(®s)?;
|
||||
u2f.save(conn).await?;
|
||||
|
||||
TwoFactor::new(u2f.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(&webauthn_regs)?)
|
||||
Self::new(u2f.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(&webauthn_regs)?)
|
||||
.save(conn)
|
||||
.await?;
|
||||
}
|
||||
@@ -254,7 +254,7 @@ impl TwoFactor {
|
||||
|
||||
let regs = regs.into_iter().map(Into::into).collect::<Vec<WebauthnRegistration>>();
|
||||
|
||||
TwoFactor::new(webauthn_factor.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(®s)?)
|
||||
Self::new(webauthn_factor.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(®s)?)
|
||||
.save(conn)
|
||||
.await?;
|
||||
}
|
||||
|
||||
+13
-8
@@ -147,7 +147,7 @@ impl User {
|
||||
verified_at: None,
|
||||
last_verifying_at: None,
|
||||
login_verify_count: 0,
|
||||
name: name.unwrap_or(email.clone()),
|
||||
name: name.unwrap_or_else(|| email.clone()),
|
||||
email,
|
||||
akey: String::new(),
|
||||
email_new: None,
|
||||
@@ -222,15 +222,11 @@ impl User {
|
||||
}
|
||||
|
||||
pub fn check_valid_recovery_code(&self, recovery_code: &str) -> bool {
|
||||
if let Some(ref totp_recover) = self.totp_recover {
|
||||
crypto::ct_eq(recovery_code, totp_recover.to_lowercase())
|
||||
} else {
|
||||
false
|
||||
}
|
||||
self.totp_recover.as_ref().is_some_and(|c| crypto::ct_eq(recovery_code, c.to_lowercase()))
|
||||
}
|
||||
|
||||
pub fn check_valid_api_key(&self, key: &str) -> bool {
|
||||
matches!(self.api_key, Some(ref api_key) if crypto::ct_eq(api_key, key))
|
||||
self.api_key.as_ref().is_some_and(|k| crypto::ct_eq(key, k))
|
||||
}
|
||||
|
||||
/// Set the password hash generated
|
||||
@@ -290,7 +286,7 @@ impl User {
|
||||
grace.push(UserStampException {
|
||||
routes: None,
|
||||
security_stamp: previous_stamp,
|
||||
expire: (Utc::now() + *DEFAULT_ACCESS_VALIDITY).timestamp(),
|
||||
expire: (Utc::now() + DEFAULT_ACCESS_VALIDITY).timestamp(),
|
||||
});
|
||||
let mut exceptions = self.stamp_exceptions();
|
||||
exceptions.extend(grace);
|
||||
@@ -773,6 +769,15 @@ mod tests {
|
||||
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
|
||||
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
|
||||
.env("DATABASE_URL", "sqlite://:memory:")
|
||||
// Keep a local `.env` out of the tests, such as SMTP settings that would send mail.
|
||||
.env(
|
||||
"ENV_FILE",
|
||||
if cfg!(windows) {
|
||||
"NUL"
|
||||
} else {
|
||||
"/dev/null"
|
||||
},
|
||||
)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
|
||||
Reference in new issue
Block a user