1
0
mirror of https://github.com/bitwarden/server synced 2025-12-06 00:03:34 +00:00
Commit Graph

136 Commits

Author SHA1 Message Date
Nick Krantz
087c6915e7 when ciphers are soft deleted, complete any associated security tasks (#6492) 2025-11-06 08:28:13 -06:00
Rui Tomé
9b313d9c0a [PM-25923] Simplify and align response models for Organization members and Provider users (#6385)
* Update ProviderUserOrganizationDetailsView to include SSO configuration data

* Updated the ProviderUserOrganizationDetailsViewQuery to join with SsoConfigs and select SSO-related fields.
* Modified the SQL view to reflect the inclusion of SSO configuration data.
* Added a new migration script for the updated view structure.

* Add SSO configuration properties to ProviderUserOrganizationDetails model

* Add SSO configuration handling to ProfileProviderOrganizationResponseModel

* Introduced properties for SSO configuration, including SSO enabled status and KeyConnector details.
* Implemented deserialization of SSO configuration data to populate new fields in the response model.

* Add integration tests for ProviderUserRepository.GetManyOrganizationDetailsByUserAsync

* Add BaseUserOrganizationDetails model to encapsulate common properties

* Introduced a new abstract class to define shared properties for organization users and provider organization users

* Add BaseProfileOrganizationResponseModel to encapsulate organization response properties

* Introduced a new abstract class that ensures all properties are fully populated for profile organization responses.

* Update ProviderUserOrganizationDetailsViewQuery to include missing ProviderUserId

* Refactor OrganizationUserOrganizationDetails and ProviderUserOrganizationDetails to inherit from BaseUserOrganizationDetails

* Updated both models to extend BaseUserOrganizationDetails, promoting code reuse and ensure they have the same base properties

* Refactor ProfileOrganizationResponseModel and ProfileProviderOrganizationResponseModel to inherit from BaseProfileOrganizationResponseModel

* Refactor ProviderUserRepositoryTests to improve organization detail assertions

* Consolidated assertions for organization details into a new method, AssertProviderOrganizationDetails, enhancing code readability and maintainability.
* Updated test cases to verify all relevant properties for organizations with and without SSO configurations.

* Add integration test for GetManyDetailsByUserAsync to verify SSO properties

* Implemented a new test case to ensure that the SSO properties are correctly populated for organizations with and without SSO configurations.
* The test verifies the expected behavior of the method when interacting with the user and organization repositories, including cleanup of created entities after the test execution.

* Add unit tests for ProfileOrganizationResponseModel and ProfileProviderOrganizationResponseModel

* Introduced tests to validate the constructors of ProfileOrganizationResponseModel and ProfileProviderOrganizationResponseModel, ensuring that all properties are populated correctly based on the provided organization details.
* Verified expected behavior for both organization and provider models, including SSO configurations and relevant properties.

* Update SyncControllerTests.Get_ProviderPlanTypeProperlyPopulated to nullify SSO configurations in provider user organization details

* Refactor BaseProfileOrganizationResponseModel and ProfileOrganizationResponseModel for null safety

Updated properties in BaseProfileOrganizationResponseModel and ProfileOrganizationResponseModel to support null safety by introducing nullable types where appropriate.

* Enhance null safety in BaseUserOrganizationDetails and OrganizationUserOrganizationDetails

Updated properties in BaseUserOrganizationDetails and OrganizationUserOrganizationDetails to support null safety by introducing nullable types where appropriate, ensuring better handling of potential null values.

* Move common properties from ProfileOrganizationResponseModel to BaseProfileOrganizationResponseModel

* Refactor organization details: Remove BaseUserOrganizationDetails and introduce IProfileMemberOrganizationDetails interface for improved structure and clarity in organization user data management.

* Enhance OrganizationUserOrganizationDetails: Implement IProfileMemberOrganizationDetails interface

* Refactor ProviderUserOrganizationDetails: Implement IProfileMemberOrganizationDetails interface

* Refactor ProfileOrganizationResponseModelTests and ProfileProviderOrganizationResponseModelTests: Update constructors to utilize Organization and ProviderUserOrganizationDetails, enhancing property population and test coverage.

* Enhance ProviderUserOrganizationDetails: Add UseResetPassword, UseSecretsManager, and UsePasswordManager properties to the query and SQL views

* Update BaseProfileOrganizationResponseModel documentation: Clarify purpose and usage of organization properties for OrganizationUsers and ProviderUsers.

* Rename ProfileOrganizationResponseModel to ProfileMemberOrganizationResponseModel, update references and update related test names

* Add XML documentation for ProfileMemberOrganizationResponseModel and ProfileProviderOrganizationResponseModel to clarify their purpose and relationships

* Remove unnecessary cleanup code from OrganizationUserRepositoryTests

* Remove unnecessary cleanup code from ProviderUserRepositoryTests

* Rename test method in ProviderUserRepositoryTests to improve clarity on property population

* Add CreateFullOrganization method to ProviderUserRepositoryTests for improved organization setup in tests

* Refactor organization creation in tests to use CreateTestOrganizationAsync for consistency and improved setup

* Rename IProfileMemberOrganizationDetails to IProfileOrganizationDetails

* Rename ProfileMemberOrganizationResponseModel back to ProfileOrganizationResponseModel

* Refactor organization response models to remove Family Sponsorship properties from BaseProfileOrganizationResponseModel and reintroduce them in ProfileOrganizationResponseModel. Update related interfaces and tests accordingly.

* Bump date on migration script

* Update OrganizationUserOrganizationDetailsViewQuery to include UseAutomaticUserConfirmation property
2025-10-24 20:42:28 +01:00
Rui Tomé
3866bc5155 [PM-23134] Update PolicyDetails sprocs for performance (#6421)
* Add integration tests for GetByUserIdWithPolicyDetailsAsync in OrganizationUserRepository

- Implemented multiple test cases to verify the behavior of GetByUserIdWithPolicyDetailsAsync for different user statuses (Confirmed, Accepted, Invited, Revoked).
- Ensured that the method returns correct policy details based on user status and organization.
- Added tests for scenarios with multiple organizations and non-existing policy types.
- Included checks for provider users and custom user permissions.

These tests enhance coverage and ensure the correctness of policy retrieval logic.

* Add UserProviderAccessView to identify which organizations a user can access as a provider

* Refactor PolicyDetails_ReadByUserId stored procedure to improve user access logic

- Introduced a Common Table Expression (CTE) for organization users to streamline the selection process based on user status and email.
- Added a CTE for providers to enhance clarity and maintainability.
- Updated the main query to utilize the new CTEs, improving readability and performance.
- Ensured that the procedure correctly identifies provider access based on user permissions.

* Refactor OrganizationUser_ReadByUserIdWithPolicyDetails stored procedure to enhance user access logic

- Introduced a Common Table Expression (CTE) for organization users to improve selection based on user status and email.
- Updated the main query to utilize the new CTEs, enhancing readability and performance.
- Adjusted the logic for identifying provider access to ensure accurate policy retrieval based on user permissions.

* Add new SQL migration script to refactor policy details queries

- Created a new view, UserProviderAccessView, to streamline user access to provider organizations.
- Introduced two stored procedures: PolicyDetails_ReadByUserId and OrganizationUser_ReadByUserIdWithPolicyDetails, enhancing the logic for retrieving policy details based on user ID and policy type.
- Utilized Common Table Expressions (CTEs) to improve query readability and performance, ensuring accurate policy retrieval based on user permissions and organization status.

* Remove GetPolicyDetailsByUserIdTests

* Refactor PolicyRequirementQuery to use GetPolicyDetailsByUserIdsAndPolicyType and update unit tests

* Remove GetPolicyDetailsByUserId method from IPolicyRepository and its implementations in PolicyRepository classes

* Revert changes to PolicyDetails_ReadByUserId stored procedure

* Refactor OrganizationUser_ReadByUserIdWithPolicyDetails stored procedure to use UNION instead of OR

* Reduce UserEmail variable size from NVARCHAR(320) to NVARCHAR(256) for consistency in stored procedures

* Bump date on migration script
2025-10-22 13:20:53 +01:00
Jared McCannon
449603d180 [PM-26632] - Adding Idempotent Confirm User (#6459)
* Added repo call for idempotent user confirm. PLUS TESTS!

* Code review changes
2025-10-16 11:19:48 -05:00
Vincent Salucci
0fbc314fb4 [PM-24954] [PM-24955] Remove BulkResourceCreationService Feature Flag (#6428)
* chore: remove ff implementation and superflous tests, refs PM-24954

* chore: remove UpdateForKeyRotation vNext, refs PM-24954

* chore: remove CreateAsync vNext for ImportCiphersCommand, refs PM-24954

* chore: remove UpdateCiphersAsync vNext from CipherService, refs PM-24954

* chore: formatting, refs PM-24954

* chore: fix CipherRepositoryTests by removing vNext references, refs PM-24954

* chore: remove bulk cipher copy ff key, refs PM-24954
2025-10-08 12:21:02 -05:00
Rui Tomé
7cefca330b [PM-26050] Migrate all DefaultUserCollection when claimed user is deleted (#6366)
* feat: migrate DefaultUserCollection to SharedCollection during user deletion

- Implemented migration of DefaultUserCollection to SharedCollection in EF UserRepository before deleting organization users.
- Updated stored procedures User_DeleteById and User_DeleteByIds to include migration logic.
- Added new migration script for updating stored procedures.

* Add unit test for user deletion and DefaultUserCollection migration

- Implemented a new test to verify the migration of DefaultUserCollection to SharedCollection during user deletion in UserRepository.
- The test ensures that the user is deleted and the associated collection is updated correctly.

* Refactor user deletion process in UserRepository

- Moved migrating DefaultUserCollection to SharedCollection to happen before the deletion of user-related entities.
- Updated the deletion logic to use ExecuteDeleteAsync for improved performance and clarity.
- Ensured that all related entities are removed in a single transaction to maintain data integrity.

* Add unit test for DeleteManyAsync in UserRepository

- Implemented a new test to verify the deletion of multiple users and the migration of their DefaultUserCollections to SharedCollections.
- Ensured that both users are deleted and their associated collections are updated correctly in a single transaction.

* Refactor UserRepositoryTests to use test user creation methods and streamline collection creation

* Ensure changes are saved after deleting users in bulk

* Refactor UserRepository to simplify migration queries and remove unnecessary loops for better performance

* Refactor UserRepository to encapsulate DefaultUserCollection migration logic in a separate method

* Refactor UserRepository to optimize deletion queries by using joins instead of subqueries for improved performance

* Refactor UserRepositoryTest DeleteManyAsync_Works to ensure GroupUser and CollectionUser deletion

---------

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
2025-10-01 14:28:19 +01:00
Jordan Aasen
3a6b9564d5 [PM-26004] - fix DeleteByOrganizationIdAsync_ExcludesDefaultCollectionCiphers test (#6389)
* fix test

* fix test
2025-09-26 14:30:34 -07:00
Nick Krantz
6edab46d97 [PM-24357] Do not purge ciphers in the default collection (#6320)
* do not purge ciphers in the default collection

* Update `DeleteByOrganizationId` procedure to be more performant based on PR review feedback

* update EF integration for purge to match new SQL implementation

* update Cipher_DeleteByOrganizationId based on PR feedback from dbops team
2025-09-24 12:52:04 -05:00
Rui Tomé
d83395aeb0 [PM-25372] Filter out DefaultUserCollections from CiphersController.GetAssignedOrganizationCiphers (#6274)
Co-authored-by: Jimmy Vo <huynhmaivo82@gmail.com>
2025-09-17 12:43:27 -04:00
Patrick-Pimentel-Bitwarden
4e64d35f89 [PM-19151] [PM-19161] Innovation/archive/server (#5672)
* Added the ArchivedDate to cipher entity and response model
* Created migration scripts for sqlserver and ef core migration to add the ArchivedDate column

---------

Co-authored-by: gbubemismith <gsmithwalter@gmail.com>
Co-authored-by: SmithThe4th <gsmith@bitwarden.com>
Co-authored-by: Shane <smelton@bitwarden.com>
Co-authored-by: cd-bitwarden <106776772+cd-bitwarden@users.noreply.github.com>
Co-authored-by: jng <jng@bitwarden.com>
2025-09-12 13:24:30 -04:00
Jared McCannon
2986a883eb [PM-25126] Add Bulk Policy Details (#6256)
* Added new bulk get for policy details

* Query improvements to avoid unnecessary look-ups.
2025-09-09 13:43:14 -05:00
Rui Tomé
1b0be3e87f [PM-22839] Add SSO configuration fields to organization user details for hiding device approvals page (#6245)
* Add SsoEnabled field to OrganizationUserOrganizationDetailsView

- Updated OrganizationUserOrganizationDetailsViewQuery to include SsoEnabled property.
- Modified SQL view to select SsoEnabled from SsoConfig.
- Created migration script to alter the view and refresh dependent views.

* Enhance OrganizationUserRepositoryTests to include SSO configuration

- Added ISsoConfigRepository dependency to GetManyDetailsByUserAsync test.
- Created SsoConfigurationData instance and integrated SSO configuration checks in assertions.
- Updated tests to validate SSO-related properties in the response model.

* Add SSO properties to ProfileOrganizationResponseModel and OrganizationUserOrganizationDetails

- Introduced SsoEnabled and SsoMemberDecryptionType fields in ProfileOrganizationResponseModel.
- Added SsoEnabled property to OrganizationUserOrganizationDetails for enhanced SSO configuration support.
2025-09-05 11:22:50 +01:00
Rui Tomé
1dade9d4b8 [PM-24233] Use BulkResourceCreationService in CipherRepository (#6201)
* Add constant for CipherRepositoryBulkResourceCreation in FeatureFlagKeys

* Add bulk creation methods for Ciphers, Folders, and CollectionCiphers in BulkResourceCreationService

- Implemented CreateCiphersAsync, CreateFoldersAsync, CreateCollectionCiphersAsync, and CreateTempCiphersAsync methods for bulk insertion.
- Added helper methods to build DataTables for Ciphers, Folders, and CollectionCiphers.
- Enhanced error handling for empty collections during bulk operations.

* Refactor CipherRepository to utilize BulkResourceCreationService

- Introduced IFeatureService to manage feature flag checks for bulk operations.
- Updated methods to conditionally use BulkResourceCreationService for creating Ciphers, Folders, and CollectionCiphers based on feature flag status.
- Enhanced existing bulk copy logic to maintain functionality while integrating feature flag checks.

* Add InlineFeatureService to DatabaseDataAttribute for feature flag management

- Introduced EnabledFeatureFlags property to DatabaseDataAttribute for configuring feature flags.
- Integrated InlineFeatureService to provide feature flag checks within the service collection.
- Enhanced GetData method to utilize feature flags for conditional service registration.

* Add tests for bulk creation of Ciphers in CipherRepositoryTests

- Implemented tests for bulk creation of Ciphers, Folders, and Collections with feature flag checks.
- Added test cases for updating multiple Ciphers to validate bulk update functionality.
- Enhanced existing test structure to ensure comprehensive coverage of bulk operations in the CipherRepository.

* Refactor BulkResourceCreationService to use dynamic types for DataColumns

- Updated DataColumn definitions in BulkResourceCreationService to utilize the actual types of properties from the cipher object instead of hardcoded types.
- Simplified the assignment of nullable properties to directly use their values, improving code readability and maintainability.

* Update BulkResourceCreationService to use specific types for DataColumns

- Changed DataColumn definitions to use specific types (short and string) instead of dynamic types based on cipher properties.
- Improved handling of nullable properties when assigning values to DataTable rows, ensuring proper handling of DBNull for null values.

* Refactor CipherRepositoryTests for improved clarity and consistency

- Renamed test methods to better reflect their purpose and improve readability.
- Updated test data to use more descriptive names for users, folders, and collections.
- Enhanced test structure with clear Arrange, Act, and Assert sections for better understanding of test flow.
- Ensured all tests validate the expected outcomes for bulk operations with feature flag checks.

* Update CipherRepositoryBulkResourceCreation feature flag key

* Refactor DatabaseDataAttribute usage in CipherRepositoryTests to use array syntax for EnabledFeatureFlags

* Update CipherRepositoryTests to use GenerateComb for generating unique IDs

* Refactor CipherRepository methods to accept a boolean parameter for enabling bulk resource creation based on feature flags. Update tests to verify functionality with and without the feature flag enabled.

* Refactor CipherRepository and related services to support new methods for bulk resource creation without boolean parameters.
2025-09-03 14:57:53 +01:00
Jimmy Vo
8ceb6f5621 [PM-24278] Create Remove Individual Vault validator (#6139) 2025-08-27 11:01:22 -04:00
Justin Baur
5a712ebb6b Xunit v3 (#6241)
* Initial v3 Migration

* Migrate tests and debug duplicate ids

* Debug duplicate ids

* Support seeding

* remove seeder

* Upgrade to latest XUnit.v3 version

* Remove Theory changes for now

* Remove Theory change from DeviceRepositoryTests

* Remove cancellation token additions
2025-08-25 08:43:24 +02:00
Brandon Treston
c189e4aaf5 [PM-22104] Migrate default collection when org user is removed (#6135)
* migrate default collection to a shared collection when users are removed

* remove redundant logic

* fix test

* fix tests

* fix test

* clean up

* add migrations

* run dotnet format

* clean up, refactor duplicate logic to sproc, wip integration test

* fix sql

* add migration for new sproc

* integration test wip

* integration test wip

* integration test wip

* integration test wip

* fix integration test LINQ expression

* fix using wrong Id

* wip integration test for DeleteManyAsync

* fix LINQ

* only set DefaultUserEmail when it is null in sproc

* check for null

* spelling, separate create and update request models

* fix test

* fix child class

* refactor sproc

* clean up

* more cleanup

* fix tests

* fix user email

* remove unneccesary test

* add DefaultUserCollectionEmail to EF query

* fix test

* fix EF logic to match sprocs

* clean up logic

* cleanup
2025-08-19 14:12:34 -04:00
Jimmy Vo
03327cb082 [PM-24278] Fix sproc to return UserId (#6203) 2025-08-18 11:12:42 -04:00
Rui Tomé
41f82bb357 [PM-23116/PM-23117] Remove deprecated feature flag MembersGetEndpointOptimization (#6179)
* Refactor OrganizationUserRepositoryTests: Swap GetManyByOrganizationWithClaimedDomainsAsync_vNext with GetManyByOrganizationWithClaimedDomainsAsync and remove outdated test

* Refactor GetOrganizationUsersClaimedStatusQuery: Remove unused IFeatureService dependency and simplify domain claimed status retrieval logic.

* Refactor OrganizationUserUserDetailsQuery: Remove unused IFeatureService dependency and streamline user details retrieval methods.

* Refactor OrganizationUserRepository: Remove deprecated GetManyByOrganizationWithClaimedDomainsAsync_vNext method and its implementation

* Remove deprecated feature flag MembersGetEndpointOptimization
2025-08-15 10:14:38 +01:00
Nick Krantz
f88baba66b [PM-23580] Security Task Metrics (#6164)
* add metrics endpoint for an organization to return completed and total security tasks

* refactor metrics fetch to use sql sproc for efficiency rather than having to pull all security task data

* add separate response model for security task metrics endpoint

* Pascal Case to match existing implementations

* refactor org to organization for consistency with other methods

* alter security task endpoint:
- remove "count" from variable naming
- update sproc naming

* remove enablement check

* replace orgId with organizationId
2025-08-13 08:23:22 -05:00
Jimmy Vo
de13932ffe [PM-22108] Add PolicyDetails_ReadByOrganizationId proc (#6019) 2025-07-31 11:24:39 -04:00
Jimmy Vo
ff5659cc0f Add bulk default collection creation method (#6075) 2025-07-31 11:24:16 -04:00
Jared McCannon
86ce3a86e9 [PM-20452] - Offloading Stripe Update (#6034)
* Adding job to update stripe subscriptions and increment seat count  when inviting a user.

* Updating name

* Added ef migrations

* Fixing script

* Fixing procedures. Added repo tests.

* Fixed set stored procedure. Fixed parameter name.

* Added tests for database calls and updated stored procedures

* Fixed build for sql file.

* fixing sproc

* File is nullsafe

* Adding view to select from instead of table.

* Updating UpdateSubscriptionStatus to use a CTE and do all the updates in 1 statement.

* Setting revision date when incrementing seat count

* Added feature flag check for the background job.

* Fixing nullable property.

* Removing new table and just adding the column to org. Updating to query and command. Updated tests.

* Adding migration script rename

* Add SyncSeats to Org.sql def

* Adding contraint name

* Removing old table files.

* Added tests

* Upped the frequency to be at the top of every 3rd hour.

* Updating error message.

* Removing extension method

* Changed to GuidIdArray

* Added xml doc and switched class to record
2025-07-31 07:54:51 -05:00
Rui Tomé
b00e689ff6 [PM-22558] Update IOrganizationUserRepository.ReplaceAsync to preserve existing access to collections of the type DefaultUserCollection (#6037)
* feat: exclude DefaultUserCollection from GetManyByOrganizationIdWithPermissionsAsync

Updated EF implementation, SQL procedure, and unit test to verify that default user collections are filtered from results

* Update the public CollectionsController.Get method to return a NotFoundResult for collections of type DefaultUserCollection.

* Add unit tests for the public CollectionsController

* Update ICollectionRepository.GetManyByOrganizationIdAsync to exclude results of the type DefaultUserCollection

Modified the SQL stored procedure and the EF query to reflect this change and added a new integration test to ensure the functionality works as expected.

* Refactor CollectionsController to remove unused IApplicationCacheService dependency

* Update IOrganizationUserRepository.GetDetailsByIdWithCollectionsAsync to exclude DefaultUserCollections

* Update IOrganizationUserRepository.GetManyDetailsByOrganizationAsync to exclude DefaultUserCollections

* Undo change to GetByIdWithCollectionsAsync

* Update integration test to verify exclusion of DefaultUserCollection in OrganizationUserRepository.GetDetailsByIdWithCollectionsAsync

* Clarify documentation in ICollectionRepository to specify that GetManyByOrganizationIdWithAccessAsync returns only shared collections belonging to the organization.

* Update IOrganizationUserRepository.ReplaceAsync to preserve existing access to collections of the type DefaultUserCollection
2025-07-29 15:04:45 +01:00
Rui Tomé
6dea40c868 [PM-23987] Fix saving to default collections by updating collection lookup (#6122)
* Refactor ICollectionRepository.GetManyByOrganizationIdAsync logic to include default user collections

* Add stored procedure Collection_ReadSharedCollectionsByOrganizationId to retrieve collections by organization ID, excluding default user collections.

* Add GetManySharedCollectionsByOrganizationIdAsync method to ICollectionRepository and its implementations to retrieve collections excluding default user collections.

* Add unit test for GetManySharedCollectionsByOrganizationIdAsync method in CollectionRepositoryTests to verify retrieval of collections excluding default user collections.

* Refactor controllers to use GetManySharedCollectionsByOrganizationIdAsync for retrieving shared collections

* Update unit tests to use GetManySharedCollectionsByOrganizationIdAsync for verifying shared collections retrieval

* Revert CiphersController.CanEditItemsInCollections to use GetManyByOrganizationIdAsync for retrieving organization collections

* Update stored procedures to retrieve only DefaultUserCollection by modifying the WHERE clause in Collection_ReadSharedCollectionsByOrganizationId.sql and its corresponding migration script.

* Update EF CollectionRepository.GetManySharedCollectionsByOrganizationIdAsync to filter collections by SharedCollection

* Update OrganizationUserRepository.GetManyDetailsByOrganizationAsync_vNext to only include Shared collections

* Update comments in stored procedure and migration script to clarify filtering for SharedCollections only
2025-07-29 15:04:00 +01:00
Rui Tomé
acd556d56f [PM-21031] Optimize GET Members endpoint performance (#5907)
* Add new feature flag for Members Get Endpoint Optimization

* Add a new version of OrganizationUser_ReadByOrganizationIdWithClaimedDomains that uses CTE for better performance

* Add stored procedure OrganizationUserUserDetails_ReadByOrganizationId_V2 for retrieving user details, group associations, and collection associations by organization ID.

* Add the sql migration script to add the new stored procedures

* Introduce GetManyDetailsByOrganizationAsync_vNext and GetManyByOrganizationWithClaimedDomainsAsync_vNext in IOrganizationUserRepository to enhance performance by reducing database round trips.

* Updated GetOrganizationUsersClaimedStatusQuery to use an optimized query when the feature flag is enabled

* Updated OrganizationUserUserDetailsQuery to use optimized queries when the feature flag is enabled

* Add integration tests for GetManyDetailsByOrganizationAsync_vNext

* Add integration tests for GetManyByOrganizationWithClaimedDomainsAsync_vNext to validate behavior with verified and unverified domains.

* Optimize performance by conditionally setting permissions only for Custom user types in OrganizationUserUserDetailsQuery.

* Create UserEmailDomainView to extract email domains from users' email addresses

* Create stored procedure Organization_ReadByClaimedUserEmailDomain_V2 that uses UserEmailDomainView to fetch Email domains

* Add GetByVerifiedUserEmailDomainAsync_vNext method to IOrganizationRepository and its implementations

* Refactor OrganizationUser_ReadByOrganizationIdWithClaimedDomains_V2 stored procedure to use UserEmailDomainView for email domain extraction, improving query efficiency and clarity.

* Enhance IOrganizationUserRepository with detailed documentation for GetManyDetailsByOrganizationAsync method, clarifying its purpose and performance optimizations. Added remarks for better understanding of its functionality.

* Fix missing newline at the end of Organization_ReadByClaimedUserEmailDomain_V2.sql to adhere to coding standards.

* Update the database migration script to include UserEmailDomainView

* Bumped the date on the migration script

* Remove GetByVerifiedUserEmailDomainAsync_vNext method and its stored procedure.

* Refactor UserEmailDomainView index creation to check for existence before creation

* Update OrganizationUser_ReadByOrganizationIdWithClaimedDomains_V2 to use CTE and add indexes

* Remove creation of unique clustered index from UserEmailDomainView and related migration script adjustments

* Update indexes and sproc

* Fix index name when checking if it already exists

* Bump up date on migration script
2025-07-23 10:04:20 +01:00
Rui Tomé
30300bc59b [PM-22103] Exclude default collections from admin apis (#6021)
* feat: exclude DefaultUserCollection from GetManyByOrganizationIdWithPermissionsAsync

Updated EF implementation, SQL procedure, and unit test to verify that default user collections are filtered from results

* Update the public CollectionsController.Get method to return a NotFoundResult for collections of type DefaultUserCollection.

* Add unit tests for the public CollectionsController

* Update ICollectionRepository.GetManyByOrganizationIdAsync to exclude results of the type DefaultUserCollection

Modified the SQL stored procedure and the EF query to reflect this change and added a new integration test to ensure the functionality works as expected.

* Refactor CollectionsController to remove unused IApplicationCacheService dependency

* Update IOrganizationUserRepository.GetDetailsByIdWithCollectionsAsync to exclude DefaultUserCollections

* Update IOrganizationUserRepository.GetManyDetailsByOrganizationAsync to exclude DefaultUserCollections

* Undo change to GetByIdWithCollectionsAsync

* Update integration test to verify exclusion of DefaultUserCollection in OrganizationUserRepository.GetDetailsByIdWithCollectionsAsync

* Clarify documentation in ICollectionRepository to specify that GetManyByOrganizationIdWithAccessAsync returns only shared collections belonging to the organization.

* Add Arrange, Act, and Assert comments to CollectionsControllerTests
2025-07-18 13:00:54 +01:00
Ike
20bf1455cf [PM-20348] Add pending auth request endpoint (#5957)
* Feat(pm-20348): 
  * Add migration scripts for Read Pending Auth Requests by UserId stored procedure and new `view` for pending AuthRequest. 
  * View only returns the most recent pending authRequest, or none at all if the most recent is answered.
  * Implement stored procedure in AuthRequestRepository for both Dapper and Entity Framework.
  * Update AuthRequestController to query the new View to get a user's most recent pending auth requests response includes the requesting deviceId.

* Doc: 
  * Move summary xml comments to interface.
  * Added comments for the AuthRequestService.

* Test: 
  * Added testing for AuthRequestsController.
  * Added testing for repositories. 
  * Added integration tests for multiple auth requests but only returning the most recent.
2025-06-30 13:17:51 -04:00
Nick Krantz
8bccf255c0 [PM-22974] Cascade delete NotificationStatus entities (#6011)
* cascade delete NotificationStatus entities

* add userId to test for foreign constraint

* add missing properties for Notification

* add check for foreign key
2025-06-27 11:17:47 -05:00
Jared McCannon
d2410747d0 [PM-22503] Fix manage cipher permission (#5972)
* Added new tests to validate that the ciphers are being grouped and filtered correctly when assigned to multiple collections and changing order of grouping properties.
2025-06-23 11:11:32 -05:00
cyprain-okeke
a618f97234 [PM 20621]Update error message when lowering seat count (#5836)
* implement the seat decrease error message

* Resolve the comment regarding abstraction

* Resolved the database failure

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing upgrade test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Removed the unused method

* Remove the total calculation from the stored procedure

* Refactoring base on pr feedback

* Refactoring base on pr feedback

* Resolve the fauiling database

* Resolve the failing database test

* Resolve the database test

* Remove duplicate migrations

* resolve the failing test

* Removed the unneeded change

* remove this file

* Reverted Deleted migration

* revert the added space

* resolve the stored procedure name

* Rename the migration name

* Updated the stored procedure name

* Revert the changes on the sproc

* Revert unrelated changes

* Remove the unused method

* improved the xmldoc

* Add an integration testing

* Add the use of helper test class

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* remove object look up

* Resolve message rollback

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

---------

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>
2025-06-11 14:03:45 +01:00
Thomas Rittson
c7b0c30370 Bump account revision date in OrgUserRepository (#5884)
Match equivalent MSSQL logic. Also ensures that the revision date
is bumped when the user is revoked.
2025-05-29 07:30:23 +10:00
Thomas Rittson
198d96e155 [PM-21612] [Unified] Fix unhandled error when editing an invited member (#5817)
* Check for UserId instead of passing potentially default value to
  bump account revision date method.

* Pass explicit UserId into CipherRepository.CreateAsync method
  used for imports.
2025-05-23 11:45:41 +10:00
Thomas Rittson
83478f9c69 [PM-13274] [Unified] Add integration tests for creating and updating collections (#5814) 2025-05-23 11:27:37 +10:00
cyprain-okeke
e4359f071c [PM-21097] Fix: Prevent admin-added sponsored families from appearing in individual vault settings (#5767)
* Changes to resolve sponsorship showing in individual vault

* Resolve the failing unit test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing test

* Resolve the failing test

* Resolve the failing test

* fix make IsAdminInitiated nullable

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Add the isAdminInitiated property

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the database error

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the failing unit test

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the scan error

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>

* Resolve the database issue

* resolve the database build error

* Resolve the database build error

* Resolve the synchronization issue

---------

Signed-off-by: Cy Okeke <cokeke@bitwarden.com>
2025-05-12 18:21:07 +01:00
Justin Baur
15b498184f Resolve platform warnings (#5798)
* Installation Repository tests

* Formatting

* Remove extra LastActivityDate property

* Remove exclusion
2025-05-09 16:03:09 -04:00
Nick Krantz
6809709628 [PM-20064] Add cascade deletion for cipher with tasks (#5690)
* add cascade deletion for cipher tasks

* add migrations for cascade delete on ciphers and security tasks

* remove trailing comma

* add SQL migration for PasswordHealthReportApplication

- Allow cascade delete when an organization is deleted
2025-04-23 13:16:29 -05:00
Jared McCannon
dc758c5176 [PM-19128] - Optimize Update Collections (#5626)
* added data clean up to test

* Added indices and edited sproc to avoid merge commands

* Forgot GO

* Adding some more GOs
2025-04-18 11:51:50 -05:00
Jonas Hendrickx
c182b37347 [PM-17830] Backend changes for admin initiated sponsorships (#5531)
* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* Add `Notes` column to `OrganizationSponsorships` table

* Add feature flag to `CreateAdminInitiatedSponsorshipHandler`

* Unit tests for `CreateSponsorshipHandler`

* More tests for `CreateSponsorshipHandler`

* Forgot to add `Notes` column to `OrganizationSponsorships` table in the migration script

* `CreateAdminInitiatedSponsorshipHandler` unit tests

* Fix `CreateSponsorshipCommandTests`

* Encrypt the notes field

* Wrong business logic checking for invalid permissions.

* Wrong business logic checking for invalid permissions.

* Remove design patterns

* duplicate definition in Constants.cs

* Allow rollback

* Fix stored procedures & type

* Fix stored procedures & type

* Properly encapsulating this PR behind its feature flag

* Removed comments

* Updated ValidateSponsorshipCommand to validate admin initiated requirements

---------

Co-authored-by: Conner Turnbull <133619638+cturnbull-bitwarden@users.noreply.github.com>
Co-authored-by: Conner Turnbull <cturnbull@bitwarden.com>
2025-04-16 11:27:58 -04:00
Justin Baur
bfe5ecda92 Add UpdateCiphersAsync Test (#5543)
* Add UpdateCiphersAsync Test

* Fix UpdateCiphersAsync

* Fix #2

* Fix SQL Server

* Formatting
2025-04-11 15:59:54 -04:00
Jared McCannon
0d7363c6af [PM-16811] - SCIM Invite Users Optimizations (#5398)
* WIP changes for Invite User optimization from Scim

* feature flag string

* Added plan validation to PasswordManagerInviteUserValidation. Cleaned up a few things.

* Added Secrets Manager Validations and Tests.

* Added bulk procedure for saving users, collections and groups from inviting. Added test to validate Ef and Sproc

* Created SendOrganizationInvitesCommand and moved some tests from OrgServiceTests. Fixed some tests in org service in relation to moving out SendOrgInviteCommand code.

Added side effects to InviteOrganizationUsersCommand

* First test of new command.

* Added test to verify valid request with a user calls db method and sends the invite

* Added more tests for the updates

* Added integration test around enabling feature and sending invite via scim. Did a bit of refactoring on the SM validation. Fixed couple bugs found.

* Switching over to a local factory.

* created response model and split interface out.

* switched to initialization block

* Moved to private method. Made ScimInvite inherit the single invite base model. Moved create methods to constructors. A few more CR changes included.

* Moved `FromOrganization` mapper method to a constructor

* Updated to use new pricing client. Supressed null dereference errors.

* Fixing bad merge.

* Rename of OrgDto

* undoing this

* Moved into class

* turned into a switch statement

* Separated into separate files.

* Renamed dto and added ctor

* Dto rename. Moved from static methods to ctors

* Removed unused request model

* changes from main

* missed value

* Fixed some compilation errors.

* Fixed some changes.

* Removed comment

* fixed compiler warning.

* Refactored to use new ValidationResult pattern. added mapping method.

* Added throwing of Failure as the previous implementation would have.

* Cleaned up return.

* fixing test.

* Made HasSecretsManagerStandalone return if org doesn't have sm. Added overload for lighter weight model and moved common code to private method.

* Fixed tests.

* Made public method private. added some comments.

* Refactor validation parameter to improve clarity and consistency. Added XML doc

* fixed test

* Removed test only constructor from InviteOrganization

* Separated old and new code explicitly. Moved old code checks down into new code as well. Added error and mapper to Failure<T>

* Variable/Field/Property renames

* Renamed InviteUsersValidation to InviteUsersValidator

* Rename for InvitingUserOrganizationValidation to InvitingUserOrganizationValidator

* PasswordManagerInviteUserValidation to PasswordManagerInviteUserValidator

* Moved XML comment. Added check to see if additional seats are needed.

* Fixing name.

* Updated names.

* Corrected double negation.

* Added groups and collection and users checks.

* Fixed comment. Fixed multiple enumeration. Changed variable name.

* Cleaned up DTO models. Moved some validation steps around. A few quick fixes to address CR concerns. Still need to move a few things yet.

* Fixed naming in subscription update models.

* put back in the request for now.

* Quick rename

* Added provider email addresses as well.

* Removed valid wrapper to pass in to validation methods.

* fix tests

* Code Review changes.

* Removed unused classes

* Using GetPlanOrThrow instead.

* Switches to extension method

* Made Revert and Adjust Sm methods consistent. Corrected string comparer. Added comment for revert sm.

* Fixing compiler complaint.

* Adding XML docs

* Calculated seat addition for SM.

* Fixing compiler complaints.

* Renames for organization.

* Fixing comparison issue.

* Adding error and aligning message.

* fixing name of method.

* Made extension method.

* Rearranged some things. Fixed the tests.

* Added test around validating the revert.

* Added test to validate the provider email is sent if org is managed by a provider.

* Created new errors and removed references in business code to ErrorMessages property. This aligns Invite User code to use Errors instead of ErrorMessages

* Delayed the hasSecretsManagerStandalone call as long as possible.

* Corrected model name. Corrected SM seat calculation. Added test for it.

* Corrected logic and added more tests.
2025-04-07 09:14:10 -05:00
Jared McCannon
786b0edceb [PM-18527] - Fix allowing restored user to own multiple free orgs (#5444)
* Moved RestoreUserAsync and RestoreUsersAsync to Command.

* Fixing the bug.

* Added test for bulk method.

* Fixing sonar cube warning.

* SonarQube warning fix.

* Excluding org users we already have.

* Fixed misspelling. Added integration test for method.

* test had the misspelling as well 🤦

* Split out interface. Added admin and confirmed constraints.

* fixed queries and added xml comments and tests.
2025-03-31 08:33:57 -05:00
Brandon Treston
546b5a0849 [pm-17804] Fix deferred execution issue in EF CreateManyAsync (#5425)
* Add failing repository tests

* test

* clean up comments

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
2025-02-27 10:21:01 -05:00
Nick Krantz
1267332b5b [PM-14406] Security Task Notifications (#5344)
* initial commit of `CipherOrganizationPermission_GetManyByUserId`

* create queries to get all of the security tasks that are actionable by a user

- A task is "actionable" when the user has manage permissions for that cipher

* rename query

* return the user's email from the query as well

* Add email notification for at-risk passwords

- Added email layouts for security tasks

* add push notification for security tasks

* update entity framework to match stored procedure plus testing

* update date of migration and remove orderby

* add push service to security task controller

* rename `SyncSecurityTasksCreated` to `SyncNotification`

* remove duplicate return

* remove unused directive

* remove unneeded new notification type

* use `createNotificationCommand` to alert all platforms

* return the cipher id that is associated with the security task and store the security task id on the notification entry

* Add `TaskId` to the output model of `GetUserSecurityTasksByCipherIdsAsync`

* move notification logic to command

* use TaskId from `_getSecurityTasksNotificationDetailsQuery`

* add service

* only push last notification for each user

* formatting

* refactor `CreateNotificationCommand` parameter to `sendPush`

* flip boolean in test

* update interface to match usage

* do not push any of the security related notifications to the user

* add `PendingSecurityTasks` push type

* add push notification for pending security tasks
2025-02-27 08:34:42 -06:00
Rui Tomé
2b1db97d5c [PM-18085] Add Manage property to UserCipherDetails (#5390)
* Add Manage permission to UserCipherDetails and CipherDetails_ReadByIdUserId

* Add Manage property to CipherDetails and UserCipherDetailsQuery

* Add integration test for CipherRepository Manage permission rules

* Update CipherDetails_ReadWithoutOrganizationsByUserId to include Manage permission

* Refactor UserCipherDetailsQuery to include detailed permission and organization properties

* Refactor CipherRepositoryTests to improve test organization and readability

- Split large test method into smaller, focused methods
- Added helper methods for creating test data and performing assertions
- Improved test coverage for cipher permissions in different scenarios
- Maintained existing test logic while enhancing code structure

* Refactor CipherRepositoryTests to consolidate cipher permission tests

- Removed redundant helper methods for permission assertions
- Simplified test methods for GetCipherPermissionsForOrganizationAsync, GetManyByUserIdAsync, and GetByIdAsync
- Maintained existing test coverage for cipher manage permissions
- Improved code readability and reduced code duplication

* Add integration test for CipherRepository group collection manage permissions

- Added new test method GetCipherPermissionsForOrganizationAsync_ManageProperty_RespectsCollectionGroupRules
- Implemented helper method CreateCipherInOrganizationCollectionWithGroup to support group-based collection permission testing
- Verified manage permissions are correctly applied based on group collection access settings

* Add @Manage parameter to Cipher stored procedures

- Updated CipherDetails_Create, CipherDetails_CreateWithCollections, and CipherDetails_Update stored procedures
- Added @Manage parameter with comment "-- not used"
- Included new stored procedure implementations in migration script
- Consistent with previous work on adding Manage property to cipher details

* Update UserCipherDetails functions to reorder Manage and ViewPassword columns

* Reorder Manage and ViewPassword properties in cipher details queries

* Bump date in migration script
2025-02-24 11:40:53 +00:00
Jimmy Vo
2f4d5283d3 [PM-17449] Add stored proc, EF query, and an integration test for them (#5413) 2025-02-20 15:08:06 -05:00
Thomas Rittson
f4341b2f3b [PM-14439] Add PolicyRequirementQuery for enforcement logic (#5336)
* Add PolicyRequirementQuery, helpers and models in preparation for migrating domain code

Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>
2025-02-14 11:05:49 +00:00
Thomas Rittson
54d59b3b92 [PM-16812] Shortcut duplicate group patch requests (#5354)
* Copy PatchGroupCommand to vNext and refactor

* Detect duplicate add requests and return early

* Update read repository method to use HA replica

* Add new write repository method
2025-02-14 11:09:01 +10:00
Jimmy Vo
a8b2dde615 [PM-18079] Fix intermittent failing database integration tests. (#5381) 2025-02-07 09:47:47 -05:00
Justin Baur
af07dffa6f Relax nullable in test projects (#5379)
* Relax nullable in test projects

* Fix xUnit Warnings

* More xUnit fixes
2025-02-06 17:07:43 -05:00
SmithThe4th
46004b9c68 [PM-14381] Add POST /tasks/bulk-create endpoint (#5188)
* [PM-14378] Introduce GetCipherPermissionsForOrganization query for Dapper CipherRepository

* [PM-14378] Introduce GetCipherPermissionsForOrganization method for Entity Framework

* [PM-14378] Add integration tests for new repository method

* [PM-14378] Introduce IGetCipherPermissionsForUserQuery CQRS query

* [PM-14378] Introduce SecurityTaskOperationRequirement

* [PM-14378] Introduce SecurityTaskAuthorizationHandler.cs

* [PM-14378] Introduce SecurityTaskOrganizationAuthorizationHandler.cs

* [PM-14378] Register new authorization handlers

* [PM-14378] Formatting

* [PM-14378] Add unit tests for GetCipherPermissionsForUserQuery

* [PM-15378] Cleanup SecurityTaskAuthorizationHandler and add tests

* [PM-14378] Add tests for SecurityTaskOrganizationAuthorizationHandler

* [PM-14378] Formatting

* [PM-14378] Update date in migration file

* [PM-14378] Add missing awaits

* Added bulk create request model

* Created sproc to create bulk security tasks

* Renamed tasks to SecurityTasksInput

* Added create many implementation for sqlserver and ef core

* removed trailing comma

* created ef implementatin for create many and added integration test

* Refactored request model

* Refactored request model

* created create many tasks command interface and class

* added security authorization handler work temp

* Added the implementation for the create manys tasks command

* Added comment

* Changed return to return list of created security tasks

* Registered command

* Completed bulk create action

* Added unit tests for the command

* removed hard coded table name

* Fixed lint issue

* Added JsonConverter attribute to allow enum value to be passed as string

* Removed makshift security task operations

* Fixed references

* Removed old migration

* Rebased

* [PM-14378] Introduce GetCipherPermissionsForOrganization query for Dapper CipherRepository

* [PM-14378] Introduce GetCipherPermissionsForOrganization method for Entity Framework

* [PM-14378] Add unit tests for GetCipherPermissionsForUserQuery

* Completed bulk create action

* bumped migration version

* Fixed lint issue

* Removed complex sql data type in favour of json string

* Register IGetTasksForOrganizationQuery

* Fixed lint issue

* Removed tasks grouping

* Fixed linting

* Removed unused code

* Removed unused code

* Aligned with client change

* Fixed linting

---------

Co-authored-by: Shane Melton <smelton@bitwarden.com>
2025-02-05 16:56:01 -05:00