@ -29,7 +29,7 @@ use crate::{
} ,
} ,
mail ,
mail ,
sso ::FAKE_SSO_IDENTIFIER ,
sso ::FAKE_SSO_IDENTIFIER ,
util ::{ NumberOrString , convert_json_key_lcase_first } ,
util ::{ NumberOrString , convert_json_key_lcase_first , is_valid_enc_string } ,
} ;
} ;
use super ::accounts ::{ AuthenticationData , UnlockData , V2UpgradeTokenData } ;
use super ::accounts ::{ AuthenticationData , UnlockData , V2UpgradeTokenData } ;
@ -80,6 +80,7 @@ pub fn routes() -> Vec<Route> {
get_organization_public_key ,
get_organization_public_key ,
bulk_public_keys ,
bulk_public_keys ,
revoke_member ,
revoke_member ,
revoke_self ,
bulk_revoke_members ,
bulk_revoke_members ,
restore_member ,
restore_member ,
restore_member_vnext ,
restore_member_vnext ,
@ -130,7 +131,8 @@ struct OrganizationUpdateData {
#[ derive(Deserialize) ]
#[ derive(Deserialize) ]
#[ serde(rename_all = " camelCase " ) ]
#[ serde(rename_all = " camelCase " ) ]
struct FullCollectionData {
struct FullCollectionData {
name : String ,
// Optional on updates only: the clients send none for a former My Items collection, like upstream
name : Option < String > ,
groups : Vec < CollectionGroupData > ,
groups : Vec < CollectionGroupData > ,
users : Vec < CollectionMembershipData > ,
users : Vec < CollectionMembershipData > ,
external_id : Option < String > ,
external_id : Option < String > ,
@ -443,7 +445,10 @@ async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHea
. collect ( ) ;
. collect ( ) ;
let mut data = Vec ::new ( ) ;
let mut data = Vec ::new ( ) ;
for col in Collection ::find_by_organization ( & org_id , & conn ) . await {
// Like upstream, the members' My Items collections are not managed here
for col in
Collection ::find_by_organization ( & org_id , & conn ) . await . into_iter ( ) . filter ( | c | ! c . is_default_user_collection ( ) )
{
// check whether the current user has access to the given collection
// check whether the current user has access to the given collection
let assigned = has_full_access_to_org
let assigned = has_full_access_to_org
| | CollectionUser ::has_access_to_collection_by_user ( & col . uuid , & member . user_uuid , & conn ) . await
| | CollectionUser ::has_access_to_collection_by_user ( & col . uuid , & member . user_uuid , & conn ) . await
@ -499,8 +504,14 @@ async fn get_org_collections_details(org_id: OrganizationId, headers: ManagerHea
} ) ) )
} ) ) )
}
}
// The shared collections only, like upstream
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 ( )
. filter ( | c | ! c . is_default_user_collection ( ) )
. map ( Collection ::to_json )
. collect ::< Value > ( )
}
}
#[ post( " /organizations/<org_id>/collections " , data = " <data> " ) ]
#[ post( " /organizations/<org_id>/collections " , data = " <data> " ) ]
@ -523,7 +534,10 @@ async fn post_organization_collections(
err ! ( "You don't have permission to create collections" )
err ! ( "You don't have permission to create collections" )
}
}
let collection = Collection ::new ( org_id . clone ( ) , data . name , data . external_id ) ;
let Some ( name ) = data . name else {
err ! ( "The Name field is required." )
} ;
let collection = Collection ::new ( org_id . clone ( ) , name , data . external_id ) ;
collection . save ( & conn ) . await ? ;
collection . save ( & conn ) . await ? ;
log_event (
log_event (
@ -619,6 +633,10 @@ async fn post_bulk_access_collections(
)
)
}
}
if collection . is_default_user_collection ( ) {
err ! ( "You cannot add access to collections with the type as DefaultUserCollection." )
}
collections . push ( collection ) ;
collections . push ( collection ) ;
}
}
@ -693,7 +711,16 @@ async fn put_organization_collection_update(
err ! ( "Collection not found" )
err ! ( "Collection not found" )
} ;
} ;
collection . name = data . name ;
if collection . is_default_user_collection ( ) {
err ! ( "You cannot edit a collection with the type as DefaultUserCollection." )
}
// A former My Items collection is shown by its former owner's email address, its name stays as it is
if collection . default_user_collection_email . is_none ( )
& & let Some ( name ) = data . name . filter ( | n | ! n . trim ( ) . is_empty ( ) )
{
collection . name = name ;
}
collection . external_id = match data . external_id {
collection . external_id = match data . external_id {
Some ( external_id ) if ! external_id . trim ( ) . is_empty ( ) = > Some ( external_id ) ,
Some ( external_id ) if ! external_id . trim ( ) . is_empty ( ) = > Some ( external_id ) ,
_ = > None ,
_ = > None ,
@ -750,6 +777,9 @@ async fn delete_organization_collection_impl(
let Some ( collection ) = Collection ::find_by_uuid_and_org ( col_id , org_id , conn ) . await else {
let Some ( collection ) = Collection ::find_by_uuid_and_org ( col_id , org_id , conn ) . await else {
err ! ( "Collection not found" , "Collection does not exist or does not belong to this organization" )
err ! ( "Collection not found" , "Collection does not exist or does not belong to this organization" )
} ;
} ;
if collection . is_default_user_collection ( ) {
err ! ( "You cannot delete a collection with the type as DefaultUserCollection." )
}
log_event (
log_event (
EventType ::CollectionDeleted ,
EventType ::CollectionDeleted ,
& collection . uuid ,
& collection . uuid ,
@ -795,6 +825,16 @@ async fn bulk_delete_organization_collections(
let headers = CollectionDeleteHeaders ::from_loose ( headers , & collections , & conn ) . await ? ;
let headers = CollectionDeleteHeaders ::from_loose ( headers , & collections , & conn ) . await ? ;
// Like upstream, reject them all before deleting any
for col_id in & collections {
if Collection ::find_by_uuid_and_org ( col_id , & org_id , & conn )
. await
. is_some_and ( | c | c . is_default_user_collection ( ) )
{
err ! ( "You cannot delete collections with the type as DefaultUserCollection." )
}
}
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 ? ;
}
}
@ -905,18 +945,29 @@ struct OrgIdData {
organization_id : OrganizationId ,
organization_id : OrganizationId ,
}
}
#[ derive(FromForm) ]
struct OrgDetailsData {
#[ field(name = " organizationId " ) ]
organization_id : OrganizationId ,
// Set by the organization reports, which also cover the members' My Items
#[ field(name = " includeMemberItems " , default = false) ]
include_member_items : bool ,
}
#[ get( " /ciphers/organization-details?<data..> " ) ]
#[ get( " /ciphers/organization-details?<data..> " ) ]
async fn get_org_details ( data : OrgIdData , headers : ManagerHeadersLoose , conn : DbConn ) -> JsonResult {
async fn get_org_details ( data : OrgDetails Data , headers : ManagerHeadersLoose , conn : DbConn ) -> JsonResult {
if data . organization_id ! = headers . membership . org_uuid {
if data . organization_id ! = headers . membership . org_uuid {
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 ) ;
}
}
// The organization-wide cipher authority upstream requires, which also lets the reports include the members' My
// Items
if ! headers . membership . can_list_all_ciphers ( ) {
if ! headers . membership . can_list_all_ciphers ( ) {
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_details_impl ( & data . organization_id , & headers . host , & headers . user . uuid , & conn ) . await ? ,
"data" : get_org_details_impl ( & data . organization_id , & headers . host , & headers . user . uuid , data . include_member_items , & conn ) . await ? ,
"object" : "list" ,
"object" : "list" ,
"continuationToken" : null ,
"continuationToken" : null ,
} ) ) )
} ) ) )
@ -926,11 +977,19 @@ async fn get_org_details_impl(
org_id : & OrganizationId ,
org_id : & OrganizationId ,
host : & str ,
host : & str ,
user_id : & UserId ,
user_id : & UserId ,
include_member_items : bool ,
conn : & DbConn ,
conn : & DbConn ,
) -> Result < Value , crate ::Error > {
) -> Result < Value , crate ::Error > {
let ciphers = Cipher ::find_by_org ( org_id , conn ) . await ;
let mut ciphers = Cipher ::find_by_org ( org_id , conn ) . await ;
if ! include_member_items {
// Like upstream, leave out the items that are only in the members' My Items collections
let my_items_only = CollectionCipher ::find_my_items_only_by_orgs ( vec ! [ org_id . clone ( ) ] , conn ) . await ;
ciphers . retain ( | c | ! my_items_only . contains ( & c . uuid ) ) ;
}
let my_items = CollectionCipher ::find_my_items_by_org ( org_id , conn ) . await ;
let mut 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
// Every cipher of the organization is listed, so list every collection of them too. The My Items ones are
// sorted out below.
cipher_sync_data . cipher_collections = HashMap ::new ( ) ;
cipher_sync_data . cipher_collections = HashMap ::new ( ) ;
for ( cipher_id , collection_id ) in Cipher ::get_collections_with_cipher_by_organization ( org_id , conn ) . await {
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 ) ;
cipher_sync_data . cipher_collections . entry ( cipher_id ) . or_default ( ) . push ( collection_id ) ;
@ -938,7 +997,18 @@ async fn get_org_details_impl(
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 {
ciphers_json . push ( c . to_json ( host , user_id , Some ( & cipher_sync_data ) , CipherSyncType ::Organization , conn ) . await ? ) ;
let mut details = c . to_json ( host , user_id , Some ( & cipher_sync_data ) , CipherSyncType ::Organization , conn ) . await ? ;
// Like upstream, the members' items list all their collections, including the My Items ones, and the
// organization's items none of those
if let Some ( cipher_my_items ) = my_items . get ( & c . uuid )
& & let Some ( collection_ids ) = details [ "collectionIds" ] . as_array_mut ( )
{
collection_ids . retain ( | id | id . as_str ( ) . is_none_or ( | id | ! cipher_my_items . iter ( ) . any ( | c | c . as_ref ( ) = = id ) ) ) ;
if include_member_items {
collection_ids . extend ( cipher_my_items . iter ( ) . map ( | c | json ! ( c ) ) ) ;
}
}
ciphers_json . push ( details ) ;
}
}
Ok ( json ! ( ciphers_json ) )
Ok ( json ! ( ciphers_json ) )
}
}
@ -1089,8 +1159,10 @@ struct InviteData {
impl InviteData {
impl InviteData {
async fn validate ( & self , org_id : & OrganizationId , conn : & DbConn ) -> EmptyResult {
async fn validate ( & self , org_id : & OrganizationId , conn : & DbConn ) -> EmptyResult {
// A My Items collection can't be assigned, it fails like a collection of another organization, like upstream
let org_collections = Collection ::find_by_organization ( org_id , conn ) . await ;
let org_collections = Collection ::find_by_organization ( org_id , conn ) . await ;
let org_collection_ids : HashSet < & CollectionId > = org_collections . iter ( ) . map ( | c | & c . uuid ) . collect ( ) ;
let org_collection_ids : HashSet < & CollectionId > =
org_collections . iter ( ) . filter ( | c | ! c . is_default_user_collection ( ) ) . map ( | c | & c . uuid ) . collect ( ) ;
if let Some ( e ) = self . collections . iter ( ) . flatten ( ) . find ( | c | ! org_collection_ids . contains ( & c . id ) ) {
if let Some ( e ) = self . collections . iter ( ) . flatten ( ) . find ( | c | ! org_collection_ids . contains ( & c . id ) ) {
err ! (
err ! (
"Invalid collection" ,
"Invalid collection" ,
@ -1486,12 +1558,30 @@ async fn accept_invite(
struct ConfirmData {
struct ConfirmData {
id : Option < MembershipId > ,
id : Option < MembershipId > ,
key : Option < String > ,
key : Option < String > ,
// The encrypted name of the member's My Items collection, sent by the clients whenever they confirm or restore
// a member, and when they demote one from Owner or Admin
default_user_collection_name : Option < String > ,
}
}
#[ derive(Deserialize) ]
#[ derive(Deserialize) ]
#[ serde(rename_all = " camelCase " ) ]
#[ serde(rename_all = " camelCase " ) ]
struct BulkConfirmData {
struct BulkConfirmData {
keys : Option < Vec < ConfirmData > > ,
keys : Option < Vec < ConfirmData > > ,
default_user_collection_name : Option < String > ,
}
/// Like upstream's `[EncryptedString]` and `[EncryptedStringLength(1000)]`, the name of a My Items collection has to
/// be an encrypted string: the collection can't be renamed afterwards.
fn check_default_user_collection_name ( name : Option < & str > ) -> EmptyResult {
if let Some ( name ) = name {
if name . len ( ) > 1000 {
err ! ( "The field DefaultUserCollectionName exceeds the maximum encrypted value length of 1000 characters." )
}
if ! is_valid_enc_string ( name ) {
err ! ( "DefaultUserCollectionName is not a valid encrypted string." )
}
}
Ok ( ( ) )
}
}
#[ post( " /organizations/<org_id>/users/confirm " , data = " <data> " ) ]
#[ post( " /organizations/<org_id>/users/confirm " , data = " <data> " ) ]
@ -1506,6 +1596,7 @@ async fn bulk_confirm_invite(
err ! ( "Organization not found" , "Organization id's do not match" ) ;
err ! ( "Organization not found" , "Organization id's do not match" ) ;
}
}
let data = data . into_inner ( ) ;
let data = data . into_inner ( ) ;
check_default_user_collection_name ( data . default_user_collection_name . as_deref ( ) ) ? ;
let mut bulk_response = Vec ::new ( ) ;
let mut bulk_response = Vec ::new ( ) ;
match data . keys {
match data . keys {
@ -1515,7 +1606,11 @@ async fn bulk_confirm_invite(
err ! ( "Member id is required" )
err ! ( "Member id is required" )
} ;
} ;
let user_key = invite . key . unwrap_or_default ( ) ;
let user_key = invite . key . unwrap_or_default ( ) ;
let err_msg = match confirm_invite_impl ( & org_id , & member_id , & user_key , & headers , & conn , & nt ) . await {
let collection_name = data . default_user_collection_name . as_deref ( ) ;
let err_msg =
match confirm_invite_impl ( & org_id , & member_id , & user_key , collection_name , & headers , & conn , & nt )
. await
{
Ok ( ( ) ) = > String ::new ( ) ,
Ok ( ( ) ) = > String ::new ( ) ,
Err ( e ) = > {
Err ( e ) = > {
warn ! ( "Unable to confirm member {}: {e:?}" , member_id . escape_debug ( ) ) ;
warn ! ( "Unable to confirm member {}: {e:?}" , member_id . escape_debug ( ) ) ;
@ -1552,14 +1647,25 @@ async fn confirm_invite(
nt : Notify < '_ > ,
nt : Notify < '_ > ,
) -> EmptyResult {
) -> EmptyResult {
let data = data . into_inner ( ) ;
let data = data . into_inner ( ) ;
check_default_user_collection_name ( data . default_user_collection_name . as_deref ( ) ) ? ;
let user_key = data . key . unwrap_or_default ( ) ;
let user_key = data . key . unwrap_or_default ( ) ;
confirm_invite_impl ( & org_id , & member_id , & user_key , & headers , & conn , & nt ) . await
confirm_invite_impl (
& org_id ,
& member_id ,
& user_key ,
data . default_user_collection_name . as_deref ( ) ,
& headers ,
& conn ,
& nt ,
)
. await
}
}
async fn confirm_invite_impl (
async fn confirm_invite_impl (
org_id : & OrganizationId ,
org_id : & OrganizationId ,
member_id : & MembershipId ,
member_id : & MembershipId ,
key : & str ,
key : & str ,
default_collection_name : Option < & str > ,
headers : & ManageUsersHeaders ,
headers : & ManageUsersHeaders ,
conn : & DbConn ,
conn : & DbConn ,
nt : & Notify < '_ > ,
nt : & Notify < '_ > ,
@ -1612,13 +1718,18 @@ async fn confirm_invite_impl(
mail ::send_invite_confirmed ( & address , & org_name ) . await ? ;
mail ::send_invite_confirmed ( & address , & org_name ) . await ? ;
}
}
let save_result = member_to_confirm . save ( conn ) . await ;
let mut result = member_to_confirm . save ( conn ) . await ;
// Only once the membership is stored as confirmed, like upstream: a concurrent policy update then either
// finds this member confirmed or this check finds the policy enabled, so the member always gets one.
if result . is_ok ( ) {
result = Collection ::create_default_user_collection ( & member_to_confirm , default_collection_name , conn ) . await ;
}
if let Some ( user ) = User ::find_by_uuid ( & member_to_confirm . user_uuid , conn ) . await {
if let Some ( user ) = User ::find_by_uuid ( & member_to_confirm . user_uuid , conn ) . await {
nt . send_user_update ( UpdateType ::SyncOrgKeys , & user , headers . device . push_uuid . as_ref ( ) , conn ) . await ;
nt . send_user_update ( UpdateType ::SyncOrgKeys , & user , headers . device . push_uuid . as_ref ( ) , conn ) . await ;
}
}
save_ result
result
}
}
#[ get( " /organizations/<org_id>/users/mini-details " , rank = 1) ]
#[ get( " /organizations/<org_id>/users/mini-details " , rank = 1) ]
@ -1677,6 +1788,7 @@ struct EditUserData {
groups : Option < Vec < GroupId > > ,
groups : Option < Vec < GroupId > > ,
#[ serde(default) ]
#[ serde(default) ]
permissions : HashMap < String , Value > ,
permissions : HashMap < String , Value > ,
default_user_collection_name : Option < String > ,
}
}
#[ put( " /organizations/<org_id>/users/<member_id> " , data = " <data> " , rank = 1) ]
#[ put( " /organizations/<org_id>/users/<member_id> " , data = " <data> " , rank = 1) ]
@ -1691,6 +1803,7 @@ async fn edit_member(
err ! ( "Organization not found" , "Organization id's do not match" ) ;
err ! ( "Organization not found" , "Organization id's do not match" ) ;
}
}
let data : EditUserData = data . into_inner ( ) ;
let data : EditUserData = data . into_inner ( ) ;
check_default_user_collection_name ( data . default_user_collection_name . as_deref ( ) ) ? ;
// HACK: We need the raw user-type to be sure custom role is selected to determine the access_all permission
// HACK: We need the raw user-type to be sure custom role is selected to determine the access_all permission
// Unless Custom roles are enabled, a custom role (4) is converted to a manager role (3)
// Unless Custom roles are enabled, a custom role (4) is converted to a manager role (3)
@ -1741,10 +1854,21 @@ async fn edit_member(
}
}
}
}
// Like upstream, the posted access leaves out My Items collections, before it is authorized: they are no member's
// to give. The member keeps their own one, see below.
let org_collections : HashMap < CollectionId , Collection > =
Collection ::find_by_organization ( & org_id , & conn ) . await . into_iter ( ) . map ( | c | ( c . uuid . clone ( ) , c ) ) . collect ( ) ;
let posted_collections : Vec < & CollectionData > = data
. collections
. iter ( )
. flatten ( )
. filter ( | col | ! org_collections . get ( & col . id ) . is_some_and ( Collection ::is_default_user_collection ) )
. collect ( ) ;
// A Custom member with Manage users only gives what they have themselves. Manage users authorizes member access
// A Custom member with Manage users only gives what they have themselves. Manage users authorizes member access
// to every collection in this organization.
// to every collection in this organization.
if headers . membership_type = = MembershipType ::Custom {
if headers . membership_type = = MembershipType ::Custom {
let collections : Vec < & CollectionId > = data . collections . iter ( ) . flatten ( ) . map ( | c | & c . id ) . collect ( ) ;
let collections : Vec < & CollectionId > = posted_ collections. iter ( ) . map ( | c | & c . id ) . collect ( ) ;
let groups = data . groups . iter ( ) . flatten ( ) . cloned ( ) . collect ( ) ;
let groups = data . groups . iter ( ) . flatten ( ) . cloned ( ) . collect ( ) ;
check_custom_member_grants (
check_custom_member_grants (
& headers . membership ,
& headers . membership ,
@ -1756,6 +1880,8 @@ async fn edit_member(
. await ? ;
. await ? ;
}
}
// Upstream creates the My Items collection of a member demoted from Owner or Admin
let demoted = member_to_edit . atype > = MembershipType ::Admin & & new_type < MembershipType ::Admin ;
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 . as_ref ( ) . filter ( | _ | new_type = = MembershipType ::Custom ) {
if let Some ( permissions ) = custom_permissions . as_ref ( ) . filter ( | _ | new_type = = MembershipType ::Custom ) {
@ -1766,15 +1892,13 @@ async fn edit_member(
// We need to perform the check after changing the type since `admin` is exempt.
// We need to perform the check after changing the type since `admin` is exempt.
OrgPolicy ::check_user_allowed ( & member_to_edit , "modify" , & conn ) . await ? ;
OrgPolicy ::check_user_allowed ( & member_to_edit , "modify" , & conn ) . await ? ;
// Replace the member's direct collection assignments with those in the request.
// Delete all the odd collections, but keep the member's My Items
for c in CollectionUser ::find_by_organization_and_user_uuid ( & org_id , & member_to_edit . user_uuid , & conn ) . await {
CollectionUser ::delete_all_but_my_items_by_user_and_org ( & member_to_edit . user_uuid , & org_id , & conn ) . await ? ;
c . delete ( & conn ) . await ? ;
}
// If no accessAll, add the collections received
// If no accessAll, add the collections received
if ! access_all {
if ! access_all {
for col in data . collections . iter ( ) . flatten ( ) {
for col in posted_collections {
match Collection ::find_by_uuid_and_org ( & col . id , & org_id , & conn ) . await {
match org_collections . get ( & col . id ) {
None = > err ! ( "Collection not found in Organization" ) ,
None = > err ! ( "Collection not found in Organization" ) ,
Some ( collection ) = > {
Some ( collection ) = > {
CollectionUser ::save (
CollectionUser ::save (
@ -1812,7 +1936,17 @@ async fn edit_member(
)
)
. await ;
. await ;
member_to_edit . save ( & conn ) . await
member_to_edit . save ( & conn ) . await ? ;
// Only once the demotion is stored, like upstream, see `confirm_invite_impl()`
if demoted {
Collection ::create_default_user_collection (
& member_to_edit ,
data . default_user_collection_name . as_deref ( ) ,
& conn ,
)
. await ? ;
}
Ok ( ( ) )
}
}
#[ delete( " /organizations/<org_id>/users " , data = " <data> " ) ]
#[ delete( " /organizations/<org_id>/users " , data = " <data> " ) ]
@ -1961,7 +2095,8 @@ async fn bulk_public_keys(
}
}
use super ::ciphers ::CipherData ;
use super ::ciphers ::CipherData ;
use super ::ciphers ::update_cipher_from_data ;
use super ::ciphers ::{ import_folders , update_cipher_from_data } ;
use super ::folders ::FolderData ;
// The import endpoint only ever uses the name/id/external_id of a collection.
// The import endpoint only ever uses the name/id/external_id of a collection.
// Bitwarden's own server ignores `groups`/`users` here too, so do not make them
// Bitwarden's own server ignores `groups`/`users` here too, so do not make them
@ -1980,6 +2115,11 @@ struct ImportData {
ciphers : Vec < CipherData > ,
ciphers : Vec < CipherData > ,
collections : Vec < ImportCollectionData > ,
collections : Vec < ImportCollectionData > ,
collection_relationships : Vec < RelationsData > ,
collection_relationships : Vec < RelationsData > ,
// The clients keep the folders of an import into My Items
#[ serde(default) ]
folders : Vec < FolderData > ,
#[ serde(default) ]
folder_relationships : Vec < RelationsData > ,
}
}
#[ derive(Deserialize) ]
#[ derive(Deserialize) ]
@ -2029,6 +2169,9 @@ 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 ) ) {
// Like upstream's `ImportCiphers` authorization, also for a My Items collection: Owners, Admins and
// members who may edit any collection may import into it, others only into one they may manage or
// write to, which for a My Items collection is only its owner
if membership . atype < MembershipType ::Admin & & ! membership . can_edit_any_collection ( ) {
if membership . atype < MembershipType ::Admin & & ! membership . can_edit_any_collection ( ) {
let can_import = if let Some ( manageable ) = & manageable {
let can_import = if let Some ( manageable ) = & manageable {
manageable . contains ( & collection . uuid )
manageable . contains ( & collection . uuid )
@ -2081,6 +2224,8 @@ async fn post_org_import(
let ImportData {
let ImportData {
ciphers : imported_ciphers ,
ciphers : imported_ciphers ,
collections : imported_collections ,
collections : imported_collections ,
folders : imported_folders ,
folder_relationships ,
. .
. .
} = data ;
} = data ;
let grant_new_collection_manage = headers . membership . has_type ( MembershipType ::Custom ) ;
let grant_new_collection_manage = headers . membership . has_type ( MembershipType ::Custom ) ;
@ -2119,12 +2264,17 @@ async fn post_org_import(
collections . push ( collection_uuid ) ;
collections . push ( collection_uuid ) ;
}
}
// The clients keep the folders of an import into My Items
let folder_relations = folder_relationships . into_iter ( ) . map ( | r | ( r . key , r . value ) ) ;
let cipher_folders = import_folders ( imported_folders , folder_relations , & headers . user . uuid , & conn ) . await ? ;
let mut assigned = vec ! [ Vec ::< CollectionId > ::new ( ) ; imported_ciphers . len ( ) ] ;
let mut assigned = vec ! [ Vec ::< CollectionId > ::new ( ) ; imported_ciphers . len ( ) ] ;
for ( cipher_index , collection_index ) in relations {
for ( cipher_index , collection_index ) in relations {
assigned [ cipher_index ] . push ( collections [ collection_index ] . clone ( ) ) ;
assigned [ cipher_index ] . push ( collections [ collection_index ] . clone ( ) ) ;
}
}
for ( mut cipher_data , collection_ids ) in imported_ciphers . into_iter ( ) . zip ( assigned ) {
for ( index , ( mut cipher_data , collection_ids ) ) in imported_ciphers . into_iter ( ) . zip ( assigned ) . enumerate ( ) {
cipher_data . folder_id = None ;
// Only the folder relationships of the import set a folder, never the client-provided folderId
cipher_data . folder_id = cipher_folders . get ( & index ) . cloned ( ) ;
// The authenticated membership, rather than the imported file, selects the organization.
// The authenticated membership, rather than the imported file, selects the organization.
cipher_data . organization_id = Some ( org_id . clone ( ) ) ;
cipher_data . organization_id = Some ( org_id . clone ( ) ) ;
let mut cipher = Cipher ::new ( cipher_data . r#type ) ;
let mut cipher = Cipher ::new ( cipher_data . r#type ) ;
@ -2279,6 +2429,8 @@ async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers
} ;
} ;
let user_collections : HashMap < CollectionId , Collection > = collections
let user_collections : HashMap < CollectionId , Collection > = collections
. into_iter ( )
. into_iter ( )
// Like upstream, never another member's My Items collection, not even for those who may edit any collection
. filter ( | c | c . default_user_uuid . as_ref ( ) . is_none_or ( | owner | owner = = & headers . user . uuid ) )
. filter_map ( | c | {
. filter_map ( | c | {
if data . collection_ids . contains ( & c . uuid ) {
if data . collection_ids . contains ( & c . uuid ) {
Some ( ( c . uuid . clone ( ) , c ) )
Some ( ( c . uuid . clone ( ) , c ) )
@ -2297,12 +2449,39 @@ async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers
}
}
}
}
let mut ciphers = Vec ::with_capacity ( data . cipher_ids . len ( ) ) ;
for cipher_id in & data . cipher_ids {
for cipher_id in & data . cipher_ids {
// 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 , CipherAccessScope ::OrganizationAdmin , & conn ) . await
& & cipher . is_write_accessible_to_user ( & headers . user . uuid , CipherAccessScope ::OrganizationAdmin , & conn ) . await
{
{
// Upstream rejects sharing an item held only in somebody else's My Items,
// even when all destination collections are ordinary shared collections.
if ! data . remove_collections
& & CollectionCipher ::find_my_items_owners_if_only ( & cipher . uuid , & conn )
. await
. is_some_and ( | owners | owners . iter ( ) . any ( | owner | owner ! = & headers . user . uuid ) )
{
err_code ! ( "Resource not found" , "Cannot share another member's My Items" , 404 )
}
ciphers . push ( cipher ) ;
}
}
// Only the user's own My Items collection can be among them, check all ciphers before changing any
let my_items =
user_collections . values ( ) . find ( | c | c . is_default_user_collection ( ) ) . filter ( | _ | ! data . remove_collections ) ;
if let Some ( my_items ) = my_items {
for cipher in & ciphers {
my_items . check_cipher_assignment (
& HashSet ::from_iter ( cipher . get_accessible_collections ( headers . user . uuid . clone ( ) , & conn ) . await ) ,
& CollectionCipher ::find_my_items_of_cipher ( & cipher . uuid , & conn ) . await ,
) ? ;
}
}
for cipher in ciphers {
// 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.
if data . remove_collections {
if data . remove_collections {
@ -2310,12 +2489,16 @@ async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers
CollectionCipher ::delete ( & cipher . uuid , collection , & conn ) . await ? ;
CollectionCipher ::delete ( & cipher . uuid , collection , & conn ) . await ? ;
}
}
} else {
} else {
// Moved into My Items, an unassigned cipher is taken away from the members with organization-wide access,
// so they sync as well
if my_items . is_some ( ) {
cipher . update_users_revision ( & conn ) . await ;
}
for collection in & data . collection_ids {
for collection in & data . collection_ids {
CollectionCipher ::save ( & cipher . uuid , collection , & conn ) . await ? ;
CollectionCipher ::save ( & cipher . uuid , collection , & conn ) . await ? ;
}
}
}
}
}
}
}
Ok ( ( ) )
Ok ( ( ) )
}
}
@ -2413,10 +2596,14 @@ struct PolicyData {
#[ derive(Deserialize) ]
#[ derive(Deserialize) ]
struct PutPolicy {
struct PutPolicy {
policy : PolicyData ,
policy : PolicyData ,
// Ignore metadata for now as we do not yet support this
metadata : Option < PolicyMetadata > ,
// "metadata": {
}
// "defaultUserCollectionName": "2.xx|xx==|xx="
// }
#[ derive(Deserialize) ]
#[ serde(rename_all = " camelCase " ) ]
struct PolicyMetadata {
// Sent with the organization data ownership policy, see `ConfirmData`
default_user_collection_name : Option < String > ,
}
}
#[ put( " /organizations/<org_id>/policies/<pol_type> " , data = " <data> " ) ]
#[ put( " /organizations/<org_id>/policies/<pol_type> " , data = " <data> " ) ]
@ -2430,11 +2617,17 @@ async fn put_policy(
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" ) ;
}
}
let data : PolicyData = data . into_inner ( ) . policy ;
let PutPolicy {
policy : data ,
metadata ,
} = data . into_inner ( ) ;
let Some ( pol_type_enum ) = OrgPolicyType ::from_i32 ( pol_type ) else {
let Some ( pol_type_enum ) = OrgPolicyType ::from_i32 ( pol_type ) else {
err ! ( "Invalid or unsupported policy type" )
err ! ( "Invalid or unsupported policy type" )
} ;
} ;
if pol_type_enum = = OrgPolicyType ::PersonalOwnership {
check_default_user_collection_name ( metadata . as_ref ( ) . and_then ( | m | m . default_user_collection_name . as_deref ( ) ) ) ? ;
}
let current_policy = OrgPolicy ::find_by_org_and_type ( & org_id , pol_type_enum , & conn ) . await ;
let current_policy = OrgPolicy ::find_by_org_and_type ( & org_id , pol_type_enum , & conn ) . await ;
let is_currently_enabled = current_policy . as_ref ( ) . is_some_and ( | policy | policy . enabled ) ;
let is_currently_enabled = current_policy . as_ref ( ) . is_some_and ( | policy | policy . enabled ) ;
@ -2548,6 +2741,8 @@ async fn put_policy(
None = > OrgPolicy ::new ( org_id . clone ( ) , pol_type_enum , false , "{}" . to_owned ( ) ) ,
None = > OrgPolicy ::new ( org_id . clone ( ) , pol_type_enum , false , "{}" . to_owned ( ) ) ,
} ;
} ;
// Bitwarden provisions default collections on first enable or re-enable, not on ordinary updates.
let policy_becomes_enabled = data . enabled & & ! policy . enabled ;
policy . enabled = data . enabled ;
policy . enabled = data . enabled ;
policy . data = serde_json ::to_string ( & data . data ) ? ;
policy . data = serde_json ::to_string ( & data . data ) ? ;
policy . save ( & conn ) . await ? ;
policy . save ( & conn ) . await ? ;
@ -2563,6 +2758,15 @@ async fn put_policy(
)
)
. await ;
. await ;
// Like upstream, provision on first enable or re-enable, after the policy has been saved.
// A subsequent ordinary policy update must not create new My Items collections.
if pol_type_enum = = OrgPolicyType ::PersonalOwnership & & policy_becomes_enabled {
let collection_name = metadata . as_ref ( ) . and_then ( | m | m . default_user_collection_name . as_deref ( ) ) ;
// `create_default_user_collections()` only provisions the confirmed members the policy applies to
let members = Membership ::find_by_org ( & org_id , & conn ) . await ;
Collection ::create_default_user_collections ( & members , collection_name , & conn ) . await ? ;
}
Ok ( Json ( policy . to_json ( ) ) )
Ok ( Json ( policy . to_json ( ) ) )
}
}
@ -2669,6 +2873,39 @@ async fn revoke_member(
revoke_member_impl ( & org_id , & member_id , & headers , & conn ) . await
revoke_member_impl ( & org_id , & member_id , & headers , & conn ) . await
}
}
// Called by the clients when a member declines to transfer their personal items into their My Items collection,
// as the organization data ownership policy asks of them.
#[ put( " /organizations/<org_id>/users/revoke-self " ) ]
async fn revoke_self ( org_id : OrganizationId , headers : OrgMemberHeaders , conn : DbConn , nt : Notify < '_ > ) -> EmptyResult {
if org_id ! = headers . membership . org_uuid {
err ! ( "Organization not found" , "Organization id's do not match" ) ;
}
let mut member = headers . membership ;
if ! OrgPolicy ::is_personal_ownership_enforced_for ( & member , & conn ) . await {
err ! (
"User is not eligible for self-revocation. The organization data ownership policy must be enabled and the user must be a confirmed member."
)
}
member . revoke ( ) ;
member . save ( & conn ) . await ? ;
log_event (
EventType ::OrganizationUserSelfRevoked ,
& member . uuid ,
& org_id ,
& headers . user . uuid ,
headers . device . atype ,
& headers . ip . ip ,
& conn ,
)
. await ;
nt . send_user_update ( UpdateType ::SyncOrgKeys , & headers . user , headers . device . push_uuid . as_ref ( ) , & conn ) . await ;
Ok ( ( ) )
}
#[ put( " /organizations/<org_id>/users/revoke " , data = " <data> " ) ]
#[ put( " /organizations/<org_id>/users/revoke " , data = " <data> " ) ]
async fn bulk_revoke_members (
async fn bulk_revoke_members (
org_id : OrganizationId ,
org_id : OrganizationId ,
@ -2758,16 +2995,23 @@ async fn revoke_member_impl(
Ok ( ( ) )
Ok ( ( ) )
}
}
#[ put( " /organizations/<org_id>/users/<member_id>/restore/vnext " ) ]
#[ derive(Deserialize) ]
#[ serde(rename_all = " camelCase " ) ]
struct RestoreMemberData {
default_user_collection_name : Option < String > ,
}
#[ put( " /organizations/<org_id>/users/<member_id>/restore/vnext " , data = " <data> " ) ]
async fn restore_member_vnext (
async fn restore_member_vnext (
org_id : OrganizationId ,
org_id : OrganizationId ,
member_id : MembershipId ,
member_id : MembershipId ,
data : Json < RestoreMemberData > ,
headers : ManageUsersHeaders ,
headers : ManageUsersHeaders ,
conn : DbConn ,
conn : DbConn ,
) -> EmptyResult {
) -> EmptyResult {
// Vaultwarden does not (yet) support the per User Collection linked to the `Enforce organization data ownership` policy.
let collection_name = data . into_inner ( ) . default_user_collection_name ;
// Therefor we ignore the `defaultUserCollectionName` data sent and just call restore_member
check_default_user_collection_name ( collection_name . as_deref ( ) ) ? ;
restore_member_impl ( & org_id , & member_id , & headers , & conn ) . await
restore_member_impl ( & org_id , & member_id , collection_name . as_deref ( ) , & headers , & conn ) . await
}
}
#[ put( " /organizations/<org_id>/users/<member_id>/restore " ) ]
#[ put( " /organizations/<org_id>/users/<member_id>/restore " ) ]
@ -2777,13 +3021,20 @@ async fn restore_member(
headers : ManageUsersHeaders ,
headers : ManageUsersHeaders ,
conn : DbConn ,
conn : DbConn ,
) -> EmptyResult {
) -> EmptyResult {
restore_member_impl ( & org_id , & member_id , & headers , & conn ) . await
restore_member_impl ( & org_id , & member_id , None , & headers , & conn ) . await
}
#[ derive(Deserialize) ]
#[ serde(rename_all = " camelCase " ) ]
struct BulkRestoreMemberData {
ids : Vec < MembershipId > ,
default_user_collection_name : Option < String > ,
}
}
#[ put( " /organizations/<org_id>/users/restore " , data = " <data> " ) ]
#[ put( " /organizations/<org_id>/users/restore " , data = " <data> " ) ]
async fn bulk_restore_members (
async fn bulk_restore_members (
org_id : OrganizationId ,
org_id : OrganizationId ,
data : Json < BulkMembershipIds > ,
data : Json < BulkRestoreMemberData > ,
headers : ManageUsersHeaders ,
headers : ManageUsersHeaders ,
conn : DbConn ,
conn : DbConn ,
) -> JsonResult {
) -> JsonResult {
@ -2791,10 +3042,12 @@ async fn bulk_restore_members(
err ! ( "Organization not found" , "Organization id's do not match" ) ;
err ! ( "Organization not found" , "Organization id's do not match" ) ;
}
}
let data = data . into_inner ( ) ;
let data = data . into_inner ( ) ;
let collection_name = data . default_user_collection_name . as_deref ( ) ;
check_default_user_collection_name ( collection_name ) ? ;
let mut bulk_response = Vec ::new ( ) ;
let mut bulk_response = Vec ::new ( ) ;
for member_id in data . ids {
for member_id in data . ids {
let err_msg = match restore_member_impl ( & org_id , & member_id , & headers , & conn ) . await {
let err_msg = match restore_member_impl ( & org_id , & member_id , collection_name , & headers , & conn ) . await {
Ok ( ( ) ) = > String ::new ( ) ,
Ok ( ( ) ) = > String ::new ( ) ,
Err ( e ) = > {
Err ( e ) = > {
warn ! ( "Unable to restore member {}: {e:?}" , member_id . escape_debug ( ) ) ;
warn ! ( "Unable to restore member {}: {e:?}" , member_id . escape_debug ( ) ) ;
@ -2821,6 +3074,7 @@ async fn bulk_restore_members(
async fn restore_member_impl (
async fn restore_member_impl (
org_id : & OrganizationId ,
org_id : & OrganizationId ,
member_id : & MembershipId ,
member_id : & MembershipId ,
default_collection_name : Option < & str > ,
headers : & ManageUsersHeaders ,
headers : & ManageUsersHeaders ,
conn : & DbConn ,
conn : & DbConn ,
) -> EmptyResult {
) -> EmptyResult {
@ -2855,6 +3109,9 @@ async fn restore_member_impl(
conn ,
conn ,
)
)
. await ;
. await ;
// Only once the restore is stored, like upstream, see `confirm_invite_impl()`
Collection ::create_default_user_collection ( & member , default_collection_name , conn ) . await ? ;
}
}
Some ( _ ) = > err ! ( "User is already active" ) ,
Some ( _ ) = > err ! ( "User is already active" ) ,
None = > err ! ( "User not found in organization" ) ,
None = > err ! ( "User not found in organization" ) ,
@ -2986,6 +3243,12 @@ impl GroupRequest {
format ! ( "Collection {} does not belong to organization {}!" , e . id . escape_debug ( ) , org_id )
format ! ( "Collection {} does not belong to organization {}!" , e . id . escape_debug ( ) , org_id )
)
)
}
}
if org_collections
. iter ( )
. any ( | c | c . is_default_user_collection ( ) & & self . collections . iter ( ) . any ( | g | g . id = = c . uuid ) )
{
err ! ( "You cannot modify group access for collections with the type as DefaultUserCollection." )
}
let org_memberships = Membership ::find_by_org ( org_id , conn ) . await ;
let org_memberships = Membership ::find_by_org ( org_id , conn ) . await ;
let org_membership_ids : HashSet < & MembershipId > = org_memberships . iter ( ) . map ( | m | & m . uuid ) . collect ( ) ;
let org_membership_ids : HashSet < & MembershipId > = org_memberships . iter ( ) . map ( | m | & m . uuid ) . collect ( ) ;
@ -3782,7 +4045,7 @@ async fn get_org_export(org_id: OrganizationId, headers: AccessImportExportHeade
Ok ( Json ( json ! ( {
Ok ( Json ( json ! ( {
"collections" : convert_json_key_lcase_first ( get_org_collections_impl ( & org_id , & conn ) . await ) ,
"collections" : convert_json_key_lcase_first ( get_org_collections_impl ( & org_id , & conn ) . await ) ,
"ciphers" : convert_json_key_lcase_first ( get_org_details_impl ( & org_id , & headers . host , & headers . user . uuid , & conn ) . await ? ) ,
"ciphers" : convert_json_key_lcase_first ( get_org_details_impl ( & org_id , & headers . host , & headers . user . uuid , false , & conn ) . await ? ) ,
} ) ) )
} ) ) )
}
}
@ -3935,7 +4198,7 @@ mod tests {
) ;
) ;
let rocket = rocket ::build ( ) . manage ( Arc ::clone ( & WS_USERS ) ) ;
let rocket = rocket ::build ( ) . manage ( Arc ::clone ( & WS_USERS ) ) ;
let notify = rocket . state ::< Arc < WebSocketUsers > > ( ) . unwrap ( ) ;
let notify = rocket . state ::< Arc < WebSocketUsers > > ( ) . unwrap ( ) ;
confirm_invite_impl ( & org . uuid , & target . uuid , "encrypted-key" , & headers , & conn , & notify . into ( ) )
confirm_invite_impl ( & org . uuid , & target . uuid , "encrypted-key" , None , & headers , & conn , & notify . into ( ) )
. await
. await
. unwrap ( ) ;
. unwrap ( ) ;
let after = Membership ::find_by_uuid ( & target . uuid , & conn ) . await . unwrap ( ) ;
let after = Membership ::find_by_uuid ( & target . uuid , & conn ) . await . unwrap ( ) ;
@ -4004,6 +4267,7 @@ mod tests {
enabled : true ,
enabled : true ,
data : None ,
data : None ,
} ,
} ,
metadata : None ,
} ) ,
} ) ,
headers ,
headers ,
db . conn ( ) ,
db . conn ( ) ,