@ -8,17 +8,21 @@ use crate::{
CONFIG ,
CONFIG ,
api ::admin ::FAKE_ADMIN_UUID ,
api ::admin ::FAKE_ADMIN_UUID ,
api ::{
api ::{
EmptyResult , JsonResult , Notify , PasswordOrOtpData , UpdateType ,
ApiResult , EmptyResult , JsonResult , Notify , PasswordOrOtpData , UpdateType ,
core ::{ CipherSyncData , CipherSyncType , accept_org_invite , log_event , two_factor } ,
core ::{ CipherSyncData , CipherSyncType , accept_org_invite , log_event , two_factor } ,
} ,
} ,
auth ::{ AdminHeaders , Headers , ManagerHeaders , ManagerHeadersLoose , OrgMemberHeaders , OwnerHeaders , decode_invite } ,
auth ::{
AdminHeaders , CollectionAction , CollectionDeleteHeaders , CollectionReadHeaders , Headers , ManagerHeaders ,
ManagerHeadersLoose , OrgMemberHeaders , OwnerHeaders , custom_member_may , decode_invite ,
} ,
db ::{
db ::{
DbConn ,
DbConn ,
models ::{
models ::{
Cipher , CipherId , Collection , CollectionCipher , CollectionGroup , CollectionId , CollectionUser ,
Cipher , CipherAccessScope , CipherId , Collection , CollectionCipher , CollectionGroup , CollectionId ,
CustomPermission , Device , EventType , FillAssistPolicyData , Group , GroupId , GroupUser , Invitation ,
CollectionUser , CustomPermission , Device , EventType , FillAssistPolicyData , Group , GroupId , GroupUser ,
Membership , MembershipId , MembershipStatus , MembershipType , OrgPolicy , OrgPolicyType , Organization ,
Invitation , Membership , MembershipId , MembershipStatus , MembershipType , OrgPolicy , OrgPolicyType ,
OrganizationApiKey , OrganizationId , TwoFactor , TwoFactorType , User , UserId , custom_roles_enabled ,
Organization , OrganizationApiKey , OrganizationId , TwoFactor , TwoFactorType , User , UserId ,
custom_roles_enabled ,
} ,
} ,
} ,
} ,
mail ,
mail ,
@ -47,6 +51,7 @@ pub fn routes() -> Vec<Route> {
bulk_delete_organization_collections ,
bulk_delete_organization_collections ,
post_bulk_collections ,
post_bulk_collections ,
get_org_details ,
get_org_details ,
get_assigned_org_details ,
get_org_domain_sso_verified ,
get_org_domain_sso_verified ,
get_members ,
get_members ,
send_invite ,
send_invite ,
@ -363,12 +368,24 @@ async fn get_org_collections(org_id: OrganizationId, headers: ManagerHeadersLoos
err ! ( "Organization not found" , "Organization id's do not match" ) ;
err ! ( "Organization not found" , "Organization id's do not match" ) ;
}
}
if ! headers . membership . has_full_access ( ) {
let collections = if headers . membership . can_view_all_collections ( ) {
get_org_collections_impl ( & org_id , & conn ) . await
} else if headers . membership . has_type ( MembershipType ::Custom ) {
// A Custom member gets the collections they may manage
let manageable =
Collection ::find_explicitly_manageable_by_user ( & org_id , & headers . membership . user_uuid , & conn ) . await ;
Collection ::find_by_organization ( & org_id , & conn )
. await
. iter ( )
. filter ( | collection | manageable . contains ( & collection . uuid ) )
. map ( Collection ::to_json )
. collect ::< Value > ( )
} else {
err_code ! ( "Resource not found." , "User does not have full access" , Status ::NotFound . code ) ;
err_code ! ( "Resource not found." , "User does not have full access" , Status ::NotFound . code ) ;
}
} ;
Ok ( Json ( json ! ( {
Ok ( Json ( json ! ( {
"data" : get_org_collections_impl ( & org_id , & conn ) . await ,
"data" : collections ,
"object" : "list" ,
"object" : "list" ,
"continuationToken" : null ,
"continuationToken" : null ,
} ) ) )
} ) ) )
@ -395,6 +412,12 @@ async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHea
// check if current user has full access to the organization (either directly or via any group)
// 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 ( )
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 ) ;
| | ( CONFIG . org_groups_enabled ( ) & & GroupUser ::has_full_access_by_member ( & org_id , & member . uuid , & conn ) . await ) ;
// A Custom member gets every collection when they may see all of them, else the ones they may manage
let custom_collections = if member . has_type ( MembershipType ::Custom ) & & ! member . can_view_all_collections ( ) {
Some ( Collection ::find_explicitly_manageable_by_user ( & org_id , & member . user_uuid , & conn ) . await )
} else {
None
} ;
// Get all admins, owners and managers who can manage/access all
// 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.
// Those are currently not listed in the col_users but need to be listed too.
@ -420,7 +443,12 @@ async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHea
& & GroupUser ::has_access_to_collection_by_member ( & col . uuid , & member . uuid , & conn ) . await ) ;
& & 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
// If the user is a manager, and is not assigned to this collection, skip this and continue with the next collection
if ! assigned {
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 ;
}
}
@ -480,7 +508,10 @@ 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 {
if ( headers . membership . atype = = MembershipType ::Manager & & ! headers . membership . access_all )
| | ( headers . membership . has_type ( MembershipType ::Custom )
& & ! 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" )
}
}
@ -563,7 +594,12 @@ async fn post_bulk_access_collections(
err ! ( "Collection not found" )
err ! ( "Collection not found" )
} ;
} ;
if ! collection . is_manageable_by_user ( & headers . membership . user_uuid , & conn ) . await {
let manageable = if headers . membership . has_type ( MembershipType ::Custom ) {
custom_member_may ( CollectionAction ::Edit , & headers . membership , & collection . uuid , & conn ) . await
} else {
collection . is_manageable_by_user ( & headers . membership . user_uuid , & conn ) . await
} ;
if ! manageable {
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" )
}
}
@ -676,7 +712,7 @@ async fn put_organization_collection_update(
async fn delete_organization_collection_impl (
async fn delete_organization_collection_impl (
org_id : & OrganizationId ,
org_id : & OrganizationId ,
col_id : & CollectionId ,
col_id : & CollectionId ,
headers : & Manager Headers,
headers : & CollectionDelete Headers,
conn : & DbConn ,
conn : & DbConn ,
) -> EmptyResult {
) -> EmptyResult {
if org_id ! = & headers . org_id {
if org_id ! = & headers . org_id {
@ -702,7 +738,7 @@ async fn delete_organization_collection_impl(
async fn delete_organization_collection (
async fn delete_organization_collection (
org_id : OrganizationId ,
org_id : OrganizationId ,
col_id : CollectionId ,
col_id : CollectionId ,
headers : Manager Headers,
headers : CollectionDelete Headers,
conn : DbConn ,
conn : DbConn ,
) -> EmptyResult {
) -> EmptyResult {
delete_organization_collection_impl ( & org_id , & col_id , & headers , & conn ) . await
delete_organization_collection_impl ( & org_id , & col_id , & headers , & conn ) . await
@ -728,7 +764,7 @@ async fn bulk_delete_organization_collections(
let collections = data . ids ;
let collections = data . ids ;
let headers = Manager Headers ::from_loose ( headers , & collections , & conn ) . await ? ;
let headers = CollectionDelete Headers ::from_loose ( headers , & collections , & conn ) . await ? ;
for col_id in collections {
for col_id in collections {
delete_organization_collection_impl ( & org_id , & col_id , & headers , & conn ) . await ? ;
delete_organization_collection_impl ( & org_id , & col_id , & headers , & conn ) . await ? ;
@ -740,23 +776,28 @@ async fn bulk_delete_organization_collections(
async fn get_org_collection_detail (
async fn get_org_collection_detail (
org_id : OrganizationId ,
org_id : OrganizationId ,
col_id : CollectionId ,
col_id : CollectionId ,
headers : Manager Headers,
headers : CollectionRead Headers,
conn : DbConn ,
conn : DbConn ,
) -> JsonResult {
) -> JsonResult {
if org_id ! = headers . org_id {
if org_id ! = headers . org_id {
err ! ( "Organization not found" , "Organization id's do not match" ) ;
err ! ( "Organization not found" , "Organization id's do not match" ) ;
}
}
match Collection ::find_by_uuid_and_user ( & col_id , headers . user . uuid . clone ( ) , & conn ) . await {
let Some ( member ) = Membership ::find_by_user_and_org ( & headers . user . uuid , & org_id , & conn ) . await else {
err ! ( "User is not part of organization" )
} ;
// A Custom member may be allowed to read a collection they are not assigned to
let collection = if member . has_type ( MembershipType ::Custom ) {
Collection ::find_by_uuid_and_org ( & col_id , & org_id , & conn ) . await
} else {
Collection ::find_by_uuid_and_user ( & col_id , headers . user . uuid . clone ( ) , & conn ) . await
} ;
match collection {
None = > err ! ( "Collection not found" ) ,
None = > err ! ( "Collection not found" ) ,
Some ( collection ) = > {
Some ( collection ) = > {
if collection . org_uuid ! = org_id {
if collection . org_uuid ! = org_id {
err ! ( "Collection is not owned by organization" )
err ! ( "Collection is not owned by organization" )
}
}
let Some ( member ) = Membership ::find_by_user_and_org ( & headers . user . uuid , & org_id , & conn ) . await else {
err ! ( "User is not part of organization" )
} ;
let groups : Vec < Value > = if CONFIG . org_groups_enabled ( ) {
let groups : Vec < Value > = if CONFIG . org_groups_enabled ( ) {
CollectionGroup ::find_by_collection ( & collection . uuid , & conn )
CollectionGroup ::find_by_collection ( & collection . uuid , & conn )
. await
. await
@ -805,7 +846,7 @@ async fn get_org_collection_detail(
async fn get_collection_users (
async fn get_collection_users (
org_id : OrganizationId ,
org_id : OrganizationId ,
col_id : CollectionId ,
col_id : CollectionId ,
headers : Manager Headers,
headers : CollectionRead Headers,
conn : DbConn ,
conn : DbConn ,
) -> JsonResult {
) -> JsonResult {
if org_id ! = headers . org_id {
if org_id ! = headers . org_id {
@ -841,7 +882,7 @@ async fn get_org_details(data: OrgIdData, headers: ManagerHeadersLoose, conn: Db
err_code ! ( "Resource not found." , "Organization id's do not match" , Status ::NotFound . code ) ;
err_code ! ( "Resource not found." , "Organization id's do not match" , Status ::NotFound . code ) ;
}
}
if ! headers . membership . has_full_access ( ) {
if ! headers . membership . can_edit_any_collection ( ) {
err_code ! ( "Resource not found." , "User does not have full access" , Status ::NotFound . code ) ;
err_code ! ( "Resource not found." , "User does not have full access" , Status ::NotFound . code ) ;
}
}
@ -859,7 +900,12 @@ async fn get_org_details_impl(
conn : & DbConn ,
conn : & DbConn ,
) -> Result < Value , crate ::Error > {
) -> Result < Value , crate ::Error > {
let ciphers = Cipher ::find_by_org ( org_id , conn ) . await ;
let ciphers = Cipher ::find_by_org ( org_id , conn ) . await ;
let cipher_sync_data = CipherSyncData ::new ( user_id , CipherSyncType ::Organization , conn ) . await ;
let mut cipher_sync_data = CipherSyncData ::new ( user_id , CipherSyncType ::Organization , conn ) . await ;
// Every cipher of the organization is listed, so list every collection of them too
cipher_sync_data . cipher_collections = HashMap ::new ( ) ;
for ( cipher_id , collection_id ) in Cipher ::get_collections_with_cipher_by_organization ( org_id , conn ) . await {
cipher_sync_data . cipher_collections . entry ( cipher_id ) . or_default ( ) . push ( collection_id ) ;
}
let mut ciphers_json = Vec ::with_capacity ( ciphers . len ( ) ) ;
let mut ciphers_json = Vec ::with_capacity ( ciphers . len ( ) ) ;
for c in ciphers {
for c in ciphers {
@ -868,6 +914,39 @@ async fn get_org_details_impl(
Ok ( json ! ( ciphers_json ) )
Ok ( json ! ( ciphers_json ) )
}
}
// The Admin Console lists these instead of every cipher of the organization for a member who may not edit every
// cipher, like a Custom member with Delete any collection only. As in Bitwarden, any confirmed member may list them.
#[ get( " /ciphers/organization-details/assigned?<data..> " ) ]
async fn get_assigned_org_details ( data : OrgIdData , headers : Headers , conn : DbConn ) -> JsonResult {
let Some ( member ) =
Membership ::find_confirmed_by_user_and_org ( & headers . user . uuid , & data . organization_id , & conn ) . await
else {
err_code ! ( "Resource not found." , "User is not a confirmed member of the organization" , Status ::NotFound . code ) ;
} ;
let ( assigned , unassigned ) = Cipher ::find_assigned_to_member ( & member , & conn ) . await ;
let mut ciphers_json = Vec ::with_capacity ( assigned . len ( ) + unassigned . len ( ) ) ;
// The ciphers of the member's own vault, as they are there
let cipher_sync_data = CipherSyncData ::new ( & headers . user . uuid , CipherSyncType ::User , & conn ) . await ;
for cipher in assigned {
ciphers_json . push (
cipher
. to_json ( & headers . host , & headers . user . uuid , Some ( & cipher_sync_data ) , CipherSyncType ::User , & conn )
. await ? ,
) ;
}
// The ciphers in no collection, as the member may use them in the Admin Console
for cipher in unassigned {
ciphers_json . push ( cipher . to_json_org_admin ( & headers . host , & headers . user . uuid , & conn ) . await ? ) ;
}
Ok ( Json ( json ! ( {
"data" : ciphers_json ,
"object" : "list" ,
"continuationToken" : null ,
} ) ) )
}
// Returning a Domain/Organization here allow to prefill it and prevent prompting the user
// Returning a Domain/Organization here allow to prefill it and prevent prompting the user
// So we return a dummy value, since we only support a single SSO integration, and do not use the response anywhere
// So we return a dummy value, since we only support a single SSO integration, and do not use the response anywhere
// In use since `v2025.6.0`, appears to use only the first `organizationIdentifier`
// In use since `v2025.6.0`, appears to use only the first `organizationIdentifier`
@ -1013,7 +1092,13 @@ async fn send_invite(
let Some ( requested_type ) = MembershipType ::from_str ( raw_type ) else {
let Some ( requested_type ) = MembershipType ::from_str ( raw_type ) else {
err ! ( "Invalid type" )
err ! ( "Invalid type" )
} ;
} ;
let new_type = MembershipType ::requested ( requested_type , None , custom_roles_enabled ( ) ) ;
// Checked before anything is created, so a rejected permission leaves nothing behind
let custom_permissions = if requested_type = = MembershipType ::Custom & & custom_roles_enabled ( ) {
Some ( CustomPermission ::requested ( & data . permissions ) ? )
} else {
None
} ;
let new_type = MembershipType ::requested ( requested_type , None , custom_permissions . as_ref ( ) ) ;
if new_type ! = MembershipType ::User & & headers . membership_type ! = MembershipType ::Owner {
if new_type ! = MembershipType ::User & & headers . membership_type ! = MembershipType ::Owner {
err ! ( "Only Owners can invite Managers, Admins or Owners" )
err ! ( "Only Owners can invite Managers, Admins or Owners" )
@ -1029,13 +1114,6 @@ async fn send_invite(
& & data . permissions . get ( "deleteAnyCollection" ) = = Some ( & json ! ( true ) )
& & data . permissions . get ( "deleteAnyCollection" ) = = Some ( & json ! ( true ) )
& & data . permissions . get ( "createNewCollections" ) = = Some ( & json ! ( true ) ) ) ;
& & data . permissions . get ( "createNewCollections" ) = = Some ( & json ! ( true ) ) ) ;
// Checked before anything is created, so a rejected permission leaves nothing behind
let custom_permissions = if new_type = = MembershipType ::Custom {
Some ( CustomPermission ::requested ( & data . permissions ) ? )
} else {
None
} ;
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 ;
@ -1458,6 +1536,11 @@ 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" ) ;
}
}
if headers . membership . has_type ( MembershipType ::Custom )
& & ! may_assign_collection_access ( & headers . membership , & conn ) . await
{
err_code ! ( "Resource not found." , "User does not have access" , Status ::NotFound . code ) ;
}
let mut members_json = Vec ::new ( ) ;
let mut members_json = Vec ::new ( ) ;
for m in Membership ::find_by_org ( & org_id , & conn ) . await {
for m in Membership ::find_by_org ( & org_id , & conn ) . await {
members_json . push ( m . to_json_mini_details ( & conn ) . await ) ;
members_json . push ( m . to_json_mini_details ( & conn ) . await ) ;
@ -1526,7 +1609,20 @@ async fn edit_member(
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" )
} ;
} ;
let new_type = MembershipType ::requested ( requested_type , Some ( & member_to_edit ) , custom_roles_enabled ( ) ) ;
// While Custom roles are disabled, a Custom member keeps their stored permissions untouched
let custom_permissions = if requested_type = = MembershipType ::Custom & & custom_roles_enabled ( ) {
Some ( CustomPermission ::requested ( & data . permissions ) ? )
} else {
None
} ;
let new_type = MembershipType ::requested ( requested_type , Some ( & member_to_edit ) , custom_permissions . as_ref ( ) ) ;
// A Manager whose permissions are changed only becomes a Custom member if that keeps what they may do
if new_type = = MembershipType ::Custom
& & let Some ( permissions ) = & custom_permissions
& & let Some ( loss ) = member_to_edit . custom_role_conversion_loss ( permissions , & conn ) . await
{
err ! ( loss )
}
// HACK: This converts the Custom role which has the `Manage all collections` box checked into an access_all flag
// 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
// Since the parent checkbox is not sent to the server we need to check and verify the child checkboxes
@ -1538,13 +1634,6 @@ async fn edit_member(
& & data . permissions . get ( "deleteAnyCollection" ) = = Some ( & json ! ( true ) )
& & data . permissions . get ( "deleteAnyCollection" ) = = Some ( & json ! ( true ) )
& & data . permissions . get ( "createNewCollections" ) = = Some ( & json ! ( true ) ) ) ;
& & data . permissions . get ( "createNewCollections" ) = = Some ( & json ! ( true ) ) ) ;
// While Custom roles are disabled, a Custom member keeps their stored permissions untouched
let custom_permissions = if new_type = = MembershipType ::Custom & & custom_roles_enabled ( ) {
Some ( CustomPermission ::requested ( & data . permissions ) ? )
} else {
None
} ;
if new_type ! = member_to_edit . atype
if new_type ! = member_to_edit . atype
& & ( member_to_edit . atype > = MembershipType ::Admin | | new_type > = MembershipType ::Admin )
& & ( member_to_edit . atype > = MembershipType ::Admin | | new_type > = MembershipType ::Admin )
& & headers . membership_type ! = MembershipType ::Owner
& & headers . membership_type ! = MembershipType ::Owner
@ -1568,7 +1657,7 @@ 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 ;
member_to_edit . access_all = access_all ;
if let Some ( permissions ) = & custom_permissions {
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 ) ;
}
}
@ -1799,6 +1888,46 @@ struct RelationsData {
value : usize ,
value : usize ,
}
}
fn validate_org_import_relationships ( data : & ImportData ) -> ApiResult < Vec < ( usize , usize ) > > {
let mut relations = Vec ::with_capacity ( data . collection_relationships . len ( ) ) ;
let mut seen = HashSet ::new ( ) ;
for relation in & data . collection_relationships {
if relation . key > = data . ciphers . len ( ) | | relation . value > = data . collections . len ( ) {
err ! ( Compact , "Invalid collection relationship" )
}
if seen . insert ( ( relation . key , relation . value ) ) {
relations . push ( ( relation . key , relation . value ) ) ;
}
}
Ok ( relations )
}
async fn validate_org_import_collections (
imported : & [ ImportCollectionData ] ,
org_id : & OrganizationId ,
membership : & Membership ,
conn : & DbConn ,
) -> ApiResult < 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 ( ) ;
for col in imported {
if let Some ( collection ) = col . id . as_ref ( ) . and_then ( | id | existing . get ( id ) ) {
if membership . atype < MembershipType ::Admin
& & ! membership . can_edit_any_collection ( )
& & ! collection . is_writable_by_user ( & membership . user_uuid , conn ) . await
{
err ! ( Compact , "The current user isn't allowed to manage this collection" )
}
} else if membership . atype < = MembershipType ::Manager
& & ! membership . has_full_access ( )
& & ! membership . has_custom_permission ( CustomPermission ::CreateNewCollections )
{
err ! ( Compact , "The current user isn't allowed to create new collections" )
}
}
Ok ( existing )
}
// https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/Tools/Controllers/ImportCiphersController.cs#L62
// https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/Tools/Controllers/ImportCiphersController.cs#L62
#[ post( " /ciphers/import-organization?<query..> " , data = " <data> " ) ]
#[ post( " /ciphers/import-organization?<query..> " , data = " <data> " ) ]
async fn post_org_import (
async fn post_org_import (
@ -1824,73 +1953,171 @@ async fn post_org_import(
// TODO: See if we can optimize the whole cipher adding/importing and prevent duplicate code and checks.
// TODO: See if we can optimize the whole cipher adding/importing and prevent duplicate code and checks.
Cipher ::validate_cipher_data ( & data . ciphers ) ? ;
Cipher ::validate_cipher_data ( & data . ciphers ) ? ;
let existing_collections : HashMap < CollectionId , Collection > =
let relations = validate_org_import_relationships ( & data ) ? ;
Collection ::find_by_organization ( & org_id , & conn ) . await . into_iter ( ) . map ( | c | ( c . uuid . clone ( ) , c ) ) . collect ( ) ;
let ImportData {
let mut collections : Vec < CollectionId > = Vec ::with_capacity ( data . collections . len ( ) ) ;
ciphers : imported_ciphers ,
for col in data . collections {
collections : imported_collections ,
let existing = col . id . as_ref ( ) . and_then ( | col_id | existing_collections . get ( col_id ) ) ;
. .
let collection_uuid = if let Some ( collection ) = existing {
} = data ;
// When not an Owner or Admin, check if the member is allowed to write to the collection.
let grant_new_collection_manage = headers . membership . has_type ( MembershipType ::Custom ) ;
if headers . membership . atype < MembershipType ::Admin
let importer_uuid = headers . membership . user_uuid . clone ( ) ;
& & ! collection . is_writable_by_user ( & headers . membership . user_uuid , & conn ) . await
let OrgMemberHeaders {
{
host ,
err ! ( Compact , "The current user isn't allowed to manage this collection" )
device ,
}
user ,
collection . uuid . clone ( )
membership ,
} else {
ip ,
// We do not allow users or managers which can not manage all collections to create new collections
} = headers ;
// If there is any collection other than an existing import collection, abort the import.
let headers = Headers {
if headers . membership . atype < = MembershipType ::Manager & & ! headers . membership . has_full_access ( ) {
host ,
err ! ( Compact , "The current user isn't allowed to create new collections" )
device ,
}
user ,
let new_collection = Collection ::new ( org_id . clone ( ) , col . name , col . external_id ) ;
ip ,
new_collection . save ( & conn ) . await ? ;
} ;
new_collection . uuid
} ;
collections . push ( collection_uuid ) ;
// Keep authorization and every write on the same connection. A failure at any later cipher or
}
// relationship must also roll back newly created collections and their Manage assignments.
conn . transaction ( async | | {
let existing = validate_org_import_collections ( & imported_collections , & org_id , & membership , & conn ) . await ? ;
let mut collections : Vec < CollectionId > = Vec ::with_capacity ( imported_collections . len ( ) ) ;
for col in imported_collections {
let collection_uuid = if let Some ( collection ) = col . id . as_ref ( ) . and_then ( | id | existing . get ( id ) ) {
collection . uuid . clone ( )
} else {
let new_collection = Collection ::new ( org_id . clone ( ) , col . name , col . external_id ) ;
new_collection . save ( & conn ) . await ? ;
if grant_new_collection_manage {
CollectionUser ::save ( & importer_uuid , & new_collection . uuid , false , false , true , & conn ) . await ? ;
}
new_collection . uuid
} ;
collections . push ( collection_uuid ) ;
}
// Read the relations between collections and ciphers
let mut assigned = vec ! [ Vec ::< CollectionId > ::new ( ) ; imported_ciphers . len ( ) ] ;
// Ciphers can be in multiple collections at the same time
for ( cipher_index , collection_index ) in relations {
let mut relations = Vec ::with_capacity ( data . collection_relationships . len ( ) ) ;
assigned [ cipher_index ] . push ( collections [ collection_index ] . clone ( ) ) ;
for relation in data . collection_relationships {
}
relations . push ( ( relation . key , relation . value ) ) ;
for ( mut cipher_data , collection_ids ) in imported_ciphers . into_iter ( ) . zip ( assigned ) {
}
cipher_data . folder_id = None ;
// The authenticated membership, rather than the imported file, selects the organization.
let headers : Headers = headers . into ( ) ;
cipher_data . organization_id = Some ( org_id . clone ( ) ) ;
let mut cipher = Cipher ::new ( cipher_data . r#type ) ;
let mut ciphers : Vec < CipherId > = Vec ::with_capacity ( data . ciphers . len ( ) ) ;
update_cipher_from_data (
for mut cipher_data in data . ciphers {
& mut cipher ,
// Always clear folder_id's via an organization import
cipher_data ,
cipher_data . folder_id = None ;
& headers ,
// Replace the client-provided, unvalidated organizationId with the real target org
Some ( collection_ids . clone ( ) ) ,
cipher_data . organization_id = Some ( org_id . clone ( ) ) ;
& conn ,
let mut cipher = Cipher ::new ( cipher_data . r#type , cipher_data . name . clone ( ) ) ;
& nt ,
update_cipher_from_data (
UpdateType ::None ,
& mut cipher ,
false ,
cipher_data ,
)
& headers ,
. await ? ;
Some ( collections . clone ( ) ) ,
for collection_id in collection_ids {
& conn ,
CollectionCipher ::save ( & cipher . uuid , & collection_id , & conn ) . await ? ;
& nt ,
}
UpdateType ::None ,
}
)
. await
. ok ( ) ;
ciphers . push ( cipher . uuid ) ;
}
// Assign the collections
let mut user = headers . user ;
for ( cipher_index , col_index ) in relations {
user . update_revision ( & conn ) . await
let ( Some ( cipher_id ) , Some ( col_id ) ) = ( ciphers . get ( cipher_index ) , collections . get ( col_index ) ) else {
} )
err ! ( Compact , "Invalid collection relationship" )
. await
} ;
}
CollectionCipher ::save ( cipher_id , col_id , & conn ) . await ? ;
}
let mut user = headers . user ;
#[ cfg(all(test, feature = " sqlite " )) ]
user . update_revision ( & conn ) . await
mod org_import_tests {
use super ::* ;
use crate ::{
api ::notifications ::{ WS_USERS , WebSocketUsers } ,
db ::{ models ::test_flag , test_db } ,
} ;
use diesel ::connection ::SimpleConnection ;
use std ::sync ::Arc ;
#[ test ]
fn imports_preserve_authorization_atomicity_and_creator_access ( ) {
test_db ::run ( async | db | {
let conn = db . conn ( ) ;
for ( case , role , permission ) in [
( "owner" , MembershipType ::Owner , CustomPermission ::CreateNewCollections ) ,
( "admin" , MembershipType ::Admin , CustomPermission ::CreateNewCollections ) ,
( "cipher" , MembershipType ::Custom , CustomPermission ::CreateNewCollections ) ,
( "custom" , MembershipType ::Custom , CustomPermission ::CreateNewCollections ) ,
( "legacy" , MembershipType ::Manager , CustomPermission ::CreateNewCollections ) ,
( "authorization" , MembershipType ::Custom , CustomPermission ::CreateNewCollections ) ,
( "rollback" , MembershipType ::Custom , CustomPermission ::CreateNewCollections ) ,
( "index" , MembershipType ::Custom , CustomPermission ::CreateNewCollections ) ,
( "disabled" , MembershipType ::Custom , CustomPermission ::CreateNewCollections ) ,
( "export" , MembershipType ::Owner , CustomPermission ::CreateNewCollections ) ,
] {
test_flag ::CUSTOM_ROLES_ENABLED . set ( Some ( case ! = "disabled" ) ) ;
let org = test_db ::organization ( & conn ) . await ;
let permissions = if role = = MembershipType ::Custom {
vec ! [ permission ]
} else {
vec ! [ ]
} ;
let ( user , mut membership ) = test_db ::member ( & conn , & org . uuid , role , & permissions ) . await ;
membership . access_all = role = = MembershipType ::Manager ;
membership . save ( & conn ) . await . unwrap ( ) ;
let mut payload = json ! ( { "ciphers" :[ { "name" :"Cipher" , "type" :2 , "encryptedFor" :user . uuid , "secureNote" :{ "type" :0 } } ] ,
"collections" :[ { "name" :"New" } ] , "collectionRelationships" :[ { "key" :0 , "value" :0 } ] } ) ;
match case {
"authorization" = > {
let existing = test_db ::collection ( & conn , & org . uuid ) . await ;
payload [ "collections" ] . as_array_mut ( ) . unwrap ( ) . push ( json ! ( { "name" :"Existing" , "id" :existing . uuid } ) ) ;
}
"cipher" = > {
payload [ "ciphers" ] . as_array_mut ( ) . unwrap ( ) . push ( json ! ( { "name" :"Invalid" , "type" :99 , "encryptedFor" :user . uuid , "secureNote" :{ "type" :0 } } ) ) ;
payload [ "collectionRelationships" ] . as_array_mut ( ) . unwrap ( ) . push ( json ! ( { "key" :1 , "value" :0 } ) ) ;
}
"rollback" = > conn . run ( | c | c . batch_execute ( "CREATE TRIGGER reject_link BEFORE INSERT ON ciphers_collections BEGIN SELECT RAISE(ABORT,'test failure'); END" ) ) . await . unwrap ( ) ,
"index" = > payload [ "collectionRelationships" ] [ 0 ] [ "value" ] = json ! ( 1 ) ,
"export" = > payload [ "collectionRelationships" ] = json ! ( [ ] ) ,
_ = > { }
}
let user_id = user . uuid . clone ( ) ;
let headers = OrgMemberHeaders {
host : "http://localhost" . into ( ) ,
device : Device ::new ( "test" . to_owned ( ) . into ( ) , user_id . clone ( ) , "test" . into ( ) , 1 ) ,
user ,
membership ,
ip : crate ::auth ::ClientIp {
ip : "127.0.0.1" . parse ( ) . unwrap ( ) ,
} ,
} ;
let rocket = rocket ::build ( ) . manage ( Arc ::clone ( & WS_USERS ) ) ;
let notify = rocket . state ::< Arc < WebSocketUsers > > ( ) . unwrap ( ) ;
let result = post_org_import (
OrgIdData {
organization_id : org . uuid . clone ( ) ,
} ,
Json ( serde_json ::from_value ( payload ) . unwrap ( ) ) ,
headers ,
db . conn ( ) ,
notify . into ( ) ,
)
. await ;
conn . run ( | c | c . batch_execute ( "DROP TRIGGER IF EXISTS reject_link" ) ) . await . unwrap ( ) ;
let success = matches ! ( case , "owner" | "admin" | "custom" | "legacy" | "export" ) ;
assert_eq ! ( result . is_ok ( ) , success , "{case}" ) ;
assert_eq ! (
Collection ::find_by_organization ( & org . uuid , & conn ) . await . len ( ) ,
usize ::from ( success | | case = = "authorization" )
) ;
assert_eq ! ( Cipher ::find_by_org ( & org . uuid , & conn ) . await . len ( ) , usize ::from ( success ) ) ;
assert_eq ! (
CollectionUser ::find_by_user ( & user_id , & conn ) . await . len ( ) ,
usize ::from ( success & & role = = MembershipType ::Custom )
) ;
assert_eq ! (
Cipher ::get_collections_with_cipher_by_organization ( & org . uuid , & conn ) . await . len ( ) ,
usize ::from ( success & & case ! = "export" )
) ;
}
} ) ;
}
}
}
#[ derive(Deserialize) ]
#[ derive(Deserialize) ]
@ -1908,29 +2135,37 @@ struct BulkCollectionsData {
async fn post_bulk_collections ( data : Json < BulkCollectionsData > , headers : Headers , conn : DbConn ) -> EmptyResult {
async fn post_bulk_collections ( data : Json < BulkCollectionsData > , headers : Headers , conn : DbConn ) -> EmptyResult {
let data : BulkCollectionsData = data . into_inner ( ) ;
let data : BulkCollectionsData = data . into_inner ( ) ;
if Membership ::find_confirmed_by_user_and_org ( & headers . user . uuid , & data . organization_id , & conn ) . await . is_none ( ) {
let Some ( member ) =
Membership ::find_confirmed_by_user_and_org ( & headers . user . uuid , & data . organization_id , & conn ) . await
else {
err ! ( "You need to be a Member of the Organization to call this endpoint" )
err ! ( "You need to be a Member of the Organization to call this endpoint" )
}
} ;
// A member who may edit any collection may use every collection of the organization
let can_edit_any_collection = member . can_edit_any_collection ( ) ;
// Get all the collection available to the user in one query
// Get all the collection available to the user in one query
// Also filter based upon the provided collections
// Also filter based upon the provided collections
let user_collections : HashMap < CollectionId , Collection > =
let collections = if can_edit_any_collection {
Collection ::find_by_organization_and_user_uuid ( & data . organization_id , & headers . user . uuid , & conn )
Collection ::find_by_organization ( & data . organization_id , & conn ) . await
. await
} else {
. into_iter ( )
Collection ::find_by_organization_and_user_uuid ( & data . organization_id , & headers . user . uuid , & conn ) . await
. filter_map ( | c | {
} ;
if data . collection_ids . contains ( & c . uuid ) {
let user_collections : HashMap < CollectionId , Collection > = collections
Some ( ( c . uuid . clone ( ) , c ) )
. into_iter ( )
} else {
. filter_map ( | c | {
None
if data . collection_ids . contains ( & c . uuid ) {
}
Some ( ( c . uuid . clone ( ) , c ) )
} )
} else {
. collect ( ) ;
None
}
} )
. collect ( ) ;
// Verify if all the collections requested exists and are writable for the user, else abort
// Verify if all the collections requested exists and are writable for the user, else abort
for collection_uuid in & data . collection_ids {
for collection_uuid in & data . collection_ids {
match user_collections . get ( collection_uuid ) {
match user_collections . get ( collection_uuid ) {
Some ( collection ) if collection . is_writable_by_user ( & headers . user . uuid , & conn ) . await = > ( ) ,
Some ( collection )
if can_edit_any_collection | | collection . is_writable_by_user ( & headers . user . uuid , & conn ) . await = > { }
_ = > err_code ! ( "Resource not found" , "User does not have access to a collection" , 404 ) ,
_ = > err_code ! ( "Resource not found" , "User does not have access to a collection" , 404 ) ,
}
}
}
}
@ -1939,7 +2174,7 @@ async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers
// Only act on existing cipher uuid's
// Only act on existing cipher uuid's
// Do not abort the operation just ignore it, it could be a cipher was just deleted for example
// Do not abort the operation just ignore it, it could be a cipher was just deleted for example
if let Some ( cipher ) = Cipher ::find_by_uuid_and_org ( cipher_id , & data . organization_id , & conn ) . await
if let Some ( cipher ) = Cipher ::find_by_uuid_and_org ( cipher_id , & data . organization_id , & conn ) . await
& & cipher . is_write_accessible_to_user ( & headers . user . uuid , & conn ) . await
& & cipher . is_write_accessible_to_user ( & headers . user . uuid , CipherAccessScope ::OrganizationAdmin , & conn ) . await
{
{
// When selecting a specific collection from the left filter list, and use the bulk option, you can remove an item from that collection
// When selecting a specific collection from the left filter list, and use the bulk option, you can remove an item from that collection
// In these cases the client will call this endpoint twice, once for adding the new collections and a second for deleting.
// In these cases the client will call this endpoint twice, once for adding the new collections and a second for deleting.
@ -2480,6 +2715,14 @@ async fn restore_member_impl(
Ok ( ( ) )
Ok ( ( ) )
}
}
/// Whether a member may give others access to collections, and so needs to see the members and groups: by seeing
/// or creating any collection, or by the manage option on a collection.
async fn may_assign_collection_access ( member : & Membership , conn : & DbConn ) -> bool {
member . can_view_all_collections ( )
| | member . has_custom_permission ( CustomPermission ::CreateNewCollections )
| | Collection ::has_manageable_collection_by_user ( & member . org_uuid , & member . user_uuid , conn ) . await
}
async fn get_groups_data (
async fn get_groups_data (
details : bool ,
details : bool ,
org_id : OrganizationId ,
org_id : OrganizationId ,
@ -2493,14 +2736,15 @@ 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 manager of a collection (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 ( )
| | ( CONFIG . org_groups_enabled ( )
& & ! headers . membership . has_type ( MembershipType ::Custom )
& & GroupUser ::has_full_access_by_member ( & org_id , & headers . membership . uuid , & conn ) . await ) ;
& & 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
} else {
} else {
has_full_access
has_full_access | | may_assign_collection_access ( & headers . membership , & conn ) . await
| | Collection ::has_manageable_collection_by_user ( & org_id , & headers . membership . user_uuid , & conn ) . await
} ;
} ;
if ! allowed {
if ! allowed {
err_code ! ( "Resource not found." , "User does not have access" , Status ::NotFound . code ) ;
err_code ! ( "Resource not found." , "User does not have access" , Status ::NotFound . code ) ;
@ -2869,8 +3113,26 @@ struct OrganizationUserRecoverAccountRequest {
// But the clients do not seem to use this at all
// But the clients do not seem to use this at all
// Just add it here in case they will
// Just add it here in case they will
#[ get( " /organizations/<org_id>/public-key " ) ]
#[ get( " /organizations/<org_id>/public-key " ) ]
async fn get_organization_public_key ( org_id : OrganizationId , headers : OrgMemberHeaders , conn : DbConn ) -> JsonResult {
async fn get_organization_public_key (
if org_id ! = headers . membership . org_uuid {
org_id : OrganizationId ,
headers : Headers ,
member : Result < OrgMemberHeaders , & 'static str > ,
conn : DbConn ,
) -> JsonResult {
// SSO users without an org get the fake one, whose key the v2 JIT password flow fetches anyway
if org_id . eq_ignore_ascii_case ( FAKE_SSO_IDENTIFIER ) & & headers . user . private_key . is_none ( ) {
return Ok ( Json ( json ! ( {
"object" : "organizationPublicKey" ,
"publicKey" : fake_sso_org_public_key ( ) . await ? ,
} ) ) ) ;
}
let member = match member {
Ok ( member ) = > member ,
// The guard already logged it
Err ( e ) = > return Err ( crate ::error ::Error ::new_msg ( e ) . with_code ( Status ::Unauthorized . code ) ) ,
} ;
if org_id ! = member . membership . org_uuid {
err ! ( "Organization not found" , "Organization id's do not match" ) ;
err ! ( "Organization not found" , "Organization id's do not match" ) ;
}
}
let Some ( org ) = Organization ::find_by_uuid ( & org_id , & conn ) . await else {
let Some ( org ) = Organization ::find_by_uuid ( & org_id , & conn ) . await else {
@ -2883,11 +3145,30 @@ async fn get_organization_public_key(org_id: OrganizationId, headers: OrgMemberH
} ) ) )
} ) ) )
}
}
/// The SDK only uses this key to wrap an account recovery key that it never sends for the fake org,
/// so it is made once and its private half dropped.
async fn fake_sso_org_public_key ( ) -> ApiResult < String > {
static PUBLIC_KEY : std ::sync ::LazyLock < Option < String > > = std ::sync ::LazyLock ::new ( | | {
let der = openssl ::rsa ::Rsa ::generate ( 2048 ) . and_then ( | rsa | rsa . public_key_to_der ( ) ) . ok ( ) ? ;
Some ( data_encoding ::BASE64 . encode ( & der ) )
} ) ;
let Ok ( Some ( public_key ) ) = tokio ::task ::spawn_blocking ( | | PUBLIC_KEY . clone ( ) ) . await else {
err ! ( "Failed to generate the organization key" )
} ;
Ok ( public_key )
}
// Obsolete - Renamed to public-key (2023.8), left for backwards compatibility with older clients
// Obsolete - Renamed to public-key (2023.8), left for backwards compatibility with older clients
// https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Controllers/OrganizationsController.cs#L487-L492
// https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Controllers/OrganizationsController.cs#L487-L492
#[ get( " /organizations/<org_id>/keys " ) ]
#[ get( " /organizations/<org_id>/keys " ) ]
async fn get_organization_keys ( org_id : OrganizationId , headers : OrgMemberHeaders , conn : DbConn ) -> JsonResult {
async fn get_organization_keys (
get_organization_public_key ( org_id , headers , conn ) . await
org_id : OrganizationId ,
headers : Headers ,
member : Result < OrgMemberHeaders , & 'static str > ,
conn : DbConn ,
) -> JsonResult {
get_organization_public_key ( org_id , headers , member , conn ) . await
}
}
// Will allow to reset 2FA too
// Will allow to reset 2FA too