mirror of
https://github.com/bitwarden/server
synced 2026-02-09 13:09:58 +00:00
Merge branch 'main' into ac/pm-28842/cap-password-minimum-length
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
using System.Text.Json;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Bit.Core.AdminConsole.Entities;
|
||||
using Bit.Core.Auth.Enums;
|
||||
using Bit.Core.Auth.Models;
|
||||
using Bit.Core.Billing.Organizations.Models;
|
||||
using Bit.Test.Common.Helpers;
|
||||
using Xunit;
|
||||
|
||||
@@ -96,4 +99,124 @@ public class OrganizationTests
|
||||
var host = Assert.Contains("Host", (IDictionary<string, object>)duo.MetaData);
|
||||
Assert.Equal("Host_value", host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UseDisableSmAdsForUsers_DefaultValue_IsFalse()
|
||||
{
|
||||
var organization = new Organization();
|
||||
|
||||
Assert.False(organization.UseDisableSmAdsForUsers);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UseDisableSmAdsForUsers_CanBeSetToTrue()
|
||||
{
|
||||
var organization = new Organization
|
||||
{
|
||||
UseDisableSmAdsForUsers = true
|
||||
};
|
||||
|
||||
Assert.True(organization.UseDisableSmAdsForUsers);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateFromLicense_AppliesAllLicenseProperties()
|
||||
{
|
||||
// This test ensures that when a new property is added to OrganizationLicense,
|
||||
// it is also applied to the Organization in UpdateFromLicense().
|
||||
// This is the fourth step in the license synchronization pipeline:
|
||||
// Property → Constant → Claim → Extraction → Application
|
||||
|
||||
// 1. Get all public properties from OrganizationLicense
|
||||
var licenseProperties = typeof(OrganizationLicense)
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Select(p => p.Name)
|
||||
.ToHashSet();
|
||||
|
||||
// 2. Define properties that don't need to be applied to Organization
|
||||
var excludedProperties = new HashSet<string>
|
||||
{
|
||||
// Internal/computed properties
|
||||
"SignatureBytes", // Computed from Signature property
|
||||
"ValidLicenseVersion", // Internal property, not serialized
|
||||
"CurrentLicenseFileVersion", // Constant field, not an instance property
|
||||
"Hash", // Signature-related, not applied to org
|
||||
"Signature", // Signature-related, not applied to org
|
||||
"Token", // The JWT itself, not applied to org
|
||||
"Version", // License version, not stored on org
|
||||
|
||||
// Properties intentionally excluded from UpdateFromLicense
|
||||
"Id", // Self-hosted org has its own unique Guid
|
||||
"MaxStorageGb", // Not enforced for self-hosted (per comment in UpdateFromLicense)
|
||||
|
||||
// Properties not stored on Organization model
|
||||
"LicenseType", // Not a property on Organization
|
||||
"InstallationId", // Not a property on Organization
|
||||
"Issued", // Not a property on Organization
|
||||
"Refresh", // Not a property on Organization
|
||||
"ExpirationWithoutGracePeriod", // Not a property on Organization
|
||||
"Trial", // Not a property on Organization
|
||||
"Expires", // Mapped to ExpirationDate on Organization (different name)
|
||||
|
||||
// Deprecated properties not applied
|
||||
"LimitCollectionCreationDeletion", // Deprecated, not applied
|
||||
"AllowAdminAccessToAllCollectionItems", // Deprecated, not applied
|
||||
};
|
||||
|
||||
// 3. Get properties that should be applied
|
||||
var propertiesThatShouldBeApplied = licenseProperties
|
||||
.Except(excludedProperties)
|
||||
.ToHashSet();
|
||||
|
||||
// 4. Read Organization.UpdateFromLicense source code
|
||||
var organizationSourcePath = Path.Combine(
|
||||
Directory.GetCurrentDirectory(),
|
||||
"..", "..", "..", "..", "..", "src", "Core", "AdminConsole", "Entities", "Organization.cs");
|
||||
var sourceCode = File.ReadAllText(organizationSourcePath);
|
||||
|
||||
// 5. Find all property assignments in UpdateFromLicense method
|
||||
// Pattern matches: PropertyName = license.PropertyName
|
||||
// This regex looks for assignments like "Name = license.Name" or "ExpirationDate = license.Expires"
|
||||
var assignmentPattern = @"(\w+)\s*=\s*license\.(\w+)";
|
||||
var matches = Regex.Matches(sourceCode, assignmentPattern);
|
||||
|
||||
var appliedProperties = new HashSet<string>();
|
||||
foreach (Match match in matches)
|
||||
{
|
||||
// Get the license property name (right side of assignment)
|
||||
var licensePropertyName = match.Groups[2].Value;
|
||||
appliedProperties.Add(licensePropertyName);
|
||||
}
|
||||
|
||||
// Special case: Expires is mapped to ExpirationDate
|
||||
if (appliedProperties.Contains("Expires"))
|
||||
{
|
||||
appliedProperties.Add("Expires"); // Already added, but being explicit
|
||||
}
|
||||
|
||||
// 6. Find missing applications
|
||||
var missingApplications = propertiesThatShouldBeApplied
|
||||
.Except(appliedProperties)
|
||||
.OrderBy(p => p)
|
||||
.ToList();
|
||||
|
||||
// 7. Build error message with guidance
|
||||
var errorMessage = "";
|
||||
if (missingApplications.Any())
|
||||
{
|
||||
errorMessage = $"The following OrganizationLicense properties are NOT applied to Organization in UpdateFromLicense():\n";
|
||||
errorMessage += string.Join("\n", missingApplications.Select(p => $" - {p}"));
|
||||
errorMessage += "\n\nPlease add the following lines to Organization.UpdateFromLicense():\n";
|
||||
foreach (var prop in missingApplications)
|
||||
{
|
||||
errorMessage += $" {prop} = license.{prop};\n";
|
||||
}
|
||||
errorMessage += "\nNote: If the property maps to a different name on Organization (like Expires → ExpirationDate), adjust accordingly.";
|
||||
}
|
||||
|
||||
// 8. Assert - if this fails, the error message guides the developer to add the application
|
||||
Assert.True(
|
||||
!missingApplications.Any(),
|
||||
$"\n{errorMessage}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,6 +240,6 @@ public class SendOrganizationConfirmationCommandTests
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetSubject(string organizationName) => $"You Have Been Confirmed To {organizationName}";
|
||||
private static string GetSubject(string organizationName) => $"You can now access items from {organizationName}";
|
||||
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ public class AutomaticUserConfirmationPolicyEventHandlerTests
|
||||
OrganizationId = policyUpdate.OrganizationId,
|
||||
Type = OrganizationUserType.User,
|
||||
Status = OrganizationUserStatusType.Invited,
|
||||
UserId = Guid.NewGuid(),
|
||||
UserId = null,
|
||||
Email = "invited@example.com"
|
||||
};
|
||||
|
||||
@@ -302,6 +302,56 @@ public class AutomaticUserConfirmationPolicyEventHandlerTests
|
||||
Assert.True(string.IsNullOrEmpty(result));
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task ValidateAsync_EnablingPolicy_MixedUsersWithNullUserId_HandlesCorrectly(
|
||||
[PolicyUpdate(PolicyType.AutomaticUserConfirmation)] PolicyUpdate policyUpdate,
|
||||
Guid confirmedUserId,
|
||||
SutProvider<AutomaticUserConfirmationPolicyEventHandler> sutProvider)
|
||||
{
|
||||
// Arrange
|
||||
var invitedUser = new OrganizationUserUserDetails
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
OrganizationId = policyUpdate.OrganizationId,
|
||||
Type = OrganizationUserType.User,
|
||||
Status = OrganizationUserStatusType.Invited,
|
||||
UserId = null,
|
||||
Email = "invited@example.com"
|
||||
};
|
||||
|
||||
var confirmedUser = new OrganizationUserUserDetails
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
OrganizationId = policyUpdate.OrganizationId,
|
||||
Type = OrganizationUserType.User,
|
||||
Status = OrganizationUserStatusType.Confirmed,
|
||||
UserId = confirmedUserId,
|
||||
Email = "confirmed@example.com"
|
||||
};
|
||||
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetManyDetailsByOrganizationAsync(policyUpdate.OrganizationId)
|
||||
.Returns([invitedUser, confirmedUser]);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetManyByManyUsersAsync(Arg.Any<IEnumerable<Guid>>())
|
||||
.Returns([]);
|
||||
|
||||
sutProvider.GetDependency<IProviderUserRepository>()
|
||||
.GetManyByManyUsersAsync(Arg.Any<IEnumerable<Guid>>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.ValidateAsync(policyUpdate, null);
|
||||
|
||||
// Assert
|
||||
Assert.True(string.IsNullOrEmpty(result));
|
||||
|
||||
await sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.Received(1)
|
||||
.GetManyByManyUsersAsync(Arg.Is<IEnumerable<Guid>>(ids => ids.Count() == 1 && ids.First() == confirmedUserId));
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task ValidateAsync_EnablingPolicy_RevokedUsersIncluded_InComplianceCheck(
|
||||
[PolicyUpdate(PolicyType.AutomaticUserConfirmation)] PolicyUpdate policyUpdate,
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using Bit.Core.AdminConsole.Entities;
|
||||
using Bit.Core.Auth.Models.Data;
|
||||
using Bit.Core.Auth.UserFeatures.UserMasterPassword;
|
||||
using Bit.Core.Entities;
|
||||
using Bit.Core.Enums;
|
||||
using Bit.Core.Exceptions;
|
||||
using Bit.Core.KeyManagement.Models.Data;
|
||||
using Bit.Core.OrganizationFeatures.OrganizationUsers.Interfaces;
|
||||
using Bit.Core.Repositories;
|
||||
using Bit.Core.Services;
|
||||
@@ -21,106 +23,154 @@ public class SetInitialMasterPasswordCommandTests
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_Success(SutProvider<SetInitialMasterPasswordCommand> sutProvider,
|
||||
User user, string masterPassword, string key, string orgIdentifier,
|
||||
Organization org, OrganizationUser orgUser)
|
||||
User user, UserAccountKeysData accountKeys, KdfSettings kdfSettings,
|
||||
Organization org, OrganizationUser orgUser, string serverSideHash, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
user.Key = null;
|
||||
var model = CreateValidModel(user, accountKeys, kdfSettings, org.Identifier, masterPasswordHint);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgIdentifier)
|
||||
.GetByIdentifierAsync(org.Identifier)
|
||||
.Returns(org);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.Returns(orgUser);
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier);
|
||||
sutProvider.GetDependency<IPasswordHasher<User>>()
|
||||
.HashPassword(user, model.MasterPasswordAuthentication.MasterPasswordAuthenticationHash)
|
||||
.Returns(serverSideHash);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(IdentityResult.Success, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_UserIsNull_ThrowsArgumentNullException(SutProvider<SetInitialMasterPasswordCommand> sutProvider, string masterPassword, string key, string orgIdentifier)
|
||||
{
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(null, masterPassword, key, orgIdentifier));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_AlreadyHasPassword_ReturnsFalse(SutProvider<SetInitialMasterPasswordCommand> sutProvider, User user, string masterPassword, string key, string orgIdentifier)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = "ExistingPassword";
|
||||
// Mock SetMasterPassword to return a specific UpdateUserData delegate
|
||||
UpdateUserData mockUpdateUserData = (connection, transaction) => Task.CompletedTask;
|
||||
sutProvider.GetDependency<IUserRepository>()
|
||||
.SetMasterPassword(user.Id, model.MasterPasswordUnlock, serverSideHash, model.MasterPasswordHint)
|
||||
.Returns(mockUpdateUserData);
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier);
|
||||
await sutProvider.Sut.SetInitialMasterPasswordAsync(user, model);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.Succeeded);
|
||||
await sutProvider.GetDependency<IUserRepository>().Received(1)
|
||||
.SetV2AccountCryptographicStateAsync(
|
||||
user.Id,
|
||||
model.AccountKeys,
|
||||
Arg.Do<IEnumerable<UpdateUserData>>(actions =>
|
||||
{
|
||||
var actionsList = actions.ToList();
|
||||
Assert.Single(actionsList);
|
||||
Assert.Same(mockUpdateUserData, actionsList[0]);
|
||||
}));
|
||||
|
||||
await sutProvider.GetDependency<IEventService>().Received(1)
|
||||
.LogUserEventAsync(user.Id, EventType.User_ChangedPassword);
|
||||
|
||||
await sutProvider.GetDependency<IAcceptOrgUserCommand>().Received(1)
|
||||
.AcceptOrgUserAsync(orgUser, user, sutProvider.GetDependency<IUserService>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_NullOrgSsoIdentifier_ThrowsBadRequestException(
|
||||
SutProvider<SetInitialMasterPasswordCommand> sutProvider, User user, string masterPassword, string key)
|
||||
public async Task SetInitialMasterPassword_UserAlreadyHasPassword_ThrowsBadRequestException(
|
||||
SutProvider<SetInitialMasterPasswordCommand> sutProvider,
|
||||
User user, UserAccountKeysData accountKeys, KdfSettings kdfSettings, string orgSsoIdentifier, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
string orgSsoIdentifier = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
user.Key = "existing-key";
|
||||
var model = CreateValidModel(user, accountKeys, kdfSettings, orgSsoIdentifier, masterPasswordHint);
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(
|
||||
async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgSsoIdentifier));
|
||||
Assert.Equal("Organization SSO Identifier required.", exception.Message);
|
||||
async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, model));
|
||||
Assert.Equal("User already has a master password set.", exception.Message);
|
||||
}
|
||||
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_InvalidOrganization_Throws(SutProvider<SetInitialMasterPasswordCommand> sutProvider, User user, string masterPassword, string key, string orgIdentifier)
|
||||
public async Task SetInitialMasterPassword_AccountKeysNull_ThrowsBadRequestException(
|
||||
SutProvider<SetInitialMasterPasswordCommand> sutProvider,
|
||||
User user, KdfSettings kdfSettings, string orgSsoIdentifier, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
user.Key = null;
|
||||
var model = CreateValidModel(user, null, kdfSettings, orgSsoIdentifier, masterPasswordHint);
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(
|
||||
async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, model));
|
||||
Assert.Equal("Account keys are required.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData("wrong-salt", null)]
|
||||
[BitAutoData([null, "wrong-salt"])]
|
||||
[BitAutoData("wrong-salt", "different-wrong-salt")]
|
||||
public async Task SetInitialMasterPassword_InvalidSalt_ThrowsBadRequestException(
|
||||
string? authSaltOverride, string? unlockSaltOverride,
|
||||
SutProvider<SetInitialMasterPasswordCommand> sutProvider,
|
||||
User user, UserAccountKeysData accountKeys, KdfSettings kdfSettings, string orgSsoIdentifier, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.Key = null;
|
||||
var correctSalt = user.GetMasterPasswordSalt();
|
||||
var model = new SetInitialMasterPasswordDataModel
|
||||
{
|
||||
MasterPasswordAuthentication = new MasterPasswordAuthenticationData
|
||||
{
|
||||
Salt = authSaltOverride ?? correctSalt,
|
||||
MasterPasswordAuthenticationHash = "hash",
|
||||
Kdf = kdfSettings
|
||||
},
|
||||
MasterPasswordUnlock = new MasterPasswordUnlockData
|
||||
{
|
||||
Salt = unlockSaltOverride ?? correctSalt,
|
||||
MasterKeyWrappedUserKey = "wrapped-key",
|
||||
Kdf = kdfSettings
|
||||
},
|
||||
AccountKeys = accountKeys,
|
||||
OrgSsoIdentifier = orgSsoIdentifier,
|
||||
MasterPasswordHint = masterPasswordHint
|
||||
};
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(
|
||||
async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, model));
|
||||
Assert.Equal("Invalid master password salt.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_InvalidOrgSsoIdentifier_ThrowsBadRequestException(
|
||||
SutProvider<SetInitialMasterPasswordCommand> sutProvider,
|
||||
User user, UserAccountKeysData accountKeys, KdfSettings kdfSettings, string orgSsoIdentifier, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.Key = null;
|
||||
var model = CreateValidModel(user, accountKeys, kdfSettings, orgSsoIdentifier, masterPasswordHint);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgIdentifier)
|
||||
.GetByIdentifierAsync(orgSsoIdentifier)
|
||||
.ReturnsNull();
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier));
|
||||
Assert.Equal("Organization invalid.", exception.Message);
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(
|
||||
async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, model));
|
||||
Assert.Equal("Organization SSO identifier is invalid.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_UserNotFoundInOrganization_Throws(SutProvider<SetInitialMasterPasswordCommand> sutProvider, User user, string masterPassword, string key, Organization org)
|
||||
public async Task SetInitialMasterPassword_UserNotFoundInOrganization_ThrowsBadRequestException(
|
||||
SutProvider<SetInitialMasterPasswordCommand> sutProvider,
|
||||
User user, UserAccountKeysData accountKeys, KdfSettings kdfSettings, Organization org, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
user.Key = null;
|
||||
var model = CreateValidModel(user, accountKeys, kdfSettings, org.Identifier, masterPasswordHint);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(Arg.Any<string>())
|
||||
.GetByIdentifierAsync(org.Identifier)
|
||||
.Returns(org);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
@@ -128,67 +178,33 @@ public class SetInitialMasterPasswordCommandTests
|
||||
.ReturnsNull();
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, org.Identifier));
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(
|
||||
async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, model));
|
||||
Assert.Equal("User not found within organization.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_ConfirmedOrgUser_DoesNotCallAcceptOrgUser(SutProvider<SetInitialMasterPasswordCommand> sutProvider,
|
||||
User user, string masterPassword, string key, string orgIdentifier, Organization org, OrganizationUser orgUser)
|
||||
private static SetInitialMasterPasswordDataModel CreateValidModel(
|
||||
User user, UserAccountKeysData? accountKeys, KdfSettings kdfSettings,
|
||||
string orgSsoIdentifier, string? masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgIdentifier)
|
||||
.Returns(org);
|
||||
|
||||
orgUser.Status = OrganizationUserStatusType.Confirmed;
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.Returns(orgUser);
|
||||
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(IdentityResult.Success, result);
|
||||
await sutProvider.GetDependency<IAcceptOrgUserCommand>().DidNotReceive().AcceptOrgUserAsync(Arg.Any<OrganizationUser>(), Arg.Any<User>(), Arg.Any<IUserService>());
|
||||
var salt = user.GetMasterPasswordSalt();
|
||||
return new SetInitialMasterPasswordDataModel
|
||||
{
|
||||
MasterPasswordAuthentication = new MasterPasswordAuthenticationData
|
||||
{
|
||||
Salt = salt,
|
||||
MasterPasswordAuthenticationHash = "hash",
|
||||
Kdf = kdfSettings
|
||||
},
|
||||
MasterPasswordUnlock = new MasterPasswordUnlockData
|
||||
{
|
||||
Salt = salt,
|
||||
MasterKeyWrappedUserKey = "wrapped-key",
|
||||
Kdf = kdfSettings
|
||||
},
|
||||
AccountKeys = accountKeys,
|
||||
OrgSsoIdentifier = orgSsoIdentifier,
|
||||
MasterPasswordHint = masterPasswordHint
|
||||
};
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_InvitedOrgUser_CallsAcceptOrgUser(SutProvider<SetInitialMasterPasswordCommand> sutProvider,
|
||||
User user, string masterPassword, string key, string orgIdentifier, Organization org, OrganizationUser orgUser)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgIdentifier)
|
||||
.Returns(org);
|
||||
|
||||
orgUser.Status = OrganizationUserStatusType.Invited;
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.Returns(orgUser);
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(IdentityResult.Success, result);
|
||||
await sutProvider.GetDependency<IAcceptOrgUserCommand>().Received(1).AcceptOrgUserAsync(orgUser, user, sutProvider.GetDependency<IUserService>());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
using Bit.Core.AdminConsole.Entities;
|
||||
using Bit.Core.Auth.UserFeatures.UserMasterPassword;
|
||||
using Bit.Core.Entities;
|
||||
using Bit.Core.Enums;
|
||||
using Bit.Core.Exceptions;
|
||||
using Bit.Core.OrganizationFeatures.OrganizationUsers.Interfaces;
|
||||
using Bit.Core.Repositories;
|
||||
using Bit.Core.Services;
|
||||
using Bit.Test.Common.AutoFixture;
|
||||
using Bit.Test.Common.AutoFixture.Attributes;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ReturnsExtensions;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Core.Test.Auth.UserFeatures.UserMasterPassword;
|
||||
|
||||
[SutProviderCustomize]
|
||||
public class SetInitialMasterPasswordCommandV1Tests
|
||||
{
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_Success(SutProvider<SetInitialMasterPasswordCommandV1> sutProvider,
|
||||
User user, string masterPassword, string key, string orgIdentifier,
|
||||
Organization org, OrganizationUser orgUser)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgIdentifier)
|
||||
.Returns(org);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.Returns(orgUser);
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(IdentityResult.Success, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_UserIsNull_ThrowsArgumentNullException(SutProvider<SetInitialMasterPasswordCommandV1> sutProvider, string masterPassword, string key, string orgIdentifier)
|
||||
{
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(null, masterPassword, key, orgIdentifier));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_AlreadyHasPassword_ReturnsFalse(SutProvider<SetInitialMasterPasswordCommandV1> sutProvider, User user, string masterPassword, string key, string orgIdentifier)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = "ExistingPassword";
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.Succeeded);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_NullOrgSsoIdentifier_ThrowsBadRequestException(
|
||||
SutProvider<SetInitialMasterPasswordCommandV1> sutProvider, User user, string masterPassword, string key)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
string orgSsoIdentifier = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(
|
||||
async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgSsoIdentifier));
|
||||
Assert.Equal("Organization SSO Identifier required.", exception.Message);
|
||||
}
|
||||
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_InvalidOrganization_Throws(SutProvider<SetInitialMasterPasswordCommandV1> sutProvider, User user, string masterPassword, string key, string orgIdentifier)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgIdentifier)
|
||||
.ReturnsNull();
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier));
|
||||
Assert.Equal("Organization invalid.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_UserNotFoundInOrganization_Throws(SutProvider<SetInitialMasterPasswordCommandV1> sutProvider, User user, string masterPassword, string key, Organization org)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(Arg.Any<string>())
|
||||
.Returns(org);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.ReturnsNull();
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(async () => await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, org.Identifier));
|
||||
Assert.Equal("User not found within organization.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_ConfirmedOrgUser_DoesNotCallAcceptOrgUser(SutProvider<SetInitialMasterPasswordCommandV1> sutProvider,
|
||||
User user, string masterPassword, string key, string orgIdentifier, Organization org, OrganizationUser orgUser)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgIdentifier)
|
||||
.Returns(org);
|
||||
|
||||
orgUser.Status = OrganizationUserStatusType.Confirmed;
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.Returns(orgUser);
|
||||
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(IdentityResult.Success, result);
|
||||
await sutProvider.GetDependency<IAcceptOrgUserCommand>().DidNotReceive().AcceptOrgUserAsync(Arg.Any<OrganizationUser>(), Arg.Any<User>(), Arg.Any<IUserService>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task SetInitialMasterPassword_InvitedOrgUser_CallsAcceptOrgUser(SutProvider<SetInitialMasterPasswordCommandV1> sutProvider,
|
||||
User user, string masterPassword, string key, string orgIdentifier, Organization org, OrganizationUser orgUser)
|
||||
{
|
||||
// Arrange
|
||||
user.MasterPassword = null;
|
||||
|
||||
sutProvider.GetDependency<IUserService>()
|
||||
.UpdatePasswordHash(Arg.Any<User>(), Arg.Any<string>(), true, false)
|
||||
.Returns(IdentityResult.Success);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgIdentifier)
|
||||
.Returns(org);
|
||||
|
||||
orgUser.Status = OrganizationUserStatusType.Invited;
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.Returns(orgUser);
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.SetInitialMasterPasswordAsync(user, masterPassword, key, orgIdentifier);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(IdentityResult.Success, result);
|
||||
await sutProvider.GetDependency<IAcceptOrgUserCommand>().Received(1).AcceptOrgUserAsync(orgUser, user, sutProvider.GetDependency<IUserService>());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using Bit.Core.AdminConsole.Entities;
|
||||
using Bit.Core.Auth.Models.Data;
|
||||
using Bit.Core.Auth.UserFeatures.UserMasterPassword;
|
||||
using Bit.Core.Entities;
|
||||
using Bit.Core.Enums;
|
||||
using Bit.Core.Exceptions;
|
||||
using Bit.Core.KeyManagement.Models.Data;
|
||||
using Bit.Core.Repositories;
|
||||
using Bit.Core.Services;
|
||||
using Bit.Test.Common.AutoFixture;
|
||||
using Bit.Test.Common.AutoFixture.Attributes;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ReturnsExtensions;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Core.Test.Auth.UserFeatures.UserMasterPassword;
|
||||
|
||||
[SutProviderCustomize]
|
||||
public class TdeSetPasswordCommandTests
|
||||
{
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task OnboardMasterPassword_Success(SutProvider<TdeSetPasswordCommand> sutProvider,
|
||||
User user, KdfSettings kdfSettings,
|
||||
Organization org, OrganizationUser orgUser, string serverSideHash, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.Key = null;
|
||||
user.PublicKey = "public-key";
|
||||
user.PrivateKey = "private-key";
|
||||
var model = CreateValidModel(user, kdfSettings, org.Identifier, masterPasswordHint);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(org.Identifier)
|
||||
.Returns(org);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.Returns(orgUser);
|
||||
|
||||
sutProvider.GetDependency<IPasswordHasher<User>>()
|
||||
.HashPassword(user, model.MasterPasswordAuthentication.MasterPasswordAuthenticationHash)
|
||||
.Returns(serverSideHash);
|
||||
|
||||
// Mock SetMasterPassword to return a specific UpdateUserData delegate
|
||||
UpdateUserData mockUpdateUserData = (connection, transaction) => Task.CompletedTask;
|
||||
sutProvider.GetDependency<IUserRepository>()
|
||||
.SetMasterPassword(user.Id, model.MasterPasswordUnlock, serverSideHash, model.MasterPasswordHint)
|
||||
.Returns(mockUpdateUserData);
|
||||
|
||||
// Act
|
||||
await sutProvider.Sut.SetMasterPasswordAsync(user, model);
|
||||
|
||||
// Assert
|
||||
await sutProvider.GetDependency<IUserRepository>().Received(1)
|
||||
.UpdateUserDataAsync(Arg.Do<IEnumerable<UpdateUserData>>(actions =>
|
||||
{
|
||||
var actionsList = actions.ToList();
|
||||
Assert.Single(actionsList);
|
||||
Assert.Same(mockUpdateUserData, actionsList[0]);
|
||||
}));
|
||||
|
||||
await sutProvider.GetDependency<IEventService>().Received(1)
|
||||
.LogUserEventAsync(user.Id, EventType.User_ChangedPassword);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task OnboardMasterPassword_UserAlreadyHasPassword_ThrowsBadRequestException(
|
||||
SutProvider<TdeSetPasswordCommand> sutProvider,
|
||||
User user, KdfSettings kdfSettings, string orgSsoIdentifier, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.Key = "existing-key";
|
||||
var model = CreateValidModel(user, kdfSettings, orgSsoIdentifier, masterPasswordHint);
|
||||
|
||||
// Act & Assert
|
||||
var exception =
|
||||
await Assert.ThrowsAsync<BadRequestException>(async () =>
|
||||
await sutProvider.Sut.SetMasterPasswordAsync(user, model));
|
||||
Assert.Equal("User already has a master password set.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData([null, "private-key"])]
|
||||
[BitAutoData("public-key", null)]
|
||||
[BitAutoData([null, null])]
|
||||
public async Task OnboardMasterPassword_MissingAccountKeys_ThrowsBadRequestException(
|
||||
string? publicKey, string? privateKey,
|
||||
SutProvider<TdeSetPasswordCommand> sutProvider,
|
||||
User user, KdfSettings kdfSettings, string orgSsoIdentifier, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.Key = null;
|
||||
user.PublicKey = publicKey;
|
||||
user.PrivateKey = privateKey;
|
||||
var model = CreateValidModel(user, kdfSettings, orgSsoIdentifier, masterPasswordHint);
|
||||
|
||||
// Act & Assert
|
||||
var exception =
|
||||
await Assert.ThrowsAsync<BadRequestException>(async () =>
|
||||
await sutProvider.Sut.SetMasterPasswordAsync(user, model));
|
||||
Assert.Equal("TDE user account keys must be set before setting initial master password.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData("wrong-salt", null)]
|
||||
[BitAutoData([null, "wrong-salt"])]
|
||||
[BitAutoData("wrong-salt", "different-wrong-salt")]
|
||||
public async Task OnboardMasterPassword_InvalidSalt_ThrowsBadRequestException(
|
||||
string? authSaltOverride, string? unlockSaltOverride,
|
||||
SutProvider<TdeSetPasswordCommand> sutProvider,
|
||||
User user, KdfSettings kdfSettings, string orgSsoIdentifier, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.Key = null;
|
||||
user.PublicKey = "public-key";
|
||||
user.PrivateKey = "private-key";
|
||||
var correctSalt = user.GetMasterPasswordSalt();
|
||||
var model = new SetInitialMasterPasswordDataModel
|
||||
{
|
||||
MasterPasswordAuthentication =
|
||||
new MasterPasswordAuthenticationData
|
||||
{
|
||||
Salt = authSaltOverride ?? correctSalt,
|
||||
MasterPasswordAuthenticationHash = "hash",
|
||||
Kdf = kdfSettings
|
||||
},
|
||||
MasterPasswordUnlock = new MasterPasswordUnlockData
|
||||
{
|
||||
Salt = unlockSaltOverride ?? correctSalt,
|
||||
MasterKeyWrappedUserKey = "wrapped-key",
|
||||
Kdf = kdfSettings
|
||||
},
|
||||
AccountKeys = null,
|
||||
OrgSsoIdentifier = orgSsoIdentifier,
|
||||
MasterPasswordHint = masterPasswordHint
|
||||
};
|
||||
|
||||
// Act & Assert
|
||||
var exception =
|
||||
await Assert.ThrowsAsync<BadRequestException>(async () =>
|
||||
await sutProvider.Sut.SetMasterPasswordAsync(user, model));
|
||||
Assert.Equal("Invalid master password salt.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task OnboardMasterPassword_InvalidOrgSsoIdentifier_ThrowsBadRequestException(
|
||||
SutProvider<TdeSetPasswordCommand> sutProvider,
|
||||
User user, KdfSettings kdfSettings, string orgSsoIdentifier, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.Key = null;
|
||||
user.PublicKey = "public-key";
|
||||
user.PrivateKey = "private-key";
|
||||
var model = CreateValidModel(user, kdfSettings, orgSsoIdentifier, masterPasswordHint);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(orgSsoIdentifier)
|
||||
.ReturnsNull();
|
||||
|
||||
// Act & Assert
|
||||
var exception =
|
||||
await Assert.ThrowsAsync<BadRequestException>(async () =>
|
||||
await sutProvider.Sut.SetMasterPasswordAsync(user, model));
|
||||
Assert.Equal("Organization SSO identifier is invalid.", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task OnboardMasterPassword_UserNotFoundInOrganization_ThrowsBadRequestException(
|
||||
SutProvider<TdeSetPasswordCommand> sutProvider,
|
||||
User user, KdfSettings kdfSettings, Organization org, string masterPasswordHint)
|
||||
{
|
||||
// Arrange
|
||||
user.Key = null;
|
||||
user.PublicKey = "public-key";
|
||||
user.PrivateKey = "private-key";
|
||||
var model = CreateValidModel(user, kdfSettings, org.Identifier, masterPasswordHint);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationRepository>()
|
||||
.GetByIdentifierAsync(org.Identifier)
|
||||
.Returns(org);
|
||||
|
||||
sutProvider.GetDependency<IOrganizationUserRepository>()
|
||||
.GetByOrganizationAsync(org.Id, user.Id)
|
||||
.ReturnsNull();
|
||||
|
||||
// Act & Assert
|
||||
var exception =
|
||||
await Assert.ThrowsAsync<BadRequestException>(async () =>
|
||||
await sutProvider.Sut.SetMasterPasswordAsync(user, model));
|
||||
Assert.Equal("User not found within organization.", exception.Message);
|
||||
}
|
||||
|
||||
private static SetInitialMasterPasswordDataModel CreateValidModel(
|
||||
User user, KdfSettings kdfSettings, string orgSsoIdentifier, string? masterPasswordHint)
|
||||
{
|
||||
var salt = user.GetMasterPasswordSalt();
|
||||
return new SetInitialMasterPasswordDataModel
|
||||
{
|
||||
MasterPasswordAuthentication =
|
||||
new MasterPasswordAuthenticationData
|
||||
{
|
||||
Salt = salt,
|
||||
MasterPasswordAuthenticationHash = "hash",
|
||||
Kdf = kdfSettings
|
||||
},
|
||||
MasterPasswordUnlock =
|
||||
new MasterPasswordUnlockData
|
||||
{
|
||||
Salt = salt,
|
||||
MasterKeyWrappedUserKey = "wrapped-key",
|
||||
Kdf = kdfSettings
|
||||
},
|
||||
AccountKeys = null,
|
||||
OrgSsoIdentifier = orgSsoIdentifier,
|
||||
MasterPasswordHint = masterPasswordHint
|
||||
};
|
||||
}
|
||||
}
|
||||
68
test/Core.Test/Billing/Licenses/LicenseConstantsTests.cs
Normal file
68
test/Core.Test/Billing/Licenses/LicenseConstantsTests.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using System.Reflection;
|
||||
using Bit.Core.Billing.Licenses;
|
||||
using Bit.Core.Billing.Organizations.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Core.Test.Billing.Licenses;
|
||||
|
||||
public class LicenseConstantsTests
|
||||
{
|
||||
[Fact]
|
||||
public void OrganizationLicenseConstants_HasConstantForEveryLicenseProperty()
|
||||
{
|
||||
// This test ensures that when a new property is added to OrganizationLicense,
|
||||
// a corresponding constant is added to OrganizationLicenseConstants.
|
||||
// This is the first step in the license synchronization pipeline:
|
||||
// Property → Constant → Claim → Extraction → Application
|
||||
|
||||
// 1. Get all public properties from OrganizationLicense
|
||||
var licenseProperties = typeof(OrganizationLicense)
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Select(p => p.Name)
|
||||
.ToHashSet();
|
||||
|
||||
// 2. Get all constants from OrganizationLicenseConstants
|
||||
var constants = typeof(OrganizationLicenseConstants)
|
||||
.GetFields(BindingFlags.Public | BindingFlags.Static)
|
||||
.Where(f => f.IsLiteral && !f.IsInitOnly)
|
||||
.Select(f => f.GetValue(null) as string)
|
||||
.ToHashSet();
|
||||
|
||||
// 3. Define properties that don't need constants (internal/computed/non-claims properties)
|
||||
var excludedProperties = new HashSet<string>
|
||||
{
|
||||
"SignatureBytes", // Computed from Signature property
|
||||
"ValidLicenseVersion", // Internal property, not serialized
|
||||
"CurrentLicenseFileVersion", // Constant field, not an instance property
|
||||
"Hash", // Signature-related, not in claims system
|
||||
"Signature", // Signature-related, not in claims system
|
||||
"Token", // The JWT itself, not a claim within the token
|
||||
"Version" // Not in claims system (only in deprecated property-based licenses)
|
||||
};
|
||||
|
||||
// 4. Find license properties without corresponding constants
|
||||
var propertiesWithoutConstants = licenseProperties
|
||||
.Except(constants)
|
||||
.Except(excludedProperties)
|
||||
.OrderBy(p => p)
|
||||
.ToList();
|
||||
|
||||
// 5. Build error message with guidance
|
||||
var errorMessage = "";
|
||||
if (propertiesWithoutConstants.Any())
|
||||
{
|
||||
errorMessage = $"The following OrganizationLicense properties don't have constants in OrganizationLicenseConstants:\n";
|
||||
errorMessage += string.Join("\n", propertiesWithoutConstants.Select(p => $" - {p}"));
|
||||
errorMessage += "\n\nPlease add the following constants to OrganizationLicenseConstants:\n";
|
||||
foreach (var prop in propertiesWithoutConstants)
|
||||
{
|
||||
errorMessage += $" public const string {prop} = nameof({prop});\n";
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Assert - if this fails, the error message guides the developer to add the constant
|
||||
Assert.True(
|
||||
!propertiesWithoutConstants.Any(),
|
||||
$"\n{errorMessage}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Reflection;
|
||||
using Bit.Core.AdminConsole.Entities;
|
||||
using Bit.Core.Billing.Licenses;
|
||||
using Bit.Core.Billing.Licenses.Models;
|
||||
using Bit.Core.Billing.Licenses.Services.Implementations;
|
||||
using Bit.Core.Models.Business;
|
||||
using Bit.Test.Common.AutoFixture.Attributes;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Core.Test.Billing.Licenses.Services.Implementations;
|
||||
|
||||
public class OrganizationLicenseClaimsFactoryTests
|
||||
{
|
||||
[Theory, BitAutoData]
|
||||
public async Task GenerateClaims_CreatesClaimsForAllConstants(Organization organization)
|
||||
{
|
||||
// This test ensures that when a constant is added to OrganizationLicenseConstants,
|
||||
// it is also added to the OrganizationLicenseClaimsFactory to generate claims.
|
||||
// This is the second step in the license synchronization pipeline:
|
||||
// Property → Constant → Claim → Extraction → Application
|
||||
|
||||
// 1. Populate all nullable properties to ensure claims can be generated
|
||||
// The factory only adds claims for properties that have values
|
||||
organization.Name = "Test Organization";
|
||||
organization.BillingEmail = "billing@test.com";
|
||||
organization.BusinessName = "Test Business";
|
||||
organization.Plan = "Enterprise";
|
||||
organization.LicenseKey = "test-license-key";
|
||||
organization.Seats = 100;
|
||||
organization.MaxCollections = 50;
|
||||
organization.MaxStorageGb = 10;
|
||||
organization.SmSeats = 25;
|
||||
organization.SmServiceAccounts = 10;
|
||||
organization.ExpirationDate = DateTime.UtcNow.AddYears(1); // Ensure org is not expired
|
||||
|
||||
// Create a LicenseContext with a minimal SubscriptionInfo to trigger conditional claims
|
||||
// ExpirationWithoutGracePeriod is only generated for active, non-trial, annual subscriptions
|
||||
var licenseContext = new LicenseContext
|
||||
{
|
||||
InstallationId = Guid.NewGuid(),
|
||||
SubscriptionInfo = new SubscriptionInfo
|
||||
{
|
||||
Subscription = new SubscriptionInfo.BillingSubscription(null!)
|
||||
{
|
||||
TrialEndDate = DateTime.UtcNow.AddDays(-30), // Trial ended in the past
|
||||
PeriodStartDate = DateTime.UtcNow,
|
||||
PeriodEndDate = DateTime.UtcNow.AddDays(365), // Annual subscription (>180 days)
|
||||
Status = "active"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Generate claims
|
||||
var factory = new OrganizationLicenseClaimsFactory();
|
||||
var claims = await factory.GenerateClaims(organization, licenseContext);
|
||||
|
||||
// 3. Get all constants from OrganizationLicenseConstants
|
||||
var allConstants = typeof(OrganizationLicenseConstants)
|
||||
.GetFields(BindingFlags.Public | BindingFlags.Static)
|
||||
.Where(f => f.IsLiteral && !f.IsInitOnly)
|
||||
.Select(f => f.GetValue(null) as string)
|
||||
.ToHashSet();
|
||||
|
||||
// 4. Get claim types from generated claims
|
||||
var generatedClaimTypes = claims.Select(c => c.Type).ToHashSet();
|
||||
|
||||
// 5. Find constants that don't have corresponding claims
|
||||
var constantsWithoutClaims = allConstants
|
||||
.Except(generatedClaimTypes)
|
||||
.OrderBy(c => c)
|
||||
.ToList();
|
||||
|
||||
// 6. Build error message with guidance
|
||||
var errorMessage = "";
|
||||
if (constantsWithoutClaims.Any())
|
||||
{
|
||||
errorMessage = $"The following constants in OrganizationLicenseConstants are NOT generated as claims in OrganizationLicenseClaimsFactory:\n";
|
||||
errorMessage += string.Join("\n", constantsWithoutClaims.Select(c => $" - {c}"));
|
||||
errorMessage += "\n\nPlease add the following claims to OrganizationLicenseClaimsFactory.GenerateClaims():\n";
|
||||
foreach (var constant in constantsWithoutClaims)
|
||||
{
|
||||
errorMessage += $" new(nameof(OrganizationLicenseConstants.{constant}), entity.{constant}.ToString()),\n";
|
||||
}
|
||||
errorMessage += "\nNote: If the property is nullable, you may need to add it conditionally.";
|
||||
}
|
||||
|
||||
// 7. Assert - if this fails, the error message guides the developer to add claim generation
|
||||
Assert.True(
|
||||
!constantsWithoutClaims.Any(),
|
||||
$"\n{errorMessage}");
|
||||
}
|
||||
}
|
||||
@@ -214,6 +214,7 @@ If you believe you need to change the version for a valid reason, please discuss
|
||||
AllowAdminAccessToAllCollectionItems = true,
|
||||
UseOrganizationDomains = true,
|
||||
UseAdminSponsoredFamilies = false,
|
||||
UseDisableSmAdsForUsers = false,
|
||||
UsePhishingBlocker = false,
|
||||
};
|
||||
}
|
||||
@@ -260,4 +261,34 @@ If you believe you need to change the version for a valid reason, please discuss
|
||||
.Returns([0x00, 0x01, 0x02, 0x03]); // Dummy signature for hash testing
|
||||
return mockService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that UseDisableSmAdsForUsers claim is properly generated in the license Token
|
||||
/// and that VerifyData correctly validates the claim.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[BitAutoData(true)]
|
||||
[BitAutoData(false)]
|
||||
public void OrganizationLicense_UseDisableSmAdsForUsers_ClaimGenerationAndValidation(bool useDisableSmAdsForUsers, ClaimsPrincipal claimsPrincipal)
|
||||
{
|
||||
// Arrange
|
||||
var organization = CreateDeterministicOrganization();
|
||||
organization.UseDisableSmAdsForUsers = useDisableSmAdsForUsers;
|
||||
|
||||
var subscriptionInfo = CreateDeterministicSubscriptionInfo();
|
||||
var installationId = new Guid("78900000-0000-0000-0000-000000000123");
|
||||
var mockLicensingService = CreateMockLicensingService();
|
||||
|
||||
var license = new OrganizationLicense(organization, subscriptionInfo, installationId, mockLicensingService);
|
||||
license.Expires = DateTime.MaxValue; // Prevent expiration during test
|
||||
|
||||
var globalSettings = Substitute.For<IGlobalSettings>();
|
||||
globalSettings.Installation.Returns(new GlobalSettings.InstallationSettings
|
||||
{
|
||||
Id = installationId
|
||||
});
|
||||
|
||||
// Act & Assert - Verify VerifyData passes with the UseDisableSmAdsForUsers value
|
||||
Assert.True(license.VerifyData(organization, claimsPrincipal, globalSettings));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
using System.Security.Claims;
|
||||
using System.Reflection;
|
||||
using System.Security.Claims;
|
||||
using System.Text.RegularExpressions;
|
||||
using Bit.Core.AdminConsole.Entities;
|
||||
using Bit.Core.Billing.Enums;
|
||||
using Bit.Core.Billing.Licenses;
|
||||
using Bit.Core.Billing.Organizations.Commands;
|
||||
using Bit.Core.Billing.Organizations.Models;
|
||||
using Bit.Core.Billing.Services;
|
||||
using Bit.Core.Enums;
|
||||
using Bit.Core.Exceptions;
|
||||
using Bit.Core.Models.Data.Organizations;
|
||||
using Bit.Core.Services;
|
||||
using Bit.Core.Settings;
|
||||
@@ -88,7 +93,7 @@ public class UpdateOrganizationLicenseCommandTests
|
||||
"Hash", "Signature", "SignatureBytes", "InstallationId", "Expires",
|
||||
"ExpirationWithoutGracePeriod", "Token", "LimitCollectionCreationDeletion",
|
||||
"LimitCollectionCreation", "LimitCollectionDeletion", "AllowAdminAccessToAllCollectionItems",
|
||||
"UseOrganizationDomains", "UseAdminSponsoredFamilies", "UseAutomaticUserConfirmation", "UsePhishingBlocker") &&
|
||||
"UseOrganizationDomains", "UseAdminSponsoredFamilies", "UseAutomaticUserConfirmation", "UsePhishingBlocker", "UseDisableSmAdsForUsers") &&
|
||||
// Same property but different name, use explicit mapping
|
||||
org.ExpirationDate == license.Expires));
|
||||
}
|
||||
@@ -99,6 +104,320 @@ public class UpdateOrganizationLicenseCommandTests
|
||||
}
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task UpdateLicenseAsync_WithClaimsPrincipal_ExtractsAllPropertiesFromClaims(
|
||||
SelfHostedOrganizationDetails selfHostedOrg,
|
||||
OrganizationLicense license,
|
||||
SutProvider<UpdateOrganizationLicenseCommand> sutProvider)
|
||||
{
|
||||
var globalSettings = sutProvider.GetDependency<IGlobalSettings>();
|
||||
globalSettings.LicenseDirectory = LicenseDirectory;
|
||||
globalSettings.SelfHosted = true;
|
||||
|
||||
// Setup license for CanUse validation
|
||||
license.Enabled = true;
|
||||
license.Issued = DateTime.Now.AddDays(-1);
|
||||
license.Expires = DateTime.Now.AddDays(1);
|
||||
license.Version = OrganizationLicense.CurrentLicenseFileVersion;
|
||||
license.InstallationId = globalSettings.Installation.Id;
|
||||
license.LicenseType = LicenseType.Organization;
|
||||
license.Token = "test-token"; // Indicates this is a claims-based license
|
||||
sutProvider.GetDependency<ILicensingService>().VerifyLicense(license).Returns(true);
|
||||
|
||||
// Create a ClaimsPrincipal with all organization license claims
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(OrganizationLicenseConstants.LicenseType, ((int)LicenseType.Organization).ToString()),
|
||||
new(OrganizationLicenseConstants.InstallationId, globalSettings.Installation.Id.ToString()),
|
||||
new(OrganizationLicenseConstants.Name, "Test Organization"),
|
||||
new(OrganizationLicenseConstants.BillingEmail, "billing@test.com"),
|
||||
new(OrganizationLicenseConstants.BusinessName, "Test Business"),
|
||||
new(OrganizationLicenseConstants.PlanType, ((int)PlanType.EnterpriseAnnually).ToString()),
|
||||
new(OrganizationLicenseConstants.Seats, "100"),
|
||||
new(OrganizationLicenseConstants.MaxCollections, "50"),
|
||||
new(OrganizationLicenseConstants.UsePolicies, "true"),
|
||||
new(OrganizationLicenseConstants.UseSso, "true"),
|
||||
new(OrganizationLicenseConstants.UseKeyConnector, "true"),
|
||||
new(OrganizationLicenseConstants.UseScim, "true"),
|
||||
new(OrganizationLicenseConstants.UseGroups, "true"),
|
||||
new(OrganizationLicenseConstants.UseDirectory, "true"),
|
||||
new(OrganizationLicenseConstants.UseEvents, "true"),
|
||||
new(OrganizationLicenseConstants.UseTotp, "true"),
|
||||
new(OrganizationLicenseConstants.Use2fa, "true"),
|
||||
new(OrganizationLicenseConstants.UseApi, "true"),
|
||||
new(OrganizationLicenseConstants.UseResetPassword, "true"),
|
||||
new(OrganizationLicenseConstants.Plan, "Enterprise"),
|
||||
new(OrganizationLicenseConstants.SelfHost, "true"),
|
||||
new(OrganizationLicenseConstants.UsersGetPremium, "true"),
|
||||
new(OrganizationLicenseConstants.UseCustomPermissions, "true"),
|
||||
new(OrganizationLicenseConstants.Enabled, "true"),
|
||||
new(OrganizationLicenseConstants.Expires, DateTime.Now.AddDays(1).ToString("O")),
|
||||
new(OrganizationLicenseConstants.LicenseKey, "test-license-key"),
|
||||
new(OrganizationLicenseConstants.UsePasswordManager, "true"),
|
||||
new(OrganizationLicenseConstants.UseSecretsManager, "true"),
|
||||
new(OrganizationLicenseConstants.SmSeats, "25"),
|
||||
new(OrganizationLicenseConstants.SmServiceAccounts, "10"),
|
||||
new(OrganizationLicenseConstants.UseRiskInsights, "true"),
|
||||
new(OrganizationLicenseConstants.UseOrganizationDomains, "true"),
|
||||
new(OrganizationLicenseConstants.UseAdminSponsoredFamilies, "true"),
|
||||
new(OrganizationLicenseConstants.UseAutomaticUserConfirmation, "true"),
|
||||
new(OrganizationLicenseConstants.UseDisableSmAdsForUsers, "true"),
|
||||
new(OrganizationLicenseConstants.UsePhishingBlocker, "true"),
|
||||
new(OrganizationLicenseConstants.MaxStorageGb, "5"),
|
||||
new(OrganizationLicenseConstants.Issued, DateTime.Now.AddDays(-1).ToString("O")),
|
||||
new(OrganizationLicenseConstants.Refresh, DateTime.Now.AddMonths(1).ToString("O")),
|
||||
new(OrganizationLicenseConstants.ExpirationWithoutGracePeriod, DateTime.Now.AddMonths(12).ToString("O")),
|
||||
new(OrganizationLicenseConstants.Trial, "false"),
|
||||
new(OrganizationLicenseConstants.LimitCollectionCreationDeletion, "true"),
|
||||
new(OrganizationLicenseConstants.AllowAdminAccessToAllCollectionItems, "true")
|
||||
};
|
||||
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims));
|
||||
|
||||
sutProvider.GetDependency<ILicensingService>()
|
||||
.GetClaimsPrincipalFromLicense(license)
|
||||
.Returns(claimsPrincipal);
|
||||
|
||||
// Setup selfHostedOrg for CanUseLicense validation
|
||||
selfHostedOrg.OccupiedSeatCount = 50; // Less than the 100 seats in the license
|
||||
selfHostedOrg.CollectionCount = 10; // Less than the 50 max collections in the license
|
||||
selfHostedOrg.GroupCount = 1;
|
||||
selfHostedOrg.UseGroups = true;
|
||||
selfHostedOrg.UsePolicies = true;
|
||||
selfHostedOrg.UseSso = true;
|
||||
selfHostedOrg.UseKeyConnector = true;
|
||||
selfHostedOrg.UseScim = true;
|
||||
selfHostedOrg.UseCustomPermissions = true;
|
||||
selfHostedOrg.UseResetPassword = true;
|
||||
|
||||
try
|
||||
{
|
||||
await sutProvider.Sut.UpdateLicenseAsync(selfHostedOrg, license, null);
|
||||
|
||||
// Assertion: license file should be written to disk
|
||||
var filePath = Path.Combine(LicenseDirectory, "organization", $"{selfHostedOrg.Id}.json");
|
||||
await using var fs = File.OpenRead(filePath);
|
||||
var licenseFromFile = await JsonSerializer.DeserializeAsync<OrganizationLicense>(fs);
|
||||
|
||||
AssertHelper.AssertPropertyEqual(license, licenseFromFile, "SignatureBytes");
|
||||
|
||||
// Assertion: organization should be updated with ALL properties extracted from claims
|
||||
await sutProvider.GetDependency<IOrganizationService>()
|
||||
.Received(1)
|
||||
.ReplaceAndUpdateCacheAsync(Arg.Is<Organization>(org =>
|
||||
org.Name == "Test Organization" &&
|
||||
org.BillingEmail == "billing@test.com" &&
|
||||
org.BusinessName == "Test Business" &&
|
||||
org.PlanType == PlanType.EnterpriseAnnually &&
|
||||
org.Seats == 100 &&
|
||||
org.MaxCollections == 50 &&
|
||||
org.UsePolicies == true &&
|
||||
org.UseSso == true &&
|
||||
org.UseKeyConnector == true &&
|
||||
org.UseScim == true &&
|
||||
org.UseGroups == true &&
|
||||
org.UseDirectory == true &&
|
||||
org.UseEvents == true &&
|
||||
org.UseTotp == true &&
|
||||
org.Use2fa == true &&
|
||||
org.UseApi == true &&
|
||||
org.UseResetPassword == true &&
|
||||
org.Plan == "Enterprise" &&
|
||||
org.SelfHost == true &&
|
||||
org.UsersGetPremium == true &&
|
||||
org.UseCustomPermissions == true &&
|
||||
org.Enabled == true &&
|
||||
org.LicenseKey == "test-license-key" &&
|
||||
org.UsePasswordManager == true &&
|
||||
org.UseSecretsManager == true &&
|
||||
org.SmSeats == 25 &&
|
||||
org.SmServiceAccounts == 10 &&
|
||||
org.UseRiskInsights == true &&
|
||||
org.UseOrganizationDomains == true &&
|
||||
org.UseAdminSponsoredFamilies == true &&
|
||||
org.UseAutomaticUserConfirmation == true &&
|
||||
org.UseDisableSmAdsForUsers == true &&
|
||||
org.UsePhishingBlocker == true));
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Clean up temporary directory
|
||||
if (Directory.Exists(OrganizationLicenseDirectory.Value))
|
||||
{
|
||||
Directory.Delete(OrganizationLicenseDirectory.Value, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task UpdateLicenseAsync_WrongInstallationIdInClaims_ThrowsBadRequestException(
|
||||
SelfHostedOrganizationDetails selfHostedOrg,
|
||||
OrganizationLicense license,
|
||||
SutProvider<UpdateOrganizationLicenseCommand> sutProvider)
|
||||
{
|
||||
var globalSettings = sutProvider.GetDependency<IGlobalSettings>();
|
||||
globalSettings.LicenseDirectory = LicenseDirectory;
|
||||
globalSettings.SelfHosted = true;
|
||||
|
||||
// Setup license for CanUse validation
|
||||
license.Enabled = true;
|
||||
license.Issued = DateTime.Now.AddDays(-1);
|
||||
license.Expires = DateTime.Now.AddDays(1);
|
||||
license.Version = OrganizationLicense.CurrentLicenseFileVersion;
|
||||
license.LicenseType = LicenseType.Organization;
|
||||
license.Token = "test-token"; // Indicates this is a claims-based license
|
||||
sutProvider.GetDependency<ILicensingService>().VerifyLicense(license).Returns(true);
|
||||
|
||||
// Create a ClaimsPrincipal with WRONG installation ID
|
||||
var wrongInstallationId = Guid.NewGuid(); // Different from globalSettings.Installation.Id
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(OrganizationLicenseConstants.LicenseType, ((int)LicenseType.Organization).ToString()),
|
||||
new(OrganizationLicenseConstants.InstallationId, wrongInstallationId.ToString()),
|
||||
new(OrganizationLicenseConstants.Enabled, "true"),
|
||||
new(OrganizationLicenseConstants.SelfHost, "true")
|
||||
};
|
||||
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims));
|
||||
|
||||
sutProvider.GetDependency<ILicensingService>()
|
||||
.GetClaimsPrincipalFromLicense(license)
|
||||
.Returns(claimsPrincipal);
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(
|
||||
() => sutProvider.Sut.UpdateLicenseAsync(selfHostedOrg, license, null));
|
||||
|
||||
Assert.Contains("The installation ID does not match the current installation.", exception.Message);
|
||||
|
||||
// Verify organization was NOT saved
|
||||
await sutProvider.GetDependency<IOrganizationService>()
|
||||
.DidNotReceive()
|
||||
.ReplaceAndUpdateCacheAsync(Arg.Any<Organization>());
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task UpdateLicenseAsync_ExpiredLicenseWithoutClaims_ThrowsBadRequestException(
|
||||
SelfHostedOrganizationDetails selfHostedOrg,
|
||||
OrganizationLicense license,
|
||||
SutProvider<UpdateOrganizationLicenseCommand> sutProvider)
|
||||
{
|
||||
var globalSettings = sutProvider.GetDependency<IGlobalSettings>();
|
||||
globalSettings.LicenseDirectory = LicenseDirectory;
|
||||
globalSettings.SelfHosted = true;
|
||||
|
||||
// Setup legacy license (no Token, no claims)
|
||||
license.Token = null; // Legacy license
|
||||
license.Enabled = true;
|
||||
license.Issued = DateTime.Now.AddDays(-2);
|
||||
license.Expires = DateTime.Now.AddDays(-1); // Expired yesterday
|
||||
license.Version = OrganizationLicense.CurrentLicenseFileVersion;
|
||||
license.InstallationId = globalSettings.Installation.Id;
|
||||
license.LicenseType = LicenseType.Organization;
|
||||
license.SelfHost = true;
|
||||
|
||||
sutProvider.GetDependency<ILicensingService>().VerifyLicense(license).Returns(true);
|
||||
sutProvider.GetDependency<ILicensingService>()
|
||||
.GetClaimsPrincipalFromLicense(license)
|
||||
.Returns((ClaimsPrincipal)null); // No claims for legacy license
|
||||
|
||||
// Passing values for SelfHostedOrganizationDetails.CanUseLicense
|
||||
license.Seats = null;
|
||||
license.MaxCollections = null;
|
||||
license.UseGroups = true;
|
||||
license.UsePolicies = true;
|
||||
license.UseSso = true;
|
||||
license.UseKeyConnector = true;
|
||||
license.UseScim = true;
|
||||
license.UseCustomPermissions = true;
|
||||
license.UseResetPassword = true;
|
||||
|
||||
// Act & Assert
|
||||
var exception = await Assert.ThrowsAsync<BadRequestException>(
|
||||
() => sutProvider.Sut.UpdateLicenseAsync(selfHostedOrg, license, null));
|
||||
|
||||
Assert.Contains("The license has expired.", exception.Message);
|
||||
|
||||
// Verify organization was NOT saved
|
||||
await sutProvider.GetDependency<IOrganizationService>()
|
||||
.DidNotReceive()
|
||||
.ReplaceAndUpdateCacheAsync(Arg.Any<Organization>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLicenseAsync_ExtractsAllClaimsBasedProperties_WhenClaimsPrincipalProvided()
|
||||
{
|
||||
// This test ensures that when new properties are added to OrganizationLicense,
|
||||
// they are automatically extracted from JWT claims in UpdateOrganizationLicenseCommand.
|
||||
// If a new constant is added to OrganizationLicenseConstants but not extracted,
|
||||
// this test will fail with a clear message showing which properties are missing.
|
||||
|
||||
// 1. Get all OrganizationLicenseConstants
|
||||
var constantFields = typeof(OrganizationLicenseConstants)
|
||||
.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.GetField)
|
||||
.Where(f => f.IsLiteral && !f.IsInitOnly)
|
||||
.Select(f => f.GetValue(null) as string)
|
||||
.ToList();
|
||||
|
||||
// 2. Define properties that should be excluded (not claims-based or intentionally not extracted)
|
||||
var excludedProperties = new HashSet<string>
|
||||
{
|
||||
"Version", // Not in claims system (only in deprecated property-based licenses)
|
||||
"Hash", // Signature-related, not extracted from claims
|
||||
"Signature", // Signature-related, not extracted from claims
|
||||
"SignatureBytes", // Computed from Signature, not a claim
|
||||
"Token", // The JWT itself, not extracted from claims
|
||||
"Id" // Cloud org ID from license, not used - self-hosted org has its own separate ID
|
||||
};
|
||||
|
||||
// 3. Get properties that should be extracted from claims
|
||||
var propertiesThatShouldBeExtracted = constantFields
|
||||
.Where(c => !excludedProperties.Contains(c))
|
||||
.ToHashSet();
|
||||
|
||||
// 4. Read UpdateOrganizationLicenseCommand source code
|
||||
var commandSourcePath = Path.Combine(
|
||||
Directory.GetCurrentDirectory(),
|
||||
"..", "..", "..", "..", "..",
|
||||
"src", "Core", "Billing", "Organizations", "Commands", "UpdateOrganizationLicenseCommand.cs");
|
||||
var sourceCode = await File.ReadAllTextAsync(commandSourcePath);
|
||||
|
||||
// 5. Find all GetValue calls that extract properties from claims
|
||||
// Pattern matches: license.PropertyName = claimsPrincipal.GetValue<Type>(OrganizationLicenseConstants.PropertyName)
|
||||
var extractedProperties = new HashSet<string>();
|
||||
var getValuePattern = @"claimsPrincipal\.GetValue<[^>]+>\(OrganizationLicenseConstants\.(\w+)\)";
|
||||
var matches = Regex.Matches(sourceCode, getValuePattern);
|
||||
|
||||
foreach (Match match in matches)
|
||||
{
|
||||
extractedProperties.Add(match.Groups[1].Value);
|
||||
}
|
||||
|
||||
// 6. Find missing extractions
|
||||
var missingExtractions = propertiesThatShouldBeExtracted
|
||||
.Except(extractedProperties)
|
||||
.OrderBy(p => p)
|
||||
.ToList();
|
||||
|
||||
// 7. Build error message with guidance if there are missing extractions
|
||||
var errorMessage = "";
|
||||
if (missingExtractions.Any())
|
||||
{
|
||||
errorMessage = $"The following constants in OrganizationLicenseConstants are NOT extracted from claims in UpdateOrganizationLicenseCommand:\n";
|
||||
errorMessage += string.Join("\n", missingExtractions.Select(p => $" - {p}"));
|
||||
errorMessage += "\n\nPlease add the following lines to UpdateOrganizationLicenseCommand.cs in the 'if (claimsPrincipal != null)' block:\n";
|
||||
foreach (var prop in missingExtractions)
|
||||
{
|
||||
errorMessage += $" license.{prop} = claimsPrincipal.GetValue<TYPE>(OrganizationLicenseConstants.{prop});\n";
|
||||
}
|
||||
}
|
||||
|
||||
// 8. Assert - if this fails, the error message guides the developer to add the extraction
|
||||
// Note: We don't check for "extra extractions" because that would be a compile error
|
||||
// (can't reference OrganizationLicenseConstants.Foo if Foo doesn't exist)
|
||||
Assert.True(
|
||||
!missingExtractions.Any(),
|
||||
$"\n{errorMessage}");
|
||||
}
|
||||
|
||||
// Wrapper to compare 2 objects that are different types
|
||||
private bool AssertPropertyEqual(OrganizationLicense expected, Organization actual, params string[] excludedPropertyStrings)
|
||||
{
|
||||
|
||||
@@ -8,6 +8,7 @@ using Bit.Core.Billing.Payment.Queries;
|
||||
using Bit.Core.Billing.Premium.Commands;
|
||||
using Bit.Core.Billing.Pricing;
|
||||
using Bit.Core.Billing.Services;
|
||||
using Bit.Core.Billing.Subscriptions.Models;
|
||||
using Bit.Core.Entities;
|
||||
using Bit.Core.Platform.Push;
|
||||
using Bit.Core.Services;
|
||||
@@ -29,6 +30,7 @@ namespace Bit.Core.Test.Billing.Premium.Commands;
|
||||
public class CreatePremiumCloudHostedSubscriptionCommandTests
|
||||
{
|
||||
private readonly IBraintreeGateway _braintreeGateway = Substitute.For<IBraintreeGateway>();
|
||||
private readonly IBraintreeService _braintreeService = Substitute.For<IBraintreeService>();
|
||||
private readonly IGlobalSettings _globalSettings = Substitute.For<IGlobalSettings>();
|
||||
private readonly ISetupIntentCache _setupIntentCache = Substitute.For<ISetupIntentCache>();
|
||||
private readonly IStripeAdapter _stripeAdapter = Substitute.For<IStripeAdapter>();
|
||||
@@ -59,6 +61,7 @@ public class CreatePremiumCloudHostedSubscriptionCommandTests
|
||||
|
||||
_command = new CreatePremiumCloudHostedSubscriptionCommand(
|
||||
_braintreeGateway,
|
||||
_braintreeService,
|
||||
_globalSettings,
|
||||
_setupIntentCache,
|
||||
_stripeAdapter,
|
||||
@@ -235,11 +238,15 @@ public class CreatePremiumCloudHostedSubscriptionCommandTests
|
||||
var mockCustomer = Substitute.For<StripeCustomer>();
|
||||
mockCustomer.Id = "cust_123";
|
||||
mockCustomer.Address = new Address { Country = "US", PostalCode = "12345" };
|
||||
mockCustomer.Metadata = new Dictionary<string, string>();
|
||||
mockCustomer.Metadata = new Dictionary<string, string>
|
||||
{
|
||||
[Core.Billing.Utilities.BraintreeCustomerIdKey] = "bt_customer_123"
|
||||
};
|
||||
|
||||
var mockSubscription = Substitute.For<StripeSubscription>();
|
||||
mockSubscription.Id = "sub_123";
|
||||
mockSubscription.Status = "active";
|
||||
mockSubscription.LatestInvoiceId = "in_123";
|
||||
|
||||
var mockInvoice = Substitute.For<Invoice>();
|
||||
|
||||
@@ -258,6 +265,12 @@ public class CreatePremiumCloudHostedSubscriptionCommandTests
|
||||
await _stripeAdapter.Received(1).CreateCustomerAsync(Arg.Any<CustomerCreateOptions>());
|
||||
await _stripeAdapter.Received(1).CreateSubscriptionAsync(Arg.Any<SubscriptionCreateOptions>());
|
||||
await _subscriberService.Received(1).CreateBraintreeCustomer(user, paymentMethod.Token);
|
||||
await _stripeAdapter.Received(1).UpdateInvoiceAsync(mockSubscription.LatestInvoiceId,
|
||||
Arg.Is<InvoiceUpdateOptions>(opts =>
|
||||
opts.AutoAdvance == false &&
|
||||
opts.Expand != null &&
|
||||
opts.Expand.Contains("customer")));
|
||||
await _braintreeService.Received(1).PayInvoice(Arg.Any<SubscriberId>(), mockInvoice);
|
||||
await _userService.Received(1).SaveUserAsync(user);
|
||||
await _pushNotificationService.Received(1).PushSyncVaultAsync(user.Id);
|
||||
}
|
||||
@@ -456,11 +469,15 @@ public class CreatePremiumCloudHostedSubscriptionCommandTests
|
||||
var mockCustomer = Substitute.For<StripeCustomer>();
|
||||
mockCustomer.Id = "cust_123";
|
||||
mockCustomer.Address = new Address { Country = "US", PostalCode = "12345" };
|
||||
mockCustomer.Metadata = new Dictionary<string, string>();
|
||||
mockCustomer.Metadata = new Dictionary<string, string>
|
||||
{
|
||||
[Core.Billing.Utilities.BraintreeCustomerIdKey] = "bt_customer_123"
|
||||
};
|
||||
|
||||
var mockSubscription = Substitute.For<StripeSubscription>();
|
||||
mockSubscription.Id = "sub_123";
|
||||
mockSubscription.Status = "incomplete";
|
||||
mockSubscription.LatestInvoiceId = "in_123";
|
||||
mockSubscription.Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data =
|
||||
@@ -487,6 +504,12 @@ public class CreatePremiumCloudHostedSubscriptionCommandTests
|
||||
Assert.True(result.IsT0);
|
||||
Assert.True(user.Premium);
|
||||
Assert.Equal(mockSubscription.GetCurrentPeriodEnd(), user.PremiumExpirationDate);
|
||||
await _stripeAdapter.Received(1).UpdateInvoiceAsync(mockSubscription.LatestInvoiceId,
|
||||
Arg.Is<InvoiceUpdateOptions>(opts =>
|
||||
opts.AutoAdvance == false &&
|
||||
opts.Expand != null &&
|
||||
opts.Expand.Contains("customer")));
|
||||
await _braintreeService.Received(1).PayInvoice(Arg.Any<SubscriberId>(), mockInvoice);
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
@@ -559,11 +582,15 @@ public class CreatePremiumCloudHostedSubscriptionCommandTests
|
||||
var mockCustomer = Substitute.For<StripeCustomer>();
|
||||
mockCustomer.Id = "cust_123";
|
||||
mockCustomer.Address = new Address { Country = "US", PostalCode = "12345" };
|
||||
mockCustomer.Metadata = new Dictionary<string, string>();
|
||||
mockCustomer.Metadata = new Dictionary<string, string>
|
||||
{
|
||||
[Core.Billing.Utilities.BraintreeCustomerIdKey] = "bt_customer_123"
|
||||
};
|
||||
|
||||
var mockSubscription = Substitute.For<StripeSubscription>();
|
||||
mockSubscription.Id = "sub_123";
|
||||
mockSubscription.Status = "active"; // PayPal + active doesn't match pattern
|
||||
mockSubscription.LatestInvoiceId = "in_123";
|
||||
mockSubscription.Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data =
|
||||
@@ -590,6 +617,12 @@ public class CreatePremiumCloudHostedSubscriptionCommandTests
|
||||
Assert.True(result.IsT0);
|
||||
Assert.False(user.Premium);
|
||||
Assert.Null(user.PremiumExpirationDate);
|
||||
await _stripeAdapter.Received(1).UpdateInvoiceAsync(mockSubscription.LatestInvoiceId,
|
||||
Arg.Is<InvoiceUpdateOptions>(opts =>
|
||||
opts.AutoAdvance == false &&
|
||||
opts.Expand != null &&
|
||||
opts.Expand.Contains("customer")));
|
||||
await _braintreeService.Received(1).PayInvoice(Arg.Any<SubscriberId>(), mockInvoice);
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
|
||||
@@ -18,13 +18,11 @@ public class UpdatePremiumStorageCommandTests
|
||||
private readonly IStripeAdapter _stripeAdapter = Substitute.For<IStripeAdapter>();
|
||||
private readonly IUserService _userService = Substitute.For<IUserService>();
|
||||
private readonly IPricingClient _pricingClient = Substitute.For<IPricingClient>();
|
||||
private readonly PremiumPlan _premiumPlan;
|
||||
private readonly UpdatePremiumStorageCommand _command;
|
||||
|
||||
public UpdatePremiumStorageCommandTests()
|
||||
{
|
||||
// Setup default premium plan with standard pricing
|
||||
_premiumPlan = new PremiumPlan
|
||||
var premiumPlan = new PremiumPlan
|
||||
{
|
||||
Name = "Premium",
|
||||
Available = true,
|
||||
@@ -32,7 +30,7 @@ public class UpdatePremiumStorageCommandTests
|
||||
Seat = new PremiumPurchasable { Price = 10M, StripePriceId = "price_premium", Provided = 1 },
|
||||
Storage = new PremiumPurchasable { Price = 4M, StripePriceId = "price_storage", Provided = 1 }
|
||||
};
|
||||
_pricingClient.ListPremiumPlans().Returns(new List<PremiumPlan> { _premiumPlan });
|
||||
_pricingClient.ListPremiumPlans().Returns([premiumPlan]);
|
||||
|
||||
_command = new UpdatePremiumStorageCommand(
|
||||
_stripeAdapter,
|
||||
@@ -43,18 +41,19 @@ public class UpdatePremiumStorageCommandTests
|
||||
|
||||
private Subscription CreateMockSubscription(string subscriptionId, int? storageQuantity = null)
|
||||
{
|
||||
var items = new List<SubscriptionItem>();
|
||||
|
||||
// Always add the seat item
|
||||
items.Add(new SubscriptionItem
|
||||
var items = new List<SubscriptionItem>
|
||||
{
|
||||
Id = "si_seat",
|
||||
Price = new Price { Id = "price_premium" },
|
||||
Quantity = 1
|
||||
});
|
||||
// Always add the seat item
|
||||
new()
|
||||
{
|
||||
Id = "si_seat",
|
||||
Price = new Price { Id = "price_premium" },
|
||||
Quantity = 1
|
||||
}
|
||||
};
|
||||
|
||||
// Add storage item if quantity is provided
|
||||
if (storageQuantity.HasValue && storageQuantity.Value > 0)
|
||||
if (storageQuantity is > 0)
|
||||
{
|
||||
items.Add(new SubscriptionItem
|
||||
{
|
||||
@@ -142,7 +141,7 @@ public class UpdatePremiumStorageCommandTests
|
||||
// Assert
|
||||
Assert.True(result.IsT1);
|
||||
var badRequest = result.AsT1;
|
||||
Assert.Equal("No access to storage.", badRequest.Response);
|
||||
Assert.Equal("User has no access to storage.", badRequest.Response);
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
@@ -216,7 +215,7 @@ public class UpdatePremiumStorageCommandTests
|
||||
opts.Items.Count == 1 &&
|
||||
opts.Items[0].Id == "si_storage" &&
|
||||
opts.Items[0].Quantity == 9 &&
|
||||
opts.ProrationBehavior == "create_prorations"));
|
||||
opts.ProrationBehavior == "always_invoice"));
|
||||
|
||||
// Verify user was saved
|
||||
await _userService.Received(1).SaveUserAsync(Arg.Is<User>(u =>
|
||||
@@ -233,7 +232,7 @@ public class UpdatePremiumStorageCommandTests
|
||||
user.Storage = 500L * 1024 * 1024;
|
||||
user.GatewaySubscriptionId = "sub_123";
|
||||
|
||||
var subscription = CreateMockSubscription("sub_123", null);
|
||||
var subscription = CreateMockSubscription("sub_123");
|
||||
_stripeAdapter.GetSubscriptionAsync("sub_123").Returns(subscription);
|
||||
|
||||
// Act
|
||||
|
||||
@@ -0,0 +1,646 @@
|
||||
using Bit.Core.AdminConsole.Entities;
|
||||
using Bit.Core.Billing.Constants;
|
||||
using Bit.Core.Billing.Enums;
|
||||
using Bit.Core.Billing.Premium.Commands;
|
||||
using Bit.Core.Billing.Pricing;
|
||||
using Bit.Core.Billing.Services;
|
||||
using Bit.Core.Entities;
|
||||
using Bit.Core.Enums;
|
||||
using Bit.Core.Repositories;
|
||||
using Bit.Core.Services;
|
||||
using Bit.Test.Common.AutoFixture.Attributes;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using Stripe;
|
||||
using Xunit;
|
||||
using PremiumPlan = Bit.Core.Billing.Pricing.Premium.Plan;
|
||||
using PremiumPurchasable = Bit.Core.Billing.Pricing.Premium.Purchasable;
|
||||
|
||||
namespace Bit.Core.Test.Billing.Premium.Commands;
|
||||
|
||||
public class UpgradePremiumToOrganizationCommandTests
|
||||
{
|
||||
// Concrete test implementation of the abstract Plan record
|
||||
private record TestPlan : Core.Models.StaticStore.Plan
|
||||
{
|
||||
public TestPlan(
|
||||
PlanType planType,
|
||||
string? stripePlanId = null,
|
||||
string? stripeSeatPlanId = null,
|
||||
string? stripePremiumAccessPlanId = null,
|
||||
string? stripeStoragePlanId = null)
|
||||
{
|
||||
Type = planType;
|
||||
ProductTier = ProductTierType.Teams;
|
||||
Name = "Test Plan";
|
||||
IsAnnual = true;
|
||||
NameLocalizationKey = "";
|
||||
DescriptionLocalizationKey = "";
|
||||
CanBeUsedByBusiness = true;
|
||||
TrialPeriodDays = null;
|
||||
HasSelfHost = false;
|
||||
HasPolicies = false;
|
||||
HasGroups = false;
|
||||
HasDirectory = false;
|
||||
HasEvents = false;
|
||||
HasTotp = false;
|
||||
Has2fa = false;
|
||||
HasApi = false;
|
||||
HasSso = false;
|
||||
HasOrganizationDomains = false;
|
||||
HasKeyConnector = false;
|
||||
HasScim = false;
|
||||
HasResetPassword = false;
|
||||
UsersGetPremium = false;
|
||||
HasCustomPermissions = false;
|
||||
UpgradeSortOrder = 0;
|
||||
DisplaySortOrder = 0;
|
||||
LegacyYear = null;
|
||||
Disabled = false;
|
||||
PasswordManager = new PasswordManagerPlanFeatures
|
||||
{
|
||||
StripePlanId = stripePlanId,
|
||||
StripeSeatPlanId = stripeSeatPlanId,
|
||||
StripePremiumAccessPlanId = stripePremiumAccessPlanId,
|
||||
StripeStoragePlanId = stripeStoragePlanId,
|
||||
BasePrice = 0,
|
||||
SeatPrice = 0,
|
||||
ProviderPortalSeatPrice = 0,
|
||||
AllowSeatAutoscale = true,
|
||||
HasAdditionalSeatsOption = true,
|
||||
BaseSeats = 1,
|
||||
HasPremiumAccessOption = !string.IsNullOrEmpty(stripePremiumAccessPlanId),
|
||||
PremiumAccessOptionPrice = 0,
|
||||
MaxSeats = null,
|
||||
BaseStorageGb = 1,
|
||||
HasAdditionalStorageOption = !string.IsNullOrEmpty(stripeStoragePlanId),
|
||||
AdditionalStoragePricePerGb = 0,
|
||||
MaxCollections = null
|
||||
};
|
||||
SecretsManager = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Core.Models.StaticStore.Plan CreateTestPlan(
|
||||
PlanType planType,
|
||||
string? stripePlanId = null,
|
||||
string? stripeSeatPlanId = null,
|
||||
string? stripePremiumAccessPlanId = null,
|
||||
string? stripeStoragePlanId = null)
|
||||
{
|
||||
return new TestPlan(planType, stripePlanId, stripeSeatPlanId, stripePremiumAccessPlanId, stripeStoragePlanId);
|
||||
}
|
||||
|
||||
private static PremiumPlan CreateTestPremiumPlan(
|
||||
string seatPriceId = "premium-annually",
|
||||
string storagePriceId = "personal-storage-gb-annually",
|
||||
bool available = true)
|
||||
{
|
||||
return new PremiumPlan
|
||||
{
|
||||
Name = "Premium",
|
||||
LegacyYear = null,
|
||||
Available = available,
|
||||
Seat = new PremiumPurchasable
|
||||
{
|
||||
StripePriceId = seatPriceId,
|
||||
Price = 10m,
|
||||
Provided = 1
|
||||
},
|
||||
Storage = new PremiumPurchasable
|
||||
{
|
||||
StripePriceId = storagePriceId,
|
||||
Price = 4m,
|
||||
Provided = 1
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static List<PremiumPlan> CreateTestPremiumPlansList()
|
||||
{
|
||||
return new List<PremiumPlan>
|
||||
{
|
||||
// Current available plan
|
||||
CreateTestPremiumPlan("premium-annually", "personal-storage-gb-annually", available: true),
|
||||
// Legacy plan from 2020
|
||||
CreateTestPremiumPlan("premium-annually-2020", "personal-storage-gb-annually-2020", available: false)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private readonly IPricingClient _pricingClient = Substitute.For<IPricingClient>();
|
||||
private readonly IStripeAdapter _stripeAdapter = Substitute.For<IStripeAdapter>();
|
||||
private readonly IUserService _userService = Substitute.For<IUserService>();
|
||||
private readonly IOrganizationRepository _organizationRepository = Substitute.For<IOrganizationRepository>();
|
||||
private readonly IOrganizationUserRepository _organizationUserRepository = Substitute.For<IOrganizationUserRepository>();
|
||||
private readonly IOrganizationApiKeyRepository _organizationApiKeyRepository = Substitute.For<IOrganizationApiKeyRepository>();
|
||||
private readonly IApplicationCacheService _applicationCacheService = Substitute.For<IApplicationCacheService>();
|
||||
private readonly ILogger<UpgradePremiumToOrganizationCommand> _logger = Substitute.For<ILogger<UpgradePremiumToOrganizationCommand>>();
|
||||
private readonly UpgradePremiumToOrganizationCommand _command;
|
||||
|
||||
public UpgradePremiumToOrganizationCommandTests()
|
||||
{
|
||||
_command = new UpgradePremiumToOrganizationCommand(
|
||||
_logger,
|
||||
_pricingClient,
|
||||
_stripeAdapter,
|
||||
_userService,
|
||||
_organizationRepository,
|
||||
_organizationUserRepository,
|
||||
_organizationApiKeyRepository,
|
||||
_applicationCacheService);
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_UserNotPremium_ReturnsBadRequest(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = false;
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT1);
|
||||
var badRequest = result.AsT1;
|
||||
Assert.Equal("User does not have an active Premium subscription.", badRequest.Response);
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_UserNoGatewaySubscriptionId_ReturnsBadRequest(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = null;
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT1);
|
||||
var badRequest = result.AsT1;
|
||||
Assert.Equal("User does not have an active Premium subscription.", badRequest.Response);
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_UserEmptyGatewaySubscriptionId_ReturnsBadRequest(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = "";
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT1);
|
||||
var badRequest = result.AsT1;
|
||||
Assert.Equal("User does not have an active Premium subscription.", badRequest.Response);
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_SuccessfulUpgrade_SeatBasedPlan_ReturnsSuccess(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = "sub_123";
|
||||
user.GatewayCustomerId = "cus_123";
|
||||
user.Id = Guid.NewGuid();
|
||||
|
||||
var currentPeriodEnd = DateTime.UtcNow.AddMonths(1);
|
||||
var mockSubscription = new Subscription
|
||||
{
|
||||
Id = "sub_123",
|
||||
Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = new List<SubscriptionItem>
|
||||
{
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_premium",
|
||||
Price = new Price { Id = "premium-annually" },
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
}
|
||||
}
|
||||
},
|
||||
Metadata = new Dictionary<string, string>()
|
||||
};
|
||||
|
||||
var mockPremiumPlans = CreateTestPremiumPlansList();
|
||||
var mockPlan = CreateTestPlan(
|
||||
PlanType.TeamsAnnually,
|
||||
stripeSeatPlanId: "teams-seat-annually"
|
||||
);
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync("sub_123")
|
||||
.Returns(mockSubscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(mockPremiumPlans);
|
||||
_pricingClient.GetPlanOrThrow(PlanType.TeamsAnnually).Returns(mockPlan);
|
||||
_stripeAdapter.UpdateSubscriptionAsync(Arg.Any<string>(), Arg.Any<SubscriptionUpdateOptions>())
|
||||
.Returns(Task.FromResult(mockSubscription));
|
||||
_organizationRepository.CreateAsync(Arg.Any<Organization>()).Returns(callInfo => Task.FromResult(callInfo.Arg<Organization>()));
|
||||
_organizationApiKeyRepository.CreateAsync(Arg.Any<OrganizationApiKey>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationApiKey>()));
|
||||
_organizationUserRepository.CreateAsync(Arg.Any<OrganizationUser>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationUser>()));
|
||||
_applicationCacheService.UpsertOrganizationAbilityAsync(Arg.Any<Organization>()).Returns(Task.CompletedTask);
|
||||
_userService.SaveUserAsync(user).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT0);
|
||||
|
||||
await _stripeAdapter.Received(1).UpdateSubscriptionAsync(
|
||||
"sub_123",
|
||||
Arg.Is<SubscriptionUpdateOptions>(opts =>
|
||||
opts.Items.Count == 2 && // 1 deleted + 1 seat (no storage)
|
||||
opts.Items.Any(i => i.Deleted == true) &&
|
||||
opts.Items.Any(i => i.Price == "teams-seat-annually" && i.Quantity == 1)));
|
||||
|
||||
await _organizationRepository.Received(1).CreateAsync(Arg.Is<Organization>(o =>
|
||||
o.Name == "My Organization" &&
|
||||
o.Gateway == GatewayType.Stripe &&
|
||||
o.GatewaySubscriptionId == "sub_123" &&
|
||||
o.GatewayCustomerId == "cus_123"));
|
||||
await _organizationUserRepository.Received(1).CreateAsync(Arg.Is<OrganizationUser>(ou =>
|
||||
ou.Key == "encrypted-key" &&
|
||||
ou.Status == OrganizationUserStatusType.Confirmed));
|
||||
await _organizationApiKeyRepository.Received(1).CreateAsync(Arg.Any<OrganizationApiKey>());
|
||||
|
||||
await _userService.Received(1).SaveUserAsync(Arg.Is<User>(u =>
|
||||
u.Premium == false &&
|
||||
u.GatewaySubscriptionId == null &&
|
||||
u.GatewayCustomerId == null));
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_SuccessfulUpgrade_NonSeatBasedPlan_ReturnsSuccess(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = "sub_123";
|
||||
user.GatewayCustomerId = "cus_123";
|
||||
|
||||
var currentPeriodEnd = DateTime.UtcNow.AddMonths(1);
|
||||
var mockSubscription = new Subscription
|
||||
{
|
||||
Id = "sub_123",
|
||||
Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = new List<SubscriptionItem>
|
||||
{
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_premium",
|
||||
Price = new Price { Id = "premium-annually" },
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
}
|
||||
}
|
||||
},
|
||||
Metadata = new Dictionary<string, string>()
|
||||
};
|
||||
|
||||
var mockPremiumPlans = CreateTestPremiumPlansList();
|
||||
var mockPlan = CreateTestPlan(
|
||||
PlanType.FamiliesAnnually,
|
||||
stripePlanId: "families-plan-annually",
|
||||
stripeSeatPlanId: null // Non-seat-based
|
||||
);
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync("sub_123")
|
||||
.Returns(mockSubscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(mockPremiumPlans);
|
||||
_pricingClient.GetPlanOrThrow(PlanType.FamiliesAnnually).Returns(mockPlan);
|
||||
_stripeAdapter.UpdateSubscriptionAsync(Arg.Any<string>(), Arg.Any<SubscriptionUpdateOptions>())
|
||||
.Returns(Task.FromResult(mockSubscription));
|
||||
_organizationRepository.CreateAsync(Arg.Any<Organization>()).Returns(callInfo => Task.FromResult(callInfo.Arg<Organization>()));
|
||||
_organizationApiKeyRepository.CreateAsync(Arg.Any<OrganizationApiKey>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationApiKey>()));
|
||||
_organizationUserRepository.CreateAsync(Arg.Any<OrganizationUser>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationUser>()));
|
||||
_applicationCacheService.UpsertOrganizationAbilityAsync(Arg.Any<Organization>()).Returns(Task.CompletedTask);
|
||||
_userService.SaveUserAsync(user).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Families Org", "encrypted-key", PlanType.FamiliesAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT0);
|
||||
|
||||
await _stripeAdapter.Received(1).UpdateSubscriptionAsync(
|
||||
"sub_123",
|
||||
Arg.Is<SubscriptionUpdateOptions>(opts =>
|
||||
opts.Items.Count == 2 && // 1 deleted + 1 plan
|
||||
opts.Items.Any(i => i.Deleted == true) &&
|
||||
opts.Items.Any(i => i.Price == "families-plan-annually" && i.Quantity == 1)));
|
||||
|
||||
await _organizationRepository.Received(1).CreateAsync(Arg.Is<Organization>(o =>
|
||||
o.Name == "My Families Org"));
|
||||
await _userService.Received(1).SaveUserAsync(Arg.Is<User>(u =>
|
||||
u.Premium == false &&
|
||||
u.GatewaySubscriptionId == null));
|
||||
}
|
||||
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_AddsMetadataWithOriginalPremiumPriceId(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = "sub_123";
|
||||
|
||||
var mockSubscription = new Subscription
|
||||
{
|
||||
Id = "sub_123",
|
||||
Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = new List<SubscriptionItem>
|
||||
{
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_premium",
|
||||
Price = new Price { Id = "premium-annually" },
|
||||
CurrentPeriodEnd = DateTime.UtcNow.AddMonths(1)
|
||||
}
|
||||
}
|
||||
},
|
||||
Metadata = new Dictionary<string, string>
|
||||
{
|
||||
["userId"] = user.Id.ToString()
|
||||
}
|
||||
};
|
||||
|
||||
var mockPremiumPlans = CreateTestPremiumPlansList();
|
||||
var mockPlan = CreateTestPlan(
|
||||
PlanType.TeamsAnnually,
|
||||
stripeSeatPlanId: "teams-seat-annually"
|
||||
);
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync("sub_123")
|
||||
.Returns(mockSubscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(mockPremiumPlans);
|
||||
_pricingClient.GetPlanOrThrow(PlanType.TeamsAnnually).Returns(mockPlan);
|
||||
_stripeAdapter.UpdateSubscriptionAsync(Arg.Any<string>(), Arg.Any<SubscriptionUpdateOptions>())
|
||||
.Returns(Task.FromResult(mockSubscription));
|
||||
_userService.SaveUserAsync(user).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT0);
|
||||
|
||||
await _stripeAdapter.Received(1).UpdateSubscriptionAsync(
|
||||
"sub_123",
|
||||
Arg.Is<SubscriptionUpdateOptions>(opts =>
|
||||
opts.Metadata.ContainsKey(StripeConstants.MetadataKeys.OrganizationId) &&
|
||||
opts.Metadata.ContainsKey(StripeConstants.MetadataKeys.PreviousPremiumPriceId) &&
|
||||
opts.Metadata[StripeConstants.MetadataKeys.PreviousPremiumPriceId] == "premium-annually" &&
|
||||
opts.Metadata.ContainsKey(StripeConstants.MetadataKeys.PreviousPeriodEndDate) &&
|
||||
opts.Metadata.ContainsKey(StripeConstants.MetadataKeys.PreviousAdditionalStorage) &&
|
||||
opts.Metadata[StripeConstants.MetadataKeys.PreviousAdditionalStorage] == "0" &&
|
||||
opts.Metadata.ContainsKey(StripeConstants.MetadataKeys.UserId) &&
|
||||
opts.Metadata[StripeConstants.MetadataKeys.UserId] == string.Empty)); // Removes userId to unlink from User
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_UserOnLegacyPremiumPlan_SuccessfullyDeletesLegacyItems(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = "sub_123";
|
||||
user.GatewayCustomerId = "cus_123";
|
||||
|
||||
var currentPeriodEnd = DateTime.UtcNow.AddMonths(1);
|
||||
var mockSubscription = new Subscription
|
||||
{
|
||||
Id = "sub_123",
|
||||
Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = new List<SubscriptionItem>
|
||||
{
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_premium_legacy",
|
||||
Price = new Price { Id = "premium-annually-2020" }, // Legacy price ID
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
},
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_storage_legacy",
|
||||
Price = new Price { Id = "personal-storage-gb-annually-2020" }, // Legacy storage price ID
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
}
|
||||
}
|
||||
},
|
||||
Metadata = new Dictionary<string, string>()
|
||||
};
|
||||
|
||||
var mockPremiumPlans = CreateTestPremiumPlansList();
|
||||
var mockPlan = CreateTestPlan(
|
||||
PlanType.TeamsAnnually,
|
||||
stripeSeatPlanId: "teams-seat-annually"
|
||||
);
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync("sub_123")
|
||||
.Returns(mockSubscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(mockPremiumPlans);
|
||||
_pricingClient.GetPlanOrThrow(PlanType.TeamsAnnually).Returns(mockPlan);
|
||||
_stripeAdapter.UpdateSubscriptionAsync(Arg.Any<string>(), Arg.Any<SubscriptionUpdateOptions>())
|
||||
.Returns(Task.FromResult(mockSubscription));
|
||||
_organizationRepository.CreateAsync(Arg.Any<Organization>()).Returns(callInfo => Task.FromResult(callInfo.Arg<Organization>()));
|
||||
_organizationApiKeyRepository.CreateAsync(Arg.Any<OrganizationApiKey>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationApiKey>()));
|
||||
_organizationUserRepository.CreateAsync(Arg.Any<OrganizationUser>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationUser>()));
|
||||
_applicationCacheService.UpsertOrganizationAbilityAsync(Arg.Any<Organization>()).Returns(Task.CompletedTask);
|
||||
_userService.SaveUserAsync(user).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT0);
|
||||
|
||||
// Verify that BOTH legacy items (password manager + storage) are deleted by ID
|
||||
await _stripeAdapter.Received(1).UpdateSubscriptionAsync(
|
||||
"sub_123",
|
||||
Arg.Is<SubscriptionUpdateOptions>(opts =>
|
||||
opts.Items.Count == 3 && // 2 deleted (legacy PM + legacy storage) + 1 new seat
|
||||
opts.Items.Count(i => i.Deleted == true && i.Id == "si_premium_legacy") == 1 && // Legacy PM deleted
|
||||
opts.Items.Count(i => i.Deleted == true && i.Id == "si_storage_legacy") == 1 && // Legacy storage deleted
|
||||
opts.Items.Any(i => i.Price == "teams-seat-annually" && i.Quantity == 1)));
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_UserHasPremiumPlusOtherProducts_OnlyDeletesPremiumItems(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = "sub_123";
|
||||
user.GatewayCustomerId = "cus_123";
|
||||
|
||||
var currentPeriodEnd = DateTime.UtcNow.AddMonths(1);
|
||||
var mockSubscription = new Subscription
|
||||
{
|
||||
Id = "sub_123",
|
||||
Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = new List<SubscriptionItem>
|
||||
{
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_premium",
|
||||
Price = new Price { Id = "premium-annually" },
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
},
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_other_product",
|
||||
Price = new Price { Id = "some-other-product-id" }, // Non-premium item
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
}
|
||||
}
|
||||
},
|
||||
Metadata = new Dictionary<string, string>()
|
||||
};
|
||||
|
||||
var mockPremiumPlans = CreateTestPremiumPlansList();
|
||||
var mockPlan = CreateTestPlan(
|
||||
PlanType.TeamsAnnually,
|
||||
stripeSeatPlanId: "teams-seat-annually"
|
||||
);
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync("sub_123")
|
||||
.Returns(mockSubscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(mockPremiumPlans);
|
||||
_pricingClient.GetPlanOrThrow(PlanType.TeamsAnnually).Returns(mockPlan);
|
||||
_stripeAdapter.UpdateSubscriptionAsync(Arg.Any<string>(), Arg.Any<SubscriptionUpdateOptions>())
|
||||
.Returns(Task.FromResult(mockSubscription));
|
||||
_organizationRepository.CreateAsync(Arg.Any<Organization>()).Returns(callInfo => Task.FromResult(callInfo.Arg<Organization>()));
|
||||
_organizationApiKeyRepository.CreateAsync(Arg.Any<OrganizationApiKey>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationApiKey>()));
|
||||
_organizationUserRepository.CreateAsync(Arg.Any<OrganizationUser>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationUser>()));
|
||||
_applicationCacheService.UpsertOrganizationAbilityAsync(Arg.Any<Organization>()).Returns(Task.CompletedTask);
|
||||
_userService.SaveUserAsync(user).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT0);
|
||||
|
||||
// Verify that ONLY the premium password manager item is deleted (not other products)
|
||||
// Note: We delete the specific premium item by ID, so other products are untouched
|
||||
await _stripeAdapter.Received(1).UpdateSubscriptionAsync(
|
||||
"sub_123",
|
||||
Arg.Is<SubscriptionUpdateOptions>(opts =>
|
||||
opts.Items.Count == 2 && // 1 deleted (premium password manager) + 1 new seat
|
||||
opts.Items.Count(i => i.Deleted == true && i.Id == "si_premium") == 1 && // Premium item deleted by ID
|
||||
opts.Items.Count(i => i.Id == "si_other_product") == 0 && // Other product NOT in update (untouched)
|
||||
opts.Items.Any(i => i.Price == "teams-seat-annually" && i.Quantity == 1)));
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_UserHasAdditionalStorage_CapturesStorageInMetadata(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = "sub_123";
|
||||
user.GatewayCustomerId = "cus_123";
|
||||
|
||||
var currentPeriodEnd = DateTime.UtcNow.AddMonths(1);
|
||||
var mockSubscription = new Subscription
|
||||
{
|
||||
Id = "sub_123",
|
||||
Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = new List<SubscriptionItem>
|
||||
{
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_premium",
|
||||
Price = new Price { Id = "premium-annually" },
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
},
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_storage",
|
||||
Price = new Price { Id = "personal-storage-gb-annually" },
|
||||
Quantity = 5, // User has 5GB additional storage
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
}
|
||||
}
|
||||
},
|
||||
Metadata = new Dictionary<string, string>()
|
||||
};
|
||||
|
||||
var mockPremiumPlans = CreateTestPremiumPlansList();
|
||||
var mockPlan = CreateTestPlan(
|
||||
PlanType.TeamsAnnually,
|
||||
stripeSeatPlanId: "teams-seat-annually"
|
||||
);
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync("sub_123")
|
||||
.Returns(mockSubscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(mockPremiumPlans);
|
||||
_pricingClient.GetPlanOrThrow(PlanType.TeamsAnnually).Returns(mockPlan);
|
||||
_stripeAdapter.UpdateSubscriptionAsync(Arg.Any<string>(), Arg.Any<SubscriptionUpdateOptions>())
|
||||
.Returns(Task.FromResult(mockSubscription));
|
||||
_organizationRepository.CreateAsync(Arg.Any<Organization>()).Returns(callInfo => Task.FromResult(callInfo.Arg<Organization>()));
|
||||
_organizationApiKeyRepository.CreateAsync(Arg.Any<OrganizationApiKey>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationApiKey>()));
|
||||
_organizationUserRepository.CreateAsync(Arg.Any<OrganizationUser>()).Returns(callInfo => Task.FromResult(callInfo.Arg<OrganizationUser>()));
|
||||
_applicationCacheService.UpsertOrganizationAbilityAsync(Arg.Any<Organization>()).Returns(Task.CompletedTask);
|
||||
_userService.SaveUserAsync(user).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT0);
|
||||
|
||||
// Verify that the additional storage quantity (5) is captured in metadata
|
||||
await _stripeAdapter.Received(1).UpdateSubscriptionAsync(
|
||||
"sub_123",
|
||||
Arg.Is<SubscriptionUpdateOptions>(opts =>
|
||||
opts.Metadata.ContainsKey(StripeConstants.MetadataKeys.PreviousAdditionalStorage) &&
|
||||
opts.Metadata[StripeConstants.MetadataKeys.PreviousAdditionalStorage] == "5" &&
|
||||
opts.Items.Count == 3 && // 2 deleted (premium + storage) + 1 new seat
|
||||
opts.Items.Count(i => i.Deleted == true) == 2));
|
||||
}
|
||||
|
||||
[Theory, BitAutoData]
|
||||
public async Task Run_NoPremiumSubscriptionItemFound_ReturnsBadRequest(User user)
|
||||
{
|
||||
// Arrange
|
||||
user.Premium = true;
|
||||
user.GatewaySubscriptionId = "sub_123";
|
||||
|
||||
var mockSubscription = new Subscription
|
||||
{
|
||||
Id = "sub_123",
|
||||
Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = new List<SubscriptionItem>
|
||||
{
|
||||
new SubscriptionItem
|
||||
{
|
||||
Id = "si_other",
|
||||
Price = new Price { Id = "some-other-product" }, // Not a premium plan
|
||||
CurrentPeriodEnd = DateTime.UtcNow.AddMonths(1)
|
||||
}
|
||||
}
|
||||
},
|
||||
Metadata = new Dictionary<string, string>()
|
||||
};
|
||||
|
||||
var mockPremiumPlans = CreateTestPremiumPlansList();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync("sub_123")
|
||||
.Returns(mockSubscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(mockPremiumPlans);
|
||||
|
||||
// Act
|
||||
var result = await _command.Run(user, "My Organization", "encrypted-key", PlanType.TeamsAnnually);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsT1);
|
||||
var badRequest = result.AsT1;
|
||||
Assert.Equal("Premium subscription item not found.", badRequest.Response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
using Bit.Core.Billing.Constants;
|
||||
using Bit.Core.Billing.Enums;
|
||||
using Bit.Core.Billing.Pricing;
|
||||
using Bit.Core.Billing.Services;
|
||||
using Bit.Core.Billing.Subscriptions.Models;
|
||||
using Bit.Core.Billing.Subscriptions.Queries;
|
||||
using Bit.Core.Entities;
|
||||
using Bit.Core.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using Stripe;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Core.Test.Billing.Subscriptions.Queries;
|
||||
|
||||
using static StripeConstants;
|
||||
|
||||
public class GetBitwardenSubscriptionQueryTests
|
||||
{
|
||||
private readonly ILogger<GetBitwardenSubscriptionQuery> _logger = Substitute.For<ILogger<GetBitwardenSubscriptionQuery>>();
|
||||
private readonly IPricingClient _pricingClient = Substitute.For<IPricingClient>();
|
||||
private readonly IStripeAdapter _stripeAdapter = Substitute.For<IStripeAdapter>();
|
||||
private readonly GetBitwardenSubscriptionQuery _query;
|
||||
|
||||
public GetBitwardenSubscriptionQueryTests()
|
||||
{
|
||||
_query = new GetBitwardenSubscriptionQuery(
|
||||
_logger,
|
||||
_pricingClient,
|
||||
_stripeAdapter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_IncompleteStatus_ReturnsBitwardenSubscriptionWithSuspension()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Incomplete);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.Incomplete, result.Status);
|
||||
Assert.NotNull(result.Suspension);
|
||||
Assert.Equal(subscription.Created.AddHours(23), result.Suspension);
|
||||
Assert.Equal(1, result.GracePeriod);
|
||||
Assert.Null(result.NextCharge);
|
||||
Assert.Null(result.CancelAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_IncompleteExpiredStatus_ReturnsBitwardenSubscriptionWithSuspension()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.IncompleteExpired);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.IncompleteExpired, result.Status);
|
||||
Assert.NotNull(result.Suspension);
|
||||
Assert.Equal(subscription.Created.AddHours(23), result.Suspension);
|
||||
Assert.Equal(1, result.GracePeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_TrialingStatus_ReturnsBitwardenSubscriptionWithNextCharge()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Trialing);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.Trialing, result.Status);
|
||||
Assert.NotNull(result.NextCharge);
|
||||
Assert.Equal(subscription.Items.First().CurrentPeriodEnd, result.NextCharge);
|
||||
Assert.Null(result.Suspension);
|
||||
Assert.Null(result.GracePeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_ActiveStatus_ReturnsBitwardenSubscriptionWithNextCharge()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.Active, result.Status);
|
||||
Assert.NotNull(result.NextCharge);
|
||||
Assert.Equal(subscription.Items.First().CurrentPeriodEnd, result.NextCharge);
|
||||
Assert.Null(result.Suspension);
|
||||
Assert.Null(result.GracePeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_ActiveStatusWithCancelAt_ReturnsCancelAt()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var cancelAt = DateTime.UtcNow.AddMonths(1);
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active, cancelAt: cancelAt);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.Active, result.Status);
|
||||
Assert.Equal(cancelAt, result.CancelAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_PastDueStatus_WithOpenInvoices_ReturnsSuspension()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.PastDue, collectionMethod: "charge_automatically");
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
var openInvoice = CreateInvoice();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
_stripeAdapter.SearchInvoiceAsync(Arg.Any<InvoiceSearchOptions>())
|
||||
.Returns([openInvoice]);
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.PastDue, result.Status);
|
||||
Assert.NotNull(result.Suspension);
|
||||
Assert.Equal(openInvoice.Created.AddDays(14), result.Suspension);
|
||||
Assert.Equal(14, result.GracePeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_PastDueStatus_WithoutOpenInvoices_ReturnsNoSuspension()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.PastDue);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
_stripeAdapter.SearchInvoiceAsync(Arg.Any<InvoiceSearchOptions>())
|
||||
.Returns([]);
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.PastDue, result.Status);
|
||||
Assert.Null(result.Suspension);
|
||||
Assert.Null(result.GracePeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_UnpaidStatus_WithOpenInvoices_ReturnsSuspension()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Unpaid, collectionMethod: "charge_automatically");
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
var openInvoice = CreateInvoice();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
_stripeAdapter.SearchInvoiceAsync(Arg.Any<InvoiceSearchOptions>())
|
||||
.Returns([openInvoice]);
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.Unpaid, result.Status);
|
||||
Assert.NotNull(result.Suspension);
|
||||
Assert.Equal(14, result.GracePeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_CanceledStatus_ReturnsCanceledDate()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var canceledAt = DateTime.UtcNow.AddDays(-5);
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Canceled, canceledAt: canceledAt);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(SubscriptionStatus.Canceled, result.Status);
|
||||
Assert.Equal(canceledAt, result.Canceled);
|
||||
Assert.Null(result.Suspension);
|
||||
Assert.Null(result.NextCharge);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_UnmanagedStatus_ThrowsConflictException()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription("unmanaged_status");
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
await Assert.ThrowsAsync<ConflictException>(() => _query.Run(user));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_WithAdditionalStorage_IncludesStorageInCart()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active, includeStorage: true);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.Cart.PasswordManager.AdditionalStorage);
|
||||
Assert.Equal("additionalStorageGB", result.Cart.PasswordManager.AdditionalStorage.TranslationKey);
|
||||
Assert.Equal(2, result.Cart.PasswordManager.AdditionalStorage.Quantity);
|
||||
Assert.NotNull(result.Storage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_WithoutAdditionalStorage_ExcludesStorageFromCart()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active, includeStorage: false);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.Cart.PasswordManager.AdditionalStorage);
|
||||
Assert.NotNull(result.Storage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_WithCartLevelDiscount_IncludesDiscountInCart()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active);
|
||||
subscription.Customer.Discount = CreateDiscount(discountType: "cart");
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.Cart.Discount);
|
||||
Assert.Equal(BitwardenDiscountType.PercentOff, result.Cart.Discount.Type);
|
||||
Assert.Equal(20, result.Cart.Discount.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_WithProductLevelDiscount_IncludesDiscountInCartItem()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active);
|
||||
var productDiscount = CreateDiscount(discountType: "product", productId: "prod_premium_seat");
|
||||
subscription.Discounts = [productDiscount];
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.Cart.PasswordManager.Seats.Discount);
|
||||
Assert.Equal(BitwardenDiscountType.PercentOff, result.Cart.PasswordManager.Seats.Discount.Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_WithoutMaxStorageGb_ReturnsNullStorage()
|
||||
{
|
||||
var user = CreateUser();
|
||||
user.MaxStorageGb = null;
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.Storage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_CalculatesStorageCorrectly()
|
||||
{
|
||||
var user = CreateUser();
|
||||
user.Storage = 5368709120; // 5 GB in bytes
|
||||
user.MaxStorageGb = 10;
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active, includeStorage: true);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.Storage);
|
||||
Assert.Equal(10, result.Storage.Available);
|
||||
Assert.Equal(5.0, result.Storage.Used);
|
||||
Assert.NotEmpty(result.Storage.ReadableUsed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_TaxEstimation_WithInvoiceUpcomingNoneError_ReturnsZeroTax()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.ThrowsAsync(new StripeException { StripeError = new StripeError { Code = ErrorCodes.InvoiceUpcomingNone } });
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(0, result.Cart.EstimatedTax);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_MissingPasswordManagerSeatsItem_ThrowsConflictException()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active);
|
||||
subscription.Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = []
|
||||
};
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
|
||||
await Assert.ThrowsAsync<ConflictException>(() => _query.Run(user));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_IncludesEstimatedTax()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
var invoice = CreateInvoicePreview(totalTax: 500); // $5.00 tax
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(invoice);
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(5.0m, result.Cart.EstimatedTax);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_SetsCadenceToAnnually()
|
||||
{
|
||||
var user = CreateUser();
|
||||
var subscription = CreateSubscription(SubscriptionStatus.Active);
|
||||
var premiumPlans = CreatePremiumPlans();
|
||||
|
||||
_stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, Arg.Any<SubscriptionGetOptions>())
|
||||
.Returns(subscription);
|
||||
_pricingClient.ListPremiumPlans().Returns(premiumPlans);
|
||||
_stripeAdapter.CreateInvoicePreviewAsync(Arg.Any<InvoiceCreatePreviewOptions>())
|
||||
.Returns(CreateInvoicePreview());
|
||||
|
||||
var result = await _query.Run(user);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(PlanCadenceType.Annually, result.Cart.Cadence);
|
||||
}
|
||||
|
||||
#region Helper Methods
|
||||
|
||||
private static User CreateUser()
|
||||
{
|
||||
return new User
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
GatewaySubscriptionId = "sub_test123",
|
||||
MaxStorageGb = 1,
|
||||
Storage = 1073741824 // 1 GB in bytes
|
||||
};
|
||||
}
|
||||
|
||||
private static Subscription CreateSubscription(
|
||||
string status,
|
||||
bool includeStorage = false,
|
||||
DateTime? cancelAt = null,
|
||||
DateTime? canceledAt = null,
|
||||
string collectionMethod = "charge_automatically")
|
||||
{
|
||||
var currentPeriodEnd = DateTime.UtcNow.AddMonths(1);
|
||||
var items = new List<SubscriptionItem>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Id = "si_premium_seat",
|
||||
Price = new Price
|
||||
{
|
||||
Id = "price_premium_seat",
|
||||
UnitAmountDecimal = 1000,
|
||||
Product = new Product { Id = "prod_premium_seat" }
|
||||
},
|
||||
Quantity = 1,
|
||||
CurrentPeriodStart = DateTime.UtcNow,
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
}
|
||||
};
|
||||
|
||||
if (includeStorage)
|
||||
{
|
||||
items.Add(new SubscriptionItem
|
||||
{
|
||||
Id = "si_storage",
|
||||
Price = new Price
|
||||
{
|
||||
Id = "price_storage",
|
||||
UnitAmountDecimal = 400,
|
||||
Product = new Product { Id = "prod_storage" }
|
||||
},
|
||||
Quantity = 2,
|
||||
CurrentPeriodStart = DateTime.UtcNow,
|
||||
CurrentPeriodEnd = currentPeriodEnd
|
||||
});
|
||||
}
|
||||
|
||||
return new Subscription
|
||||
{
|
||||
Id = "sub_test123",
|
||||
Status = status,
|
||||
Created = DateTime.UtcNow.AddMonths(-1),
|
||||
Customer = new Customer
|
||||
{
|
||||
Id = "cus_test123",
|
||||
Discount = null
|
||||
},
|
||||
Items = new StripeList<SubscriptionItem>
|
||||
{
|
||||
Data = items
|
||||
},
|
||||
CancelAt = cancelAt,
|
||||
CanceledAt = canceledAt,
|
||||
CollectionMethod = collectionMethod,
|
||||
Discounts = []
|
||||
};
|
||||
}
|
||||
|
||||
private static List<Bit.Core.Billing.Pricing.Premium.Plan> CreatePremiumPlans()
|
||||
{
|
||||
return
|
||||
[
|
||||
new()
|
||||
{
|
||||
Name = "Premium",
|
||||
Available = true,
|
||||
Seat = new Bit.Core.Billing.Pricing.Premium.Purchasable
|
||||
{
|
||||
StripePriceId = "price_premium_seat",
|
||||
Price = 10.0m,
|
||||
Provided = 1
|
||||
},
|
||||
Storage = new Bit.Core.Billing.Pricing.Premium.Purchasable
|
||||
{
|
||||
StripePriceId = "price_storage",
|
||||
Price = 4.0m,
|
||||
Provided = 1
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
private static Invoice CreateInvoice()
|
||||
{
|
||||
return new Invoice
|
||||
{
|
||||
Id = "in_test123",
|
||||
Created = DateTime.UtcNow.AddDays(-10),
|
||||
PeriodEnd = DateTime.UtcNow.AddDays(-5),
|
||||
Attempted = true,
|
||||
Status = "open"
|
||||
};
|
||||
}
|
||||
|
||||
private static Invoice CreateInvoicePreview(long totalTax = 0)
|
||||
{
|
||||
var taxes = totalTax > 0
|
||||
? new List<InvoiceTotalTax> { new() { Amount = totalTax } }
|
||||
: new List<InvoiceTotalTax>();
|
||||
|
||||
return new Invoice
|
||||
{
|
||||
Id = "in_preview",
|
||||
TotalTaxes = taxes
|
||||
};
|
||||
}
|
||||
|
||||
private static Discount CreateDiscount(string discountType = "cart", string? productId = null)
|
||||
{
|
||||
var coupon = new Coupon
|
||||
{
|
||||
Valid = true,
|
||||
PercentOff = 20,
|
||||
AppliesTo = discountType == "product" && productId != null
|
||||
? new CouponAppliesTo { Products = [productId] }
|
||||
: new CouponAppliesTo { Products = [] }
|
||||
};
|
||||
|
||||
return new Discount
|
||||
{
|
||||
Coupon = coupon
|
||||
};
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
<PropertyGroup>
|
||||
<IsPackable>false</IsPackable>
|
||||
<RootNamespace>Bit.Core.Test</RootNamespace>
|
||||
<!-- These opt outs should be removed when all warnings are addressed -->
|
||||
<WarningsNotAsErrors>$(WarningsNotAsErrors);CA1304;CA1305</WarningsNotAsErrors>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="$(CoverletCollectorVersion)">
|
||||
@@ -30,7 +32,7 @@
|
||||
<ItemGroup>
|
||||
<!-- Email templates uses .hbs extension, they must be included for emails to work -->
|
||||
<EmbeddedResource Include="**\*.hbs" />
|
||||
|
||||
|
||||
<EmbeddedResource Include="Utilities\data\embeddedResource.txt" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
211
test/Core.Test/Services/PlayIdServiceTests.cs
Normal file
211
test/Core.Test/Services/PlayIdServiceTests.cs
Normal file
@@ -0,0 +1,211 @@
|
||||
using Bit.Core.Services;
|
||||
using Bit.Test.Common.AutoFixture;
|
||||
using Bit.Test.Common.AutoFixture.Attributes;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Core.Test.Services;
|
||||
|
||||
[SutProviderCustomize]
|
||||
public class PlayIdServiceTests
|
||||
{
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public void InPlay_WhenPlayIdSetAndDevelopment_ReturnsTrue(
|
||||
string playId,
|
||||
SutProvider<PlayIdService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IHostEnvironment>().EnvironmentName.Returns(Environments.Development);
|
||||
sutProvider.Sut.PlayId = playId;
|
||||
|
||||
var result = sutProvider.Sut.InPlay(out var resultPlayId);
|
||||
|
||||
Assert.True(result);
|
||||
Assert.Equal(playId, resultPlayId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public void InPlay_WhenPlayIdSetButNotDevelopment_ReturnsFalse(
|
||||
string playId,
|
||||
SutProvider<PlayIdService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IHostEnvironment>().EnvironmentName.Returns(Environments.Production);
|
||||
sutProvider.Sut.PlayId = playId;
|
||||
|
||||
var result = sutProvider.Sut.InPlay(out var resultPlayId);
|
||||
|
||||
Assert.False(result);
|
||||
Assert.Equal(playId, resultPlayId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData((string?)null)]
|
||||
[BitAutoData("")]
|
||||
public void InPlay_WhenPlayIdNullOrEmptyAndDevelopment_ReturnsFalse(
|
||||
string? playId,
|
||||
SutProvider<PlayIdService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IHostEnvironment>().EnvironmentName.Returns(Environments.Development);
|
||||
sutProvider.Sut.PlayId = playId;
|
||||
|
||||
var result = sutProvider.Sut.InPlay(out var resultPlayId);
|
||||
|
||||
Assert.False(result);
|
||||
Assert.Empty(resultPlayId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public void PlayId_CanGetAndSet(string playId)
|
||||
{
|
||||
var hostEnvironment = Substitute.For<IHostEnvironment>();
|
||||
var sut = new PlayIdService(hostEnvironment);
|
||||
|
||||
sut.PlayId = playId;
|
||||
|
||||
Assert.Equal(playId, sut.PlayId);
|
||||
}
|
||||
}
|
||||
|
||||
[SutProviderCustomize]
|
||||
public class NeverPlayIdServicesTests
|
||||
{
|
||||
[Fact]
|
||||
public void InPlay_ReturnsFalse()
|
||||
{
|
||||
var sut = new NeverPlayIdServices();
|
||||
|
||||
var result = sut.InPlay(out var playId);
|
||||
|
||||
Assert.False(result);
|
||||
Assert.Empty(playId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("test-play-id")]
|
||||
[InlineData(null)]
|
||||
public void PlayId_SetterDoesNothing_GetterReturnsNull(string? value)
|
||||
{
|
||||
var sut = new NeverPlayIdServices();
|
||||
|
||||
sut.PlayId = value;
|
||||
|
||||
Assert.Null(sut.PlayId);
|
||||
}
|
||||
}
|
||||
|
||||
[SutProviderCustomize]
|
||||
public class PlayIdSingletonServiceTests
|
||||
{
|
||||
public static IEnumerable<object[]> SutProvider()
|
||||
{
|
||||
var sutProvider = new SutProvider<PlayIdSingletonService>();
|
||||
var httpContext = sutProvider.CreateDependency<HttpContext>();
|
||||
var serviceProvider = sutProvider.CreateDependency<IServiceProvider>();
|
||||
var hostEnvironment = sutProvider.CreateDependency<IHostEnvironment>();
|
||||
var playIdService = new PlayIdService(hostEnvironment);
|
||||
sutProvider.SetDependency(playIdService);
|
||||
httpContext.RequestServices.Returns(serviceProvider);
|
||||
serviceProvider.GetService<PlayIdService>().Returns(playIdService);
|
||||
serviceProvider.GetRequiredService<PlayIdService>().Returns(playIdService);
|
||||
sutProvider.CreateDependency<IHttpContextAccessor>().HttpContext.Returns(httpContext);
|
||||
sutProvider.Create();
|
||||
return [[sutProvider]];
|
||||
}
|
||||
|
||||
private void PrepHttpContext(
|
||||
SutProvider<PlayIdSingletonService> sutProvider)
|
||||
{
|
||||
var httpContext = sutProvider.CreateDependency<HttpContext>();
|
||||
var serviceProvider = sutProvider.CreateDependency<IServiceProvider>();
|
||||
var PlayIdService = sutProvider.CreateDependency<PlayIdService>();
|
||||
httpContext.RequestServices.Returns(serviceProvider);
|
||||
serviceProvider.GetRequiredService<PlayIdService>().Returns(PlayIdService);
|
||||
sutProvider.GetDependency<IHttpContextAccessor>().HttpContext.Returns(httpContext);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitMemberAutoData(nameof(SutProvider))]
|
||||
public void InPlay_WhenNoHttpContext_ReturnsFalse(
|
||||
SutProvider<PlayIdSingletonService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IHttpContextAccessor>().HttpContext.Returns((HttpContext?)null);
|
||||
sutProvider.GetDependency<IHostEnvironment>().EnvironmentName.Returns(Environments.Development);
|
||||
|
||||
var result = sutProvider.Sut.InPlay(out var playId);
|
||||
|
||||
Assert.False(result);
|
||||
Assert.Empty(playId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitMemberAutoData(nameof(SutProvider))]
|
||||
public void InPlay_WhenNotDevelopment_ReturnsFalse(
|
||||
SutProvider<PlayIdSingletonService> sutProvider,
|
||||
string playIdValue)
|
||||
{
|
||||
var scopedPlayIdService = sutProvider.GetDependency<PlayIdService>();
|
||||
scopedPlayIdService.PlayId = playIdValue;
|
||||
sutProvider.GetDependency<IHostEnvironment>().EnvironmentName.Returns(Environments.Production);
|
||||
|
||||
var result = sutProvider.Sut.InPlay(out var playId);
|
||||
|
||||
Assert.False(result);
|
||||
Assert.Empty(playId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitMemberAutoData(nameof(SutProvider))]
|
||||
public void InPlay_WhenDevelopmentAndHttpContextWithPlayId_ReturnsTrue(
|
||||
SutProvider<PlayIdSingletonService> sutProvider,
|
||||
string playIdValue)
|
||||
{
|
||||
sutProvider.GetDependency<PlayIdService>().PlayId = playIdValue;
|
||||
sutProvider.GetDependency<IHostEnvironment>().EnvironmentName.Returns(Environments.Development);
|
||||
|
||||
var result = sutProvider.Sut.InPlay(out var playId);
|
||||
|
||||
Assert.True(result);
|
||||
Assert.Equal(playIdValue, playId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitMemberAutoData(nameof(SutProvider))]
|
||||
public void PlayId_SetterSetsOnScopedService(
|
||||
SutProvider<PlayIdSingletonService> sutProvider,
|
||||
string playIdValue)
|
||||
{
|
||||
var scopedPlayIdService = sutProvider.GetDependency<PlayIdService>();
|
||||
|
||||
sutProvider.Sut.PlayId = playIdValue;
|
||||
|
||||
Assert.Equal(playIdValue, scopedPlayIdService.PlayId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitMemberAutoData(nameof(SutProvider))]
|
||||
public void PlayId_WhenNoHttpContext_GetterReturnsNull(
|
||||
SutProvider<PlayIdSingletonService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IHttpContextAccessor>().HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
var result = sutProvider.Sut.PlayId;
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitMemberAutoData(nameof(SutProvider))]
|
||||
public void PlayId_WhenNoHttpContext_SetterDoesNotThrow(
|
||||
SutProvider<PlayIdSingletonService> sutProvider,
|
||||
string playIdValue)
|
||||
{
|
||||
sutProvider.GetDependency<IHttpContextAccessor>().HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
sutProvider.Sut.PlayId = playIdValue;
|
||||
}
|
||||
}
|
||||
143
test/Core.Test/Services/PlayItemServiceTests.cs
Normal file
143
test/Core.Test/Services/PlayItemServiceTests.cs
Normal file
@@ -0,0 +1,143 @@
|
||||
using Bit.Core.AdminConsole.Entities;
|
||||
using Bit.Core.Entities;
|
||||
using Bit.Core.Repositories;
|
||||
using Bit.Core.Services;
|
||||
using Bit.Test.Common.AutoFixture;
|
||||
using Bit.Test.Common.AutoFixture.Attributes;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Core.Test.Services;
|
||||
|
||||
[SutProviderCustomize]
|
||||
public class PlayItemServiceTests
|
||||
{
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task Record_User_WhenInPlay_RecordsPlayItem(
|
||||
string playId,
|
||||
User user,
|
||||
SutProvider<PlayItemService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IPlayIdService>()
|
||||
.InPlay(out Arg.Any<string>())
|
||||
.Returns(x =>
|
||||
{
|
||||
x[0] = playId;
|
||||
return true;
|
||||
});
|
||||
|
||||
await sutProvider.Sut.Record(user);
|
||||
|
||||
await sutProvider.GetDependency<IPlayItemRepository>()
|
||||
.Received(1)
|
||||
.CreateAsync(Arg.Is<PlayItem>(pd =>
|
||||
pd.PlayId == playId &&
|
||||
pd.UserId == user.Id &&
|
||||
pd.OrganizationId == null));
|
||||
|
||||
sutProvider.GetDependency<ILogger<PlayItemService>>()
|
||||
.Received(1)
|
||||
.Log(
|
||||
LogLevel.Information,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(o => o.ToString().Contains(user.Id.ToString()) && o.ToString().Contains(playId)),
|
||||
null,
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task Record_User_WhenNotInPlay_DoesNotRecordPlayItem(
|
||||
User user,
|
||||
SutProvider<PlayItemService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IPlayIdService>()
|
||||
.InPlay(out Arg.Any<string>())
|
||||
.Returns(x =>
|
||||
{
|
||||
x[0] = null;
|
||||
return false;
|
||||
});
|
||||
|
||||
await sutProvider.Sut.Record(user);
|
||||
|
||||
await sutProvider.GetDependency<IPlayItemRepository>()
|
||||
.DidNotReceive()
|
||||
.CreateAsync(Arg.Any<PlayItem>());
|
||||
|
||||
sutProvider.GetDependency<ILogger<PlayItemService>>()
|
||||
.DidNotReceive()
|
||||
.Log(
|
||||
LogLevel.Information,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task Record_Organization_WhenInPlay_RecordsPlayItem(
|
||||
string playId,
|
||||
Organization organization,
|
||||
SutProvider<PlayItemService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IPlayIdService>()
|
||||
.InPlay(out Arg.Any<string>())
|
||||
.Returns(x =>
|
||||
{
|
||||
x[0] = playId;
|
||||
return true;
|
||||
});
|
||||
|
||||
await sutProvider.Sut.Record(organization);
|
||||
|
||||
await sutProvider.GetDependency<IPlayItemRepository>()
|
||||
.Received(1)
|
||||
.CreateAsync(Arg.Is<PlayItem>(pd =>
|
||||
pd.PlayId == playId &&
|
||||
pd.OrganizationId == organization.Id &&
|
||||
pd.UserId == null));
|
||||
|
||||
sutProvider.GetDependency<ILogger<PlayItemService>>()
|
||||
.Received(1)
|
||||
.Log(
|
||||
LogLevel.Information,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(o => o.ToString().Contains(organization.Id.ToString()) && o.ToString().Contains(playId)),
|
||||
null,
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task Record_Organization_WhenNotInPlay_DoesNotRecordPlayItem(
|
||||
Organization organization,
|
||||
SutProvider<PlayItemService> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IPlayIdService>()
|
||||
.InPlay(out Arg.Any<string>())
|
||||
.Returns(x =>
|
||||
{
|
||||
x[0] = null;
|
||||
return false;
|
||||
});
|
||||
|
||||
await sutProvider.Sut.Record(organization);
|
||||
|
||||
await sutProvider.GetDependency<IPlayItemRepository>()
|
||||
.DidNotReceive()
|
||||
.CreateAsync(Arg.Any<PlayItem>());
|
||||
|
||||
sutProvider.GetDependency<ILogger<PlayItemService>>()
|
||||
.DidNotReceive()
|
||||
.Log(
|
||||
LogLevel.Information,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Bit.Core.Tools.Entities;
|
||||
using Bit.Core.Tools.Enums;
|
||||
using Bit.Core.Tools.Models.Data;
|
||||
using Bit.Core.Tools.Repositories;
|
||||
using Bit.Core.Tools.SendFeatures.Queries;
|
||||
@@ -47,7 +48,7 @@ public class SendAuthenticationQueryTests
|
||||
{
|
||||
// Arrange
|
||||
var sendId = Guid.NewGuid();
|
||||
var send = CreateSend(accessCount: 0, maxAccessCount: 10, emails: emailString, password: null);
|
||||
var send = CreateSend(accessCount: 0, maxAccessCount: 10, emails: emailString, password: null, AuthType.Email);
|
||||
_sendRepository.GetByIdAsync(sendId).Returns(send);
|
||||
|
||||
// Act
|
||||
@@ -63,7 +64,7 @@ public class SendAuthenticationQueryTests
|
||||
{
|
||||
// Arrange
|
||||
var sendId = Guid.NewGuid();
|
||||
var send = CreateSend(accessCount: 0, maxAccessCount: 10, emails: "test@example.com", password: "hashedpassword");
|
||||
var send = CreateSend(accessCount: 0, maxAccessCount: 10, emails: "test@example.com", password: "hashedpassword", AuthType.Email);
|
||||
_sendRepository.GetByIdAsync(sendId).Returns(send);
|
||||
|
||||
// Act
|
||||
@@ -78,7 +79,7 @@ public class SendAuthenticationQueryTests
|
||||
{
|
||||
// Arrange
|
||||
var sendId = Guid.NewGuid();
|
||||
var send = CreateSend(accessCount: 0, maxAccessCount: 10, emails: null, password: null);
|
||||
var send = CreateSend(accessCount: 0, maxAccessCount: 10, emails: null, password: null, AuthType.None);
|
||||
_sendRepository.GetByIdAsync(sendId).Returns(send);
|
||||
|
||||
// Act
|
||||
@@ -105,11 +106,11 @@ public class SendAuthenticationQueryTests
|
||||
public static IEnumerable<object[]> AuthenticationMethodTestCases()
|
||||
{
|
||||
yield return new object[] { null, typeof(NeverAuthenticate) };
|
||||
yield return new object[] { CreateSend(accessCount: 5, maxAccessCount: 5, emails: null, password: null), typeof(NeverAuthenticate) };
|
||||
yield return new object[] { CreateSend(accessCount: 6, maxAccessCount: 5, emails: null, password: null), typeof(NeverAuthenticate) };
|
||||
yield return new object[] { CreateSend(accessCount: 0, maxAccessCount: 10, emails: "test@example.com", password: null), typeof(EmailOtp) };
|
||||
yield return new object[] { CreateSend(accessCount: 0, maxAccessCount: 10, emails: null, password: "hashedpassword"), typeof(ResourcePassword) };
|
||||
yield return new object[] { CreateSend(accessCount: 0, maxAccessCount: 10, emails: null, password: null), typeof(NotAuthenticated) };
|
||||
yield return new object[] { CreateSend(accessCount: 5, maxAccessCount: 5, emails: null, password: null, AuthType.None), typeof(NeverAuthenticate) };
|
||||
yield return new object[] { CreateSend(accessCount: 6, maxAccessCount: 5, emails: null, password: null, AuthType.None), typeof(NeverAuthenticate) };
|
||||
yield return new object[] { CreateSend(accessCount: 0, maxAccessCount: 10, emails: "test@example.com", password: null, AuthType.Email), typeof(EmailOtp) };
|
||||
yield return new object[] { CreateSend(accessCount: 0, maxAccessCount: 10, emails: null, password: "hashedpassword", AuthType.Password), typeof(ResourcePassword) };
|
||||
yield return new object[] { CreateSend(accessCount: 0, maxAccessCount: 10, emails: null, password: null, AuthType.None), typeof(NotAuthenticated) };
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> EmailParsingTestCases()
|
||||
@@ -121,7 +122,7 @@ public class SendAuthenticationQueryTests
|
||||
yield return new object[] { " , test@example.com, ,other@example.com, ", new[] { "test@example.com", "other@example.com" } };
|
||||
}
|
||||
|
||||
private static Send CreateSend(int accessCount, int? maxAccessCount, string? emails, string? password)
|
||||
private static Send CreateSend(int accessCount, int? maxAccessCount, string? emails, string? password, AuthType? authType)
|
||||
{
|
||||
return new Send
|
||||
{
|
||||
@@ -129,7 +130,8 @@ public class SendAuthenticationQueryTests
|
||||
AccessCount = accessCount,
|
||||
MaxAccessCount = maxAccessCount,
|
||||
Emails = emails,
|
||||
Password = password
|
||||
Password = password,
|
||||
AuthType = authType
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ namespace Bit.Core.Test.Tools.Services;
|
||||
public class SendOwnerQueryTests
|
||||
{
|
||||
private readonly ISendRepository _sendRepository;
|
||||
private readonly IFeatureService _featureService;
|
||||
private readonly IUserService _userService;
|
||||
private readonly SendOwnerQuery _sendOwnerQuery;
|
||||
private readonly Guid _currentUserId = Guid.NewGuid();
|
||||
@@ -21,11 +20,10 @@ public class SendOwnerQueryTests
|
||||
public SendOwnerQueryTests()
|
||||
{
|
||||
_sendRepository = Substitute.For<ISendRepository>();
|
||||
_featureService = Substitute.For<IFeatureService>();
|
||||
_userService = Substitute.For<IUserService>();
|
||||
_user = new ClaimsPrincipal();
|
||||
_userService.GetProperUserId(_user).Returns(_currentUserId);
|
||||
_sendOwnerQuery = new SendOwnerQuery(_sendRepository, _featureService, _userService);
|
||||
_sendOwnerQuery = new SendOwnerQuery(_sendRepository, _userService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -84,7 +82,7 @@ public class SendOwnerQueryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOwned_WithFeatureFlagEnabled_ReturnsAllSends()
|
||||
public async Task GetOwned_ReturnsAllSendsIncludingEmailOTP()
|
||||
{
|
||||
// Arrange
|
||||
var sends = new List<Send>
|
||||
@@ -94,7 +92,6 @@ public class SendOwnerQueryTests
|
||||
CreateSend(Guid.NewGuid(), _currentUserId, emails: "other@example.com")
|
||||
};
|
||||
_sendRepository.GetManyByUserIdAsync(_currentUserId).Returns(sends);
|
||||
_featureService.IsEnabled(FeatureFlagKeys.PM19051_ListEmailOtpSends).Returns(true);
|
||||
|
||||
// Act
|
||||
var result = await _sendOwnerQuery.GetOwned(_user);
|
||||
@@ -105,28 +102,6 @@ public class SendOwnerQueryTests
|
||||
Assert.Contains(sends[1], result);
|
||||
Assert.Contains(sends[2], result);
|
||||
await _sendRepository.Received(1).GetManyByUserIdAsync(_currentUserId);
|
||||
_featureService.Received(1).IsEnabled(FeatureFlagKeys.PM19051_ListEmailOtpSends);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOwned_WithFeatureFlagDisabled_FiltersOutEmailOtpSends()
|
||||
{
|
||||
// Arrange
|
||||
var sendWithoutEmails = CreateSend(Guid.NewGuid(), _currentUserId, emails: null);
|
||||
var sendWithEmails = CreateSend(Guid.NewGuid(), _currentUserId, emails: "test@example.com");
|
||||
var sends = new List<Send> { sendWithoutEmails, sendWithEmails };
|
||||
_sendRepository.GetManyByUserIdAsync(_currentUserId).Returns(sends);
|
||||
_featureService.IsEnabled(FeatureFlagKeys.PM19051_ListEmailOtpSends).Returns(false);
|
||||
|
||||
// Act
|
||||
var result = await _sendOwnerQuery.GetOwned(_user);
|
||||
|
||||
// Assert
|
||||
Assert.Single(result);
|
||||
Assert.Contains(sendWithoutEmails, result);
|
||||
Assert.DoesNotContain(sendWithEmails, result);
|
||||
await _sendRepository.Received(1).GetManyByUserIdAsync(_currentUserId);
|
||||
_featureService.Received(1).IsEnabled(FeatureFlagKeys.PM19051_ListEmailOtpSends);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -147,7 +122,6 @@ public class SendOwnerQueryTests
|
||||
// Arrange
|
||||
var emptySends = new List<Send>();
|
||||
_sendRepository.GetManyByUserIdAsync(_currentUserId).Returns(emptySends);
|
||||
_featureService.IsEnabled(FeatureFlagKeys.PM19051_ListEmailOtpSends).Returns(true);
|
||||
|
||||
// Act
|
||||
var result = await _sendOwnerQuery.GetOwned(_user);
|
||||
|
||||
219
test/Core.Test/Utilities/EnumMemberJsonConverterTests.cs
Normal file
219
test/Core.Test/Utilities/EnumMemberJsonConverterTests.cs
Normal file
@@ -0,0 +1,219 @@
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Bit.Core.Utilities;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Core.Test.Utilities;
|
||||
|
||||
public class EnumMemberJsonConverterTests
|
||||
{
|
||||
[Fact]
|
||||
public void Serialize_WithEnumMemberAttribute_UsesAttributeValue()
|
||||
{
|
||||
// Arrange
|
||||
var obj = new EnumConverterTestObject
|
||||
{
|
||||
Status = EnumConverterTestStatus.InProgress
|
||||
};
|
||||
const string expectedJsonString = "{\"Status\":\"in_progress\"}";
|
||||
|
||||
// Act
|
||||
var jsonString = JsonSerializer.Serialize(obj);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedJsonString, jsonString);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Serialize_WithoutEnumMemberAttribute_UsesEnumName()
|
||||
{
|
||||
// Arrange
|
||||
var obj = new EnumConverterTestObject
|
||||
{
|
||||
Status = EnumConverterTestStatus.Pending
|
||||
};
|
||||
const string expectedJsonString = "{\"Status\":\"Pending\"}";
|
||||
|
||||
// Act
|
||||
var jsonString = JsonSerializer.Serialize(obj);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedJsonString, jsonString);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Serialize_MultipleValues_SerializesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var obj = new EnumConverterTestObjectWithMultiple
|
||||
{
|
||||
Status1 = EnumConverterTestStatus.Active,
|
||||
Status2 = EnumConverterTestStatus.InProgress,
|
||||
Status3 = EnumConverterTestStatus.Pending
|
||||
};
|
||||
const string expectedJsonString = "{\"Status1\":\"active\",\"Status2\":\"in_progress\",\"Status3\":\"Pending\"}";
|
||||
|
||||
// Act
|
||||
var jsonString = JsonSerializer.Serialize(obj);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedJsonString, jsonString);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WithEnumMemberAttribute_ReturnsCorrectEnumValue()
|
||||
{
|
||||
// Arrange
|
||||
const string json = "{\"Status\":\"in_progress\"}";
|
||||
|
||||
// Act
|
||||
var obj = JsonSerializer.Deserialize<EnumConverterTestObject>(json);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(EnumConverterTestStatus.InProgress, obj.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_WithoutEnumMemberAttribute_ReturnsCorrectEnumValue()
|
||||
{
|
||||
// Arrange
|
||||
const string json = "{\"Status\":\"Pending\"}";
|
||||
|
||||
// Act
|
||||
var obj = JsonSerializer.Deserialize<EnumConverterTestObject>(json);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(EnumConverterTestStatus.Pending, obj.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_MultipleValues_DeserializesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
const string json = "{\"Status1\":\"active\",\"Status2\":\"in_progress\",\"Status3\":\"Pending\"}";
|
||||
|
||||
// Act
|
||||
var obj = JsonSerializer.Deserialize<EnumConverterTestObjectWithMultiple>(json);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(EnumConverterTestStatus.Active, obj.Status1);
|
||||
Assert.Equal(EnumConverterTestStatus.InProgress, obj.Status2);
|
||||
Assert.Equal(EnumConverterTestStatus.Pending, obj.Status3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_InvalidEnumString_ThrowsJsonException()
|
||||
{
|
||||
// Arrange
|
||||
const string json = "{\"Status\":\"invalid_value\"}";
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<EnumConverterTestObject>(json));
|
||||
Assert.Contains("Unable to convert 'invalid_value' to EnumConverterTestStatus", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_EmptyString_ThrowsJsonException()
|
||||
{
|
||||
// Arrange
|
||||
const string json = "{\"Status\":\"\"}";
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<EnumConverterTestObject>(json));
|
||||
Assert.Contains("Unable to convert '' to EnumConverterTestStatus", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WithEnumMemberAttribute_PreservesValue()
|
||||
{
|
||||
// Arrange
|
||||
var originalObj = new EnumConverterTestObject
|
||||
{
|
||||
Status = EnumConverterTestStatus.Completed
|
||||
};
|
||||
|
||||
// Act
|
||||
var json = JsonSerializer.Serialize(originalObj);
|
||||
var deserializedObj = JsonSerializer.Deserialize<EnumConverterTestObject>(json);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(originalObj.Status, deserializedObj.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WithoutEnumMemberAttribute_PreservesValue()
|
||||
{
|
||||
// Arrange
|
||||
var originalObj = new EnumConverterTestObject
|
||||
{
|
||||
Status = EnumConverterTestStatus.Pending
|
||||
};
|
||||
|
||||
// Act
|
||||
var json = JsonSerializer.Serialize(originalObj);
|
||||
var deserializedObj = JsonSerializer.Deserialize<EnumConverterTestObject>(json);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(originalObj.Status, deserializedObj.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Serialize_AllEnumValues_ProducesExpectedStrings()
|
||||
{
|
||||
// Arrange & Act & Assert
|
||||
Assert.Equal("\"Pending\"", JsonSerializer.Serialize(EnumConverterTestStatus.Pending, CreateOptions()));
|
||||
Assert.Equal("\"active\"", JsonSerializer.Serialize(EnumConverterTestStatus.Active, CreateOptions()));
|
||||
Assert.Equal("\"in_progress\"", JsonSerializer.Serialize(EnumConverterTestStatus.InProgress, CreateOptions()));
|
||||
Assert.Equal("\"completed\"", JsonSerializer.Serialize(EnumConverterTestStatus.Completed, CreateOptions()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_AllEnumValues_ReturnsCorrectEnums()
|
||||
{
|
||||
// Arrange & Act & Assert
|
||||
Assert.Equal(EnumConverterTestStatus.Pending, JsonSerializer.Deserialize<EnumConverterTestStatus>("\"Pending\"", CreateOptions()));
|
||||
Assert.Equal(EnumConverterTestStatus.Active, JsonSerializer.Deserialize<EnumConverterTestStatus>("\"active\"", CreateOptions()));
|
||||
Assert.Equal(EnumConverterTestStatus.InProgress, JsonSerializer.Deserialize<EnumConverterTestStatus>("\"in_progress\"", CreateOptions()));
|
||||
Assert.Equal(EnumConverterTestStatus.Completed, JsonSerializer.Deserialize<EnumConverterTestStatus>("\"completed\"", CreateOptions()));
|
||||
}
|
||||
|
||||
private static JsonSerializerOptions CreateOptions()
|
||||
{
|
||||
var options = new JsonSerializerOptions();
|
||||
options.Converters.Add(new EnumMemberJsonConverter<EnumConverterTestStatus>());
|
||||
return options;
|
||||
}
|
||||
}
|
||||
|
||||
public class EnumConverterTestObject
|
||||
{
|
||||
[JsonConverter(typeof(EnumMemberJsonConverter<EnumConverterTestStatus>))]
|
||||
public EnumConverterTestStatus Status { get; set; }
|
||||
}
|
||||
|
||||
public class EnumConverterTestObjectWithMultiple
|
||||
{
|
||||
[JsonConverter(typeof(EnumMemberJsonConverter<EnumConverterTestStatus>))]
|
||||
public EnumConverterTestStatus Status1 { get; set; }
|
||||
|
||||
[JsonConverter(typeof(EnumMemberJsonConverter<EnumConverterTestStatus>))]
|
||||
public EnumConverterTestStatus Status2 { get; set; }
|
||||
|
||||
[JsonConverter(typeof(EnumMemberJsonConverter<EnumConverterTestStatus>))]
|
||||
public EnumConverterTestStatus Status3 { get; set; }
|
||||
}
|
||||
|
||||
public enum EnumConverterTestStatus
|
||||
{
|
||||
Pending, // No EnumMemberAttribute
|
||||
|
||||
[EnumMember(Value = "active")]
|
||||
Active,
|
||||
|
||||
[EnumMember(Value = "in_progress")]
|
||||
InProgress,
|
||||
|
||||
[EnumMember(Value = "completed")]
|
||||
Completed
|
||||
}
|
||||
@@ -12,7 +12,6 @@ internal class OrganizationCipher : ICustomization
|
||||
{
|
||||
fixture.Customize<Cipher>(composer => composer
|
||||
.With(c => c.OrganizationId, OrganizationId ?? Guid.NewGuid())
|
||||
.Without(c => c.ArchivedDate)
|
||||
.Without(c => c.UserId));
|
||||
fixture.Customize<CipherDetails>(composer => composer
|
||||
.With(c => c.OrganizationId, Guid.NewGuid())
|
||||
@@ -28,7 +27,6 @@ internal class UserCipher : ICustomization
|
||||
{
|
||||
fixture.Customize<Cipher>(composer => composer
|
||||
.With(c => c.UserId, UserId ?? Guid.NewGuid())
|
||||
.Without(c => c.ArchivedDate)
|
||||
.Without(c => c.OrganizationId));
|
||||
fixture.Customize<CipherDetails>(composer => composer
|
||||
.With(c => c.UserId, Guid.NewGuid())
|
||||
|
||||
@@ -16,16 +16,15 @@ namespace Bit.Core.Test.Vault.Commands;
|
||||
public class ArchiveCiphersCommandTest
|
||||
{
|
||||
[Theory]
|
||||
[BitAutoData(true, false, 1, 1, 1)]
|
||||
[BitAutoData(false, false, 1, 0, 1)]
|
||||
[BitAutoData(false, true, 1, 0, 1)]
|
||||
[BitAutoData(true, true, 1, 0, 1)]
|
||||
public async Task ArchiveAsync_Works(
|
||||
bool isEditable, bool hasOrganizationId,
|
||||
[BitAutoData(true, 1, 1, 1)]
|
||||
[BitAutoData(false, 1, 0, 1)]
|
||||
[BitAutoData(false, 1, 0, 1)]
|
||||
[BitAutoData(true, 1, 0, 1)]
|
||||
public async Task ArchiveManyAsync_Works(
|
||||
bool hasOrganizationId,
|
||||
int cipherRepoCalls, int resultCountFromQuery, int pushNotificationsCalls,
|
||||
SutProvider<ArchiveCiphersCommand> sutProvider, CipherDetails cipher, User user)
|
||||
{
|
||||
cipher.Edit = isEditable;
|
||||
cipher.OrganizationId = hasOrganizationId ? Guid.NewGuid() : null;
|
||||
|
||||
var cipherList = new List<CipherDetails> { cipher };
|
||||
@@ -46,4 +45,33 @@ public class ArchiveCiphersCommandTest
|
||||
await sutProvider.GetDependency<IPushNotificationService>().Received(pushNotificationsCalls)
|
||||
.PushSyncCiphersAsync(user.Id);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task ArchiveManyAsync_SetsArchivedDateOnReturnedCiphers(
|
||||
SutProvider<ArchiveCiphersCommand> sutProvider,
|
||||
CipherDetails cipher,
|
||||
User user)
|
||||
{
|
||||
// Allow organization cipher to be archived in this test
|
||||
cipher.OrganizationId = Guid.Parse("3f2504e0-4f89-11d3-9a0c-0305e82c3301");
|
||||
|
||||
sutProvider.GetDependency<ICipherRepository>()
|
||||
.GetManyByUserIdAsync(user.Id)
|
||||
.Returns(new List<CipherDetails> { cipher });
|
||||
|
||||
var repoRevisionDate = DateTime.UtcNow;
|
||||
|
||||
sutProvider.GetDependency<ICipherRepository>()
|
||||
.ArchiveAsync(Arg.Any<IEnumerable<Guid>>(), user.Id)
|
||||
.Returns(repoRevisionDate);
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.ArchiveManyAsync(new[] { cipher.Id }, user.Id);
|
||||
|
||||
// Assert
|
||||
var archivedCipher = Assert.Single(result);
|
||||
Assert.Equal(repoRevisionDate, archivedCipher.RevisionDate);
|
||||
Assert.Equal(repoRevisionDate, archivedCipher.ArchivedDate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,16 +16,15 @@ namespace Bit.Core.Test.Vault.Commands;
|
||||
public class UnarchiveCiphersCommandTest
|
||||
{
|
||||
[Theory]
|
||||
[BitAutoData(true, false, 1, 1, 1)]
|
||||
[BitAutoData(false, false, 1, 0, 1)]
|
||||
[BitAutoData(false, true, 1, 0, 1)]
|
||||
[BitAutoData(true, true, 1, 1, 1)]
|
||||
[BitAutoData(true, 1, 1, 1)]
|
||||
[BitAutoData(false, 1, 0, 1)]
|
||||
[BitAutoData(false, 1, 0, 1)]
|
||||
[BitAutoData(true, 1, 1, 1)]
|
||||
public async Task UnarchiveAsync_Works(
|
||||
bool isEditable, bool hasOrganizationId,
|
||||
bool hasOrganizationId,
|
||||
int cipherRepoCalls, int resultCountFromQuery, int pushNotificationsCalls,
|
||||
SutProvider<UnarchiveCiphersCommand> sutProvider, CipherDetails cipher, User user)
|
||||
{
|
||||
cipher.Edit = isEditable;
|
||||
cipher.OrganizationId = hasOrganizationId ? Guid.NewGuid() : null;
|
||||
|
||||
var cipherList = new List<CipherDetails> { cipher };
|
||||
@@ -46,4 +45,33 @@ public class UnarchiveCiphersCommandTest
|
||||
await sutProvider.GetDependency<IPushNotificationService>().Received(pushNotificationsCalls)
|
||||
.PushSyncCiphersAsync(user.Id);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task UnarchiveAsync_ClearsArchivedDateOnReturnedCiphers(
|
||||
SutProvider<UnarchiveCiphersCommand> sutProvider,
|
||||
CipherDetails cipher,
|
||||
User user)
|
||||
{
|
||||
cipher.OrganizationId = null;
|
||||
cipher.ArchivedDate = DateTime.UtcNow;
|
||||
|
||||
sutProvider.GetDependency<ICipherRepository>()
|
||||
.GetManyByUserIdAsync(user.Id)
|
||||
.Returns(new List<CipherDetails> { cipher });
|
||||
|
||||
var repoRevisionDate = DateTime.UtcNow.AddMinutes(1);
|
||||
|
||||
sutProvider.GetDependency<ICipherRepository>()
|
||||
.UnarchiveAsync(Arg.Any<IEnumerable<Guid>>(), user.Id)
|
||||
.Returns(repoRevisionDate);
|
||||
|
||||
// Act
|
||||
var result = await sutProvider.Sut.UnarchiveManyAsync(new[] { cipher.Id }, user.Id);
|
||||
|
||||
// Assert
|
||||
var unarchivedCipher = Assert.Single(result);
|
||||
Assert.Equal(repoRevisionDate, unarchivedCipher.RevisionDate);
|
||||
Assert.Null(unarchivedCipher.ArchivedDate);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user