From c82156a166408762c0b6dd51b196627e9d8fabbd Mon Sep 17 00:00:00 2001 From: tom27052006 <83423411+tom27052006@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:58:33 +0100 Subject: [PATCH] Remove access all and the legacy Manager role --- .../down.sql | 6 + .../up.sql | 62 +++ .../down.sql | 6 + .../up.sql | 62 +++ .../down.sql | 6 + .../up.sql | 62 +++ src/api/admin.rs | 34 +- src/api/core/ciphers.rs | 34 +- src/api/core/organizations.rs | 380 ++++++------------ src/api/core/public.rs | 3 +- src/auth.rs | 74 ++-- src/db/mod.rs | 273 ++++++++++++- src/db/models/cipher.rs | 130 ++---- src/db/models/collection.rs | 358 +++-------------- src/db/models/group.rs | 106 ++--- src/db/models/mod.rs | 2 +- src/db/models/organization.rs | 297 +++----------- src/db/schema.rs | 2 - src/static/scripts/admin_users.js | 4 - src/static/templates/admin/users.hbs | 3 - .../templates/scss/vaultwarden.scss.hbs | 4 +- 21 files changed, 833 insertions(+), 1075 deletions(-) create mode 100644 migrations/mysql/2026-11-15-140000_remove_access_all/down.sql create mode 100644 migrations/mysql/2026-11-15-140000_remove_access_all/up.sql create mode 100644 migrations/postgresql/2026-11-15-140000_remove_access_all/down.sql create mode 100644 migrations/postgresql/2026-11-15-140000_remove_access_all/up.sql create mode 100644 migrations/sqlite/2026-11-15-140000_remove_access_all/down.sql create mode 100644 migrations/sqlite/2026-11-15-140000_remove_access_all/up.sql diff --git a/migrations/mysql/2026-11-15-140000_remove_access_all/down.sql b/migrations/mysql/2026-11-15-140000_remove_access_all/down.sql new file mode 100644 index 00000000..2c485c39 --- /dev/null +++ b/migrations/mysql/2026-11-15-140000_remove_access_all/down.sql @@ -0,0 +1,6 @@ +-- The memberships and groups keep the explicit assignments the upgrade gave them. Owners and Admins get the access to +-- all collections back that they always had before, which the older versions need to show them every collection. The +-- Managers stay Users who manage their collections. +ALTER TABLE users_organizations ADD COLUMN access_all BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE `groups` ADD COLUMN access_all BOOLEAN NOT NULL DEFAULT FALSE; +UPDATE users_organizations SET access_all = TRUE WHERE atype IN (0, 1); diff --git a/migrations/mysql/2026-11-15-140000_remove_access_all/up.sql b/migrations/mysql/2026-11-15-140000_remove_access_all/up.sql new file mode 100644 index 00000000..4c347a98 --- /dev/null +++ b/migrations/mysql/2026-11-15-140000_remove_access_all/up.sql @@ -0,0 +1,62 @@ +-- Removes the legacy "access all collections" flags and the legacy Manager role, like Bitwarden's +-- Organization_EnableCollectionEnhancements: whoever had access to all collections gets an explicit assignment to every +-- collection that exists now, and a Manager becomes a User who manages every collection they are assigned to. +-- Ref: https://github.com/bitwarden/server/blob/341acc9d3d8988cec8fe05debfa6d557cf5ab749/util/Migrator/DbScripts/2024-01-25_00_Organization_EnableCollectionEnhancements.sql + +-- Everyone whose access changes syncs again +UPDATE users SET updated_at = UTC_TIMESTAMP() +WHERE uuid IN (SELECT user_uuid FROM users_organizations WHERE access_all OR atype = 3) + OR uuid IN ( + SELECT uo.user_uuid FROM users_organizations uo + JOIN groups_users gu ON gu.users_organizations_uuid = uo.uuid + JOIN `groups` g ON g.uuid = gu.groups_uuid + WHERE g.access_all + ); + +-- Groups with access to all collections: read and write access to every collection. Bitwarden also cleared the manage +-- option here, which none of its organizations could have set yet. Vaultwarden has had it for a while, so it is kept. +UPDATE collections_groups SET read_only = FALSE, hide_passwords = FALSE +WHERE EXISTS ( + SELECT 1 FROM `groups` g JOIN collections c ON c.org_uuid = g.organizations_uuid + WHERE g.access_all AND g.uuid = collections_groups.groups_uuid AND c.uuid = collections_groups.collections_uuid +); +INSERT INTO collections_groups (collections_uuid, groups_uuid, read_only, hide_passwords, manage) +SELECT c.uuid, g.uuid, FALSE, FALSE, FALSE +FROM `groups` g JOIN collections c ON c.org_uuid = g.organizations_uuid +WHERE g.access_all + AND NOT EXISTS (SELECT 1 FROM collections_groups cg WHERE cg.collections_uuid = c.uuid AND cg.groups_uuid = g.uuid); +UPDATE `groups` SET revision_date = UTC_TIMESTAMP() WHERE access_all; + +-- Members with access to all collections: the same for them +UPDATE users_collections SET read_only = FALSE, hide_passwords = FALSE +WHERE EXISTS ( + SELECT 1 FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid + WHERE uo.access_all AND uo.user_uuid = users_collections.user_uuid AND c.uuid = users_collections.collection_uuid +); +INSERT INTO users_collections (user_uuid, collection_uuid, read_only, hide_passwords, manage) +SELECT uo.user_uuid, c.uuid, FALSE, FALSE, FALSE +FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid +WHERE uo.access_all + AND NOT EXISTS (SELECT 1 FROM users_collections uc WHERE uc.user_uuid = uo.user_uuid AND uc.collection_uuid = c.uuid); + +-- Managers, as in Bitwarden: every assignment of a Manager becomes read and write access with the manage option, and the +-- collections of their groups get such an assignment of their own, since the groups themselves don't get the option. +UPDATE users_collections SET read_only = FALSE, hide_passwords = FALSE, manage = TRUE +WHERE EXISTS ( + SELECT 1 FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid + WHERE uo.atype = 3 AND uo.user_uuid = users_collections.user_uuid AND c.uuid = users_collections.collection_uuid +); +INSERT INTO users_collections (user_uuid, collection_uuid, read_only, hide_passwords, manage) +SELECT DISTINCT uo.user_uuid, cg.collections_uuid, FALSE, FALSE, TRUE +FROM users_organizations uo +JOIN groups_users gu ON gu.users_organizations_uuid = uo.uuid +JOIN `groups` g ON g.uuid = gu.groups_uuid AND g.organizations_uuid = uo.org_uuid +JOIN collections_groups cg ON cg.groups_uuid = g.uuid +WHERE uo.atype = 3 + AND NOT EXISTS ( + SELECT 1 FROM users_collections uc WHERE uc.user_uuid = uo.user_uuid AND uc.collection_uuid = cg.collections_uuid + ); +UPDATE users_organizations SET atype = 2 WHERE atype = 3; + +ALTER TABLE `groups` DROP COLUMN access_all; +ALTER TABLE users_organizations DROP COLUMN access_all; diff --git a/migrations/postgresql/2026-11-15-140000_remove_access_all/down.sql b/migrations/postgresql/2026-11-15-140000_remove_access_all/down.sql new file mode 100644 index 00000000..6f6ef637 --- /dev/null +++ b/migrations/postgresql/2026-11-15-140000_remove_access_all/down.sql @@ -0,0 +1,6 @@ +-- The memberships and groups keep the explicit assignments the upgrade gave them. Owners and Admins get the access to +-- all collections back that they always had before, which the older versions need to show them every collection. The +-- Managers stay Users who manage their collections. +ALTER TABLE users_organizations ADD COLUMN access_all BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE groups ADD COLUMN access_all BOOLEAN NOT NULL DEFAULT FALSE; +UPDATE users_organizations SET access_all = TRUE WHERE atype IN (0, 1); diff --git a/migrations/postgresql/2026-11-15-140000_remove_access_all/up.sql b/migrations/postgresql/2026-11-15-140000_remove_access_all/up.sql new file mode 100644 index 00000000..eec946c2 --- /dev/null +++ b/migrations/postgresql/2026-11-15-140000_remove_access_all/up.sql @@ -0,0 +1,62 @@ +-- Removes the legacy "access all collections" flags and the legacy Manager role, like Bitwarden's +-- Organization_EnableCollectionEnhancements: whoever had access to all collections gets an explicit assignment to every +-- collection that exists now, and a Manager becomes a User who manages every collection they are assigned to. +-- Ref: https://github.com/bitwarden/server/blob/341acc9d3d8988cec8fe05debfa6d557cf5ab749/util/Migrator/DbScripts/2024-01-25_00_Organization_EnableCollectionEnhancements.sql + +-- Everyone whose access changes syncs again +UPDATE users SET updated_at = (now() AT TIME ZONE 'utc') +WHERE uuid IN (SELECT user_uuid FROM users_organizations WHERE access_all OR atype = 3) + OR uuid IN ( + SELECT uo.user_uuid FROM users_organizations uo + JOIN groups_users gu ON gu.users_organizations_uuid = uo.uuid + JOIN groups g ON g.uuid = gu.groups_uuid + WHERE g.access_all + ); + +-- Groups with access to all collections: read and write access to every collection. Bitwarden also cleared the manage +-- option here, which none of its organizations could have set yet. Vaultwarden has had it for a while, so it is kept. +UPDATE collections_groups SET read_only = FALSE, hide_passwords = FALSE +WHERE EXISTS ( + SELECT 1 FROM groups g JOIN collections c ON c.org_uuid = g.organizations_uuid + WHERE g.access_all AND g.uuid = collections_groups.groups_uuid AND c.uuid = collections_groups.collections_uuid +); +INSERT INTO collections_groups (collections_uuid, groups_uuid, read_only, hide_passwords, manage) +SELECT c.uuid, g.uuid, FALSE, FALSE, FALSE +FROM groups g JOIN collections c ON c.org_uuid = g.organizations_uuid +WHERE g.access_all + AND NOT EXISTS (SELECT 1 FROM collections_groups cg WHERE cg.collections_uuid = c.uuid AND cg.groups_uuid = g.uuid); +UPDATE groups SET revision_date = (now() AT TIME ZONE 'utc') WHERE access_all; + +-- Members with access to all collections: the same for them +UPDATE users_collections SET read_only = FALSE, hide_passwords = FALSE +WHERE EXISTS ( + SELECT 1 FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid + WHERE uo.access_all AND uo.user_uuid = users_collections.user_uuid AND c.uuid = users_collections.collection_uuid +); +INSERT INTO users_collections (user_uuid, collection_uuid, read_only, hide_passwords, manage) +SELECT uo.user_uuid, c.uuid, FALSE, FALSE, FALSE +FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid +WHERE uo.access_all + AND NOT EXISTS (SELECT 1 FROM users_collections uc WHERE uc.user_uuid = uo.user_uuid AND uc.collection_uuid = c.uuid); + +-- Managers, as in Bitwarden: every assignment of a Manager becomes read and write access with the manage option, and the +-- collections of their groups get such an assignment of their own, since the groups themselves don't get the option. +UPDATE users_collections SET read_only = FALSE, hide_passwords = FALSE, manage = TRUE +WHERE EXISTS ( + SELECT 1 FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid + WHERE uo.atype = 3 AND uo.user_uuid = users_collections.user_uuid AND c.uuid = users_collections.collection_uuid +); +INSERT INTO users_collections (user_uuid, collection_uuid, read_only, hide_passwords, manage) +SELECT DISTINCT uo.user_uuid, cg.collections_uuid, FALSE, FALSE, TRUE +FROM users_organizations uo +JOIN groups_users gu ON gu.users_organizations_uuid = uo.uuid +JOIN groups g ON g.uuid = gu.groups_uuid AND g.organizations_uuid = uo.org_uuid +JOIN collections_groups cg ON cg.groups_uuid = g.uuid +WHERE uo.atype = 3 + AND NOT EXISTS ( + SELECT 1 FROM users_collections uc WHERE uc.user_uuid = uo.user_uuid AND uc.collection_uuid = cg.collections_uuid + ); +UPDATE users_organizations SET atype = 2 WHERE atype = 3; + +ALTER TABLE groups DROP COLUMN access_all; +ALTER TABLE users_organizations DROP COLUMN access_all; diff --git a/migrations/sqlite/2026-11-15-140000_remove_access_all/down.sql b/migrations/sqlite/2026-11-15-140000_remove_access_all/down.sql new file mode 100644 index 00000000..ba69cd1d --- /dev/null +++ b/migrations/sqlite/2026-11-15-140000_remove_access_all/down.sql @@ -0,0 +1,6 @@ +-- The memberships and groups keep the explicit assignments the upgrade gave them. Owners and Admins get the access to +-- all collections back that they always had before, which the older versions need to show them every collection. The +-- Managers stay Users who manage their collections. +ALTER TABLE users_organizations ADD COLUMN access_all BOOLEAN NOT NULL DEFAULT 0; -- FALSE +ALTER TABLE groups ADD COLUMN access_all BOOLEAN NOT NULL DEFAULT 0; -- FALSE +UPDATE users_organizations SET access_all = TRUE WHERE atype IN (0, 1); diff --git a/migrations/sqlite/2026-11-15-140000_remove_access_all/up.sql b/migrations/sqlite/2026-11-15-140000_remove_access_all/up.sql new file mode 100644 index 00000000..e945f39a --- /dev/null +++ b/migrations/sqlite/2026-11-15-140000_remove_access_all/up.sql @@ -0,0 +1,62 @@ +-- Removes the legacy "access all collections" flags and the legacy Manager role, like Bitwarden's +-- Organization_EnableCollectionEnhancements: whoever had access to all collections gets an explicit assignment to every +-- collection that exists now, and a Manager becomes a User who manages every collection they are assigned to. +-- Ref: https://github.com/bitwarden/server/blob/341acc9d3d8988cec8fe05debfa6d557cf5ab749/util/Migrator/DbScripts/2024-01-25_00_Organization_EnableCollectionEnhancements.sql + +-- Everyone whose access changes syncs again +UPDATE users SET updated_at = CURRENT_TIMESTAMP +WHERE uuid IN (SELECT user_uuid FROM users_organizations WHERE access_all OR atype = 3) + OR uuid IN ( + SELECT uo.user_uuid FROM users_organizations uo + JOIN groups_users gu ON gu.users_organizations_uuid = uo.uuid + JOIN groups g ON g.uuid = gu.groups_uuid + WHERE g.access_all + ); + +-- Groups with access to all collections: read and write access to every collection. Bitwarden also cleared the manage +-- option here, which none of its organizations could have set yet. Vaultwarden has had it for a while, so it is kept. +UPDATE collections_groups SET read_only = FALSE, hide_passwords = FALSE +WHERE EXISTS ( + SELECT 1 FROM groups g JOIN collections c ON c.org_uuid = g.organizations_uuid + WHERE g.access_all AND g.uuid = collections_groups.groups_uuid AND c.uuid = collections_groups.collections_uuid +); +INSERT INTO collections_groups (collections_uuid, groups_uuid, read_only, hide_passwords, manage) +SELECT c.uuid, g.uuid, FALSE, FALSE, FALSE +FROM groups g JOIN collections c ON c.org_uuid = g.organizations_uuid +WHERE g.access_all + AND NOT EXISTS (SELECT 1 FROM collections_groups cg WHERE cg.collections_uuid = c.uuid AND cg.groups_uuid = g.uuid); +UPDATE groups SET revision_date = CURRENT_TIMESTAMP WHERE access_all; + +-- Members with access to all collections: the same for them +UPDATE users_collections SET read_only = FALSE, hide_passwords = FALSE +WHERE EXISTS ( + SELECT 1 FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid + WHERE uo.access_all AND uo.user_uuid = users_collections.user_uuid AND c.uuid = users_collections.collection_uuid +); +INSERT INTO users_collections (user_uuid, collection_uuid, read_only, hide_passwords, manage) +SELECT uo.user_uuid, c.uuid, FALSE, FALSE, FALSE +FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid +WHERE uo.access_all + AND NOT EXISTS (SELECT 1 FROM users_collections uc WHERE uc.user_uuid = uo.user_uuid AND uc.collection_uuid = c.uuid); + +-- Managers, as in Bitwarden: every assignment of a Manager becomes read and write access with the manage option, and the +-- collections of their groups get such an assignment of their own, since the groups themselves don't get the option. +UPDATE users_collections SET read_only = FALSE, hide_passwords = FALSE, manage = TRUE +WHERE EXISTS ( + SELECT 1 FROM users_organizations uo JOIN collections c ON c.org_uuid = uo.org_uuid + WHERE uo.atype = 3 AND uo.user_uuid = users_collections.user_uuid AND c.uuid = users_collections.collection_uuid +); +INSERT INTO users_collections (user_uuid, collection_uuid, read_only, hide_passwords, manage) +SELECT DISTINCT uo.user_uuid, cg.collections_uuid, FALSE, FALSE, TRUE +FROM users_organizations uo +JOIN groups_users gu ON gu.users_organizations_uuid = uo.uuid +JOIN groups g ON g.uuid = gu.groups_uuid AND g.organizations_uuid = uo.org_uuid +JOIN collections_groups cg ON cg.groups_uuid = g.uuid +WHERE uo.atype = 3 + AND NOT EXISTS ( + SELECT 1 FROM users_collections uc WHERE uc.user_uuid = uo.user_uuid AND uc.collection_uuid = cg.collections_uuid + ); +UPDATE users_organizations SET atype = 2 WHERE atype = 3; + +ALTER TABLE groups DROP COLUMN access_all; +ALTER TABLE users_organizations DROP COLUMN access_all; diff --git a/src/api/admin.rs b/src/api/admin.rs index 621601ad..89956928 100644 --- a/src/api/admin.rs +++ b/src/api/admin.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, env, sync::LazyLock}; +use std::{env, sync::LazyLock}; use reqwest::Method; use rocket::{ @@ -393,18 +393,6 @@ async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult = Membership::find_confirmed_by_user(&u.uuid, &conn) - .await - .into_iter() - .map(|member| (member.org_uuid.to_string(), member.atype)) - .collect(); - for org in usr["organizations"].as_array_mut().into_iter().flatten() { - if let Some(atype) = org["id"].as_str().and_then(|org_id| roles.get(org_id)) { - org["type"] = json!(atype); - } - } - users_json.push(usr); } @@ -580,15 +568,10 @@ async fn update_membership_type(data: Json, token: AdminToke err!("The specified user isn't member of the organization") }; - let new_type = match MembershipType::from_str(&data.user_type.into_string()) { - // Unlike the clients, the admin panel tells the Custom and the legacy Manager role apart. Unless Custom roles - // are enabled, a Custom role is a Manager here as well, but an existing Custom member is kept as one. - Some(MembershipType::Custom) if !custom_roles_enabled() && !member_to_edit.has_type(MembershipType::Custom) => { - MembershipType::Manager - } - Some(new_type) => new_type, - None => err!("Invalid type"), + let Some(new_type) = MembershipType::from_str(&data.user_type.into_string()) else { + err!("Invalid type") }; + MembershipType::check_requested(new_type, Some(&member_to_edit))?; if member_to_edit.atype == MembershipType::Owner && new_type != MembershipType::Owner { // Removing owner permission, check that there is at least one other confirmed owner @@ -597,15 +580,6 @@ async fn update_membership_type(data: Json, token: AdminToke } } - // A Manager only becomes a Custom member if that changes nothing they may do. Here they would keep the permissions - // they are shown with, the admin panel can't give up their access to all collections, so that is refused. - if new_type == MembershipType::Custom - && let Some(loss) = - member_to_edit.custom_role_conversion_loss(&member_to_edit.legacy_manager_permissions(), &conn).await - { - err!(loss) - } - member_to_edit.set_type(new_type); // This check is also done at api::organizations::{accept_invite, _confirm_invite, _activate_member, edit_member}, update_membership_type OrgPolicy::check_user_allowed(&member_to_edit, "modify", &conn).await?; diff --git a/src/api/core/ciphers.rs b/src/api/core/ciphers.rs index 78c27b39..442651e7 100644 --- a/src/api/core/ciphers.rs +++ b/src/api/core/ciphers.rs @@ -23,8 +23,8 @@ use crate::{ models::{ Archive, Attachment, AttachmentId, Cipher, CipherAccessScope, CipherId, Collection, CollectionCipher, CollectionGroup, CollectionId, CollectionUser, CustomPermission, EventType, Favorite, Folder, FolderCipher, - FolderId, Group, KeyId, Membership, MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, - Send, User, UserId, is_data_blob_encrypted, + FolderId, KeyId, Membership, MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, Send, + User, UserId, is_data_blob_encrypted, }, }, util::{NumberOrString, deser_opt_nonempty_str, save_temp_file}, @@ -2731,7 +2731,6 @@ pub struct CipherSyncData { pub members: HashMap, pub user_collections: HashMap, pub user_collections_groups: HashMap, - pub user_group_full_access_for_organizations: HashSet, } #[derive(Eq, PartialEq)] @@ -2817,13 +2816,6 @@ impl CipherSyncData { HashMap::new() }; - // Get all organizations that the given user has full access to via group assignment - let user_group_full_access_for_organizations: HashSet = if CONFIG.org_groups_enabled() { - Group::get_orgs_by_user_with_full_access(user_id, conn).await.into_iter().collect() - } else { - HashSet::new() - }; - Self { cipher_attachments, cipher_folders, @@ -2833,7 +2825,6 @@ impl CipherSyncData { members, user_collections, user_collections_groups, - user_group_full_access_for_organizations, } } } @@ -2946,19 +2937,16 @@ mod custom_role_tests { for request in [None, Some(false)] { assert_eq!(CipherAccessScope::requested(request), CipherAccessScope::User); } - for (role, status, all, allowed) in [ - (MembershipType::User, 2, false, false), - (MembershipType::Custom, 2, false, false), - (MembershipType::Manager, 2, false, false), - (MembershipType::Manager, 2, true, true), - (MembershipType::Owner, 2, false, true), - (MembershipType::Admin, 2, false, true), - (MembershipType::Admin, 1, false, false), - (MembershipType::Admin, -126, false, false), + for (role, status, allowed) in [ + (MembershipType::User, 2, false), + (MembershipType::Custom, 2, false), + (MembershipType::Owner, 2, true), + (MembershipType::Admin, 2, true), + (MembershipType::Admin, 1, false), + (MembershipType::Admin, -126, false), ] { member.set_type(role); member.status = status; - member.access_all = all; member.save(&conn).await.unwrap(); assert_eq!( CipherAccessScope::for_member(Some(&member)), @@ -2970,10 +2958,12 @@ mod custom_role_tests { ); for org_id in [&org.uuid, &foreign.uuid] { cipher.organization_uuid = Some(org_id.clone()); + // Like Bitwarden, an Owner or Admin only reaches a cipher they aren't assigned to on the + // administrative routes for scope in [CipherAccessScope::User, admin_scope] { assert_eq!( cipher.is_write_accessible_to_user(&user.uuid, scope, &conn).await, - allowed && org_id == &org.uuid + allowed && org_id == &org.uuid && scope == admin_scope ); } } diff --git a/src/api/core/organizations.rs b/src/api/core/organizations.rs index ee2165a0..137f21b5 100644 --- a/src/api/core/organizations.rs +++ b/src/api/core/organizations.rs @@ -14,17 +14,17 @@ use crate::{ auth::{ AccessImportExportHeaders, AdminHeaders, CollectionAction, CollectionDeleteHeaders, CollectionReadHeaders, CollectionUsersReadHeaders, Headers, ManageGroupsHeaders, ManagePoliciesHeaders, ManageResetPasswordHeaders, - ManageUsersHeaders, ManagerHeaders, ManagerHeadersLoose, OrgMemberHeaders, OwnerHeaders, custom_member_may, - decode_invite, + ManageUsersHeaders, ManagerHeaders, ManagerHeadersLoose, OrgMemberHeaders, OwnerHeaders, decode_invite, + member_may, }, db::{ DbConn, models::{ Cipher, CipherAccessScope, CipherId, Collection, CollectionCipher, CollectionGroup, CollectionId, - CollectionUser, CustomPermission, Device, EventType, FillAssistPolicyData, Group, GroupId, GroupUser, - Invitation, KeyId, Membership, MembershipId, MembershipStatus, MembershipType, OrgPolicy, OrgPolicyType, - Organization, OrganizationApiKey, OrganizationId, TwoFactor, TwoFactorType, User, UserId, - custom_roles_enabled, + CollectionMembership, CollectionUser, CustomPermission, Device, EventType, FillAssistPolicyData, Group, + GroupId, GroupUser, Invitation, KeyId, Membership, MembershipId, MembershipStatus, MembershipType, + OrgPolicy, OrgPolicyType, Organization, OrganizationApiKey, OrganizationId, TwoFactor, TwoFactorType, User, + UserId, custom_roles_enabled, }, }, mail, @@ -217,13 +217,14 @@ async fn create_organization(headers: Headers, data: Json, conn: DbConn let collection = Collection::new(org.uuid.clone(), data.collection_name, None); member.akey = data.key; - member.access_all = true; member.atype = MembershipType::Owner as i32; member.status = MembershipStatus::Confirmed as i32; org.save(&conn).await?; member.save(&conn).await?; collection.save(&conn).await?; + // Like upstream, the owner manages the default collection, which puts it in their vault + CollectionUser::save(&member.user_uuid, &collection.uuid, false, false, true, &conn).await?; Ok(Json(org.to_json())) } @@ -375,8 +376,8 @@ async fn get_org_collections(org_id: OrganizationId, headers: ManagerHeadersLoos let collections = if headers.membership.can_list_all_collections() { get_org_collections_impl(&org_id, &conn).await - } else if headers.membership.has_type(MembershipType::Custom) { - // A Custom member gets the collections they may manage + } else { + // Everyone else gets the collections they manage let manageable = Collection::find_explicitly_manageable_by_user(&org_id, &headers.membership.user_uuid, &conn).await; Collection::find_by_organization(&org_id, &conn) @@ -385,8 +386,6 @@ async fn get_org_collections(org_id: OrganizationId, headers: ManagerHeadersLoos .filter(|collection| manageable.contains(&collection.uuid)) .map(Collection::to_json) .collect::() - } else { - err_code!("Resource not found.", "User does not have full access", Status::NotFound.code); }; Ok(Json(json!({ @@ -408,18 +407,10 @@ async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHea // get all collection memberships for the current organization let col_users = CollectionUser::find_by_organization_swap_user_uuid_with_member_uuid(&org_id, &conn).await; - // Generate a HashMap to get the correct MembershipType per user to determine the manage permission - // We use the uuid instead of the user_uuid here, since that is what is used in CollectionUser - // This lists other members for admins, so it must not depend on the membership status - let membership_type: HashMap = - Membership::find_by_org(&org_id, &conn).await.into_iter().map(|m| (m.uuid, m.atype)).collect(); - - // check if current user has full access to the organization (either directly or via any group) - let has_full_access_to_org = member.has_full_access() - || (CONFIG.org_groups_enabled() && GroupUser::has_full_access_by_member(&org_id, &member.uuid, &conn).await); - // Manage users and Manage groups may read collection access details without editing collection metadata. - let custom_collections = if member.has_type(MembershipType::Custom) - && !member.can_view_all_collection_access_details() + + // As in Bitwarden, a member who may not read the access of every collection only gets those they manage. Manage + // users and Manage groups may read collection access details without editing collection metadata. + let manageable_collections = if !member.can_view_all_collection_access_details() && !member.has_custom_permission(CustomPermission::ManageGroups) { Some(Collection::find_explicitly_manageable_by_user(&org_id, &member.user_uuid, &conn).await) @@ -427,68 +418,32 @@ async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHea None }; - // Get all admins, owners and managers who can manage/access all - // Those are currently not listed in the col_users but need to be listed too. - let manage_all_members: Vec = Membership::find_confirmed_and_manage_all_by_org(&org_id, &conn) - .await - .into_iter() - .map(|member| { - json!({ - "id": member.uuid, - "readOnly": false, - "hidePasswords": false, - "manage": true, - }) - }) - .collect(); - let mut data = Vec::new(); for col in Collection::find_by_organization(&org_id, &conn).await { - // check whether the current user has access to the given collection - let assigned = has_full_access_to_org - || CollectionUser::has_access_to_collection_by_user(&col.uuid, &member.user_uuid, &conn).await - || (CONFIG.org_groups_enabled() - && GroupUser::has_access_to_collection_by_member(&col.uuid, &member.uuid, &conn).await); - - // If the user is a manager, and is not assigned to this collection, skip this and continue with the next collection - let listed = if member.has_type(MembershipType::Custom) { - custom_collections.as_ref().is_none_or(|manageable| manageable.contains(&col.uuid)) - } else { - assigned - }; - if !listed { + if manageable_collections.as_ref().is_some_and(|manageable| !manageable.contains(&col.uuid)) { continue; } - // get the users assigned directly to the given collection - let mut users: Vec = col_users - .iter() - .filter(|collection_member| collection_member.collection_uuid == col.uuid) - .map(|collection_member| { - collection_member.to_json_details_for_member( - *membership_type.get(&collection_member.membership_uuid).unwrap_or(&(MembershipType::User as i32)), - ) - }) - .collect(); - users.extend_from_slice(&manage_all_members); + // the members assigned directly to the given collection + let collection_members: Vec<&CollectionMembership> = + col_users.iter().filter(|collection_member| collection_member.collection_uuid == col.uuid).collect(); + let users: Vec = collection_members.iter().map(|cm| cm.to_json_details_for_member()).collect(); - // get the group details for the given collection - let groups: Vec = if CONFIG.org_groups_enabled() { - CollectionGroup::find_by_collection(&col.uuid, &conn) - .await - .iter() - .map(CollectionGroup::to_json_details_for_group) - .collect() + // the groups assigned to the given collection + let collection_groups = if CONFIG.org_groups_enabled() { + CollectionGroup::find_by_collection(&col.uuid, &conn).await } else { Vec::new() }; + let groups: Vec = collection_groups.iter().map(CollectionGroup::to_json_details_for_group).collect(); let mut json_object = col.to_json_details(&headers.user.uuid, None, &conn).await; - json_object["assigned"] = json!(assigned); + // Like Bitwarden, whether the current user is assigned to it themselves, the role doesn't count + json_object["assigned"] = json!(Collection::is_assigned(&member, &col.uuid, &conn).await); json_object["users"] = json!(users); json_object["groups"] = json!(groups); json_object["object"] = json!("collectionAccessDetails"); - json_object["unmanaged"] = json!(false); + json_object["unmanaged"] = json!(is_unmanaged(&collection_members, &collection_groups)); data.push(json_object); } @@ -499,6 +454,12 @@ async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHea }))) } +/// Whether no member and no group may manage a collection, given everyone assigned to it, like Bitwarden's `Unmanaged`. +/// The Admin Console offers to add access to such a collection. +fn is_unmanaged(members: &[&CollectionMembership], groups: &[CollectionGroup]) -> bool { + !members.iter().any(|member| member.manage) && !groups.iter().any(|group| group.manage) +} + async fn get_org_collections_impl(org_id: &OrganizationId, conn: &DbConn) -> Value { Collection::find_by_organization(org_id, conn).await.iter().map(Collection::to_json).collect::() } @@ -516,9 +477,9 @@ async fn post_organization_collections( let data: FullCollectionData = data.into_inner(); data.validate(&org_id, &conn).await?; - if (headers.membership.atype == MembershipType::Manager && !headers.membership.access_all) - || (headers.membership.has_type(MembershipType::Custom) - && !headers.membership.has_custom_permission(CustomPermission::CreateNewCollections)) + // The clients are told collection creation is limited + if !headers.membership.has_full_access() + && !headers.membership.has_custom_permission(CustomPermission::CreateNewCollections) { err!("You don't have permission to create collections") } @@ -548,10 +509,6 @@ async fn post_organization_collections( err!("User is not part of organization") }; - if member.access_all { - continue; - } - CollectionUser::save( &member.user_uuid, &collection.uuid, @@ -604,13 +561,9 @@ async fn post_bulk_access_collections( err_code!("One or more collections not found.", Status::NotFound.code) }; - let manageable = if headers.membership.has_type(MembershipType::Custom) { - custom_member_may(CollectionAction::Edit, &headers.membership, &collection.uuid, &conn).await - || (headers.membership.has_custom_permission(CustomPermission::ManageUsers) - && headers.membership.has_custom_permission(CustomPermission::ManageGroups)) - } else { - collection.is_manageable_by_user(&headers.membership.user_uuid, &conn).await - }; + let manageable = member_may(CollectionAction::Edit, &headers.membership, &collection.uuid, &conn).await + || (headers.membership.has_custom_permission(CustomPermission::ManageUsers) + && headers.membership.has_custom_permission(CustomPermission::ManageGroups)); if !manageable { err_code!( "Resource not found.", @@ -659,10 +612,6 @@ async fn post_bulk_access_collections( } for (user, member) in data.users.iter().zip(&members) { - if member.access_all { - continue; - } - CollectionUser::save(&member.user_uuid, &col_id, user.read_only, user.hide_passwords, user.manage, &conn) .await?; } @@ -727,10 +676,6 @@ async fn put_organization_collection_update( err!("User is not part of organization") }; - if member.access_all { - continue; - } - CollectionUser::save(&member.user_uuid, &col_id, user.read_only, user.hide_passwords, user.manage, &conn) .await?; } @@ -827,44 +772,31 @@ async fn get_org_collection_detail( err!("Collection is not owned by organization") } - let groups: Vec = if CONFIG.org_groups_enabled() { - CollectionGroup::find_by_collection(&collection.uuid, &conn) - .await - .iter() - .map(CollectionGroup::to_json_details_for_group) - .collect() + // The Bitwarden clients seem to call this API regardless of whether groups are enabled, + // so just act as if there are no groups. + let collection_groups = if CONFIG.org_groups_enabled() { + CollectionGroup::find_by_collection(&collection.uuid, &conn).await } 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() }; + let groups: Vec = collection_groups.iter().map(CollectionGroup::to_json_details_for_group).collect(); - // Generate a HashMap to get the correct MembershipType per user to determine the manage permission - // We use the uuid instead of the user_uuid here, since that is what is used in CollectionUser - // This lists other members for admins, so it must not depend on the membership status - let membership_type: HashMap = - Membership::find_by_org(&org_id, &conn).await.into_iter().map(|m| (m.uuid, m.atype)).collect(); - - let users: Vec = + let collection_members = CollectionUser::find_by_org_and_coll_swap_user_uuid_with_member_uuid(&org_id, &collection.uuid, &conn) - .await - .iter() - .map(|collection_member| { - collection_member.to_json_details_for_member( - *membership_type - .get(&collection_member.membership_uuid) - .unwrap_or(&(MembershipType::User as i32)), - ) - }) - .collect(); - - let assigned = Collection::can_access_collection(&member, &collection.uuid, &conn).await; + .await; + let users: Vec = + collection_members.iter().map(CollectionMembership::to_json_details_for_member).collect(); + + // Like Bitwarden, whether the current user is assigned to it themselves, the role doesn't count + let assigned = Collection::is_assigned(&member, &collection.uuid, &conn).await; + let unmanaged = is_unmanaged(&collection_members.iter().collect::>(), &collection_groups); let mut json_object = collection.to_json_details(&headers.user.uuid, None, &conn).await; json_object["assigned"] = json!(assigned); json_object["users"] = json!(users); json_object["groups"] = json!(groups); json_object["object"] = json!("collectionAccessDetails"); + json_object["unmanaged"] = json!(unmanaged); Ok(Json(json_object)) } @@ -1025,7 +957,6 @@ async fn get_members( if recovery_only && (!u.has_status(MembershipStatus::Confirmed) || u.reset_password_key.is_none()) { continue; } - // The user can be a manager instead of an admin, but we've checked above that they have full access users_json.push( u.to_json_details_for_admin( data.include_collections.unwrap_or(false), @@ -1174,19 +1105,16 @@ async fn send_invite( let data: InviteData = data.into_inner(); data.validate(&org_id, &conn).await?; - // HACK: We need the raw user-type to be sure custom role is selected to determine the access_all permission - // Unless Custom roles are enabled, a custom role (4) is converted to a manager role (3) - let raw_type = &data.r#type.into_string(); - let Some(requested_type) = MembershipType::from_str(raw_type) else { + let Some(new_type) = MembershipType::from_str(&data.r#type.into_string()) else { err!("Invalid type") }; + MembershipType::check_requested(new_type, None)?; // Checked before anything is created, so a rejected permission leaves nothing behind - let custom_permissions = if requested_type == MembershipType::Custom && custom_roles_enabled() { + let custom_permissions = if new_type == MembershipType::Custom { Some(CustomPermission::requested(&data.permissions)?) } else { None }; - let new_type = MembershipType::requested(requested_type, None, custom_permissions.as_ref()); check_role_manageable(headers.membership_type, new_type as i32)?; if headers.membership_type == MembershipType::Custom { @@ -1196,16 +1124,6 @@ async fn send_invite( .await?; } - // HACK: This converts the Custom role which has the `Manage all collections` box checked into an access_all flag - // Since the parent checkbox is not sent to the server we need to check and verify the child checkboxes - // If the box is not checked, the user will still be a manager, but not with the access_all permission - let access_all = new_type >= MembershipType::Admin - || (new_type == MembershipType::Manager - && raw_type.eq("4") - && data.permissions.get("editAnyCollection") == Some(&json!(true)) - && data.permissions.get("deleteAnyCollection") == Some(&json!(true)) - && data.permissions.get("createNewCollections") == Some(&json!(true))); - let mut user_created: bool; for email in &data.emails { let mut member_status = MembershipStatus::Invited as i32; @@ -1248,7 +1166,6 @@ async fn send_invite( let mut new_member = Membership::new(user.uuid.clone(), org_id.clone(), Some(headers.user.email.clone())); new_member.set_type(new_type); - new_member.access_all = access_all; if let Some(permissions) = &custom_permissions { new_member.set_custom_permissions(permissions); } @@ -1293,22 +1210,19 @@ async fn send_invite( ) .await; - // If no accessAll, add the collections received - if !access_all { - for col in data.collections.iter().flatten() { - match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await { - None => err!("Collection not found in Organization"), - Some(collection) => { - CollectionUser::save( - &user.uuid, - &collection.uuid, - col.read_only, - col.hide_passwords, - col.manage, - &conn, - ) - .await?; - } + for col in data.collections.iter().flatten() { + match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await { + None => err!("Collection not found in Organization"), + Some(collection) => { + CollectionUser::save( + &user.uuid, + &collection.uuid, + col.read_only, + col.hide_passwords, + col.manage, + &conn, + ) + .await?; } } } @@ -1626,8 +1540,8 @@ async fn get_org_user_mini_details(org_id: OrganizationId, headers: ManagerHeade if org_id != headers.membership.org_uuid { err!("Organization not found", "Organization id's do not match"); } - // A Custom member may also need basic member details for event logs or reports. - if headers.membership.has_type(MembershipType::Custom) + // Besides those assigning collection access, a Custom member may need basic member details for event logs or reports. + if !headers.membership.has_full_access() && !headers.membership.has_custom_permission(CustomPermission::AccessEventLogs) && !headers.membership.has_custom_permission(CustomPermission::AccessReports) && !may_assign_collection_access(&headers.membership, &conn).await @@ -1692,40 +1606,20 @@ async fn edit_member( } let data: EditUserData = data.into_inner(); - // HACK: We need the raw user-type to be sure custom role is selected to determine the access_all permission - // Unless Custom roles are enabled, a custom role (4) is converted to a manager role (3) - let raw_type = &data.r#type.into_string(); - let Some(requested_type) = MembershipType::from_str(raw_type) else { + let Some(new_type) = MembershipType::from_str(&data.r#type.into_string()) else { err!("Invalid type") }; let Some(mut member_to_edit) = Membership::find_by_uuid_and_org(&member_id, &org_id, &conn).await else { err!("The specified user isn't member of the organization") }; + MembershipType::check_requested(new_type, Some(&member_to_edit))?; // While Custom roles are disabled, a Custom member keeps their stored permissions untouched - let custom_permissions = if requested_type == MembershipType::Custom && custom_roles_enabled() { + let custom_permissions = if new_type == MembershipType::Custom && custom_roles_enabled() { Some(CustomPermission::requested(&data.permissions)?) } else { None }; - let new_type = MembershipType::requested(requested_type, Some(&member_to_edit), custom_permissions.as_ref()); - // A Manager whose permissions are changed only becomes a Custom member if that keeps what they may do - if new_type == MembershipType::Custom - && let Some(permissions) = &custom_permissions - && let Some(loss) = member_to_edit.custom_role_conversion_loss(permissions, &conn).await - { - err!(loss) - } - - // HACK: This converts the Custom role which has the `Manage all collections` box checked into an access_all flag - // Since the parent checkbox is not sent to the server we need to check and verify the child checkboxes - // If the box is not checked, the user will still be a manager, but not with the access_all permission - let access_all = new_type >= MembershipType::Admin - || (new_type == MembershipType::Manager - && raw_type.eq("4") - && data.permissions.get("editAnyCollection") == Some(&json!(true)) - && data.permissions.get("deleteAnyCollection") == Some(&json!(true)) - && data.permissions.get("createNewCollections") == Some(&json!(true))); // Both the current and the requested role must be one the caller may manage check_role_manageable(headers.membership_type, member_to_edit.atype)?; @@ -1757,7 +1651,6 @@ async fn edit_member( } member_to_edit.set_type(new_type); - member_to_edit.access_all = access_all; if let Some(permissions) = custom_permissions.as_ref().filter(|_| new_type == MembershipType::Custom) { member_to_edit.set_custom_permissions(permissions); } @@ -1771,22 +1664,19 @@ async fn edit_member( c.delete(&conn).await?; } - // If no accessAll, add the collections received - if !access_all { - for col in data.collections.iter().flatten() { - match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await { - None => err!("Collection not found in Organization"), - Some(collection) => { - CollectionUser::save( - &member_to_edit.user_uuid, - &collection.uuid, - col.read_only, - col.hide_passwords, - col.manage, - &conn, - ) - .await?; - } + for col in data.collections.iter().flatten() { + match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await { + None => err!("Collection not found in Organization"), + Some(collection) => { + CollectionUser::save( + &member_to_edit.user_uuid, + &collection.uuid, + col.read_only, + col.hide_passwords, + col.manage, + &conn, + ) + .await?; } } } @@ -2014,10 +1904,7 @@ async fn validate_org_import_collections( ) -> ApiResult> { let existing: HashMap = Collection::find_by_organization(org_id, conn).await.into_iter().map(|c| (c.uuid.clone(), c)).collect(); - let manageable = if membership.atype < MembershipType::Admin - && !membership.can_edit_any_collection() - && !membership.has_type(MembershipType::Manager) - { + let manageable = if membership.atype < MembershipType::Admin && !membership.can_edit_any_collection() { Some( Collection::find_explicitly_manageable_by_user(org_id, &membership.user_uuid, conn) .await @@ -2029,18 +1916,12 @@ async fn validate_org_import_collections( }; for col in imported { if let Some(collection) = col.id.as_ref().and_then(|id| existing.get(id)) { - if membership.atype < MembershipType::Admin && !membership.can_edit_any_collection() { - let can_import = if let Some(manageable) = &manageable { - manageable.contains(&collection.uuid) - } else { - collection.is_writable_by_user(&membership.user_uuid, conn).await - }; - if !can_import { - err!(Compact, "The current user isn't allowed to manage this collection") - } + if let Some(manageable) = &manageable + && !manageable.contains(&collection.uuid) + { + err!(Compact, "The current user isn't allowed to manage this collection") } - } else if membership.atype <= MembershipType::Manager - && !membership.has_full_access() + } else if !membership.has_full_access() && !membership.has_custom_permission(CustomPermission::CreateNewCollections) && !import_export { @@ -2083,7 +1964,6 @@ async fn post_org_import( collections: imported_collections, .. } = data; - let grant_new_collection_manage = headers.membership.has_type(MembershipType::Custom); let importer_uuid = headers.membership.user_uuid.clone(); let OrgMemberHeaders { host, @@ -2111,9 +1991,8 @@ async fn post_org_import( } else { let new_collection = Collection::new(org_id.clone(), col.name, col.external_id); new_collection.save(&conn).await?; - if grant_new_collection_manage { - CollectionUser::save(&importer_uuid, &new_collection.uuid, false, false, true, &conn).await?; - } + // Like upstream, the importer manages the collections they create + CollectionUser::save(&importer_uuid, &new_collection.uuid, false, false, true, &conn).await?; new_collection.uuid }; collections.push(collection_uuid); @@ -2170,7 +2049,7 @@ mod org_import_tests { ("admin", MembershipType::Admin, CustomPermission::CreateNewCollections), ("cipher", MembershipType::Custom, CustomPermission::CreateNewCollections), ("custom", MembershipType::Custom, CustomPermission::CreateNewCollections), - ("legacy", MembershipType::Manager, CustomPermission::CreateNewCollections), + ("user", MembershipType::User, CustomPermission::CreateNewCollections), ("authorization", MembershipType::Custom, CustomPermission::CreateNewCollections), ("rollback", MembershipType::Custom, CustomPermission::CreateNewCollections), ("index", MembershipType::Custom, CustomPermission::CreateNewCollections), @@ -2185,9 +2064,7 @@ mod org_import_tests { } else { vec![] }; - let (user, mut membership) = test_db::member(&conn, &org.uuid, role, &permissions).await; - membership.access_all = role == MembershipType::Manager; - membership.save(&conn).await.unwrap(); + let (user, membership) = test_db::member(&conn, &org.uuid, role, &permissions).await; let mut payload = json!({"ciphers":[{"name":"Cipher","type":2,"encryptedFor":user.uuid,"secureNote":{"type":0}}], "collections":[{"name":"New"}],"collectionRelationships":[{"key":0,"value":0}]}); match case { @@ -2227,17 +2104,14 @@ mod org_import_tests { ) .await; conn.run(|c| c.batch_execute("DROP TRIGGER IF EXISTS reject_link")).await.unwrap(); - let success = matches!(case, "owner" | "admin" | "custom" | "legacy" | "export"); + let success = matches!(case, "owner" | "admin" | "custom" | "export"); assert_eq!(result.is_ok(), success, "{case}"); assert_eq!( Collection::find_by_organization(&org.uuid, &conn).await.len(), usize::from(success || case == "authorization") ); assert_eq!(Cipher::find_by_org(&org.uuid, &conn).await.len(), usize::from(success)); - assert_eq!( - CollectionUser::find_by_user(&user_id, &conn).await.len(), - usize::from(success && role == MembershipType::Custom) - ); + assert_eq!(CollectionUser::find_by_user(&user_id, &conn).await.len(), usize::from(success)); assert_eq!( Cipher::get_collections_with_cipher_by_organization(&org.uuid, &conn).await.len(), usize::from(success && case != "export") @@ -2883,13 +2757,9 @@ async fn get_groups_data( } // The details view (group→collection/user mappings) needs full org access; the plain list only - // needs manage access to a collection, so a manager of a collection (directly or via a group) + // needs manage access to a collection, so a member who manages one (directly or via a group) // can load it to assign groups. - // A group with access to all collections gives a Custom member access to them, but not to the Admin Console. - let has_full_access = headers.membership.has_full_access() - || (CONFIG.org_groups_enabled() - && !headers.membership.has_type(MembershipType::Custom) - && GroupUser::has_full_access_by_member(&org_id, &headers.membership.uuid, &conn).await); + let has_full_access = headers.membership.has_full_access(); let allowed = if details { has_full_access || headers.membership.has_custom_permission(CustomPermission::ManageUsers) @@ -2954,7 +2824,6 @@ async fn get_groups_details(org_id: OrganizationId, headers: ManagerHeadersLoose #[serde(rename_all = "camelCase")] struct GroupRequest { name: String, - access_all: Option, external_id: Option, collections: Vec, users: Vec, @@ -2962,14 +2831,11 @@ struct GroupRequest { impl GroupRequest { pub fn to_group(&self, org_uuid: &OrganizationId) -> Group { - Group::new(org_uuid.clone(), self.name.clone(), self.access_all.unwrap_or(false), self.external_id.clone()) + Group::new(org_uuid.clone(), self.name.clone(), self.external_id.clone()) } pub fn update_group(&self, mut group: Group) -> Group { group.name.clone_from(&self.name); - if let Some(access_all) = self.access_all { - group.access_all = access_all; - } // Group Updates do not support changing the external_id // These input fields are in a disabled state, and can only be updated/added via ldap_import @@ -3856,6 +3722,25 @@ mod tests { } } + #[test] + fn collections_no_member_or_group_manages_are_unmanaged() { + let member = |manage| CollectionMembership { + membership_uuid: String::from("member").into(), + collection_uuid: String::from("collection").into(), + read_only: false, + hide_passwords: false, + manage, + }; + let group = |manage| { + CollectionGroup::new(String::from("collection").into(), String::from("group").into(), false, false, manage) + }; + let (editor, manager) = (member(false), member(true)); + assert!(is_unmanaged(&[], &[])); + assert!(is_unmanaged(&[&editor], &[group(false)])); + assert!(!is_unmanaged(&[&editor, &manager], &[group(false)])); + assert!(!is_unmanaged(&[&editor], &[group(false), group(true)])); + } + #[cfg(sqlite)] #[test] fn manage_users_grants_are_confined_to_permission_and_organization() { @@ -3865,7 +3750,7 @@ mod tests { let foreign = test_db::organization(&conn).await; for org_id in [&org.uuid, &foreign.uuid] { let collection = test_db::collection(&conn, org_id).await; - let mut group = Group::new(org_id.clone(), "Group".into(), true, None); + let mut group = Group::new(org_id.clone(), "Group".into(), None); group.save(&conn).await.unwrap(); let empty = HashSet::new(); for (collections, groups) in [ @@ -3873,7 +3758,6 @@ mod tests { (&[][..], HashSet::from([group.uuid.clone()])), (&[&collection.uuid][..], HashSet::from([group.uuid])), ] { - // A group with access to all collections may be given as well, as in Bitwarden assert_eq!( check_custom_member_grants(&member, None, collections, &groups, &conn).await.is_ok(), org_id == &org.uuid @@ -3881,18 +3765,18 @@ mod tests { } } let collection = test_db::collection(&conn, &org.uuid).await; - assert!(!Collection::can_access_collection(&member, &collection.uuid, &conn).await); + assert!(!Collection::is_assigned(&member, &collection.uuid, &conn).await); let escalated = HashSet::from([CustomPermission::EditAnyCollection]); let empty = HashSet::new(); for (enabled, status) in [(true, 2), (true, 1), (true, -126), (false, 2)] { test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled)); member.status = status; assert_eq!( - custom_member_may(CollectionAction::Read, &member, &collection.uuid, &conn).await, + member_may(CollectionAction::Read, &member, &collection.uuid, &conn).await, enabled && status == 2 ); - assert!(!custom_member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await); - assert!(!custom_member_may(CollectionAction::ReadAccess, &member, &collection.uuid, &conn).await); + assert!(!member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await); + assert!(!member_may(CollectionAction::ReadAccess, &member, &collection.uuid, &conn).await); assert_eq!( check_custom_member_grants(&member, None, &[], &empty, &conn).await.is_ok(), enabled && status == 2 @@ -3947,7 +3831,7 @@ mod tests { } #[cfg(sqlite)] #[test] - fn group_requests_stay_in_their_organization_and_keep_access_all() { + fn group_requests_stay_in_their_organization() { test_db::run(async |db| { let conn = db.conn(); let (org, _, member) = test_db::custom_member(&conn, CustomPermission::ManageGroups).await; @@ -3958,13 +3842,9 @@ mod tests { {"id":collection.uuid,"readOnly":false,"hidePasswords":false,"manage":true}],"users":[]})) .unwrap(); assert_eq!(request.validate(&org.uuid, &conn).await.is_ok(), org_id == &org.uuid); - assert!(!Collection::can_access_collection(&member, &collection.uuid, &conn).await); - assert!(!custom_member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await); + assert!(!Collection::is_assigned(&member, &collection.uuid, &conn).await); + assert!(!member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await); } - let group = Group::new(org.uuid.clone(), "Group".into(), true, None); - let omitted: GroupRequest = - serde_json::from_value(json!({"name":"Group","collections":[],"users":[member.uuid]})).unwrap(); - assert!(omitted.update_group(group).access_all); }); } @@ -4092,7 +3972,7 @@ mod tests { for (role, permissions) in [ (Owner, vec![]), (Admin, vec![]), - (Manager, vec![]), + (User, vec![]), (User, vec![]), (Custom, vec![ManageResetPassword]), (Custom, vec![ManageResetPassword, ManageUsers]), @@ -4100,7 +3980,7 @@ mod tests { members.push(test_db::member(&conn, &org.uuid, role, &permissions).await.1); } // Who may recover whom: a row per caller, a column per target, both in the order above - for (caller, row) in members.iter().zip(["111111", "011111", "000000", "000000", "000110", "000111"]) { + for (caller, row) in members.iter().zip(["111111", "011111", "000000", "000000", "001110", "001111"]) { for (target, allowed) in members.iter().zip(row.chars()) { assert_eq!( may_recover_account(caller, target), diff --git a/src/api/core/public.rs b/src/api/core/public.rs index 1ee80515..1c34d6e4 100644 --- a/src/api/core/public.rs +++ b/src/api/core/public.rs @@ -113,7 +113,6 @@ async fn ldap_import(data: Json, token: PublicToken, conn: DbConn let mut new_member = Membership::new(user.uuid.clone(), org_id.clone(), Some(org_email.clone())); new_member.set_external_id(Some(user_data.external_id.clone())); - new_member.access_all = false; new_member.atype = MembershipType::User as i32; new_member.status = member_status; @@ -147,7 +146,7 @@ async fn ldap_import(data: Json, token: PublicToken, conn: DbConn group.uuid } else { let mut group = - Group::new(org_id.clone(), group_data.name.clone(), false, Some(group_data.external_id.clone())); + Group::new(org_id.clone(), group_data.name.clone(), Some(group_data.external_id.clone())); group.save(&conn).await?; group.uuid }; diff --git a/src/auth.rs b/src/auth.rs index 9da34a85..6cb6634c 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -751,9 +751,6 @@ impl OrgHeaders { fn is_confirmed_and_admin(&self) -> bool { self.membership_status == MembershipStatus::Confirmed && self.membership_type >= MembershipType::Admin } - fn is_confirmed_and_manager(&self) -> bool { - self.membership_status == MembershipStatus::Confirmed && self.membership_type >= MembershipType::Manager - } fn is_confirmed_and_owner(&self) -> bool { self.membership_status == MembershipStatus::Confirmed && self.membership_type == MembershipType::Owner } @@ -975,24 +972,22 @@ pub enum CollectionAction { Delete, } -/// Whether `member`, a confirmed Custom member, may `action` the collection `col_id` of their organization. +/// Whether `member` may `action` the collection `col_id` of their organization, like upstream's +/// BulkCollectionAuthorizationHandler: an Owner or Admin every collection, a Custom member as their permissions allow, +/// and every confirmed member the collections they manage with the manage option. /// /// Deleting needs Delete any collection: the clients are told collection deletion is limited, so the manage option /// on a collection is no permission to delete it. Editing is open with Edit any collection, reading also with Delete -/// any collection, and otherwise both need the manage option on the collection itself. Neither the role nor any -/// `access_all` counts as that. -pub async fn custom_member_may( - action: CollectionAction, - member: &Membership, - col_id: &CollectionId, - conn: &DbConn, -) -> bool { - if !(member.has_type(MembershipType::Custom) - && member.has_status(MembershipStatus::Confirmed) - && custom_roles_enabled()) +/// any collection, and otherwise both need the manage option on the collection itself. +pub async fn member_may(action: CollectionAction, member: &Membership, col_id: &CollectionId, conn: &DbConn) -> bool { + if !member.has_status(MembershipStatus::Confirmed) + || Collection::find_by_uuid_and_org(col_id, &member.org_uuid, conn).await.is_none() { return false; } + if member.has_full_access() { + return true; + } match action { CollectionAction::Delete => member.has_custom_permission(CustomPermission::DeleteAnyCollection), CollectionAction::Edit if member.can_edit_any_collection() => true, @@ -1008,13 +1003,12 @@ pub async fn custom_member_may( } } -/// Checks a collection route for the collection provided via the /collections/collectionId: a Manager, Admin -/// or Owner needs to be able to manage the collection, a Custom member is checked for the `action`. +/// Checks a collection route for the collection provided via the /collections/collectionId: the confirmed +/// member must be allowed the `action` on it. async fn collection_headers(request: &Request<'_>, action: CollectionAction) -> Outcome { let headers = try_outcome!(OrgHeaders::from_request(request).await); - let is_custom = headers.is_confirmed_and_custom(); - if !headers.is_confirmed_and_manager() && !is_custom { - err_handler!("You need to be a Manager, Admin or Owner to call this endpoint") + if headers.membership_status != MembershipStatus::Confirmed { + err_handler!("You need to be a confirmed member of the organization to call this endpoint") } let Some(col_id) = get_col_id(request) else { @@ -1024,12 +1018,7 @@ async fn collection_headers(request: &Request<'_>, action: CollectionAction) -> err_handler!("Error getting DB") }; - let allowed = if is_custom { - custom_member_may(action, &headers.membership, &col_id, &conn).await - } else { - Collection::is_coll_manageable_by_user(&col_id, &headers.membership.user_uuid, &conn).await - }; - if !allowed { + if !member_may(action, &headers.membership, &col_id, &conn).await { // NotFound as in Bitwarden, the web vault logs the user out on a 401 error!(target: "auth", "Collection not found. The current user isn't a manager for this collection"); return Outcome::Error((rocket::http::Status::NotFound, "Collection not found")); @@ -1078,9 +1067,8 @@ macro_rules! collection_headers { } collection_headers!( - /// The ManagerHeaders are used to check if you are at least a Manager - /// and have access to the specific collection provided via the /collections/collectionId. - /// This does strict checking on the collection_id, ManagerHeadersLoose does not. + /// The ManagerHeaders are used to check if you may manage the specific collection provided via the + /// /collections/collectionId. This does strict checking on the collection_id, ManagerHeadersLoose does not. ManagerHeaders, CollectionAction::Edit ); @@ -1100,9 +1088,9 @@ collection_headers!( CollectionAction::Delete ); -/// The ManagerHeadersLoose is used when you at least need to be a Manager, -/// but there is no collection_id sent with the request (either in the path or as form data). -/// A Custom member is let through as well, the routes check what their permissions allow. +/// The ManagerHeadersLoose is used when you need to be an Admin or Owner, a Custom member, or to manage at least one +/// collection, but there is no collection_id sent with the request (either in the path or as form data). The routes +/// check what the member may do. pub struct ManagerHeadersLoose { pub host: String, pub device: Device, @@ -1117,7 +1105,16 @@ impl<'r> FromRequest<'r> for ManagerHeadersLoose { async fn from_request(request: &'r Request<'_>) -> Outcome { let headers = try_outcome!(OrgHeaders::from_request(request).await); - if headers.is_confirmed_and_manager() || headers.is_confirmed_and_custom() { + let allowed = headers.is_confirmed_and_admin() + || headers.is_confirmed_and_custom() + || (headers.membership_status == MembershipStatus::Confirmed && { + let Outcome::Success(conn) = DbConn::from_request(request).await else { + err_handler!("Error getting DB") + }; + Collection::has_manageable_collection_by_user(&headers.membership.org_uuid, &headers.user.uuid, &conn) + .await + }); + if allowed { Outcome::Success(Self { host: headers.host, device: headers.device, @@ -1126,7 +1123,7 @@ impl<'r> FromRequest<'r> for ManagerHeadersLoose { ip: headers.ip, }) } else { - err_handler!("You need to be a Manager, Admin or Owner to call this endpoint") + err_handler!("You need to be an Admin or Owner, or to manage a collection, to call this endpoint") } } } @@ -1148,18 +1145,11 @@ impl CollectionDeleteHeaders { collections: &Vec, conn: &DbConn, ) -> Result { - let is_custom = h.membership.has_type(MembershipType::Custom) && custom_roles_enabled(); for col_id in collections { if uuid::Uuid::parse_str(col_id.as_ref()).is_err() { err!("Collection Id is malformed!"); } - let allowed = if is_custom { - Collection::find_by_uuid_and_org(col_id, &h.membership.org_uuid, conn).await.is_some() - && custom_member_may(CollectionAction::Delete, &h.membership, col_id, conn).await - } else { - Collection::is_coll_manageable_by_user(col_id, &h.membership.user_uuid, conn).await - }; - if !allowed { + if !member_may(CollectionAction::Delete, &h.membership, col_id, conn).await { err!("Collection not found", "The current user isn't a manager for this collection") } } diff --git a/src/db/mod.rs b/src/db/mod.rs index 39aea1d3..6823f514 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -631,17 +631,24 @@ pub mod test_db { }); } - #[test] - fn custom_role_migration_preserves_memberships_and_guards_downgrade() { - use super::schema::users_organizations::dsl::*; - use diesel::{migration::MigrationSource, prelude::*}; - let mut conn = SqliteConnection::establish(":memory:").unwrap(); + /// Runs the pending migrations older than `version`. + fn migrate_until(conn: &mut SqliteConnection, version: &str) { for migration in conn.pending_migrations(MIGRATIONS).unwrap() { - if migration.name().version().to_string() == "20261010120000" { + if migration.name().version().to_string() == version { break; } conn.run_migration(&migration).unwrap(); } + } + + const REMOVE_ACCESS_ALL: &str = "20261115140000"; + + #[test] + fn custom_role_migration_preserves_memberships_and_guards_downgrade() { + use super::schema::users_organizations::dsl::*; + use diesel::{migration::MigrationSource, prelude::*}; + let mut conn = SqliteConnection::establish(":memory:").unwrap(); + migrate_until(&mut conn, "20261010120000"); conn.batch_execute( "PRAGMA foreign_keys=OFF; INSERT INTO organizations (uuid,name,billing_email) VALUES ('org','Org','a@b'); @@ -652,13 +659,13 @@ pub mod test_db { .unwrap(); let rows = |conn: &mut SqliteConnection| { users_organizations - .select((uuid, user_uuid, org_uuid, access_all, akey, status, atype)) + .select((uuid, user_uuid, org_uuid, akey, status, atype)) .order(uuid) - .load::<(String, String, String, bool, String, i32, i32)>(conn) + .load::<(String, String, String, String, i32, i32)>(conn) .unwrap() }; let before = rows(&mut conn); - conn.run_pending_migrations(MIGRATIONS).unwrap(); + migrate_until(&mut conn, REMOVE_ACCESS_ALL); assert_eq!(rows(&mut conn), before); let grants = |conn: &mut SqliteConnection| { diesel::select(diesel::dsl::sql::( @@ -689,11 +696,129 @@ pub mod test_db { .unwrap(); conn.revert_migration(&*migration).unwrap(); assert!(diesel::sql_query("SELECT manage_users FROM users_organizations").execute(&mut conn).is_err()); - conn.run_pending_migrations(MIGRATIONS).unwrap(); + migrate_until(&mut conn, REMOVE_ACCESS_ALL); assert_eq!(grants(&mut conn), 0); assert_eq!(rows(&mut conn), before); } + #[test] + fn access_all_migration_assigns_collections_and_turns_managers_into_users() { + use super::schema::{collections_groups, users_collections, users_organizations}; + use diesel::{migration::MigrationSource, prelude::*}; + let mut conn = SqliteConnection::establish(":memory:").unwrap(); + migrate_until(&mut conn, REMOVE_ACCESS_ALL); + // Users: o Owner and a Admin with access to all collections, u User, m Manager who is also a User of the other + // organization, ma Manager with access to all collections, mg Manager through groups, mx Manager assigned read + // only who manages the same collection through a group. Group gall has access to all collections. Each + // membership's uuid is "m-" and the user's, so that mixing the two up fails. + conn.batch_execute( + "PRAGMA foreign_keys=OFF; + INSERT INTO organizations (uuid,name,billing_email) VALUES ('org','Org','a@b'), ('other','Other','a@b'); + INSERT INTO collections (uuid,org_uuid,name) VALUES ('c1','org','C1'), ('c2','org','C2'), ('c3','other','C3'); + INSERT INTO users_organizations (uuid,user_uuid,org_uuid,access_all,akey,status,atype) VALUES + ('m-o','o','org',TRUE,'key',2,0), ('m-a','a','org',TRUE,'key',2,1), ('m-u','u','org',FALSE,'key',2,2), + ('m-m','m','org',FALSE,'key',2,3), ('m-m2','m','other',FALSE,'key',2,2), + ('m-ma','ma','org',TRUE,'key',0,3), ('m-mg','mg','org',FALSE,'key',2,3), ('m-mx','mx','org',FALSE,'key',2,3); + INSERT INTO users_collections (user_uuid,collection_uuid,read_only,hide_passwords,manage) VALUES + ('a','c1',TRUE,TRUE,TRUE), ('u','c1',TRUE,FALSE,FALSE), ('m','c1',FALSE,FALSE,FALSE), + ('m','c2',TRUE,FALSE,FALSE), ('m','c3',FALSE,FALSE,FALSE), ('mx','c1',TRUE,FALSE,FALSE); + INSERT INTO groups (uuid,organizations_uuid,name,access_all,creation_date,revision_date) VALUES + ('gall','org','All',TRUE,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP), + ('g1','org','G1',FALSE,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP), + ('g2','org','G2',FALSE,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP), + ('g3','org','G3',FALSE,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP); + INSERT INTO groups_users (groups_uuid,users_organizations_uuid) VALUES + ('gall','m-u'), ('g1','m-mg'), ('g2','m-mg'), ('g3','m-mx'); + INSERT INTO collections_groups (collections_uuid,groups_uuid,read_only,hide_passwords,manage) VALUES + ('c1','gall',TRUE,TRUE,FALSE), ('c2','g1',FALSE,FALSE,FALSE), ('c1','g2',TRUE,FALSE,FALSE), + ('c1','g3',FALSE,FALSE,TRUE);", + ) + .unwrap(); + let state = |conn: &mut SqliteConnection| { + let users = users_collections::table + .select(( + users_collections::user_uuid, + users_collections::collection_uuid, + users_collections::read_only, + users_collections::hide_passwords, + users_collections::manage, + )) + .order((users_collections::user_uuid, users_collections::collection_uuid)) + .load::<(String, String, bool, bool, bool)>(conn) + .unwrap(); + let groups = collections_groups::table + .select(( + collections_groups::groups_uuid, + collections_groups::collections_uuid, + collections_groups::read_only, + collections_groups::hide_passwords, + collections_groups::manage, + )) + .order((collections_groups::groups_uuid, collections_groups::collections_uuid)) + .load::<(String, String, bool, bool, bool)>(conn) + .unwrap(); + let roles = users_organizations::table + .select((users_organizations::uuid, users_organizations::atype)) + .order(users_organizations::uuid) + .load::<(String, i32)>(conn) + .unwrap(); + (users, groups, roles) + }; + let row = |a: &str, b: &str, ro, hp, mn| (a.to_owned(), b.to_owned(), ro, hp, mn); + let expected = ( + vec![ + // The Owner and Admin read and write every collection of their organization, keeping manage + row("a", "c1", false, false, true), + row("a", "c2", false, false, false), + // As in Bitwarden, the Managers manage every collection they are assigned to, read only or not, and + // those of their groups too. Their assignments in the other organization stay as they are. + row("m", "c1", false, false, true), + row("m", "c2", false, false, true), + row("m", "c3", false, false, false), + row("ma", "c1", false, false, true), + row("ma", "c2", false, false, true), + row("mg", "c1", false, false, true), + row("mg", "c2", false, false, true), + row("mx", "c1", false, false, true), + row("o", "c1", false, false, false), + row("o", "c2", false, false, false), + // Other members keep what they have + row("u", "c1", true, false, false), + ], + vec![ + row("g1", "c2", false, false, false), + row("g2", "c1", true, false, false), + row("g3", "c1", false, false, true), + row("gall", "c1", false, false, false), + row("gall", "c2", false, false, false), + ], + [("m-a", 1), ("m-m", 2), ("m-m2", 2), ("m-ma", 2), ("m-mg", 2), ("m-mx", 2), ("m-o", 0), ("m-u", 2)] + .map(|(m, t)| (m.to_owned(), t)) + .to_vec(), + ); + conn.run_pending_migrations(MIGRATIONS).unwrap(); + assert_eq!(state(&mut conn), expected); + for table in ["users_organizations", "groups"] { + assert!(diesel::sql_query(format!("SELECT access_all FROM {table}")).execute(&mut conn).is_err()); + } + + // A downgrade gives Owners and Admins their access to all collections back, an upgrade again changes nothing + let migration = MigrationSource::::migrations(&MIGRATIONS) + .unwrap() + .into_iter() + .find(|m| m.name().version().to_string() == REMOVE_ACCESS_ALL) + .unwrap(); + conn.revert_migration(&*migration).unwrap(); + let full = diesel::select(diesel::dsl::sql::( + "(SELECT group_concat(uuid) FROM (SELECT uuid FROM users_organizations WHERE access_all ORDER BY uuid))", + )) + .get_result::(&mut conn) + .unwrap(); + assert_eq!(full, "m-a,m-o"); + conn.run_pending_migrations(MIGRATIONS).unwrap(); + assert_eq!(state(&mut conn), expected); + } + use super::models::{Collection, CustomPermission, Membership, MembershipType, Organization, OrganizationId, User}; pub async fn organization(conn: &DbConn) -> Organization { @@ -765,7 +890,7 @@ pub mod test_db { use super::models::{Cipher, CipherAccessScope, CollectionCipher, CollectionUser, test_flag}; use crate::{ api::core::{CipherSyncData, CipherSyncType}, - auth::{CollectionAction, custom_member_may}, + auth::{CollectionAction, member_may}, }; run(async |db| { let conn = db.conn(); @@ -795,8 +920,8 @@ pub mod test_db { cipher.organization_uuid = Some(org.uuid.clone()); member.set_custom_permissions(&std::collections::HashSet::new()); member.save(&conn).await.unwrap(); - let sql=format!("INSERT INTO groups (uuid,organizations_uuid,name,access_all,creation_date,revision_date) - VALUES ('g','{}','Group',FALSE,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP); + let sql=format!("INSERT INTO groups (uuid,organizations_uuid,name,creation_date,revision_date) + VALUES ('g','{}','Group',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP); INSERT INTO groups_users (groups_uuid,users_organizations_uuid) VALUES ('g','{}'); INSERT INTO collections_groups (collections_uuid,groups_uuid,read_only,hide_passwords,manage) VALUES ('{}','g',FALSE,FALSE,TRUE);", org.uuid,member.uuid,collection.uuid); @@ -805,7 +930,7 @@ pub mod test_db { member.status = status; member.save(&conn).await.unwrap(); let allowed = status == 2 && crate::CONFIG.org_groups_enabled(); - assert_eq!(custom_member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await, allowed); + assert_eq!(member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await, allowed); let sync = CipherSyncData::new(&user.uuid, CipherSyncType::User, &conn).await; for cached in [None, Some(&sync)] { assert_eq!( @@ -820,7 +945,125 @@ pub mod test_db { member.status = 2; member.save(&conn).await.unwrap(); CollectionUser::save(&user.uuid, &collection.uuid, false, false, true, &conn).await.unwrap(); - assert!(custom_member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await); + assert!(member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await); + }); + } + + #[test] + fn collections_are_managed_by_role_or_manage_option_within_the_organization() { + use super::models::CollectionUser; + use crate::auth::{CollectionAction, member_may}; + run(async |db| { + let conn = db.conn(); + let org = organization(&conn).await; + let foreign = organization(&conn).await; + let managed = collection(&conn, &org.uuid).await; + let assigned = collection(&conn, &org.uuid).await; + let other = collection(&conn, &foreign.uuid).await; + let (_, admin) = member(&conn, &org.uuid, MembershipType::Admin, &[]).await; + let (user, mut manager_member) = member(&conn, &org.uuid, MembershipType::User, &[]).await; + CollectionUser::save(&user.uuid, &managed.uuid, false, false, true, &conn).await.unwrap(); + CollectionUser::save(&user.uuid, &assigned.uuid, false, false, false, &conn).await.unwrap(); + for action in [CollectionAction::Edit, CollectionAction::Read, CollectionAction::ReadAccess] { + // A member manages the collection with the manage option, an Admin every one of their organization + assert!(member_may(action, &manager_member, &managed.uuid, &conn).await); + assert!(!member_may(action, &manager_member, &assigned.uuid, &conn).await); + assert!(member_may(action, &admin, &assigned.uuid, &conn).await); + assert!(!member_may(action, &admin, &other.uuid, &conn).await); + } + // Collection deletion is limited to those who may delete any collection + assert!(!member_may(CollectionAction::Delete, &manager_member, &managed.uuid, &conn).await); + assert!(member_may(CollectionAction::Delete, &admin, &managed.uuid, &conn).await); + // Only while confirmed + manager_member.status = 1; + manager_member.save(&conn).await.unwrap(); + assert!(!member_may(CollectionAction::Edit, &manager_member, &managed.uuid, &conn).await); + assert!(!Collection::has_manageable_collection_by_user(&org.uuid, &user.uuid, &conn).await); + manager_member.status = 2; + manager_member.save(&conn).await.unwrap(); + assert!(Collection::has_manageable_collection_by_user(&org.uuid, &user.uuid, &conn).await); + }); + } + + #[test] + fn owners_and_admins_only_reach_every_cipher_on_the_administrative_routes() { + use super::models::{ + Cipher, CipherAccessScope, CollectionCipher, CollectionGroup, CollectionUser, Group, GroupUser, + }; + use crate::api::core::{CipherSyncData, CipherSyncType}; + run(async |db| { + let conn = db.conn(); + let org = organization(&conn).await; + let assigned = collection(&conn, &org.uuid).await; + let unassigned = collection(&conn, &org.uuid).await; + let (user, admin) = member(&conn, &org.uuid, MembershipType::Admin, &[]).await; + // The Admin may only view the items of one collection, without their passwords + CollectionUser::save(&user.uuid, &assigned.uuid, true, true, false, &conn).await.unwrap(); + let mut ciphers = Vec::new(); + for collection in [&assigned, &unassigned] { + let mut cipher = Cipher::new(2); + cipher.name = "Cipher".into(); + cipher.organization_uuid = Some(org.uuid.clone()); + cipher.save(&conn).await.unwrap(); + CollectionCipher::save(&cipher.uuid, &collection.uuid, &conn).await.unwrap(); + ciphers.push(cipher); + } + + // Like Bitwarden, their own vault has what they are assigned, with the access they are assigned + let sync = CipherSyncData::new(&user.uuid, CipherSyncType::User, &conn).await; + for cached in [None, Some(&sync)] { + let own = ciphers[0].get_access_restrictions(&user.uuid, CipherAccessScope::User, cached, &conn).await; + assert_eq!(own, Some((true, true, false))); + let other = + ciphers[1].get_access_restrictions(&user.uuid, CipherAccessScope::User, cached, &conn).await; + assert_eq!(other, None); + let details = assigned.to_json_details(&user.uuid, cached, &conn).await; + assert_eq!( + (&details["readOnly"], &details["hidePasswords"], &details["manage"]), + (&json!(true), &json!(true), &json!(false)) + ); + } + // A collection they aren't assigned to has neither restrictions nor the manage option in the details + let details = unassigned.to_json_details(&user.uuid, None, &conn).await; + assert_eq!( + (&details["readOnly"], &details["hidePasswords"], &details["manage"]), + (&json!(false), &json!(false), &json!(false)) + ); + assert!(Collection::is_assigned(&admin, &assigned.uuid, &conn).await); + assert!(!Collection::is_assigned(&admin, &unassigned.uuid, &conn).await); + assert!(!assigned.is_writable_by_user(&user.uuid, &conn).await); + assert!(!unassigned.is_writable_by_user(&user.uuid, &conn).await); + let user_collections = + ciphers[1].get_admin_collections(user.uuid.clone(), CipherAccessScope::User, &conn).await; + assert_eq!(user_collections, Vec::new()); + + // Every cipher of the organization only on the administrative routes + for cipher in &ciphers { + let admin_access = + cipher.get_access_restrictions(&user.uuid, CipherAccessScope::OrganizationAdmin, None, &conn).await; + assert_eq!(admin_access, Some((false, false, true))); + } + let admin_collections = + ciphers[1].get_admin_collections(user.uuid.clone(), CipherAccessScope::OrganizationAdmin, &conn).await; + assert_eq!(admin_collections, vec![unassigned.uuid.clone()]); + + // A group with more access doesn't override their own assignment, like in Bitwarden, but counts for the rest + if crate::CONFIG.org_groups_enabled() { + let mut group = Group::new(org.uuid.clone(), "Group".into(), None); + group.save(&conn).await.unwrap(); + GroupUser::new(group.uuid.clone(), admin.uuid.clone()).save(&conn).await.unwrap(); + for (collection, manage) in [(&assigned, true), (&unassigned, false)] { + CollectionGroup::new(collection.uuid.clone(), group.uuid.clone(), false, false, manage) + .save(&org.uuid, &conn) + .await + .unwrap(); + } + assert_eq!(assigned.assigned_access(&admin, &conn).await, Some((true, true, false))); + assert!(!assigned.is_writable_by_user(&user.uuid, &conn).await); + assert_eq!(unassigned.assigned_access(&admin, &conn).await, Some((false, false, false))); + assert!(unassigned.is_writable_by_user(&user.uuid, &conn).await); + assert!(Collection::is_assigned(&admin, &unassigned.uuid, &conn).await); + } }); } } diff --git a/src/db/models/cipher.rs b/src/db/models/cipher.rs index 97807279..c162a7b1 100644 --- a/src/db/models/cipher.rs +++ b/src/db/models/cipher.rs @@ -24,7 +24,7 @@ use crate::{ use macros::UuidFromParam; use super::{ - Archive, Attachment, CollectionCipher, CollectionId, Favorite, FolderCipher, FolderId, Group, Membership, + Archive, Attachment, CollectionCipher, CollectionId, Favorite, FolderCipher, FolderId, Membership, MembershipStatus, OrganizationId, User, UserId, organization::{ORG_ADMIN_ATYPES, custom_edit_any_collection}, }; @@ -84,9 +84,10 @@ pub enum RepromptType { /// Which access a cipher operation is authorized with. /// /// The administrative cipher routes (`/ciphers//admin` and friends) are served by the same handlers as the -/// regular vault routes, so the handlers state which one applies. They only differ for a Custom member with Edit -/// any collection, who reaches every cipher of the organization on the administrative routes, but keeps their -/// own vault limited to the collections they are assigned to. +/// regular vault routes, so the handlers state which one applies. They differ for every member who may edit any +/// collection, an Owner, an Admin or a Custom member with Edit any collection: like in Bitwarden, they reach every +/// cipher of the organization on the administrative routes only, and keep their own vault limited to the collections +/// they are assigned to, with the access they are assigned. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CipherAccessScope { User, @@ -94,10 +95,11 @@ pub enum CipherAccessScope { } impl CipherAccessScope { - /// Whether `member` reaches every cipher of their organization with this access. + /// Whether `member` reaches every cipher of their organization with this access. On the regular vault routes no + /// role does, like Bitwarden's UserCipherDetails: everyone only reaches what they own or are assigned to. fn reaches_all_ciphers(self, member: &Membership) -> bool { match self { - CipherAccessScope::User => member.has_full_access(), + CipherAccessScope::User => false, CipherAccessScope::OrganizationAdmin => member.can_edit_any_collection(), } } @@ -711,25 +713,6 @@ impl Cipher { false } - /// Returns whether this cipher is owned by an group in which the user has full access. - async fn is_in_full_access_group( - &self, - user_uuid: &UserId, - cipher_sync_data: Option<&CipherSyncData>, - conn: &DbConn, - ) -> bool { - if !CONFIG.org_groups_enabled() { - return false; - } - if let Some(ref org_uuid) = self.organization_uuid { - if let Some(cipher_sync_data) = cipher_sync_data { - return cipher_sync_data.user_group_full_access_for_organizations.contains(org_uuid); - } - return Group::is_in_full_access_group(user_uuid, org_uuid, conn).await; - } - false - } - /// Returns the user's access restrictions to this cipher. A return value /// of None means that this cipher does not belong to the user, and is /// not in any collection the user has access to. Otherwise, the user has @@ -742,12 +725,10 @@ impl Cipher { cipher_sync_data: Option<&CipherSyncData>, conn: &DbConn, ) -> Option<(bool, bool, bool)> { - // Check whether this cipher is directly owned by the user, or is in - // a collection that the user has full access to. If so, there are no - // access restrictions. + // Check whether this cipher is directly owned by the user, or the user may reach every cipher of its + // organization. If so, there are no access restrictions. if self.is_owned_by_user(user_uuid) || self.is_in_full_access_org(user_uuid, scope, cipher_sync_data, conn).await - || self.is_in_full_access_group(user_uuid, cipher_sync_data, conn).await { return Some((false, false, true)); } @@ -956,24 +937,10 @@ impl Cipher { .await } - // Find all ciphers accessible or visible to the specified user. - // - // "Accessible" means the user has read access to the cipher, either via - // direct ownership, collection or via group access. - // - // "Visible" usually means the same as accessible, except when an org - // owner/admin sets their account or group to have access to only selected - // collections in the org (presumably because they aren't interested in - // the other collections in the org). In this case, if `visible_only` is - // true, then the non-interesting ciphers will not be returned. As a - // result, those ciphers will not appear in "My Vault" for the org - // owner/admin, but they can still be accessed via the org vault view. - pub async fn find_by_user( - user_uuid: &UserId, - visible_only: bool, - cipher_uuids: &Vec, - conn: &DbConn, - ) -> Vec { + // Find the ciphers the user has read access to in their own vault: the ones they own, and the ones in a collection + // they are assigned to, directly or via a group. Like Bitwarden, the role doesn't add any: an Owner or Admin reaches + // the other ciphers of their organization in the Admin Console. + pub async fn find_by_user(user_uuid: &UserId, cipher_uuids: &Vec, conn: &DbConn) -> Vec { if CONFIG.org_groups_enabled() { conn.run(move |conn| { let mut query = ciphers::table @@ -1005,18 +972,10 @@ impl Cipher { .and(collections_groups::groups_uuid.eq(groups::uuid))), ) .filter(ciphers::user_uuid.eq(user_uuid)) // Cipher owner - .or_filter(users_organizations::access_all.eq(true)) // access_all in org .or_filter(users_collections::user_uuid.eq(user_uuid)) // Access to collection - .or_filter(groups::access_all.eq(true)) // Access via groups .or_filter(collections_groups::collections_uuid.is_not_null()) // Access via groups .into_boxed(); - if !visible_only { - query = query.or_filter( - users_organizations::atype.eq_any(ORG_ADMIN_ATYPES), // Org admin/owner - ); - } - // Only filter for one specific cipher if !cipher_uuids.is_empty() { query = query.filter(ciphers::uuid.eq_any(cipher_uuids)); @@ -1042,16 +1001,9 @@ impl Cipher { .and(users_organizations::user_uuid.eq(users_collections::user_uuid))), ) .filter(ciphers::user_uuid.eq(user_uuid)) // Cipher owner - .or_filter(users_organizations::access_all.eq(true)) // access_all in org .or_filter(users_collections::user_uuid.eq(user_uuid)) // Access to collection .into_boxed(); - if !visible_only { - query = query.or_filter( - users_organizations::atype.eq_any(ORG_ADMIN_ATYPES), // Org admin/owner - ); - } - // Only filter for one specific cipher if !cipher_uuids.is_empty() { query = query.filter(ciphers::uuid.eq_any(cipher_uuids)); @@ -1065,7 +1017,7 @@ impl Cipher { // Find all ciphers visible to the specified user. pub async fn find_by_user_visible(user_uuid: &UserId, conn: &DbConn) -> Vec { - Self::find_by_user(user_uuid, true, &vec![], conn).await + Self::find_by_user(user_uuid, &vec![], conn).await } pub async fn find_by_user_and_ciphers( @@ -1073,11 +1025,11 @@ impl Cipher { cipher_uuids: &Vec, conn: &DbConn, ) -> Vec { - Self::find_by_user(user_uuid, true, cipher_uuids, conn).await + Self::find_by_user(user_uuid, cipher_uuids, conn).await } pub async fn find_by_user_and_cipher(user_uuid: &UserId, cipher_uuid: &CipherId, conn: &DbConn) -> Option { - Self::find_by_user(user_uuid, true, &vec![cipher_uuid.clone()], conn).await.pop() + Self::find_by_user(user_uuid, &vec![cipher_uuid.clone()], conn).await.pop() } // Find all ciphers directly owned by the specified user. @@ -1166,12 +1118,9 @@ impl Cipher { ) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter( - users_organizations::access_all - .eq(true) // User has access all - .or(users_collections::user_uuid - .eq(user_uuid) // User has access to collection - .and(users_collections::read_only.eq(false))) - .or(groups::access_all.eq(true)) // Access via groups + users_collections::user_uuid + .eq(user_uuid) // User has access to collection + .and(users_collections::read_only.eq(false)) .or(collections_groups::collections_uuid .is_not_null() // Access via groups .and(collections_groups::read_only.eq(false))), @@ -1198,11 +1147,9 @@ impl Cipher { ) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter( - users_organizations::access_all - .eq(true) // User has access all - .or(users_collections::user_uuid - .eq(user_uuid) // User has access to collection - .and(users_collections::read_only.eq(false))), + users_collections::user_uuid + .eq(user_uuid) // User has access to collection + .and(users_collections::read_only.eq(false)), ) .select(ciphers_collections::collection_uuid) .load::(conn) @@ -1248,16 +1195,16 @@ impl Cipher { ) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter( - users_organizations::access_all - .eq(true) // User has access all - .or(users_collections::user_uuid - .eq(user_uuid) // User has access to collection - .and(users_collections::read_only.eq(false))) - .or(groups::access_all.eq(true)) // Access via groups + users_collections::user_uuid + .eq(user_uuid) // User has access to collection + .and(users_collections::read_only.eq(false)) .or(collections_groups::collections_uuid .is_not_null() // Access via groups .and(collections_groups::read_only.eq(false))) - .or(users_organizations::atype.eq_any(ORG_ADMIN_ATYPES)) // User is admin or owner + // On the administrative routes only, an Owner or Admin reaches every collection + .or(users_organizations::atype + .eq_any(ORG_ADMIN_ATYPES) + .and::<_, diesel::sql_types::Bool>(scope == CipherAccessScope::OrganizationAdmin)) .or(custom_edit_any_collection() .and::<_, diesel::sql_types::Bool>(scope == CipherAccessScope::OrganizationAdmin)), ) @@ -1283,12 +1230,13 @@ impl Cipher { ) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter( - users_organizations::access_all - .eq(true) // User has access all - .or(users_collections::user_uuid - .eq(user_uuid) // User has access to collection - .and(users_collections::read_only.eq(false))) - .or(users_organizations::atype.eq_any(ORG_ADMIN_ATYPES)) // User is admin or owner + users_collections::user_uuid + .eq(user_uuid) // User has access to collection + .and(users_collections::read_only.eq(false)) + // On the administrative routes only, an Owner or Admin reaches every collection + .or(users_organizations::atype + .eq_any(ORG_ADMIN_ATYPES) + .and::<_, diesel::sql_types::Bool>(scope == CipherAccessScope::OrganizationAdmin)) .or(custom_edit_any_collection() .and::<_, diesel::sql_types::Bool>(scope == CipherAccessScope::OrganizationAdmin)), ) @@ -1330,10 +1278,8 @@ impl Cipher { .eq(ciphers_collections::collection_uuid) .and(collections_groups::groups_uuid.eq(groups::uuid))), ) + // Like upstream, an Owner or Admin only gets the collections they are assigned to .or_filter(users_collections::user_uuid.eq(user_uuid)) // User has access to collection - .or_filter(users_organizations::access_all.eq(true)) // User has access all - .or_filter(users_organizations::atype.eq_any(ORG_ADMIN_ATYPES)) // User is admin or owner - .or_filter(groups::access_all.eq(true)) //Access via group .or_filter(collections_groups::collections_uuid.is_not_null()) //Access via group .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .select(ciphers_collections::all_columns) diff --git a/src/db/models/collection.rs b/src/db/models/collection.rs index 4f1533e3..88abee3c 100644 --- a/src/db/models/collection.rs +++ b/src/db/models/collection.rs @@ -17,8 +17,8 @@ use crate::{ use macros::UuidFromParam; use super::{ - CipherId, CollectionGroup, GroupUser, Membership, MembershipId, MembershipStatus, MembershipType, OrganizationId, - User, UserId, custom_roles_enabled, organization::ORG_ADMIN_ATYPES, + CipherId, CollectionGroup, GroupUser, Membership, MembershipId, MembershipStatus, OrganizationId, User, UserId, + organization::ORG_ADMIN_ATYPES, }; // See (v2026.7.0): https://github.com/bitwarden/server/blob/5d4461aa42cadbacfef8fe2166c5453a5c52773a/src/Core/AdminConsole/Entities/Collection.cs @@ -102,60 +102,25 @@ impl Collection { cipher_sync_data: Option<&crate::api::core::CipherSyncData>, conn: &DbConn, ) -> Value { + // Like Bitwarden, every member gets the access they are assigned, directly or else through a group: the role + // doesn't count, an Owner or Admin reaches the other collections in the Admin Console. A collection they aren't + // assigned to has neither restrictions nor the manage option, as Bitwarden's Admin Console reports it. let (read_only, hide_passwords, manage) = if let Some(cipher_sync_data) = cipher_sync_data { - match cipher_sync_data.members.get(&self.org_uuid) { - // Only for Manager types Bitwarden returns true for the manage option - // Owners and Admins always have true. Users are not able to have full access - Some(m) if m.has_full_access() => (false, false, m.atype >= MembershipType::Manager), - Some(m) => { - // Only let a manager manage collections when the have full read/write access - // A Custom member only manages a collection with the manage option - let is_manager = m.atype == MembershipType::Manager; - let is_custom = m.has_type(MembershipType::Custom) && custom_roles_enabled(); - if let Some(cu) = cipher_sync_data.user_collections.get(&self.uuid) { - ( - cu.read_only, - cu.hide_passwords, - (is_manager && (cu.manage || (!cu.read_only && !cu.hide_passwords))) - || (is_custom && cu.manage), - ) - } else if let Some(cg) = cipher_sync_data.user_collections_groups.get(&self.uuid) { - ( - cg.read_only, - cg.hide_passwords, - (is_manager && (cg.manage || (!cg.read_only && !cg.hide_passwords))) - || (is_custom && cg.manage), - ) - } else { - (false, false, false) - } + if cipher_sync_data.members.contains_key(&self.org_uuid) { + if let Some(cu) = cipher_sync_data.user_collections.get(&self.uuid) { + (cu.read_only, cu.hide_passwords, cu.manage) + } else if let Some(cg) = cipher_sync_data.user_collections_groups.get(&self.uuid) { + (cg.read_only, cg.hide_passwords, cg.manage) + } else { + (false, false, false) } - _ => (true, true, false), + } else { + (true, true, false) } } else { match Membership::find_confirmed_by_user_and_org(user_uuid, &self.org_uuid, conn).await { - Some(m) if m.has_full_access() => (false, false, m.atype >= MembershipType::Manager), - Some(m) if m.atype == MembershipType::Manager && self.is_manageable_by_user(user_uuid, conn).await => { - (false, false, true) - } - // A Custom member reads and writes every collection with Edit any collection in the Admin Console, but - // only manages a collection with the manage option on it - Some(m) if m.has_type(MembershipType::Custom) && custom_roles_enabled() => { - let manage = self.is_explicitly_manageable_by_user(user_uuid, conn).await; - if manage || m.can_edit_any_collection() { - (false, false, manage) - } else { - let read_only = !self.is_writable_by_user(user_uuid, conn).await; - (read_only, self.hide_passwords_for_user(user_uuid, conn).await, false) - } - } - Some(m) => { - let is_manager = m.atype == MembershipType::Manager; - let read_only = !self.is_writable_by_user(user_uuid, conn).await; - let hide_passwords = self.hide_passwords_for_user(user_uuid, conn).await; - (read_only, hide_passwords, is_manager && !read_only && !hide_passwords) - } - _ => (true, true, false), + Some(member) => self.assigned_access(&member, conn).await.unwrap_or((false, false, false)), + None => (true, true, false), } }; @@ -167,13 +132,31 @@ impl Collection { json_object } - pub async fn can_access_collection(member: &Membership, col_id: &CollectionId, conn: &DbConn) -> bool { + /// Whether `member` is assigned to the collection, directly or through a group, which is what Bitwarden's Admin + /// Console calls assigned. The role doesn't count. + pub async fn is_assigned(member: &Membership, col_id: &CollectionId, conn: &DbConn) -> bool { member.has_status(MembershipStatus::Confirmed) - && (member.has_full_access() - || CollectionUser::has_access_to_collection_by_user(col_id, &member.user_uuid, conn).await + && (CollectionUser::has_access_to_collection_by_user(col_id, &member.user_uuid, conn).await || (CONFIG.org_groups_enabled() - && (GroupUser::has_full_access_by_member(&member.org_uuid, &member.uuid, conn).await - || GroupUser::has_access_to_collection_by_member(col_id, &member.uuid, conn).await))) + && GroupUser::has_access_to_collection_by_member(col_id, &member.uuid, conn).await)) + } + + /// The access `member` is assigned to this collection with, as (read only, hide passwords, manage). Like Bitwarden, + /// their own assignment decides, or else the most permissive of their groups. `None` if they are assigned neither way. + pub async fn assigned_access(&self, member: &Membership, conn: &DbConn) -> Option<(bool, bool, bool)> { + if let Some(cu) = CollectionUser::find_by_collection_and_user(&self.uuid, &member.user_uuid, conn).await { + return Some((cu.read_only, cu.hide_passwords, cu.manage)); + } + if !CONFIG.org_groups_enabled() { + return None; + } + CollectionGroup::find_by_collection_and_member(&self.uuid, &member.uuid, conn) + .await + .into_iter() + .map(|cg| (cg.read_only, cg.hide_passwords, cg.manage)) + .reduce(|(read_only, hide_passwords, manage), (ro, hp, mn)| { + (read_only && ro, hide_passwords && hp, manage || mn) + }) } } @@ -265,14 +248,7 @@ impl Collection { .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter( users_collections::user_uuid - .eq(user_uuid) - .or( - // Directly accessed collection - users_organizations::access_all.eq(true), // access_all in Organization - ) - .or( - groups::access_all.eq(true), // access_all in groups - ) + .eq(user_uuid) // Directly accessed collection .or( // access via groups groups_users::users_organizations_uuid @@ -300,10 +276,7 @@ impl Collection { .and(users_organizations::user_uuid.eq(user_uuid.clone()))), ) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) - .filter(users_collections::user_uuid.eq(user_uuid).or( - // Directly accessed collection - users_organizations::access_all.eq(true), // access_all in Organization - )) + .filter(users_collections::user_uuid.eq(user_uuid)) // Directly accessed collection .select(collections::all_columns) .distinct() .load::(conn) @@ -386,16 +359,7 @@ impl Collection { .filter( users_collections::collection_uuid .eq(uuid) - .or( - // Directly accessed collection - users_organizations::access_all.eq(true).or( - // access_all in Organization - users_organizations::atype.eq_any(ORG_ADMIN_ATYPES), // Org admin or owner - ), - ) - .or( - groups::access_all.eq(true), // access_all in groups - ) + .or(users_organizations::atype.eq_any(ORG_ADMIN_ATYPES)) // Org admin or owner .or( // access via groups groups_users::users_organizations_uuid @@ -423,13 +387,11 @@ impl Collection { ) .filter(collections::uuid.eq(uuid)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) - .filter(users_collections::collection_uuid.eq(uuid).or( - // Directly accessed collection - users_organizations::access_all.eq(true).or( - // access_all in Organization - users_organizations::atype.eq_any(ORG_ADMIN_ATYPES), // Org admin or owner - ), - )) + .filter( + users_collections::collection_uuid + .eq(uuid) // Directly accessed collection + .or(users_organizations::atype.eq_any(ORG_ADMIN_ATYPES)), // Org admin or owner + ) .select(collections::all_columns) .first::(conn) .ok() @@ -438,213 +400,16 @@ impl Collection { } } + /// Whether the user may put ciphers into this collection or take them out of it in their own vault. Like Bitwarden's + /// CollectionCipher_UpdateCollections, only the access they are assigned counts, never the role. pub async fn is_writable_by_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool { - let user_uuid = user_uuid.to_string(); - if CONFIG.org_groups_enabled() { - conn.run(move |conn| { - collections::table - .filter(collections::uuid.eq(&self.uuid)) - .inner_join( - users_organizations::table.on(collections::org_uuid - .eq(users_organizations::org_uuid) - .and(users_organizations::user_uuid.eq(user_uuid.clone())) - .and(users_organizations::status.eq(MembershipStatus::Confirmed as i32))), - ) - .left_join( - users_collections::table.on(users_collections::collection_uuid - .eq(collections::uuid) - .and(users_collections::user_uuid.eq(user_uuid))), - ) - .left_join( - groups_users::table.on(groups_users::users_organizations_uuid.eq(users_organizations::uuid)), - ) - .left_join( - groups::table.on(groups::uuid - .eq(groups_users::groups_uuid) - .and(groups::organizations_uuid.eq(users_organizations::org_uuid))), - ) - .left_join( - collections_groups::table.on(collections_groups::groups_uuid - .eq(groups_users::groups_uuid) - .and(collections_groups::collections_uuid.eq(collections::uuid))), - ) - .filter( - users_organizations::atype - .eq_any(ORG_ADMIN_ATYPES) // Org admin or owner - .or(users_organizations::access_all.eq(true)) // access_all via membership - .or(users_collections::collection_uuid - .eq(&self.uuid) // write access given to collection - .and(users_collections::read_only.eq(false))) - .or(groups::access_all.eq(true)) // access_all via group - .or(collections_groups::collections_uuid - .is_not_null() // write access given via group - .and(collections_groups::read_only.eq(false))), - ) - .count() - .first::(conn) - .ok() - .unwrap_or(0) - != 0 - }) - .await - } else { - conn.run(move |conn| { - collections::table - .filter(collections::uuid.eq(&self.uuid)) - .inner_join( - users_organizations::table.on(collections::org_uuid - .eq(users_organizations::org_uuid) - .and(users_organizations::user_uuid.eq(user_uuid.clone())) - .and(users_organizations::status.eq(MembershipStatus::Confirmed as i32))), - ) - .left_join( - users_collections::table.on(users_collections::collection_uuid - .eq(collections::uuid) - .and(users_collections::user_uuid.eq(user_uuid))), - ) - .filter( - users_organizations::atype - .eq_any(ORG_ADMIN_ATYPES) // Org admin or owner - .or(users_organizations::access_all.eq(true)) // access_all via membership - .or(users_collections::collection_uuid - .eq(&self.uuid) // write access given to collection - .and(users_collections::read_only.eq(false))), - ) - .count() - .first::(conn) - .ok() - .unwrap_or(0) - != 0 - }) - .await + match Membership::find_confirmed_by_user_and_org(user_uuid, &self.org_uuid, conn).await { + Some(member) => self.assigned_access(&member, conn).await.is_some_and(|(read_only, _, _)| !read_only), + None => false, } } - pub async fn hide_passwords_for_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool { - let user_uuid = user_uuid.to_string(); - conn.run(move |conn| { - collections::table - .left_join( - users_collections::table.on(users_collections::collection_uuid - .eq(collections::uuid) - .and(users_collections::user_uuid.eq(user_uuid.clone()))), - ) - .left_join( - users_organizations::table.on(collections::org_uuid - .eq(users_organizations::org_uuid) - .and(users_organizations::user_uuid.eq(user_uuid))), - ) - .left_join(groups_users::table.on(groups_users::users_organizations_uuid.eq(users_organizations::uuid))) - .left_join( - groups::table.on(groups::uuid - .eq(groups_users::groups_uuid) - .and(groups::organizations_uuid.eq(users_organizations::org_uuid))), - ) - .left_join( - collections_groups::table.on(collections_groups::groups_uuid - .eq(groups_users::groups_uuid) - .and(collections_groups::collections_uuid.eq(collections::uuid))), - ) - .filter(collections::uuid.eq(&self.uuid)) - .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) - .filter( - users_collections::collection_uuid - .eq(&self.uuid) - .and(users_collections::hide_passwords.eq(true)) - .or( - // Directly accessed collection - users_organizations::access_all.eq(true).or( - // access_all in Organization - users_organizations::atype.eq_any(ORG_ADMIN_ATYPES), // Org admin or owner - ), - ) - .or( - groups::access_all.eq(true), // access_all in groups - ) - .or( - // access via groups - groups_users::users_organizations_uuid.eq(users_organizations::uuid).and( - collections_groups::collections_uuid - .is_not_null() - .and(collections_groups::hide_passwords.eq(true)), - ), - ), - ) - .count() - .first::(conn) - .ok() - .unwrap_or(0) - != 0 - }) - .await - } - - pub async fn is_coll_manageable_by_user(uuid: &CollectionId, user_uuid: &UserId, conn: &DbConn) -> bool { - let uuid = uuid.to_string(); - let user_uuid = user_uuid.to_string(); - conn.run(move |conn| { - collections::table - .left_join( - users_collections::table.on(users_collections::collection_uuid - .eq(collections::uuid) - .and(users_collections::user_uuid.eq(user_uuid.clone()))), - ) - .left_join( - users_organizations::table.on(collections::org_uuid - .eq(users_organizations::org_uuid) - .and(users_organizations::user_uuid.eq(user_uuid))), - ) - .left_join(groups_users::table.on(groups_users::users_organizations_uuid.eq(users_organizations::uuid))) - .left_join( - groups::table.on(groups::uuid - .eq(groups_users::groups_uuid) - .and(groups::organizations_uuid.eq(users_organizations::org_uuid))), - ) - .left_join( - collections_groups::table.on(collections_groups::groups_uuid - .eq(groups_users::groups_uuid) - .and(collections_groups::collections_uuid.eq(collections::uuid))), - ) - .filter(collections::uuid.eq(&uuid)) - .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) - .filter( - users_collections::collection_uuid - .eq(&uuid) - .and(users_collections::manage.eq(true)) - .or( - // Directly accessed collection - users_organizations::access_all.eq(true).or( - // access_all in Organization - users_organizations::atype.eq_any(ORG_ADMIN_ATYPES), // Org admin or owner - ), - ) - .or( - groups::access_all.eq(true), // access_all in groups - ) - .or( - // access via groups - groups_users::users_organizations_uuid.eq(users_organizations::uuid).and( - collections_groups::collections_uuid - .is_not_null() - .and(collections_groups::manage.eq(true)), - ), - ), - ) - .count() - .first::(conn) - .ok() - .unwrap_or(0) - != 0 - }) - .await - } - - pub async fn is_manageable_by_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool { - Self::is_coll_manageable_by_user(&self.uuid, user_uuid, conn).await - } - - // Whether the user has manage access to at least one collection in the org, directly or via a - // group. Org-scoped counterpart of is_coll_manageable_by_user. + // Whether the user has manage access to at least one collection in the org, directly or via a group. pub async fn has_manageable_collection_by_user( org_uuid: &OrganizationId, user_uuid: &UserId, @@ -653,12 +418,8 @@ impl Collection { !Self::find_explicitly_manageable_by_user(org_uuid, user_uuid, conn).await.is_empty() } - pub async fn is_explicitly_manageable_by_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool { - Self::find_explicitly_manageable_by_user(&self.org_uuid, user_uuid, conn).await.contains(&self.uuid) - } - - // The collections of the org the user has manage access to by the manage option, directly or via a group. - // Unlike is_coll_manageable_by_user, neither the role nor any access_all counts. + // The collections of the org the user has manage access to by the manage option, directly or else via a group. The + // role doesn't count: an Owner or Admin manages every collection by it. pub async fn find_explicitly_manageable_by_user( org_uuid: &OrganizationId, user_uuid: &UserId, @@ -690,7 +451,6 @@ impl Collection { .filter( users_collections::manage.eq(true).or(users_collections::user_uuid .is_null() - .or(users_organizations::atype.eq(MembershipType::Manager as i32)) .and(collections_groups::manage.eq(true)) .and::<_, diesel::sql_types::Bool>(groups_enabled)), ) @@ -1000,16 +760,12 @@ pub struct CollectionMembership { } impl CollectionMembership { - pub fn to_json_details_for_member(&self, membership_type: i32) -> Value { + pub fn to_json_details_for_member(&self) -> Value { json!({ "id": self.membership_uuid, "readOnly": self.read_only, "hidePasswords": self.hide_passwords, - "manage": membership_type >= MembershipType::Admin - || self.manage - || (membership_type == MembershipType::Manager - && !self.read_only - && !self.hide_passwords), + "manage": self.manage, }) } } diff --git a/src/db/models/group.rs b/src/db/models/group.rs index c8df7ef2..fa534790 100644 --- a/src/db/models/group.rs +++ b/src/db/models/group.rs @@ -23,7 +23,6 @@ pub struct Group { pub uuid: GroupId, pub organizations_uuid: OrganizationId, pub name: String, - pub access_all: bool, pub external_id: Option, pub creation_date: NaiveDateTime, pub revision_date: NaiveDateTime, @@ -50,19 +49,13 @@ pub struct GroupUser { /// Local methods impl Group { - pub fn new( - organizations_uuid: OrganizationId, - name: String, - access_all: bool, - external_id: Option, - ) -> Self { + pub fn new(organizations_uuid: OrganizationId, name: String, external_id: Option) -> Self { let now = Utc::now().naive_utc(); let mut new_model = Self { uuid: GroupId(crate::util::get_uuid()), organizations_uuid, name, - access_all, external_id: None, creation_date: now, revision_date: now, @@ -84,9 +77,6 @@ impl Group { } pub async fn to_json_details(&self, conn: &DbConn) -> Value { - // If both read_only and hide_passwords are false, then manage should be true - // You can't have an entry with read_only and manage, or hide_passwords and manage - // Or an entry with everything to false let collections_groups: Vec = CollectionGroup::find_by_group(&self.uuid, &self.organizations_uuid, conn) .await .iter() @@ -235,50 +225,6 @@ impl Group { }) .await } - //Returns all organizations the user has full access to - pub async fn get_orgs_by_user_with_full_access(user_uuid: &UserId, conn: &DbConn) -> Vec { - conn.run(move |conn| { - groups_users::table - .inner_join( - users_organizations::table.on(users_organizations::uuid.eq(groups_users::users_organizations_uuid)), - ) - .inner_join( - groups::table.on(groups::uuid - .eq(groups_users::groups_uuid) - .and(groups::organizations_uuid.eq(users_organizations::org_uuid))), - ) - .filter(users_organizations::user_uuid.eq(user_uuid)) - .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) - .filter(groups::access_all.eq(true)) - .select(groups::organizations_uuid) - .distinct() - .load::(conn) - .expect("Error loading organization group full access information for user") - }) - .await - } - - pub async fn is_in_full_access_group(user_uuid: &UserId, org_uuid: &OrganizationId, conn: &DbConn) -> bool { - conn.run(move |conn| { - groups::table - .inner_join(groups_users::table.on(groups_users::groups_uuid.eq(groups::uuid))) - .inner_join( - users_organizations::table.on(users_organizations::uuid - .eq(groups_users::users_organizations_uuid) - .and(users_organizations::org_uuid.eq(groups::organizations_uuid))), - ) - .filter(users_organizations::user_uuid.eq(user_uuid)) - // Only allow full access via a confirmed membership, since - // groups_users rows are kept when a membership is revoked. - .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) - .filter(groups::organizations_uuid.eq(org_uuid)) - .filter(groups::access_all.eq(true)) - .select(groups::access_all) - .first::(conn) - .unwrap_or_default() - }) - .await - } pub async fn delete(&self, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult { CollectionGroup::delete_all_by_group(&self.uuid, org_uuid, conn).await?; @@ -395,6 +341,37 @@ impl CollectionGroup { .await } + /// The assignments to the collection of the groups `member` is in. The caller checks the membership's status. + pub async fn find_by_collection_and_member( + collection_uuid: &CollectionId, + member_uuid: &MembershipId, + conn: &DbConn, + ) -> Vec { + conn.run(move |conn| { + collections_groups::table + .inner_join(groups_users::table.on(groups_users::groups_uuid.eq(collections_groups::groups_uuid))) + .inner_join( + users_organizations::table.on(users_organizations::uuid.eq(groups_users::users_organizations_uuid)), + ) + .inner_join( + groups::table.on(groups::uuid + .eq(collections_groups::groups_uuid) + .and(groups::organizations_uuid.eq(users_organizations::org_uuid))), + ) + .inner_join( + collections::table.on(collections::uuid + .eq(collections_groups::collections_uuid) + .and(collections::org_uuid.eq(groups::organizations_uuid))), + ) + .filter(collections_groups::collections_uuid.eq(collection_uuid)) + .filter(groups_users::users_organizations_uuid.eq(member_uuid)) + .select(collections_groups::all_columns) + .load::(conn) + .expect("Error loading the collection groups of a member") + }) + .await + } + pub async fn find_by_collection(collection_uuid: &CollectionId, conn: &DbConn) -> Vec { conn.run(move |conn| { collections_groups::table @@ -547,25 +524,6 @@ impl GroupUser { .await } - pub async fn has_full_access_by_member( - org_uuid: &OrganizationId, - member_uuid: &MembershipId, - conn: &DbConn, - ) -> bool { - conn.run(move |conn| { - groups_users::table - .inner_join(groups::table.on(groups::uuid.eq(groups_users::groups_uuid))) - .filter(groups::organizations_uuid.eq(org_uuid)) - .filter(groups::access_all.eq(true)) - .filter(groups_users::users_organizations_uuid.eq(member_uuid)) - .count() - .first::(conn) - .unwrap_or(0) - != 0 - }) - .await - } - pub async fn update_user_revision(&self, conn: &DbConn) { match Membership::find_by_uuid(&self.users_organizations_uuid, conn).await { Some(member) => User::update_uuid_revision(&member.user_uuid, conn).await, diff --git a/src/db/models/mod.rs b/src/db/models/mod.rs index e4e77c4d..46ef1c85 100644 --- a/src/db/models/mod.rs +++ b/src/db/models/mod.rs @@ -23,7 +23,7 @@ pub use self::archive::Archive; pub use self::attachment::{Attachment, AttachmentId}; pub use self::auth_request::{AuthRequest, AuthRequestId}; pub use self::cipher::{Cipher, CipherAccessScope, CipherId, RepromptType, is_data_blob_encrypted}; -pub use self::collection::{Collection, CollectionCipher, CollectionId, CollectionUser}; +pub use self::collection::{Collection, CollectionCipher, CollectionId, CollectionMembership, CollectionUser}; pub use self::device::{Device, DeviceId, DeviceType, DeviceWithAuthRequest, PushId}; pub use self::emergency_access::{ EMERGENCY_ACCESS_TIMEOUT_RANGE, EmergencyAccess, EmergencyAccessId, EmergencyAccessStatus, EmergencyAccessType, diff --git a/src/db/models/organization.rs b/src/db/models/organization.rs index 4b859406..fe6c5135 100644 --- a/src/db/models/organization.rs +++ b/src/db/models/organization.rs @@ -64,7 +64,6 @@ pub struct Membership { pub invited_by_email: Option, - pub access_all: bool, pub akey: String, pub status: i32, pub atype: i32, @@ -125,8 +124,7 @@ pub enum MembershipType { Owner = 0, Admin = 1, User = 2, - // The legacy Manager role. The Bitwarden clients no longer know it and are shown a Custom role instead. - Manager = 3, + // 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, } @@ -137,50 +135,32 @@ impl MembershipType { "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), _ => None, } } - /// The role a member invite or edit from the Bitwarden clients asks for, given the member's current - /// role (`None` for an invite). - /// - /// The clients no longer know the legacy Manager role and are shown a Custom role in its place, so a - /// requested Custom role is the legacy Manager unless EXPERIMENTAL_CUSTOM_ROLES is enabled, in which case - /// `custom_permissions` are the permissions requested along with it. An existing Manager or Custom member - /// 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, - current: Option<&Membership>, - custom_permissions: Option<&HashSet>, - ) -> MembershipType { - if requested != MembershipType::Custom { - return requested; - } - match (current, custom_permissions) { - (Some(member), _) if member.has_type(MembershipType::Custom) => MembershipType::Custom, - (Some(member), Some(permissions)) - if member.has_type(MembershipType::Manager) && *permissions != member.legacy_manager_permissions() => - { - MembershipType::Custom - } - (Some(member), _) if member.has_type(MembershipType::Manager) => MembershipType::Manager, - (_, Some(_)) => MembershipType::Custom, - (_, None) => MembershipType::Manager, + /// 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 Manager. + /// 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::Manager => 2, - MembershipType::Admin => 3, - MembershipType::Owner => 4, + MembershipType::Admin => 2, + MembershipType::Owner => 3, } } } @@ -393,7 +373,7 @@ impl Organization { "maxCollections": null, "maxStorageGb": i16::MAX, // The value doesn't matter, we don't check server-side "use2fa": true, - "useCustomPermissions": 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(), @@ -457,7 +437,6 @@ impl Membership { org_uuid, invited_by_email, - access_all: false, akey: String::new(), status: MembershipStatus::Accepted as i32, atype: MembershipType::User as i32, @@ -495,17 +474,13 @@ impl Membership { } /// 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. A Custom role never keeps the legacy - /// `access_all` flag, its reach only comes from its permissions. + /// 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; } } - if new_type == MembershipType::Custom { - self.access_all = false; - } self.atype = new_type as i32; } @@ -517,38 +492,6 @@ impl Membership { } } - /// Why this legacy Manager can't become a Custom member with `permissions` without losing what they may do now, if - /// they can't. A conversion must not silently change their access. A Custom role can't keep access to all - /// collections, which also puts every collection in the Manager's own vault, unless the permissions it is shown as - /// are given up too. And it only manages every collection with Edit any collection, not through a group with access - /// to all collections, which stays dynamic. The collections they manage with the manage permission stay managed. - pub async fn custom_role_conversion_loss( - &self, - permissions: &HashSet, - conn: &DbConn, - ) -> Option<&'static str> { - if !self.has_type(MembershipType::Manager) { - return None; - } - if self.access_all && permissions.is_superset(&self.legacy_manager_permissions()) { - return Some( - "This Manager has access to all collections, which a Custom member can't have: the collections they \ - aren't assigned to would disappear from their vault. Uncheck Manage all collections for them to give \ - that access up, or keep the Manager role.", - ); - } - if !permissions.contains(&CustomPermission::EditAnyCollection) - && GroupUser::has_full_access_by_member(&self.org_uuid, &self.uuid, conn).await - { - return Some( - "This Manager manages every collection through a group with access to all collections, which a Custom \ - member only does with Edit any collection. Grant that permission, or remove them from the group \ - first.", - ); - } - None - } - fn custom_permission(&self, permission: CustomPermission) -> bool { match permission { CustomPermission::ManageUsers => self.manage_users, @@ -585,26 +528,9 @@ impl Membership { CustomPermission::ALL.into_iter().all(|p| !other.custom_permission(p) || self.has_custom_permission(p)) } - /// The permissions the "Manage all collections" a legacy Manager is shown with stands for: their `access_all`. - pub fn legacy_manager_permissions(&self) -> HashSet { - if self.has_type(MembershipType::Manager) && self.access_all { - HashSet::from([ - CustomPermission::CreateNewCollections, - CustomPermission::EditAnyCollection, - CustomPermission::DeleteAnyCollection, - ]) - } else { - HashSet::new() - } - } - - /// The permissions the clients are shown, which a legacy Manager is shown as a Custom member with. + /// The permissions the clients are shown. pub fn shown_custom_permissions(&self) -> HashSet { - if self.has_type(MembershipType::Manager) { - self.legacy_manager_permissions() - } else { - CustomPermission::ALL.into_iter().filter(|p| self.grants_custom_permission(*p)).collect() - } + CustomPermission::ALL.into_iter().filter(|p| self.grants_custom_permission(*p)).collect() } fn custom_permissions_json(&self) -> Value { @@ -655,15 +581,6 @@ impl Membership { } false } - - /// HACK: Convert the manager type to a custom type - /// It will be converted back on other locations - pub fn type_manager_as_custom(&self) -> i32 { - match self.atype { - 3 => 4, - _ => self.atype, - } - } } impl OrganizationApiKey { @@ -783,11 +700,6 @@ impl Membership { pub async fn to_json(&self, conn: &DbConn) -> Value { let org = Organization::find_by_uuid(&self.org_uuid, conn).await.unwrap(); - // HACK: Convert the manager type to a custom type - // It will be converted back on other locations - let membership_type = self.type_manager_as_custom(); - - // A Manager is shown with the 3 Collection permissions set, when they have the access_all permission let permissions = self.custom_permissions_json(); // https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Models/Response/ProfileOrganizationResponseModel.cs @@ -815,7 +727,7 @@ impl Membership { "useKeyConnector": false, "useSecretsManager": false, // Not supported (Not AGPLv3 Licensed) "usePasswordManager": true, - "useCustomPermissions": true, + "useCustomPermissions": custom_roles_enabled(), "useActivateAutofillPolicy": false, "useAdminSponsoredFamilies": false, "useRiskInsights": false, // Not supported (Not AGPLv3 Licensed) @@ -839,8 +751,7 @@ impl Membership { "familySponsorshipValidUntil": null, "familySponsorshipToDelete": null, "accessSecretsManager": false, - // limit collection creation to managers with access_all permission to prevent issues - "limitCollectionCreation": self.atype < MembershipType::Manager || !self.access_all, + "limitCollectionCreation": true, "limitCollectionDeletion": true, "limitItemDeletion": false, "allowAdminAccessToAllCollectionItems": true, @@ -855,7 +766,7 @@ impl Membership { // 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": membership_type, + "type": self.atype, "enabled": true, "object": "profileOrganization", @@ -889,15 +800,8 @@ impl Membership { Vec::new() }; - // Check if a user is in a group which has access to all collections - // If that is the case, we should not return individual collections! - // This is used by admins to view other members, so it must not depend on the membership status - let full_access_group = - CONFIG.org_groups_enabled() && GroupUser::has_full_access_by_member(&self.org_uuid, &self.uuid, conn).await; - - // If collections are to be included, only include them if the user does not have full access via a group or defined to the user it self // 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 && !(full_access_group || self.access_all) { + let collections: Vec = if include_collections { CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn) .await .into_iter() @@ -906,7 +810,7 @@ impl Membership { "id": cu.collection_uuid, "readOnly": cu.read_only, "hidePasswords": cu.hide_passwords, - "manage": cu.manage || (self.atype == MembershipType::Manager && !cu.read_only && !cu.hide_passwords), + "manage": cu.manage, }) }) .collect() @@ -914,10 +818,6 @@ impl Membership { Vec::new() }; - // HACK: Convert the manager type to a custom type - // It will be converted back on other locations - let membership_type = self.type_manager_as_custom(); - // 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) @@ -936,7 +836,7 @@ impl Membership { "collections": collections, "status": status, - "type": membership_type, + "type": self.atype, "twoFactorEnabled": twofactor_enabled, "resetPasswordEnrolled": self.reset_password_key.is_some(), "hasMasterPassword": !user.password_hash.is_empty(), @@ -962,12 +862,9 @@ impl Membership { } pub async fn to_json_details(&self, conn: &DbConn) -> Value { - let coll_uuids = if self.access_all { - vec![] // If we have complete access, no need to fill the array - } else { - let collections = - CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn).await; - collections + let coll_uuids: Vec = + CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn) + .await .iter() .map(|cu| { json!({ @@ -977,8 +874,7 @@ impl Membership { "manage": cu.manage, }) }) - .collect() - }; + .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. @@ -1014,7 +910,7 @@ impl Membership { json!({ "id": self.uuid, "userId": self.user_uuid, - "type": self.type_manager_as_custom(), // HACK: Convert the manager type to a custom type + "type": self.atype, "status": status, "name": user.name, "email": user.email, @@ -1023,12 +919,6 @@ impl Membership { } pub async fn save(&self, conn: &DbConn) -> EmptyResult { - // The legacy `access_all` flag reaches every collection, which a Custom role may only do through its - // permissions, so it must never be stored on one. `set_type` takes care of this. - if self.has_type(MembershipType::Custom) && self.access_all { - err!("A Custom role membership can't have access to all collections") - } - User::update_uuid_revision(&self.user_uuid, conn).await; db_run! { conn: @@ -1099,13 +989,15 @@ impl Membership { 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.access_all || self.atype >= MembershipType::Admin) && self.has_status(MembershipStatus::Confirmed) + 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. Unlike full access, the permission does not add - /// anything to the member's own vault. + /// 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) } @@ -1276,27 +1168,6 @@ impl Membership { .await } - // Get all users which are either owner or admin, or a manager which can manage/access all - // A Custom member with Edit any collection is not listed: the Admin Console sends this list back when a collection - // is saved, which would assign them to it for good, while the others are skipped there for their access_all. - pub async fn find_confirmed_and_manage_all_by_org(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)) - .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))), - ) - .load::(conn) - .unwrap_or_default() - }) - .await - } - pub async fn count_by_org(org_uuid: &OrganizationId, conn: &DbConn) -> i64 { conn.run(move |conn| { users_organizations::table @@ -1492,10 +1363,7 @@ impl Membership { .eq(users_collections::collection_uuid) .and(ciphers_collections::cipher_uuid.eq(&cipher_uuid))), ) - .filter(users_organizations::access_all.eq(true).or( - // AccessAll.. - ciphers_collections::cipher_uuid.eq(&cipher_uuid), // ..or access to collection with cipher - )) + .filter(ciphers_collections::cipher_uuid.eq(&cipher_uuid)) // Access to a collection with the cipher .select(users_organizations::all_columns) .distinct() .load::(conn) @@ -1527,10 +1395,7 @@ impl Membership { .eq(collections_groups::collections_uuid) .and(ciphers_collections::cipher_uuid.eq(&cipher_uuid))), ) - .filter(groups::access_all.eq(true).or( - // AccessAll via groups - ciphers_collections::cipher_uuid.eq(&cipher_uuid), // ..or access to collection via group - )) + .filter(ciphers_collections::cipher_uuid.eq(&cipher_uuid)) // Access to a collection via a group .select(users_organizations::all_columns) .distinct() .load::(conn) @@ -1548,10 +1413,7 @@ impl Membership { 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_organizations::access_all.eq(true).or( - // AccessAll.. - users_collections::collection_uuid.eq(&collection_uuid), // ..or access to collection with cipher - )) + .filter(users_collections::collection_uuid.eq(&collection_uuid)) // Access to the collection .select(users_organizations::all_columns) .load::(conn) .expect("Error loading user organizations") @@ -1667,7 +1529,7 @@ pub struct OrgApiKeyId(String); mod tests { use super::*; use CustomPermission::*; - use MembershipType::{Admin, Custom, Manager, Owner, User}; + use MembershipType::{Admin, Custom, Owner, User}; fn member(role: MembershipType) -> Membership { let mut member = Membership::new("user".into(), "org".into(), None); @@ -1678,52 +1540,32 @@ 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)); + 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", Some(Manager)), - ("Manager", Some(Manager)), - ("4", Some(Custom)), - ("Custom", Some(Custom)), - ("5", None), - ] { + 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() { - let none = HashSet::new(); - let edit = HashSet::from([EditAnyCollection]); - let legacy = HashSet::from([CreateNewCollections, EditAnyCollection, DeleteAnyCollection]); - for (current, all, permissions, disabled, enabled) in [ - (None, false, &none, Manager, Custom), - (Some(User), false, &edit, Manager, Custom), - (Some(Owner), false, &none, Manager, Custom), - (Some(Manager), false, &none, Manager, Manager), - (Some(Manager), true, &legacy, Manager, Manager), - (Some(Manager), false, &edit, Manager, Custom), - (Some(Manager), true, &none, Manager, Custom), - (Some(Manager), true, &edit, Manager, Custom), - (Some(Custom), false, &none, Custom, Custom), - ] { - let current = current.map(|role| { - let mut m = member(role); - m.access_all = all; - m - }); - for (permissions, expected) in [(None, disabled), (Some(permissions), enabled)] { - assert_eq!(MembershipType::requested(Custom, current.as_ref(), permissions), expected); + 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:?}"); + } } } - assert_eq!(MembershipType::requested(User, Some(&member(Custom)), None), User); - assert_eq!(MembershipType::requested(User, Some(&member(Manager)), None), User); - for requested in [Owner, Admin, Manager] { - assert_eq!(MembershipType::requested(requested, Some(&member(Custom)), None), requested); - } + test_flag::CUSTOM_ROLES_ENABLED.set(None); } #[test] @@ -1760,18 +1602,10 @@ mod tests { #[test] fn role_changes_drop_custom_permissions() { - for (from, to) in [ - (Custom, Owner), - (Custom, Admin), - (Custom, Manager), - (Custom, User), - (User, Custom), - (Manager, Custom), - (Custom, Custom), - (Admin, User), - ] { + for (from, to) in + [(Custom, Owner), (Custom, Admin), (Custom, User), (User, Custom), (Custom, Custom), (Admin, User)] + { let mut member = member(from); - member.access_all = true; for permission in CustomPermission::ALL { *member.custom_permission_mut(permission) = true; } @@ -1779,24 +1613,17 @@ mod tests { for permission in CustomPermission::ALL { assert_eq!(*member.custom_permission_mut(permission), from == to, "{from:?} -> {to:?}"); } - assert_eq!(member.access_all, to != Custom); } } #[test] fn permission_matrix_preserves_role_status_flag_and_collection_boundaries() { - let legacy = HashSet::from([CreateNewCollections, EditAnyCollection, DeleteAnyCollection]); - for (role, all) in - [(Owner, false), (Admin, false), (Manager, false), (Manager, true), (Custom, false), (User, false)] - { + for role in [Owner, Admin, Custom, User] { for permission in CustomPermission::ALL { let mut member = member(role); - member.access_all = all; *member.custom_permission_mut(permission) = true; for enabled in [false, true] { test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled)); - let shown = if role == Manager && all { - legacy.clone() - } else if role == Custom && enabled && permission.is_supported() { + let shown = if role == Custom && enabled && permission.is_supported() { HashSet::from([permission]) } else { HashSet::new() @@ -1805,7 +1632,7 @@ mod tests { 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 || all); + let full = status == 2 && (role == Owner || role == Admin); let edit = full || (allowed && permission == EditAnyCollection); let view = full || (allowed && matches!(permission, EditAnyCollection | DeleteAnyCollection)); assert_eq!( @@ -1815,7 +1642,7 @@ mod tests { member.can_view_all_collections() ), (allowed, edit, view), - "{role:?} {all} {enabled} {status} {permission:?}" + "{role:?} {enabled} {status} {permission:?}" ); assert_eq!( (member.can_list_all_collections(), member.can_list_all_ciphers()), diff --git a/src/db/schema.rs b/src/db/schema.rs index 112e14e6..edb07eb7 100644 --- a/src/db/schema.rs +++ b/src/db/schema.rs @@ -254,7 +254,6 @@ table! { user_uuid -> Text, org_uuid -> Text, invited_by_email -> Nullable, - access_all -> Bool, akey -> Text, status -> Integer, atype -> Integer, @@ -328,7 +327,6 @@ table! { uuid -> Text, organizations_uuid -> Text, name -> Text, - access_all -> Bool, external_id -> Nullable, creation_date -> Timestamp, revision_date -> Timestamp, diff --git a/src/static/scripts/admin_users.js b/src/static/scripts/admin_users.js index 63128627..74b3f176 100644 --- a/src/static/scripts/admin_users.js +++ b/src/static/scripts/admin_users.js @@ -173,10 +173,6 @@ const ORG_TYPES = { "name": "User", "bg": "blue" }, - "3": { - "name": "Manager", - "bg": "green" - }, "4": { "name": "Custom", "bg": "teal" diff --git a/src/static/templates/admin/users.hbs b/src/static/templates/admin/users.hbs index 22d8205c..abd5b9f3 100644 --- a/src/static/templates/admin/users.hbs +++ b/src/static/templates/admin/users.hbs @@ -132,9 +132,6 @@
-
- -
{{#if custom_roles_enabled}}
diff --git a/src/static/templates/scss/vaultwarden.scss.hbs b/src/static/templates/scss/vaultwarden.scss.hbs index 49cfb549..b56684cd 100644 --- a/src/static/templates/scss/vaultwarden.scss.hbs +++ b/src/static/templates/scss/vaultwarden.scss.hbs @@ -104,8 +104,8 @@ app-security > app-two-factor-setup > form { @extend %vw-hide; } {{else}} -:is(bit-dialog, [bit-dialog]) div.tw-ml-4:has(bit-form-control input), -:is(bit-dialog, [bit-dialog]) div.tw-col-span-4:has(input[formcontrolname*="access"], input[formcontrolname*="manage"]) { +/* An existing Custom member keeps the role, but has no permissions to show */ +:is(bit-dialog, [bit-dialog]) div.tw-grid:has(> div.tw-col-span-4 input[formcontrolname="accessEventLogs"]) { @extend %vw-hide; } {{/if}}