1
0
mirror of https://github.com/bitwarden/server synced 2025-12-06 00:03:34 +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

View File

@@ -12,9 +12,11 @@ internal class OrganizationCipher : ICustomization
{
fixture.Customize<Cipher>(composer => composer
.With(c => c.OrganizationId, OrganizationId ?? Guid.NewGuid())
.Without(c => c.ArchivedDate)
.Without(c => c.UserId));
fixture.Customize<CipherDetails>(composer => composer
.With(c => c.OrganizationId, Guid.NewGuid())
.Without(c => c.ArchivedDate)
.Without(c => c.UserId));
}
}
@@ -26,9 +28,11 @@ internal class UserCipher : ICustomization
{
fixture.Customize<Cipher>(composer => composer
.With(c => c.UserId, UserId ?? Guid.NewGuid())
.Without(c => c.ArchivedDate)
.Without(c => c.OrganizationId));
fixture.Customize<CipherDetails>(composer => composer
.With(c => c.UserId, Guid.NewGuid())
.Without(c => c.ArchivedDate)
.Without(c => c.OrganizationId));
}
}

View File

@@ -0,0 +1,49 @@
using Bit.Core.Entities;
using Bit.Core.Platform.Push;
using Bit.Core.Test.AutoFixture.CipherFixtures;
using Bit.Core.Vault.Commands;
using Bit.Core.Vault.Models.Data;
using Bit.Core.Vault.Repositories;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.Vault.Commands;
[UserCipherCustomize]
[SutProviderCustomize]
public class ArchiveCiphersCommandTest
{
[Theory]
[BitAutoData(true, false, 1, 1, 1)]
[BitAutoData(false, false, 1, 0, 1)]
[BitAutoData(false, true, 1, 0, 1)]
[BitAutoData(true, true, 1, 0, 1)]
public async Task ArchiveAsync_Works(
bool isEditable, bool hasOrganizationId,
int cipherRepoCalls, int resultCountFromQuery, int pushNotificationsCalls,
SutProvider<ArchiveCiphersCommand> sutProvider, CipherDetails cipher, User user)
{
cipher.Edit = isEditable;
cipher.OrganizationId = hasOrganizationId ? Guid.NewGuid() : null;
var cipherList = new List<CipherDetails> { cipher };
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(user.Id).Returns(cipherList);
// Act
await sutProvider.Sut.ArchiveManyAsync([cipher.Id], user.Id);
// Assert
await sutProvider.GetDependency<ICipherRepository>().Received(cipherRepoCalls).ArchiveAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.Count() == resultCountFromQuery
&& ids.Count() >= 1
? true
: ids.All(id => cipherList.Contains(cipher))),
user.Id);
await sutProvider.GetDependency<IPushNotificationService>().Received(pushNotificationsCalls)
.PushSyncCiphersAsync(user.Id);
}
}

View File

@@ -0,0 +1,49 @@
using Bit.Core.Entities;
using Bit.Core.Platform.Push;
using Bit.Core.Test.AutoFixture.CipherFixtures;
using Bit.Core.Vault.Commands;
using Bit.Core.Vault.Models.Data;
using Bit.Core.Vault.Repositories;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.Vault.Commands;
[UserCipherCustomize]
[SutProviderCustomize]
public class UnarchiveCiphersCommandTest
{
[Theory]
[BitAutoData(true, false, 1, 1, 1)]
[BitAutoData(false, false, 1, 0, 1)]
[BitAutoData(false, true, 1, 0, 1)]
[BitAutoData(true, true, 1, 1, 1)]
public async Task UnarchiveAsync_Works(
bool isEditable, bool hasOrganizationId,
int cipherRepoCalls, int resultCountFromQuery, int pushNotificationsCalls,
SutProvider<UnarchiveCiphersCommand> sutProvider, CipherDetails cipher, User user)
{
cipher.Edit = isEditable;
cipher.OrganizationId = hasOrganizationId ? Guid.NewGuid() : null;
var cipherList = new List<CipherDetails> { cipher };
sutProvider.GetDependency<ICipherRepository>()
.GetManyByUserIdAsync(user.Id).Returns(cipherList);
// Act
await sutProvider.Sut.UnarchiveManyAsync([cipher.Id], user.Id);
// Assert
await sutProvider.GetDependency<ICipherRepository>().Received(cipherRepoCalls).UnarchiveAsync(
Arg.Is<IEnumerable<Guid>>(ids => ids.Count() == resultCountFromQuery
&& ids.Count() >= 1
? true
: ids.All(id => cipherList.Contains(cipher))),
user.Id);
await sutProvider.GetDependency<IPushNotificationService>().Received(pushNotificationsCalls)
.PushSyncCiphersAsync(user.Id);
}
}

View File

@@ -1211,4 +1211,34 @@ public class CipherRepositoryTests
Assert.Null(deletedCipher2);
}
[DatabaseTheory, DatabaseData]
public async Task ArchiveAsync_Works(
ICipherRepository sutRepository,
IUserRepository userRepository)
{
var user = await userRepository.CreateAsync(new User
{
Name = "Test User",
Email = $"test+{Guid.NewGuid()}@email.com",
ApiKey = "TEST",
SecurityStamp = "stamp",
});
// Ciphers
var cipher = await sutRepository.CreateAsync(new Cipher
{
Type = CipherType.Login,
Data = "",
UserId = user.Id
});
// Act
await sutRepository.ArchiveAsync(new List<Guid> { cipher.Id }, user.Id);
// Assert
var archivedCipher = await sutRepository.GetByIdAsync(cipher.Id, user.Id);
Assert.NotNull(archivedCipher);
Assert.NotNull(archivedCipher.ArchivedDate);
}
}

View File

@@ -0,0 +1,576 @@
-- Add the ArchivedDate column to the Cipher table
IF COL_LENGTH('[dbo].[Cipher]', 'ArchivedDate') IS NULL
BEGIN
ALTER TABLE [dbo].[Cipher]
ADD [ArchivedDate] DATETIME2(7) NULL
END
GO
-- Recreate CipherView
CREATE OR ALTER VIEW [dbo].[CipherView]
AS
SELECT
*
FROM
[dbo].[Cipher]
GO
-- Alter CipherDetails function
CREATE OR ALTER FUNCTION [dbo].[CipherDetails](@UserId UNIQUEIDENTIFIER)
RETURNS TABLE
AS RETURN
SELECT
C.[Id],
C.[UserId],
C.[OrganizationId],
C.[Type],
C.[Data],
C.[Attachments],
C.[CreationDate],
C.[RevisionDate],
CASE
WHEN
@UserId IS NULL
OR C.[Favorites] IS NULL
OR JSON_VALUE(C.[Favorites], CONCAT('$."', @UserId, '"')) IS NULL
THEN 0
ELSE 1
END [Favorite],
CASE
WHEN
@UserId IS NULL
OR C.[Folders] IS NULL
THEN NULL
ELSE TRY_CONVERT(UNIQUEIDENTIFIER, JSON_VALUE(C.[Folders], CONCAT('$."', @UserId, '"')))
END [FolderId],
C.[DeletedDate],
C.[Reprompt],
C.[Key],
C.[ArchivedDate]
FROM
[dbo].[Cipher] C
GO
-- Manually refresh UserCipherDetails
IF OBJECT_ID('[dbo].[UserCipherDetails]') IS NOT NULL
BEGIN
EXECUTE sp_refreshsqlmodule N'[dbo].[UserCipherDetails]';
END
GO
-- Update sprocs
CREATE OR ALTER PROCEDURE [dbo].[Cipher_Create]
@Id UNIQUEIDENTIFIER OUTPUT,
@UserId UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Type TINYINT,
@Data NVARCHAR(MAX),
@Favorites NVARCHAR(MAX),
@Folders NVARCHAR(MAX),
@Attachments NVARCHAR(MAX),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[Cipher]
(
[Id],
[UserId],
[OrganizationId],
[Type],
[Data],
[Favorites],
[Folders],
[CreationDate],
[RevisionDate],
[DeletedDate],
[Reprompt],
[Key],
[ArchivedDate]
)
VALUES
(
@Id,
CASE WHEN @OrganizationId IS NULL THEN @UserId ELSE NULL END,
@OrganizationId,
@Type,
@Data,
@Favorites,
@Folders,
@CreationDate,
@RevisionDate,
@DeletedDate,
@Reprompt,
@Key,
@ArchivedDate
)
IF @OrganizationId IS NOT NULL
BEGIN
EXEC [dbo].[User_BumpAccountRevisionDateByCipherId] @Id, @OrganizationId
END
ELSE IF @UserId IS NOT NULL
BEGIN
EXEC [dbo].[User_BumpAccountRevisionDate] @UserId
END
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Cipher_Update]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Type TINYINT,
@Data NVARCHAR(MAX),
@Favorites NVARCHAR(MAX),
@Folders NVARCHAR(MAX),
@Attachments NVARCHAR(MAX),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[Cipher]
SET
[UserId] = CASE WHEN @OrganizationId IS NULL THEN @UserId ELSE NULL END,
[OrganizationId] = @OrganizationId,
[Type] = @Type,
[Data] = @Data,
[Favorites] = @Favorites,
[Folders] = @Folders,
[Attachments] = @Attachments,
[CreationDate] = @CreationDate,
[RevisionDate] = @RevisionDate,
[DeletedDate] = @DeletedDate,
[Reprompt] = @Reprompt,
[Key] = @Key,
[ArchivedDate] = @ArchivedDate
WHERE
[Id] = @Id
IF @OrganizationId IS NOT NULL
BEGIN
EXEC [dbo].[User_BumpAccountRevisionDateByCipherId] @Id, @OrganizationId
END
ELSE IF @UserId IS NOT NULL
BEGIN
EXEC [dbo].[User_BumpAccountRevisionDate] @UserId
END
END
GO
CREATE OR ALTER PROCEDURE [dbo].[CipherDetails_Create]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Type TINYINT,
@Data NVARCHAR(MAX),
@Favorites NVARCHAR(MAX), -- not used
@Folders NVARCHAR(MAX), -- not used
@Attachments NVARCHAR(MAX), -- not used
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@FolderId UNIQUEIDENTIFIER,
@Favorite BIT,
@Edit BIT, -- not used
@ViewPassword BIT, -- not used
@Manage BIT, -- not used
@OrganizationUseTotp BIT, -- not used
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
DECLARE @UserIdKey VARCHAR(50) = CONCAT('"', @UserId, '"')
DECLARE @UserIdPath VARCHAR(50) = CONCAT('$.', @UserIdKey)
INSERT INTO [dbo].[Cipher]
(
[Id],
[UserId],
[OrganizationId],
[Type],
[Data],
[Favorites],
[Folders],
[CreationDate],
[RevisionDate],
[DeletedDate],
[Reprompt],
[Key],
[ArchivedDate]
)
VALUES
(
@Id,
CASE WHEN @OrganizationId IS NULL THEN @UserId ELSE NULL END,
@OrganizationId,
@Type,
@Data,
CASE WHEN @Favorite = 1 THEN CONCAT('{', @UserIdKey, ':true}') ELSE NULL END,
CASE WHEN @FolderId IS NOT NULL THEN CONCAT('{', @UserIdKey, ':"', @FolderId, '"', '}') ELSE NULL END,
@CreationDate,
@RevisionDate,
@DeletedDate,
@Reprompt,
@Key,
@ArchivedDate
)
IF @OrganizationId IS NOT NULL
BEGIN
EXEC [dbo].[User_BumpAccountRevisionDateByCipherId] @Id, @OrganizationId
END
ELSE IF @UserId IS NOT NULL
BEGIN
EXEC [dbo].[User_BumpAccountRevisionDate] @UserId
END
END
GO
CREATE OR ALTER PROCEDURE [dbo].[CipherDetails_Update]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Type TINYINT,
@Data NVARCHAR(MAX),
@Favorites NVARCHAR(MAX), -- not used
@Folders NVARCHAR(MAX), -- not used
@Attachments NVARCHAR(MAX),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@FolderId UNIQUEIDENTIFIER,
@Favorite BIT,
@Edit BIT, -- not used
@ViewPassword BIT, -- not used
@Manage BIT, -- not used
@OrganizationUseTotp BIT, -- not used
@DeletedDate DATETIME2(2),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
DECLARE @UserIdKey VARCHAR(50) = CONCAT('"', @UserId, '"')
DECLARE @UserIdPath VARCHAR(50) = CONCAT('$.', @UserIdKey)
UPDATE
[dbo].[Cipher]
SET
[UserId] = CASE WHEN @OrganizationId IS NULL THEN @UserId ELSE NULL END,
[OrganizationId] = @OrganizationId,
[Type] = @Type,
[Data] = @Data,
[Folders] =
CASE
WHEN @FolderId IS NOT NULL AND [Folders] IS NULL THEN
CONCAT('{', @UserIdKey, ':"', @FolderId, '"', '}')
WHEN @FolderId IS NOT NULL THEN
JSON_MODIFY([Folders], @UserIdPath, CAST(@FolderId AS VARCHAR(50)))
ELSE
JSON_MODIFY([Folders], @UserIdPath, NULL)
END,
[Favorites] =
CASE
WHEN @Favorite = 1 AND [Favorites] IS NULL THEN
CONCAT('{', @UserIdKey, ':true}')
WHEN @Favorite = 1 THEN
JSON_MODIFY([Favorites], @UserIdPath, CAST(1 AS BIT))
ELSE
JSON_MODIFY([Favorites], @UserIdPath, NULL)
END,
[Attachments] = @Attachments,
[Reprompt] = @Reprompt,
[CreationDate] = @CreationDate,
[RevisionDate] = @RevisionDate,
[DeletedDate] = @DeletedDate,
[Key] = @Key,
[ArchivedDate] = @ArchivedDate
WHERE
[Id] = @Id
IF @OrganizationId IS NOT NULL
BEGIN
EXEC [dbo].[User_BumpAccountRevisionDateByCipherId] @Id, @OrganizationId
END
ELSE IF @UserId IS NOT NULL
BEGIN
EXEC [dbo].[User_BumpAccountRevisionDate] @UserId
END
END
GO
CREATE OR ALTER PROCEDURE [dbo].[CipherDetails_CreateWithCollections]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Type TINYINT,
@Data NVARCHAR(MAX),
@Favorites NVARCHAR(MAX), -- not used
@Folders NVARCHAR(MAX), -- not used
@Attachments NVARCHAR(MAX), -- not used
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@FolderId UNIQUEIDENTIFIER,
@Favorite BIT,
@Edit BIT, -- not used
@ViewPassword BIT, -- not used
@Manage BIT, -- not used
@OrganizationUseTotp BIT, -- not used
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@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, @ArchivedDate
DECLARE @UpdateCollectionsSuccess INT
EXEC @UpdateCollectionsSuccess = [dbo].[Cipher_UpdateCollections] @Id, @UserId, @OrganizationId, @CollectionIds
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Cipher_CreateWithCollections]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Type TINYINT,
@Data NVARCHAR(MAX),
@Favorites NVARCHAR(MAX),
@Folders NVARCHAR(MAX),
@Attachments NVARCHAR(MAX),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@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, @ArchivedDate
DECLARE @UpdateCollectionsSuccess INT
EXEC @UpdateCollectionsSuccess = [dbo].[Cipher_UpdateCollections] @Id, @UserId, @OrganizationId, @CollectionIds
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Cipher_UpdateWithCollections]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Type TINYINT,
@Data NVARCHAR(MAX),
@Favorites NVARCHAR(MAX),
@Folders NVARCHAR(MAX),
@Attachments NVARCHAR(MAX),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@DeletedDate DATETIME2(7),
@Reprompt TINYINT,
@Key VARCHAR(MAX) = NULL,
@CollectionIds AS [dbo].[GuidIdArray] READONLY,
@ArchivedDate DATETIME2(7) = NULL
AS
BEGIN
SET NOCOUNT ON
BEGIN TRANSACTION Cipher_UpdateWithCollections
DECLARE @UpdateCollectionsSuccess INT
EXEC @UpdateCollectionsSuccess = [dbo].[Cipher_UpdateCollections] @Id, @UserId, @OrganizationId, @CollectionIds
IF @UpdateCollectionsSuccess < 0
BEGIN
COMMIT TRANSACTION Cipher_UpdateWithCollections
SELECT -1 -- -1 = Failure
RETURN
END
UPDATE
[dbo].[Cipher]
SET
[UserId] = NULL,
[OrganizationId] = @OrganizationId,
[Data] = @Data,
[Attachments] = @Attachments,
[RevisionDate] = @RevisionDate,
[DeletedDate] = @DeletedDate,
[Key] = @Key,
[ArchivedDate] = @ArchivedDate
-- No need to update CreationDate, Favorites, Folders, or Type since that data will not change
WHERE
[Id] = @Id
COMMIT TRANSACTION Cipher_UpdateWithCollections
IF @Attachments IS NOT NULL
BEGIN
EXEC [dbo].[Organization_UpdateStorage] @OrganizationId
EXEC [dbo].[User_UpdateStorage] @UserId
END
EXEC [dbo].[User_BumpAccountRevisionDateByCipherId] @Id, @OrganizationId
SELECT 0 -- 0 = Success
END
GO
CREATE OR ALTER 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
GO
CREATE OR ALTER 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
GO
-- Update User Cipher Details With Archive
CREATE OR ALTER PROCEDURE [dbo].[CipherDetails_ReadByIdUserId]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
[Id],
[UserId],
[OrganizationId],
[Type],
[Data],
[Attachments],
[CreationDate],
[RevisionDate],
[Favorite],
[FolderId],
[DeletedDate],
[Reprompt],
[Key],
[OrganizationUseTotp],
[ArchivedDate],
MAX ([Edit]) AS [Edit],
MAX ([ViewPassword]) AS [ViewPassword],
MAX ([Manage]) AS [Manage]
FROM
[dbo].[UserCipherDetails](@UserId)
WHERE
[Id] = @Id
GROUP BY
[Id],
[UserId],
[OrganizationId],
[Type],
[Data],
[Attachments],
[CreationDate],
[RevisionDate],
[Favorite],
[FolderId],
[DeletedDate],
[Reprompt],
[Key],
[OrganizationUseTotp],
[ArchivedDate]
END

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.MySqlMigrations.Migrations;
/// <inheritdoc />
public partial class AddArchivedDateToCipher : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "ArchivedDate",
table: "Cipher",
type: "datetime(6)",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ArchivedDate",
table: "Cipher");
}
}

View File

@@ -2184,6 +2184,9 @@ namespace Bit.MySqlMigrations.Migrations
b.Property<Guid>("Id")
.HasColumnType("char(36)");
b.Property<DateTime?>("ArchivedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Attachments")
.HasColumnType("longtext");

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.PostgresMigrations.Migrations;
/// <inheritdoc />
public partial class AddArchivedDateToCipher : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "ArchivedDate",
table: "Cipher",
type: "timestamp with time zone",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ArchivedDate",
table: "Cipher");
}
}

View File

@@ -2190,6 +2190,9 @@ namespace Bit.PostgresMigrations.Migrations
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime?>("ArchivedDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("Attachments")
.HasColumnType("text");

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.SqliteMigrations.Migrations;
/// <inheritdoc />
public partial class AddArchivedDateToCipher : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "ArchivedDate",
table: "Cipher",
type: "TEXT",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ArchivedDate",
table: "Cipher");
}
}

View File

@@ -2173,6 +2173,9 @@ namespace Bit.SqliteMigrations.Migrations
b.Property<Guid>("Id")
.HasColumnType("TEXT");
b.Property<DateTime?>("ArchivedDate")
.HasColumnType("TEXT");
b.Property<string>("Attachments")
.HasColumnType("TEXT");