1
0
mirror of https://github.com/bitwarden/server.git synced 2025-06-16 07:50:49 -05:00

Merge branch 'main' into pm-18699-add-trial-path-to-stripe-metadata

This commit is contained in:
cyprain-okeke 2025-06-10 12:56:26 +01:00 committed by GitHub
commit eac8700f30
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
38 changed files with 10506 additions and 849 deletions

View File

@ -3,7 +3,7 @@
"isRoot": true, "isRoot": true,
"tools": { "tools": {
"swashbuckle.aspnetcore.cli": { "swashbuckle.aspnetcore.cli": {
"version": "7.2.0", "version": "7.3.2",
"commands": ["swagger"] "commands": ["swagger"]
}, },
"dotnet-ef": { "dotnet-ef": {

View File

@ -550,6 +550,15 @@ public class ProviderBillingService(
[ [
new CustomerTaxIdDataOptions { Type = taxIdType, Value = taxInfo.TaxIdNumber } new CustomerTaxIdDataOptions { Type = taxIdType, Value = taxInfo.TaxIdNumber }
]; ];
if (taxIdType == StripeConstants.TaxIdType.SpanishNIF)
{
options.TaxIdData.Add(new CustomerTaxIdDataOptions
{
Type = StripeConstants.TaxIdType.EUVAT,
Value = $"ES{taxInfo.TaxIdNumber}"
});
}
} }
if (!string.IsNullOrEmpty(provider.DiscountId)) if (!string.IsNullOrEmpty(provider.DiscountId))

View File

@ -242,10 +242,32 @@ public class OrganizationsController : Controller
Seats = organization.Seats Seats = organization.Seats
}; };
if (model.PlanType.HasValue)
{
var freePlan = await _pricingClient.GetPlanOrThrow(model.PlanType.Value);
var isDowngradingToFree = organization.PlanType != PlanType.Free && model.PlanType.Value == PlanType.Free;
if (isDowngradingToFree)
{
if (model.Seats.HasValue && model.Seats.Value > freePlan.PasswordManager.MaxSeats)
{
TempData["Error"] = $"Organizations with more than {freePlan.PasswordManager.MaxSeats} seats cannot be downgraded to the Free plan";
return RedirectToAction("Edit", new { id });
}
if (model.MaxCollections > freePlan.PasswordManager.MaxCollections)
{
TempData["Error"] = $"Organizations with more than {freePlan.PasswordManager.MaxCollections} collections cannot be downgraded to the Free plan. Your organization currently has {organization.MaxCollections} collections.";
return RedirectToAction("Edit", new { id });
}
model.MaxStorageGb = null;
model.ExpirationDate = null;
model.Enabled = true;
}
}
UpdateOrganization(organization, model); UpdateOrganization(organization, model);
var plan = await _pricingClient.GetPlanOrThrow(organization.PlanType); var plan = await _pricingClient.GetPlanOrThrow(organization.PlanType);
if (organization.UseSecretsManager && !plan.SupportsSecretsManager) if (organization.UseSecretsManager && !plan.SupportsSecretsManager)
{ {
TempData["Error"] = "Plan does not support Secrets Manager"; TempData["Error"] = "Plan does not support Secrets Manager";

View File

@ -34,7 +34,7 @@
<PackageReference Include="AspNetCore.HealthChecks.SqlServer" Version="8.0.2" /> <PackageReference Include="AspNetCore.HealthChecks.SqlServer" Version="8.0.2" />
<PackageReference Include="AspNetCore.HealthChecks.Uris" Version="8.0.1" /> <PackageReference Include="AspNetCore.HealthChecks.Uris" Version="8.0.1" />
<PackageReference Include="Azure.Messaging.EventGrid" Version="4.25.0" /> <PackageReference Include="Azure.Messaging.EventGrid" Version="4.25.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="7.3.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -4,6 +4,7 @@ using Bit.Api.AdminConsole.Models.Request.Organizations;
using Bit.Api.Billing.Models.Requests; using Bit.Api.Billing.Models.Requests;
using Bit.Api.Billing.Models.Responses; using Bit.Api.Billing.Models.Responses;
using Bit.Api.Billing.Queries.Organizations; using Bit.Api.Billing.Queries.Organizations;
using Bit.Core.Billing.Enums;
using Bit.Core.Billing.Models; using Bit.Core.Billing.Models;
using Bit.Core.Billing.Models.Sales; using Bit.Core.Billing.Models.Sales;
using Bit.Core.Billing.Pricing; using Bit.Core.Billing.Pricing;
@ -280,17 +281,36 @@ public class OrganizationBillingController(
} }
var organization = await organizationRepository.GetByIdAsync(organizationId); var organization = await organizationRepository.GetByIdAsync(organizationId);
if (organization == null) if (organization == null)
{ {
return Error.NotFound(); return Error.NotFound();
} }
var existingPlan = organization.PlanType;
var organizationSignup = model.ToOrganizationSignup(user); var organizationSignup = model.ToOrganizationSignup(user);
var sale = OrganizationSale.From(organization, organizationSignup); var sale = OrganizationSale.From(organization, organizationSignup);
var plan = await pricingClient.GetPlanOrThrow(model.PlanType); var plan = await pricingClient.GetPlanOrThrow(model.PlanType);
sale.Organization.PlanType = plan.Type; sale.Organization.PlanType = plan.Type;
sale.Organization.Plan = plan.Name; sale.Organization.Plan = plan.Name;
sale.SubscriptionSetup.SkipTrial = true; sale.SubscriptionSetup.SkipTrial = true;
if (existingPlan == PlanType.Free && organization.GatewaySubscriptionId is not null)
{
sale.Organization.UseTotp = plan.HasTotp;
sale.Organization.UseGroups = plan.HasGroups;
sale.Organization.UseDirectory = plan.HasDirectory;
sale.Organization.SelfHost = plan.HasSelfHost;
sale.Organization.UsersGetPremium = plan.UsersGetPremium;
sale.Organization.UseEvents = plan.HasEvents;
sale.Organization.Use2fa = plan.Has2fa;
sale.Organization.UseApi = plan.HasApi;
sale.Organization.UsePolicies = plan.HasPolicies;
sale.Organization.UseSso = plan.HasSso;
sale.Organization.UseResetPassword = plan.HasResetPassword;
sale.Organization.UseKeyConnector = plan.HasKeyConnector;
sale.Organization.UseScim = plan.HasScim;
sale.Organization.UseCustomPermissions = plan.HasCustomPermissions;
sale.Organization.UseOrganizationDomains = plan.HasOrganizationDomains;
sale.Organization.MaxCollections = plan.PasswordManager.MaxCollections;
}
if (organizationSignup.PaymentMethodType == null || string.IsNullOrEmpty(organizationSignup.PaymentToken)) if (organizationSignup.PaymentMethodType == null || string.IsNullOrEmpty(organizationSignup.PaymentToken))
{ {

View File

@ -42,7 +42,6 @@ public class CiphersController : Controller
private readonly ICurrentContext _currentContext; private readonly ICurrentContext _currentContext;
private readonly ILogger<CiphersController> _logger; private readonly ILogger<CiphersController> _logger;
private readonly GlobalSettings _globalSettings; private readonly GlobalSettings _globalSettings;
private readonly IFeatureService _featureService;
private readonly IOrganizationCiphersQuery _organizationCiphersQuery; private readonly IOrganizationCiphersQuery _organizationCiphersQuery;
private readonly IApplicationCacheService _applicationCacheService; private readonly IApplicationCacheService _applicationCacheService;
private readonly ICollectionRepository _collectionRepository; private readonly ICollectionRepository _collectionRepository;
@ -57,7 +56,6 @@ public class CiphersController : Controller
ICurrentContext currentContext, ICurrentContext currentContext,
ILogger<CiphersController> logger, ILogger<CiphersController> logger,
GlobalSettings globalSettings, GlobalSettings globalSettings,
IFeatureService featureService,
IOrganizationCiphersQuery organizationCiphersQuery, IOrganizationCiphersQuery organizationCiphersQuery,
IApplicationCacheService applicationCacheService, IApplicationCacheService applicationCacheService,
ICollectionRepository collectionRepository) ICollectionRepository collectionRepository)
@ -71,7 +69,6 @@ public class CiphersController : Controller
_currentContext = currentContext; _currentContext = currentContext;
_logger = logger; _logger = logger;
_globalSettings = globalSettings; _globalSettings = globalSettings;
_featureService = featureService;
_organizationCiphersQuery = organizationCiphersQuery; _organizationCiphersQuery = organizationCiphersQuery;
_applicationCacheService = applicationCacheService; _applicationCacheService = applicationCacheService;
_collectionRepository = collectionRepository; _collectionRepository = collectionRepository;
@ -375,11 +372,6 @@ public class CiphersController : Controller
private async Task<bool> CanDeleteOrRestoreCipherAsAdminAsync(Guid organizationId, IEnumerable<Guid> cipherIds) private async Task<bool> CanDeleteOrRestoreCipherAsAdminAsync(Guid organizationId, IEnumerable<Guid> cipherIds)
{ {
if (!_featureService.IsEnabled(FeatureFlagKeys.LimitItemDeletion))
{
return await CanEditCipherAsAdminAsync(organizationId, cipherIds);
}
var org = _currentContext.GetOrganization(organizationId); var org = _currentContext.GetOrganization(organizationId);
// If we're not an "admin" or if we're a provider user we don't need to check the ciphers // If we're not an "admin" or if we're a provider user we don't need to check the ciphers

View File

@ -10,7 +10,7 @@
<ProjectReference Include="..\Core\Core.csproj" /> <ProjectReference Include="..\Core\Core.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="7.3.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -96,6 +96,12 @@ public static class StripeConstants
public const string Reverse = "reverse"; public const string Reverse = "reverse";
} }
public static class TaxIdType
{
public const string EUVAT = "eu_vat";
public const string SpanishNIF = "es_cif";
}
public static class ValidateTaxLocationTiming public static class ValidateTaxLocationTiming
{ {
public const string Deferred = "deferred"; public const string Deferred = "deferred";

View File

@ -247,12 +247,23 @@ public class OrganizationBillingService(
organization.Id, organization.Id,
customerSetup.TaxInformation.Country, customerSetup.TaxInformation.Country,
customerSetup.TaxInformation.TaxId); customerSetup.TaxInformation.TaxId);
throw new BadRequestException("billingTaxIdTypeInferenceError");
} }
customerCreateOptions.TaxIdData = customerCreateOptions.TaxIdData =
[ [
new() { Type = taxIdType, Value = customerSetup.TaxInformation.TaxId } new() { Type = taxIdType, Value = customerSetup.TaxInformation.TaxId }
]; ];
if (taxIdType == StripeConstants.TaxIdType.SpanishNIF)
{
customerCreateOptions.TaxIdData.Add(new CustomerTaxIdDataOptions
{
Type = StripeConstants.TaxIdType.EUVAT,
Value = $"ES{customerSetup.TaxInformation.TaxId}"
});
}
} }
var (paymentMethodType, paymentMethodToken) = customerSetup.TokenizedPaymentSource; var (paymentMethodType, paymentMethodToken) = customerSetup.TokenizedPaymentSource;

View File

@ -648,6 +648,12 @@ public class SubscriberService(
{ {
await stripeAdapter.TaxIdCreateAsync(customer.Id, await stripeAdapter.TaxIdCreateAsync(customer.Id,
new TaxIdCreateOptions { Type = taxIdType, Value = taxInformation.TaxId }); new TaxIdCreateOptions { Type = taxIdType, Value = taxInformation.TaxId });
if (taxIdType == StripeConstants.TaxIdType.SpanishNIF)
{
await stripeAdapter.TaxIdCreateAsync(customer.Id,
new TaxIdCreateOptions { Type = StripeConstants.TaxIdType.EUVAT, Value = $"ES{taxInformation.TaxId}" });
}
} }
catch (StripeException e) catch (StripeException e)
{ {

View File

@ -80,6 +80,15 @@ public class PreviewTaxAmountCommand(
Value = taxInformation.TaxId Value = taxInformation.TaxId
} }
]; ];
if (taxIdType == StripeConstants.TaxIdType.SpanishNIF)
{
options.CustomerDetails.TaxIds.Add(new InvoiceCustomerDetailsTaxIdOptions
{
Type = StripeConstants.TaxIdType.EUVAT,
Value = $"ES{parameters.TaxInformation.TaxId}"
});
}
} }
if (planType.GetProductTier() == ProductTierType.Families) if (planType.GetProductTier() == ProductTierType.Families)

View File

@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using Bit.Core.Enums;
using Bit.Core.Utilities; using Bit.Core.Utilities;
#nullable enable #nullable enable
@ -14,6 +15,8 @@ public class Collection : ITableObject<Guid>
public string? ExternalId { get; set; } public string? ExternalId { get; set; }
public DateTime CreationDate { get; set; } = DateTime.UtcNow; public DateTime CreationDate { get; set; } = DateTime.UtcNow;
public DateTime RevisionDate { get; set; } = DateTime.UtcNow; public DateTime RevisionDate { get; set; } = DateTime.UtcNow;
public CollectionType Type { get; set; } = CollectionType.SharedCollection;
public string? DefaultUserCollectionEmail { get; set; }
public void SetNewId() public void SetNewId()
{ {

View File

@ -0,0 +1,7 @@
namespace Bit.Core.Enums;
public enum CollectionType
{
SharedCollection = 0,
DefaultUserCollection = 1,
}

View File

@ -842,7 +842,13 @@ public class StripePaymentService : IPaymentService
try try
{ {
await _stripeAdapter.TaxIdCreateAsync(customer.Id, await _stripeAdapter.TaxIdCreateAsync(customer.Id,
new TaxIdCreateOptions { Type = taxInfo.TaxIdType, Value = taxInfo.TaxIdNumber, }); new TaxIdCreateOptions { Type = taxInfo.TaxIdType, Value = taxInfo.TaxIdNumber });
if (taxInfo.TaxIdType == StripeConstants.TaxIdType.SpanishNIF)
{
await _stripeAdapter.TaxIdCreateAsync(customer.Id,
new TaxIdCreateOptions { Type = StripeConstants.TaxIdType.EUVAT, Value = $"ES{taxInfo.TaxIdNumber}" });
}
} }
catch (StripeException e) catch (StripeException e)
{ {
@ -1000,6 +1006,15 @@ public class StripePaymentService : IPaymentService
Value = parameters.TaxInformation.TaxId Value = parameters.TaxInformation.TaxId
} }
]; ];
if (taxIdType == StripeConstants.TaxIdType.SpanishNIF)
{
options.CustomerDetails.TaxIds.Add(new InvoiceCustomerDetailsTaxIdOptions
{
Type = StripeConstants.TaxIdType.EUVAT,
Value = $"ES{parameters.TaxInformation.TaxId}"
});
}
} }
if (!string.IsNullOrWhiteSpace(gatewayCustomerId)) if (!string.IsNullOrWhiteSpace(gatewayCustomerId))
@ -1154,6 +1169,15 @@ public class StripePaymentService : IPaymentService
Value = parameters.TaxInformation.TaxId Value = parameters.TaxInformation.TaxId
} }
]; ];
if (taxIdType == StripeConstants.TaxIdType.SpanishNIF)
{
options.CustomerDetails.TaxIds.Add(new InvoiceCustomerDetailsTaxIdOptions
{
Type = StripeConstants.TaxIdType.EUVAT,
Value = $"ES{parameters.TaxInformation.TaxId}"
});
}
} }
Customer gatewayCustomer = null; Customer gatewayCustomer = null;

View File

@ -821,11 +821,6 @@ public class CipherService : ICipherService
private async Task<bool> UserCanDeleteAsync(CipherDetails cipher, Guid userId) private async Task<bool> UserCanDeleteAsync(CipherDetails cipher, Guid userId)
{ {
if (!_featureService.IsEnabled(FeatureFlagKeys.LimitItemDeletion))
{
return await UserCanEditAsync(cipher, userId);
}
var user = await _userService.GetUserByIdAsync(userId); var user = await _userService.GetUserByIdAsync(userId);
var organizationAbility = cipher.OrganizationId.HasValue ? var organizationAbility = cipher.OrganizationId.HasValue ?
await _applicationCacheService.GetOrganizationAbilityAsync(cipher.OrganizationId.Value) : null; await _applicationCacheService.GetOrganizationAbilityAsync(cipher.OrganizationId.Value) : null;
@ -835,11 +830,6 @@ public class CipherService : ICipherService
private async Task<bool> UserCanRestoreAsync(CipherDetails cipher, Guid userId) private async Task<bool> UserCanRestoreAsync(CipherDetails cipher, Guid userId)
{ {
if (!_featureService.IsEnabled(FeatureFlagKeys.LimitItemDeletion))
{
return await UserCanEditAsync(cipher, userId);
}
var user = await _userService.GetUserByIdAsync(userId); var user = await _userService.GetUserByIdAsync(userId);
var organizationAbility = cipher.OrganizationId.HasValue ? var organizationAbility = cipher.OrganizationId.HasValue ?
await _applicationCacheService.GetOrganizationAbilityAsync(cipher.OrganizationId.Value) : null; await _applicationCacheService.GetOrganizationAbilityAsync(cipher.OrganizationId.Value) : null;
@ -1059,17 +1049,11 @@ public class CipherService : ICipherService
} }
// This method is used to filter ciphers based on the user's permissions to delete them. // This method is used to filter ciphers based on the user's permissions to delete them.
// It supports both the old and new logic depending on the feature flag.
private async Task<List<T>> FilterCiphersByDeletePermission<T>( private async Task<List<T>> FilterCiphersByDeletePermission<T>(
IEnumerable<T> ciphers, IEnumerable<T> ciphers,
HashSet<Guid> cipherIdsSet, HashSet<Guid> cipherIdsSet,
Guid userId) where T : CipherDetails Guid userId) where T : CipherDetails
{ {
if (!_featureService.IsEnabled(FeatureFlagKeys.LimitItemDeletion))
{
return ciphers.Where(c => cipherIdsSet.Contains(c.Id) && c.Edit).ToList();
}
var user = await _userService.GetUserByIdAsync(userId); var user = await _userService.GetUserByIdAsync(userId);
var organizationAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); var organizationAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync();

View File

@ -7,7 +7,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="7.2.0" /> <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="7.3.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -4,7 +4,9 @@
@Name VARCHAR(MAX), @Name VARCHAR(MAX),
@ExternalId NVARCHAR(300), @ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7), @CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7) @RevisionDate DATETIME2(7),
@DefaultUserCollectionEmail NVARCHAR(256) = NULL,
@Type TINYINT = 0
AS AS
BEGIN BEGIN
SET NOCOUNT ON SET NOCOUNT ON
@ -16,7 +18,9 @@ BEGIN
[Name], [Name],
[ExternalId], [ExternalId],
[CreationDate], [CreationDate],
[RevisionDate] [RevisionDate],
[DefaultUserCollectionEmail],
[Type]
) )
VALUES VALUES
( (
@ -25,7 +29,9 @@ BEGIN
@Name, @Name,
@ExternalId, @ExternalId,
@CreationDate, @CreationDate,
@RevisionDate @RevisionDate,
@DefaultUserCollectionEmail,
@Type
) )
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @Id, @OrganizationId EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @Id, @OrganizationId

View File

@ -6,12 +6,14 @@ CREATE PROCEDURE [dbo].[Collection_CreateWithGroupsAndUsers]
@CreationDate DATETIME2(7), @CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7), @RevisionDate DATETIME2(7),
@Groups AS [dbo].[CollectionAccessSelectionType] READONLY, @Groups AS [dbo].[CollectionAccessSelectionType] READONLY,
@Users AS [dbo].[CollectionAccessSelectionType] READONLY @Users AS [dbo].[CollectionAccessSelectionType] READONLY,
@DefaultUserCollectionEmail NVARCHAR(256) = NULL,
@Type TINYINT = 0
AS AS
BEGIN BEGIN
SET NOCOUNT ON SET NOCOUNT ON
EXEC [dbo].[Collection_Create] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate EXEC [dbo].[Collection_Create] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate, @DefaultUserCollectionEmail, @Type
-- Groups -- Groups
;WITH [AvailableGroupsCTE] AS( ;WITH [AvailableGroupsCTE] AS(

View File

@ -13,7 +13,9 @@ BEGIN
ExternalId, ExternalId,
MIN([ReadOnly]) AS [ReadOnly], MIN([ReadOnly]) AS [ReadOnly],
MIN([HidePasswords]) AS [HidePasswords], MIN([HidePasswords]) AS [HidePasswords],
MAX([Manage]) AS [Manage] MAX([Manage]) AS [Manage],
[DefaultUserCollectionEmail],
[Type]
FROM FROM
[dbo].[UserCollectionDetails](@UserId) [dbo].[UserCollectionDetails](@UserId)
GROUP BY GROUP BY
@ -22,5 +24,7 @@ BEGIN
[Name], [Name],
CreationDate, CreationDate,
RevisionDate, RevisionDate,
ExternalId ExternalId,
[DefaultUserCollectionEmail],
[Type]
END END

View File

@ -4,7 +4,9 @@
@Name VARCHAR(MAX), @Name VARCHAR(MAX),
@ExternalId NVARCHAR(300), @ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7), @CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7) @RevisionDate DATETIME2(7),
@DefaultUserCollectionEmail NVARCHAR(256) = NULL,
@Type TINYINT = 0
AS AS
BEGIN BEGIN
SET NOCOUNT ON SET NOCOUNT ON
@ -16,7 +18,9 @@ BEGIN
[Name] = @Name, [Name] = @Name,
[ExternalId] = @ExternalId, [ExternalId] = @ExternalId,
[CreationDate] = @CreationDate, [CreationDate] = @CreationDate,
[RevisionDate] = @RevisionDate [RevisionDate] = @RevisionDate,
[DefaultUserCollectionEmail] = @DefaultUserCollectionEmail,
[Type] = @Type
WHERE WHERE
[Id] = @Id [Id] = @Id

View File

@ -6,12 +6,14 @@
@CreationDate DATETIME2(7), @CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7), @RevisionDate DATETIME2(7),
@Groups AS [dbo].[CollectionAccessSelectionType] READONLY, @Groups AS [dbo].[CollectionAccessSelectionType] READONLY,
@Users AS [dbo].[CollectionAccessSelectionType] READONLY @Users AS [dbo].[CollectionAccessSelectionType] READONLY,
@DefaultUserCollectionEmail NVARCHAR(256) = NULL,
@Type TINYINT = 0
AS AS
BEGIN BEGIN
SET NOCOUNT ON SET NOCOUNT ON
EXEC [dbo].[Collection_Update] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate EXEC [dbo].[Collection_Update] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate, @DefaultUserCollectionEmail, @Type
-- Groups -- Groups
-- Delete groups that are no longer in source -- Delete groups that are no longer in source

View File

@ -5,6 +5,8 @@
[ExternalId] NVARCHAR (300) NULL, [ExternalId] NVARCHAR (300) NULL,
[CreationDate] DATETIME2 (7) NOT NULL, [CreationDate] DATETIME2 (7) NOT NULL,
[RevisionDate] DATETIME2 (7) NOT NULL, [RevisionDate] DATETIME2 (7) NOT NULL,
[DefaultUserCollectionEmail] NVARCHAR(256) NULL,
[Type] TINYINT NOT NULL DEFAULT(0),
CONSTRAINT [PK_Collection] PRIMARY KEY CLUSTERED ([Id] ASC), CONSTRAINT [PK_Collection] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Collection_Organization] FOREIGN KEY ([OrganizationId]) REFERENCES [dbo].[Organization] ([Id]) ON DELETE CASCADE CONSTRAINT [FK_Collection_Organization] FOREIGN KEY ([OrganizationId]) REFERENCES [dbo].[Organization] ([Id]) ON DELETE CASCADE
); );

View File

@ -73,7 +73,9 @@ BEGIN
C.[Name], C.[Name],
C.[CreationDate], C.[CreationDate],
C.[RevisionDate], C.[RevisionDate],
C.[ExternalId] C.[ExternalId],
C.[DefaultUserCollectionEmail],
C.[Type]
IF (@IncludeAccessRelationships = 1) IF (@IncludeAccessRelationships = 1)
BEGIN BEGIN

View File

@ -73,7 +73,9 @@ BEGIN
C.[Name], C.[Name],
C.[CreationDate], C.[CreationDate],
C.[RevisionDate], C.[RevisionDate],
C.[ExternalId] C.[ExternalId],
C.[DefaultUserCollectionEmail],
C.[Type]
IF (@IncludeAccessRelationships = 1) IF (@IncludeAccessRelationships = 1)
BEGIN BEGIN

View File

@ -4,7 +4,6 @@ using Bit.Api.Vault.Controllers;
using Bit.Api.Vault.Models; using Bit.Api.Vault.Models;
using Bit.Api.Vault.Models.Request; using Bit.Api.Vault.Models.Request;
using Bit.Api.Vault.Models.Response; using Bit.Api.Vault.Models.Response;
using Bit.Core;
using Bit.Core.Context; using Bit.Core.Context;
using Bit.Core.Entities; using Bit.Core.Entities;
using Bit.Core.Enums; using Bit.Core.Enums;
@ -169,6 +168,7 @@ public class CiphersControllerTests
} }
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails); sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
@ -197,65 +197,7 @@ public class CiphersControllerTests
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task DeleteAdmin_WithOwnerOrAdmin_WithEditPermission_DeletesCipher( public async Task DeleteAdmin_WithOwnerOrAdmin_WithManagePermission_DeletesCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Edit = true;
cipherDetails.Manage = false;
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails>
{
cipherDetails
});
await sutProvider.Sut.DeleteAdmin(cipherDetails.Id);
await sutProvider.GetDependency<ICipherService>().Received(1).DeleteAsync(cipherDetails, userId, true);
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task DeleteAdmin_WithOwnerOrAdmin_WithoutEditPermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Edit = false;
cipherDetails.Manage = false;
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails>
{
cipherDetails
});
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteAdmin(cipherDetails.Id));
await sutProvider.GetDependency<ICipherService>().DidNotReceive().DeleteAsync(Arg.Any<CipherDetails>(), Arg.Any<Guid>(), Arg.Any<bool>());
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task DeleteAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithManagePermission_DeletesCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId, OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -266,7 +208,6 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -293,7 +234,7 @@ public class CiphersControllerTests
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task DeleteAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException( public async Task DeleteAdmin_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId, OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -304,7 +245,6 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -339,11 +279,22 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails); sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id) .GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id)
.Returns(new List<CipherOrganizationDetails> { new() { Id = cipherDetails.Id } }); .Returns(new List<CipherOrganizationDetails>
{
new() { Id = cipherDetails.Id, OrganizationId = cipherDetails.OrganizationId }
});
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = true
});
await sutProvider.Sut.DeleteAdmin(cipherDetails.Id); await sutProvider.Sut.DeleteAdmin(cipherDetails.Id);
@ -426,10 +377,14 @@ public class CiphersControllerTests
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteAdmin(cipher.Id)); await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteAdmin(cipher.Id));
} }
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task DeleteManyAdmin_WithOwnerOrAdmin_WithEditPermission_DeletesCiphers( public async Task DeleteManyAdmin_WithOwnerOrAdmin_WithManagePermission_DeletesCiphers(
OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers, OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -437,74 +392,6 @@ public class CiphersControllerTests
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList(); model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(ciphers.Select(c => new CipherDetails
{
Id = c.Id,
OrganizationId = organization.Id,
Edit = true
}).ToList());
await sutProvider.Sut.DeleteManyAdmin(model);
await sutProvider.GetDependency<ICipherService>()
.Received(1)
.DeleteManyAsync(
Arg.Is<IEnumerable<Guid>>(ids =>
ids.All(id => model.Ids.Contains(id.ToString())) && ids.Count() == model.Ids.Count()),
userId, organization.Id, true);
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task DeleteManyAdmin_WithOwnerOrAdmin_WithoutEditPermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
model.OrganizationId = organization.Id.ToString();
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>()
.GetProperUserId(default)
.ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>()
.GetOrganization(new Guid(model.OrganizationId))
.Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByOrganizationIdAsync(new Guid(model.OrganizationId))
.Returns(ciphers);
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(new Guid(model.OrganizationId))
.Returns(new OrganizationAbility
{
Id = new Guid(model.OrganizationId),
AllowAdminAccessToAllCollectionItems = false,
});
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteManyAdmin(model));
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task DeleteManyAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithManagePermission_DeletesCiphers(
OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
model.OrganizationId = organization.Id.ToString();
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -540,7 +427,7 @@ public class CiphersControllerTests
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task DeleteManyAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException( public async Task DeleteManyAdmin_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers, OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -548,7 +435,6 @@ public class CiphersControllerTests
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList(); model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -586,10 +472,18 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id) .GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id)
.Returns(ciphers.Select(c => new CipherOrganizationDetails { Id = c.Id }).ToList()); .Returns(ciphers.Select(c => new CipherOrganizationDetails { Id = c.Id, OrganizationId = organization.Id }).ToList());
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = true
});
await sutProvider.Sut.DeleteManyAdmin(model); await sutProvider.Sut.DeleteManyAdmin(model);
@ -688,67 +582,14 @@ public class CiphersControllerTests
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteManyAdmin(model)); await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteManyAdmin(model));
} }
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteAdmin_WithOwnerOrAdmin_WithEditPermission_SoftDeletesCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Edit = true;
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails>
{
cipherDetails
});
await sutProvider.Sut.PutDeleteAdmin(cipherDetails.Id);
await sutProvider.GetDependency<ICipherService>().Received(1).SoftDeleteAsync(cipherDetails, userId, true);
}
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteAdmin_WithOwnerOrAdmin_WithoutEditPermission_ThrowsNotFoundException( public async Task PutDeleteAdmin_WithOwnerOrAdmin_WithManagePermission_SoftDeletesCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Edit = false;
cipherDetails.Manage = false;
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails>
{
cipherDetails
});
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutDeleteAdmin(cipherDetails.Id));
await sutProvider.GetDependency<ICipherService>().DidNotReceive().SoftDeleteAsync(Arg.Any<CipherDetails>(), Arg.Any<Guid>(), Arg.Any<bool>());
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithManagePermission_SoftDeletesCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId, OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -759,7 +600,6 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -786,7 +626,7 @@ public class CiphersControllerTests
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException( public async Task PutDeleteAdmin_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId, OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -797,7 +637,6 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -833,12 +672,20 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails); sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id) .GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id)
.Returns(new List<CipherOrganizationDetails> { new() { Id = cipherDetails.Id } }); .Returns(new List<CipherOrganizationDetails> { new() { Id = cipherDetails.Id, OrganizationId = organization.Id } });
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = true
});
await sutProvider.Sut.PutDeleteAdmin(cipherDetails.Id); await sutProvider.Sut.PutDeleteAdmin(cipherDetails.Id);
@ -856,6 +703,7 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails); sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetManyByOrganizationIdAsync(organization.Id).Returns(new List<Cipher> { cipherDetails }); sutProvider.GetDependency<ICipherRepository>().GetManyByOrganizationIdAsync(organization.Id).Returns(new List<Cipher> { cipherDetails });
@ -890,6 +738,70 @@ public class CiphersControllerTests
await sutProvider.GetDependency<ICipherService>().Received(1).SoftDeleteAsync(cipherDetails, userId, true); await sutProvider.GetDependency<ICipherService>().Received(1).SoftDeleteAsync(cipherDetails, userId, true);
} }
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteAdmin_WithOwnerOrAdmin_WithEditPermission_WithLimitItemDeletionFalse_SoftDeletesCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Edit = true;
cipherDetails.Manage = false; // Only Edit permission, not Manage
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails> { cipherDetails });
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = false
});
await sutProvider.Sut.PutDeleteAdmin(cipherDetails.Id);
await sutProvider.GetDependency<ICipherService>().Received(1).SoftDeleteAsync(cipherDetails, userId, true);
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteAdmin_WithOwnerOrAdmin_WithEditPermission_WithLimitItemDeletionTrue_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Edit = true;
cipherDetails.Manage = false; // Only Edit permission, not Manage
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails> { cipherDetails });
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = true
});
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutDeleteAdmin(cipherDetails.Id));
}
[Theory] [Theory]
[BitAutoData] [BitAutoData]
public async Task PutDeleteAdmin_WithCustomUser_WithEditAnyCollectionFalse_ThrowsNotFoundException( public async Task PutDeleteAdmin_WithCustomUser_WithEditAnyCollectionFalse_ThrowsNotFoundException(
@ -922,10 +834,14 @@ public class CiphersControllerTests
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutDeleteAdmin(cipher.Id)); await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutDeleteAdmin(cipher.Id));
} }
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteManyAdmin_WithOwnerOrAdmin_WithEditPermission_SoftDeletesCiphers( public async Task PutDeleteManyAdmin_WithOwnerOrAdmin_WithManagePermission_SoftDeletesCiphers(
OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers, OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -933,65 +849,6 @@ public class CiphersControllerTests
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList(); model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(ciphers.Select(c => new CipherDetails
{
Id = c.Id,
OrganizationId = organization.Id,
Edit = true
}).ToList());
await sutProvider.Sut.PutDeleteManyAdmin(model);
await sutProvider.GetDependency<ICipherService>()
.Received(1)
.SoftDeleteManyAsync(
Arg.Is<IEnumerable<Guid>>(ids =>
ids.All(id => model.Ids.Contains(id.ToString())) && ids.Count() == model.Ids.Count()),
userId, organization.Id, true);
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteManyAdmin_WithOwnerOrAdmin_WithoutEditPermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
model.OrganizationId = organization.Id.ToString();
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(ciphers.Select(c => new CipherDetails
{
Id = c.Id,
OrganizationId = organization.Id,
Edit = false
}).ToList());
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutDeleteManyAdmin(model));
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteManyAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithManagePermission_SoftDeletesCiphers(
OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
model.OrganizationId = organization.Id.ToString();
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -1027,7 +884,7 @@ public class CiphersControllerTests
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task PutDeleteManyAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException( public async Task PutDeleteManyAdmin_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers, OrganizationUserType organizationUserType, CipherBulkDeleteRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -1035,7 +892,6 @@ public class CiphersControllerTests
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList(); model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -1073,10 +929,18 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id) .GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id)
.Returns(ciphers.Select(c => new CipherOrganizationDetails { Id = c.Id }).ToList()); .Returns(ciphers.Select(c => new CipherOrganizationDetails { Id = c.Id, OrganizationId = organization.Id }).ToList());
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = true
});
await sutProvider.Sut.PutDeleteManyAdmin(model); await sutProvider.Sut.PutDeleteManyAdmin(model);
@ -1099,7 +963,14 @@ public class CiphersControllerTests
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList(); model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType; organization.Type = organizationUserType;
// Set organization ID on ciphers to avoid "Cipher needs to belong to a user or an organization" error
foreach (var cipher in ciphers)
{
cipher.OrganizationId = organization.Id;
}
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetManyByOrganizationIdAsync(organization.Id).Returns(ciphers); sutProvider.GetDependency<ICipherRepository>().GetManyByOrganizationIdAsync(organization.Id).Returns(ciphers);
sutProvider.GetDependency<IApplicationCacheService>().GetOrganizationAbilityAsync(organization.Id).Returns(new OrganizationAbility sutProvider.GetDependency<IApplicationCacheService>().GetOrganizationAbilityAsync(organization.Id).Returns(new OrganizationAbility
@ -1130,7 +1001,14 @@ public class CiphersControllerTests
organization.Type = OrganizationUserType.Custom; organization.Type = OrganizationUserType.Custom;
organization.Permissions.EditAnyCollection = true; organization.Permissions.EditAnyCollection = true;
// Set organization ID on ciphers to avoid "Cipher needs to belong to a user or an organization" error
foreach (var cipher in ciphers)
{
cipher.OrganizationId = organization.Id;
}
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetManyByOrganizationIdAsync(organization.Id).Returns(ciphers); sutProvider.GetDependency<ICipherRepository>().GetManyByOrganizationIdAsync(organization.Id).Returns(ciphers);
@ -1175,68 +1053,14 @@ public class CiphersControllerTests
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutDeleteManyAdmin(model)); await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutDeleteManyAdmin(model));
} }
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreAdmin_WithOwnerOrAdmin_WithEditPermission_RestoresCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Type = CipherType.Login;
cipherDetails.Data = JsonSerializer.Serialize(new CipherLoginData());
cipherDetails.Edit = true;
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails>
{
cipherDetails
});
var result = await sutProvider.Sut.PutRestoreAdmin(cipherDetails.Id);
Assert.IsType<CipherMiniResponseModel>(result);
await sutProvider.GetDependency<ICipherService>().Received(1).RestoreAsync(cipherDetails, userId, true);
}
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreAdmin_WithOwnerOrAdmin_WithoutEditPermission_ThrowsNotFoundException( public async Task PutRestoreAdmin_WithOwnerOrAdmin_WithManagePermission_RestoresCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Edit = false;
cipherDetails.Manage = false;
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails>
{
cipherDetails
});
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutRestoreAdmin(cipherDetails.Id));
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithManagePermission_RestoresCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId, OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -1249,7 +1073,6 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -1277,7 +1100,7 @@ public class CiphersControllerTests
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException( public async Task PutRestoreAdmin_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId, OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -1288,7 +1111,6 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -1323,11 +1145,19 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails); sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id) .GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organization.Id)
.Returns(new List<CipherOrganizationDetails> { new() { Id = cipherDetails.Id } }); .Returns(new List<CipherOrganizationDetails> { new() { Id = cipherDetails.Id, OrganizationId = organization.Id } });
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = true
});
var result = await sutProvider.Sut.PutRestoreAdmin(cipherDetails.Id); var result = await sutProvider.Sut.PutRestoreAdmin(cipherDetails.Id);
@ -1386,6 +1216,75 @@ public class CiphersControllerTests
await sutProvider.GetDependency<ICipherService>().Received(1).RestoreAsync(cipherDetails, userId, true); await sutProvider.GetDependency<ICipherService>().Received(1).RestoreAsync(cipherDetails, userId, true);
} }
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreAdmin_WithOwnerOrAdmin_WithEditPermission_LimitItemDeletionFalse_RestoresCipher(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Type = CipherType.Login;
cipherDetails.Data = JsonSerializer.Serialize(new CipherLoginData());
cipherDetails.Edit = true;
cipherDetails.Manage = false; // Only Edit permission, not Manage
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails> { cipherDetails });
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = false // Permissive mode - Edit permission should work
});
var result = await sutProvider.Sut.PutRestoreAdmin(cipherDetails.Id);
Assert.IsType<CipherMiniResponseModel>(result);
await sutProvider.GetDependency<ICipherService>().Received(1).RestoreAsync(cipherDetails, userId, true);
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreAdmin_WithOwnerOrAdmin_WithEditPermission_LimitItemDeletionTrue_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherDetails cipherDetails, Guid userId,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
cipherDetails.UserId = null;
cipherDetails.OrganizationId = organization.Id;
cipherDetails.Type = CipherType.Login;
cipherDetails.Data = JsonSerializer.Serialize(new CipherLoginData());
cipherDetails.Edit = true;
cipherDetails.Manage = false; // Only Edit permission, not Manage
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>().GetByIdAsync(cipherDetails.Id, userId).Returns(cipherDetails);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(new List<CipherDetails> { cipherDetails });
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = true // Restrictive mode - Edit permission should NOT work
});
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutRestoreAdmin(cipherDetails.Id));
}
[Theory] [Theory]
[BitAutoData] [BitAutoData]
public async Task PutRestoreAdmin_WithCustomUser_WithEditAnyCollectionFalse_ThrowsNotFoundException( public async Task PutRestoreAdmin_WithCustomUser_WithEditAnyCollectionFalse_ThrowsNotFoundException(
@ -1420,10 +1319,14 @@ public class CiphersControllerTests
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutRestoreAdmin(cipherDetails.Id)); await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutRestoreAdmin(cipherDetails.Id));
} }
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreManyAdmin_WithOwnerOrAdmin_WithEditPermission_RestoresCiphers( public async Task PutRestoreManyAdmin_WithOwnerOrAdmin_WithManagePermission_RestoresCiphers(
OrganizationUserType organizationUserType, CipherBulkRestoreRequestModel model, Guid userId, List<Cipher> ciphers, OrganizationUserType organizationUserType, CipherBulkRestoreRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -1431,77 +1334,6 @@ public class CiphersControllerTests
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList(); model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(ciphers.Select(c => new CipherDetails
{
Id = c.Id,
OrganizationId = organization.Id,
Edit = true
}).ToList());
var cipherOrgDetails = ciphers.Select(c => new CipherOrganizationDetails
{
Id = c.Id,
OrganizationId = organization.Id
}).ToList();
sutProvider.GetDependency<ICipherService>()
.RestoreManyAsync(Arg.Is<HashSet<Guid>>(ids =>
ids.All(id => model.Ids.Contains(id.ToString())) && ids.Count == model.Ids.Count()),
userId, organization.Id, true)
.Returns(cipherOrgDetails);
var result = await sutProvider.Sut.PutRestoreManyAdmin(model);
await sutProvider.GetDependency<ICipherService>().Received(1)
.RestoreManyAsync(
Arg.Is<HashSet<Guid>>(ids =>
ids.All(id => model.Ids.Contains(id.ToString())) && ids.Count == model.Ids.Count()),
userId, organization.Id, true);
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreManyAdmin_WithOwnerOrAdmin_WithoutEditPermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherBulkRestoreRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
model.OrganizationId = organization.Id;
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(userId)
.Returns(ciphers.Select(c => new CipherDetails
{
Id = c.Id,
OrganizationId = organization.Id,
Edit = false,
Type = CipherType.Login,
Data = JsonSerializer.Serialize(new CipherLoginData())
}).ToList());
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.PutRestoreManyAdmin(model));
}
[Theory]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreManyAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithManagePermission_RestoresCiphers(
OrganizationUserType organizationUserType, CipherBulkRestoreRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{
model.OrganizationId = organization.Id;
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -1553,7 +1385,7 @@ public class CiphersControllerTests
[Theory] [Theory]
[BitAutoData(OrganizationUserType.Owner)] [BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Admin)] [BitAutoData(OrganizationUserType.Admin)]
public async Task PutRestoreManyAdmin_WithLimitItemDeletionEnabled_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException( public async Task PutRestoreManyAdmin_WithOwnerOrAdmin_WithoutManagePermission_ThrowsNotFoundException(
OrganizationUserType organizationUserType, CipherBulkRestoreRequestModel model, Guid userId, List<Cipher> ciphers, OrganizationUserType organizationUserType, CipherBulkRestoreRequestModel model, Guid userId, List<Cipher> ciphers,
CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider) CurrentContextOrganization organization, SutProvider<CiphersController> sutProvider)
{ {
@ -1561,7 +1393,6 @@ public class CiphersControllerTests
model.Ids = ciphers.Select(c => c.Id.ToString()).ToList(); model.Ids = ciphers.Select(c => c.Id.ToString()).ToList();
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IFeatureService>().IsEnabled(FeatureFlagKeys.LimitItemDeletion).Returns(true);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId }); sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
@ -1599,6 +1430,7 @@ public class CiphersControllerTests
organization.Type = organizationUserType; organization.Type = organizationUserType;
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId); sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<IUserService>().GetUserByPrincipalAsync(default).ReturnsForAnyArgs(new User { Id = userId });
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization); sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
var cipherOrgDetails = ciphers.Select(c => new CipherOrganizationDetails var cipherOrgDetails = ciphers.Select(c => new CipherOrganizationDetails
@ -1614,9 +1446,16 @@ public class CiphersControllerTests
.Returns(cipherOrgDetails); .Returns(cipherOrgDetails);
sutProvider.GetDependency<ICipherService>() sutProvider.GetDependency<ICipherService>()
.RestoreManyAsync(Arg.Is<HashSet<Guid>>(ids => .RestoreManyAsync(Arg.Is<HashSet<Guid>>(ids =>
ids.All(id => model.Ids.Contains(id.ToString()) && ids.Count == model.Ids.Count())), ids.All(id => model.Ids.Contains(id.ToString())) && ids.Count() == model.Ids.Count()),
userId, organization.Id, true) userId, organization.Id, true)
.Returns(cipherOrgDetails); .Returns(cipherOrgDetails);
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(organization.Id)
.Returns(new OrganizationAbility
{
Id = organization.Id,
LimitItemDeletion = true
});
var result = await sutProvider.Sut.PutRestoreManyAdmin(model); var result = await sutProvider.Sut.PutRestoreManyAdmin(model);

View File

@ -10,7 +10,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" /> <PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="MartinCostello.Logging.XUnit" Version="0.5.1" /> <PackageReference Include="MartinCostello.Logging.XUnit" Version="0.5.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Rnwood.SmtpServer" Version="3.1.0-ci0868" /> <PackageReference Include="Rnwood.SmtpServer" Version="3.1.0-ci0868" />

View File

@ -673,13 +673,21 @@ public class CipherServiceTests
[BitAutoData] [BitAutoData]
public async Task RestoreAsync_UpdatesUserCipher(Guid restoringUserId, CipherDetails cipher, SutProvider<CipherService> sutProvider) public async Task RestoreAsync_UpdatesUserCipher(Guid restoringUserId, CipherDetails cipher, SutProvider<CipherService> sutProvider)
{ {
sutProvider.GetDependency<ICipherRepository>().GetCanEditByIdAsync(restoringUserId, cipher.Id).Returns(true); cipher.UserId = restoringUserId;
cipher.OrganizationId = null;
var initialRevisionDate = new DateTime(1970, 1, 1, 0, 0, 0); var initialRevisionDate = new DateTime(1970, 1, 1, 0, 0, 0);
cipher.DeletedDate = initialRevisionDate; cipher.DeletedDate = initialRevisionDate;
cipher.RevisionDate = initialRevisionDate; cipher.RevisionDate = initialRevisionDate;
await sutProvider.Sut.RestoreAsync(cipher, restoringUserId, cipher.OrganizationId.HasValue); sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(restoringUserId)
.Returns(new User
{
Id = restoringUserId,
});
await sutProvider.Sut.RestoreAsync(cipher, restoringUserId);
Assert.Null(cipher.DeletedDate); Assert.Null(cipher.DeletedDate);
Assert.NotEqual(initialRevisionDate, cipher.RevisionDate); Assert.NotEqual(initialRevisionDate, cipher.RevisionDate);
@ -688,15 +696,28 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task RestoreAsync_UpdatesOrganizationCipher(Guid restoringUserId, CipherDetails cipher, SutProvider<CipherService> sutProvider) public async Task RestoreAsync_UpdatesOrganizationCipher(Guid restoringUserId, CipherDetails cipher, User user, SutProvider<CipherService> sutProvider)
{ {
sutProvider.GetDependency<ICipherRepository>().GetCanEditByIdAsync(restoringUserId, cipher.Id).Returns(true); cipher.OrganizationId = Guid.NewGuid();
cipher.Edit = false;
cipher.Manage = true;
sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(restoringUserId)
.Returns(user);
sutProvider.GetDependency<IApplicationCacheService>()
.GetOrganizationAbilityAsync(cipher.OrganizationId.Value)
.Returns(new OrganizationAbility
{
Id = cipher.OrganizationId.Value,
LimitItemDeletion = true
});
var initialRevisionDate = new DateTime(1970, 1, 1, 0, 0, 0); var initialRevisionDate = new DateTime(1970, 1, 1, 0, 0, 0);
cipher.DeletedDate = initialRevisionDate; cipher.DeletedDate = initialRevisionDate;
cipher.RevisionDate = initialRevisionDate; cipher.RevisionDate = initialRevisionDate;
await sutProvider.Sut.RestoreAsync(cipher, restoringUserId, cipher.OrganizationId.HasValue); await sutProvider.Sut.RestoreAsync(cipher, restoringUserId);
Assert.Null(cipher.DeletedDate); Assert.Null(cipher.DeletedDate);
Assert.NotEqual(initialRevisionDate, cipher.RevisionDate); Assert.NotEqual(initialRevisionDate, cipher.RevisionDate);
@ -724,24 +745,12 @@ public class CipherServiceTests
cipherDetails.UserId = Guid.NewGuid(); cipherDetails.UserId = Guid.NewGuid();
cipherDetails.OrganizationId = null; cipherDetails.OrganizationId = null;
var exception = await Assert.ThrowsAsync<BadRequestException>( sutProvider.GetDependency<IUserService>()
() => sutProvider.Sut.RestoreAsync(cipherDetails, restoringUserId)); .GetUserByIdAsync(restoringUserId)
.Returns(new User
Assert.Contains("do not have permissions", exception.Message);
await sutProvider.GetDependency<ICipherRepository>().DidNotReceiveWithAnyArgs().UpsertAsync(default);
await sutProvider.GetDependency<IEventService>().DidNotReceiveWithAnyArgs().LogCipherEventAsync(default, default);
await sutProvider.GetDependency<IPushNotificationService>().DidNotReceiveWithAnyArgs().PushSyncCipherUpdateAsync(default, default);
}
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task RestoreAsync_WithOrgCipherLackingEditPermission_ThrowsBadRequestException(
Guid restoringUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider)
{ {
sutProvider.GetDependency<ICipherRepository>() Id = restoringUserId,
.GetCanEditByIdAsync(restoringUserId, cipherDetails.Id) });
.Returns(false);
var exception = await Assert.ThrowsAsync<BadRequestException>( var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.RestoreAsync(cipherDetails, restoringUserId)); () => sutProvider.Sut.RestoreAsync(cipherDetails, restoringUserId));
@ -752,28 +761,6 @@ public class CipherServiceTests
await sutProvider.GetDependency<IPushNotificationService>().DidNotReceiveWithAnyArgs().PushSyncCipherUpdateAsync(default, default); await sutProvider.GetDependency<IPushNotificationService>().DidNotReceiveWithAnyArgs().PushSyncCipherUpdateAsync(default, default);
} }
[Theory]
[BitAutoData]
public async Task RestoreAsync_WithEditPermission_RestoresCipherDetails(
Guid restoringUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider)
{
sutProvider.GetDependency<ICipherRepository>()
.GetCanEditByIdAsync(restoringUserId, cipherDetails.Id)
.Returns(true);
var initialRevisionDate = new DateTime(1970, 1, 1, 0, 0, 0);
cipherDetails.DeletedDate = initialRevisionDate;
cipherDetails.RevisionDate = initialRevisionDate;
await sutProvider.Sut.RestoreAsync(cipherDetails, restoringUserId);
Assert.Null(cipherDetails.DeletedDate);
Assert.NotEqual(initialRevisionDate, cipherDetails.RevisionDate);
await sutProvider.GetDependency<ICipherRepository>().Received(1).UpsertAsync(cipherDetails);
await sutProvider.GetDependency<IEventService>().Received(1).LogCipherEventAsync(cipherDetails, EventType.Cipher_Restored);
await sutProvider.GetDependency<IPushNotificationService>().Received(1).PushSyncCipherUpdateAsync(cipherDetails, null);
}
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
@ -794,7 +781,7 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task RestoreAsync_WithLimitItemDeletionEnabled_WithManagePermission_RestoresCipher( public async Task RestoreAsync_WithManagePermission_RestoresCipher(
Guid restoringUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider) Guid restoringUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider)
{ {
cipherDetails.OrganizationId = Guid.NewGuid(); cipherDetails.OrganizationId = Guid.NewGuid();
@ -802,9 +789,6 @@ public class CipherServiceTests
cipherDetails.Edit = false; cipherDetails.Edit = false;
cipherDetails.Manage = true; cipherDetails.Manage = true;
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<IUserService>() sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(restoringUserId) .GetUserByIdAsync(restoringUserId)
.Returns(user); .Returns(user);
@ -828,7 +812,7 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task RestoreAsync_WithLimitItemDeletionEnabled_WithoutManagePermission_ThrowsBadRequestException( public async Task RestoreAsync_WithoutManagePermission_ThrowsBadRequestException(
Guid restoringUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider) Guid restoringUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider)
{ {
cipherDetails.OrganizationId = Guid.NewGuid(); cipherDetails.OrganizationId = Guid.NewGuid();
@ -836,9 +820,6 @@ public class CipherServiceTests
cipherDetails.Edit = true; cipherDetails.Edit = true;
cipherDetails.Manage = false; cipherDetails.Manage = false;
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<IUserService>() sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(restoringUserId) .GetUserByIdAsync(restoringUserId)
.Returns(user); .Returns(user);
@ -859,32 +840,7 @@ public class CipherServiceTests
await sutProvider.GetDependency<IPushNotificationService>().DidNotReceiveWithAnyArgs().PushSyncCipherUpdateAsync(default, default); await sutProvider.GetDependency<IPushNotificationService>().DidNotReceiveWithAnyArgs().PushSyncCipherUpdateAsync(default, default);
} }
[Theory]
[BitAutoData]
public async Task RestoreManyAsync_UpdatesCiphers(ICollection<CipherDetails> ciphers,
SutProvider<CipherService> sutProvider)
{
var cipherIds = ciphers.Select(c => c.Id).ToArray();
var restoringUserId = ciphers.First().UserId.Value;
var previousRevisionDate = DateTime.UtcNow;
foreach (var cipher in ciphers)
{
cipher.Edit = true;
cipher.RevisionDate = previousRevisionDate;
}
sutProvider.GetDependency<ICipherRepository>().GetManyByUserIdAsync(restoringUserId).Returns(ciphers);
var revisionDate = previousRevisionDate + TimeSpan.FromMinutes(1);
sutProvider.GetDependency<ICipherRepository>().RestoreAsync(Arg.Any<IEnumerable<Guid>>(), restoringUserId).Returns(revisionDate);
await sutProvider.Sut.RestoreManyAsync(cipherIds, restoringUserId);
foreach (var cipher in ciphers)
{
Assert.Null(cipher.DeletedDate);
Assert.Equal(revisionDate, cipher.RevisionDate);
}
}
[Theory] [Theory]
[BitAutoData] [BitAutoData]
@ -971,90 +927,14 @@ public class CipherServiceTests
.PushSyncCiphersAsync(restoringUserId); .PushSyncCiphersAsync(restoringUserId);
} }
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task RestoreManyAsync_WithOrgCipherAndEditPermission_RestoresCiphers(
Guid restoringUserId, List<CipherDetails> ciphers, Guid organizationId, SutProvider<CipherService> sutProvider)
{
var cipherIds = ciphers.Select(c => c.Id).ToArray();
var previousRevisionDate = DateTime.UtcNow;
foreach (var cipher in ciphers)
{
cipher.OrganizationId = organizationId;
cipher.Edit = true;
cipher.DeletedDate = DateTime.UtcNow;
cipher.RevisionDate = previousRevisionDate;
}
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(restoringUserId)
.Returns(ciphers);
var revisionDate = previousRevisionDate + TimeSpan.FromMinutes(1);
sutProvider.GetDependency<ICipherRepository>()
.RestoreAsync(Arg.Any<IEnumerable<Guid>>(), restoringUserId)
.Returns(revisionDate);
var result = await sutProvider.Sut.RestoreManyAsync(cipherIds, restoringUserId);
Assert.Equal(ciphers.Count, result.Count);
foreach (var cipher in result)
{
Assert.Null(cipher.DeletedDate);
Assert.Equal(revisionDate, cipher.RevisionDate);
}
await sutProvider.GetDependency<ICipherRepository>()
.Received(1)
.RestoreAsync(Arg.Is<IEnumerable<Guid>>(ids => ids.Count() == cipherIds.Count() &&
ids.All(id => cipherIds.Contains(id))), restoringUserId);
await sutProvider.GetDependency<IEventService>()
.Received(1)
.LogCipherEventsAsync(Arg.Any<IEnumerable<Tuple<Cipher, EventType, DateTime?>>>());
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncCiphersAsync(restoringUserId);
}
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task RestoreManyAsync_WithOrgCipherLackingEditPermission_DoesNotRestoreCiphers( public async Task RestoreManyAsync_WithManagePermission_RestoresCiphers(
Guid restoringUserId, List<Cipher> ciphers, Guid organizationId, SutProvider<CipherService> sutProvider)
{
var cipherIds = ciphers.Select(c => c.Id).ToArray();
var cipherDetailsList = ciphers.Select(c => new CipherDetails
{
Id = c.Id,
OrganizationId = organizationId,
Edit = false,
DeletedDate = DateTime.UtcNow
}).ToList();
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(restoringUserId)
.Returns(cipherDetailsList);
var result = await sutProvider.Sut.RestoreManyAsync(cipherIds, restoringUserId);
Assert.Empty(result);
await sutProvider.GetDependency<ICipherRepository>()
.Received(1)
.RestoreAsync(Arg.Is<IEnumerable<Guid>>(ids => !ids.Any()), restoringUserId);
await sutProvider.GetDependency<IEventService>()
.DidNotReceiveWithAnyArgs()
.LogCipherEventsAsync(Arg.Any<IEnumerable<Tuple<Cipher, EventType, DateTime?>>>());
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncCiphersAsync(restoringUserId);
}
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task RestoreManyAsync_WithLimitItemDeletionEnabled_WithManagePermission_RestoresCiphers(
Guid restoringUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider) Guid restoringUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider)
{ {
var organizationId = Guid.NewGuid(); var organizationId = Guid.NewGuid();
@ -1070,9 +950,6 @@ public class CipherServiceTests
cipher.RevisionDate = previousRevisionDate; cipher.RevisionDate = previousRevisionDate;
} }
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(restoringUserId) .GetManyByUserIdAsync(restoringUserId)
.Returns(ciphers); .Returns(ciphers);
@ -1121,7 +998,7 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task RestoreManyAsync_WithLimitItemDeletionEnabled_WithoutManagePermission_DoesNotRestoreCiphers( public async Task RestoreManyAsync_WithoutManagePermission_DoesNotRestoreCiphers(
Guid restoringUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider) Guid restoringUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider)
{ {
var organizationId = Guid.NewGuid(); var organizationId = Guid.NewGuid();
@ -1135,9 +1012,6 @@ public class CipherServiceTests
cipher.DeletedDate = DateTime.UtcNow; cipher.DeletedDate = DateTime.UtcNow;
} }
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(restoringUserId) .GetManyByUserIdAsync(restoringUserId)
.Returns(ciphers); .Returns(ciphers);
@ -1502,23 +1376,12 @@ public class CipherServiceTests
cipherDetails.UserId = deletingUserId; cipherDetails.UserId = deletingUserId;
cipherDetails.OrganizationId = null; cipherDetails.OrganizationId = null;
await sutProvider.Sut.DeleteAsync(cipherDetails, deletingUserId); sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(deletingUserId)
await sutProvider.GetDependency<ICipherRepository>().Received(1).DeleteAsync(cipherDetails); .Returns(new User
await sutProvider.GetDependency<IAttachmentStorageService>().Received(1).DeleteAttachmentsForCipherAsync(cipherDetails.Id);
await sutProvider.GetDependency<IEventService>().Received(1).LogCipherEventAsync(cipherDetails, EventType.Cipher_Deleted);
await sutProvider.GetDependency<IPushNotificationService>().Received(1).PushSyncCipherDeleteAsync(cipherDetails);
}
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task DeleteAsync_WithOrgCipherAndEditPermission_DeletesCipher(
Guid deletingUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider)
{ {
sutProvider.GetDependency<ICipherRepository>() Id = deletingUserId,
.GetCanEditByIdAsync(deletingUserId, cipherDetails.Id) });
.Returns(true);
await sutProvider.Sut.DeleteAsync(cipherDetails, deletingUserId); await sutProvider.Sut.DeleteAsync(cipherDetails, deletingUserId);
@ -1528,6 +1391,8 @@ public class CipherServiceTests
await sutProvider.GetDependency<IPushNotificationService>().Received(1).PushSyncCipherDeleteAsync(cipherDetails); await sutProvider.GetDependency<IPushNotificationService>().Received(1).PushSyncCipherDeleteAsync(cipherDetails);
} }
[Theory] [Theory]
[BitAutoData] [BitAutoData]
public async Task DeleteAsync_WithPersonalCipherBelongingToDifferentUser_ThrowsBadRequestException( public async Task DeleteAsync_WithPersonalCipherBelongingToDifferentUser_ThrowsBadRequestException(
@ -1536,25 +1401,12 @@ public class CipherServiceTests
cipherDetails.UserId = Guid.NewGuid(); cipherDetails.UserId = Guid.NewGuid();
cipherDetails.OrganizationId = null; cipherDetails.OrganizationId = null;
var exception = await Assert.ThrowsAsync<BadRequestException>( sutProvider.GetDependency<IUserService>()
() => sutProvider.Sut.DeleteAsync(cipherDetails, deletingUserId)); .GetUserByIdAsync(deletingUserId)
.Returns(new User
Assert.Contains("do not have permissions", exception.Message);
await sutProvider.GetDependency<ICipherRepository>().DidNotReceiveWithAnyArgs().DeleteAsync(default);
await sutProvider.GetDependency<IAttachmentStorageService>().DidNotReceiveWithAnyArgs().DeleteAttachmentsForCipherAsync(default);
await sutProvider.GetDependency<IEventService>().DidNotReceiveWithAnyArgs().LogCipherEventAsync(default, default);
await sutProvider.GetDependency<IPushNotificationService>().DidNotReceiveWithAnyArgs().PushSyncCipherDeleteAsync(default);
}
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task DeleteAsync_WithOrgCipherLackingEditPermission_ThrowsBadRequestException(
Guid deletingUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider)
{ {
sutProvider.GetDependency<ICipherRepository>() Id = deletingUserId,
.GetCanEditByIdAsync(deletingUserId, cipherDetails.Id) });
.Returns(false);
var exception = await Assert.ThrowsAsync<BadRequestException>( var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.DeleteAsync(cipherDetails, deletingUserId)); () => sutProvider.Sut.DeleteAsync(cipherDetails, deletingUserId));
@ -1583,16 +1435,13 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task DeleteAsync_WithLimitItemDeletionEnabled_WithManagePermission_DeletesCipher( public async Task DeleteAsync_WithManagePermission_DeletesCipher(
Guid deletingUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider) Guid deletingUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider)
{ {
cipherDetails.OrganizationId = Guid.NewGuid(); cipherDetails.OrganizationId = Guid.NewGuid();
cipherDetails.Edit = false; cipherDetails.Edit = false;
cipherDetails.Manage = true; cipherDetails.Manage = true;
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<IUserService>() sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(deletingUserId) .GetUserByIdAsync(deletingUserId)
.Returns(user); .Returns(user);
@ -1615,16 +1464,13 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task DeleteAsync_WithLimitItemDeletionEnabled_WithoutManagePermission_ThrowsBadRequestException( public async Task DeleteAsync_WithoutManagePermission_ThrowsBadRequestException(
Guid deletingUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider) Guid deletingUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider)
{ {
cipherDetails.OrganizationId = Guid.NewGuid(); cipherDetails.OrganizationId = Guid.NewGuid();
cipherDetails.Edit = true; cipherDetails.Edit = true;
cipherDetails.Manage = false; cipherDetails.Manage = false;
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<IUserService>() sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(deletingUserId) .GetUserByIdAsync(deletingUserId)
.Returns(user); .Returns(user);
@ -1691,6 +1537,12 @@ public class CipherServiceTests
cipher.Edit = true; cipher.Edit = true;
} }
sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(deletingUserId)
.Returns(new User
{
Id = deletingUserId,
});
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId) .GetManyByUserIdAsync(deletingUserId)
.Returns(ciphers); .Returns(ciphers);
@ -1740,71 +1592,14 @@ public class CipherServiceTests
.PushSyncCiphersAsync(deletingUserId); .PushSyncCiphersAsync(deletingUserId);
} }
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task DeleteManyAsync_WithOrgCipherAndEditPermission_DeletesCiphers(
Guid deletingUserId, List<CipherDetails> ciphers, Guid organizationId, SutProvider<CipherService> sutProvider)
{
var cipherIds = ciphers.Select(c => c.Id).ToArray();
foreach (var cipher in ciphers)
{
cipher.OrganizationId = organizationId;
cipher.Edit = true;
}
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId)
.Returns(ciphers);
await sutProvider.Sut.DeleteManyAsync(cipherIds, deletingUserId, organizationId);
await sutProvider.GetDependency<ICipherRepository>()
.Received(1)
.DeleteAsync(Arg.Is<IEnumerable<Guid>>(ids => ids.Count() == cipherIds.Count() && ids.All(id => cipherIds.Contains(id))), deletingUserId);
await sutProvider.GetDependency<IEventService>()
.Received(1)
.LogCipherEventsAsync(Arg.Any<IEnumerable<Tuple<Cipher, EventType, DateTime?>>>());
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncCiphersAsync(deletingUserId);
}
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task DeleteManyAsync_WithOrgCipherLackingEditPermission_DoesNotDeleteCiphers( public async Task DeleteManyAsync_WithoutManagePermission_DoesNotDeleteCiphers(
Guid deletingUserId, List<Cipher> ciphers, Guid organizationId, SutProvider<CipherService> sutProvider)
{
var cipherIds = ciphers.Select(c => c.Id).ToArray();
var cipherDetailsList = ciphers.Select(c => new CipherDetails
{
Id = c.Id,
OrganizationId = organizationId,
Edit = false
}).ToList();
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId)
.Returns(cipherDetailsList);
await sutProvider.Sut.DeleteManyAsync(cipherIds, deletingUserId, organizationId);
await sutProvider.GetDependency<ICipherRepository>()
.Received(1)
.DeleteAsync(Arg.Is<IEnumerable<Guid>>(ids => !ids.Any()), deletingUserId);
await sutProvider.GetDependency<IEventService>()
.DidNotReceiveWithAnyArgs()
.LogCipherEventsAsync(Arg.Any<IEnumerable<Tuple<Cipher, EventType, DateTime?>>>());
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncCiphersAsync(deletingUserId);
}
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task DeleteManyAsync_WithLimitItemDeletionEnabled_WithoutManagePermission_DoesNotDeleteCiphers(
Guid deletingUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider) Guid deletingUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider)
{ {
var organizationId = Guid.NewGuid(); var organizationId = Guid.NewGuid();
@ -1817,9 +1612,6 @@ public class CipherServiceTests
cipher.Manage = false; cipher.Manage = false;
} }
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId) .GetManyByUserIdAsync(deletingUserId)
.Returns(ciphers); .Returns(ciphers);
@ -1855,7 +1647,7 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task DeleteManyAsync_WithLimitItemDeletionEnabled_WithManagePermission_DeletesCiphers( public async Task DeleteManyAsync_WithManagePermission_DeletesCiphers(
Guid deletingUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider) Guid deletingUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider)
{ {
var organizationId = Guid.NewGuid(); var organizationId = Guid.NewGuid();
@ -1868,9 +1660,6 @@ public class CipherServiceTests
cipher.Manage = true; cipher.Manage = true;
} }
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId) .GetManyByUserIdAsync(deletingUserId)
.Returns(ciphers); .Returns(ciphers);
@ -1913,30 +1702,12 @@ public class CipherServiceTests
cipherDetails.OrganizationId = null; cipherDetails.OrganizationId = null;
cipherDetails.DeletedDate = null; cipherDetails.DeletedDate = null;
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<IUserService>()
.GetCanEditByIdAsync(deletingUserId, cipherDetails.Id) .GetUserByIdAsync(deletingUserId)
.Returns(true); .Returns(new User
await sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId);
Assert.NotNull(cipherDetails.DeletedDate);
Assert.Equal(cipherDetails.RevisionDate, cipherDetails.DeletedDate);
await sutProvider.GetDependency<ICipherRepository>().Received(1).UpsertAsync(cipherDetails);
await sutProvider.GetDependency<IEventService>().Received(1).LogCipherEventAsync(cipherDetails, EventType.Cipher_SoftDeleted);
await sutProvider.GetDependency<IPushNotificationService>().Received(1).PushSyncCipherUpdateAsync(cipherDetails, null);
}
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task SoftDeleteAsync_WithOrgCipherAndEditPermission_SoftDeletesCipher(
Guid deletingUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider)
{ {
cipherDetails.DeletedDate = null; Id = deletingUserId,
});
sutProvider.GetDependency<ICipherRepository>()
.GetCanEditByIdAsync(deletingUserId, cipherDetails.Id)
.Returns(true);
await sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId); await sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId);
@ -1947,6 +1718,8 @@ public class CipherServiceTests
await sutProvider.GetDependency<IPushNotificationService>().Received(1).PushSyncCipherUpdateAsync(cipherDetails, null); await sutProvider.GetDependency<IPushNotificationService>().Received(1).PushSyncCipherUpdateAsync(cipherDetails, null);
} }
[Theory] [Theory]
[BitAutoData] [BitAutoData]
public async Task SoftDeleteAsync_WithPersonalCipherBelongingToDifferentUser_ThrowsBadRequestException( public async Task SoftDeleteAsync_WithPersonalCipherBelongingToDifferentUser_ThrowsBadRequestException(
@ -1955,9 +1728,12 @@ public class CipherServiceTests
cipherDetails.UserId = Guid.NewGuid(); cipherDetails.UserId = Guid.NewGuid();
cipherDetails.OrganizationId = null; cipherDetails.OrganizationId = null;
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<IUserService>()
.GetCanEditByIdAsync(deletingUserId, cipherDetails.Id) .GetUserByIdAsync(deletingUserId)
.Returns(false); .Returns(new User
{
Id = deletingUserId,
});
var exception = await Assert.ThrowsAsync<BadRequestException>( var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId)); () => sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId));
@ -1965,48 +1741,23 @@ public class CipherServiceTests
Assert.Contains("do not have permissions", exception.Message); Assert.Contains("do not have permissions", exception.Message);
} }
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task SoftDeleteAsync_WithOrgCipherLackingEditPermission_ThrowsBadRequestException(
Guid deletingUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider)
{
sutProvider.GetDependency<ICipherRepository>()
.GetCanEditByIdAsync(deletingUserId, cipherDetails.Id)
.Returns(false);
var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId));
Assert.Contains("do not have permissions", exception.Message);
}
[Theory]
[BitAutoData]
public async Task SoftDeleteAsync_WithEditPermission_SoftDeletesCipherDetails(
Guid deletingUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider)
{
cipherDetails.DeletedDate = null;
await sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId, true);
Assert.NotNull(cipherDetails.DeletedDate);
Assert.Equal(cipherDetails.RevisionDate, cipherDetails.DeletedDate);
await sutProvider.GetDependency<ICipherRepository>().Received(1).UpsertAsync(cipherDetails);
await sutProvider.GetDependency<IEventService>().Received(1).LogCipherEventAsync(cipherDetails, EventType.Cipher_SoftDeleted);
await sutProvider.GetDependency<IPushNotificationService>().Received(1).PushSyncCipherUpdateAsync(cipherDetails, null);
}
[Theory] [Theory]
[BitAutoData] [BitAutoData]
public async Task SoftDeleteAsync_WithAlreadySoftDeletedCipher_SkipsOperation( public async Task SoftDeleteAsync_WithAlreadySoftDeletedCipher_SkipsOperation(
Guid deletingUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider) Guid deletingUserId, CipherDetails cipherDetails, SutProvider<CipherService> sutProvider)
{ {
sutProvider.GetDependency<ICipherRepository>() // Set up as personal cipher owned by the deleting user
.GetCanEditByIdAsync(deletingUserId, cipherDetails.Id) cipherDetails.UserId = deletingUserId;
.Returns(true); cipherDetails.OrganizationId = null;
cipherDetails.DeletedDate = DateTime.UtcNow.AddDays(-1); cipherDetails.DeletedDate = DateTime.UtcNow.AddDays(-1);
sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(deletingUserId)
.Returns(new User
{
Id = deletingUserId,
});
await sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId); await sutProvider.Sut.SoftDeleteAsync(cipherDetails, deletingUserId);
await sutProvider.GetDependency<ICipherRepository>().DidNotReceive().UpsertAsync(Arg.Any<Cipher>()); await sutProvider.GetDependency<ICipherRepository>().DidNotReceive().UpsertAsync(Arg.Any<Cipher>());
@ -2032,7 +1783,7 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task SoftDeleteAsync_WithLimitItemDeletionEnabled_WithManagePermission_SoftDeletesCipher( public async Task SoftDeleteAsync_WithManagePermission_SoftDeletesCipher(
Guid deletingUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider) Guid deletingUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider)
{ {
cipherDetails.OrganizationId = Guid.NewGuid(); cipherDetails.OrganizationId = Guid.NewGuid();
@ -2040,9 +1791,6 @@ public class CipherServiceTests
cipherDetails.Edit = false; cipherDetails.Edit = false;
cipherDetails.Manage = true; cipherDetails.Manage = true;
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<IUserService>() sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(deletingUserId) .GetUserByIdAsync(deletingUserId)
.Returns(user); .Returns(user);
@ -2066,7 +1814,7 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task SoftDeleteAsync_WithLimitItemDeletionEnabled_WithoutManagePermission_ThrowsBadRequestException( public async Task SoftDeleteAsync_WithoutManagePermission_ThrowsBadRequestException(
Guid deletingUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider) Guid deletingUserId, CipherDetails cipherDetails, User user, SutProvider<CipherService> sutProvider)
{ {
cipherDetails.OrganizationId = Guid.NewGuid(); cipherDetails.OrganizationId = Guid.NewGuid();
@ -2074,9 +1822,6 @@ public class CipherServiceTests
cipherDetails.Edit = true; cipherDetails.Edit = true;
cipherDetails.Manage = false; cipherDetails.Manage = false;
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<IUserService>() sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(deletingUserId) .GetUserByIdAsync(deletingUserId)
.Returns(user); .Returns(user);
@ -2143,6 +1888,12 @@ public class CipherServiceTests
cipher.DeletedDate = null; cipher.DeletedDate = null;
} }
sutProvider.GetDependency<IUserService>()
.GetUserByIdAsync(deletingUserId)
.Returns(new User
{
Id = deletingUserId,
});
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId) .GetManyByUserIdAsync(deletingUserId)
.Returns(ciphers); .Returns(ciphers);
@ -2192,72 +1943,14 @@ public class CipherServiceTests
.PushSyncCiphersAsync(deletingUserId); .PushSyncCiphersAsync(deletingUserId);
} }
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task SoftDeleteManyAsync_WithOrgCipherAndEditPermission_SoftDeletesCiphers(
Guid deletingUserId, List<CipherDetails> ciphers, Guid organizationId, SutProvider<CipherService> sutProvider)
{
var cipherIds = ciphers.Select(c => c.Id).ToArray();
foreach (var cipher in ciphers)
{
cipher.OrganizationId = organizationId;
cipher.Edit = true;
cipher.DeletedDate = null;
}
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId)
.Returns(ciphers);
await sutProvider.Sut.SoftDeleteManyAsync(cipherIds, deletingUserId, organizationId, false);
await sutProvider.GetDependency<ICipherRepository>()
.Received(1)
.SoftDeleteAsync(Arg.Is<IEnumerable<Guid>>(ids => ids.Count() == cipherIds.Count() && ids.All(id => cipherIds.Contains(id))), deletingUserId);
await sutProvider.GetDependency<IEventService>()
.Received(1)
.LogCipherEventsAsync(Arg.Any<IEnumerable<Tuple<Cipher, EventType, DateTime?>>>());
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncCiphersAsync(deletingUserId);
}
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task SoftDeleteManyAsync_WithOrgCipherLackingEditPermission_DoesNotDeleteCiphers( public async Task SoftDeleteManyAsync_WithoutManagePermission_DoesNotDeleteCiphers(
Guid deletingUserId, List<Cipher> ciphers, Guid organizationId, SutProvider<CipherService> sutProvider)
{
var cipherIds = ciphers.Select(c => c.Id).ToArray();
var cipherDetailsList = ciphers.Select(c => new CipherDetails
{
Id = c.Id,
OrganizationId = organizationId,
Edit = false
}).ToList();
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId)
.Returns(cipherDetailsList);
await sutProvider.Sut.SoftDeleteManyAsync(cipherIds, deletingUserId, organizationId, false);
await sutProvider.GetDependency<ICipherRepository>()
.Received(1)
.SoftDeleteAsync(Arg.Is<IEnumerable<Guid>>(ids => !ids.Any()), deletingUserId);
await sutProvider.GetDependency<IEventService>()
.DidNotReceiveWithAnyArgs()
.LogCipherEventsAsync(Arg.Any<IEnumerable<Tuple<Cipher, EventType, DateTime?>>>());
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncCiphersAsync(deletingUserId);
}
[Theory]
[OrganizationCipherCustomize]
[BitAutoData]
public async Task SoftDeleteManyAsync_WithLimitItemDeletionEnabled_WithoutManagePermission_DoesNotDeleteCiphers(
Guid deletingUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider) Guid deletingUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider)
{ {
var organizationId = Guid.NewGuid(); var organizationId = Guid.NewGuid();
@ -2270,9 +1963,6 @@ public class CipherServiceTests
cipher.Manage = false; cipher.Manage = false;
} }
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId) .GetManyByUserIdAsync(deletingUserId)
.Returns(ciphers); .Returns(ciphers);
@ -2308,7 +1998,7 @@ public class CipherServiceTests
[Theory] [Theory]
[OrganizationCipherCustomize] [OrganizationCipherCustomize]
[BitAutoData] [BitAutoData]
public async Task SoftDeleteManyAsync_WithLimitItemDeletionEnabled_WithManagePermission_SoftDeletesCiphers( public async Task SoftDeleteManyAsync_WithManagePermission_SoftDeletesCiphers(
Guid deletingUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider) Guid deletingUserId, List<CipherDetails> ciphers, User user, SutProvider<CipherService> sutProvider)
{ {
var organizationId = Guid.NewGuid(); var organizationId = Guid.NewGuid();
@ -2322,9 +2012,6 @@ public class CipherServiceTests
cipher.DeletedDate = null; cipher.DeletedDate = null;
} }
sutProvider.GetDependency<IFeatureService>()
.IsEnabled(FeatureFlagKeys.LimitItemDeletion)
.Returns(true);
sutProvider.GetDependency<ICipherRepository>() sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(deletingUserId) .GetManyByUserIdAsync(deletingUserId)
.Returns(ciphers); .Returns(ciphers);

View File

@ -0,0 +1,55 @@
IF NOT EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Collection'
AND COLUMN_NAME = 'DefaultUserCollectionEmail'
)
BEGIN
ALTER TABLE [dbo].[Collection]
ADD [DefaultUserCollectionEmail] NVARCHAR(256) NULL
END
GO
IF NOT EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Collection'
AND COLUMN_NAME = 'Type'
)
BEGIN
ALTER TABLE [dbo].[Collection]
ADD [Type] TINYINT NOT NULL DEFAULT (0)
END
GO
IF OBJECT_ID('[dbo].[CollectionView]') IS NOT NULL
BEGIN
EXECUTE sp_refreshsqlmodule N'[dbo].[CollectionView]';
END
GO
IF OBJECT_ID('[dbo].[Collection_ReadById]') IS NOT NULL
BEGIN
EXECUTE sp_refreshsqlmodule N'[dbo].[Collection_ReadById]';
END
GO
IF OBJECT_ID('[dbo].[Collection_ReadByIds]') IS NOT NULL
BEGIN
EXECUTE sp_refreshsqlmodule N'[dbo].[Collection_ReadByIds]';
END
GO
IF OBJECT_ID('[dbo].[Collection_ReadByOrganizationId]') IS NOT NULL
BEGIN
EXECUTE sp_refreshsqlmodule N'[dbo].[Collection_ReadByOrganizationId]';
END
GO
IF OBJECT_ID('[dbo].[UserCollectionDetails]') IS NOT NULL
BEGIN
EXECUTE sp_refreshsqlmodule N'[dbo].[UserCollectionDetails]';
END
GO

View File

@ -0,0 +1,456 @@
CREATE OR ALTER PROCEDURE [dbo].[Collection_Create]
@Id UNIQUEIDENTIFIER OUTPUT,
@OrganizationId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@DefaultUserCollectionEmail NVARCHAR(256) = NULL,
@Type TINYINT = 0
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[Collection]
(
[Id],
[OrganizationId],
[Name],
[ExternalId],
[CreationDate],
[RevisionDate],
[DefaultUserCollectionEmail],
[Type]
)
VALUES
(
@Id,
@OrganizationId,
@Name,
@ExternalId,
@CreationDate,
@RevisionDate,
@DefaultUserCollectionEmail,
@Type
)
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @Id, @OrganizationId
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Collection_ReadByUserId]
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
[Id],
[OrganizationId],
[Name],
[CreationDate],
[RevisionDate],
[ExternalId],
MIN([ReadOnly]) AS [ReadOnly],
MIN([HidePasswords]) AS [HidePasswords],
MAX([Manage]) AS [Manage],
[DefaultUserCollectionEmail],
[Type]
FROM
[dbo].[UserCollectionDetails](@UserId)
GROUP BY
[Id],
[OrganizationId],
[Name],
[CreationDate],
[RevisionDate],
[ExternalId],
[DefaultUserCollectionEmail],
[Type]
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Collection_Update]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@DefaultUserCollectionEmail NVARCHAR(256) = NULL,
@Type TINYINT = 0
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[Collection]
SET
[OrganizationId] = @OrganizationId,
[Name] = @Name,
[ExternalId] = @ExternalId,
[CreationDate] = @CreationDate,
[RevisionDate] = @RevisionDate,
[DefaultUserCollectionEmail] = @DefaultUserCollectionEmail,
[Type] = @Type
WHERE
[Id] = @Id
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @Id, @OrganizationId
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Collection_UpdateWithGroupsAndUsers]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Groups AS [dbo].[CollectionAccessSelectionType] READONLY,
@Users AS [dbo].[CollectionAccessSelectionType] READONLY,
@DefaultUserCollectionEmail NVARCHAR(256) = NULL,
@Type TINYINT = 0
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_Update] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate, @DefaultUserCollectionEmail, @Type
-- Groups
-- Delete groups that are no longer in source
DELETE cg
FROM [dbo].[CollectionGroup] cg
LEFT JOIN @Groups g ON cg.GroupId = g.Id
WHERE cg.CollectionId = @Id
AND g.Id IS NULL;
-- Update existing groups
UPDATE cg
SET cg.ReadOnly = g.ReadOnly,
cg.HidePasswords = g.HidePasswords,
cg.Manage = g.Manage
FROM [dbo].[CollectionGroup] cg
INNER JOIN @Groups g ON cg.GroupId = g.Id
WHERE cg.CollectionId = @Id
AND (cg.ReadOnly != g.ReadOnly
OR cg.HidePasswords != g.HidePasswords
OR cg.Manage != g.Manage);
-- Insert new groups
INSERT INTO [dbo].[CollectionGroup]
(
[CollectionId],
[GroupId],
[ReadOnly],
[HidePasswords],
[Manage]
)
SELECT
@Id,
g.Id,
g.ReadOnly,
g.HidePasswords,
g.Manage
FROM @Groups g
INNER JOIN [dbo].[Group] grp ON grp.Id = g.Id
LEFT JOIN [dbo].[CollectionGroup] cg
ON cg.CollectionId = @Id AND cg.GroupId = g.Id
WHERE grp.OrganizationId = @OrganizationId
AND cg.CollectionId IS NULL;
-- Users
-- Delete users that are no longer in source
DELETE cu
FROM [dbo].[CollectionUser] cu
LEFT JOIN @Users u ON cu.OrganizationUserId = u.Id
WHERE cu.CollectionId = @Id
AND u.Id IS NULL;
-- Update existing users
UPDATE cu
SET cu.ReadOnly = u.ReadOnly,
cu.HidePasswords = u.HidePasswords,
cu.Manage = u.Manage
FROM [dbo].[CollectionUser] cu
INNER JOIN @Users u ON cu.OrganizationUserId = u.Id
WHERE cu.CollectionId = @Id
AND (cu.ReadOnly != u.ReadOnly
OR cu.HidePasswords != u.HidePasswords
OR cu.Manage != u.Manage);
-- Insert new users
INSERT INTO [dbo].[CollectionUser]
(
[CollectionId],
[OrganizationUserId],
[ReadOnly],
[HidePasswords],
[Manage]
)
SELECT
@Id,
u.Id,
u.ReadOnly,
u.HidePasswords,
u.Manage
FROM @Users u
INNER JOIN [dbo].[OrganizationUser] ou ON ou.Id = u.Id
LEFT JOIN [dbo].[CollectionUser] cu
ON cu.CollectionId = @Id AND cu.OrganizationUserId = u.Id
WHERE ou.OrganizationId = @OrganizationId
AND cu.CollectionId IS NULL;
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @Id, @OrganizationId
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Collection_ReadByOrganizationIdWithPermissions]
@OrganizationId UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@IncludeAccessRelationships BIT
AS
BEGIN
SET NOCOUNT ON
SELECT
C.*,
MIN(CASE
WHEN
COALESCE(CU.[ReadOnly], CG.[ReadOnly], 0) = 0
THEN 0
ELSE 1
END) AS [ReadOnly],
MIN(CASE
WHEN
COALESCE(CU.[HidePasswords], CG.[HidePasswords], 0) = 0
THEN 0
ELSE 1
END) AS [HidePasswords],
MAX(CASE
WHEN
COALESCE(CU.[Manage], CG.[Manage], 0) = 0
THEN 0
ELSE 1
END) AS [Manage],
MAX(CASE
WHEN
CU.[CollectionId] IS NULL AND CG.[CollectionId] IS NULL
THEN 0
ELSE 1
END) AS [Assigned],
CASE
WHEN
-- No user or group has manage rights
NOT EXISTS(
SELECT 1
FROM [dbo].[CollectionUser] CU2
JOIN [dbo].[OrganizationUser] OU2 ON CU2.[OrganizationUserId] = OU2.[Id]
WHERE
CU2.[CollectionId] = C.[Id] AND
CU2.[Manage] = 1
)
AND NOT EXISTS (
SELECT 1
FROM [dbo].[CollectionGroup] CG2
WHERE
CG2.[CollectionId] = C.[Id] AND
CG2.[Manage] = 1
)
THEN 1
ELSE 0
END AS [Unmanaged]
FROM
[dbo].[CollectionView] C
LEFT JOIN
[dbo].[OrganizationUser] OU ON C.[OrganizationId] = OU.[OrganizationId] AND OU.[UserId] = @UserId
LEFT JOIN
[dbo].[CollectionUser] CU ON CU.[CollectionId] = C.[Id] AND CU.[OrganizationUserId] = [OU].[Id]
LEFT JOIN
[dbo].[GroupUser] GU ON CU.[CollectionId] IS NULL AND GU.[OrganizationUserId] = OU.[Id]
LEFT JOIN
[dbo].[Group] G ON G.[Id] = GU.[GroupId]
LEFT JOIN
[dbo].[CollectionGroup] CG ON CG.[CollectionId] = C.[Id] AND CG.[GroupId] = GU.[GroupId]
WHERE
C.[OrganizationId] = @OrganizationId
GROUP BY
C.[Id],
C.[OrganizationId],
C.[Name],
C.[CreationDate],
C.[RevisionDate],
C.[ExternalId],
C.[DefaultUserCollectionEmail],
C.[Type]
IF (@IncludeAccessRelationships = 1)
BEGIN
EXEC [dbo].[CollectionGroup_ReadByOrganizationId] @OrganizationId
EXEC [dbo].[CollectionUser_ReadByOrganizationId] @OrganizationId
END
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Collection_CreateWithGroupsAndUsers]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Groups AS [dbo].[CollectionAccessSelectionType] READONLY,
@Users AS [dbo].[CollectionAccessSelectionType] READONLY,
@DefaultUserCollectionEmail NVARCHAR(256) = NULL,
@Type TINYINT = 0
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_Create] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate, @DefaultUserCollectionEmail, @Type
-- Groups
;WITH [AvailableGroupsCTE] AS(
SELECT
[Id]
FROM
[dbo].[Group]
WHERE
[OrganizationId] = @OrganizationId
)
INSERT INTO [dbo].[CollectionGroup]
(
[CollectionId],
[GroupId],
[ReadOnly],
[HidePasswords],
[Manage]
)
SELECT
@Id,
[Id],
[ReadOnly],
[HidePasswords],
[Manage]
FROM
@Groups
WHERE
[Id] IN (SELECT [Id] FROM [AvailableGroupsCTE])
-- Users
;WITH [AvailableUsersCTE] AS(
SELECT
[Id]
FROM
[dbo].[OrganizationUser]
WHERE
[OrganizationId] = @OrganizationId
)
INSERT INTO [dbo].[CollectionUser]
(
[CollectionId],
[OrganizationUserId],
[ReadOnly],
[HidePasswords],
[Manage]
)
SELECT
@Id,
[Id],
[ReadOnly],
[HidePasswords],
[Manage]
FROM
@Users
WHERE
[Id] IN (SELECT [Id] FROM [AvailableUsersCTE])
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationId] @OrganizationId
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Collection_ReadByIdWithPermissions]
@CollectionId UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@IncludeAccessRelationships BIT
AS
BEGIN
SET NOCOUNT ON
SELECT
C.*,
MIN(CASE
WHEN
COALESCE(CU.[ReadOnly], CG.[ReadOnly], 0) = 0
THEN 0
ELSE 1
END) AS [ReadOnly],
MIN (CASE
WHEN
COALESCE(CU.[HidePasswords], CG.[HidePasswords], 0) = 0
THEN 0
ELSE 1
END) AS [HidePasswords],
MAX(CASE
WHEN
COALESCE(CU.[Manage], CG.[Manage], 0) = 0
THEN 0
ELSE 1
END) AS [Manage],
MAX(CASE
WHEN
CU.[CollectionId] IS NULL AND CG.[CollectionId] IS NULL
THEN 0
ELSE 1
END) AS [Assigned],
CASE
WHEN
-- No user or group has manage rights
NOT EXISTS(
SELECT 1
FROM [dbo].[CollectionUser] CU2
JOIN [dbo].[OrganizationUser] OU2 ON CU2.[OrganizationUserId] = OU2.[Id]
WHERE
CU2.[CollectionId] = C.[Id] AND
CU2.[Manage] = 1
)
AND NOT EXISTS (
SELECT 1
FROM [dbo].[CollectionGroup] CG2
WHERE
CG2.[CollectionId] = C.[Id] AND
CG2.[Manage] = 1
)
THEN 1
ELSE 0
END AS [Unmanaged]
FROM
[dbo].[CollectionView] C
LEFT JOIN
[dbo].[OrganizationUser] OU ON C.[OrganizationId] = OU.[OrganizationId] AND OU.[UserId] = @UserId
LEFT JOIN
[dbo].[CollectionUser] CU ON CU.[CollectionId] = C.[Id] AND CU.[OrganizationUserId] = [OU].[Id]
LEFT JOIN
[dbo].[GroupUser] GU ON CU.[CollectionId] IS NULL AND GU.[OrganizationUserId] = OU.[Id]
LEFT JOIN
[dbo].[Group] G ON G.[Id] = GU.[GroupId]
LEFT JOIN
[dbo].[CollectionGroup] CG ON CG.[CollectionId] = C.[Id] AND CG.[GroupId] = GU.[GroupId]
WHERE
C.[Id] = @CollectionId
GROUP BY
C.[Id],
C.[OrganizationId],
C.[Name],
C.[CreationDate],
C.[RevisionDate],
C.[ExternalId],
C.[DefaultUserCollectionEmail],
C.[Type]
IF (@IncludeAccessRelationships = 1)
BEGIN
EXEC [dbo].[CollectionGroup_ReadByCollectionId] @CollectionId
EXEC [dbo].[CollectionUser_ReadByCollectionId] @CollectionId
END
END

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.MySqlMigrations.Migrations;
/// <inheritdoc />
public partial class AddOrgUserDefaultCollection : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "DefaultUserCollectionEmail",
table: "Collection",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<int>(
name: "Type",
table: "Collection",
type: "int",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DefaultUserCollectionEmail",
table: "Collection");
migrationBuilder.DropColumn(
name: "Type",
table: "Collection");
}
}

View File

@ -956,6 +956,9 @@ namespace Bit.MySqlMigrations.Migrations
b.Property<DateTime>("CreationDate") b.Property<DateTime>("CreationDate")
.HasColumnType("datetime(6)"); .HasColumnType("datetime(6)");
b.Property<string>("DefaultUserCollectionEmail")
.HasColumnType("longtext");
b.Property<string>("ExternalId") b.Property<string>("ExternalId")
.HasMaxLength(300) .HasMaxLength(300)
.HasColumnType("varchar(300)"); .HasColumnType("varchar(300)");
@ -970,6 +973,9 @@ namespace Bit.MySqlMigrations.Migrations
b.Property<DateTime>("RevisionDate") b.Property<DateTime>("RevisionDate")
.HasColumnType("datetime(6)"); .HasColumnType("datetime(6)");
b.Property<int>("Type")
.HasColumnType("int");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("OrganizationId"); b.HasIndex("OrganizationId");

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.PostgresMigrations.Migrations;
/// <inheritdoc />
public partial class AddOrgUserDefaultCollection : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "DefaultUserCollectionEmail",
table: "Collection",
type: "text",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "Type",
table: "Collection",
type: "integer",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DefaultUserCollectionEmail",
table: "Collection");
migrationBuilder.DropColumn(
name: "Type",
table: "Collection");
}
}

View File

@ -961,6 +961,9 @@ namespace Bit.PostgresMigrations.Migrations
b.Property<DateTime>("CreationDate") b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp with time zone"); .HasColumnType("timestamp with time zone");
b.Property<string>("DefaultUserCollectionEmail")
.HasColumnType("text");
b.Property<string>("ExternalId") b.Property<string>("ExternalId")
.HasMaxLength(300) .HasMaxLength(300)
.HasColumnType("character varying(300)"); .HasColumnType("character varying(300)");
@ -975,6 +978,9 @@ namespace Bit.PostgresMigrations.Migrations
b.Property<DateTime>("RevisionDate") b.Property<DateTime>("RevisionDate")
.HasColumnType("timestamp with time zone"); .HasColumnType("timestamp with time zone");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("OrganizationId"); b.HasIndex("OrganizationId");

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.SqliteMigrations.Migrations;
/// <inheritdoc />
public partial class AddOrgUserDefaultCollection : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "DefaultUserCollectionEmail",
table: "Collection",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "Type",
table: "Collection",
type: "INTEGER",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DefaultUserCollectionEmail",
table: "Collection");
migrationBuilder.DropColumn(
name: "Type",
table: "Collection");
}
}

View File

@ -945,6 +945,9 @@ namespace Bit.SqliteMigrations.Migrations
b.Property<DateTime>("CreationDate") b.Property<DateTime>("CreationDate")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("DefaultUserCollectionEmail")
.HasColumnType("TEXT");
b.Property<string>("ExternalId") b.Property<string>("ExternalId")
.HasMaxLength(300) .HasMaxLength(300)
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@ -959,6 +962,9 @@ namespace Bit.SqliteMigrations.Migrations
b.Property<DateTime>("RevisionDate") b.Property<DateTime>("RevisionDate")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("OrganizationId"); b.HasIndex("OrganizationId");