Files
server/test/Api.IntegrationTest/Helpers/OrganizationTestHelpers.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

229 lines
9.9 KiB
C#
Raw Permalink Normal View History

using System.Diagnostics;
using Bit.Api.IntegrationTest.Factories;
using Bit.Core.AdminConsole.Entities;
[PM-22241] Add DefaultUserCollectionName support to bulk organization user confirmation (#6153) * Implement GetByOrganizationAsync method in PolicyRequirementQuery and add corresponding unit tests * Refactor ConfirmOrganizationUserCommand for clarity and add bulk support * Update ConfirmOrganizationUserCommandTests to use GetByOrganizationAsync for policy requirement queries * Add DefaultUserCollectionName property to OrganizationUserBulkConfirmRequestModel with encryption attributes * Update ConfirmUsersAsync method to include DefaultUserCollectionName parameter in OrganizationUsersController * Add EnableOrganizationDataOwnershipPolicyAsync method to OrganizationTestHelpers * Add integration tests for confirming organization users in OrganizationUserControllerTests - Implemented Confirm_WithValidUser test to verify successful confirmation of a single user. - Added BulkConfirm_WithValidUsers test to ensure multiple users can be confirmed successfully. * Refactor organization user confirmation integration tests to also test when the organization data ownership policy is disabled * Refactor ConfirmOrganizationUserCommand to consolidate confirmation side effects handling - Replaced single and bulk confirmation side effect methods with a unified HandleConfirmationSideEffectsAsync method. - Updated related logic to handle confirmed organization users more efficiently. - Adjusted unit tests to reflect changes in the collection creation process for confirmed users. * Refactor OrganizationUserControllerTests to simplify feature flag handling and consolidate test logic - Removed redundant feature flag checks in Confirm and BulkConfirm tests. - Updated tests to directly enable the Organization Data Ownership policy without conditional checks. - Ensured verification of DefaultUserCollection for confirmed users remains intact. * Refactor OrganizationUserControllerTests to enhance clarity and reduce redundancy - Simplified user creation and confirmation logic in tests by introducing helper methods. - Consolidated verification of confirmed users and their associated collections. - Removed unnecessary comments and streamlined test flow for better readability.
2025-08-05 15:34:13 +01:00
using Bit.Core.AdminConsole.Enums;
using Bit.Core.AdminConsole.OrganizationFeatures.Organizations;
using Bit.Core.AdminConsole.Repositories;
using Bit.Core.Billing.Enums;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Models.Business;
using Bit.Core.Models.Data;
using Bit.Core.Repositories;
using Bit.IntegrationTestCommon.Factories;
namespace Bit.Api.IntegrationTest.Helpers;
public static class OrganizationTestHelpers
{
public static async Task<Tuple<Organization, OrganizationUser>> SignUpAsync<T>(WebApplicationFactoryBase<T> factory,
PlanType plan = PlanType.Free,
string ownerEmail = "integration-test@bitwarden.com",
string name = "Integration Test Org",
string billingEmail = "integration-test@bitwarden.com",
string ownerKey = "test-key",
int passwordManagerSeats = 0,
PaymentMethodType paymentMethod = PaymentMethodType.None) where T : class
{
var userRepository = factory.GetService<IUserRepository>();
var organizationSignUpCommand = factory.GetService<ICloudOrganizationSignUpCommand>();
var owner = await userRepository.GetByEmailAsync(ownerEmail);
var signUpResult = await organizationSignUpCommand.SignUpOrganizationAsync(new OrganizationSignup
{
Name = name,
BillingEmail = billingEmail,
Plan = plan,
OwnerKey = ownerKey,
Owner = owner,
AdditionalSeats = passwordManagerSeats,
PaymentMethodType = paymentMethod,
PaymentToken = "TOKEN",
TaxInfo = new TaxInfo
{
BillingAddressCountry = "US",
BillingAddressPostalCode = "12345"
}
});
Debug.Assert(signUpResult.OrganizationUser is not null);
return new Tuple<Organization, OrganizationUser>(signUpResult.Organization, signUpResult.OrganizationUser);
}
/// <summary>
/// Creates an OrganizationUser. The user account must already be created.
/// </summary>
public static async Task<OrganizationUser> CreateUserAsync<T>(
WebApplicationFactoryBase<T> factory,
Guid organizationId,
string userEmail,
OrganizationUserType type,
bool accessSecretsManager = false,
Permissions? permissions = null,
OrganizationUserStatusType userStatusType = OrganizationUserStatusType.Confirmed,
string? externalId = null
) where T : class
{
var userRepository = factory.GetService<IUserRepository>();
var organizationUserRepository = factory.GetService<IOrganizationUserRepository>();
var user = await userRepository.GetByEmailAsync(userEmail);
Debug.Assert(user is not null);
var orgUser = new OrganizationUser
{
OrganizationId = organizationId,
UserId = user.Id,
Key = null,
Type = type,
Status = userStatusType,
ExternalId = externalId,
AccessSecretsManager = accessSecretsManager,
Email = userEmail
};
if (permissions != null)
{
orgUser.SetPermissions(permissions);
}
await organizationUserRepository.CreateAsync(orgUser);
return orgUser;
}
/// <summary>
/// Creates a new User account with a unique email address and a corresponding OrganizationUser for
/// the specified organization.
/// </summary>
public static async Task<(string, OrganizationUser)> CreateNewUserWithAccountAsync(
ApiApplicationFactory factory,
Guid organizationId,
OrganizationUserType userType,
Permissions? permissions = null
)
{
var email = $"integration-test{Guid.NewGuid()}@bitwarden.com";
// Create user
await factory.LoginWithNewAccount(email);
// Create organizationUser
var organizationUser = await CreateUserAsync(factory, organizationId, email, userType,
permissions: permissions);
return (email, organizationUser);
}
[PM-11405] Account Management: Prevent a verified user from changing their email address (#4875) * Add check for managed user before purging account * Rename IOrganizationRepository.GetByClaimedUserDomainAsync to GetByVerifiedUserEmailDomainAsync and refactor to return a list. Remove ManagedByOrganizationId from ProfileResponseMode. Add ManagesActiveUser to ProfileOrganizationResponseModel * Rename the property ManagesActiveUser to UserIsManagedByOrganization * Remove whole class #nullable enable and add it to specific places * [PM-11405] Account Deprovisioning: Prevent a verified user from changing their email address * Remove unnecessary .ToList() * Refactor IUserService methods GetOrganizationsManagingUserAsync and IsManagedByAnyOrganizationAsync to not return nullable objects. Update ProfileOrganizationResponseModel.UserIsManagedByOrganization to not be nullable * Update error message when unable to purge vault for managed account * Update error message when unable to change email for managed account * Update expected error messages on unit tests * Add TestFeatureService to Api.IntegrationTest.Helpers and use it on ApiApplicationFactory to be able to enable specific features for each test * Add CreateVerifiedDomainAsync method to OrganizationTestHelpers * Add tests to AccountsControllerTest to prevent changing email for managed accounts * Remove setting the feature flag value in ApiApplicationFactory and set it on AccountsControllerTest * Remove TestFeatureService class from Api.IntegrationTest.Helpers
2024-10-28 16:12:13 +00:00
/// <summary>
/// Creates a VerifiedDomain for the specified organization.
/// </summary>
public static async Task CreateVerifiedDomainAsync(ApiApplicationFactory factory, Guid organizationId, string domain)
{
var organizationDomainRepository = factory.GetService<IOrganizationDomainRepository>();
var verifiedDomain = new OrganizationDomain
{
OrganizationId = organizationId,
DomainName = domain,
Txt = "btw+test18383838383"
};
verifiedDomain.SetVerifiedDate();
await organizationDomainRepository.CreateAsync(verifiedDomain);
}
public static async Task<Group> CreateGroup(ApiApplicationFactory factory, Guid organizationId)
{
var groupRepository = factory.GetService<IGroupRepository>();
var group = new Group
{
OrganizationId = organizationId,
Id = new Guid(),
ExternalId = "bwtest-externalId",
Name = "bwtest"
};
await groupRepository.CreateAsync(group, new List<CollectionAccessSelection>());
return group;
}
[PM-22241] Add DefaultUserCollectionName support to bulk organization user confirmation (#6153) * Implement GetByOrganizationAsync method in PolicyRequirementQuery and add corresponding unit tests * Refactor ConfirmOrganizationUserCommand for clarity and add bulk support * Update ConfirmOrganizationUserCommandTests to use GetByOrganizationAsync for policy requirement queries * Add DefaultUserCollectionName property to OrganizationUserBulkConfirmRequestModel with encryption attributes * Update ConfirmUsersAsync method to include DefaultUserCollectionName parameter in OrganizationUsersController * Add EnableOrganizationDataOwnershipPolicyAsync method to OrganizationTestHelpers * Add integration tests for confirming organization users in OrganizationUserControllerTests - Implemented Confirm_WithValidUser test to verify successful confirmation of a single user. - Added BulkConfirm_WithValidUsers test to ensure multiple users can be confirmed successfully. * Refactor organization user confirmation integration tests to also test when the organization data ownership policy is disabled * Refactor ConfirmOrganizationUserCommand to consolidate confirmation side effects handling - Replaced single and bulk confirmation side effect methods with a unified HandleConfirmationSideEffectsAsync method. - Updated related logic to handle confirmed organization users more efficiently. - Adjusted unit tests to reflect changes in the collection creation process for confirmed users. * Refactor OrganizationUserControllerTests to simplify feature flag handling and consolidate test logic - Removed redundant feature flag checks in Confirm and BulkConfirm tests. - Updated tests to directly enable the Organization Data Ownership policy without conditional checks. - Ensured verification of DefaultUserCollection for confirmed users remains intact. * Refactor OrganizationUserControllerTests to enhance clarity and reduce redundancy - Simplified user creation and confirmation logic in tests by introducing helper methods. - Consolidated verification of confirmed users and their associated collections. - Removed unnecessary comments and streamlined test flow for better readability.
2025-08-05 15:34:13 +01:00
/// <summary>
/// Creates a collection with optional user and group associations.
/// </summary>
public static async Task<Collection> CreateCollectionAsync(
ApiApplicationFactory factory,
Guid organizationId,
string name,
IEnumerable<CollectionAccessSelection>? users = null,
IEnumerable<CollectionAccessSelection>? groups = null,
string? externalId = null)
{
var collectionRepository = factory.GetService<ICollectionRepository>();
var collection = new Collection
{
OrganizationId = organizationId,
Name = name,
Type = CollectionType.SharedCollection,
ExternalId = externalId
};
await collectionRepository.CreateAsync(collection, groups, users);
return collection;
}
[PM-22241] Add DefaultUserCollectionName support to bulk organization user confirmation (#6153) * Implement GetByOrganizationAsync method in PolicyRequirementQuery and add corresponding unit tests * Refactor ConfirmOrganizationUserCommand for clarity and add bulk support * Update ConfirmOrganizationUserCommandTests to use GetByOrganizationAsync for policy requirement queries * Add DefaultUserCollectionName property to OrganizationUserBulkConfirmRequestModel with encryption attributes * Update ConfirmUsersAsync method to include DefaultUserCollectionName parameter in OrganizationUsersController * Add EnableOrganizationDataOwnershipPolicyAsync method to OrganizationTestHelpers * Add integration tests for confirming organization users in OrganizationUserControllerTests - Implemented Confirm_WithValidUser test to verify successful confirmation of a single user. - Added BulkConfirm_WithValidUsers test to ensure multiple users can be confirmed successfully. * Refactor organization user confirmation integration tests to also test when the organization data ownership policy is disabled * Refactor ConfirmOrganizationUserCommand to consolidate confirmation side effects handling - Replaced single and bulk confirmation side effect methods with a unified HandleConfirmationSideEffectsAsync method. - Updated related logic to handle confirmed organization users more efficiently. - Adjusted unit tests to reflect changes in the collection creation process for confirmed users. * Refactor OrganizationUserControllerTests to simplify feature flag handling and consolidate test logic - Removed redundant feature flag checks in Confirm and BulkConfirm tests. - Updated tests to directly enable the Organization Data Ownership policy without conditional checks. - Ensured verification of DefaultUserCollection for confirmed users remains intact. * Refactor OrganizationUserControllerTests to enhance clarity and reduce redundancy - Simplified user creation and confirmation logic in tests by introducing helper methods. - Consolidated verification of confirmed users and their associated collections. - Removed unnecessary comments and streamlined test flow for better readability.
2025-08-05 15:34:13 +01:00
/// <summary>
/// Enables the Organization Data Ownership policy for the specified organization.
/// </summary>
public static async Task EnableOrganizationDataOwnershipPolicyAsync<T>(
WebApplicationFactoryBase<T> factory,
Guid organizationId) where T : class
{
var policyRepository = factory.GetService<IPolicyRepository>();
var policy = new Policy
{
OrganizationId = organizationId,
Type = PolicyType.OrganizationDataOwnership,
Enabled = true
};
await policyRepository.CreateAsync(policy);
}
[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
/// <summary>
/// Generates a unique random domain name for testing purposes.
/// </summary>
/// <returns>A domain string like "a1b2c3d4.com"</returns>
public static string GenerateRandomDomain()
{
return $"{Guid.NewGuid().ToString("N").Substring(0, 8)}.com";
}
/// <summary>
/// Creates a user account without a Master Password and adds them as a member to the specified organization.
/// </summary>
public static async Task<(User User, OrganizationUser OrganizationUser)> CreateUserWithoutMasterPasswordAsync(ApiApplicationFactory factory, string email, Guid organizationId)
{
var userRepository = factory.GetService<IUserRepository>();
var user = await userRepository.CreateAsync(new User
{
Email = email,
Culture = "en-US",
SecurityStamp = "D7ZH62BWAZ5R5CASKULCDDIQGKDA2EJ6",
PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwMj7W00xS7H0NWasGn7PfEq8VfH3fa5XuZucsKxLLRAHHZk0xGRZJH2lFIznizv3GpF8vzhHhe9VpmMkrdIa5oWhwHpy+D7Z1QCQxuUXzvMKpa95GOntr89nN/mWKpk6abjgjmDcqFJ0lhDqkKnDfes+d8BBd5oEA8p41/Ykz7OfG7AiktVBpTQFW09MQh1NOvcLxVgiUUVRPwNRKrOeCekWDtOjZhASMETv3kI1ogvhHukOQ3ztDzrxvmwnLQ+cXl1EeD8gQnGDp3QLiJqxPgh2EdmANh4IzjRexoDn6BqhRGqLLIoLAbbkoiNrd6NYujrWW0N8KMMoVEXuJL2g4wIDAQAB",
PrivateKey = "2.Ytudv+Qk3ET9hN8whqpuGg==|ijsFhmjaf1aaT9uz+IPhVTzMS+2W/ldAP8LdT5VyJaFdx4HSdLcWSZvz5xWuuW94zfv1Qh+p3iQIuZOr29G4jcx47rYtz4ssiFtB7Ia552ZeF+cb7uuVg40CIe7ycuJQITk00o8gots+wFnaEvk0Vjgycnqutm0jpeBJ1joWJWqTVgSsYdUGLu7PiJywQ9NgY4+bJXqadlcviS3rhPKJXtiXYJhqJqSw+vI0Yxp96MJ0HcFJk/LG22YJPTvL5kzuDq/Wzj40kj8blQ+ag+xHD4P/KJ/MppEB3OpDw3UoJ50Ek+YB9pOqGxZtvqMEzBDsgh0yoz1O992UnhaUqtJ5e9Bxy3PA6cJsdyn9npdu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d7EvpSkydwQu7QXn9+H4jxn6UEntNGxcL0xkG+xippvZEe+HBvcDD40efDQW1bDbILLjPb4rNRx4d3xaQnVNaF7L33osm5LgfXAQSwHJiURdkU4zmhtPP4zn0br0OdFlR3mPcrkeNeSvs7FxiKtD6n6s+av+4bKjbLL1OyuwmTnMilL6p+m8ldte0yos/r+zOuxWeI=|euhiXWXehYbFQhlAV6LIECSIPCIRaHbNdr9OI4cTPUM=",
ApiKey = "CfGrD4MoJu3NprOBZNL8tu5ocmtnmU",
KdfIterations = 600000
});
var organizationUser = await CreateUserAsync(factory, organizationId, user.Email,
OrganizationUserType.User, externalId: email);
return (user, organizationUser);
}
}