2 Commits

Author SHA1 Message Date
Rui Tomé
e09e63569c [PM-33086] Remove the feature flag RefactorOrgAcceptInit (#7287) 2026-03-26 12:36:07 +00:00
Rui Tomé
c97ccc1610 [PM-28795] Refactor organization accept-init flow with atomic database operations and upfront validation (#6831)
* Add integration tests for AcceptInit endpoint in OrganizationUsersController

* Add new feature flag for organization acceptance initialization refactor

* Add InitPendingOrganizationVNextAsync for consolidated organization initialization

Introduces a new method that consolidates organization initialization,
user confirmation, email verification, and collection creation into a
single operation with upfront validation.

Key improvements:
- All validation performed before any state changes
- Returns typed errors via CommandResult instead of throwing exceptions
- Reduces three separate command calls into one unified flow
- Maintains backward compatibility via feature flag

The existing InitPendingOrganizationAsync is marked obsolete and will be
removed after feature flag rollout completes.

* Add unit tests for InitPendingOrganizationVNextAsync method

Introduces comprehensive unit tests for the InitPendingOrganizationVNextAsync method, covering various scenarios including valid data initialization, error handling for invalid tokens, organization status checks, and user confirmation requirements.

Key additions:
- Tests for successful organization initialization and user confirmation.
- Error handling tests for invalid tokens, already enabled organizations, and mismatched organization IDs.
- Validation for existing keys and email mismatches.
- Support for creating default collections during initialization.

These tests enhance the reliability and robustness of the organization initialization process.

* Refactor AcceptInit method to support feature flag for organization initialization

Updated the AcceptInit method in OrganizationUsersController to return an IResult type and handle organization initialization based on a feature flag. If the feature is enabled, it utilizes the new InitPendingOrganizationVNextAsync method for atomic organization setup and user confirmation. Integration tests were added to verify the behavior under both feature flag states, ensuring proper initialization and error handling.

* Enhance InitPendingOrganizationCommand with policy validation and feature flag support

Updated the ValidatePoliciesAsync method to enforce the Automatic User Confirmation Policy when the feature flag is enabled. Added new unit tests to cover scenarios for automatic user confirmation and single organization policy violations, ensuring comprehensive validation during organization initialization. This improves error handling and maintains compliance with organizational policies.

* Add InitializePendingOrganizationAsync method for atomic organization initialization

Implemented the InitializePendingOrganizationAsync method in both Dapper and Entity Framework repositories to streamline the initialization of pending organizations. This method enables the organization, confirms the first owner, updates user details, and optionally creates a default collection, all within a single atomic transaction. Enhanced error handling ensures robustness during the initialization process.

* Add unit tests for InitializePendingOrganizationAsync method

Introduced several unit tests for the InitializePendingOrganizationAsync method, covering scenarios such as successful organization initialization with and without collections, exception handling for invalid organization IDs, and rollback behavior on errors. These tests enhance the reliability of the organization initialization process and ensure proper handling of various edge cases.

* Refactor InitPendingOrganizationCommand to use consolidated InitializePendingOrganizationAsync method

Replaced multiple asynchronous calls for organization initialization with a single call to the new InitializePendingOrganizationAsync method. This change streamlines the process by encapsulating organization setup, user confirmation, and collection creation into one atomic operation, enhancing maintainability and reducing complexity in the command logic.

* Enhance InitPendingOrganizationCommandTests with new test cases and refactor existing ones

Added a new test case for InitPendingOrganizationVNextAsync to validate organization initialization with a collection name. Refactored existing tests to improve clarity and maintainability, including the removal of redundant assertions and the consolidation of organization setup logic. This update strengthens the test coverage for the organization initialization process and ensures proper handling of various scenarios.

* Refactor IOrganizationRepository and OrganizationRepository to remove nullable collectionName parameter

Updated the IOrganizationRepository and OrganizationRepository interfaces to change the collectionName parameter from nullable to non-nullable. This change enforces stricter parameter requirements and improves data integrity during organization initialization processes.

* Improve error handling in OrganizationRepository by logging exceptions during transaction rollback

Updated the OrganizationRepository in both Dapper and Entity Framework implementations to log detailed error messages when exceptions occur during the initialization of pending organizations. This enhancement improves traceability and debugging capabilities by providing context on failures, ensuring better maintainability of the organization initialization process.

* Refactor OrganizationRepository to consolidate SaveChangesAsync calls

Updated the OrganizationRepository to reduce multiple SaveChangesAsync calls into a single call at the end of the transaction. This change enhances performance and ensures that all changes are committed atomically, improving the overall maintainability of the organization initialization process.

* refactor: Introduce InitPendingOrganizationRequest model and update InitPendingOrganizationVNextAsync method

- Created InitPendingOrganizationRequest to encapsulate parameters for initializing a pending organization.
- Refactored InitPendingOrganizationVNextAsync method to accept the new request model instead of multiple parameters.
- Updated OrganizationUsersController to use the new request model for improved readability and maintainability.
- Adjusted related tests to accommodate the new request structure.

* Create database update action delegate for organization initialization.

* Add BuildVerifyUserEmailAction method to IUserRepository and implementations in UserRepository classes

- Introduced a new method in IUserRepository to create an action for verifying user emails.
- Implemented the method in both Dapper and Entity Framework UserRepository classes to update the email verification status of users.
- Ensured that the method checks if the user's email is already verified before updating.

* Add BuildCreateDefaultCollectionAction method to ICollectionRepository and implementations in CollectionRepository classes

- Introduced a new method in ICollectionRepository to build an action for creating a default collection with user access.
- Implemented the method in both Dapper and Entity Framework CollectionRepository classes to handle collection creation and user access assignments.
- Enhanced the functionality to support transaction execution for database operations.

* Add BuildConfirmOrganizationUserAction method to IOrganizationUserRepository and implementations in OrganizationUserRepository classes

- Introduced a new method in IOrganizationUserRepository to build an action for confirming an organization user.
- Implemented the method in both Dapper and Entity Framework OrganizationUserRepository classes to handle user confirmation and status updates.
- Enhanced the functionality to support transaction execution for database operations.

* Refactor organization initialization methods in IOrganizationRepository and implementations

- Introduced BuildUpdateOrganizationAction method to create an action for updating organization properties during initialization.
- Replaced the InitializePendingOrganizationAsync method with ExecuteOrganizationInitializationUpdatesAsync to handle multiple update actions in a single transaction.
- Updated Dapper and Entity Framework implementations to support the new action-based approach for organization initialization, enhancing transaction management and code clarity.

* Add integration tests for ExecuteOrganizationInitializationUpdatesAsync

* Refactor InitPendingOrganizationCommand to streamline organization initialization process

- Introduced methods for preparing organization and organization user for initialization.
- Replaced direct calls to repository methods with a new action-based approach for executing multiple database updates in a single transaction.
- Enhanced test cases to validate the new initialization logic and ensure proper handling of organization states.

* Refactor organization user acceptance tests to utilize feature flags

- Converted existing tests to use [Theory] with [InlineData] for feature flag variations.
- Updated assertions to reflect expected status codes based on feature flag state.
- Enhanced user confirmation checks to ensure proper linking and email verification after acceptance.
- Improved test coverage for organization initialization scenarios with and without collections.

* Refactor BuildVerifyUserEmailAction to accept User entity instead of user ID

- Updated IUserRepository and its implementations to change the parameter of BuildVerifyUserEmailAction from Guid userId to User user.
- Modified related repository methods in Dapper and Entity Framework to utilize the User entity for email verification.
- Adjusted tests to reflect the new method signature, ensuring proper functionality and integration with the updated user verification process.

* Revert "Refactor BuildVerifyUserEmailAction to accept User entity instead of user ID"

This reverts commit 71047bee2a.

* Enhance InitPendingOrganizationCommand for null safety and error handling

- Removed nullable disable directive to enable null safety checks.
- Added a null check for the organization retrieval, throwing a BadRequestException if not found.
- Updated validation methods to return nullable Error types, improving error handling in the organization initialization process.

* Add remarks to IInitPendingOrganizationCommand for clarity on organization initialization

- Enhanced the documentation for the InitPendingOrganizationCommand interface by adding remarks to clarify the role of the user initializing the organization.
- Explained the default state assumptions during validation, emphasizing that no policies are enforced at this stage.

* Implement InitPendingOrganizationValidator for improved organization initialization validation

- Introduced IInitPendingOrganizationValidator interface and its implementation to encapsulate validation logic for organization initialization.
- Refactored InitPendingOrganizationCommand to utilize the new validator for token validation, user email matching, organization state checks, and policy enforcement.
- Enhanced dependency injection in OrganizationServiceCollectionExtensions to include the new validator.
- Added comprehensive unit tests for the validator to ensure robust validation logic and error handling.

* Update documentation in IInitPendingOrganizationCommand to clarify organization initialization process

- Revised the summary comment to specify that the method initializes a pending organization created via the Bitwarden Portal on behalf of a Reseller.
- Added a reference to the ResellerClientOrganizationSignUpCommand for better context.
- Emphasized the confirmation of the first owner during the initialization process.

* Update InitPendingOrganizationRequest to allow optional collection name

- Modified the CollectionName property to be nullable, allowing for no collection to be created if the value is null or empty.
- Enhanced documentation to clarify the optional nature of the CollectionName parameter.

* Fix nullability issue in InitPendingOrganizationCommand by enforcing non-null collection name assignment

* Refactor organization key handling in InitPendingOrganization features. Updated OrganizationUsersController to use new key pair data structure. Adjusted InitPendingOrganizationCommand and InitPendingOrganizationRequest to reflect changes in key management.

* Update organization key handling to use the name EncryptedOrganizationSymmetricKey. Refactor OrganizationUsersController, InitPendingOrganizationCommand, and InitPendingOrganizationRequest for consistency in key management.

* Refactor InitPendingOrganizationCommand to utilize TimeProvider for date handling. Updated methods to replace direct DateTime calls with _timeProvider.GetUtcNow().

* Refactor InitPendingOrganization validation methods to rename ValidateBusinessRulesAsync to ValidateFreeOrganizationLimitAsync for clarity and consistency. Updated related command and test files accordingly.

* Refactor InitPendingOrganizationCommand and related classes to streamline validation logic. Introduced InitPendingOrganizationValidationRequest for enriched validation context and updated methods to improve clarity and consistency in error handling. Adjusted tests to reflect changes in validation flow.

* Remove unused dependencies from InitPendingOrganizationCommand

* Refactor InitPendingOrganizationCommand to streamline organization initialization process. Replaced multiple update actions with a single atomic operation for organization and owner confirmation. Updated related repository interfaces and methods for improved clarity and consistency in transaction handling.

* Remove commented-out regions and clean up whitespace in InitPendingOrganizationCommandTests for improved readability.

* Remove unnecessary null check for organization in InitPendingOrganizationCommand

* Revert "Remove unnecessary null check for organization in InitPendingOrganizationCommand"

This reverts commit 1ad7148fc9.

* Refactor organization initialization actions to use DbConnection and DbTransaction instead of SqlConnection and SqlTransaction. Update related interfaces and implementations across repositories for improved database transaction handling.

* Refactor organization and organization user update logic to use null checks for entity existence. Throw exceptions for not found entities to improve error handling during initialization.

* Update InitPendingOrganizationCommandTests to use SendConfirmationAsync for email notifications and added missing using directive for OrganizationConfirmation.

* Remove unnecessary blank lines from CollectionRepository and UserRepository classes for improved code readability.

* Remove redundant test cases from OrganizationUsersControllerAcceptInitTests

* Enhance InitPendingOrganizationCommandTests to validate organization and user properties in repository interactions

* Update RefactorOrgAcceptInit feature flag key to new identifier pm-33082-refactor-org-accept-init
2026-03-03 17:50:31 +00:00