use std::{ cmp::Ordering, collections::{HashMap, HashSet}, }; use chrono::{NaiveDateTime, Utc}; use derive_more::{AsRef, Deref, Display, From}; use diesel::prelude::*; use num_traits::FromPrimitive; use serde_json::Value; use crate::{ CONFIG, api::EmptyResult, db::{ DbConn, schema::{ ciphers_collections, collections_groups, groups, groups_users, org_policies, organization_api_key, organizations, users, users_collections, users_organizations, }, }, error::{Error, MapResult}, }; use macros::UuidFromParam; use super::{ Cipher, CipherId, Collection, CollectionId, CollectionUser, Group, GroupId, GroupUser, KeyId, OrgPolicy, OrgPolicyType, TwoFactor, User, UserId, }; /// A membership whose account recovery key still wraps the member's V1 user key: an upgrade to V2 encryption can't /// re-wrap it (that needs the member to trust the organization's key), so it left the token the admin re-wraps it from. #[derive(Queryable)] pub struct PendingV2Upgrade { pub member_id: MembershipId, /// The member's current user key id, which the re-wrapped key must be sent back with pub user_key_id: KeyId, /// The V1 user key, wrapped with the organization's public key pub account_recovery_key: String, pub v2_upgrade_token: String, } #[derive(Identifiable, Queryable, Insertable, AsChangeset)] #[diesel(table_name = organizations)] #[diesel(treat_none_as_null = true)] #[diesel(primary_key(uuid))] pub struct Organization { pub uuid: OrganizationId, pub name: String, pub billing_email: String, pub private_key: Option, pub public_key: Option, } #[derive(Identifiable, Queryable, Insertable, AsChangeset)] #[diesel(table_name = users_organizations)] #[diesel(treat_none_as_null = true)] #[diesel(primary_key(uuid))] #[expect(clippy::struct_excessive_bools, reason = "Each Custom role permission is a column of its own")] pub struct Membership { pub uuid: MembershipId, pub user_uuid: UserId, pub org_uuid: OrganizationId, pub invited_by_email: Option, pub akey: String, pub status: i32, pub atype: i32, pub reset_password_key: Option, pub external_id: Option, // The permissions of a Custom role, only accessed through `CustomPermission`. manage_users: bool, manage_groups: bool, manage_policies: bool, create_new_collections: bool, edit_any_collection: bool, delete_any_collection: bool, access_event_logs: bool, access_import_export: bool, access_reports: bool, manage_reset_password: bool, /// The user's v2 upgrade token, for the org to unwrap the v2 user key after an upgrade. Opaque to us. pub v2_upgrade_token: Option, } #[derive(Identifiable, Queryable, Insertable, AsChangeset)] #[diesel(table_name = organization_api_key)] #[diesel(primary_key(uuid, org_uuid))] pub struct OrganizationApiKey { pub uuid: OrgApiKeyId, pub org_uuid: OrganizationId, pub atype: i32, pub api_key: String, pub revision_date: NaiveDateTime, } // https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Core/AdminConsole/Enums/OrganizationUserStatusType.cs #[derive(PartialEq)] pub enum MembershipStatus { Revoked = -1, Invited = 0, Accepted = 1, Confirmed = 2, } impl MembershipStatus { pub fn from_i32(status: i32) -> Option { match status { 0 => Some(Self::Invited), 1 => Some(Self::Accepted), 2 => Some(Self::Confirmed), // NOTE: we don't care about revoked members where this is used // if this ever changes also adapt the OrgHeaders check. _ => None, } } } #[derive(Copy, Clone, Debug, PartialEq, Eq, num_derive::FromPrimitive)] pub enum MembershipType { Owner = 0, Admin = 1, User = 2, // Manager = 3 was removed like upstream: the managers became Users with the manage option on their collections. // Only granted while EXPERIMENTAL_CUSTOM_ROLES is enabled. Custom = 4, } impl MembershipType { pub fn from_str(s: &str) -> Option { match s { "0" | "Owner" => Some(MembershipType::Owner), "1" | "Admin" => Some(MembershipType::Admin), "2" | "User" => Some(MembershipType::User), "4" | "Custom" => Some(MembershipType::Custom), _ => None, } } /// Whether a member invite or edit may ask for `requested`, given the member's current role (`None` for an /// invite). A Custom role needs EXPERIMENTAL_CUSTOM_ROLES, except for a member who already has it: an unrelated /// edit of them keeps it while Custom roles are disabled, with the permissions they have. pub fn check_requested(requested: MembershipType, current: Option<&Membership>) -> EmptyResult { if requested == MembershipType::Custom && !custom_roles_enabled() && !current.is_some_and(|member| member.has_type(MembershipType::Custom)) { err!("Custom roles are not enabled") } Ok(()) } /// The authority of a role, which is what roles are compared by. A Custom member gets its authority from /// its permissions, never from its role, so the role itself ranks right above User and below Admin. const fn rank(self) -> u8 { match self { MembershipType::User => 0, MembershipType::Custom => 1, MembershipType::Admin => 2, MembershipType::Owner => 3, } } } impl Ord for MembershipType { fn cmp(&self, other: &MembershipType) -> Ordering { self.rank().cmp(&other.rank()) } } impl PartialOrd for MembershipType { fn partial_cmp(&self, other: &MembershipType) -> Option { Some(self.cmp(other)) } } impl PartialEq for MembershipType { fn eq(&self, other: &i32) -> bool { *other == *self as i32 } } impl PartialOrd for MembershipType { fn partial_cmp(&self, other: &i32) -> Option { if let Some(other) = Self::from_i32(*other) { return Some(self.cmp(&other)); } None } fn gt(&self, other: &i32) -> bool { matches!(self.partial_cmp(other), Some(Ordering::Greater)) } fn ge(&self, other: &i32) -> bool { matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal)) } } impl PartialEq for i32 { fn eq(&self, other: &MembershipType) -> bool { *self == *other as i32 } } impl PartialOrd for i32 { fn partial_cmp(&self, other: &MembershipType) -> Option { if let Some(self_type) = MembershipType::from_i32(*self) { return Some(self_type.cmp(other)); } None } fn lt(&self, other: &MembershipType) -> bool { matches!(self.partial_cmp(other), Some(Ordering::Less) | None) } fn le(&self, other: &MembershipType) -> bool { matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal) | None) } } /// The granular permissions of the Custom role. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum CustomPermission { ManageUsers, ManageGroups, ManagePolicies, CreateNewCollections, EditAnyCollection, DeleteAnyCollection, AccessEventLogs, AccessImportExport, AccessReports, ManageResetPassword, } /// The permissions this version enforces on every endpoint they open. Only these can be granted, a stored /// grant of any other one grants nothing. Every stored permission is enforced now, a permission added later only /// belongs here once every endpoint it opens enforces it. const SUPPORTED_CUSTOM_PERMISSIONS: &[CustomPermission] = &[ CustomPermission::ManageUsers, CustomPermission::ManageGroups, CustomPermission::ManagePolicies, CustomPermission::CreateNewCollections, CustomPermission::EditAnyCollection, CustomPermission::DeleteAnyCollection, CustomPermission::AccessEventLogs, CustomPermission::AccessImportExport, CustomPermission::AccessReports, CustomPermission::ManageResetPassword, ]; 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, ]; /// 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", } } pub fn is_supported(self) -> bool { SUPPORTED_CUSTOM_PERMISSIONS.contains(&self) } /// The permissions a member invite or edit grants a Custom role. /// /// A permission is only granted when it is set to `true`, and anything but a boolean is rejected: this /// 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) -> Result, Error> { let mut granted = HashSet::new(); for permission in CustomPermission::ALL { match permissions.get(permission.json_key()) { None | Some(Value::Bool(false)) => {} Some(Value::Bool(true)) if permission.is_supported() => { granted.insert(permission); } Some(Value::Bool(true)) => { err!(format!("The Custom role permission '{}' is not supported yet", permission.json_key())) } Some(_) => { err!(format!("The Custom role permission '{}' must be true or false", permission.json_key())) } } } Ok(granted) } } /// The stored roles with authority over the whole organization. Queries match them by value, comparing /// `atype <= Admin` would also match any unknown value below it. pub(super) const ORG_ADMIN_ATYPES: [i32; 2] = [MembershipType::Owner as i32, MembershipType::Admin as i32]; /// Whether the experimental Custom role is enabled. Nothing is ever granted through a Custom role otherwise. pub fn custom_roles_enabled() -> bool { #[cfg(test)] if let Some(enabled) = test_flag::CUSTOM_ROLES_ENABLED.get() { return enabled; } CONFIG.experimental_custom_roles() } type CustomEditAnyCollection = diesel::dsl::And< diesel::dsl::And< diesel::dsl::Eq, diesel::dsl::Eq, >, bool, diesel::sql_types::Bool, >; /// SQL: a Custom member with Edit any collection, while Custom roles are enabled. pub(super) fn custom_edit_any_collection() -> CustomEditAnyCollection { users_organizations::atype .eq(MembershipType::Custom as i32) .and(users_organizations::edit_any_collection.eq(true)) .and::<_, diesel::sql_types::Bool>(custom_roles_enabled()) } #[cfg(test)] pub mod test_flag { thread_local! { /// Overrides EXPERIMENTAL_CUSTOM_ROLES for the tests running on this thread. pub static CUSTOM_ROLES_ENABLED: std::cell::Cell> = const { std::cell::Cell::new(None) }; } } /// Local methods impl Organization { pub fn new(name: String, billing_email: &str, private_key: Option, public_key: Option) -> Self { let billing_email = billing_email.to_lowercase(); Self { uuid: OrganizationId(crate::util::get_uuid()), name, billing_email, private_key, public_key, } } // https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Models/Response/Organizations/OrganizationResponseModel.cs pub fn to_json(&self) -> Value { json!({ "id": self.uuid, "name": self.name, "seats": null, "maxCollections": null, "maxStorageGb": i16::MAX, // The value doesn't matter, we don't check server-side "use2fa": true, "useCustomPermissions": custom_roles_enabled(), "useDirectory": false, // Is supported, but this value isn't checked anywhere (yet) "useEvents": CONFIG.org_events_enabled(), "useGroups": CONFIG.org_groups_enabled(), "useTotp": true, "usePolicies": true, "useScim": false, // Not supported (Not AGPLv3 Licensed) "useSso": false, // Not supported "useKeyConnector": false, // Not supported "usePasswordManager": true, "useSecretsManager": false, // Not supported (Not AGPLv3 Licensed) "selfHost": true, "useApi": true, "useDisableSMAdsForUsers": true, // Hide Secrets Manager ads "useInviteLinks": false, // Not (yet) supported "useMyItems": false, // Not (yet) supported "useOrganizationDomains": false, // Not supported (Linked to SSO) "usePam": false, // Not supported "usePhishingBlocker": false, "hasPublicAndPrivateKeys": self.private_key.is_some() && self.public_key.is_some(), "useResetPassword": CONFIG.mail_enabled(), "allowAdminAccessToAllCollectionItems": true, "limitCollectionCreation": true, "limitCollectionDeletion": true, "limitItemDeletion": false, "businessName": self.name, "businessAddress1": null, "businessAddress2": null, "businessAddress3": null, "businessCountry": null, "businessTaxNumber": null, "maxAutoscaleSeats": null, "maxAutoscaleSmSeats": null, "maxAutoscaleSmServiceAccounts": null, "secretsManagerPlan": null, "smSeats": null, "smServiceAccounts": null, "billingEmail": self.billing_email, "planType": 6, // Custom plan "usersGetPremium": true, "object": "organization", }) } } // Used to either subtract or add to the current status // The number 128 should be fine, it is well within the range of an i32 // The same goes for the database where we only use INTEGER (the same as an i32) // It should also provide enough room for 100+ types, which i doubt will ever happen. const ACTIVATE_REVOKE_DIFF: i32 = 128; impl Membership { pub fn new(user_uuid: UserId, org_uuid: OrganizationId, invited_by_email: Option) -> Self { Self { uuid: MembershipId(crate::util::get_uuid()), user_uuid, org_uuid, invited_by_email, akey: String::new(), status: MembershipStatus::Accepted as i32, atype: MembershipType::User as i32, reset_password_key: None, external_id: None, manage_users: false, manage_groups: false, manage_policies: false, create_new_collections: false, edit_any_collection: false, delete_any_collection: false, access_event_logs: false, access_import_export: false, access_reports: false, manage_reset_password: false, v2_upgrade_token: None, } } fn custom_permission_mut(&mut self, permission: CustomPermission) -> &mut bool { match permission { CustomPermission::ManageUsers => &mut self.manage_users, CustomPermission::ManageGroups => &mut self.manage_groups, CustomPermission::ManagePolicies => &mut self.manage_policies, CustomPermission::CreateNewCollections => &mut self.create_new_collections, CustomPermission::EditAnyCollection => &mut self.edit_any_collection, CustomPermission::DeleteAnyCollection => &mut self.delete_any_collection, CustomPermission::AccessEventLogs => &mut self.access_event_logs, CustomPermission::AccessImportExport => &mut self.access_import_export, CustomPermission::AccessReports => &mut self.access_reports, CustomPermission::ManageResetPassword => &mut self.manage_reset_password, } } /// Change the role. Nothing the old role carried survives a role change: the Custom role permissions are /// dropped, so changing the role back later starts from none. pub fn set_type(&mut self, new_type: MembershipType) { if self.atype != new_type as i32 { for permission in CustomPermission::ALL { *self.custom_permission_mut(permission) = false; } } self.atype = new_type as i32; } /// Grant this Custom member exactly `permissions` out of those this version enforces. A stored grant of a /// permission this version does not enforce is kept as it is: it grants nothing here. pub fn set_custom_permissions(&mut self, permissions: &HashSet) { for permission in CustomPermission::ALL.into_iter().filter(|p| p.is_supported()) { *self.custom_permission_mut(permission) = permissions.contains(&permission); } } fn custom_permission(&self, permission: CustomPermission) -> bool { match permission { CustomPermission::ManageUsers => self.manage_users, CustomPermission::ManageGroups => self.manage_groups, CustomPermission::ManagePolicies => self.manage_policies, CustomPermission::CreateNewCollections => self.create_new_collections, CustomPermission::EditAnyCollection => self.edit_any_collection, CustomPermission::DeleteAnyCollection => self.delete_any_collection, CustomPermission::AccessEventLogs => self.access_event_logs, CustomPermission::AccessImportExport => self.access_import_export, CustomPermission::AccessReports => self.access_reports, CustomPermission::ManageResetPassword => self.manage_reset_password, } } /// Whether the role of this member grants `permission`. Only a Custom role grants any, only while Custom roles /// are enabled, and only the permissions this version enforces. fn grants_custom_permission(&self, permission: CustomPermission) -> bool { custom_roles_enabled() && permission.is_supported() && self.has_type(MembershipType::Custom) && self.custom_permission(permission) } /// Whether this member may act with `permission`, granted by their Custom role. Like the authority of any /// other role, it needs a confirmed membership. pub fn has_custom_permission(&self, permission: CustomPermission) -> bool { self.has_status(MembershipStatus::Confirmed) && self.grants_custom_permission(permission) } /// 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 { CustomPermission::ALL.into_iter().all(|p| !other.custom_permission(p) || self.has_custom_permission(p)) } /// The permissions the clients are shown. pub fn shown_custom_permissions(&self) -> HashSet { CustomPermission::ALL.into_iter().filter(|p| self.grants_custom_permission(*p)).collect() } fn custom_permissions_json(&self) -> Value { let shown = self.shown_custom_permissions(); let mut permissions = json!({ "manageSso": false, // Not supported "manageScim": false, // Not supported (Not AGPLv3 Licensed) }); for permission in CustomPermission::ALL { permissions[permission.json_key()] = json!(shown.contains(&permission)); } permissions } pub fn restore(&mut self) -> bool { if self.status < MembershipStatus::Invited as i32 { self.status += ACTIVATE_REVOKE_DIFF; return true; } false } pub fn revoke(&mut self) -> bool { if self.status > MembershipStatus::Revoked as i32 { self.status -= ACTIVATE_REVOKE_DIFF; return true; } false } /// Return the status of the user in an unrevoked state pub fn get_unrevoked_status(&self) -> i32 { if self.status <= MembershipStatus::Revoked as i32 { return self.status + ACTIVATE_REVOKE_DIFF; } self.status } pub fn set_external_id(&mut self, external_id: Option) -> 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; } false } } impl OrganizationApiKey { pub fn new(org_uuid: OrganizationId, api_key: String) -> Self { Self { uuid: OrgApiKeyId(crate::util::get_uuid()), org_uuid, atype: 0, // Type 0 is the default and only type we support currently api_key, revision_date: Utc::now().naive_utc(), } } pub fn check_valid_api_key(&self, api_key: &str) -> bool { crate::crypto::ct_eq(&self.api_key, api_key) } } /// Database methods impl Organization { pub async fn save(&self, conn: &DbConn) -> EmptyResult { if !crate::util::is_valid_email(&self.billing_email) { err!(format!("BillingEmail {} is not a valid email address", self.billing_email.escape_debug())) } for member in &Membership::find_by_org(&self.uuid, conn).await { User::update_uuid_revision(&member.user_uuid, conn).await; } db_run! { conn: mysql { diesel::insert_into(organizations::table) .values(self) .on_conflict(diesel::dsl::DuplicatedKeys) .do_update() .set(self) .execute(conn) .map_res("Error saving organization") } postgresql, sqlite { diesel::insert_into(organizations::table) .values(self) .on_conflict(organizations::uuid) .do_update() .set(self) .execute(conn) .map_res("Error saving organization") } } } pub async fn delete(self, conn: &DbConn) -> EmptyResult { Cipher::delete_all_by_organization(&self.uuid, conn).await?; Collection::delete_all_by_organization(&self.uuid, conn).await?; Membership::delete_all_by_organization(&self.uuid, conn).await?; OrgPolicy::delete_all_by_organization(&self.uuid, conn).await?; Group::delete_all_by_organization(&self.uuid, conn).await?; OrganizationApiKey::delete_all_by_organization(&self.uuid, conn).await?; conn.run(move |conn| { diesel::delete(organizations::table.filter(organizations::uuid.eq(self.uuid))) .execute(conn) .map_res("Error saving organization") }) .await } pub async fn find_by_uuid(uuid: &OrganizationId, conn: &DbConn) -> Option { conn.run(move |conn| organizations::table.filter(organizations::uuid.eq(uuid)).first::(conn).ok()).await } pub async fn find_by_name(name: &str, conn: &DbConn) -> Option { conn.run(move |conn| organizations::table.filter(organizations::name.eq(name)).first::(conn).ok()).await } pub async fn get_all(conn: &DbConn) -> Vec { conn.run(move |conn| organizations::table.load::(conn).expect("Error loading organizations")).await } pub async fn find_main_org_user_email(user_email: &str, conn: &DbConn) -> Option { let lower_mail = user_email.to_lowercase(); conn.run(move |conn| { organizations::table .inner_join(users_organizations::table.on(users_organizations::org_uuid.eq(organizations::uuid))) .inner_join(users::table.on(users::uuid.eq(users_organizations::user_uuid))) .filter(users::email.eq(lower_mail)) .filter(users_organizations::status.ne(MembershipStatus::Revoked as i32)) .order(users_organizations::atype.asc()) .select(organizations::all_columns) .first::(conn) .ok() }) .await } pub async fn find_org_user_email(user_email: &str, conn: &DbConn) -> Vec { let lower_mail = user_email.to_lowercase(); conn.run(move |conn| { organizations::table .inner_join(users_organizations::table.on(users_organizations::org_uuid.eq(organizations::uuid))) .inner_join(users::table.on(users::uuid.eq(users_organizations::user_uuid))) .filter(users::email.eq(lower_mail)) .filter(users_organizations::status.ne(MembershipStatus::Revoked as i32)) .order(users_organizations::atype.asc()) .select(organizations::all_columns) .load::(conn) .expect("Error loading user orgs") }) .await } } impl Membership { pub async fn to_json(&self, conn: &DbConn) -> Value { let org = Organization::find_by_uuid(&self.org_uuid, conn).await.unwrap(); let permissions = self.custom_permissions_json(); // https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Models/Response/ProfileOrganizationResponseModel.cs json!({ "id": self.org_uuid, "identifier": null, // Not supported "name": org.name, "seats": 20, // hardcoded maxEmailsCount in the web-vault "maxCollections": null, "usersGetPremium": true, "use2fa": true, "useDirectory": false, // Is supported, but this value isn't checked anywhere (yet) "useEvents": CONFIG.org_events_enabled(), "useGroups": CONFIG.org_groups_enabled(), "useTotp": true, "useScim": false, // Not supported (Not AGPLv3 Licensed) "usePolicies": true, "useApi": true, "selfHost": true, "hasPublicAndPrivateKeys": org.private_key.is_some() && org.public_key.is_some(), "resetPasswordEnrolled": self.reset_password_key.is_some(), "useResetPassword": CONFIG.mail_enabled(), "ssoBound": false, // Not supported "useSso": false, // Not supported "useKeyConnector": false, "useSecretsManager": false, // Not supported (Not AGPLv3 Licensed) "usePasswordManager": true, "useCustomPermissions": custom_roles_enabled(), "useActivateAutofillPolicy": false, "useAdminSponsoredFamilies": false, "useRiskInsights": false, // Not supported (Not AGPLv3 Licensed) "useDisableSMAdsForUsers": true, // Hide Secrets Manager ads "useInviteLinks": false, // Not (yet) supported "useMyItems": false, // Not (yet) supported "useOrganizationDomains": false, // Not supported (Linked to SSO) "usePam": false, // Not supported "usePhishingBlocker": false, "organizationUserId": self.uuid, "providerId": null, "providerName": null, "providerType": null, "familySponsorshipFriendlyName": null, "familySponsorshipAvailable": false, "productTierType": 3, // Enterprise tier "keyConnectorEnabled": false, "keyConnectorUrl": null, "familySponsorshipLastSyncDate": null, "familySponsorshipValidUntil": null, "familySponsorshipToDelete": null, "accessSecretsManager": false, "limitCollectionCreation": true, "limitCollectionDeletion": true, "limitItemDeletion": false, "allowAdminAccessToAllCollectionItems": true, "userIsClaimedByOrganization": false, // Means not managed via the Members UI, like SSO "permissions": permissions, "maxStorageGb": i16::MAX, // The value doesn't matter, we don't check server-side // These are per user "userId": self.user_uuid, // Accepted (not yet confirmed) members have no key yet; send null like upstream, not "" "key": (!self.akey.is_empty()).then_some(&self.akey), "status": self.status, "type": self.atype, "enabled": true, "object": "profileOrganization", }) } // Used by admins to view other members, so nothing here may depend on this member's status pub async fn to_json_details_for_admin( &self, include_collections: bool, include_groups: bool, conn: &DbConn, ) -> Value { let user = User::find_by_uuid(&self.user_uuid, conn).await.unwrap(); // Because BitWarden want the status to be -1 for revoked users we need to catch that here. // We subtract/add a number so we can restore/activate the user to it's previous state again. let status = if self.status < MembershipStatus::Revoked as i32 { MembershipStatus::Revoked as i32 } else { self.status }; let twofactor_enabled = !TwoFactor::find_by_user(&user.uuid, conn).await.is_empty(); let groups: Vec = if include_groups && CONFIG.org_groups_enabled() { GroupUser::find_by_member(&self.uuid, conn).await.iter().map(|gu| gu.groups_uuid.clone()).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. Vec::new() }; // Only the collections assigned directly are returned, the ones assigned via a group are returned via a special group endpoint let collections: Vec = if include_collections { CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn) .await .into_iter() .map(|cu| { json!({ "id": cu.collection_uuid, "readOnly": cu.read_only, "hidePasswords": cu.hide_passwords, "manage": cu.manage, }) }) .collect() } else { Vec::new() }; // Only return permissions if there are any, else Bitwarden will assume the defaults of all false let permissions = if self.shown_custom_permissions().is_empty() { json!(null) } else { self.custom_permissions_json() }; json!({ "id": self.uuid, "userId": self.user_uuid, "name": if self.get_unrevoked_status() >= MembershipStatus::Accepted as i32 { Some(user.name) } else { None }, "email": user.email, "externalId": self.external_id, "avatarColor": user.avatar_color, "groups": groups, "collections": collections, "status": status, "type": self.atype, "twoFactorEnabled": twofactor_enabled, "resetPasswordEnrolled": self.reset_password_key.is_some(), "hasMasterPassword": !user.password_hash.is_empty(), "permissions": permissions, "ssoBound": false, // Not supported "claimedByOrganization": false, // Means not managed via the Members UI, like SSO "usesKeyConnector": false, // Not supported "accessSecretsManager": false, // Not supported (Not AGPLv3 Licensed) "object": "organizationUserUserDetails", }) } pub fn to_json_user_access_restrictions(&self, col_user: &CollectionUser) -> Value { json!({ "id": self.uuid, "readOnly": col_user.read_only, "hidePasswords": col_user.hide_passwords, "manage": col_user.manage, }) } pub async fn to_json_details(&self, conn: &DbConn) -> Value { let coll_uuids: Vec = CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn) .await .iter() .map(|cu| { json!({ "id": cu.collection_uuid, "readOnly": cu.read_only, "hidePasswords": cu.hide_passwords, "manage": cu.manage, }) }) .collect(); // Because BitWarden want the status to be -1 for revoked users we need to catch that here. // We subtract/add a number so we can restore/activate the user to it's previous state again. let status = if self.status < MembershipStatus::Revoked as i32 { MembershipStatus::Revoked as i32 } else { self.status }; json!({ "id": self.uuid, "userId": self.user_uuid, "status": status, "type": self.atype, "collections": coll_uuids, "object": "organizationUserDetails", }) } pub async fn to_json_mini_details(&self, conn: &DbConn) -> Value { let user = User::find_by_uuid(&self.user_uuid, conn).await.unwrap(); // Because Bitwarden wants the status to be -1 for revoked users we need to catch that here. // We subtract/add a number so we can restore/activate the user to it's previous state again. let status = if self.status < MembershipStatus::Revoked as i32 { MembershipStatus::Revoked as i32 } else { self.status }; json!({ "id": self.uuid, "userId": self.user_uuid, "type": self.atype, "status": status, "name": user.name, "email": user.email, "object": "organizationUserUserMiniDetails", }) } pub async fn save(&self, conn: &DbConn) -> EmptyResult { User::update_uuid_revision(&self.user_uuid, conn).await; db_run! { conn: mysql { diesel::insert_into(users_organizations::table) .values(self) .on_conflict(diesel::dsl::DuplicatedKeys) .do_update() .set(self) .execute(conn) .map_res("Error adding user to organization") } postgresql, sqlite { diesel::insert_into(users_organizations::table) .values(self) .on_conflict(users_organizations::uuid) .do_update() .set(self) .execute(conn) .map_res("Error adding user to organization") } } } pub async fn delete(self, conn: &DbConn) -> EmptyResult { User::update_uuid_revision(&self.user_uuid, conn).await; CollectionUser::delete_all_by_user_and_org(&self.user_uuid, &self.org_uuid, conn).await?; GroupUser::delete_all_by_member(&self.uuid, conn).await?; conn.run(move |conn| { diesel::delete(users_organizations::table.filter(users_organizations::uuid.eq(self.uuid))) .execute(conn) .map_res("Error removing user from organization") }) .await } pub async fn delete_all_by_organization(org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult { for member in Self::find_by_org(org_uuid, conn).await { member.delete(conn).await?; } Ok(()) } pub async fn delete_all_by_user(user_uuid: &UserId, conn: &DbConn) -> EmptyResult { for member in Self::find_any_state_by_user(user_uuid, conn).await { member.delete(conn).await?; } Ok(()) } pub async fn find_by_email_and_org(email: &str, org_uuid: &OrganizationId, conn: &DbConn) -> Option { 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 { return Some(member); } None } pub fn has_status(&self, status: MembershipStatus) -> bool { self.status == status as i32 } pub fn has_type(&self, user_type: MembershipType) -> bool { self.atype == user_type as i32 } /// Whether this member has authority over the whole organization: a confirmed Owner or Admin. Like upstream, it only /// counts in the Admin Console. Their own vault has the collections they are assigned to, with the access they are /// assigned, as everyone's. pub fn has_full_access(&self) -> bool { self.atype >= MembershipType::Admin && self.has_status(MembershipStatus::Confirmed) } /// Whether this member may edit every collection and the items in them in the Admin Console: every member with /// full access, and a Custom member with Edit any collection. Neither adds anything to the member's own vault. pub fn can_edit_any_collection(&self) -> bool { self.has_full_access() || self.has_custom_permission(CustomPermission::EditAnyCollection) } /// Whether this member may see every collection and who has access to them in the Admin Console. Deleting any /// collection needs that, but not the items in them. pub fn can_view_all_collections(&self) -> bool { self.can_edit_any_collection() || self.has_custom_permission(CustomPermission::DeleteAnyCollection) } /// Whether this member may read every collection's member and group assignments in the Admin Console. /// Manage users grants this access without granting the plain all-collections listing or metadata editing. pub fn can_view_all_collection_access_details(&self) -> bool { self.can_view_all_collections() || self.has_custom_permission(CustomPermission::ManageUsers) } /// Whether the member may list all organization collections in the Admin Console. This endpoint returns /// collection metadata without user or group access details. Group management and import/export need the /// complete collection list, but neither permission grants individual collection editing or cipher access. pub fn can_list_all_collections(&self) -> bool { self.can_view_all_collections() || self.has_custom_permission(CustomPermission::ManageGroups) || self.has_custom_permission(CustomPermission::AccessImportExport) } /// Whether this member may list every cipher of the organization in the Admin Console, like Bitwarden's /// CanAccessAllCiphers: every member who may edit any collection, and a Custom member with Access import/export /// (the export holds every cipher anyway) or Access reports (the reports run on every cipher). The list adds /// nothing to the member's own vault. pub fn can_list_all_ciphers(&self) -> bool { self.can_edit_any_collection() || self.has_custom_permission(CustomPermission::AccessImportExport) || self.has_custom_permission(CustomPermission::AccessReports) } pub async fn find_by_uuid(uuid: &MembershipId, conn: &DbConn) -> Option { conn.run(move |conn| { users_organizations::table.filter(users_organizations::uuid.eq(uuid)).first::(conn).ok() }) .await } pub async fn find_by_uuid_and_org(uuid: &MembershipId, org_uuid: &OrganizationId, conn: &DbConn) -> Option { conn.run(move |conn| { users_organizations::table .filter(users_organizations::uuid.eq(uuid)) .filter(users_organizations::org_uuid.eq(org_uuid)) .first::(conn) .ok() }) .await } pub async fn find_confirmed_by_user(user_uuid: &UserId, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .load::(conn) .unwrap_or_default() }) .await } pub async fn find_accepted_and_confirmed_by_user(user_uuid: &UserId, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .filter( users_organizations::status .eq(MembershipStatus::Accepted as i32) .or(users_organizations::status.eq(MembershipStatus::Confirmed as i32)), ) .load::(conn) .unwrap_or_default() }) .await } pub async fn find_invited_by_user(user_uuid: &UserId, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .filter(users_organizations::status.eq(MembershipStatus::Invited as i32)) .load::(conn) .unwrap_or_default() }) .await } // Should be used only when email are disabled. // In Organizations::send_invite status is set to Accepted only if the user has a password. pub async fn accept_user_invitations(user_uuid: &UserId, conn: &DbConn) -> EmptyResult { conn.run(move |conn| { diesel::update(users_organizations::table) .filter(users_organizations::user_uuid.eq(user_uuid)) .filter(users_organizations::status.eq(MembershipStatus::Invited as i32)) .set(users_organizations::status.eq(MembershipStatus::Accepted as i32)) .execute(conn) .map_res("Error confirming invitations") }) .await } pub async fn find_any_state_by_user(user_uuid: &UserId, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .load::(conn) .unwrap_or_default() }) .await } pub async fn count_accepted_and_confirmed_by_user( user_uuid: &UserId, excluded_org: &OrganizationId, conn: &DbConn, ) -> i64 { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .filter(users_organizations::org_uuid.ne(excluded_org)) .filter( users_organizations::status .eq(MembershipStatus::Accepted as i32) .or(users_organizations::status.eq(MembershipStatus::Confirmed as i32)), ) .count() .first::(conn) .unwrap_or(0) }) .await } /// Counts the user's accepted and confirmed memberships in other organizations, revoked ones included, which is /// what Bitwarden's Single organization policy counts, both when it is enabled and when a member joins. pub async fn count_accepted_confirmed_or_revoked_by_user( user_uuid: &UserId, excluded_org: &OrganizationId, conn: &DbConn, ) -> i64 { let statuses = [ MembershipStatus::Accepted as i32, MembershipStatus::Confirmed as i32, MembershipStatus::Accepted as i32 - ACTIVATE_REVOKE_DIFF, MembershipStatus::Confirmed as i32 - ACTIVATE_REVOKE_DIFF, ]; conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .filter(users_organizations::org_uuid.ne(excluded_org)) .filter(users_organizations::status.eq_any(statuses)) .count() .first::(conn) .unwrap_or(0) }) .await } pub async fn find_by_org(org_uuid: &OrganizationId, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::org_uuid.eq(org_uuid)) .load::(conn) .expect("Error loading user organizations") }) .await } pub async fn count_by_org(org_uuid: &OrganizationId, conn: &DbConn) -> i64 { conn.run(move |conn| { users_organizations::table .filter(users_organizations::org_uuid.eq(org_uuid)) .count() .first::(conn) .ok() .unwrap_or(0) }) .await } pub async fn find_by_org_and_type(org_uuid: &OrganizationId, atype: MembershipType, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::org_uuid.eq(org_uuid)) .filter(users_organizations::atype.eq(atype as i32)) .load::(conn) .expect("Error loading user organizations") }) .await } /// The most account recovery V2 upgrades one request reads or writes, like upstream's /// `OrganizationUserV2UpgradesRequestModel.MaxUpgrades`. pub const MAX_V2_UPGRADES: i64 = 100; /// The next page of memberships of this organization whose account recovery key the admin still has to re-wrap /// with the member's V2 user key: enrolled, carrying an upgrade token, of a user with a key id (the re-wrapped key /// is checked against it), and Owners only for an Owner. Ordered by id, after `after`, at most `MAX_V2_UPGRADES`. pub async fn find_pending_v2_upgrades( org_uuid: &OrganizationId, include_owners: bool, after: Option<&MembershipId>, conn: &DbConn, ) -> Vec { conn.run(move |conn| { let mut query = users_organizations::table .inner_join(users::table) .filter(users_organizations::org_uuid.eq(org_uuid)) .filter(users_organizations::v2_upgrade_token.is_not_null()) .filter(users_organizations::reset_password_key.is_not_null()) .filter(users::key_id.is_not_null()) .into_boxed(); if !include_owners { query = query.filter(users_organizations::atype.ne(MembershipType::Owner as i32)); } if let Some(after) = after { query = query.filter(users_organizations::uuid.gt(after)); } query .order(users_organizations::uuid) .limit(Self::MAX_V2_UPGRADES) // The filters above make sure these are set .select(( users_organizations::uuid, users::key_id.assume_not_null(), users_organizations::reset_password_key.assume_not_null(), users_organizations::v2_upgrade_token.assume_not_null(), )) .load(conn) .unwrap_or_default() }) .await } /// Replaces the account recovery key of a member who upgraded to V2 encryption with `account_recovery_key`, or /// unenrolls them when it is `None`, and consumes the upgrade token, so it can't be replayed. Only while the /// membership is still enrolled, carrying the token, not an Owner unless `include_owners`, and its user's key id is /// still `user_key_id` (the key the new recovery key wraps). Returns whether it applied, otherwise the membership /// stays pending. It runs inside a transaction, so it leaves the user's revision to the caller. pub async fn apply_v2_upgrade( &self, include_owners: bool, user_key_id: &KeyId, account_recovery_key: Option<&str>, conn: &DbConn, ) -> Result { // An empty list excludes no one let excluded = if include_owners { vec![] } else { vec![MembershipType::Owner as i32] }; let rows: usize = conn .run(move |conn| { diesel::update( users_organizations::table .filter(users_organizations::uuid.eq(&self.uuid)) .filter(users_organizations::v2_upgrade_token.is_not_null()) .filter(users_organizations::reset_password_key.is_not_null()) .filter(users_organizations::atype.ne_all(excluded)) .filter(diesel::dsl::exists( users::table.filter(users::uuid.eq(&self.user_uuid)).filter(users::key_id.eq(user_key_id)), )), ) .set(( users_organizations::reset_password_key.eq(account_recovery_key), users_organizations::v2_upgrade_token.eq(None::), )) .execute(conn) .map_res("Error saving membership") }) .await?; Ok(rows > 0) } pub async fn count_confirmed_by_org_and_type( org_uuid: &OrganizationId, atype: MembershipType, conn: &DbConn, ) -> i64 { conn.run(move |conn| { users_organizations::table .filter(users_organizations::org_uuid.eq(org_uuid)) .filter(users_organizations::atype.eq(atype as i32)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .count() .first::(conn) .unwrap_or(0) }) .await } pub async fn find_by_user_and_org(user_uuid: &UserId, org_uuid: &OrganizationId, conn: &DbConn) -> Option { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .filter(users_organizations::org_uuid.eq(org_uuid)) .first::(conn) .ok() }) .await } pub async fn find_confirmed_by_user_and_org( user_uuid: &UserId, org_uuid: &OrganizationId, conn: &DbConn, ) -> Option { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .filter(users_organizations::org_uuid.eq(org_uuid)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .first::(conn) .ok() }) .await } pub async fn find_by_user(user_uuid: &UserId, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .load::(conn) .expect("Error loading user organizations") }) .await } /// The user's accepted and confirmed memberships in organizations that have enabled `policy_type`. pub async fn find_by_user_and_policy(user_uuid: &UserId, policy_type: OrgPolicyType, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .inner_join( org_policies::table.on(org_policies::org_uuid .eq(users_organizations::org_uuid) .and(users_organizations::user_uuid.eq(user_uuid)) .and(org_policies::atype.eq(policy_type as i32)) .and(org_policies::enabled.eq(true))), ) .filter( users_organizations::status .eq(MembershipStatus::Accepted as i32) .or(users_organizations::status.eq(MembershipStatus::Confirmed as i32)), ) .select(users_organizations::all_columns) .load::(conn) .unwrap_or_default() }) .await } pub async fn find_by_cipher_and_org(cipher_uuid: &CipherId, org_uuid: &OrganizationId, conn: &DbConn) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::org_uuid.eq(org_uuid)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .left_join(users_collections::table.on(users_collections::user_uuid.eq(users_organizations::user_uuid))) .left_join( ciphers_collections::table.on(ciphers_collections::collection_uuid .eq(users_collections::collection_uuid) .and(ciphers_collections::cipher_uuid.eq(&cipher_uuid))), ) .filter(ciphers_collections::cipher_uuid.eq(&cipher_uuid)) // Access to a collection with the cipher .select(users_organizations::all_columns) .distinct() .load::(conn) .expect("Error loading user organizations") }) .await } pub async fn find_by_cipher_and_org_with_group( cipher_uuid: &CipherId, org_uuid: &OrganizationId, conn: &DbConn, ) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::org_uuid.eq(org_uuid)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .inner_join( groups_users::table.on(groups_users::users_organizations_uuid.eq(users_organizations::uuid)), ) .left_join(collections_groups::table.on(collections_groups::groups_uuid.eq(groups_users::groups_uuid))) .left_join( groups::table.on(groups::uuid .eq(groups_users::groups_uuid) .and(groups::organizations_uuid.eq(users_organizations::org_uuid))), ) .left_join( ciphers_collections::table.on(ciphers_collections::collection_uuid .eq(collections_groups::collections_uuid) .and(ciphers_collections::cipher_uuid.eq(&cipher_uuid))), ) .filter(ciphers_collections::cipher_uuid.eq(&cipher_uuid)) // Access to a collection via a group .select(users_organizations::all_columns) .distinct() .load::(conn) .expect("Error loading user organizations with groups") }) .await } pub async fn find_by_collection_and_org( collection_uuid: &CollectionId, org_uuid: &OrganizationId, conn: &DbConn, ) -> Vec { conn.run(move |conn| { users_organizations::table .filter(users_organizations::org_uuid.eq(org_uuid)) .left_join(users_collections::table.on(users_collections::user_uuid.eq(users_organizations::user_uuid))) .filter(users_collections::collection_uuid.eq(&collection_uuid)) // Access to the collection .select(users_organizations::all_columns) .load::(conn) .expect("Error loading user organizations") }) .await } pub async fn find_by_external_id_and_org(ext_id: &str, org_uuid: &OrganizationId, conn: &DbConn) -> Option { conn.run(move |conn| { users_organizations::table .filter(users_organizations::external_id.eq(ext_id).and(users_organizations::org_uuid.eq(org_uuid))) .first::(conn) .ok() }) .await } pub async fn find_main_user_org(user_uuid: &str, conn: &DbConn) -> Option { conn.run(move |conn| { users_organizations::table .filter(users_organizations::user_uuid.eq(user_uuid)) .filter(users_organizations::status.ne(MembershipStatus::Revoked as i32)) .order(users_organizations::atype.asc()) .first::(conn) .ok() }) .await } } impl OrganizationApiKey { pub async fn save(&self, conn: &DbConn) -> EmptyResult { db_run! { conn: mysql { diesel::insert_into(organization_api_key::table) .values(self) .on_conflict(diesel::dsl::DuplicatedKeys) .do_update() .set(self) .execute(conn) .map_res("Error saving organization") } postgresql, sqlite { diesel::insert_into(organization_api_key::table) .values(self) .on_conflict((organization_api_key::uuid, organization_api_key::org_uuid)) .do_update() .set(self) .execute(conn) .map_res("Error saving organization") } } } pub async fn find_by_org_uuid(org_uuid: &OrganizationId, conn: &DbConn) -> Option { conn.run(move |conn| { organization_api_key::table.filter(organization_api_key::org_uuid.eq(org_uuid)).first::(conn).ok() }) .await } pub async fn delete_all_by_organization(org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult { conn.run(move |conn| { diesel::delete(organization_api_key::table.filter(organization_api_key::org_uuid.eq(org_uuid))) .execute(conn) .map_res("Error removing organization api key from organization") }) .await } } #[derive( Clone, Debug, AsRef, Deref, DieselNewType, Display, From, FromForm, Hash, PartialEq, Eq, Serialize, Deserialize, UuidFromParam, )] #[deref(forward)] #[from(forward)] pub struct OrganizationId(String); #[derive( Clone, Debug, Deref, DieselNewType, Display, From, FromForm, Hash, PartialEq, Eq, Serialize, Deserialize, UuidFromParam, )] pub struct MembershipId(String); #[derive(Clone, Debug, DieselNewType, Display, FromForm, Hash, PartialEq, Eq, Serialize, Deserialize)] pub struct OrgApiKeyId(String); #[cfg(test)] mod tests { use super::*; use CustomPermission::*; use MembershipType::{Admin, Custom, Owner, User}; fn member(role: MembershipType) -> Membership { let mut member = Membership::new("user".into(), "org".into(), None); member.atype = role as i32; member.status = MembershipStatus::Confirmed as i32; member } #[test] fn membership_type_authority() { assert!(Owner > Admin && Admin > Custom && Custom > User); assert!((Custom as i32) >= User && (Custom as i32) < Admin); for raw in [99, 3, -1] { assert_eq!((raw >= User, raw >= Admin, raw < Admin), (false, false, true)); } for (value, expected) in [("3", None), ("Manager", None), ("4", Some(Custom)), ("Custom", Some(Custom)), ("5", None)] { assert_eq!(MembershipType::from_str(value), expected); } } #[test] fn requested_membership_type() { for enabled in [false, true] { test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled)); for current in [None, Some(User), Some(Admin), Some(Custom)] { let current = current.map(member); for requested in [Owner, Admin, User, Custom] { let allowed = requested != Custom || enabled || current.as_ref().is_some_and(|m| m.atype == 4); let result = MembershipType::check_requested(requested, current.as_ref()); assert_eq!(result.is_ok(), allowed, "{enabled} {requested:?}"); } } } test_flag::CUSTOM_ROLES_ENABLED.set(None); } #[test] fn custom_permission_requests() { let ignored = serde_json::from_value(json!({"manageUsers":false,"manageSso":true})).unwrap(); assert!(CustomPermission::requested(&ignored).unwrap().is_empty()); for permission in CustomPermission::ALL { for value in [json!(true), json!(null), json!("true"), json!(1), json!([true])] { let request = HashMap::from([(permission.json_key().to_owned(), value.clone())]); let result = CustomPermission::requested(&request); if value == json!(true) && SUPPORTED_CUSTOM_PERMISSIONS.contains(&permission) { assert_eq!(result.unwrap(), HashSet::from([permission])); } else { assert!(result.is_err(), "{permission:?}: {value}"); } } } assert_eq!( SUPPORTED_CUSTOM_PERMISSIONS, [ ManageUsers, ManageGroups, ManagePolicies, CreateNewCollections, EditAnyCollection, DeleteAnyCollection, AccessEventLogs, AccessImportExport, AccessReports, ManageResetPassword ] ); } #[test] fn role_changes_drop_custom_permissions() { for (from, to) in [(Custom, Owner), (Custom, Admin), (Custom, User), (User, Custom), (Custom, Custom), (Admin, User)] { let mut member = member(from); for permission in CustomPermission::ALL { *member.custom_permission_mut(permission) = true; } member.set_type(to); for permission in CustomPermission::ALL { assert_eq!(*member.custom_permission_mut(permission), from == to, "{from:?} -> {to:?}"); } } } #[test] fn permission_matrix_preserves_role_status_flag_and_collection_boundaries() { for role in [Owner, Admin, Custom, User] { for permission in CustomPermission::ALL { let mut member = member(role); *member.custom_permission_mut(permission) = true; for enabled in [false, true] { test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled)); let shown = if role == Custom && enabled && permission.is_supported() { HashSet::from([permission]) } else { HashSet::new() }; assert_eq!(member.shown_custom_permissions(), shown); for status in [-128, -127, -126, -3, -2, -1, 0, 1, 2] { member.status = status; let allowed = enabled && role == Custom && status == 2 && permission.is_supported(); let full = status == 2 && (role == Owner || role == Admin); let edit = full || (allowed && permission == EditAnyCollection); let view = full || (allowed && matches!(permission, EditAnyCollection | DeleteAnyCollection)); assert_eq!( ( member.has_custom_permission(permission), member.can_edit_any_collection(), member.can_view_all_collections() ), (allowed, edit, view), "{role:?} {enabled} {status} {permission:?}" ); assert_eq!( (member.can_list_all_collections(), member.can_list_all_ciphers()), ( view || (allowed && matches!(permission, ManageGroups | AccessImportExport)), edit || (allowed && matches!(permission, AccessImportExport | AccessReports)) ), "{role:?} {enabled} {status} {permission:?}" ); } } } } for raw in [99, -1] { let mut member = member(Custom); member.atype = raw; for p in CustomPermission::ALL { *member.custom_permission_mut(p) = true; } for enabled in [false, true] { test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled)); assert!(CustomPermission::ALL.into_iter().all(|p| !member.has_custom_permission(p))); assert!(!member.can_edit_any_collection() && !member.can_view_all_collections()); assert!(!member.can_list_all_collections() && !member.can_list_all_ciphers()); } } let empty = member(Custom); assert!(!empty.can_edit_any_collection() && !empty.can_view_all_collections()); assert!(empty.shown_custom_permissions().is_empty()); assert!(!empty.can_list_all_collections() && !empty.can_list_all_ciphers()); test_flag::CUSTOM_ROLES_ENABLED.set(None); } }