Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Refactor merge strategy: require client merge before save (#186)

Leendert de Borst06830baf3d9e
diff --git a/src/AliasVault.Admin/Main/Pages/Users/View.razor b/src/AliasVault.Admin/Main/Pages/Users/View.razor
index dfdacd0a3..0ff1cf649 100644
--- a/src/AliasVault.Admin/Main/Pages/Users/View.razor
+++ b/src/AliasVault.Admin/Main/Pages/Users/View.razor
@@ -257,6 +257,7 @@ else
{
Id = x.Id,
Version = x.Version,
+ RevisionNumber = x.RevisionNumber,
FileSize = x.FileSize,
CreatedAt = x.CreatedAt,
UpdatedAt = x.UpdatedAt,
diff --git a/src/AliasVault.Api/Controllers/VaultController.cs b/src/AliasVault.Api/Controllers/VaultController.cs
index a2c0f2f48..fee9312e5 100644
--- a/src/AliasVault.Api/Controllers/VaultController.cs
+++ b/src/AliasVault.Api/Controllers/VaultController.cs
@@ -50,7 +50,6 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
{
Rules =
[
- new RevisionNumberConflictRetentionRule(),
new DailyRetentionRule { DaysToKeep = 3 },
new WeeklyRetentionRule { WeeksToKeep = 1 },
new MonthlyRetentionRule { MonthsToKeep = 1 },
@@ -86,7 +85,7 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
{
return Ok(new Shared.Models.WebApi.Vault.VaultGetResponse
{
- Status = VaultGetStatus.Ok,
+ Status = VaultStatus.Ok,
Vault = new Shared.Models.WebApi.Vault.Vault
{
Blob = string.Empty,
@@ -111,14 +110,14 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
{
return Ok(new Shared.Models.WebApi.Vault.VaultGetResponse
{
- Status = VaultGetStatus.MergeRequired,
+ Status = VaultStatus.MergeRequired,
Vault = null,
});
}
return Ok(new Shared.Models.WebApi.Vault.VaultGetResponse
{
- Status = VaultGetStatus.Ok,
+ Status = VaultStatus.Ok,
Vault = new Shared.Models.WebApi.Vault.Vault
{
Blob = vault.VaultBlob,
@@ -136,9 +135,10 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
/// <summary>
/// Returns a list of vaults that should be merged by the client.
/// </summary>
- /// <returns>List of vaults to merge.</returns>
+ /// <param name="currentRevisionNumber">Current revision number of the local vault.</param>
+ /// <returns>List of vaults to merge that are newer than the provided current revision number.</returns>
[HttpGet("merge")]
- public async Task<IActionResult> GetVaultsToMerge()
+ public async Task<IActionResult> GetVaultsToMerge([FromQuery] long currentRevisionNumber)
{
await using var context = await dbContextFactory.CreateDbContextAsync();
@@ -149,26 +149,14 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
}
// Logic to retrieve vault for the user.
- var vault = await context.Vaults
- .Where(x => x.UserId == user.Id)
+ var vaultsToMerge = await context.Vaults
+ .Where(x => x.UserId == user.Id && x.RevisionNumber > currentRevisionNumber)
.OrderByDescending(x => x.UpdatedAt)
- .FirstOrDefaultAsync();
-
- // If no vault is found on server, return an empty object.
- if (vault == null)
- {
- return BadRequest("No vault(s) found for user.");
- }
-
- // Check if there are no other vaults with the same revision number.
- // If there are, return a merge required status.
- var otherVaults = await context.Vaults
- .Where(x => x.UserId == user.Id && x.RevisionNumber == vault.RevisionNumber)
.ToListAsync();
return Ok(new Shared.Models.WebApi.Vault.VaultMergeResponse
{
- Vaults = otherVaults.Select(x => new Shared.Models.WebApi.Vault.Vault
+ Vaults = vaultsToMerge.Select(x => new Shared.Models.WebApi.Vault.Vault
{
Blob = x.VaultBlob,
Version = x.Version,
@@ -199,14 +187,18 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
}
// Retrieve latest vault of user which contains the current encryption settings.
- var latestVault = user.Vaults.OrderByDescending(x => x.UpdatedAt).Select(x => new { x.Salt, x.Verifier, x.EncryptionType, x.EncryptionSettings }).First();
+ var latestVault = user.Vaults.OrderByDescending(x => x.UpdatedAt).Select(x => new { x.Salt, x.Verifier, x.EncryptionType, x.EncryptionSettings, x.RevisionNumber }).First();
// Calculate the new revision number for the vault.
- // Note: it is possible multiple clients are updating the vault at the same time which would cause
- // multiple vaults with the same revision number. This is expected and will trigger a vault
- // synchronize/merge process on the client side.
var newRevisionNumber = model.CurrentRevisionNumber + 1;
+ // Check if the latest vault revision number is equal to or higher than the new revision number.
+ // If so, reject update and return a merge required status.
+ if (latestVault.RevisionNumber >= newRevisionNumber)
+ {
+ return Ok(new VaultUpdateResponse { Status = VaultStatus.MergeRequired, NewRevisionNumber = latestVault.RevisionNumber });
+ }
+
// Create new vault entry with salt and verifier of current vault.
var newVault = new AliasServerDb.Vault
{
@@ -244,7 +236,7 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
await UpdateUserPublicKey(context, user.Id, model.EncryptionPublicKey);
}
- return Ok(new VaultUpdateResponse { NewRevisionNumber = newRevisionNumber });
+ return Ok(new VaultUpdateResponse { Status = VaultStatus.Ok, NewRevisionNumber = newRevisionNumber });
}
/// <summary>
diff --git a/src/AliasVault.Api/Vault/RetentionRules/RevisionNumberConflictRetentionRule.cs b/src/AliasVault.Api/Vault/RetentionRules/RevisionNumberConflictRetentionRule.cs
deleted file mode 100644
index 90e062a14..000000000
--- a/src/AliasVault.Api/Vault/RetentionRules/RevisionNumberConflictRetentionRule.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="RevisionNumberConflictRetentionRule.cs" company="lanedirt">
-// Copyright (c) lanedirt. All rights reserved.
-// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace AliasVault.Api.Vault.RetentionRules;
-
-using AliasServerDb;
-
-/// <summary>
-/// Revision number retention rule that keeps all vaults with the highest revision number.
-/// This is crucial for handling potential optimistic concurrency conflicts.
-/// </summary>
-public class RevisionNumberConflictRetentionRule : IRetentionRule
-{
- /// <inheritdoc cref="IRetentionRule.ApplyRule"/>
- public IEnumerable<Vault> ApplyRule(List<Vault> vaults, DateTime now)
- {
- var highestRevision = vaults.Max(v => v.RevisionNumber);
- return vaults.Where(v => v.RevisionNumber == highestRevision)
- .OrderByDescending(v => v.UpdatedAt);
- }
-}
diff --git a/src/AliasVault.Client/Main/Pages/Sync/Sync.razor b/src/AliasVault.Client/Main/Pages/Sync/Sync.razor
index 18cc75392..8a16179c8 100644
--- a/src/AliasVault.Client/Main/Pages/Sync/Sync.razor
+++ b/src/AliasVault.Client/Main/Pages/Sync/Sync.razor
@@ -90,6 +90,8 @@
await RedirectBackToReturnUrl();
}
+ Console.WriteLine("Database state changed: " + CurrentDbState.Status);
+
StateHasChanged();
}
diff --git a/src/AliasVault.Client/Services/Database/DbService.cs b/src/AliasVault.Client/Services/Database/DbService.cs
index 0589276ef..42ae84c58 100644
--- a/src/AliasVault.Client/Services/Database/DbService.cs
+++ b/src/AliasVault.Client/Services/Database/DbService.cs
@@ -100,7 +100,7 @@ public sealed class DbService : IDisposable
{
try
{
- var vaultsToMerge = await _httpClient.GetFromJsonAsync<VaultMergeResponse>("api/v1/Vault/merge");
+ var vaultsToMerge = await _httpClient.GetFromJsonAsync<VaultMergeResponse>($"api/v1/Vault/merge?currentRevisionNumber={_vaultRevisionNumber}");
if (vaultsToMerge == null || !vaultsToMerge.Vaults.Any())
{
// No vaults to merge found, set error state.
@@ -110,7 +110,7 @@ public sealed class DbService : IDisposable
var sqlConnections = new List<SqliteConnection>();
- // Decrypt and instantiate each vault as a separate in-memory SQLite database
+ // Decrypt and instantiate each vault as a separate in-memory SQLite database.
foreach (var vault in vaultsToMerge.Vaults)
{
var decryptedBase64String = await _jsInteropService.SymmetricDecrypt(vault.Blob, _authService.GetEncryptionKeyAsBase64Async());
@@ -120,54 +120,48 @@ public sealed class DbService : IDisposable
sqlConnections.Add(connection);
}
- // Use the first connection as the base
- var baseConnection = sqlConnections[0];
- sqlConnections.RemoveAt(0);
+ // Get all table names from the current base database.
+ var tables = await DbMergeUtility.GetTableNames(_sqlConnection);
- // Get all table names from the base database
- var tables = await DbMergeUtility.GetTableNames(baseConnection);
-
- // Disable foreign key checks on the base connection
- await using (var command = baseConnection.CreateCommand())
+ // Disable foreign key checks on the base connection.
+ await using (var command = _sqlConnection.CreateCommand())
{
command.CommandText = "PRAGMA foreign_keys = OFF;";
await command.ExecuteNonQueryAsync();
}
- // Merge each database into the base
+ // Merge each database into the base.
var i = 0;
foreach (var connection in sqlConnections)
{
i++;
foreach (var table in tables)
{
- await DbMergeUtility.MergeTable(baseConnection, connection, table);
+ await DbMergeUtility.MergeTable(_sqlConnection, connection, table);
}
}
- // Re-enable foreign key checks and verify integrity
- await using (var command = baseConnection.CreateCommand())
+ // Re-enable foreign key checks and verify integrity.
+ await using (var command = _sqlConnection.CreateCommand())
{
command.CommandText = "PRAGMA foreign_keys = ON;";
await command.ExecuteNonQueryAsync();
- // Verify foreign key integrity
+ // Verify foreign key integrity.
command.CommandText = "PRAGMA foreign_key_check;";
using var reader = await command.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
- // Foreign key violation detected
+ // Foreign key violation detected.
_state.UpdateState(DbServiceState.DatabaseStatus.MergeFailed, "Foreign key violation detected after merge.");
return false;
}
}
- // Set the merged database as the current database
- _sqlConnection.Close();
- _sqlConnection = baseConnection;
+ // Update the dbcontext with the new merged database.
_dbContext = new AliasClientDbContext(_sqlConnection, log => Console.WriteLine(log));
- // Clean up other connections
+ // Clean up other connections.
foreach (var connection in sqlConnections)
{
connection.Close();
@@ -175,6 +169,10 @@ public sealed class DbService : IDisposable
}
await _dbContext.Database.MigrateAsync();
+
+ // Update the current vault revision number to the highest revision number in the merged database(s).
+ // This is important so the server knows that the local client has successfully merged the databases
+ // and should overwrite the existing database on the server with the new merged database.
_vaultRevisionNumber = vaultsToMerge.Vaults.Max(v => v.CurrentRevisionNumber);
_isSuccessfullyInitialized = true;
@@ -253,11 +251,6 @@ public sealed class DbService : IDisposable
Console.WriteLine("Database successfully saved to server.");
_state.UpdateState(DbServiceState.DatabaseStatus.Ready);
}
- else
- {
- Console.WriteLine("Failed to save database to server.");
- _state.UpdateState(DbServiceState.DatabaseStatus.OperationError);
- }
}
/// <summary>
@@ -266,8 +259,6 @@ public sealed class DbService : IDisposable
/// <returns>Base64 encoded string that represents SQLite database.</returns>
public async Task<string> ExportSqliteToBase64Async()
{
- Console.WriteLine("Awaited database initialize...");
-
var tempFileName = Path.GetRandomFileName();
// Export SQLite memory database to a temp file.
@@ -568,7 +559,7 @@ public sealed class DbService : IDisposable
var response = await _httpClient.GetFromJsonAsync<VaultGetResponse>("api/v1/Vault");
if (response is not null)
{
- if (response.Status == VaultGetStatus.MergeRequired)
+ if (response.Status == VaultStatus.MergeRequired)
{
_state.UpdateState(DbServiceState.DatabaseStatus.MergeRequired);
return false;
@@ -635,7 +626,15 @@ public sealed class DbService : IDisposable
if (vaultUpdateResponse != null)
{
- // Update the revision number
+ // If the server responds with a merge required status, we need to merge the local database
+ // with the one on the server before we can continue.
+ if (vaultUpdateResponse.Status == VaultStatus.MergeRequired)
+ {
+ _state.UpdateState(DbServiceState.DatabaseStatus.MergeRequired);
+ await MergeDatabasesAsync();
+ return false;
+ }
+
_vaultRevisionNumber = vaultUpdateResponse.NewRevisionNumber;
return true;
}
diff --git a/src/AliasVault.Shared/Models/Enums/VaultGetStatus.cs b/src/AliasVault.Shared/Models/Enums/VaultStatus.cs
similarity index 70%
rename from src/AliasVault.Shared/Models/Enums/VaultGetStatus.cs
rename to src/AliasVault.Shared/Models/Enums/VaultStatus.cs
index 5ae120235..027e57b4b 100644
--- a/src/AliasVault.Shared/Models/Enums/VaultGetStatus.cs
+++ b/src/AliasVault.Shared/Models/Enums/VaultStatus.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="VaultGetStatus.cs" company="lanedirt">
+// <copyright file="VaultStatus.cs" company="lanedirt">
// Copyright (c) lanedirt. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
// </copyright>
@@ -8,17 +8,17 @@
namespace AliasVault.Shared.Models.Enums;
/// <summary>
-/// Enum representing the status of a vault get operation.
+/// Enum representing the status of a vault during get/update operations.
/// </summary>
-public enum VaultGetStatus
+public enum VaultStatus
{
/// <summary>
- /// The vault was retrieved successfully.
+ /// The vault was retrieved or updated successfully.
/// </summary>
Ok,
/// <summary>
- /// A client-side merge is required before the vault can be used.
+ /// A client-side merge is required before the vault can be retrieved or updated.
/// </summary>
MergeRequired,
}
diff --git a/src/AliasVault.Shared/Models/WebApi/Vault/VaultGetResponse.cs b/src/AliasVault.Shared/Models/WebApi/Vault/VaultGetResponse.cs
index f78b7f880..74b305850 100644
--- a/src/AliasVault.Shared/Models/WebApi/Vault/VaultGetResponse.cs
+++ b/src/AliasVault.Shared/Models/WebApi/Vault/VaultGetResponse.cs
@@ -17,7 +17,7 @@ public class VaultGetResponse
/// <summary>
/// Gets or sets the status of the vault get operation.
/// </summary>
- public VaultGetStatus Status { get; set; }
+ public VaultStatus Status { get; set; }
/// <summary>
/// Gets or sets the requested vault.
diff --git a/src/AliasVault.Shared/Models/WebApi/Vault/VaultUpdateResponse.cs b/src/AliasVault.Shared/Models/WebApi/Vault/VaultUpdateResponse.cs
index 907765d86..e01300fae 100644
--- a/src/AliasVault.Shared/Models/WebApi/Vault/VaultUpdateResponse.cs
+++ b/src/AliasVault.Shared/Models/WebApi/Vault/VaultUpdateResponse.cs
@@ -7,11 +7,18 @@
namespace AliasVault.Shared.Models.WebApi.Vault;
+using AliasVault.Shared.Models.Enums;
+
/// <summary>
/// Vault update response model.
/// </summary>
public class VaultUpdateResponse
{
+ /// <summary>
+ /// Gets or sets the status of the vault update operation.
+ /// </summary>
+ public required VaultStatus Status { get; set; }
+
/// <summary>
/// Gets or sets the current vault's revision number.
/// The server will increment this number with each change to the vault and is used for managing concurrency
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/DbSyncTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/DbSyncTests.cs
index e458c0f78..800230cd9 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/Client/DbSyncTests.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/DbSyncTests.cs
@@ -19,35 +19,87 @@ using Microsoft.EntityFrameworkCore;
public class DbSyncTests : ClientPlaywrightTest
{
/// <summary>
- /// Test if saving a new vault with the same revision number as an existing vault it results
- /// in two vaults with the same revision number in the server database.
+ /// Test that client side merge works correctly when two or more conflicting vault versions have been detected.
/// </summary>
/// <returns>Async task.</returns>
[Test]
[Order(1)]
- public async Task DbSyncDuplicateVersionNumberTest()
+ public async Task DbSyncClientMergeBasicTest()
+ {
+ var baselineVault = await CreateBaselineVault(async () =>
+ {
+ await CreateCredentialEntry(new Dictionary<string, string> { { "service-name", "TestBaseline" } });
+ });
+
+ var client1Vault = await SimulateClient(baselineVault, async () =>
+ {
+ await NavigateUsingBlazorRouter("credentials");
+ await WaitForUrlAsync("credentials", "Find all of your credentials");
+
+ await CreateCredentialEntry(new Dictionary<string, string> { { "service-name", "TestA" } });
+ });
+
+ await SimulateClient(baselineVault, async () =>
+ {
+ // Re-add client1 vault to simulate conflict when this second client updates the same vault.
+ client1Vault.Id = Guid.NewGuid();
+ ApiDbContext.Vaults.Add(client1Vault);
+ await ApiDbContext.SaveChangesAsync();
+
+ await NavigateUsingBlazorRouter("credentials");
+ await WaitForUrlAsync("credentials", "Find all of your credentials");
+
+ await CreateCredentialEntry(new Dictionary<string, string> { { "service-name", "TestB" } });
+ });
+
+ // Assert that the two conflicting vaults have been merged and all service names are found.
+ await NavigateUsingBlazorRouter("credentials");
+ await WaitForUrlAsync("credentials", "Find all of your credentials");
+
+ var pageContent = await Page.TextContentAsync("body");
+ var expectedServiceNames = new[] { "TestBaseline", "TestA", "TestB" };
+ foreach (var serviceName in expectedServiceNames)
+ {
+ Assert.That(pageContent, Does.Contain(serviceName), $"{serviceName} not found in vault after merge.");
+ }
+ }
+
+ /// <summary>
+ /// Create a baseline vault.
+ /// </summary>
+ /// <param name="clientActions">Optional client actions to execute after creating the baseline vault.</param>
+ /// <returns>The baseline vault.</returns>
+ private async Task<AliasServerDb.Vault> CreateBaselineVault(Func<Task> clientActions)
{
- // Advance time by 1 second manually to ensure the new vault is created in the future.
ApiTimeProvider.AdvanceBy(TimeSpan.FromSeconds(1));
+ await clientActions();
- // Create a new credential which will trigger a vault save to the server.
- await CreateCredentialEntry();
+ return await ApiDbContext.Vaults.OrderByDescending(x => x.UpdatedAt).FirstAsync();
+ }
- // Assert that the vault is stored in the database with revision number 1.
- var secondUpdateVault = await ApiDbContext.Vaults.OrderByDescending(x => x.UpdatedAt).FirstAsync();
- Assert.That(secondUpdateVault.RevisionNumber, Is.EqualTo(1), "Vault revision number is not 1 after the first credential save.");
+ /// <summary>
+ /// Simulate a client by removing all vaults and adding the baseline vault back.
+ /// </summary>
+ /// <param name="baselineVault">The baseline vault to add back.</param>
+ /// <param name="clientActions">Optional client actions to execute after simulating the client.</param>
+ /// <returns>The baseline vault.</returns>
+ private async Task<AliasServerDb.Vault> SimulateClient(AliasServerDb.Vault baselineVault, Func<Task> clientActions)
+ {
+ ApiTimeProvider.AdvanceBy(TimeSpan.FromSeconds(1));
- // Set the revision number of the vault to 2 (+1) to simulate a conflict where another client has
- // saved a vault with the same revision number.
- secondUpdateVault.RevisionNumber = 2;
+ // Remove all vaults and add the baseline vault back.
+ ApiDbContext.Vaults.RemoveRange(ApiDbContext.Vaults);
await ApiDbContext.SaveChangesAsync();
+ baselineVault.Id = Guid.NewGuid();
+ ApiDbContext.Vaults.Add(baselineVault);
+ await ApiDbContext.SaveChangesAsync();
+
+ // Simulate new client.
+ await RefreshPageAndUnlockVault();
- // Create a new credential. The client will provide revision number 1 as the previous one, which should result
- // in the server giving this new vault revision number 2 as well. Thus resulting in a conflict.
- await CreateCredentialEntry();
+ // Execute custom client actions.
+ await clientActions();
- // Assert that there are now two vaults in the database with revision number 2.
- var revisionNumber2VaultCount = await ApiDbContext.Vaults.CountAsync(x => x.RevisionNumber == 2);
- Assert.That(revisionNumber2VaultCount, Is.EqualTo(2), "Two vaults with revision number 2 not found in the database. Check if the server correctly handles conflicts when two clients save a vault with the same revision number.");
+ return await ApiDbContext.Vaults.OrderByDescending(x => x.UpdatedAt).FirstAsync();
}
}
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTests.cs
index 334b1129a..ad8eec680 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTests.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTests.cs
@@ -48,6 +48,7 @@ public class DbUpgradeTests : ClientPlaywrightTest
Id = Guid.NewGuid(),
UserId = ApiDbContext.AliasVaultUsers.First().Id,
Version = "1.0.0",
+ RevisionNumber = 0,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow,
EncryptionType = "Argon2Id",
diff --git a/src/Tests/AliasVault.UnitTests/Vault/RetentionManager/GeneralRetentionTests.cs b/src/Tests/AliasVault.UnitTests/Vault/RetentionManager/GeneralRetentionTests.cs
index 9858d5d71..f572e95fa 100644
--- a/src/Tests/AliasVault.UnitTests/Vault/RetentionManager/GeneralRetentionTests.cs
+++ b/src/Tests/AliasVault.UnitTests/Vault/RetentionManager/GeneralRetentionTests.cs
@@ -30,15 +30,15 @@ public class GeneralRetentionTests
now = new DateTime(2023, 6, 1, 12, 0, 0); // Set a fixed "now" date for testing: June 1, 2023, 12:00 PM
testVaults =
[
- new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty },
- new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 4, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty },
- new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 30, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty }, // 2 days ago
- new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 29, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty }, // 3 days ago
- new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 28, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty }, // 4 days ago
- new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 18, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty }, // 2 weeks ago
- new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 11, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty }, // 3 weeks ago
- new Vault { Version = "1.0.2", UpdatedAt = new DateTime(2023, 5, 1, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty }, // 1 month ago
- new Vault { Version = "1.0.1", UpdatedAt = new DateTime(2023, 4, 1, 12, 0, 0), Salt = "ghi", Verifier = "ghi", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty }, // 2 months ago
+ new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 },
+ new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 4, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 },
+ new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 30, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 }, // 2 days ago
+ new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 29, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 }, // 3 days ago
+ new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 28, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 }, // 4 days ago
+ new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 18, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 }, // 2 weeks ago
+ new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 11, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 }, // 3 weeks ago
+ new Vault { Version = "1.0.2", UpdatedAt = new DateTime(2023, 5, 1, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 }, // 1 month ago
+ new Vault { Version = "1.0.1", UpdatedAt = new DateTime(2023, 4, 1, 12, 0, 0), Salt = "ghi", Verifier = "ghi", VaultBlob = string.Empty, EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 0 }, // 2 months ago
];
}
@@ -203,6 +203,7 @@ public class GeneralRetentionTests
Verifier = string.Empty,
EncryptionType = string.Empty,
EncryptionSettings = string.Empty,
+ RevisionNumber = 0,
UpdatedAt = now,
};
diff --git a/src/Tests/AliasVault.UnitTests/Vault/RetentionManager/RevisionNumberRetentionTests.cs b/src/Tests/AliasVault.UnitTests/Vault/RetentionManager/RevisionNumberRetentionTests.cs
deleted file mode 100644
index e613818ea..000000000
--- a/src/Tests/AliasVault.UnitTests/Vault/RetentionManager/RevisionNumberRetentionTests.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="RevisionNumberRetentionTests.cs" company="lanedirt">
-// Copyright (c) lanedirt. All rights reserved.
-// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace AliasVault.Tests.Vault.RetentionManager;
-
-using AliasServerDb;
-using AliasVault.Api.Vault;
-using AliasVault.Api.Vault.RetentionRules;
-
-/// <summary>
-/// Contains unit tests for the retention behavior related to the RevisionNumber property of Vaults.
-/// These tests ensure that the retention policy correctly handles cases where multiple vaults
-/// have the same highest revision number, which could indicate optimistic concurrency conflicts.
-/// </summary>
-[TestFixture]
-public class RevisionNumberRetentionTests
-{
- private List<Vault> testVaults;
- private DateTime now;
-
- /// <summary>
- /// Sets up the test environment before each test.
- /// Creates a list of test vaults with various revision numbers and update times.
- /// </summary>
- [SetUp]
- public void Setup()
- {
- now = new DateTime(2023, 6, 1, 12, 0, 0);
- testVaults = new List<Vault>
- {
- new Vault { RevisionNumber = 5, UpdatedAt = new DateTime(2023, 5, 31, 12, 0, 0), VaultBlob = "blob1", Version = "1.0", Salt = "salt1", Verifier = "verifier1", EncryptionType = "type1", EncryptionSettings = "settings1" },
- new Vault { RevisionNumber = 5, UpdatedAt = new DateTime(2023, 5, 31, 11, 0, 0), VaultBlob = "blob2", Version = "1.0", Salt = "salt2", Verifier = "verifier2", EncryptionType = "type1", EncryptionSettings = "settings1" },
- new Vault { RevisionNumber = 5, UpdatedAt = new DateTime(2023, 5, 31, 10, 0, 0), VaultBlob = "blob3", Version = "1.0", Salt = "salt3", Verifier = "verifier3", EncryptionType = "type1", EncryptionSettings = "settings1" },
- new Vault { RevisionNumber = 4, UpdatedAt = new DateTime(2023, 5, 30, 12, 0, 0), VaultBlob = "blob4", Version = "1.0", Salt = "salt4", Verifier = "verifier4", EncryptionType = "type1", EncryptionSettings = "settings1" },
- new Vault { RevisionNumber = 3, UpdatedAt = new DateTime(2023, 5, 29, 12, 0, 0), VaultBlob = "blob5", Version = "1.0", Salt = "salt5", Verifier = "verifier5", EncryptionType = "type1", EncryptionSettings = "settings1" },
- };
- }
-
- /// <summary>
- /// Tests that the retention policy keeps all vaults with the highest revision number,
- /// even if there are multiple vaults with the same highest revision number.
- /// This is crucial for handling potential optimistic concurrency conflicts.
- /// </summary>
- [Test]
- public void RevisionNumberConflictRuleTest()
- {
- // Arrange
- var retentionPolicy = new RetentionPolicy
- {
- Rules = new List<IRetentionRule>
- {
- new RevisionNumberConflictRetentionRule(),
- new DailyRetentionRule { DaysToKeep = 1 },
- new VersionRetentionRule { VersionsToKeep = 1 },
- },
- };
-
- // Act
- var vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults, now).ToList();
- var vaultsToKeep = testVaults.Except(vaultsToDelete).ToList();
-
- // Assert
- Assert.Multiple(() =>
- {
- Assert.That(vaultsToKeep, Has.Count.EqualTo(3), "All vaults with the highest revision number should be kept");
- Assert.That(vaultsToKeep.All(v => v.RevisionNumber == 5), Is.True, "All kept vaults should have the highest revision number");
- Assert.That(vaultsToDelete, Has.Count.EqualTo(2), "Vaults with lower revision numbers should be deleted");
- Assert.That(vaultsToDelete.All(v => v.RevisionNumber < 5), Is.True, "All deleted vaults should have lower revision numbers");
- });
- }
-}