Browse Source

Merge c82156a166 into 4051a4d3a6

pull/7969/merge
Tom 7 hours ago
committed by GitHub
parent
commit
474d5652a4
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 6
      migrations/mysql/2026-11-15-140000_remove_access_all/down.sql
  2. 62
      migrations/mysql/2026-11-15-140000_remove_access_all/up.sql
  3. 6
      migrations/postgresql/2026-11-15-140000_remove_access_all/down.sql
  4. 62
      migrations/postgresql/2026-11-15-140000_remove_access_all/up.sql
  5. 6
      migrations/sqlite/2026-11-15-140000_remove_access_all/down.sql
  6. 62
      migrations/sqlite/2026-11-15-140000_remove_access_all/up.sql
  7. 34
      src/api/admin.rs
  8. 34
      src/api/core/ciphers.rs
  9. 380
      src/api/core/organizations.rs
  10. 3
      src/api/core/public.rs
  11. 74
      src/auth.rs
  12. 273
      src/db/mod.rs
  13. 130
      src/db/models/cipher.rs
  14. 358
      src/db/models/collection.rs
  15. 106
      src/db/models/group.rs
  16. 2
      src/db/models/mod.rs
  17. 297
      src/db/models/organization.rs
  18. 2
      src/db/schema.rs
  19. 4
      src/static/scripts/admin_users.js
  20. 3
      src/static/templates/admin/users.hbs
  21. 4
      src/static/templates/scss/vaultwarden.scss.hbs

6
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);

62
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;

6
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);

62
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;

6
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);

62
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;

34
src/api/admin.rs

@ -1,4 +1,4 @@
use std::{collections::HashMap, env, sync::LazyLock}; use std::{env, sync::LazyLock};
use reqwest::Method; use reqwest::Method;
use rocket::{ use rocket::{
@ -393,18 +393,6 @@ async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<Stri
usr["sso_identifier"] = json!(sso_u.map_or(String::new(), |u| u.identifier.to_string())); usr["sso_identifier"] = json!(sso_u.map_or(String::new(), |u| u.identifier.to_string()));
// The clients are shown a Manager as a Custom member, but the admin panel tells the two roles apart
let roles: HashMap<String, i32> = 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); users_json.push(usr);
} }
@ -580,15 +568,10 @@ async fn update_membership_type(data: Json<MembershipTypeData>, token: AdminToke
err!("The specified user isn't member of the organization") err!("The specified user isn't member of the organization")
}; };
let new_type = match MembershipType::from_str(&data.user_type.into_string()) { let Some(new_type) = MembershipType::from_str(&data.user_type.into_string()) else {
// Unlike the clients, the admin panel tells the Custom and the legacy Manager role apart. Unless Custom roles err!("Invalid type")
// 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"),
}; };
MembershipType::check_requested(new_type, Some(&member_to_edit))?;
if member_to_edit.atype == MembershipType::Owner && new_type != MembershipType::Owner { if member_to_edit.atype == MembershipType::Owner && new_type != MembershipType::Owner {
// Removing owner permission, check that there is at least one other confirmed 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<MembershipTypeData>, 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); 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 // 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?; OrgPolicy::check_user_allowed(&member_to_edit, "modify", &conn).await?;

34
src/api/core/ciphers.rs

@ -23,8 +23,8 @@ use crate::{
models::{ models::{
Archive, Attachment, AttachmentId, Cipher, CipherAccessScope, CipherId, Collection, CollectionCipher, Archive, Attachment, AttachmentId, Cipher, CipherAccessScope, CipherId, Collection, CollectionCipher,
CollectionGroup, CollectionId, CollectionUser, CustomPermission, EventType, Favorite, Folder, FolderCipher, CollectionGroup, CollectionId, CollectionUser, CustomPermission, EventType, Favorite, Folder, FolderCipher,
FolderId, Group, KeyId, Membership, MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, FolderId, KeyId, Membership, MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, Send,
Send, User, UserId, is_data_blob_encrypted, User, UserId, is_data_blob_encrypted,
}, },
}, },
util::{NumberOrString, deser_opt_nonempty_str, save_temp_file}, util::{NumberOrString, deser_opt_nonempty_str, save_temp_file},
@ -2731,7 +2731,6 @@ pub struct CipherSyncData {
pub members: HashMap<OrganizationId, Membership>, pub members: HashMap<OrganizationId, Membership>,
pub user_collections: HashMap<CollectionId, CollectionUser>, pub user_collections: HashMap<CollectionId, CollectionUser>,
pub user_collections_groups: HashMap<CollectionId, CollectionGroup>, pub user_collections_groups: HashMap<CollectionId, CollectionGroup>,
pub user_group_full_access_for_organizations: HashSet<OrganizationId>,
} }
#[derive(Eq, PartialEq)] #[derive(Eq, PartialEq)]
@ -2817,13 +2816,6 @@ impl CipherSyncData {
HashMap::new() HashMap::new()
}; };
// Get all organizations that the given user has full access to via group assignment
let user_group_full_access_for_organizations: HashSet<OrganizationId> = if CONFIG.org_groups_enabled() {
Group::get_orgs_by_user_with_full_access(user_id, conn).await.into_iter().collect()
} else {
HashSet::new()
};
Self { Self {
cipher_attachments, cipher_attachments,
cipher_folders, cipher_folders,
@ -2833,7 +2825,6 @@ impl CipherSyncData {
members, members,
user_collections, user_collections,
user_collections_groups, user_collections_groups,
user_group_full_access_for_organizations,
} }
} }
} }
@ -2946,19 +2937,16 @@ mod custom_role_tests {
for request in [None, Some(false)] { for request in [None, Some(false)] {
assert_eq!(CipherAccessScope::requested(request), CipherAccessScope::User); assert_eq!(CipherAccessScope::requested(request), CipherAccessScope::User);
} }
for (role, status, all, allowed) in [ for (role, status, allowed) in [
(MembershipType::User, 2, false, false), (MembershipType::User, 2, false),
(MembershipType::Custom, 2, false, false), (MembershipType::Custom, 2, false),
(MembershipType::Manager, 2, false, false), (MembershipType::Owner, 2, true),
(MembershipType::Manager, 2, true, true), (MembershipType::Admin, 2, true),
(MembershipType::Owner, 2, false, true), (MembershipType::Admin, 1, false),
(MembershipType::Admin, 2, false, true), (MembershipType::Admin, -126, false),
(MembershipType::Admin, 1, false, false),
(MembershipType::Admin, -126, false, false),
] { ] {
member.set_type(role); member.set_type(role);
member.status = status; member.status = status;
member.access_all = all;
member.save(&conn).await.unwrap(); member.save(&conn).await.unwrap();
assert_eq!( assert_eq!(
CipherAccessScope::for_member(Some(&member)), CipherAccessScope::for_member(Some(&member)),
@ -2970,10 +2958,12 @@ mod custom_role_tests {
); );
for org_id in [&org.uuid, &foreign.uuid] { for org_id in [&org.uuid, &foreign.uuid] {
cipher.organization_uuid = Some(org_id.clone()); 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] { for scope in [CipherAccessScope::User, admin_scope] {
assert_eq!( assert_eq!(
cipher.is_write_accessible_to_user(&user.uuid, scope, &conn).await, cipher.is_write_accessible_to_user(&user.uuid, scope, &conn).await,
allowed && org_id == &org.uuid allowed && org_id == &org.uuid && scope == admin_scope
); );
} }
} }

380
src/api/core/organizations.rs

@ -14,17 +14,17 @@ use crate::{
auth::{ auth::{
AccessImportExportHeaders, AdminHeaders, CollectionAction, CollectionDeleteHeaders, CollectionReadHeaders, AccessImportExportHeaders, AdminHeaders, CollectionAction, CollectionDeleteHeaders, CollectionReadHeaders,
CollectionUsersReadHeaders, Headers, ManageGroupsHeaders, ManagePoliciesHeaders, ManageResetPasswordHeaders, CollectionUsersReadHeaders, Headers, ManageGroupsHeaders, ManagePoliciesHeaders, ManageResetPasswordHeaders,
ManageUsersHeaders, ManagerHeaders, ManagerHeadersLoose, OrgMemberHeaders, OwnerHeaders, custom_member_may, ManageUsersHeaders, ManagerHeaders, ManagerHeadersLoose, OrgMemberHeaders, OwnerHeaders, decode_invite,
decode_invite, member_may,
}, },
db::{ db::{
DbConn, DbConn,
models::{ models::{
Cipher, CipherAccessScope, CipherId, Collection, CollectionCipher, CollectionGroup, CollectionId, Cipher, CipherAccessScope, CipherId, Collection, CollectionCipher, CollectionGroup, CollectionId,
CollectionUser, CustomPermission, Device, EventType, FillAssistPolicyData, Group, GroupId, GroupUser, CollectionMembership, CollectionUser, CustomPermission, Device, EventType, FillAssistPolicyData, Group,
Invitation, KeyId, Membership, MembershipId, MembershipStatus, MembershipType, OrgPolicy, OrgPolicyType, GroupId, GroupUser, Invitation, KeyId, Membership, MembershipId, MembershipStatus, MembershipType,
Organization, OrganizationApiKey, OrganizationId, TwoFactor, TwoFactorType, User, UserId, OrgPolicy, OrgPolicyType, Organization, OrganizationApiKey, OrganizationId, TwoFactor, TwoFactorType, User,
custom_roles_enabled, UserId, custom_roles_enabled,
}, },
}, },
mail, mail,
@ -217,13 +217,14 @@ async fn create_organization(headers: Headers, data: Json<OrgData>, conn: DbConn
let collection = Collection::new(org.uuid.clone(), data.collection_name, None); let collection = Collection::new(org.uuid.clone(), data.collection_name, None);
member.akey = data.key; member.akey = data.key;
member.access_all = true;
member.atype = MembershipType::Owner as i32; member.atype = MembershipType::Owner as i32;
member.status = MembershipStatus::Confirmed as i32; member.status = MembershipStatus::Confirmed as i32;
org.save(&conn).await?; org.save(&conn).await?;
member.save(&conn).await?; member.save(&conn).await?;
collection.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())) 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() { let collections = if headers.membership.can_list_all_collections() {
get_org_collections_impl(&org_id, &conn).await get_org_collections_impl(&org_id, &conn).await
} else if headers.membership.has_type(MembershipType::Custom) { } else {
// A Custom member gets the collections they may manage // Everyone else gets the collections they manage
let manageable = let manageable =
Collection::find_explicitly_manageable_by_user(&org_id, &headers.membership.user_uuid, &conn).await; Collection::find_explicitly_manageable_by_user(&org_id, &headers.membership.user_uuid, &conn).await;
Collection::find_by_organization(&org_id, &conn) 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)) .filter(|collection| manageable.contains(&collection.uuid))
.map(Collection::to_json) .map(Collection::to_json)
.collect::<Value>() .collect::<Value>()
} else {
err_code!("Resource not found.", "User does not have full access", Status::NotFound.code);
}; };
Ok(Json(json!({ 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 // 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; 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 // As in Bitwarden, a member who may not read the access of every collection only gets those they manage. Manage
// This lists other members for admins, so it must not depend on the membership status // users and Manage groups may read collection access details without editing collection metadata.
let membership_type: HashMap<MembershipId, i32> = let manageable_collections = if !member.can_view_all_collection_access_details()
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()
&& !member.has_custom_permission(CustomPermission::ManageGroups) && !member.has_custom_permission(CustomPermission::ManageGroups)
{ {
Some(Collection::find_explicitly_manageable_by_user(&org_id, &member.user_uuid, &conn).await) 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 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<Value> = 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(); let mut data = Vec::new();
for col in Collection::find_by_organization(&org_id, &conn).await { for col in Collection::find_by_organization(&org_id, &conn).await {
// check whether the current user has access to the given collection if manageable_collections.as_ref().is_some_and(|manageable| !manageable.contains(&col.uuid)) {
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 {
continue; continue;
} }
// get the users assigned directly to the given collection // the members assigned directly to the given collection
let mut users: Vec<Value> = col_users let collection_members: Vec<&CollectionMembership> =
.iter() col_users.iter().filter(|collection_member| collection_member.collection_uuid == col.uuid).collect();
.filter(|collection_member| collection_member.collection_uuid == col.uuid) let users: Vec<Value> = collection_members.iter().map(|cm| cm.to_json_details_for_member()).collect();
.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);
// get the group details for the given collection // the groups assigned to the given collection
let groups: Vec<Value> = if CONFIG.org_groups_enabled() { let collection_groups = if CONFIG.org_groups_enabled() {
CollectionGroup::find_by_collection(&col.uuid, &conn) CollectionGroup::find_by_collection(&col.uuid, &conn).await
.await
.iter()
.map(CollectionGroup::to_json_details_for_group)
.collect()
} else { } else {
Vec::new() Vec::new()
}; };
let groups: Vec<Value> = 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; 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["users"] = json!(users);
json_object["groups"] = json!(groups); json_object["groups"] = json!(groups);
json_object["object"] = json!("collectionAccessDetails"); json_object["object"] = json!("collectionAccessDetails");
json_object["unmanaged"] = json!(false); json_object["unmanaged"] = json!(is_unmanaged(&collection_members, &collection_groups));
data.push(json_object); 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 { 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::<Value>() Collection::find_by_organization(org_id, conn).await.iter().map(Collection::to_json).collect::<Value>()
} }
@ -516,9 +477,9 @@ async fn post_organization_collections(
let data: FullCollectionData = data.into_inner(); let data: FullCollectionData = data.into_inner();
data.validate(&org_id, &conn).await?; data.validate(&org_id, &conn).await?;
if (headers.membership.atype == MembershipType::Manager && !headers.membership.access_all) // The clients are told collection creation is limited
|| (headers.membership.has_type(MembershipType::Custom) if !headers.membership.has_full_access()
&& !headers.membership.has_custom_permission(CustomPermission::CreateNewCollections)) && !headers.membership.has_custom_permission(CustomPermission::CreateNewCollections)
{ {
err!("You don't have permission to create collections") 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") err!("User is not part of organization")
}; };
if member.access_all {
continue;
}
CollectionUser::save( CollectionUser::save(
&member.user_uuid, &member.user_uuid,
&collection.uuid, &collection.uuid,
@ -604,13 +561,9 @@ async fn post_bulk_access_collections(
err_code!("One or more collections not found.", Status::NotFound.code) err_code!("One or more collections not found.", Status::NotFound.code)
}; };
let manageable = if headers.membership.has_type(MembershipType::Custom) { let manageable = member_may(CollectionAction::Edit, &headers.membership, &collection.uuid, &conn).await
custom_member_may(CollectionAction::Edit, &headers.membership, &collection.uuid, &conn).await || (headers.membership.has_custom_permission(CustomPermission::ManageUsers)
|| (headers.membership.has_custom_permission(CustomPermission::ManageUsers) && headers.membership.has_custom_permission(CustomPermission::ManageGroups));
&& headers.membership.has_custom_permission(CustomPermission::ManageGroups))
} else {
collection.is_manageable_by_user(&headers.membership.user_uuid, &conn).await
};
if !manageable { if !manageable {
err_code!( err_code!(
"Resource not found.", "Resource not found.",
@ -659,10 +612,6 @@ async fn post_bulk_access_collections(
} }
for (user, member) in data.users.iter().zip(&members) { 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) CollectionUser::save(&member.user_uuid, &col_id, user.read_only, user.hide_passwords, user.manage, &conn)
.await?; .await?;
} }
@ -727,10 +676,6 @@ async fn put_organization_collection_update(
err!("User is not part of organization") 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) CollectionUser::save(&member.user_uuid, &col_id, user.read_only, user.hide_passwords, user.manage, &conn)
.await?; .await?;
} }
@ -827,44 +772,31 @@ async fn get_org_collection_detail(
err!("Collection is not owned by organization") err!("Collection is not owned by organization")
} }
let groups: Vec<Value> = if CONFIG.org_groups_enabled() { // The Bitwarden clients seem to call this API regardless of whether groups are enabled,
CollectionGroup::find_by_collection(&collection.uuid, &conn) // so just act as if there are no groups.
.await let collection_groups = if CONFIG.org_groups_enabled() {
.iter() CollectionGroup::find_by_collection(&collection.uuid, &conn).await
.map(CollectionGroup::to_json_details_for_group)
.collect()
} else { } 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() Vec::new()
}; };
let groups: Vec<Value> = 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 let collection_members =
// 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<MembershipId, i32> =
Membership::find_by_org(&org_id, &conn).await.into_iter().map(|m| (m.uuid, m.atype)).collect();
let users: Vec<Value> =
CollectionUser::find_by_org_and_coll_swap_user_uuid_with_member_uuid(&org_id, &collection.uuid, &conn) CollectionUser::find_by_org_and_coll_swap_user_uuid_with_member_uuid(&org_id, &collection.uuid, &conn)
.await .await;
.iter() let users: Vec<Value> =
.map(|collection_member| { collection_members.iter().map(CollectionMembership::to_json_details_for_member).collect();
collection_member.to_json_details_for_member(
*membership_type // Like Bitwarden, whether the current user is assigned to it themselves, the role doesn't count
.get(&collection_member.membership_uuid) let assigned = Collection::is_assigned(&member, &collection.uuid, &conn).await;
.unwrap_or(&(MembershipType::User as i32)), let unmanaged = is_unmanaged(&collection_members.iter().collect::<Vec<_>>(), &collection_groups);
)
})
.collect();
let assigned = Collection::can_access_collection(&member, &collection.uuid, &conn).await;
let mut json_object = collection.to_json_details(&headers.user.uuid, None, &conn).await; let mut json_object = collection.to_json_details(&headers.user.uuid, None, &conn).await;
json_object["assigned"] = json!(assigned); json_object["assigned"] = json!(assigned);
json_object["users"] = json!(users); json_object["users"] = json!(users);
json_object["groups"] = json!(groups); json_object["groups"] = json!(groups);
json_object["object"] = json!("collectionAccessDetails"); json_object["object"] = json!("collectionAccessDetails");
json_object["unmanaged"] = json!(unmanaged);
Ok(Json(json_object)) 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()) { if recovery_only && (!u.has_status(MembershipStatus::Confirmed) || u.reset_password_key.is_none()) {
continue; continue;
} }
// The user can be a manager instead of an admin, but we've checked above that they have full access
users_json.push( users_json.push(
u.to_json_details_for_admin( u.to_json_details_for_admin(
data.include_collections.unwrap_or(false), data.include_collections.unwrap_or(false),
@ -1174,19 +1105,16 @@ async fn send_invite(
let data: InviteData = data.into_inner(); let data: InviteData = data.into_inner();
data.validate(&org_id, &conn).await?; 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 let Some(new_type) = MembershipType::from_str(&data.r#type.into_string()) else {
// 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 {
err!("Invalid type") err!("Invalid type")
}; };
MembershipType::check_requested(new_type, None)?;
// Checked before anything is created, so a rejected permission leaves nothing behind // 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)?) Some(CustomPermission::requested(&data.permissions)?)
} else { } else {
None None
}; };
let new_type = MembershipType::requested(requested_type, None, custom_permissions.as_ref());
check_role_manageable(headers.membership_type, new_type as i32)?; check_role_manageable(headers.membership_type, new_type as i32)?;
if headers.membership_type == MembershipType::Custom { if headers.membership_type == MembershipType::Custom {
@ -1196,16 +1124,6 @@ async fn send_invite(
.await?; .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; let mut user_created: bool;
for email in &data.emails { for email in &data.emails {
let mut member_status = MembershipStatus::Invited as i32; 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())); 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.set_type(new_type);
new_member.access_all = access_all;
if let Some(permissions) = &custom_permissions { if let Some(permissions) = &custom_permissions {
new_member.set_custom_permissions(permissions); new_member.set_custom_permissions(permissions);
} }
@ -1293,22 +1210,19 @@ async fn send_invite(
) )
.await; .await;
// If no accessAll, add the collections received for col in data.collections.iter().flatten() {
if !access_all { match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await {
for col in data.collections.iter().flatten() { None => err!("Collection not found in Organization"),
match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await { Some(collection) => {
None => err!("Collection not found in Organization"), CollectionUser::save(
Some(collection) => { &user.uuid,
CollectionUser::save( &collection.uuid,
&user.uuid, col.read_only,
&collection.uuid, col.hide_passwords,
col.read_only, col.manage,
col.hide_passwords, &conn,
col.manage, )
&conn, .await?;
)
.await?;
}
} }
} }
} }
@ -1626,8 +1540,8 @@ async fn get_org_user_mini_details(org_id: OrganizationId, headers: ManagerHeade
if org_id != headers.membership.org_uuid { if org_id != headers.membership.org_uuid {
err!("Organization not found", "Organization id's do not match"); err!("Organization not found", "Organization id's do not match");
} }
// A Custom member may also need basic member details for event logs or reports. // Besides those assigning collection access, a Custom member may need basic member details for event logs or reports.
if headers.membership.has_type(MembershipType::Custom) if !headers.membership.has_full_access()
&& !headers.membership.has_custom_permission(CustomPermission::AccessEventLogs) && !headers.membership.has_custom_permission(CustomPermission::AccessEventLogs)
&& !headers.membership.has_custom_permission(CustomPermission::AccessReports) && !headers.membership.has_custom_permission(CustomPermission::AccessReports)
&& !may_assign_collection_access(&headers.membership, &conn).await && !may_assign_collection_access(&headers.membership, &conn).await
@ -1692,40 +1606,20 @@ async fn edit_member(
} }
let data: EditUserData = data.into_inner(); 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 let Some(new_type) = MembershipType::from_str(&data.r#type.into_string()) else {
// 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 {
err!("Invalid type") err!("Invalid type")
}; };
let Some(mut member_to_edit) = Membership::find_by_uuid_and_org(&member_id, &org_id, &conn).await else { 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") 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 // 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)?) Some(CustomPermission::requested(&data.permissions)?)
} else { } else {
None 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 // Both the current and the requested role must be one the caller may manage
check_role_manageable(headers.membership_type, member_to_edit.atype)?; 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.set_type(new_type);
member_to_edit.access_all = access_all;
if let Some(permissions) = custom_permissions.as_ref().filter(|_| new_type == MembershipType::Custom) { if let Some(permissions) = custom_permissions.as_ref().filter(|_| new_type == MembershipType::Custom) {
member_to_edit.set_custom_permissions(permissions); member_to_edit.set_custom_permissions(permissions);
} }
@ -1771,22 +1664,19 @@ async fn edit_member(
c.delete(&conn).await?; c.delete(&conn).await?;
} }
// If no accessAll, add the collections received for col in data.collections.iter().flatten() {
if !access_all { match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await {
for col in data.collections.iter().flatten() { None => err!("Collection not found in Organization"),
match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn).await { Some(collection) => {
None => err!("Collection not found in Organization"), CollectionUser::save(
Some(collection) => { &member_to_edit.user_uuid,
CollectionUser::save( &collection.uuid,
&member_to_edit.user_uuid, col.read_only,
&collection.uuid, col.hide_passwords,
col.read_only, col.manage,
col.hide_passwords, &conn,
col.manage, )
&conn, .await?;
)
.await?;
}
} }
} }
} }
@ -2014,10 +1904,7 @@ async fn validate_org_import_collections(
) -> ApiResult<HashMap<CollectionId, Collection>> { ) -> ApiResult<HashMap<CollectionId, Collection>> {
let existing: HashMap<CollectionId, Collection> = let existing: HashMap<CollectionId, Collection> =
Collection::find_by_organization(org_id, conn).await.into_iter().map(|c| (c.uuid.clone(), c)).collect(); Collection::find_by_organization(org_id, conn).await.into_iter().map(|c| (c.uuid.clone(), c)).collect();
let manageable = if membership.atype < MembershipType::Admin let manageable = if membership.atype < MembershipType::Admin && !membership.can_edit_any_collection() {
&& !membership.can_edit_any_collection()
&& !membership.has_type(MembershipType::Manager)
{
Some( Some(
Collection::find_explicitly_manageable_by_user(org_id, &membership.user_uuid, conn) Collection::find_explicitly_manageable_by_user(org_id, &membership.user_uuid, conn)
.await .await
@ -2029,18 +1916,12 @@ async fn validate_org_import_collections(
}; };
for col in imported { for col in imported {
if let Some(collection) = col.id.as_ref().and_then(|id| existing.get(id)) { if let Some(collection) = col.id.as_ref().and_then(|id| existing.get(id)) {
if membership.atype < MembershipType::Admin && !membership.can_edit_any_collection() { if let Some(manageable) = &manageable
let can_import = if let Some(manageable) = &manageable { && !manageable.contains(&collection.uuid)
manageable.contains(&collection.uuid) {
} else { err!(Compact, "The current user isn't allowed to manage this collection")
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")
}
} }
} else if membership.atype <= MembershipType::Manager } else if !membership.has_full_access()
&& !membership.has_full_access()
&& !membership.has_custom_permission(CustomPermission::CreateNewCollections) && !membership.has_custom_permission(CustomPermission::CreateNewCollections)
&& !import_export && !import_export
{ {
@ -2083,7 +1964,6 @@ async fn post_org_import(
collections: imported_collections, collections: imported_collections,
.. ..
} = data; } = data;
let grant_new_collection_manage = headers.membership.has_type(MembershipType::Custom);
let importer_uuid = headers.membership.user_uuid.clone(); let importer_uuid = headers.membership.user_uuid.clone();
let OrgMemberHeaders { let OrgMemberHeaders {
host, host,
@ -2111,9 +1991,8 @@ async fn post_org_import(
} else { } else {
let new_collection = Collection::new(org_id.clone(), col.name, col.external_id); let new_collection = Collection::new(org_id.clone(), col.name, col.external_id);
new_collection.save(&conn).await?; new_collection.save(&conn).await?;
if grant_new_collection_manage { // Like upstream, the importer manages the collections they create
CollectionUser::save(&importer_uuid, &new_collection.uuid, false, false, true, &conn).await?; CollectionUser::save(&importer_uuid, &new_collection.uuid, false, false, true, &conn).await?;
}
new_collection.uuid new_collection.uuid
}; };
collections.push(collection_uuid); collections.push(collection_uuid);
@ -2170,7 +2049,7 @@ mod org_import_tests {
("admin", MembershipType::Admin, CustomPermission::CreateNewCollections), ("admin", MembershipType::Admin, CustomPermission::CreateNewCollections),
("cipher", MembershipType::Custom, CustomPermission::CreateNewCollections), ("cipher", MembershipType::Custom, CustomPermission::CreateNewCollections),
("custom", MembershipType::Custom, CustomPermission::CreateNewCollections), ("custom", MembershipType::Custom, CustomPermission::CreateNewCollections),
("legacy", MembershipType::Manager, CustomPermission::CreateNewCollections), ("user", MembershipType::User, CustomPermission::CreateNewCollections),
("authorization", MembershipType::Custom, CustomPermission::CreateNewCollections), ("authorization", MembershipType::Custom, CustomPermission::CreateNewCollections),
("rollback", MembershipType::Custom, CustomPermission::CreateNewCollections), ("rollback", MembershipType::Custom, CustomPermission::CreateNewCollections),
("index", MembershipType::Custom, CustomPermission::CreateNewCollections), ("index", MembershipType::Custom, CustomPermission::CreateNewCollections),
@ -2185,9 +2064,7 @@ mod org_import_tests {
} else { } else {
vec![] vec![]
}; };
let (user, mut membership) = test_db::member(&conn, &org.uuid, role, &permissions).await; let (user, membership) = test_db::member(&conn, &org.uuid, role, &permissions).await;
membership.access_all = role == MembershipType::Manager;
membership.save(&conn).await.unwrap();
let mut payload = json!({"ciphers":[{"name":"Cipher","type":2,"encryptedFor":user.uuid,"secureNote":{"type":0}}], let mut payload = json!({"ciphers":[{"name":"Cipher","type":2,"encryptedFor":user.uuid,"secureNote":{"type":0}}],
"collections":[{"name":"New"}],"collectionRelationships":[{"key":0,"value":0}]}); "collections":[{"name":"New"}],"collectionRelationships":[{"key":0,"value":0}]});
match case { match case {
@ -2227,17 +2104,14 @@ mod org_import_tests {
) )
.await; .await;
conn.run(|c| c.batch_execute("DROP TRIGGER IF EXISTS reject_link")).await.unwrap(); 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!(result.is_ok(), success, "{case}");
assert_eq!( assert_eq!(
Collection::find_by_organization(&org.uuid, &conn).await.len(), Collection::find_by_organization(&org.uuid, &conn).await.len(),
usize::from(success || case == "authorization") usize::from(success || case == "authorization")
); );
assert_eq!(Cipher::find_by_org(&org.uuid, &conn).await.len(), usize::from(success)); assert_eq!(Cipher::find_by_org(&org.uuid, &conn).await.len(), usize::from(success));
assert_eq!( assert_eq!(CollectionUser::find_by_user(&user_id, &conn).await.len(), usize::from(success));
CollectionUser::find_by_user(&user_id, &conn).await.len(),
usize::from(success && role == MembershipType::Custom)
);
assert_eq!( assert_eq!(
Cipher::get_collections_with_cipher_by_organization(&org.uuid, &conn).await.len(), Cipher::get_collections_with_cipher_by_organization(&org.uuid, &conn).await.len(),
usize::from(success && case != "export") 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 // 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. // 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();
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 allowed = if details { let allowed = if details {
has_full_access has_full_access
|| headers.membership.has_custom_permission(CustomPermission::ManageUsers) || 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")] #[serde(rename_all = "camelCase")]
struct GroupRequest { struct GroupRequest {
name: String, name: String,
access_all: Option<bool>,
external_id: Option<String>, external_id: Option<String>,
collections: Vec<CollectionData>, collections: Vec<CollectionData>,
users: Vec<MembershipId>, users: Vec<MembershipId>,
@ -2962,14 +2831,11 @@ struct GroupRequest {
impl GroupRequest { impl GroupRequest {
pub fn to_group(&self, org_uuid: &OrganizationId) -> Group { 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 { pub fn update_group(&self, mut group: Group) -> Group {
group.name.clone_from(&self.name); 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 // 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 // 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)] #[cfg(sqlite)]
#[test] #[test]
fn manage_users_grants_are_confined_to_permission_and_organization() { fn manage_users_grants_are_confined_to_permission_and_organization() {
@ -3865,7 +3750,7 @@ mod tests {
let foreign = test_db::organization(&conn).await; let foreign = test_db::organization(&conn).await;
for org_id in [&org.uuid, &foreign.uuid] { for org_id in [&org.uuid, &foreign.uuid] {
let collection = test_db::collection(&conn, org_id).await; 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(); group.save(&conn).await.unwrap();
let empty = HashSet::new(); let empty = HashSet::new();
for (collections, groups) in [ for (collections, groups) in [
@ -3873,7 +3758,6 @@ mod tests {
(&[][..], HashSet::from([group.uuid.clone()])), (&[][..], HashSet::from([group.uuid.clone()])),
(&[&collection.uuid][..], HashSet::from([group.uuid])), (&[&collection.uuid][..], HashSet::from([group.uuid])),
] { ] {
// A group with access to all collections may be given as well, as in Bitwarden
assert_eq!( assert_eq!(
check_custom_member_grants(&member, None, collections, &groups, &conn).await.is_ok(), check_custom_member_grants(&member, None, collections, &groups, &conn).await.is_ok(),
org_id == &org.uuid org_id == &org.uuid
@ -3881,18 +3765,18 @@ mod tests {
} }
} }
let collection = test_db::collection(&conn, &org.uuid).await; 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 escalated = HashSet::from([CustomPermission::EditAnyCollection]);
let empty = HashSet::new(); let empty = HashSet::new();
for (enabled, status) in [(true, 2), (true, 1), (true, -126), (false, 2)] { for (enabled, status) in [(true, 2), (true, 1), (true, -126), (false, 2)] {
test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled)); test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled));
member.status = status; member.status = status;
assert_eq!( assert_eq!(
custom_member_may(CollectionAction::Read, &member, &collection.uuid, &conn).await, member_may(CollectionAction::Read, &member, &collection.uuid, &conn).await,
enabled && status == 2 enabled && status == 2
); );
assert!(!custom_member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await); assert!(!member_may(CollectionAction::Edit, &member, &collection.uuid, &conn).await);
assert!(!custom_member_may(CollectionAction::ReadAccess, &member, &collection.uuid, &conn).await); assert!(!member_may(CollectionAction::ReadAccess, &member, &collection.uuid, &conn).await);
assert_eq!( assert_eq!(
check_custom_member_grants(&member, None, &[], &empty, &conn).await.is_ok(), check_custom_member_grants(&member, None, &[], &empty, &conn).await.is_ok(),
enabled && status == 2 enabled && status == 2
@ -3947,7 +3831,7 @@ mod tests {
} }
#[cfg(sqlite)] #[cfg(sqlite)]
#[test] #[test]
fn group_requests_stay_in_their_organization_and_keep_access_all() { fn group_requests_stay_in_their_organization() {
test_db::run(async |db| { test_db::run(async |db| {
let conn = db.conn(); let conn = db.conn();
let (org, _, member) = test_db::custom_member(&conn, CustomPermission::ManageGroups).await; 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":[]})) {"id":collection.uuid,"readOnly":false,"hidePasswords":false,"manage":true}],"users":[]}))
.unwrap(); .unwrap();
assert_eq!(request.validate(&org.uuid, &conn).await.is_ok(), org_id == &org.uuid); 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!(!Collection::is_assigned(&member, &collection.uuid, &conn).await);
assert!(!custom_member_may(CollectionAction::Edit, &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 [ for (role, permissions) in [
(Owner, vec![]), (Owner, vec![]),
(Admin, vec![]), (Admin, vec![]),
(Manager, vec![]), (User, vec![]),
(User, vec![]), (User, vec![]),
(Custom, vec![ManageResetPassword]), (Custom, vec![ManageResetPassword]),
(Custom, vec![ManageResetPassword, ManageUsers]), (Custom, vec![ManageResetPassword, ManageUsers]),
@ -4100,7 +3980,7 @@ mod tests {
members.push(test_db::member(&conn, &org.uuid, role, &permissions).await.1); 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 // 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()) { for (target, allowed) in members.iter().zip(row.chars()) {
assert_eq!( assert_eq!(
may_recover_account(caller, target), may_recover_account(caller, target),

3
src/api/core/public.rs

@ -113,7 +113,6 @@ async fn ldap_import(data: Json<OrgImportData>, token: PublicToken, conn: DbConn
let mut new_member = Membership::new(user.uuid.clone(), org_id.clone(), Some(org_email.clone())); 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.set_external_id(Some(user_data.external_id.clone()));
new_member.access_all = false;
new_member.atype = MembershipType::User as i32; new_member.atype = MembershipType::User as i32;
new_member.status = member_status; new_member.status = member_status;
@ -147,7 +146,7 @@ async fn ldap_import(data: Json<OrgImportData>, token: PublicToken, conn: DbConn
group.uuid group.uuid
} else { } else {
let mut group = 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.save(&conn).await?;
group.uuid group.uuid
}; };

74
src/auth.rs

@ -751,9 +751,6 @@ impl OrgHeaders {
fn is_confirmed_and_admin(&self) -> bool { fn is_confirmed_and_admin(&self) -> bool {
self.membership_status == MembershipStatus::Confirmed && self.membership_type >= MembershipType::Admin 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 { fn is_confirmed_and_owner(&self) -> bool {
self.membership_status == MembershipStatus::Confirmed && self.membership_type == MembershipType::Owner self.membership_status == MembershipStatus::Confirmed && self.membership_type == MembershipType::Owner
} }
@ -975,24 +972,22 @@ pub enum CollectionAction {
Delete, 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 /// 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 /// 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 /// any collection, and otherwise both need the manage option on the collection itself.
/// `access_all` counts as that. pub async fn member_may(action: CollectionAction, member: &Membership, col_id: &CollectionId, conn: &DbConn) -> bool {
pub async fn custom_member_may( if !member.has_status(MembershipStatus::Confirmed)
action: CollectionAction, || Collection::find_by_uuid_and_org(col_id, &member.org_uuid, conn).await.is_none()
member: &Membership,
col_id: &CollectionId,
conn: &DbConn,
) -> bool {
if !(member.has_type(MembershipType::Custom)
&& member.has_status(MembershipStatus::Confirmed)
&& custom_roles_enabled())
{ {
return false; return false;
} }
if member.has_full_access() {
return true;
}
match action { match action {
CollectionAction::Delete => member.has_custom_permission(CustomPermission::DeleteAnyCollection), CollectionAction::Delete => member.has_custom_permission(CustomPermission::DeleteAnyCollection),
CollectionAction::Edit if member.can_edit_any_collection() => true, 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 <col_id>/collections/collectionId: a Manager, Admin /// Checks a collection route for the collection provided via the <col_id>/collections/collectionId: the confirmed
/// or Owner needs to be able to manage the collection, a Custom member is checked for the `action`. /// member must be allowed the `action` on it.
async fn collection_headers(request: &Request<'_>, action: CollectionAction) -> Outcome<OrgHeaders, &'static str> { async fn collection_headers(request: &Request<'_>, action: CollectionAction) -> Outcome<OrgHeaders, &'static str> {
let headers = try_outcome!(OrgHeaders::from_request(request).await); let headers = try_outcome!(OrgHeaders::from_request(request).await);
let is_custom = headers.is_confirmed_and_custom(); if headers.membership_status != MembershipStatus::Confirmed {
if !headers.is_confirmed_and_manager() && !is_custom { err_handler!("You need to be a confirmed member of the organization to call this endpoint")
err_handler!("You need to be a Manager, Admin or Owner to call this endpoint")
} }
let Some(col_id) = get_col_id(request) else { 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") err_handler!("Error getting DB")
}; };
let allowed = if is_custom { if !member_may(action, &headers.membership, &col_id, &conn).await {
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 {
// NotFound as in Bitwarden, the web vault logs the user out on a 401 // 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"); 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")); return Outcome::Error((rocket::http::Status::NotFound, "Collection not found"));
@ -1078,9 +1067,8 @@ macro_rules! collection_headers {
} }
collection_headers!( collection_headers!(
/// The ManagerHeaders are used to check if you are at least a Manager /// The ManagerHeaders are used to check if you may manage the specific collection provided via the
/// and have access to the specific collection provided via the <col_id>/collections/collectionId. /// <col_id>/collections/collectionId. This does strict checking on the collection_id, ManagerHeadersLoose does not.
/// This does strict checking on the collection_id, ManagerHeadersLoose does not.
ManagerHeaders, ManagerHeaders,
CollectionAction::Edit CollectionAction::Edit
); );
@ -1100,9 +1088,9 @@ collection_headers!(
CollectionAction::Delete CollectionAction::Delete
); );
/// The ManagerHeadersLoose is used when you at least need to be a Manager, /// The ManagerHeadersLoose is used when you need to be an Admin or Owner, a Custom member, or to manage at least one
/// but there is no collection_id sent with the request (either in the path or as form data). /// collection, but there is no collection_id sent with the request (either in the path or as form data). The routes
/// A Custom member is let through as well, the routes check what their permissions allow. /// check what the member may do.
pub struct ManagerHeadersLoose { pub struct ManagerHeadersLoose {
pub host: String, pub host: String,
pub device: Device, pub device: Device,
@ -1117,7 +1105,16 @@ impl<'r> FromRequest<'r> for ManagerHeadersLoose {
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> { async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let headers = try_outcome!(OrgHeaders::from_request(request).await); 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 { Outcome::Success(Self {
host: headers.host, host: headers.host,
device: headers.device, device: headers.device,
@ -1126,7 +1123,7 @@ impl<'r> FromRequest<'r> for ManagerHeadersLoose {
ip: headers.ip, ip: headers.ip,
}) })
} else { } 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<CollectionId>, collections: &Vec<CollectionId>,
conn: &DbConn, conn: &DbConn,
) -> Result<CollectionDeleteHeaders, Error> { ) -> Result<CollectionDeleteHeaders, Error> {
let is_custom = h.membership.has_type(MembershipType::Custom) && custom_roles_enabled();
for col_id in collections { for col_id in collections {
if uuid::Uuid::parse_str(col_id.as_ref()).is_err() { if uuid::Uuid::parse_str(col_id.as_ref()).is_err() {
err!("Collection Id is malformed!"); err!("Collection Id is malformed!");
} }
let allowed = if is_custom { if !member_may(CollectionAction::Delete, &h.membership, col_id, conn).await {
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 {
err!("Collection not found", "The current user isn't a manager for this collection") err!("Collection not found", "The current user isn't a manager for this collection")
} }
} }

273
src/db/mod.rs

@ -631,17 +631,24 @@ pub mod test_db {
}); });
} }
#[test] /// Runs the pending migrations older than `version`.
fn custom_role_migration_preserves_memberships_and_guards_downgrade() { fn migrate_until(conn: &mut SqliteConnection, version: &str) {
use super::schema::users_organizations::dsl::*;
use diesel::{migration::MigrationSource, prelude::*};
let mut conn = SqliteConnection::establish(":memory:").unwrap();
for migration in conn.pending_migrations(MIGRATIONS).unwrap() { for migration in conn.pending_migrations(MIGRATIONS).unwrap() {
if migration.name().version().to_string() == "20261010120000" { if migration.name().version().to_string() == version {
break; break;
} }
conn.run_migration(&migration).unwrap(); 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( conn.batch_execute(
"PRAGMA foreign_keys=OFF; "PRAGMA foreign_keys=OFF;
INSERT INTO organizations (uuid,name,billing_email) VALUES ('org','Org','a@b'); INSERT INTO organizations (uuid,name,billing_email) VALUES ('org','Org','a@b');
@ -652,13 +659,13 @@ pub mod test_db {
.unwrap(); .unwrap();
let rows = |conn: &mut SqliteConnection| { let rows = |conn: &mut SqliteConnection| {
users_organizations users_organizations
.select((uuid, user_uuid, org_uuid, access_all, akey, status, atype)) .select((uuid, user_uuid, org_uuid, akey, status, atype))
.order(uuid) .order(uuid)
.load::<(String, String, String, bool, String, i32, i32)>(conn) .load::<(String, String, String, String, i32, i32)>(conn)
.unwrap() .unwrap()
}; };
let before = rows(&mut conn); let before = rows(&mut conn);
conn.run_pending_migrations(MIGRATIONS).unwrap(); migrate_until(&mut conn, REMOVE_ACCESS_ALL);
assert_eq!(rows(&mut conn), before); assert_eq!(rows(&mut conn), before);
let grants = |conn: &mut SqliteConnection| { let grants = |conn: &mut SqliteConnection| {
diesel::select(diesel::dsl::sql::<diesel::sql_types::BigInt>( diesel::select(diesel::dsl::sql::<diesel::sql_types::BigInt>(
@ -689,11 +696,129 @@ pub mod test_db {
.unwrap(); .unwrap();
conn.revert_migration(&*migration).unwrap(); conn.revert_migration(&*migration).unwrap();
assert!(diesel::sql_query("SELECT manage_users FROM users_organizations").execute(&mut conn).is_err()); 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!(grants(&mut conn), 0);
assert_eq!(rows(&mut conn), before); 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::<diesel::sqlite::Sqlite>::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::<diesel::sql_types::Text>(
"(SELECT group_concat(uuid) FROM (SELECT uuid FROM users_organizations WHERE access_all ORDER BY uuid))",
))
.get_result::<String>(&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}; use super::models::{Collection, CustomPermission, Membership, MembershipType, Organization, OrganizationId, User};
pub async fn organization(conn: &DbConn) -> Organization { 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 super::models::{Cipher, CipherAccessScope, CollectionCipher, CollectionUser, test_flag};
use crate::{ use crate::{
api::core::{CipherSyncData, CipherSyncType}, api::core::{CipherSyncData, CipherSyncType},
auth::{CollectionAction, custom_member_may}, auth::{CollectionAction, member_may},
}; };
run(async |db| { run(async |db| {
let conn = db.conn(); let conn = db.conn();
@ -795,8 +920,8 @@ pub mod test_db {
cipher.organization_uuid = Some(org.uuid.clone()); cipher.organization_uuid = Some(org.uuid.clone());
member.set_custom_permissions(&std::collections::HashSet::new()); member.set_custom_permissions(&std::collections::HashSet::new());
member.save(&conn).await.unwrap(); member.save(&conn).await.unwrap();
let sql=format!("INSERT INTO groups (uuid,organizations_uuid,name,access_all,creation_date,revision_date) let sql=format!("INSERT INTO groups (uuid,organizations_uuid,name,creation_date,revision_date)
VALUES ('g','{}','Group',FALSE,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP); VALUES ('g','{}','Group',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP);
INSERT INTO groups_users (groups_uuid,users_organizations_uuid) VALUES ('g','{}'); 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);", INSERT INTO collections_groups (collections_uuid,groups_uuid,read_only,hide_passwords,manage) VALUES ('{}','g',FALSE,FALSE,TRUE);",
org.uuid,member.uuid,collection.uuid); org.uuid,member.uuid,collection.uuid);
@ -805,7 +930,7 @@ pub mod test_db {
member.status = status; member.status = status;
member.save(&conn).await.unwrap(); member.save(&conn).await.unwrap();
let allowed = status == 2 && crate::CONFIG.org_groups_enabled(); 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; let sync = CipherSyncData::new(&user.uuid, CipherSyncType::User, &conn).await;
for cached in [None, Some(&sync)] { for cached in [None, Some(&sync)] {
assert_eq!( assert_eq!(
@ -820,7 +945,125 @@ pub mod test_db {
member.status = 2; member.status = 2;
member.save(&conn).await.unwrap(); member.save(&conn).await.unwrap();
CollectionUser::save(&user.uuid, &collection.uuid, false, false, true, &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);
}
}); });
} }
} }

130
src/db/models/cipher.rs

@ -24,7 +24,7 @@ use crate::{
use macros::UuidFromParam; use macros::UuidFromParam;
use super::{ use super::{
Archive, Attachment, CollectionCipher, CollectionId, Favorite, FolderCipher, FolderId, Group, Membership, Archive, Attachment, CollectionCipher, CollectionId, Favorite, FolderCipher, FolderId, Membership,
MembershipStatus, OrganizationId, User, UserId, MembershipStatus, OrganizationId, User, UserId,
organization::{ORG_ADMIN_ATYPES, custom_edit_any_collection}, organization::{ORG_ADMIN_ATYPES, custom_edit_any_collection},
}; };
@ -84,9 +84,10 @@ pub enum RepromptType {
/// Which access a cipher operation is authorized with. /// Which access a cipher operation is authorized with.
/// ///
/// The administrative cipher routes (`/ciphers/<id>/admin` and friends) are served by the same handlers as the /// The administrative cipher routes (`/ciphers/<id>/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 /// regular vault routes, so the handlers state which one applies. They differ for every member who may edit any
/// any collection, who reaches every cipher of the organization on the administrative routes, but keeps their /// collection, an Owner, an Admin or a Custom member with Edit any collection: like in Bitwarden, they reach every
/// own vault limited to the collections they are assigned to. /// 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)] #[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CipherAccessScope { pub enum CipherAccessScope {
User, User,
@ -94,10 +95,11 @@ pub enum CipherAccessScope {
} }
impl 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 { fn reaches_all_ciphers(self, member: &Membership) -> bool {
match self { match self {
CipherAccessScope::User => member.has_full_access(), CipherAccessScope::User => false,
CipherAccessScope::OrganizationAdmin => member.can_edit_any_collection(), CipherAccessScope::OrganizationAdmin => member.can_edit_any_collection(),
} }
} }
@ -711,25 +713,6 @@ impl Cipher {
false 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 /// 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 /// 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 /// not in any collection the user has access to. Otherwise, the user has
@ -742,12 +725,10 @@ impl Cipher {
cipher_sync_data: Option<&CipherSyncData>, cipher_sync_data: Option<&CipherSyncData>,
conn: &DbConn, conn: &DbConn,
) -> Option<(bool, bool, bool)> { ) -> Option<(bool, bool, bool)> {
// Check whether this cipher is directly owned by the user, or is in // Check whether this cipher is directly owned by the user, or the user may reach every cipher of its
// a collection that the user has full access to. If so, there are no // organization. If so, there are no access restrictions.
// access restrictions.
if self.is_owned_by_user(user_uuid) 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_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)); return Some((false, false, true));
} }
@ -956,24 +937,10 @@ impl Cipher {
.await .await
} }
// Find all ciphers accessible or visible to the specified user. // 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
// "Accessible" means the user has read access to the cipher, either via // the other ciphers of their organization in the Admin Console.
// direct ownership, collection or via group access. pub async fn find_by_user(user_uuid: &UserId, cipher_uuids: &Vec<CipherId>, conn: &DbConn) -> Vec<Self> {
//
// "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<CipherId>,
conn: &DbConn,
) -> Vec<Self> {
if CONFIG.org_groups_enabled() { if CONFIG.org_groups_enabled() {
conn.run(move |conn| { conn.run(move |conn| {
let mut query = ciphers::table let mut query = ciphers::table
@ -1005,18 +972,10 @@ impl Cipher {
.and(collections_groups::groups_uuid.eq(groups::uuid))), .and(collections_groups::groups_uuid.eq(groups::uuid))),
) )
.filter(ciphers::user_uuid.eq(user_uuid)) // Cipher owner .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(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 .or_filter(collections_groups::collections_uuid.is_not_null()) // Access via groups
.into_boxed(); .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 // Only filter for one specific cipher
if !cipher_uuids.is_empty() { if !cipher_uuids.is_empty() {
query = query.filter(ciphers::uuid.eq_any(cipher_uuids)); 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))), .and(users_organizations::user_uuid.eq(users_collections::user_uuid))),
) )
.filter(ciphers::user_uuid.eq(user_uuid)) // Cipher owner .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(users_collections::user_uuid.eq(user_uuid)) // Access to collection
.into_boxed(); .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 // Only filter for one specific cipher
if !cipher_uuids.is_empty() { if !cipher_uuids.is_empty() {
query = query.filter(ciphers::uuid.eq_any(cipher_uuids)); query = query.filter(ciphers::uuid.eq_any(cipher_uuids));
@ -1065,7 +1017,7 @@ impl Cipher {
// Find all ciphers visible to the specified user. // Find all ciphers visible to the specified user.
pub async fn find_by_user_visible(user_uuid: &UserId, conn: &DbConn) -> Vec<Self> { pub async fn find_by_user_visible(user_uuid: &UserId, conn: &DbConn) -> Vec<Self> {
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( pub async fn find_by_user_and_ciphers(
@ -1073,11 +1025,11 @@ impl Cipher {
cipher_uuids: &Vec<CipherId>, cipher_uuids: &Vec<CipherId>,
conn: &DbConn, conn: &DbConn,
) -> Vec<Self> { ) -> Vec<Self> {
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> { pub async fn find_by_user_and_cipher(user_uuid: &UserId, cipher_uuid: &CipherId, conn: &DbConn) -> Option<Self> {
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. // 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::status.eq(MembershipStatus::Confirmed as i32))
.filter( .filter(
users_organizations::access_all users_collections::user_uuid
.eq(true) // User has access all .eq(user_uuid) // User has access to collection
.or(users_collections::user_uuid .and(users_collections::read_only.eq(false))
.eq(user_uuid) // User has access to collection
.and(users_collections::read_only.eq(false)))
.or(groups::access_all.eq(true)) // Access via groups
.or(collections_groups::collections_uuid .or(collections_groups::collections_uuid
.is_not_null() // Access via groups .is_not_null() // Access via groups
.and(collections_groups::read_only.eq(false))), .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::status.eq(MembershipStatus::Confirmed as i32))
.filter( .filter(
users_organizations::access_all users_collections::user_uuid
.eq(true) // User has access all .eq(user_uuid) // User has access to collection
.or(users_collections::user_uuid .and(users_collections::read_only.eq(false)),
.eq(user_uuid) // User has access to collection
.and(users_collections::read_only.eq(false))),
) )
.select(ciphers_collections::collection_uuid) .select(ciphers_collections::collection_uuid)
.load::<CollectionId>(conn) .load::<CollectionId>(conn)
@ -1248,16 +1195,16 @@ impl Cipher {
) )
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter( .filter(
users_organizations::access_all users_collections::user_uuid
.eq(true) // User has access all .eq(user_uuid) // User has access to collection
.or(users_collections::user_uuid .and(users_collections::read_only.eq(false))
.eq(user_uuid) // User has access to collection
.and(users_collections::read_only.eq(false)))
.or(groups::access_all.eq(true)) // Access via groups
.or(collections_groups::collections_uuid .or(collections_groups::collections_uuid
.is_not_null() // Access via groups .is_not_null() // Access via groups
.and(collections_groups::read_only.eq(false))) .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() .or(custom_edit_any_collection()
.and::<_, diesel::sql_types::Bool>(scope == CipherAccessScope::OrganizationAdmin)), .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::status.eq(MembershipStatus::Confirmed as i32))
.filter( .filter(
users_organizations::access_all users_collections::user_uuid
.eq(true) // User has access all .eq(user_uuid) // User has access to collection
.or(users_collections::user_uuid .and(users_collections::read_only.eq(false))
.eq(user_uuid) // User has access to collection // On the administrative routes only, an Owner or Admin reaches every collection
.and(users_collections::read_only.eq(false))) .or(users_organizations::atype
.or(users_organizations::atype.eq_any(ORG_ADMIN_ATYPES)) // User is admin or owner .eq_any(ORG_ADMIN_ATYPES)
.and::<_, diesel::sql_types::Bool>(scope == CipherAccessScope::OrganizationAdmin))
.or(custom_edit_any_collection() .or(custom_edit_any_collection()
.and::<_, diesel::sql_types::Bool>(scope == CipherAccessScope::OrganizationAdmin)), .and::<_, diesel::sql_types::Bool>(scope == CipherAccessScope::OrganizationAdmin)),
) )
@ -1330,10 +1278,8 @@ impl Cipher {
.eq(ciphers_collections::collection_uuid) .eq(ciphers_collections::collection_uuid)
.and(collections_groups::groups_uuid.eq(groups::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_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 .or_filter(collections_groups::collections_uuid.is_not_null()) //Access via group
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.select(ciphers_collections::all_columns) .select(ciphers_collections::all_columns)

358
src/db/models/collection.rs

@ -17,8 +17,8 @@ use crate::{
use macros::UuidFromParam; use macros::UuidFromParam;
use super::{ use super::{
CipherId, CollectionGroup, GroupUser, Membership, MembershipId, MembershipStatus, MembershipType, OrganizationId, CipherId, CollectionGroup, GroupUser, Membership, MembershipId, MembershipStatus, OrganizationId, User, UserId,
User, UserId, custom_roles_enabled, organization::ORG_ADMIN_ATYPES, organization::ORG_ADMIN_ATYPES,
}; };
// See (v2026.7.0): https://github.com/bitwarden/server/blob/5d4461aa42cadbacfef8fe2166c5453a5c52773a/src/Core/AdminConsole/Entities/Collection.cs // 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>, cipher_sync_data: Option<&crate::api::core::CipherSyncData>,
conn: &DbConn, conn: &DbConn,
) -> Value { ) -> 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 { let (read_only, hide_passwords, manage) = if let Some(cipher_sync_data) = cipher_sync_data {
match cipher_sync_data.members.get(&self.org_uuid) { if cipher_sync_data.members.contains_key(&self.org_uuid) {
// Only for Manager types Bitwarden returns true for the manage option if let Some(cu) = cipher_sync_data.user_collections.get(&self.uuid) {
// Owners and Admins always have true. Users are not able to have full access (cu.read_only, cu.hide_passwords, cu.manage)
Some(m) if m.has_full_access() => (false, false, m.atype >= MembershipType::Manager), } else if let Some(cg) = cipher_sync_data.user_collections_groups.get(&self.uuid) {
Some(m) => { (cg.read_only, cg.hide_passwords, cg.manage)
// Only let a manager manage collections when the have full read/write access } else {
// A Custom member only manages a collection with the manage option (false, false, false)
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)
}
} }
_ => (true, true, false), } else {
(true, true, false)
} }
} else { } else {
match Membership::find_confirmed_by_user_and_org(user_uuid, &self.org_uuid, conn).await { 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(member) => self.assigned_access(&member, conn).await.unwrap_or((false, false, false)),
Some(m) if m.atype == MembershipType::Manager && self.is_manageable_by_user(user_uuid, conn).await => { None => (true, true, false),
(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),
} }
}; };
@ -167,13 +132,31 @@ impl Collection {
json_object 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_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() || (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_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter( .filter(
users_collections::user_uuid users_collections::user_uuid
.eq(user_uuid) .eq(user_uuid) // Directly accessed collection
.or(
// Directly accessed collection
users_organizations::access_all.eq(true), // access_all in Organization
)
.or(
groups::access_all.eq(true), // access_all in groups
)
.or( .or(
// access via groups // access via groups
groups_users::users_organizations_uuid groups_users::users_organizations_uuid
@ -300,10 +276,7 @@ impl Collection {
.and(users_organizations::user_uuid.eq(user_uuid.clone()))), .and(users_organizations::user_uuid.eq(user_uuid.clone()))),
) )
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(users_collections::user_uuid.eq(user_uuid).or( .filter(users_collections::user_uuid.eq(user_uuid)) // Directly accessed collection
// Directly accessed collection
users_organizations::access_all.eq(true), // access_all in Organization
))
.select(collections::all_columns) .select(collections::all_columns)
.distinct() .distinct()
.load::<Self>(conn) .load::<Self>(conn)
@ -386,16 +359,7 @@ impl Collection {
.filter( .filter(
users_collections::collection_uuid users_collections::collection_uuid
.eq(uuid) .eq(uuid)
.or( .or(users_organizations::atype.eq_any(ORG_ADMIN_ATYPES)) // Org admin or owner
// 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( .or(
// access via groups // access via groups
groups_users::users_organizations_uuid groups_users::users_organizations_uuid
@ -423,13 +387,11 @@ impl Collection {
) )
.filter(collections::uuid.eq(uuid)) .filter(collections::uuid.eq(uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32)) .filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(users_collections::collection_uuid.eq(uuid).or( .filter(
// Directly accessed collection users_collections::collection_uuid
users_organizations::access_all.eq(true).or( .eq(uuid) // Directly accessed collection
// access_all in Organization .or(users_organizations::atype.eq_any(ORG_ADMIN_ATYPES)), // Org admin or owner
users_organizations::atype.eq_any(ORG_ADMIN_ATYPES), // Org admin or owner )
),
))
.select(collections::all_columns) .select(collections::all_columns)
.first::<Self>(conn) .first::<Self>(conn)
.ok() .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 { pub async fn is_writable_by_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool {
let user_uuid = user_uuid.to_string(); match Membership::find_confirmed_by_user_and_org(user_uuid, &self.org_uuid, conn).await {
if CONFIG.org_groups_enabled() { Some(member) => self.assigned_access(&member, conn).await.is_some_and(|(read_only, _, _)| !read_only),
conn.run(move |conn| { None => false,
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::<i64>(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::<i64>(conn)
.ok()
.unwrap_or(0)
!= 0
})
.await
} }
} }
pub async fn hide_passwords_for_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool { // Whether the user has manage access to at least one collection in the org, directly or via a group.
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::<i64>(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::<i64>(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.
pub async fn has_manageable_collection_by_user( pub async fn has_manageable_collection_by_user(
org_uuid: &OrganizationId, org_uuid: &OrganizationId,
user_uuid: &UserId, user_uuid: &UserId,
@ -653,12 +418,8 @@ impl Collection {
!Self::find_explicitly_manageable_by_user(org_uuid, user_uuid, conn).await.is_empty() !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 { // The collections of the org the user has manage access to by the manage option, directly or else via a group. The
Self::find_explicitly_manageable_by_user(&self.org_uuid, user_uuid, conn).await.contains(&self.uuid) // role doesn't count: an Owner or Admin manages every collection by it.
}
// 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.
pub async fn find_explicitly_manageable_by_user( pub async fn find_explicitly_manageable_by_user(
org_uuid: &OrganizationId, org_uuid: &OrganizationId,
user_uuid: &UserId, user_uuid: &UserId,
@ -690,7 +451,6 @@ impl Collection {
.filter( .filter(
users_collections::manage.eq(true).or(users_collections::user_uuid users_collections::manage.eq(true).or(users_collections::user_uuid
.is_null() .is_null()
.or(users_organizations::atype.eq(MembershipType::Manager as i32))
.and(collections_groups::manage.eq(true)) .and(collections_groups::manage.eq(true))
.and::<_, diesel::sql_types::Bool>(groups_enabled)), .and::<_, diesel::sql_types::Bool>(groups_enabled)),
) )
@ -1000,16 +760,12 @@ pub struct CollectionMembership {
} }
impl 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!({ json!({
"id": self.membership_uuid, "id": self.membership_uuid,
"readOnly": self.read_only, "readOnly": self.read_only,
"hidePasswords": self.hide_passwords, "hidePasswords": self.hide_passwords,
"manage": membership_type >= MembershipType::Admin "manage": self.manage,
|| self.manage
|| (membership_type == MembershipType::Manager
&& !self.read_only
&& !self.hide_passwords),
}) })
} }
} }

106
src/db/models/group.rs

@ -23,7 +23,6 @@ pub struct Group {
pub uuid: GroupId, pub uuid: GroupId,
pub organizations_uuid: OrganizationId, pub organizations_uuid: OrganizationId,
pub name: String, pub name: String,
pub access_all: bool,
pub external_id: Option<String>, pub external_id: Option<String>,
pub creation_date: NaiveDateTime, pub creation_date: NaiveDateTime,
pub revision_date: NaiveDateTime, pub revision_date: NaiveDateTime,
@ -50,19 +49,13 @@ pub struct GroupUser {
/// Local methods /// Local methods
impl Group { impl Group {
pub fn new( pub fn new(organizations_uuid: OrganizationId, name: String, external_id: Option<String>) -> Self {
organizations_uuid: OrganizationId,
name: String,
access_all: bool,
external_id: Option<String>,
) -> Self {
let now = Utc::now().naive_utc(); let now = Utc::now().naive_utc();
let mut new_model = Self { let mut new_model = Self {
uuid: GroupId(crate::util::get_uuid()), uuid: GroupId(crate::util::get_uuid()),
organizations_uuid, organizations_uuid,
name, name,
access_all,
external_id: None, external_id: None,
creation_date: now, creation_date: now,
revision_date: now, revision_date: now,
@ -84,9 +77,6 @@ impl Group {
} }
pub async fn to_json_details(&self, conn: &DbConn) -> Value { 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<Value> = CollectionGroup::find_by_group(&self.uuid, &self.organizations_uuid, conn) let collections_groups: Vec<Value> = CollectionGroup::find_by_group(&self.uuid, &self.organizations_uuid, conn)
.await .await
.iter() .iter()
@ -235,50 +225,6 @@ impl Group {
}) })
.await .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<OrganizationId> {
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::<OrganizationId>(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::<bool>(conn)
.unwrap_or_default()
})
.await
}
pub async fn delete(&self, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult { pub async fn delete(&self, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult {
CollectionGroup::delete_all_by_group(&self.uuid, org_uuid, conn).await?; CollectionGroup::delete_all_by_group(&self.uuid, org_uuid, conn).await?;
@ -395,6 +341,37 @@ impl CollectionGroup {
.await .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<Self> {
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::<Self>(conn)
.expect("Error loading the collection groups of a member")
})
.await
}
pub async fn find_by_collection(collection_uuid: &CollectionId, conn: &DbConn) -> Vec<Self> { pub async fn find_by_collection(collection_uuid: &CollectionId, conn: &DbConn) -> Vec<Self> {
conn.run(move |conn| { conn.run(move |conn| {
collections_groups::table collections_groups::table
@ -547,25 +524,6 @@ impl GroupUser {
.await .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::<i64>(conn)
.unwrap_or(0)
!= 0
})
.await
}
pub async fn update_user_revision(&self, conn: &DbConn) { pub async fn update_user_revision(&self, conn: &DbConn) {
match Membership::find_by_uuid(&self.users_organizations_uuid, conn).await { match Membership::find_by_uuid(&self.users_organizations_uuid, conn).await {
Some(member) => User::update_uuid_revision(&member.user_uuid, conn).await, Some(member) => User::update_uuid_revision(&member.user_uuid, conn).await,

2
src/db/models/mod.rs

@ -23,7 +23,7 @@ pub use self::archive::Archive;
pub use self::attachment::{Attachment, AttachmentId}; pub use self::attachment::{Attachment, AttachmentId};
pub use self::auth_request::{AuthRequest, AuthRequestId}; pub use self::auth_request::{AuthRequest, AuthRequestId};
pub use self::cipher::{Cipher, CipherAccessScope, CipherId, RepromptType, is_data_blob_encrypted}; 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::device::{Device, DeviceId, DeviceType, DeviceWithAuthRequest, PushId};
pub use self::emergency_access::{ pub use self::emergency_access::{
EMERGENCY_ACCESS_TIMEOUT_RANGE, EmergencyAccess, EmergencyAccessId, EmergencyAccessStatus, EmergencyAccessType, EMERGENCY_ACCESS_TIMEOUT_RANGE, EmergencyAccess, EmergencyAccessId, EmergencyAccessStatus, EmergencyAccessType,

297
src/db/models/organization.rs

@ -64,7 +64,6 @@ pub struct Membership {
pub invited_by_email: Option<String>, pub invited_by_email: Option<String>,
pub access_all: bool,
pub akey: String, pub akey: String,
pub status: i32, pub status: i32,
pub atype: i32, pub atype: i32,
@ -125,8 +124,7 @@ pub enum MembershipType {
Owner = 0, Owner = 0,
Admin = 1, Admin = 1,
User = 2, User = 2,
// The legacy Manager role. The Bitwarden clients no longer know it and are shown a Custom role instead. // Manager = 3 was removed like upstream: the managers became Users with the manage option on their collections.
Manager = 3,
// Only granted while EXPERIMENTAL_CUSTOM_ROLES is enabled. // Only granted while EXPERIMENTAL_CUSTOM_ROLES is enabled.
Custom = 4, Custom = 4,
} }
@ -137,50 +135,32 @@ impl MembershipType {
"0" | "Owner" => Some(MembershipType::Owner), "0" | "Owner" => Some(MembershipType::Owner),
"1" | "Admin" => Some(MembershipType::Admin), "1" | "Admin" => Some(MembershipType::Admin),
"2" | "User" => Some(MembershipType::User), "2" | "User" => Some(MembershipType::User),
"3" | "Manager" => Some(MembershipType::Manager),
"4" | "Custom" => Some(MembershipType::Custom), "4" | "Custom" => Some(MembershipType::Custom),
_ => None, _ => None,
} }
} }
/// The role a member invite or edit from the Bitwarden clients asks for, given the member's current /// Whether a member invite or edit may ask for `requested`, given the member's current role (`None` for an
/// role (`None` for an invite). /// 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.
/// The clients no longer know the legacy Manager role and are shown a Custom role in its place, so a pub fn check_requested(requested: MembershipType, current: Option<&Membership>) -> EmptyResult {
/// requested Custom role is the legacy Manager unless EXPERIMENTAL_CUSTOM_ROLES is enabled, in which case if requested == MembershipType::Custom
/// `custom_permissions` are the permissions requested along with it. An existing Manager or Custom member && !custom_roles_enabled()
/// keeps their role when the request repeats it, so an unrelated edit never turns one into the other. A && !current.is_some_and(|member| member.has_type(MembershipType::Custom))
/// Manager only becomes a Custom member when the permissions they are shown with are changed. {
pub fn requested( err!("Custom roles are not enabled")
requested: MembershipType,
current: Option<&Membership>,
custom_permissions: Option<&HashSet<CustomPermission>>,
) -> 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,
} }
Ok(())
} }
/// The authority of a role, which is what roles are compared by. A Custom member gets its authority from /// 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 { const fn rank(self) -> u8 {
match self { match self {
MembershipType::User => 0, MembershipType::User => 0,
MembershipType::Custom => 1, MembershipType::Custom => 1,
MembershipType::Manager => 2, MembershipType::Admin => 2,
MembershipType::Admin => 3, MembershipType::Owner => 3,
MembershipType::Owner => 4,
} }
} }
} }
@ -393,7 +373,7 @@ impl Organization {
"maxCollections": null, "maxCollections": null,
"maxStorageGb": i16::MAX, // The value doesn't matter, we don't check server-side "maxStorageGb": i16::MAX, // The value doesn't matter, we don't check server-side
"use2fa": true, "use2fa": true,
"useCustomPermissions": true, "useCustomPermissions": custom_roles_enabled(),
"useDirectory": false, // Is supported, but this value isn't checked anywhere (yet) "useDirectory": false, // Is supported, but this value isn't checked anywhere (yet)
"useEvents": CONFIG.org_events_enabled(), "useEvents": CONFIG.org_events_enabled(),
"useGroups": CONFIG.org_groups_enabled(), "useGroups": CONFIG.org_groups_enabled(),
@ -457,7 +437,6 @@ impl Membership {
org_uuid, org_uuid,
invited_by_email, invited_by_email,
access_all: false,
akey: String::new(), akey: String::new(),
status: MembershipStatus::Accepted as i32, status: MembershipStatus::Accepted as i32,
atype: MembershipType::User 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 /// 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 /// dropped, so changing the role back later starts from none.
/// `access_all` flag, its reach only comes from its permissions.
pub fn set_type(&mut self, new_type: MembershipType) { pub fn set_type(&mut self, new_type: MembershipType) {
if self.atype != new_type as i32 { if self.atype != new_type as i32 {
for permission in CustomPermission::ALL { for permission in CustomPermission::ALL {
*self.custom_permission_mut(permission) = false; *self.custom_permission_mut(permission) = false;
} }
} }
if new_type == MembershipType::Custom {
self.access_all = false;
}
self.atype = new_type as i32; 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<CustomPermission>,
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 { fn custom_permission(&self, permission: CustomPermission) -> bool {
match permission { match permission {
CustomPermission::ManageUsers => self.manage_users, 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)) 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`. /// The permissions the clients are shown.
pub fn legacy_manager_permissions(&self) -> HashSet<CustomPermission> {
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.
pub fn shown_custom_permissions(&self) -> HashSet<CustomPermission> { pub fn shown_custom_permissions(&self) -> HashSet<CustomPermission> {
if self.has_type(MembershipType::Manager) { CustomPermission::ALL.into_iter().filter(|p| self.grants_custom_permission(*p)).collect()
self.legacy_manager_permissions()
} else {
CustomPermission::ALL.into_iter().filter(|p| self.grants_custom_permission(*p)).collect()
}
} }
fn custom_permissions_json(&self) -> Value { fn custom_permissions_json(&self) -> Value {
@ -655,15 +581,6 @@ impl Membership {
} }
false 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 { impl OrganizationApiKey {
@ -783,11 +700,6 @@ impl Membership {
pub async fn to_json(&self, conn: &DbConn) -> Value { pub async fn to_json(&self, conn: &DbConn) -> Value {
let org = Organization::find_by_uuid(&self.org_uuid, conn).await.unwrap(); 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(); let permissions = self.custom_permissions_json();
// https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Models/Response/ProfileOrganizationResponseModel.cs // https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Models/Response/ProfileOrganizationResponseModel.cs
@ -815,7 +727,7 @@ impl Membership {
"useKeyConnector": false, "useKeyConnector": false,
"useSecretsManager": false, // Not supported (Not AGPLv3 Licensed) "useSecretsManager": false, // Not supported (Not AGPLv3 Licensed)
"usePasswordManager": true, "usePasswordManager": true,
"useCustomPermissions": true, "useCustomPermissions": custom_roles_enabled(),
"useActivateAutofillPolicy": false, "useActivateAutofillPolicy": false,
"useAdminSponsoredFamilies": false, "useAdminSponsoredFamilies": false,
"useRiskInsights": false, // Not supported (Not AGPLv3 Licensed) "useRiskInsights": false, // Not supported (Not AGPLv3 Licensed)
@ -839,8 +751,7 @@ impl Membership {
"familySponsorshipValidUntil": null, "familySponsorshipValidUntil": null,
"familySponsorshipToDelete": null, "familySponsorshipToDelete": null,
"accessSecretsManager": false, "accessSecretsManager": false,
// limit collection creation to managers with access_all permission to prevent issues "limitCollectionCreation": true,
"limitCollectionCreation": self.atype < MembershipType::Manager || !self.access_all,
"limitCollectionDeletion": true, "limitCollectionDeletion": true,
"limitItemDeletion": false, "limitItemDeletion": false,
"allowAdminAccessToAllCollectionItems": true, "allowAdminAccessToAllCollectionItems": true,
@ -855,7 +766,7 @@ impl Membership {
// Accepted (not yet confirmed) members have no key yet; send null like upstream, not "" // Accepted (not yet confirmed) members have no key yet; send null like upstream, not ""
"key": (!self.akey.is_empty()).then_some(&self.akey), "key": (!self.akey.is_empty()).then_some(&self.akey),
"status": self.status, "status": self.status,
"type": membership_type, "type": self.atype,
"enabled": true, "enabled": true,
"object": "profileOrganization", "object": "profileOrganization",
@ -889,15 +800,8 @@ impl Membership {
Vec::new() 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 // Only the collections assigned directly are returned, the ones assigned via a group are returned via a special group endpoint
let collections: Vec<Value> = if include_collections && !(full_access_group || self.access_all) { let collections: Vec<Value> = if include_collections {
CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn) CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn)
.await .await
.into_iter() .into_iter()
@ -906,7 +810,7 @@ impl Membership {
"id": cu.collection_uuid, "id": cu.collection_uuid,
"readOnly": cu.read_only, "readOnly": cu.read_only,
"hidePasswords": cu.hide_passwords, "hidePasswords": cu.hide_passwords,
"manage": cu.manage || (self.atype == MembershipType::Manager && !cu.read_only && !cu.hide_passwords), "manage": cu.manage,
}) })
}) })
.collect() .collect()
@ -914,10 +818,6 @@ impl Membership {
Vec::new() 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 // 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() { let permissions = if self.shown_custom_permissions().is_empty() {
json!(null) json!(null)
@ -936,7 +836,7 @@ impl Membership {
"collections": collections, "collections": collections,
"status": status, "status": status,
"type": membership_type, "type": self.atype,
"twoFactorEnabled": twofactor_enabled, "twoFactorEnabled": twofactor_enabled,
"resetPasswordEnrolled": self.reset_password_key.is_some(), "resetPasswordEnrolled": self.reset_password_key.is_some(),
"hasMasterPassword": !user.password_hash.is_empty(), "hasMasterPassword": !user.password_hash.is_empty(),
@ -962,12 +862,9 @@ impl Membership {
} }
pub async fn to_json_details(&self, conn: &DbConn) -> Value { pub async fn to_json_details(&self, conn: &DbConn) -> Value {
let coll_uuids = if self.access_all { let coll_uuids: Vec<Value> =
vec![] // If we have complete access, no need to fill the array CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn)
} else { .await
let collections =
CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn).await;
collections
.iter() .iter()
.map(|cu| { .map(|cu| {
json!({ json!({
@ -977,8 +874,7 @@ impl Membership {
"manage": cu.manage, "manage": cu.manage,
}) })
}) })
.collect() .collect();
};
// Because BitWarden want the status to be -1 for revoked users we need to catch that here. // 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. // 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!({ json!({
"id": self.uuid, "id": self.uuid,
"userId": self.user_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, "status": status,
"name": user.name, "name": user.name,
"email": user.email, "email": user.email,
@ -1023,12 +919,6 @@ impl Membership {
} }
pub async fn save(&self, conn: &DbConn) -> EmptyResult { 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; User::update_uuid_revision(&self.user_uuid, conn).await;
db_run! { conn: db_run! { conn:
@ -1099,13 +989,15 @@ impl Membership {
self.atype == user_type as i32 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 { 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 /// 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 /// full access, and a Custom member with Edit any collection. Neither adds anything to the member's own vault.
/// anything to the member's own vault.
pub fn can_edit_any_collection(&self) -> bool { pub fn can_edit_any_collection(&self) -> bool {
self.has_full_access() || self.has_custom_permission(CustomPermission::EditAnyCollection) self.has_full_access() || self.has_custom_permission(CustomPermission::EditAnyCollection)
} }
@ -1276,27 +1168,6 @@ impl Membership {
.await .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<Self> {
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::<Self>(conn)
.unwrap_or_default()
})
.await
}
pub async fn count_by_org(org_uuid: &OrganizationId, conn: &DbConn) -> i64 { pub async fn count_by_org(org_uuid: &OrganizationId, conn: &DbConn) -> i64 {
conn.run(move |conn| { conn.run(move |conn| {
users_organizations::table users_organizations::table
@ -1492,10 +1363,7 @@ impl Membership {
.eq(users_collections::collection_uuid) .eq(users_collections::collection_uuid)
.and(ciphers_collections::cipher_uuid.eq(&cipher_uuid))), .and(ciphers_collections::cipher_uuid.eq(&cipher_uuid))),
) )
.filter(users_organizations::access_all.eq(true).or( .filter(ciphers_collections::cipher_uuid.eq(&cipher_uuid)) // Access to a collection with the cipher
// AccessAll..
ciphers_collections::cipher_uuid.eq(&cipher_uuid), // ..or access to collection with cipher
))
.select(users_organizations::all_columns) .select(users_organizations::all_columns)
.distinct() .distinct()
.load::<Self>(conn) .load::<Self>(conn)
@ -1527,10 +1395,7 @@ impl Membership {
.eq(collections_groups::collections_uuid) .eq(collections_groups::collections_uuid)
.and(ciphers_collections::cipher_uuid.eq(&cipher_uuid))), .and(ciphers_collections::cipher_uuid.eq(&cipher_uuid))),
) )
.filter(groups::access_all.eq(true).or( .filter(ciphers_collections::cipher_uuid.eq(&cipher_uuid)) // Access to a collection via a group
// AccessAll via groups
ciphers_collections::cipher_uuid.eq(&cipher_uuid), // ..or access to collection via group
))
.select(users_organizations::all_columns) .select(users_organizations::all_columns)
.distinct() .distinct()
.load::<Self>(conn) .load::<Self>(conn)
@ -1548,10 +1413,7 @@ impl Membership {
users_organizations::table users_organizations::table
.filter(users_organizations::org_uuid.eq(org_uuid)) .filter(users_organizations::org_uuid.eq(org_uuid))
.left_join(users_collections::table.on(users_collections::user_uuid.eq(users_organizations::user_uuid))) .left_join(users_collections::table.on(users_collections::user_uuid.eq(users_organizations::user_uuid)))
.filter(users_organizations::access_all.eq(true).or( .filter(users_collections::collection_uuid.eq(&collection_uuid)) // Access to the collection
// AccessAll..
users_collections::collection_uuid.eq(&collection_uuid), // ..or access to collection with cipher
))
.select(users_organizations::all_columns) .select(users_organizations::all_columns)
.load::<Self>(conn) .load::<Self>(conn)
.expect("Error loading user organizations") .expect("Error loading user organizations")
@ -1667,7 +1529,7 @@ pub struct OrgApiKeyId(String);
mod tests { mod tests {
use super::*; use super::*;
use CustomPermission::*; use CustomPermission::*;
use MembershipType::{Admin, Custom, Manager, Owner, User}; use MembershipType::{Admin, Custom, Owner, User};
fn member(role: MembershipType) -> Membership { fn member(role: MembershipType) -> Membership {
let mut member = Membership::new("user".into(), "org".into(), None); let mut member = Membership::new("user".into(), "org".into(), None);
@ -1678,52 +1540,32 @@ mod tests {
#[test] #[test]
fn membership_type_authority() { fn membership_type_authority() {
assert!(Owner > Admin && Admin > Manager && Manager > Custom && Custom > User); assert!(Owner > Admin && Admin > Custom && Custom > User);
assert!((Custom as i32) >= User && (Custom as i32) < Manager && (Custom as i32) < Admin); assert!((Custom as i32) >= User && (Custom as i32) < Admin);
for raw in [99, -1] { for raw in [99, 3, -1] {
assert_eq!((raw >= User, raw >= Manager, raw >= Admin, raw < Admin), (false, false, false, true)); assert_eq!((raw >= User, raw >= Admin, raw < Admin), (false, false, true));
} }
for (value, expected) in [ for (value, expected) in
("3", Some(Manager)), [("3", None), ("Manager", None), ("4", Some(Custom)), ("Custom", Some(Custom)), ("5", None)]
("Manager", Some(Manager)), {
("4", Some(Custom)),
("Custom", Some(Custom)),
("5", None),
] {
assert_eq!(MembershipType::from_str(value), expected); assert_eq!(MembershipType::from_str(value), expected);
} }
} }
#[test] #[test]
fn requested_membership_type() { fn requested_membership_type() {
let none = HashSet::new(); for enabled in [false, true] {
let edit = HashSet::from([EditAnyCollection]); test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled));
let legacy = HashSet::from([CreateNewCollections, EditAnyCollection, DeleteAnyCollection]); for current in [None, Some(User), Some(Admin), Some(Custom)] {
for (current, all, permissions, disabled, enabled) in [ let current = current.map(member);
(None, false, &none, Manager, Custom), for requested in [Owner, Admin, User, Custom] {
(Some(User), false, &edit, Manager, Custom), let allowed = requested != Custom || enabled || current.as_ref().is_some_and(|m| m.atype == 4);
(Some(Owner), false, &none, Manager, Custom), let result = MembershipType::check_requested(requested, current.as_ref());
(Some(Manager), false, &none, Manager, Manager), assert_eq!(result.is_ok(), allowed, "{enabled} {requested:?}");
(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);
} }
} }
assert_eq!(MembershipType::requested(User, Some(&member(Custom)), None), User); test_flag::CUSTOM_ROLES_ENABLED.set(None);
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] #[test]
@ -1760,18 +1602,10 @@ mod tests {
#[test] #[test]
fn role_changes_drop_custom_permissions() { fn role_changes_drop_custom_permissions() {
for (from, to) in [ for (from, to) in
(Custom, Owner), [(Custom, Owner), (Custom, Admin), (Custom, User), (User, Custom), (Custom, Custom), (Admin, User)]
(Custom, Admin), {
(Custom, Manager),
(Custom, User),
(User, Custom),
(Manager, Custom),
(Custom, Custom),
(Admin, User),
] {
let mut member = member(from); let mut member = member(from);
member.access_all = true;
for permission in CustomPermission::ALL { for permission in CustomPermission::ALL {
*member.custom_permission_mut(permission) = true; *member.custom_permission_mut(permission) = true;
} }
@ -1779,24 +1613,17 @@ mod tests {
for permission in CustomPermission::ALL { for permission in CustomPermission::ALL {
assert_eq!(*member.custom_permission_mut(permission), from == to, "{from:?} -> {to:?}"); assert_eq!(*member.custom_permission_mut(permission), from == to, "{from:?} -> {to:?}");
} }
assert_eq!(member.access_all, to != Custom);
} }
} }
#[test] #[test]
fn permission_matrix_preserves_role_status_flag_and_collection_boundaries() { fn permission_matrix_preserves_role_status_flag_and_collection_boundaries() {
let legacy = HashSet::from([CreateNewCollections, EditAnyCollection, DeleteAnyCollection]); for role in [Owner, Admin, Custom, User] {
for (role, all) in
[(Owner, false), (Admin, false), (Manager, false), (Manager, true), (Custom, false), (User, false)]
{
for permission in CustomPermission::ALL { for permission in CustomPermission::ALL {
let mut member = member(role); let mut member = member(role);
member.access_all = all;
*member.custom_permission_mut(permission) = true; *member.custom_permission_mut(permission) = true;
for enabled in [false, true] { for enabled in [false, true] {
test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled)); test_flag::CUSTOM_ROLES_ENABLED.set(Some(enabled));
let shown = if role == Manager && all { let shown = if role == Custom && enabled && permission.is_supported() {
legacy.clone()
} else if role == Custom && enabled && permission.is_supported() {
HashSet::from([permission]) HashSet::from([permission])
} else { } else {
HashSet::new() HashSet::new()
@ -1805,7 +1632,7 @@ mod tests {
for status in [-128, -127, -126, -3, -2, -1, 0, 1, 2] { for status in [-128, -127, -126, -3, -2, -1, 0, 1, 2] {
member.status = status; member.status = status;
let allowed = enabled && role == Custom && status == 2 && permission.is_supported(); 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 edit = full || (allowed && permission == EditAnyCollection);
let view = full || (allowed && matches!(permission, EditAnyCollection | DeleteAnyCollection)); let view = full || (allowed && matches!(permission, EditAnyCollection | DeleteAnyCollection));
assert_eq!( assert_eq!(
@ -1815,7 +1642,7 @@ mod tests {
member.can_view_all_collections() member.can_view_all_collections()
), ),
(allowed, edit, view), (allowed, edit, view),
"{role:?} {all} {enabled} {status} {permission:?}" "{role:?} {enabled} {status} {permission:?}"
); );
assert_eq!( assert_eq!(
(member.can_list_all_collections(), member.can_list_all_ciphers()), (member.can_list_all_collections(), member.can_list_all_ciphers()),

2
src/db/schema.rs

@ -254,7 +254,6 @@ table! {
user_uuid -> Text, user_uuid -> Text,
org_uuid -> Text, org_uuid -> Text,
invited_by_email -> Nullable<Text>, invited_by_email -> Nullable<Text>,
access_all -> Bool,
akey -> Text, akey -> Text,
status -> Integer, status -> Integer,
atype -> Integer, atype -> Integer,
@ -328,7 +327,6 @@ table! {
uuid -> Text, uuid -> Text,
organizations_uuid -> Text, organizations_uuid -> Text,
name -> Text, name -> Text,
access_all -> Bool,
external_id -> Nullable<Text>, external_id -> Nullable<Text>,
creation_date -> Timestamp, creation_date -> Timestamp,
revision_date -> Timestamp, revision_date -> Timestamp,

4
src/static/scripts/admin_users.js

@ -173,10 +173,6 @@ const ORG_TYPES = {
"name": "User", "name": "User",
"bg": "blue" "bg": "blue"
}, },
"3": {
"name": "Manager",
"bg": "green"
},
"4": { "4": {
"name": "Custom", "name": "Custom",
"bg": "teal" "bg": "teal"

3
src/static/templates/admin/users.hbs

@ -132,9 +132,6 @@
<div class="radio"> <div class="radio">
<label><input type="radio" value="2" class="form-radio-input" name="user_type" id="userOrgTypeUser">&nbsp;User</label> <label><input type="radio" value="2" class="form-radio-input" name="user_type" id="userOrgTypeUser">&nbsp;User</label>
</div> </div>
<div class="radio">
<label><input type="radio" value="3" class="form-radio-input" name="user_type" id="userOrgTypeManager">&nbsp;Manager</label>
</div>
{{#if custom_roles_enabled}} {{#if custom_roles_enabled}}
<div class="radio"> <div class="radio">
<label><input type="radio" value="4" class="form-radio-input" name="user_type" id="userOrgTypeCustom">&nbsp;Custom</label> <label><input type="radio" value="4" class="form-radio-input" name="user_type" id="userOrgTypeCustom">&nbsp;Custom</label>

4
src/static/templates/scss/vaultwarden.scss.hbs

@ -104,8 +104,8 @@ app-security > app-two-factor-setup > form {
@extend %vw-hide; @extend %vw-hide;
} }
{{else}} {{else}}
:is(bit-dialog, [bit-dialog]) div.tw-ml-4:has(bit-form-control input), /* An existing Custom member keeps the role, but has no permissions to show */
:is(bit-dialog, [bit-dialog]) div.tw-col-span-4:has(input[formcontrolname*="access"], input[formcontrolname*="manage"]) { :is(bit-dialog, [bit-dialog]) div.tw-grid:has(> div.tw-col-span-4 input[formcontrolname="accessEventLogs"]) {
@extend %vw-hide; @extend %vw-hide;
} }
{{/if}} {{/if}}

Loading…
Cancel
Save