1
0
mirror of https://github.com/bitwarden/server synced 2026-01-08 03:23:20 +00:00

[PM-19151] [PM-19161] Innovation/archive/server (#5672)

* Added the ArchivedDate to cipher entity and response model
* Created migration scripts for sqlserver and ef core migration to add the ArchivedDate column

---------

Co-authored-by: gbubemismith <gsmithwalter@gmail.com>
Co-authored-by: SmithThe4th <gsmith@bitwarden.com>
Co-authored-by: Shane <smelton@bitwarden.com>
Co-authored-by: cd-bitwarden <106776772+cd-bitwarden@users.noreply.github.com>
Co-authored-by: jng <jng@bitwarden.com>
This commit is contained in:
Patrick-Pimentel-Bitwarden
2025-09-12 13:24:30 -04:00
committed by GitHub
parent 18aed0bd79
commit 4e64d35f89
43 changed files with 10342 additions and 42 deletions

View File

@@ -20,6 +20,7 @@ using Bit.Core.Settings;
using Bit.Core.Tools.Services;
using Bit.Core.Utilities;
using Bit.Core.Vault.Authorization.Permissions;
using Bit.Core.Vault.Commands.Interfaces;
using Bit.Core.Vault.Entities;
using Bit.Core.Vault.Models.Data;
using Bit.Core.Vault.Queries;
@@ -48,6 +49,8 @@ public class CiphersController : Controller
private readonly IOrganizationCiphersQuery _organizationCiphersQuery;
private readonly IApplicationCacheService _applicationCacheService;
private readonly ICollectionRepository _collectionRepository;
private readonly IArchiveCiphersCommand _archiveCiphersCommand;
private readonly IUnarchiveCiphersCommand _unarchiveCiphersCommand;
private readonly IFeatureService _featureService;
public CiphersController(
@@ -63,6 +66,8 @@ public class CiphersController : Controller
IOrganizationCiphersQuery organizationCiphersQuery,
IApplicationCacheService applicationCacheService,
ICollectionRepository collectionRepository,
IArchiveCiphersCommand archiveCiphersCommand,
IUnarchiveCiphersCommand unarchiveCiphersCommand,
IFeatureService featureService)
{
_cipherRepository = cipherRepository;
@@ -77,6 +82,8 @@ public class CiphersController : Controller
_organizationCiphersQuery = organizationCiphersQuery;
_applicationCacheService = applicationCacheService;
_collectionRepository = collectionRepository;
_archiveCiphersCommand = archiveCiphersCommand;
_unarchiveCiphersCommand = unarchiveCiphersCommand;
_featureService = featureService;
}
@@ -846,6 +853,47 @@ public class CiphersController : Controller
}
}
[HttpPut("{id}/archive")]
[RequireFeature(FeatureFlagKeys.ArchiveVaultItems)]
public async Task<CipherMiniResponseModel> PutArchive(Guid id)
{
var userId = _userService.GetProperUserId(User).Value;
var archivedCipherOrganizationDetails = await _archiveCiphersCommand.ArchiveManyAsync([id], userId);
if (archivedCipherOrganizationDetails.Count == 0)
{
throw new BadRequestException("Cipher was not archived. Ensure the provided ID is correct and you have permission to archive it.");
}
return new CipherMiniResponseModel(archivedCipherOrganizationDetails.First(), _globalSettings, archivedCipherOrganizationDetails.First().OrganizationUseTotp);
}
[HttpPut("archive")]
[RequireFeature(FeatureFlagKeys.ArchiveVaultItems)]
public async Task<ListResponseModel<CipherMiniResponseModel>> PutArchiveMany([FromBody] CipherBulkArchiveRequestModel model)
{
if (!_globalSettings.SelfHosted && model.Ids.Count() > 500)
{
throw new BadRequestException("You can only archive up to 500 items at a time.");
}
var userId = _userService.GetProperUserId(User).Value;
var cipherIdsToArchive = new HashSet<Guid>(model.Ids);
var archivedCiphers = await _archiveCiphersCommand.ArchiveManyAsync(cipherIdsToArchive, userId);
if (archivedCiphers.Count == 0)
{
throw new BadRequestException("No ciphers were archived. Ensure the provided IDs are correct and you have permission to archive them.");
}
var responses = archivedCiphers.Select(c => new CipherMiniResponseModel(c, _globalSettings, c.OrganizationUseTotp));
return new ListResponseModel<CipherMiniResponseModel>(responses);
}
[HttpDelete("{id}")]
[HttpPost("{id}/delete")]
public async Task Delete(Guid id)
@@ -979,6 +1027,47 @@ public class CiphersController : Controller
await _cipherService.SoftDeleteManyAsync(cipherIds, userId, new Guid(model.OrganizationId), true);
}
[HttpPut("{id}/unarchive")]
[RequireFeature(FeatureFlagKeys.ArchiveVaultItems)]
public async Task<CipherMiniResponseModel> PutUnarchive(Guid id)
{
var userId = _userService.GetProperUserId(User).Value;
var unarchivedCipherDetails = await _unarchiveCiphersCommand.UnarchiveManyAsync([id], userId);
if (unarchivedCipherDetails.Count == 0)
{
throw new BadRequestException("Cipher was not unarchived. Ensure the provided ID is correct and you have permission to archive it.");
}
return new CipherMiniResponseModel(unarchivedCipherDetails.First(), _globalSettings, unarchivedCipherDetails.First().OrganizationUseTotp);
}
[HttpPut("unarchive")]
[RequireFeature(FeatureFlagKeys.ArchiveVaultItems)]
public async Task<ListResponseModel<CipherMiniResponseModel>> PutUnarchiveMany([FromBody] CipherBulkUnarchiveRequestModel model)
{
if (!_globalSettings.SelfHosted && model.Ids.Count() > 500)
{
throw new BadRequestException("You can only unarchive up to 500 items at a time.");
}
var userId = _userService.GetProperUserId(User).Value;
var cipherIdsToUnarchive = new HashSet<Guid>(model.Ids);
var unarchivedCipherOrganizationDetails = await _unarchiveCiphersCommand.UnarchiveManyAsync(cipherIdsToUnarchive, userId);
if (unarchivedCipherOrganizationDetails.Count == 0)
{
throw new BadRequestException("Ciphers were not unarchived. Ensure the provided ID is correct and you have permission to archive it.");
}
var responses = unarchivedCipherOrganizationDetails.Select(c => new CipherMiniResponseModel(c, _globalSettings, c.OrganizationUseTotp));
return new ListResponseModel<CipherMiniResponseModel>(responses);
}
[HttpPut("{id}/restore")]
public async Task<CipherResponseModel> PutRestore(Guid id)
{

View File

@@ -46,6 +46,7 @@ public class CipherRequestModel
public CipherSecureNoteModel SecureNote { get; set; }
public CipherSSHKeyModel SSHKey { get; set; }
public DateTime? LastKnownRevisionDate { get; set; } = null;
public DateTime? ArchivedDate { get; set; }
public CipherDetails ToCipherDetails(Guid userId, bool allowOrgIdSet = true)
{
@@ -99,6 +100,7 @@ public class CipherRequestModel
existingCipher.Reprompt = Reprompt;
existingCipher.Key = Key;
existingCipher.ArchivedDate = ArchivedDate;
var hasAttachments2 = (Attachments2?.Count ?? 0) > 0;
var hasAttachments = (Attachments?.Count ?? 0) > 0;
@@ -316,6 +318,12 @@ public class CipherCollectionsRequestModel
public IEnumerable<string> CollectionIds { get; set; }
}
public class CipherBulkArchiveRequestModel
{
[Required]
public IEnumerable<Guid> Ids { get; set; }
}
public class CipherBulkDeleteRequestModel
{
[Required]
@@ -323,6 +331,12 @@ public class CipherBulkDeleteRequestModel
public string OrganizationId { get; set; }
}
public class CipherBulkUnarchiveRequestModel
{
[Required]
public IEnumerable<Guid> Ids { get; set; }
}
public class CipherBulkRestoreRequestModel
{
[Required]

View File

@@ -74,6 +74,7 @@ public class CipherMiniResponseModel : ResponseModel
DeletedDate = cipher.DeletedDate;
Reprompt = cipher.Reprompt.GetValueOrDefault(CipherRepromptType.None);
Key = cipher.Key;
ArchivedDate = cipher.ArchivedDate;
}
public Guid Id { get; set; }
@@ -96,6 +97,7 @@ public class CipherMiniResponseModel : ResponseModel
public DateTime? DeletedDate { get; set; }
public CipherRepromptType Reprompt { get; set; }
public string Key { get; set; }
public DateTime? ArchivedDate { get; set; }
}
public class CipherResponseModel : CipherMiniResponseModel

View File

@@ -229,6 +229,9 @@ public static class FeatureFlagKeys
public const string PM19315EndUserActivationMvp = "pm-19315-end-user-activation-mvp";
public const string PM22136_SdkCipherEncryption = "pm-22136-sdk-cipher-encryption";
/* Innovation Team */
public const string ArchiveVaultItems = "pm-19148-innovation-archive";
public static List<string> GetAllKeys()
{
return typeof(FeatureFlagKeys).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)

View File

@@ -0,0 +1,61 @@
using Bit.Core.Exceptions;
using Bit.Core.Platform.Push;
using Bit.Core.Vault.Commands.Interfaces;
using Bit.Core.Vault.Models.Data;
using Bit.Core.Vault.Repositories;
namespace Bit.Core.Vault.Commands;
public class ArchiveCiphersCommand : IArchiveCiphersCommand
{
private readonly ICipherRepository _cipherRepository;
private readonly IPushNotificationService _pushService;
public ArchiveCiphersCommand(
ICipherRepository cipherRepository,
IPushNotificationService pushService
)
{
_cipherRepository = cipherRepository;
_pushService = pushService;
}
public async Task<ICollection<CipherDetails>> ArchiveManyAsync(IEnumerable<Guid> cipherIds,
Guid archivingUserId)
{
var cipherIdEnumerable = cipherIds as Guid[] ?? cipherIds.ToArray();
if (cipherIds == null || cipherIdEnumerable.Length == 0)
throw new BadRequestException("No cipher ids provided.");
var cipherIdsSet = new HashSet<Guid>(cipherIdEnumerable);
var ciphers = await _cipherRepository.GetManyByUserIdAsync(archivingUserId);
if (ciphers == null || ciphers.Count == 0)
{
return [];
}
var archivingCiphers = ciphers
.Where(c => cipherIdsSet.Contains(c.Id) && c is { Edit: true, OrganizationId: null, ArchivedDate: null })
.ToList();
var revisionDate = await _cipherRepository.ArchiveAsync(archivingCiphers.Select(c => c.Id), archivingUserId);
// Adding specifyKind because revisionDate is currently coming back as Unspecified from the database
revisionDate = DateTime.SpecifyKind(revisionDate, DateTimeKind.Utc);
archivingCiphers.ForEach(c =>
{
c.RevisionDate = revisionDate;
c.ArchivedDate = revisionDate;
});
// Will not log an event because the archive feature is limited to individual ciphers, and event logs only apply to organization ciphers.
// Add event logging here if this is expanded to organization ciphers in the future.
await _pushService.PushSyncCiphersAsync(archivingUserId);
return archivingCiphers;
}
}

View File

@@ -0,0 +1,14 @@
using Bit.Core.Vault.Models.Data;
namespace Bit.Core.Vault.Commands.Interfaces;
public interface IArchiveCiphersCommand
{
/// <summary>
/// Archives a cipher. This fills in the ArchivedDate property on a Cipher.
/// </summary>
/// <param name="cipherIds">Cipher ID to archive.</param>
/// <param name="archivingUserId">User ID to check against the Ciphers that are trying to be archived.</param>
/// <returns></returns>
public Task<ICollection<CipherDetails>> ArchiveManyAsync(IEnumerable<Guid> cipherIds, Guid archivingUserId);
}

View File

@@ -0,0 +1,14 @@
using Bit.Core.Vault.Models.Data;
namespace Bit.Core.Vault.Commands.Interfaces;
public interface IUnarchiveCiphersCommand
{
/// <summary>
/// Unarchives a cipher. This nulls the ArchivedDate property on a Cipher.
/// </summary>
/// <param name="cipherIds">Cipher ID to unarchive.</param>
/// <param name="unarchivingUserId">User ID to check against the Ciphers that are trying to be unarchived.</param>
/// <returns></returns>
public Task<ICollection<CipherDetails>> UnarchiveManyAsync(IEnumerable<Guid> cipherIds, Guid unarchivingUserId);
}

View File

@@ -0,0 +1,60 @@
using Bit.Core.Exceptions;
using Bit.Core.Platform.Push;
using Bit.Core.Vault.Commands.Interfaces;
using Bit.Core.Vault.Models.Data;
using Bit.Core.Vault.Repositories;
namespace Bit.Core.Vault.Commands;
public class UnarchiveCiphersCommand : IUnarchiveCiphersCommand
{
private readonly ICipherRepository _cipherRepository;
private readonly IPushNotificationService _pushService;
public UnarchiveCiphersCommand(
ICipherRepository cipherRepository,
IPushNotificationService pushService
)
{
_cipherRepository = cipherRepository;
_pushService = pushService;
}
public async Task<ICollection<CipherDetails>> UnarchiveManyAsync(IEnumerable<Guid> cipherIds,
Guid unarchivingUserId)
{
var cipherIdEnumerable = cipherIds as Guid[] ?? cipherIds.ToArray();
if (cipherIds == null || cipherIdEnumerable.Length == 0)
throw new BadRequestException("No cipher ids provided.");
var cipherIdsSet = new HashSet<Guid>(cipherIdEnumerable);
var ciphers = await _cipherRepository.GetManyByUserIdAsync(unarchivingUserId);
if (ciphers == null || ciphers.Count == 0)
{
return [];
}
var unarchivingCiphers = ciphers
.Where(c => cipherIdsSet.Contains(c.Id) && c is { Edit: true, ArchivedDate: not null })
.ToList();
var revisionDate =
await _cipherRepository.UnarchiveAsync(unarchivingCiphers.Select(c => c.Id), unarchivingUserId);
// Adding specifyKind because revisionDate is currently coming back as Unspecified from the database
revisionDate = DateTime.SpecifyKind(revisionDate, DateTimeKind.Utc);
unarchivingCiphers.ForEach(c =>
{
c.RevisionDate = revisionDate;
c.ArchivedDate = null;
});
// Will not log an event because the archive feature is limited to individual ciphers, and event logs only apply to organization ciphers.
// Add event logging here if this is expanded to organization ciphers in the future.
await _pushService.PushSyncCiphersAsync(unarchivingUserId);
return unarchivingCiphers;
}
}

View File

@@ -25,6 +25,7 @@ public class Cipher : ITableObject<Guid>, ICloneable
public DateTime? DeletedDate { get; set; }
public Enums.CipherRepromptType? Reprompt { get; set; }
public string Key { get; set; }
public DateTime? ArchivedDate { get; set; }
public void SetNewId()
{

View File

@@ -3,6 +3,8 @@
public enum CipherStateAction
{
Restore,
Unarchive,
Archive,
SoftDelete,
HardDelete,
}

View File

@@ -25,6 +25,7 @@ public interface ICipherRepository : IRepository<Cipher, Guid>
Task<bool> ReplaceAsync(Cipher obj, IEnumerable<Guid> collectionIds);
Task UpdatePartialAsync(Guid id, Guid userId, Guid? folderId, bool favorite);
Task UpdateAttachmentAsync(CipherAttachment attachment);
Task<DateTime> ArchiveAsync(IEnumerable<Guid> ids, Guid userId);
Task DeleteAttachmentAsync(Guid cipherId, string attachmentId);
Task DeleteAsync(IEnumerable<Guid> ids, Guid userId);
Task DeleteByIdsOrganizationIdAsync(IEnumerable<Guid> ids, Guid organizationId);
@@ -56,6 +57,7 @@ public interface ICipherRepository : IRepository<Cipher, Guid>
IEnumerable<CollectionCipher> collectionCiphers, IEnumerable<CollectionUser> collectionUsers);
Task SoftDeleteAsync(IEnumerable<Guid> ids, Guid userId);
Task SoftDeleteByIdsOrganizationIdAsync(IEnumerable<Guid> ids, Guid organizationId);
Task<DateTime> UnarchiveAsync(IEnumerable<Guid> ids, Guid userId);
Task<DateTime> RestoreAsync(IEnumerable<Guid> ids, Guid userId);
Task<DateTime> RestoreByIdsOrganizationIdAsync(IEnumerable<Guid> ids, Guid organizationId);
Task DeleteDeletedAsync(DateTime deletedDateBefore);

View File

@@ -481,7 +481,7 @@ public class CipherService : ICipherService
throw new NotFoundException();
}
await _cipherRepository.DeleteByOrganizationIdAsync(organizationId);
await _eventService.LogOrganizationEventAsync(org, Bit.Core.Enums.EventType.Organization_PurgedVault);
await _eventService.LogOrganizationEventAsync(org, EventType.Organization_PurgedVault);
}
public async Task MoveManyAsync(IEnumerable<Guid> cipherIds, Guid? destinationFolderId, Guid movingUserId)
@@ -697,7 +697,7 @@ public class CipherService : ICipherService
await _collectionCipherRepository.UpdateCollectionsAsync(cipher.Id, savingUserId, collectionIds);
}
await _eventService.LogCipherEventAsync(cipher, Bit.Core.Enums.EventType.Cipher_UpdatedCollections);
await _eventService.LogCipherEventAsync(cipher, EventType.Cipher_UpdatedCollections);
// push
await _pushService.PushSyncCipherUpdateAsync(cipher, collectionIds);
@@ -786,8 +786,8 @@ public class CipherService : ICipherService
}
var cipherIdsSet = new HashSet<Guid>(cipherIds);
var restoringCiphers = new List<CipherOrganizationDetails>();
DateTime? revisionDate;
List<CipherOrganizationDetails> restoringCiphers;
DateTime? revisionDate; // TODO: Make this not nullable
if (orgAdmin && organizationId.HasValue)
{
@@ -971,6 +971,11 @@ public class CipherService : ICipherService
throw new BadRequestException("One or more ciphers do not belong to you.");
}
if (cipher.ArchivedDate.HasValue)
{
throw new BadRequestException("Cipher cannot be shared with organization because it is archived.");
}
var attachments = cipher.GetAttachments();
var hasAttachments = attachments?.Any() ?? false;
var org = await _organizationRepository.GetByIdAsync(organizationId);

View File

@@ -24,6 +24,8 @@ public static class VaultServiceCollectionExtensions
services.AddScoped<IGetSecurityTasksNotificationDetailsQuery, GetSecurityTasksNotificationDetailsQuery>();
services.AddScoped<ICreateManyTaskNotificationsCommand, CreateManyTaskNotificationsCommand>();
services.AddScoped<ICreateManyTasksCommand, CreateManyTasksCommand>();
services.AddScoped<IArchiveCiphersCommand, ArchiveCiphersCommand>();
services.AddScoped<IUnarchiveCiphersCommand, UnarchiveCiphersCommand>();
services.AddScoped<IMarkNotificationsForTaskAsDeletedCommand, MarkNotificationsForTaskAsDeletedCommand>();
services.AddScoped<IGetTaskMetricsForOrganizationQuery, GetTaskMetricsForOrganizationQuery>();
}

View File

@@ -240,11 +240,24 @@ public class CipherRepository : Repository<Cipher, Guid>, ICipherRepository
}
}
public async Task<DateTime> ArchiveAsync(IEnumerable<Guid> ids, Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteScalarAsync<DateTime>(
$"[{Schema}].[Cipher_Archive]",
new { Ids = ids.ToGuidIdArrayTVP(), UserId = userId },
commandType: CommandType.StoredProcedure);
return results;
}
}
public async Task DeleteAttachmentAsync(Guid cipherId, string attachmentId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteAsync(
await connection.ExecuteAsync(
$"[{Schema}].[Cipher_DeleteAttachment]",
new { Id = cipherId, AttachmentId = attachmentId },
commandType: CommandType.StoredProcedure);
@@ -830,6 +843,19 @@ public class CipherRepository : Repository<Cipher, Guid>, ICipherRepository
}
}
public async Task<DateTime> UnarchiveAsync(IEnumerable<Guid> ids, Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteScalarAsync<DateTime>(
$"[{Schema}].[Cipher_Unarchive]",
new { Ids = ids.ToGuidIdArrayTVP(), UserId = userId },
commandType: CommandType.StoredProcedure);
return results;
}
}
public async Task<DateTime> RestoreAsync(IEnumerable<Guid> ids, Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))

View File

@@ -71,7 +71,8 @@ public class UserCipherDetailsQuery : IQuery<CipherDetails>
Manage = cu == null ? (cg != null && cg.Manage == true) : cu.Manage == true,
OrganizationUseTotp = o.UseTotp,
c.Reprompt,
c.Key
c.Key,
c.ArchivedDate
};
var query2 = from c in dbContext.Ciphers
@@ -94,7 +95,8 @@ public class UserCipherDetailsQuery : IQuery<CipherDetails>
Manage = true,
OrganizationUseTotp = false,
c.Reprompt,
c.Key
c.Key,
c.ArchivedDate
};
var union = query.Union(query2).Select(c => new CipherDetails
@@ -115,7 +117,8 @@ public class UserCipherDetailsQuery : IQuery<CipherDetails>
ViewPassword = c.ViewPassword,
Manage = c.Manage,
OrganizationUseTotp = c.OrganizationUseTotp,
Key = c.Key
Key = c.Key,
ArchivedDate = c.ArchivedDate
});
return union;
}

View File

@@ -230,7 +230,7 @@ public class CipherRepository : Repository<Core.Vault.Entities.Cipher, Cipher, G
public async Task DeleteAsync(IEnumerable<Guid> ids, Guid userId)
{
await ToggleCipherStates(ids, userId, CipherStateAction.HardDelete);
await ToggleDeleteCipherStatesAsync(ids, userId, CipherStateAction.HardDelete);
}
public async Task DeleteAttachmentAsync(Guid cipherId, string attachmentId)
@@ -508,7 +508,8 @@ public class CipherRepository : Repository<Core.Vault.Entities.Cipher, Cipher, G
ViewPassword = true,
Manage = true,
OrganizationUseTotp = false,
Key = c.Key
Key = c.Key,
ArchivedDate = c.ArchivedDate,
};
}
@@ -751,9 +752,14 @@ public class CipherRepository : Repository<Core.Vault.Entities.Cipher, Cipher, G
}
}
public async Task<DateTime> UnarchiveAsync(IEnumerable<Guid> ids, Guid userId)
{
return await ToggleArchiveCipherStatesAsync(ids, userId, CipherStateAction.Unarchive);
}
public async Task<DateTime> RestoreAsync(IEnumerable<Guid> ids, Guid userId)
{
return await ToggleCipherStates(ids, userId, CipherStateAction.Restore);
return await ToggleDeleteCipherStatesAsync(ids, userId, CipherStateAction.Restore);
}
public async Task<DateTime> RestoreByIdsOrganizationIdAsync(IEnumerable<Guid> ids, Guid organizationId)
@@ -781,20 +787,25 @@ public class CipherRepository : Repository<Core.Vault.Entities.Cipher, Cipher, G
}
}
public async Task SoftDeleteAsync(IEnumerable<Guid> ids, Guid userId)
public async Task<DateTime> ArchiveAsync(IEnumerable<Guid> ids, Guid userId)
{
await ToggleCipherStates(ids, userId, CipherStateAction.SoftDelete);
return await ToggleArchiveCipherStatesAsync(ids, userId, CipherStateAction.Archive);
}
private async Task<DateTime> ToggleCipherStates(IEnumerable<Guid> ids, Guid userId, CipherStateAction action)
public async Task SoftDeleteAsync(IEnumerable<Guid> ids, Guid userId)
{
static bool FilterDeletedDate(CipherStateAction action, CipherDetails ucd)
await ToggleDeleteCipherStatesAsync(ids, userId, CipherStateAction.SoftDelete);
}
private async Task<DateTime> ToggleArchiveCipherStatesAsync(IEnumerable<Guid> ids, Guid userId, CipherStateAction action)
{
static bool FilterArchivedDate(CipherStateAction action, CipherDetails ucd)
{
return action switch
{
CipherStateAction.Restore => ucd.DeletedDate != null,
CipherStateAction.SoftDelete => ucd.DeletedDate == null,
_ => true,
CipherStateAction.Unarchive => ucd.ArchivedDate != null,
CipherStateAction.Archive => ucd.ArchivedDate == null,
_ => true
};
}
@@ -802,8 +813,49 @@ public class CipherRepository : Repository<Core.Vault.Entities.Cipher, Cipher, G
{
var dbContext = GetDatabaseContext(scope);
var userCipherDetailsQuery = new UserCipherDetailsQuery(userId);
var cipherEntitiesToCheck = await (dbContext.Ciphers.Where(c => ids.Contains(c.Id))).ToListAsync();
var query = from ucd in await (userCipherDetailsQuery.Run(dbContext)).ToListAsync()
var cipherEntitiesToCheck = await dbContext.Ciphers.Where(c => ids.Contains(c.Id)).ToListAsync();
var query = from ucd in await userCipherDetailsQuery.Run(dbContext).ToListAsync()
join c in cipherEntitiesToCheck
on ucd.Id equals c.Id
where ucd.Edit && FilterArchivedDate(action, ucd)
select c;
var utcNow = DateTime.UtcNow;
var cipherIdsToModify = query.Select(c => c.Id);
var cipherEntitiesToModify = dbContext.Ciphers.Where(x => cipherIdsToModify.Contains(x.Id));
await cipherEntitiesToModify.ForEachAsync(cipher =>
{
dbContext.Attach(cipher);
cipher.ArchivedDate = action == CipherStateAction.Unarchive ? null : utcNow;
cipher.RevisionDate = utcNow;
});
await dbContext.UserBumpAccountRevisionDateAsync(userId);
await dbContext.SaveChangesAsync();
return utcNow;
}
}
private async Task<DateTime> ToggleDeleteCipherStatesAsync(IEnumerable<Guid> ids, Guid userId, CipherStateAction action)
{
static bool FilterDeletedDate(CipherStateAction action, CipherDetails ucd)
{
return action switch
{
CipherStateAction.Restore => ucd.DeletedDate != null,
CipherStateAction.SoftDelete => ucd.DeletedDate == null,
_ => true
};
}
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var userCipherDetailsQuery = new UserCipherDetailsQuery(userId);
var cipherEntitiesToCheck = await dbContext.Ciphers.Where(c => ids.Contains(c.Id)).ToListAsync();
var query = from ucd in await userCipherDetailsQuery.Run(dbContext).ToListAsync()
join c in cipherEntitiesToCheck
on ucd.Id equals c.Id
where ucd.Edit && FilterDeletedDate(action, ucd)
@@ -841,6 +893,7 @@ public class CipherRepository : Repository<Core.Vault.Entities.Cipher, Cipher, G
}
await dbContext.UserBumpAccountRevisionDateAsync(userId);
await dbContext.SaveChangesAsync();
return utcNow;
}
}

View File

@@ -34,6 +34,7 @@ public class CipherDetailsQuery : IQuery<CipherDetails>
FolderId = (_ignoreFolders || !_userId.HasValue || c.Folders == null || !c.Folders.ToLowerInvariant().Contains(_userId.Value.ToString())) ?
null :
CoreHelpers.LoadClassFromJsonData<Dictionary<Guid, Guid>>(c.Folders)[_userId.Value],
ArchivedDate = c.ArchivedDate,
};
return query;
}

View File

@@ -27,6 +27,7 @@ SELECT
END [FolderId],
C.[DeletedDate],
C.[Reprompt],
C.[Key]
C.[Key],
C.[ArchivedDate]
FROM
[dbo].[Cipher] C
[dbo].[Cipher] C

View File

@@ -17,7 +17,8 @@
@OrganizationUseTotp BIT, -- not used
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL
@Key VARCHAR(MAX) = NULL,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
@@ -38,7 +39,8 @@ BEGIN
[RevisionDate],
[DeletedDate],
[Reprompt],
[Key]
[Key],
[ArchivedDate]
)
VALUES
(
@@ -53,7 +55,8 @@ BEGIN
@RevisionDate,
@DeletedDate,
@Reprompt,
@Key
@Key,
@ArchivedDate
)
IF @OrganizationId IS NOT NULL

View File

@@ -18,14 +18,15 @@
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@CollectionIds AS [dbo].[GuidIdArray] READONLY
@CollectionIds AS [dbo].[GuidIdArray] READONLY,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[CipherDetails_Create] @Id, @UserId, @OrganizationId, @Type, @Data, @Favorites, @Folders,
@Attachments, @CreationDate, @RevisionDate, @FolderId, @Favorite, @Edit, @ViewPassword, @Manage,
@OrganizationUseTotp, @DeletedDate, @Reprompt, @Key
@OrganizationUseTotp, @DeletedDate, @Reprompt, @Key, @ArchivedDate
DECLARE @UpdateCollectionsSuccess INT
EXEC @UpdateCollectionsSuccess = [dbo].[Cipher_UpdateCollections] @Id, @UserId, @OrganizationId, @CollectionIds

View File

@@ -20,6 +20,7 @@ SELECT
[Reprompt],
[Key],
[OrganizationUseTotp],
[ArchivedDate],
MAX ([Edit]) AS [Edit],
MAX ([ViewPassword]) AS [ViewPassword],
MAX ([Manage]) AS [Manage]
@@ -41,5 +42,6 @@ SELECT
[DeletedDate],
[Reprompt],
[Key],
[OrganizationUseTotp]
[OrganizationUseTotp],
[ArchivedDate]
END

View File

@@ -17,7 +17,8 @@
@OrganizationUseTotp BIT, -- not used
@DeletedDate DATETIME2(2),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL
@Key VARCHAR(MAX) = NULL,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
@@ -55,7 +56,8 @@ BEGIN
[CreationDate] = @CreationDate,
[RevisionDate] = @RevisionDate,
[DeletedDate] = @DeletedDate,
[Key] = @Key
[Key] = @Key,
[ArchivedDate] = @ArchivedDate
WHERE
[Id] = @Id

View File

@@ -0,0 +1,39 @@
CREATE PROCEDURE [dbo].[Cipher_Archive]
@Ids AS [dbo].[GuidIdArray] READONLY,
@UserId AS UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #Temp
(
[Id] UNIQUEIDENTIFIER NOT NULL,
[UserId] UNIQUEIDENTIFIER NULL
)
INSERT INTO #Temp
SELECT
[Id],
[UserId]
FROM
[dbo].[UserCipherDetails](@UserId)
WHERE
[Edit] = 1
AND [ArchivedDate] IS NULL
AND [Id] IN (SELECT * FROM @Ids)
DECLARE @UtcNow DATETIME2(7) = SYSUTCDATETIME();
UPDATE
[dbo].[Cipher]
SET
[ArchivedDate] = @UtcNow,
[RevisionDate] = @UtcNow
WHERE
[Id] IN (SELECT [Id] FROM #Temp)
EXEC [dbo].[User_BumpAccountRevisionDate] @UserId
DROP TABLE #Temp
SELECT @UtcNow
END

View File

@@ -11,7 +11,8 @@
@RevisionDate DATETIME2(7),
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL
@Key VARCHAR(MAX) = NULL,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
@@ -29,7 +30,8 @@ BEGIN
[RevisionDate],
[DeletedDate],
[Reprompt],
[Key]
[Key],
[ArchivedDate]
)
VALUES
(
@@ -44,7 +46,8 @@ BEGIN
@RevisionDate,
@DeletedDate,
@Reprompt,
@Key
@Key,
@ArchivedDate
)
IF @OrganizationId IS NOT NULL

View File

@@ -12,14 +12,15 @@
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@CollectionIds AS [dbo].[GuidIdArray] READONLY
@CollectionIds AS [dbo].[GuidIdArray] READONLY,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Cipher_Create] @Id, @UserId, @OrganizationId, @Type, @Data, @Favorites, @Folders,
@Attachments, @CreationDate, @RevisionDate, @DeletedDate, @Reprompt, @Key
@Attachments, @CreationDate, @RevisionDate, @DeletedDate, @Reprompt, @Key, @ArchivedDate
DECLARE @UpdateCollectionsSuccess INT
EXEC @UpdateCollectionsSuccess = [dbo].[Cipher_UpdateCollections] @Id, @UserId, @OrganizationId, @CollectionIds
END
END

View File

@@ -0,0 +1,39 @@
CREATE PROCEDURE [dbo].[Cipher_Unarchive]
@Ids AS [dbo].[GuidIdArray] READONLY,
@UserId AS UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #Temp
(
[Id] UNIQUEIDENTIFIER NOT NULL,
[UserId] UNIQUEIDENTIFIER NULL
)
INSERT INTO #Temp
SELECT
[Id],
[UserId]
FROM
[dbo].[UserCipherDetails](@UserId)
WHERE
[Edit] = 1
AND [ArchivedDate] IS NOT NULL
AND [Id] IN (SELECT * FROM @Ids)
DECLARE @UtcNow DATETIME2(7) = SYSUTCDATETIME();
UPDATE
[dbo].[Cipher]
SET
[ArchivedDate] = NULL,
[RevisionDate] = @UtcNow
WHERE
[Id] IN (SELECT [Id] FROM #Temp)
EXEC [dbo].[User_BumpAccountRevisionDate] @UserId
DROP TABLE #Temp
SELECT @UtcNow
END

View File

@@ -11,7 +11,8 @@
@RevisionDate DATETIME2(7),
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL
@Key VARCHAR(MAX) = NULL,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
@@ -30,7 +31,8 @@ BEGIN
[RevisionDate] = @RevisionDate,
[DeletedDate] = @DeletedDate,
[Reprompt] = @Reprompt,
[Key] = @Key
[Key] = @Key,
[ArchivedDate] = @ArchivedDate
WHERE
[Id] = @Id

View File

@@ -12,7 +12,8 @@
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@CollectionIds AS [dbo].[GuidIdArray] READONLY
@CollectionIds AS [dbo].[GuidIdArray] READONLY,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
@@ -37,8 +38,7 @@ BEGIN
[Data] = @Data,
[Attachments] = @Attachments,
[RevisionDate] = @RevisionDate,
[DeletedDate] = @DeletedDate,
[Key] = @Key
[DeletedDate] = @DeletedDate, [Key] = @Key, [ArchivedDate] = @ArchivedDate
-- No need to update CreationDate, Favorites, Folders, or Type since that data will not change
WHERE
[Id] = @Id
@@ -54,4 +54,4 @@ BEGIN
EXEC [dbo].[User_BumpAccountRevisionDateByCipherId] @Id, @OrganizationId
SELECT 0 -- 0 = Success
END
END

View File

@@ -13,6 +13,7 @@ CREATE TABLE [dbo].[Cipher] (
[DeletedDate] DATETIME2 (7) NULL,
[Reprompt] TINYINT NULL,
[Key] VARCHAR(MAX) NULL,
[ArchivedDate] DATETIME2 (7) NULL,
CONSTRAINT [PK_Cipher] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Cipher_Organization] FOREIGN KEY ([OrganizationId]) REFERENCES [dbo].[Organization] ([Id]),
CONSTRAINT [FK_Cipher_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([Id])
@@ -34,4 +35,5 @@ GO
CREATE NONCLUSTERED INDEX [IX_Cipher_DeletedDate]
ON [dbo].[Cipher]([DeletedDate] ASC);
GO