Commit Graph

69 Commits

Author SHA1 Message Date
Rui Tomé
9e4bef5ee7 [PM-34776/PM-37797] Add invite link email domain validation endpoint (#7683)
* Add email domain validation to OrganizationInviteLink

- Introduced IsEmailDomainAllowed method to check if an email's domain is permitted based on allowed domains.
- Added necessary using directives for MailAddress and domain sanitization utilities.

* Refactor OrganizationInviteLink by removing email domain validation

- Removed the IsEmailDomainAllowed method and associated using directives for MailAddress.
- Cleaned up the code by eliminating unused methods related to email domain validation.

* Add InviteLinkDomainValidator for email domain validation

- Introduced InviteLinkDomainValidator class with IsEmailDomainAllowed method to validate if an email's domain is in the list of allowed domains.
- Utilized MailAddress for email parsing and added domain sanitization logic.

* Add email domain validation endpoint for organization invite links

- Implemented ValidateEmailDomain method in OrganizationInviteLinksController to check if an email's domain is allowed based on the invite link's permitted domains.
- Created OrganizationInviteLinkValidateEmailDomainRequestModel for request validation and OrganizationInviteLinkValidateEmailDomainResponseModel for response formatting.
- Integrated IOrganizationInviteLinkRepository to retrieve invite link details by code.

* Add unit tests for InviteLinkDomainValidator

- Created InviteLinkDomainValidatorTests class to validate email domain functionality.
- Added tests for various scenarios including invalid emails, empty domain lists, and matching domains.
- Ensured comprehensive coverage of the IsEmailDomainAllowed method's behavior.

* Add integration test for email domain validation in OrganizationInviteLinksController

- Implemented a test to validate that an allowed email domain returns the expected result when checked against an organization invite link.
- Ensured the test verifies the creation of an invite link and the subsequent validation of an email domain against the allowed domains list.

* Add validation query and interface for organization invite link email domain

- Introduced ValidateOrganizationInviteLinkEmailDomainQuery class to validate if an email's domain is allowed based on the invite link's permitted domains.
- Created IValidateOrganizationInviteLinkEmailDomainQuery interface to define the validation method.
- Added unit tests for the validation query to ensure correct behavior for various scenarios, including link not found and domain matching.

* Refactor OrganizationInviteLinksController to use validation query for email domain

- Updated ValidateEmailDomain method to utilize IValidateOrganizationInviteLinkEmailDomainQuery for domain validation instead of directly accessing the repository.
- Removed unnecessary repository dependency and streamlined the response handling for validation results.
- Registered the new validation query in OrganizationServiceCollectionExtensions for dependency injection.

* Refactor InviteLinkDomainValidator and replace MailAddress usage with existing email validation method
2026-05-29 12:23:15 +01:00
Jared
970cacdc29 [PM-38273] feat(admin-console): Add InjectOrganizationAttribute and OrganizationModelBinder (#7659)
* feat(admin-console): Add InjectOrganizationAttribute and OrganizationModelBinder for automatic organization parameter binding

* feat(admin-console): Introduce BindOrganizationAttribute and OrganizationModelBinder for organization parameter binding with unit tests

* feat(admin-console): Update GetResetPasswordDetails to use BindOrganization for organization parameter

* fix(admin-console): Correct organization ID check in GetResetPasswordDetails method to use bound organization

* Refactor OrganizationUsersControllerTests to use bound organization in GetResetPasswordDetails method

- Updated test cases to pass the organization directly instead of relying on repository calls.
- Ensured that the tests correctly assert NotFoundException when the organization user does not match the bound organization.
- Improved clarity in test setup by explicitly binding the organization to the method calls.

* Fix UTF-8 BOM issue in BindOrganizationAttribute.cs

* Add integration tests for OrganizationUsersController's BindOrganization functionality

- Introduced OrganizationUsersControllerBindOrganizationTests to validate the behavior of the GET reset-password-details endpoint.
- Implemented tests for successful retrieval of reset password details, handling of non-existent organization users, and cases where the user belongs to a different organization.
- Ensured comprehensive coverage of scenarios to verify correct status responses and organization binding logic.
2026-05-28 13:06:25 -04:00
sven-bitwarden
83038f3dbf remove vNext policy endpoints (#7711) 2026-05-26 12:34:40 -05:00
Thomas Rittson
d903096a77 Move remaining Admin Password Reset code to AC Team (#7680) 2026-05-21 17:51:20 -04:00
Rui Tomé
7180015ed6 [PM-37251] Add public invite link GET status endpoint (#7656)
* Implement GetOrganizationInviteLinkStatusQuery to retrieve invite link status

- Added GetOrganizationInviteLinkStatusQuery class to handle fetching the status of an organization invite link based on its code.
- Introduced OrganizationInviteLinkStatus and OrganizationInviteLinkSsoStatus records to encapsulate the invite link status and SSO information.
- Created IGetOrganizationInviteLinkStatusQuery interface to define the contract for the query implementation.

* Add unit tests for GetOrganizationInviteLinkStatusQuery

- Introduced comprehensive unit tests for GetOrganizationInviteLinkStatusQuery to validate various scenarios including successful retrieval of invite link status, handling of not found errors, and seat availability checks.
- Utilized Xunit and NSubstitute for testing and mocking dependencies, ensuring robust coverage of the query's functionality.

* Add IGetOrganizationInviteLinkStatusQuery to service collection

- Registered IGetOrganizationInviteLinkStatusQuery with the service collection to enable retrieval of organization invite link status.
- This addition supports the recently implemented GetOrganizationInviteLinkStatusQuery functionality.

* Add OrganizationInviteLinksPublicController and response models

- Introduced OrganizationInviteLinksPublicController to handle requests for organization invite link status.
- Implemented GetStatus endpoint to retrieve the status of an invite link using its GUID code.
- Added OrganizationInviteLinkStatusResponseModel and OrganizationInviteLinkSsoResponseModel to structure the response data for the invite link status.
- Ensured the endpoint is accessible to anonymous users while requiring application authorization for other actions.

* Add integration tests for OrganizationInviteLinksPublicController

- Introduced integration tests for OrganizationInviteLinksPublicController to validate the GetStatus endpoint functionality.
- Implemented tests to ensure correct handling of existing invite links and appropriate responses for valid and not found scenarios.
- Utilized Xunit and NSubstitute for testing and mocking dependencies, enhancing test coverage for invite link status retrieval.

* Updated GetOrganizationInviteLinkStatusQuery to return SSO status based on organization settings, including UseSso and UsePolicies

* Move status endpoint into OrganizationInviteLinksController as POST

* Refactor OrganizationInviteLinkStatusResponseModel and OrganizationInviteLinkStatus to remove OrganizationId property

- Removed OrganizationId property from both OrganizationInviteLinkStatusResponseModel and OrganizationInviteLinkStatus records to streamline the data model.
- Updated constructors accordingly to reflect the changes in the response models.

* Refactor GetOrganizationInviteLinkStatusQuery to simplify organization checks

- Updated the logic in GetOrganizationInviteLinkStatusQuery to streamline organization validation by combining null and enabled checks.
- Removed the dependency on IApplicationCacheService and adjusted the seat availability logic to enhance clarity and efficiency.
- Modified the return statement to use organization name directly instead of organization ID.

* Add integration tests for OrganizationInviteLinksController

- Introduced a new test method to validate the GetStatus functionality for existing invite links in OrganizationInviteLinksControllerTests.
- Enhanced existing tests to ensure correct responses for valid and not found scenarios.
- Removed OrganizationInviteLinksPublicControllerTests as its functionality is now covered in the OrganizationInviteLinksControllerTests.

* Refactor OrganizationInviteLinksControllerTests

- Updated test methods in OrganizationInviteLinksControllerTests to utilize GetOrganizationInviteLinkStatusRequestModel instead of individual parameters.
- Added a new test case to handle scenarios where the invite link status is not available, returning a BadRequest response.
- Enhanced existing tests to ensure consistent handling of valid and not found scenarios.

* Update GetOrganizationInviteLinkStatusQueryTests to enable organization for invite link tests
2026-05-21 16:27:54 +01:00
Thomas Rittson
1c3dc375bd Move collections API code to AC Team (#7651) 2026-05-19 07:08:43 +10:00
Rui Tomé
1323d0fb6a [PM-25690] Create UpdateUserResetPasswordEnrollment command (#7594)
* Implement UpdateUserResetPasswordEnrollment command and interface for managing user password reset enrollment in organizations

* Add unit tests for UpdateUserResetPasswordEnrollmentCommand to validate user enrollment and error handling

* Add IUpdateUserResetPasswordEnrollmentCommand to service collection for user password reset enrollment management

* Add integration tests for OrganizationUsersController reset password enrollment functionality

* Refactor OrganizationUsersController to use IUpdateUserResetPasswordEnrollmentCommand for password reset enrollment updates

* Remove UpdateUserResetPasswordEnrollmentAsync method and related dependencies from IOrganizationService and OrganizationService implementations

* Update IUpdateUserResetPasswordEnrollmentCommand and UpdateUserResetPasswordEnrollmentCommand to support nullable resetPasswordKey

* Refactor unit tests for UpdateUserResetPasswordEnrollmentCommand to improve naming conventions and enhance clarity in test cases
2026-05-11 16:22:57 +01:00
Rui Tomé
3d08eec6c2 [PM-34389] Add refresh endpoint for organization invite links (#7588)
* [PM-34389] Add RefreshOrganizationInviteLinkRequestModel for handling invite link refresh requests

* [PM-34389] Add RefreshOrganizationInviteLinkRequest and IRefreshOrganizationInviteLinkCommand interface for invite link refresh functionality

* [PM-34389] Refactor IRefreshOrganizationInviteLinkCommand interface documentation for clarity and conciseness

* [PM-34389] Add InviteLinkEncryptedKeyRequired error for handling missing encrypted invite keys in invite link requests.

* [PM-34389] Remove InviteLinkEncryptedKeyRequired error from InviteLinks error handling.

* [PM-34389] Remove redundant key check in RefreshOrganizationInviteLinkCommand

* [PM-34389] Add IRefreshOrganizationInviteLinkCommand registration to service collection

* [PM-34389] Add unit tests for RefreshOrganizationInviteLinkCommand to validate invite link refresh functionality, including scenarios for valid input, missing links, and insufficient permissions.

* [PM-34389] Implement Refresh endpoint in OrganizationInviteLinksController to handle invite link refresh requests

* [PM-34389] Add integration tests for Refresh endpoint in OrganizationInviteLinksController, validating link replacement and domain consistency.

* [PM-34389] Implement RefreshAsync method in OrganizationInviteLinkRepository for atomic link replacement, ensuring transactional integrity during updates.

* [PM-34389] Add integration tests for RefreshAsync method in OrganizationInviteLinkRepository, verifying link replacement and rollback behavior on unique constraint violations.

* [PM-34389] Refactor RefreshOrganizationInviteLinkCommand to use RefreshAsync method for atomic link updates, simplifying invite link management.
2026-05-08 14:31:25 +01:00
Rui Tomé
ab00d4f452 [PM-34392] Add delete invite link endpoint (#7591)
* Add IDeleteOrganizationInviteLinkCommand interface for managing organization invite links

* Add DeleteOrganizationInviteLinkCommand and corresponding unit tests for invite link deletion functionality

* Add IDeleteOrganizationInviteLinkCommand to service collection for invite link deletion

* Add Delete endpoint to OrganizationInviteLinksController and corresponding integration test
2026-05-06 19:44:03 +01:00
Rui Tomé
5289a5fd8c [PM-34388] Add organization invite link update endpoint (#7560)
* Add InviteLinkDomainSanitizer utility for domain normalization

- Introduced InviteLinkDomainSanitizer class to normalize invite link domains by converting them to lowercase and removing blank entries.
- The SanitizeDomains method processes a list of domains, ensuring clean and valid entries for further use.

* Refactor CreateOrganizationInviteLinkCommand to use InviteLinkDomainSanitizer

* Add UpdateOrganizationInviteLinkRequest record for managing invite link updates

- Introduced a new record, UpdateOrganizationInviteLinkRequest, to encapsulate the data required for updating organization invite links.
- The record includes properties for OrganizationId and AllowedDomains, ensuring structured data handling for invite link modifications.

* Add UpdateOrganizationInviteLinkRequestModel for invite link updates

- Introduced UpdateOrganizationInviteLinkRequestModel class to facilitate the update of organization invite links.
- The model includes a required property for AllowedDomains, ensuring validation and structured data handling for invite link modifications.

* Add tests for UpdateOrganizationInviteLinkRequestModel validation

* Add unit tests for UpdateOrganizationInviteLinkCommand

- Introduced comprehensive tests for the UpdateOrganizationInviteLinkCommand, covering scenarios such as successful updates, handling of non-existing links, and validation of allowed domains.
- Ensured that the command behaves correctly under various conditions, including ability checks and input validation.

* Add UpdateOrganizationInviteLinkCommand and IUpdateOrganizationInviteLinkCommand interface

- Implemented UpdateOrganizationInviteLinkCommand to handle updates for organization invite links, including validation of allowed domains and organization abilities.
- Created IUpdateOrganizationInviteLinkCommand interface to define the contract for updating invite links, ensuring structured handling of update requests.

* Add IUpdateOrganizationInviteLinkCommand registration to service collection

- Registered the IUpdateOrganizationInviteLinkCommand interface with the service collection, enabling dependency injection for the UpdateOrganizationInviteLinkCommand functionality.

* Add Update endpoint to OrganizationInviteLinksController

- Implemented the Update method in OrganizationInviteLinksController to handle updates for organization invite links.
- The method utilizes the IUpdateOrganizationInviteLinkCommand to process update requests and returns the appropriate response model.
- Enhanced the controller's functionality to support invite link modifications, ensuring better management of organization invite links.

* Add unit tests for Update method in OrganizationInviteLinksController

- Implemented multiple test cases for the Update method, covering scenarios such as successful updates, handling of non-existing invite links, and validation errors for allowed domains.
- Ensured comprehensive coverage of the Update functionality to validate correct behavior and response models in various conditions.

* Add integration test for updating organization invite links

* fix(invite-link): add [MinLength(1)] to Update request model and matching test
2026-05-04 16:46:40 +01:00
Rui Tomé
5ae857002c [PM-34774] Add GET endpoint for organization invite links (#7534)
* Add Get method to OrganizationInviteLinksController for retrieving invite links by organization ID

- Implemented a new GET endpoint to fetch an invite link based on the organization ID.
- Integrated IOrganizationInviteLinkRepository to handle data retrieval.
- Updated tests to validate the new functionality, ensuring correct responses for existing and non-existing links.
- Refactored service registration for invite link commands to improve clarity.

* Add GetOrganizationInviteLinkQuery and IGetOrganizationInviteLinkQuery interface

- Implemented GetOrganizationInviteLinkQuery to retrieve invite links for organizations.
- Added IGetOrganizationInviteLinkQuery interface defining the contract for fetching invite links.
- Included error handling for cases where invite links are not available or do not exist.

* Add unit tests for GetOrganizationInviteLinkQuery

- Created GetOrganizationInviteLinkQueryTests to validate the functionality of retrieving organization invite links.
- Implemented tests for successful retrieval, handling cases where no link exists, and scenarios with insufficient permissions or null abilities.
- Ensured proper error handling and assertions for various outcomes in the query execution.

* Add InviteLinkNotFound error type for handling missing invite links

- Introduced InviteLinkNotFound record to represent a not found error for invite links.
- Enhanced error handling in the InviteLinks feature to provide clearer feedback when an invite link is not found.

* Add IGetOrganizationInviteLinkQuery to service collection

- Registered IGetOrganizationInviteLinkQuery with the service collection to enable dependency injection for retrieving organization invite links.
- This addition supports the functionality introduced in the GetOrganizationInviteLinkQuery implementation.

* Refactor OrganizationInviteLinksController to use IGetOrganizationInviteLinkQuery

- Updated OrganizationInviteLinksController to replace IOrganizationInviteLinkRepository with IGetOrganizationInviteLinkQuery for retrieving invite links.
- Enhanced the Get method to handle results more effectively, returning appropriate responses based on the query outcome.
- Modified unit tests to align with the new query implementation, ensuring proper handling of both found and not found scenarios.

* Set AllowedDomains for invite link in OrganizationInviteLinksControllerTests
2026-05-04 14:13:39 +01:00
Rui Tomé
2a52362d33 [PM-34387] Add organization invite link creation endpoint (#7477)
* Add ConflictError type

* Add generic Handle<T> and extract MapError on BaseAdminConsoleController

* Initialize Code property with a new GUID in OrganizationInviteLink class

* Add ICreateOrganizationInviteLinkCommand interface

* Add CreateOrganizationInviteLinkRequest record for invite link creation

* Add OrganizationInviteLink request and response models for invite link management

* Refactor ICreateOrganizationInviteLinkCommand interface to use CreateOrganizationInviteLinkRequest for invite link creation

* Add CreateOrganizationInviteLinkCommand class to handle invite link creation logic, including domain sanitization and validation checks.

* Add error handling for invite link creation with specific conflict and validation errors

* Add OrganizationInviteLink service commands to OrganizationServiceCollectionExtensions

* Add OrganizationInviteLinksController to manage invite link creation for organizations

* Add integration tests for OrganizationInviteLinksController and CreateOrganizationInviteLinkCommand to validate invite link creation logic, including success and error scenarios.

* Remove unnecessary blank line in OrganizationInviteLinksControllerTests class

* Refactor CreateOrganizationInviteLinkRequestModel to use required properties for AllowedDomains and EncryptedInviteKey

* Update CreateOrganizationInviteLinkCommand to validate allowed domains by using DomainNameValidator

* Add encryption validation attributes to CreateOrganizationInviteLinkRequestModel and implement unit tests for model validation

* Refactor OrganizationInviteLink to encapsulate AllowedDomains serialization logic within methods. Update OrganizationInviteLinkResponseModel to utilize new GetAllowedDomains method for improved clarity and maintainability.

* Enhance domain sanitization in CreateOrganizationInviteLinkCommand by converting domains to lowercase during trimming for improved consistency.

* Update OrganizationInviteLinksControllerTests to use a valid encrypted invite key constant for consistency in test cases.

* Add ability check for organization invite links in CreateOrganizationInviteLinkCommand

- Introduced a new method to verify if an organization can use invite links based on its ability.
- Added a new error type for cases where invite links are not available due to organizational plan restrictions.
- Updated tests to cover scenarios where the organization lacks the ability to create invite links.

* Add documentation for Code property in OrganizationInviteLink class

- Added XML summary comments to the Code property to clarify its purpose and generation method.
- Explained the choice of using Guid.NewGuid for the Code to avoid predictability and ensure uniqueness.

* Implement domain validation in CreateOrganizationInviteLinkRequestModel

- Added IValidatableObject implementation to CreateOrganizationInviteLinkRequestModel for domain validation.
- Introduced Validate method to check the format of allowed domains and return appropriate validation results.
- Updated tests to cover scenarios for invalid domain formats and mixed valid/invalid domains.
- Removed redundant domain validation logic from CreateOrganizationInviteLinkCommand.

* Remove outdated tests from CreateOrganizationInviteLinkRequestModelTests

- Deleted tests for validating EncryptedInviteKey and EncryptedOrgKey as they are no longer relevant.
- Cleaned up the test class to focus on current validation logic for allowed domains.

* Refactor GetAllowedDomains method in OrganizationInviteLink class

- Updated the GetAllowedDomains method to return an empty array instead of throwing a JsonException when deserialization fails.
- This change improves the method's resilience by providing a default value for invalid or missing allowed domains.

* Remove unused InviteLinkInvalidDomains error type from Errors.cs

- Deleted the InviteLinkInvalidDomains record as it is no longer needed.
- This cleanup aligns with recent changes in domain validation logic and improves code maintainability.

* Update OrganizationServiceCollectionExtensions to use TryAddScoped for command registration

- Changed the registration of ICreateOrganizationInviteLinkCommand to use TryAddScoped instead of AddScoped.

* Mock organization ability retrieval in OrganizationInviteLinksControllerTests

* Add ValidateSequenceAttribute for collection validation and corresponding unit tests

* Refactor CreateOrganizationInviteLinkRequestModel to use ValidateSequenceAttribute for domain validation and update unit tests for improved error handling.

* Enhance ValidateSequenceAttribute to handle null values and improve error messaging format

* Add empty line

* Refactor ValidateSequenceAttribute to support IEnumerable interface for improved type handling

* Refactor ValidateSequenceAttribute to improve validation logic and error handling for IEnumerable types

* Remove unused using directive for Microsoft.AspNetCore.Http.HttpResults in BaseAdminConsoleController.cs

* Add MinLength validation to AllowedDomains in CreateOrganizationInviteLinkRequestModel and implement unit test for empty AllowedDomains scenario

* Refactor CreateOrganizationInviteLinkCommandTests to move SetupAbility method for better organization and readability

* Add error handling methods in BaseAdminConsoleController for improved response management

* Update CreateOrganizationInviteLinkRequestModelTests to use array initialization syntax for AllowedDomains so that MinLength attribute works

* Refactor OrganizationInviteLinkResponseModel constructor for improved readability
2026-05-01 14:23:56 +01:00
Thomas Rittson
a18b600147 [PM-35489] Move collections to AC ownership - update namespaces (#7532)
* Update namespaces: Api

* Update namespaces: core commands
2026-04-27 17:57:03 -04:00
sven-bitwarden
1dcbf278eb Add revocation reasons (#7473) 2026-04-27 12:27:01 -05:00
Jared McCannon
471496c937 [PM-28045] - Org Key Validation (#7384)
* Requiring keys on create request models.

* Added tests.
2026-04-27 08:50:05 -05:00
Thomas Rittson
1e09ab4008 [PM-35489] Move collections to AC ownership (#7523) 2026-04-23 07:03:25 +10:00
Vincent Salucci
cd4e44cb04 chore: remove leftover indirect reference to create default location ff (#7499) 2026-04-18 09:10:48 +10:00
sven-bitwarden
911a5da476 Make PUT Policy identical to PUT Policy/VNext (#7485) 2026-04-17 11:28:26 -05:00
Jared McCannon
21a7e94dc9 [PM-32073] - Added Bulk Get Org Ability (#7476)
* Added bulk get method and cleaned up some test stuff.

* Changes from Code Review
2026-04-17 11:59:18 -04:00
Jimmy Vo
914d412206 [PM-32069] Add ExtendedProviderAbilityCacheService (#7447) 2026-04-17 08:45:15 -04:00
Thomas Rittson
bb5506e934 [PM-34595] Update provider controllers to use authz attribute (#7450)
* Also decouple ProviderClientsController from Billing Team code

* Also add noop authorize attribute where no additional
  authorization is required

* Also remove unused ICurrentContext getters
2026-04-17 07:49:49 +10:00
Jared McCannon
d9aef5c58f [PM-32068] - Org Ability Extended Cache (#7443)
* Added extended cache implementation for org ability.

* fixed up events

* Moved utilities to service class. Moved tests to integration tests - with specific endpoints tested. moved registration to ext method
2026-04-15 09:46:16 -05:00
Jared McCannon
f2141b93d2 [PM-34390] - Fixing Group/Provider User (#7431)
* Added attributes for all groups controller methods. Fixed ProviderUsers get endpoint. udpated tests.

* Added integration tests and removed faux regions
2026-04-14 07:38:14 +10:00
Jared
b3c8950838 [PM-26383] Remove feature flag from server-side for autoconfirm (#7402)
* Refactor organization user confirmation logic by removing direct feature flag checks. Updated related commands and tests to utilize policy requirements instead of feature service checks for automatic user confirmation. Cleaned up organization form view by simplifying checkbox rendering for automatic user confirmation.

* Refactor ProviderService to remove feature service dependency for automatic user confirmation. Updated logic to streamline policy requirement checks and cleaned up related tests by removing unnecessary feature flag assertions.

* Enhance tests for automatic user confirmation policy requirements. Updated multiple test classes to include checks for `AutomaticUserConfirmationPolicyRequirement`, ensuring no auto-confirm restrictions are applied by default. Refactored related assertions in `AcceptOrgUserCommandTests`, `ConfirmOrganizationUserCommandTests`, `RestoreOrganizationUserCommandTests`, and others to streamline compliance validation logic.

* Enhance tests for automatic user confirmation policy across multiple test classes. Added checks for `AutomaticUserConfirmationPolicyRequirement` in `ConfirmOrganizationUserCommandTests`, `RestoreOrganizationUserCommandTests`, and `SelfHostedOrganizationSignUpCommandTests`, ensuring compliance validation logic is streamlined and consistent. Updated assertions to reflect new policy requirements.

* Implement mock for AutomaticUserConfirmationPolicyRequirement in ProviderServiceTests to enhance test coverage for user confirmation policies.

* Update ProviderServiceTests to include mocks for AutomaticUserConfirmationPolicyRequirement, enhancing test coverage for user acceptance scenarios.

* Refactor test method names in EmergencyAccessServiceTests for clarity by removing feature flag references, improving readability and maintainability of the test suite.
2026-04-09 12:56:23 -04:00
Thomas Rittson
0918bfdda6 Add checks and tests to provider controllers (#7372) 2026-04-02 09:05:19 +10:00
Kyle Spearrin
30f9229b22 [PM-15489] 2fa account recovery (#7139)
* implementation plan

* feedback updates

* revert updates

* implementation plan

* feedback updates

* revert updates

* implement plan

* Revert "Merge branch '2fa-account-recovery' of github.com:bitwarden/server into 2fa-account-recovery"

This reverts commit 3be2d140f1, reversing
changes made to 9fb8d3891c.

* PR feedback

* revert claude  local settings

* lint fixes

* fix test models

* move new commands to v2 namespace.

* format

* fix swagger stuff

* update feature flag name
2026-03-30 10:48:43 -04:00
Rui Tomé
e09e63569c [PM-33086] Remove the feature flag RefactorOrgAcceptInit (#7287) 2026-03-26 12:36:07 +00:00
Thomas Rittson
cafe4ffce8 [PM-34049] Fix PoliciesController authorize attribute (#7303)
GetMasterPasswordPolicy incorrectly used the MemberRequirement
authz requirement. However, this endpoint needs to support users
who are in the invited state, and that only authorizes users who are
confirmed. Recreate previous logic inside a new attribute.
2026-03-25 19:27:38 +10:00
Rui Tomé
7c05036c01 [PM-19143] Fix custom permissions not persisting via InviteOrganizationUsersCommand (#7285) 2026-03-24 14:12:44 +00:00
Rui Tomé
454a6dbc81 [PM-19143] Refactor public API MembersController POST to use CommandResult pattern (#7182)
* Add CommandResultRefactor constant to FeatureFlagKeys in Constants.cs

* Add method to convert MemberCreateRequestModel to InviteOrganizationUsersRequest

- Introduced ToInviteRequest method for transforming MemberCreateRequestModel into InviteOrganizationUsersRequest.
- Enhanced model with additional using directives for improved functionality.

* Update GetInviterEmailAsync method to include a check for Guid.Empty to prevent unnecessary DB lookups

* Feature flag MembersController POST to use InviteOrganizationUsersCommand

Add a new code path behind the CommandResultRefactor feature flag that
replaces the legacy InviteUserAsync call with the InviteOrganizationUsersCommand.
Integration tests verify both paths produce identical results.

* Refactor feature flag for member invites from CommandResultRefactor to PublicMembersInviteRefactor in MembersController and update related tests.
2026-03-13 16:48:37 +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
Rui Tomé
9eccb0001d [PM-30327] Fix SingleOrg policy not revoking non-compliant users (#7001) 2026-02-24 10:54:51 +00:00
Jared McCannon
c1ee27f42c Fixes concurrency issue with auto confirm test (#6964) 2026-02-10 14:40:35 -06:00
Mick Letofsky
4eb9c4cf3c Enhance seeder with additional cipher types and architectural refactorings (#6935) 2026-02-04 19:27:09 +01:00
Mick Letofsky
5941e830d2 Refactor to correctly implement statics and remove hardcoded organization keys (#6924) 2026-01-30 16:03:56 +01:00
Thomas Rittson
80eec2df85 [PM-23768] Public API - add restore and revoke member endpoint (#6859)
* Add restore and revoke to public api

* Follow naming conventions

* Use POST instead of PUT

* hello claude

* Update test names

* Actually fix test names

* Add JsonConstructor attr

* Fix test
2026-01-27 12:11:15 -06:00
Rui Tomé
c8124667ee [PM-28842] Add validation to prevent excessive master password policy values (#6807)
* Enhance MasterPasswordPolicyData with validation attributes

Added data annotations for MinComplexity and MinLength properties to enforce validation rules. MinComplexity must be between 0 and 4, and MinLength must be between 12 and 128.

* Implement model validation in PolicyDataValidator and enhance error handling

Added a ValidateModel method to enforce validation rules for policy data. Updated error messages to provide clearer feedback on validation failures. Enhanced unit tests to cover new validation scenarios for MinLength and MinComplexity properties.

* Update PoliciesControllerTests to reflect new validation rules for MinComplexity and MinLength

Modified test cases to use updated values for MinComplexity (4) and MinLength (128). Added new tests to verify that excessive values for these properties return BadRequest responses. Ensured consistency across integration tests for both Admin and Public controllers.

* Enhance MasterPasswordPolicyData with XML documentation for properties

Added XML documentation comments for MinComplexity and MinLength properties to clarify their purpose and constraints. This improves code readability and provides better context for developers using the model.

* Add unit tests for PolicyDataValidator to validate minLength and minComplexity rules

Implemented new test cases to verify the behavior of the ValidateAndSerialize method in PolicyDataValidator. Tests cover scenarios for minimum and maximum values, as well as edge cases for invalid inputs, ensuring robust validation for MasterPassword policy data.
2026-01-26 11:38:06 +00:00
Jared McCannon
07b0721616 Removed old implementation and feature flag checks for bulk revoke. (#6827) 2026-01-13 08:39:27 -06:00
Rui Tomé
1b17d99bfd [PM-29555] Add self-revoke endpoint for declining organization data ownership policy (#6739)
* Add OrganizationUser_SelfRevoked event type to EventType enum

* Add SelfRevokeOrganizationUserCommand implementation and interface for user self-revocation from organizations

* Add unit tests for SelfRevokeOrganizationUserCommand to validate user self-revocation logic, including success scenarios and various failure conditions.

* Add ISelfRevokeOrganizationUserCommand registration to OrganizationServiceCollectionExtensions for user self-revocation functionality

* Add self-revoke user functionality to OrganizationUsersController with new endpoint for user-initiated revocation

* Add integration tests for self-revoke functionality in OrganizationUsersController, covering scenarios for eligible users, non-members, and users with owner/admin roles.

* Add unit test for SelfRevokeOrganizationUserCommand to validate behavior when a user attempts to self-revoke without confirmation. This test checks for a BadRequestException with an appropriate message.

* Add MemberRequirement class for organization membership authorization

- Implemented MemberRequirement to check if a user is a member of the organization.
- Added unit tests for MemberRequirement to validate authorization logic for different user types.

* Update authorization requirement for self-revoke endpoint and add integration test for provider users

- Changed authorization attribute from MemberOrProviderRequirement to MemberRequirement in the RevokeSelfAsync method.
- Added a new integration test to verify that provider users who are not members receive a forbidden response when attempting to revoke themselves.

* Add EligibleForSelfRevoke method to OrganizationDataOwnershipPolicyRequirement

- Implemented the EligibleForSelfRevoke method to determine if a user can self-revoke their data ownership based on their membership status and policy state.
- Added unit tests to validate the eligibility logic for confirmed, invited, and non-policy users, as well as for different organization IDs.

* Refactor self-revoke user command to enhance eligibility checks

- Updated the SelfRevokeOrganizationUserCommand to utilize policy requirements for determining user eligibility for self-revocation.
- Implemented checks to prevent the last owner from revoking themselves, ensuring organizational integrity.
- Modified unit tests to reflect changes in eligibility logic and added scenarios for confirmed owners and admins.
- Removed deprecated policy checks and streamlined the command's dependencies.

* Use CommandResult pattern in self-revoke command

* Clearer documentation
2026-01-06 11:25:14 +00:00
Vincent Salucci
35868c2a65 [PM-22434] Remove CreateDefaultLocation feature flag references (#6758)
* chore: remove ff ref from PoliciesController

* chore: remove ff ref from OrganizationExportController, refs PM-22434

* chore: remove ff ref from CiphersController, refs PM-22434

* chore: remove ff ref from ConfirmOrganizationUserCommand, refs PM-22434

* chore: remove ff refs from OrganizationDataOwnershipPolicyValidator, refs PM-22434

* chore: remove ff ref from OrganizationUserControllerTests, refs PM-22434

* chore: remove ff refs from ConfirmOrganizationUserCommandTests, refs PM-22434

* chore: remove ff refs from OrganizationDataOwnershipPolicyValidatorTests, refs PM-22434

* chore: format, refs PM-22434
2026-01-05 17:27:17 -06:00
Jared McCannon
2f893768f5 [PM-18718] Refactor Bulk Revoke Users (#6601) 2025-12-05 11:19:26 -06:00
Rui Tomé
80ee31b4fe [PM-25015] Add performance tests for Admin Console endpoints (#6235)
* Add GroupsRecipe to manage group creation and user relationships in organizations

* Add CollectionsRecipe to manage collection creation and user relationships in organizations

* Refactor OrganizationUsersControllerPerformanceTests to enhance performance testing and add new test cases

* Add OrganizationDomainRecipe to add verified domains for organizations

* Add more tests to OrganizationUsersControllerPerformanceTests and enhance seeding logic for organizations

- Updated performance tests to use dynamic domain generation for organization users.
- Refactored seeding methods in OrganizationWithUsersRecipe to accept user status and type.
- Modified AddToOrganization methods in CollectionsRecipe and GroupsRecipe to return created IDs.
- Adjusted DbSeederUtility to align with new seeding method signatures.

* Enhance OrganizationSeeder with additional configuration options and update seat calculation in OrganizationWithUsersRecipe to ensure a minimum of 1000 seats.

* Add performance tests for Groups, Organizations, Organization Users, and Provider Organizations controllers

- Introduced `GroupsControllerPerformanceTests` to validate the performance of the PutGroupAsync method.
- Added `OrganizationsControllerPerformanceTests` with multiple tests including DeleteOrganizationAsync, DeleteOrganizationWithTokenAsync, PostStorageAsync, and CreateWithoutPaymentAsync.
- Enhanced `OrganizationUsersControllerPerformanceTests` with DeleteSingleUserAccountAsync and InviteUsersAsync methods to test user account deletion and bulk invitations.
- Created `ProviderOrganizationsControllerPerformanceTests` to assess the performance of deleting provider organizations.

These tests ensure the reliability and efficiency of the respective controller actions under various scenarios.

* Refactor GroupsControllerPerformanceTests to use parameterized tests

- Renamed `GroupsControllerPerformanceTest` to `GroupsControllerPerformanceTests` for consistency.
- Updated `PutGroupAsync` method to use `[Theory]` with `InlineData` for dynamic user and collection counts.
- Adjusted organization user and collection seeding logic to utilize the new parameters.
- Enhanced logging to provide clearer performance metrics during tests.

* Update domain generation in GroupsControllerPerformanceTests for improved test consistency

* Remove ProviderOrganizationsControllerPerformanceTests

* Refactor performance tests for Groups, Organizations, and Organization Users controllers

- Updated method names for clarity and consistency, e.g., `PutGroupAsync` to `UpdateGroup_WithUsersAndCollections`.
- Enhanced test documentation with XML comments to describe the purpose of each test.
- Improved domain generation logic for consistency across tests.
- Adjusted logging to provide detailed performance metrics during test execution.
- Renamed several test methods to better reflect their functionality.

* Refactor performance tests in Organizations and Organization Users controllers

- Updated tests to use parameterized `[Theory]` attributes with `InlineData` for dynamic user, collection, and group counts.
- Enhanced logging to include detailed metrics such as user and collection counts during test execution.
- Marked several tests as skipped for performance considerations.
- Removed unused code and improved organization of test methods for clarity.

* Add bulk reinvite users performance test to OrganizationUsersControllerPerformanceTests

- Implemented a new performance test for the POST /organizations/{orgId}/users/reinvite endpoint.
- Utilized parameterized testing with `[Theory]` and `InlineData` to evaluate performance with varying user counts.
- Enhanced logging to capture request duration and response status for better performance insights.
- Updated OrganizationSeeder to conditionally set email based on user status during seeding.

* Refactor domain generation in performance tests to use OrganizationTestHelpers

- Updated domain generation logic in GroupsControllerPerformanceTests, OrganizationsControllerPerformanceTests, and OrganizationUsersControllerPerformanceTests to utilize the new GenerateRandomDomain method from OrganizationTestHelpers.
- This change enhances consistency and readability across the tests by centralizing domain generation logic.

* Update CollectionsRecipe to have better readability

* Update GroupsRecipe to have better readability

* Refactor authentication in performance tests to use centralized helper method. This change reduces code duplication across Groups, Organizations, and OrganizationUsers controller tests by implementing the `AuthenticateClientAsync` method in a new `PerformanceTestHelpers` class.

* Refactor OrganizationUsersControllerPerformanceTests to filter organization users by OrganizationId.

* Refactor CreateOrganizationUser method to improve handling of user status and key assignment based on invitation and confirmation states.

* Add XML documentation for CreateOrganizationUser method to clarify user status handling
2025-12-05 14:22:00 +00:00
Vincent Salucci
28e9c24f33 [PM-25584] [PM-25585] Remove feature flag - recover provider accounts (#6673)
* chore: remove ff from OrganizationUsersController, refs PM-25584

* chore: update tests with reference to ff, refs PM-25584

* chore: remove ff definition, refs PM-25585

* chore: dotnet format, refs PM-25584
2025-12-02 23:23:58 -06:00
Thomas Rittson
35b4b0754c [PM-25913] Fix owners unable to rename provider-managed organization (#6599)
And other refactors:
- move update organization method to a command
- separate authorization from business logic
- add tests
- move Billing Team logic into their service
2025-11-26 07:38:01 +10:00
Alex Morask
f595818ede [PM-24549] Remove feature flag: use-pricing-service (#6567)
* Remove feature flag and move StaticStore plans to MockPlans for tests

* Remove old plan models / move sponsored plans out of StaticStore

* Run dotnet format

* Add pricing URI to Development appsettings for local development and integration tests

* Updated Api Integration tests to get current plan type

* Run dotnet format

* Fix failing tests
2025-11-19 09:53:30 -06:00
Jared McCannon
1eb396cb40 [PM-26636] - Auto Confirm Org User Command (#6488)
* Adding auto confirm endpoint and initial command work.

* Adding validator

* Finished command implementation.

* Enabled the feature renomved used method. Enabled the policy in the tests.

* Added extension functions to allow for railroad programming.

* Removed guid from route template. Added xml docs

* Added validation for command.

* Added default collection creation to command.

* formatting.

* Added additional error types and mapped to appropriate results.

* Added tests for auto confirm validator

* Adding tests

* fixing file name

* Cleaned up OrgUserController. Added integration tests.

* Consolidated CommandResult and validation result stuff into a v2 directory.

* changing result to match handle method.

* Moves validation thenasync method.

* Added brackets.

* Updated XML comment

* Adding idempotency comment.

* Fixed up merge problems. Fixed return types for handle.

* Renamed to ValidationRequest

* I added some methods for CommandResult to cover some future use cases. Added ApplyAsync method to execute multiple functions against CommandResult without an error stopping the workflow for side-effects.

* Fixed up logic around should create default colleciton. Added more methods for chaining ValidationResult together. Added logic for user type.

* Clearing nullable enable.

* Fixed up validator tests.

* Tests for auto confirm command

* Fixed up command result and AutoConfirmCommand.

* Removed some unused methods.

* Moved autoconfirm tests to their own class.

* Moved some stuff around. Need to clean up creation of accepted org user yet.

* Moved some more code around. Folded Key into accepted constructor. removed unneeded tests since key and accepted are now a part of AcceptedOrgUser Creation.

* Clean up clean up everybody everywhere. Clean up clean up everybody do your share.

* Another quick one

* Removed aggregate Errors.cs

* Cleaned up validator and fixed up tests.

* Fixed auto confirm repo

* Cleaned up command tests.

* Unused method.

* Restoring Bulk command back to what it was. deleted handle method for bulk.

* Remove unused method.

* removed unnecssary lines and comments

* fixed layout.

* Fixed test.

* fixed spelling mistake. removed unused import.

* Update test/Core.Test/AdminConsole/OrganizationFeatures/OrganizationUsers/AutoConfirmUsers/AutomaticallyConfirmUsersCommandTests.cs

Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>

* Ensuring collection is created before full sync. Cleaning up tests and added a few more. Added check that the policy is enabled.

* Added org cleanup

* Lowering to 5 to see if  that helps the runner.

* 🤷

* Trying this

* Maybe this time will be different.

* seeing if awaiting and checking independently will work in ci

* I figured it out. Locally, it would be fast enough to all return NoContent, however in CI, its slow enough for it to return 400 due to the user already being confirmed via validation.

* Updated tests and validator

* Fixed name

---------

Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>
2025-11-19 08:09:48 -06:00
Rui Tomé
e7f3b6b12f [PM-26430] Remove Type property from PolicyRequestModel to use route parameter only (#6472)
* Enhance PolicyRequestModel and SavePolicyRequest with validation for policy data and metadata.

* Add integration tests for policy updates to validate handling of invalid data types in PolicyRequestModel and SavePolicyRequest.

* Add missing using

* Update PolicyRequestModel for null safety by making Data and ValidateAndSerializePolicyData nullable

* Add integration tests for public PoliciesController to validate handling of invalid data types in policy updates.

* Add PolicyDataValidator class for validating and serializing policy data and metadata based on policy type.

* Refactor PolicyRequestModel, SavePolicyRequest, and PolicyUpdateRequestModel to utilize PolicyDataValidator for data validation and serialization, removing redundant methods and improving code clarity.

* Update PolicyRequestModel and SavePolicyRequest to initialize Data and Metadata properties with empty dictionaries.

* Refactor PolicyDataValidator to remove null checks for input data in validation methods

* Rename test methods in SavePolicyRequestTests to reflect handling of empty data and metadata, and remove null assignments in test cases for improved clarity.

* Remove Type property from PolicyRequestModel to use route parameter only

* Run dotnet format

* Enhance error handling in PolicyDataValidator to include field-specific details in BadRequestException messages.

* Enhance PoliciesControllerTests to verify error messages for BadRequest responses by checking for specific field names in the response content.

* refactor: Update PolicyRequestModel and SavePolicyRequest to use nullable dictionaries for Data and Metadata properties; enhance validation methods in PolicyDataValidator to handle null cases.

* test: Add integration tests for handling policies with null data in PoliciesController

* fix: Catch specific JsonException in PolicyDataValidator to improve error handling

* test: Add unit tests for PolicyDataValidator to validate and serialize policy data and metadata

* test: Remove PolicyType from PolicyRequestModel in PoliciesControllerTests

* test: Update PolicyDataValidatorTests to validate organization data ownership metadata

* Refactor PoliciesControllerTests to include policy type in PutVNext method calls
2025-11-10 15:27:44 +00:00
Rui Tomé
1e2e4b9d4d [PM-26429] Add validation to policy data and metadata (#6460)
* Enhance PolicyRequestModel and SavePolicyRequest with validation for policy data and metadata.

* Add integration tests for policy updates to validate handling of invalid data types in PolicyRequestModel and SavePolicyRequest.

* Add missing using

* Update PolicyRequestModel for null safety by making Data and ValidateAndSerializePolicyData nullable

* Add integration tests for public PoliciesController to validate handling of invalid data types in policy updates.

* Add PolicyDataValidator class for validating and serializing policy data and metadata based on policy type.

* Refactor PolicyRequestModel, SavePolicyRequest, and PolicyUpdateRequestModel to utilize PolicyDataValidator for data validation and serialization, removing redundant methods and improving code clarity.

* Update PolicyRequestModel and SavePolicyRequest to initialize Data and Metadata properties with empty dictionaries.

* Refactor PolicyDataValidator to remove null checks for input data in validation methods

* Rename test methods in SavePolicyRequestTests to reflect handling of empty data and metadata, and remove null assignments in test cases for improved clarity.

* Enhance error handling in PolicyDataValidator to include field-specific details in BadRequestException messages.

* Enhance PoliciesControllerTests to verify error messages for BadRequest responses by checking for specific field names in the response content.

* refactor: Update PolicyRequestModel and SavePolicyRequest to use nullable dictionaries for Data and Metadata properties; enhance validation methods in PolicyDataValidator to handle null cases.

* test: Add integration tests for handling policies with null data in PoliciesController

* fix: Catch specific JsonException in PolicyDataValidator to improve error handling

* test: Add unit tests for PolicyDataValidator to validate and serialize policy data and metadata

* test: Update PolicyDataValidatorTests to validate organization data ownership metadata
2025-11-03 15:44:44 +00:00
Rui Tomé
de56b7f327 [PM-26099] Update public list members endpoint to include collections (#6503)
* Add CreateCollectionAsync method to OrganizationTestHelpers for collection creation with user and group associations

* Update public MembersController List endpoint to include associated collections in member response model

* Update MembersControllerTests to validate collection associations in List endpoint. Add JsonConstructor to AssociationWithPermissionsResponseModel

* Refactor MembersController by removing unused IUserService and IApplicationCacheService dependencies.

* Remove nullable disable directive from Public MembersController
2025-11-03 15:24:40 +00:00
Thomas Rittson
e11458196c [PM-24192] Move account recovery logic to command (#6184)
* Move account recovery logic to command
  (temporarily duplicated behind feature flag)

* Move permission checks to authorization handler

* Prevent user from recovering provider member account
  unless they are also provider member
2025-11-01 07:55:25 +10:00