Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Move SRP salt and verifier to vaults table (#200)
Leendert de Borst6e6f24417ac6
diff --git a/docs/architecture.md b/docs/architecture.mdnew file mode 100644index 000000000..33b329e8a--- /dev/null+++ b/docs/architecture.md@@ -0,0 +1,11 @@+# AliasVault architecture outline++TODO: create architecture outline document. Below are areas+to include.++## Document how SRP works:+- Zero-knowledge architecture+- Users master password is converted to byte[] via Argon2Id algorithm.+ - The user master password is used for both SRP (passwordless server authentication) and for symmetrically encrypting the vault.+- SRP salt and verifier are stored on server in Vaults table (before this was stored in users table). This is done because+ in case a vault is restored to a previous version the users login is also changed back to that previous version.diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.csindex 58c72376d..6493fd861 100644--- a/src/AliasVault.Api/Controllers/AuthController.cs+++ b/src/AliasVault.Api/Controllers/AuthController.cs@@ -95,13 +95,16 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn BadRequest(ServerValidationErrorResponse.Create(AccountLocked, 400));}+ // Retrieve latest vault of user which contains the current salt and verifier.+ var latestVaultSaltAndVerifier = GetUserLatestVaultSaltAndVerifier(user);+// Server creates ephemeral and sends to client- var ephemeral = Srp.GenerateEphemeralServer(user.Verifier);+ var ephemeral = Srp.GenerateEphemeralServer(latestVaultSaltAndVerifier.Verifier);// Store the server ephemeral in memory cache for Validate() endpoint to use.cache.Set(CachePrefixEphemeral + model.Username, ephemeral.Secret, TimeSpan.FromMinutes(5));- return Ok(new LoginInitiateResponse(user.Salt, ephemeral.Public));+ return Ok(new LoginInitiateResponse(latestVaultSaltAndVerifier.Salt, ephemeral.Public));}/// <summary>@@ -320,7 +323,27 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn BadRequest(ServerValidationErrorResponse.Create(["Username 'admin' is not allowed."], 400));}- var user = new AliasVaultUser { UserName = model.Username, Salt = model.Salt, Verifier = model.Verifier, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow };+ var user = new AliasVaultUser+ {+ UserName = model.Username,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,++ // TODO: delete salt and verifier from user table+ Salt = string.Empty,+ Verifier = string.Empty,+ };++ user.Vaults.Add(new AliasServerDb.Vault+ {+ VaultBlob = string.Empty,+ Version = "0.0.0",+ Salt = model.Salt,+ Verifier = model.Verifier,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ });+var result = await userManager.CreateAsync(user);if (result.Succeeded)@@ -353,13 +376,16 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn NotFound(ServerValidationErrorResponse.Create("User not found.", 404));}+ // Retrieve latest vault of user which contains the current salt and verifier.+ var latestVaultSaltAndVerifier = GetUserLatestVaultSaltAndVerifier(user);+// Server creates ephemeral and sends to client- var ephemeral = Srp.GenerateEphemeralServer(user.Verifier);+ var ephemeral = Srp.GenerateEphemeralServer(latestVaultSaltAndVerifier.Verifier);// Store the server ephemeral in memory cache for Validate() endpoint to use.cache.Set(CachePrefixEphemeral + user.UserName!, ephemeral.Secret, TimeSpan.FromMinutes(5));- return Ok(new PasswordChangeInitiateResponse(user.Salt, ephemeral.Public));+ return Ok(new PasswordChangeInitiateResponse(latestVaultSaltAndVerifier.Salt, ephemeral.Public));}/// <summary>@@ -495,21 +521,21 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn (null, null, BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400)));}- // Check if the account is locked out+ // Check if the account is locked out.if (await userManager.IsLockedOutAsync(user)){- await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);return (null, null, BadRequest(ServerValidationErrorResponse.Create(AccountLocked, 400)));}// Validate the SRP session (actual password check).- var serverSession = await ValidateSrpSession(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof);+ var serverSession = ValidateSrpSession(user, model.ClientPublicEphemeral, model.ClientSessionProof);if (serverSession is null){// Increment failed login attempts in order to lock out the account when the limit is reached.await userManager.AccessFailedAsync(user);- await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidPassword);+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, AuthFailureReason.InvalidPassword);return (null, null, BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400)));}@@ -519,29 +545,26 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac/// <summary>/// Helper method that validates the SRP session based on provided username, ephemeral and proof./// </summary>- /// <param name="username">The username.</param>+ /// <param name="user">The user object.</param>/// <param name="clientEphemeral">The client ephemeral value.</param>/// <param name="clientSessionProof">The client session proof.</param>/// <returns>Tuple.</returns>- private async Task<SrpSession?> ValidateSrpSession(string username, string clientEphemeral, string clientSessionProof)+ private SrpSession? ValidateSrpSession(AliasVaultUser user, string clientEphemeral, string clientSessionProof){- var user = await userManager.FindByNameAsync(username);- if (user == null)+ if (!cache.TryGetValue(CachePrefixEphemeral + user.UserName, out var serverSecretEphemeral) || serverSecretEphemeral is not string){return null;}- if (!cache.TryGetValue(CachePrefixEphemeral + username, out var serverSecretEphemeral) || serverSecretEphemeral is not string)- {- return null;- }+ // Retrieve latest vault of user which contains the current salt and verifier.+ var latestVaultSaltAndVerifier = GetUserLatestVaultSaltAndVerifier(user);var serverSession = Srp.DeriveSessionServer(serverSecretEphemeral.ToString() ?? string.Empty,clientEphemeral,- user.Salt,- username,- user.Verifier,+ latestVaultSaltAndVerifier.Salt,+ user.UserName ?? string.Empty,+ latestVaultSaltAndVerifier.Verifier,clientSessionProof);if (serverSession is null)@@ -615,4 +638,16 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn new TokenModel { Token = token, RefreshToken = refreshToken };}++ /// <summary>+ /// Get the user's latest vault which contains the current salt and verifier.+ /// </summary>+ /// <param name="user">User object.</param>+ /// <returns>Tuple with salt and verifier.</returns>+ private (string Salt, string Verifier) GetUserLatestVaultSaltAndVerifier(AliasVaultUser user)+ {+ // Retrieve latest vault of user which contains the current salt and verifier.+ var latestVault = user.Vaults.OrderByDescending(x => x.UpdatedAt).Select(x => new { x.Salt, x.Verifier }).First();+ return (latestVault.Salt, latestVault.Verifier);+ }}diff --git a/src/AliasVault.Api/Controllers/VaultController.cs b/src/AliasVault.Api/Controllers/VaultController.csindex 1ec730f60..a4975ee1c 100644--- a/src/AliasVault.Api/Controllers/VaultController.cs+++ b/src/AliasVault.Api/Controllers/VaultController.cs@@ -40,6 +40,7 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<new WeeklyRetentionRule { WeeksToKeep = 1 },new MonthlyRetentionRule { MonthsToKeep = 1 },new VersionRetentionRule { VersionsToKeep = 3 },+ new CredentialRetentionRule { CredentialsToKeep = 2 },],};@@ -90,13 +91,18 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<return Unauthorized();}- // Create new vault entry.+ // Retrieve latest vault of user which contains the current salt and verifier.+ var latestVault = user.Vaults.OrderByDescending(x => x.UpdatedAt).Select(x => new { x.Salt, x.Verifier }).First();++ // Create new vault entry with salt and verifier of current vault.var newVault = new Vault{UserId = user.Id,VaultBlob = model.Blob,Version = model.Version,FileSize = FileHelper.Base64StringToKilobytes(model.Blob),+ Salt = latestVault.Salt,+ Verifier = latestVault.Verifier,CreatedAt = timeProvider.UtcNow,UpdatedAt = timeProvider.UtcNow,};diff --git a/src/AliasVault.Api/Vault/RetentionRules/CredentialRetentionRule.cs b/src/AliasVault.Api/Vault/RetentionRules/CredentialRetentionRule.csnew file mode 100644index 000000000..8e9c0249a--- /dev/null+++ b/src/AliasVault.Api/Vault/RetentionRules/CredentialRetentionRule.cs@@ -0,0 +1,32 @@+//-----------------------------------------------------------------------+// <copyright file="CredentialRetentionRule.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>+/// Credential retention rule that keeps the latest X unique credentials and vaults associated with it.+/// </summary>+public class CredentialRetentionRule : IRetentionRule+{+ /// <summary>+ /// Gets or sets amount of unique credentials to keep including the vault.+ /// </summary>+ public int CredentialsToKeep { get; set; }++ /// <inheritdoc cref="IRetentionRule.ApplyRule"/>+ public IEnumerable<Vault> ApplyRule(List<Vault> vaults, DateTime now)+ {+ // For the specified amount of versions, take last vault per version.+ return vaults+ .GroupBy(x => new { x.Salt, x.Verifier })+ .Select(g => g.OrderByDescending(x => x.UpdatedAt).First())+ .OrderByDescending(x => x.UpdatedAt)+ .Take(CredentialsToKeep);+ }+}diff --git a/src/AliasVault.Client/Services/Database/DbService.cs b/src/AliasVault.Client/Services/Database/DbService.csindex 072b2b3d6..8351ad557 100644--- a/src/AliasVault.Client/Services/Database/DbService.cs+++ b/src/AliasVault.Client/Services/Database/DbService.cs@@ -114,27 +114,34 @@ public sealed class DbService : IDisposable}/// <summary>- /// Saves the database to the remote server.+ /// Generate encrypted base64 string representation of current state of database in order to save it+ /// to the server./// </summary>- /// <returns>Task.</returns>- public async Task SaveDatabaseAsync()+ /// <returns>Base64 encoded vault blob.</returns>+ public async Task<string> GetEncryptedDatabaseBase64String(){- // Set the initial state of the database service.- _state.UpdateState(DbServiceState.DatabaseStatus.SavingToServer);-- // Get the public encryption key that server requires to encrypt data they receive for current user.- var encryptionKey = await GetOrCreateEncryptionKeyAsync();-// Save the actual dbContext.await _dbContext.SaveChangesAsync();string base64String = await ExportSqliteToBase64Async();// SymmetricEncrypt base64 string using IJSInterop.- string encryptedBase64String = await _jsInteropService.SymmetricEncrypt(base64String, _authService.GetEncryptionKeyAsBase64Async());+ return await _jsInteropService.SymmetricEncrypt(base64String, _authService.GetEncryptionKeyAsBase64Async());+ }++ /// <summary>+ /// Saves the database to the remote server.+ /// </summary>+ /// <returns>Task.</returns>+ public async Task SaveDatabaseAsync()+ {+ // Set the initial state of the database service.+ _state.UpdateState(DbServiceState.DatabaseStatus.SavingToServer);++ var encryptedBase64String = await GetEncryptedDatabaseBase64String();// Save to webapi.- var success = await SaveToServerAsync(encryptionKey.PublicKey, encryptedBase64String);+ var success = await SaveToServerAsync(encryptedBase64String);if (success){Console.WriteLine("Database successfully saved to server.");@@ -470,11 +477,13 @@ public sealed class DbService : IDisposable/// <summary>/// Save encrypted database blob to server./// </summary>- /// <param name="publicEncryptionKey">RSA public key that server requires in order to encrypt data for user such as received emails.</param>/// <param name="encryptedDatabase">Encrypted database as string.</param>/// <returns>True if save action succeeded.</returns>- private async Task<bool> SaveToServerAsync(string publicEncryptionKey, string encryptedDatabase)+ private async Task<bool> SaveToServerAsync(string encryptedDatabase){+ // Get the public encryption key that server requires to encrypt data they receive for current user.+ var encryptionKey = await GetOrCreateEncryptionKeyAsync();+// Send list of email addresses that are used in aliases by this vault so they can be// claimed on the server.var emailAddresses = await _dbContext.Aliases@@ -490,7 +499,7 @@ public sealed class DbService : IDisposable.ToList();var databaseVersion = await GetCurrentDatabaseVersionAsync();- var vaultObject = new Vault(encryptedDatabase, databaseVersion, publicEncryptionKey, emailAddresses, DateTime.Now, DateTime.Now);+ var vaultObject = new Vault(encryptedDatabase, databaseVersion, encryptionKey.PublicKey, emailAddresses, DateTime.Now, DateTime.Now);try{diff --git a/src/Databases/AliasServerDb/Migrations/20240902134755_MoveSrpColsToVaultTable.Designer.cs b/src/Databases/AliasServerDb/Migrations/20240902134755_MoveSrpColsToVaultTable.Designer.csnew file mode 100644index 000000000..2093a95b5--- /dev/null+++ b/src/Databases/AliasServerDb/Migrations/20240902134755_MoveSrpColsToVaultTable.Designer.cs@@ -0,0 +1,813 @@+// <auto-generated />+using System;+using AliasServerDb;+using Microsoft.EntityFrameworkCore;+using Microsoft.EntityFrameworkCore.Infrastructure;+using Microsoft.EntityFrameworkCore.Migrations;+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;++#nullable disable++namespace AliasServerDb.Migrations+{+ [DbContext(typeof(AliasServerDbContext))]+ [Migration("20240902134755_MoveSrpColsToVaultTable")]+ partial class MoveSrpColsToVaultTable+ {+ /// <inheritdoc />+ protected override void BuildTargetModel(ModelBuilder modelBuilder)+ {+#pragma warning disable 612, 618+ modelBuilder+ .HasAnnotation("ProductVersion", "8.0.8")+ .HasAnnotation("Proxies:ChangeTracking", false)+ .HasAnnotation("Proxies:CheckEquality", false)+ .HasAnnotation("Proxies:LazyLoading", true);++ modelBuilder.Entity("AliasServerDb.AdminRole", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("TEXT");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("TEXT");++ b.Property<string>("Name")+ .HasColumnType("TEXT");++ b.Property<string>("NormalizedName")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("AdminRoles");+ });++ modelBuilder.Entity("AliasServerDb.AdminUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("TEXT");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("INTEGER");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("TEXT");++ b.Property<string>("Email")+ .HasColumnType("TEXT");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("INTEGER");++ b.Property<DateTime?>("LastPasswordChanged")+ .HasColumnType("TEXT");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("INTEGER");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("TEXT");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("TEXT");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("TEXT");++ b.Property<string>("PasswordHash")+ .HasColumnType("TEXT");++ b.Property<string>("PhoneNumber")+ .HasColumnType("TEXT");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("INTEGER");++ b.Property<string>("SecurityStamp")+ .HasColumnType("TEXT");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("INTEGER");++ b.Property<string>("UserName")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("AdminUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultRole", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("TEXT");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("TEXT");++ b.Property<string>("Name")+ .HasColumnType("TEXT");++ b.Property<string>("NormalizedName")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("AliasVaultRoles");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("TEXT");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("INTEGER");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("Email")+ .HasColumnType("TEXT");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("INTEGER");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("INTEGER");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("TEXT");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("TEXT");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("TEXT");++ b.Property<string>("PasswordHash")+ .HasColumnType("TEXT");++ b.Property<string>("PhoneNumber")+ .HasColumnType("TEXT");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("INTEGER");++ b.Property<string>("Salt")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("TEXT");++ b.Property<string>("SecurityStamp")+ .HasColumnType("TEXT");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("INTEGER");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("UserName")+ .HasColumnType("TEXT");++ b.Property<string>("Verifier")+ .IsRequired()+ .HasMaxLength(1000)+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("AliasVaultUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("DeviceIdentifier")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<DateTime>("ExpireDate")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("Value")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.ToTable("AliasVaultUserRefreshTokens");+ });++ modelBuilder.Entity("AliasServerDb.AuthLog", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("INTEGER");++ b.Property<string>("AdditionalInfo")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("Browser")+ .HasMaxLength(100)+ .HasColumnType("TEXT");++ b.Property<string>("Country")+ .HasMaxLength(50)+ .HasColumnType("TEXT");++ b.Property<string>("DeviceType")+ .HasMaxLength(100)+ .HasColumnType("TEXT");++ b.Property<int>("EventType")+ .HasColumnType("nvarchar(50)");++ b.Property<int?>("FailureReason")+ .HasColumnType("INTEGER");++ b.Property<string>("IpAddress")+ .HasMaxLength(50)+ .HasColumnType("TEXT");++ b.Property<bool>("IsSuccess")+ .HasColumnType("INTEGER");++ b.Property<bool>("IsSuspiciousActivity")+ .HasColumnType("INTEGER");++ b.Property<string>("OperatingSystem")+ .HasMaxLength(100)+ .HasColumnType("TEXT");++ b.Property<string>("RequestPath")+ .HasMaxLength(100)+ .HasColumnType("TEXT");++ b.Property<DateTime>("Timestamp")+ .HasColumnType("TEXT");++ b.Property<string>("UserAgent")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("Username")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex(new[] { "EventType" }, "IX_EventType");++ b.HasIndex(new[] { "IpAddress" }, "IX_IpAddress");++ b.HasIndex(new[] { "Timestamp" }, "IX_Timestamp");++ b.HasIndex(new[] { "Username", "IsSuccess", "Timestamp" }, "IX_Username_IsSuccess_Timestamp")+ .IsDescending(false, false, true);++ b.HasIndex(new[] { "Username", "Timestamp" }, "IX_Username_Timestamp")+ .IsDescending(false, true);++ b.ToTable("AuthLogs");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("INTEGER");++ b.Property<DateTime>("Date")+ .HasColumnType("TEXT");++ b.Property<DateTime>("DateSystem")+ .HasColumnType("TEXT");++ b.Property<string>("EncryptedSymmetricKey")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("From")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("FromDomain")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("FromLocal")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("MessageHtml")+ .HasColumnType("TEXT");++ b.Property<string>("MessagePlain")+ .HasColumnType("TEXT");++ b.Property<string>("MessagePreview")+ .HasColumnType("TEXT");++ b.Property<string>("MessageSource")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<bool>("PushNotificationSent")+ .HasColumnType("INTEGER");++ b.Property<string>("Subject")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("To")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("ToDomain")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("ToLocal")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<Guid>("UserEncryptionKeyId")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<bool>("Visible")+ .HasColumnType("INTEGER");++ b.HasKey("Id");++ b.HasIndex("Date");++ b.HasIndex("DateSystem");++ b.HasIndex("PushNotificationSent");++ b.HasIndex("ToLocal");++ b.HasIndex("UserEncryptionKeyId");++ b.HasIndex("Visible");++ b.ToTable("Emails");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("INTEGER");++ b.Property<byte[]>("Bytes")+ .IsRequired()+ .HasColumnType("BLOB");++ b.Property<DateTime>("Date")+ .HasColumnType("TEXT");++ b.Property<int>("EmailId")+ .HasColumnType("INTEGER");++ b.Property<string>("Filename")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<int>("Filesize")+ .HasColumnType("INTEGER");++ b.Property<string>("MimeType")+ .IsRequired()+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("EmailId");++ b.ToTable("EmailAttachments");+ });++ modelBuilder.Entity("AliasServerDb.Log", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("INTEGER");++ b.Property<string>("Application")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("TEXT");++ b.Property<string>("Exception")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("Level")+ .IsRequired()+ .HasMaxLength(128)+ .HasColumnType("TEXT");++ b.Property<string>("LogEvent")+ .IsRequired()+ .HasColumnType("TEXT")+ .HasColumnName("LogEvent");++ b.Property<string>("Message")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("MessageTemplate")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("Properties")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("SourceContext")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<DateTimeOffset>("TimeStamp")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("Application");++ b.HasIndex("TimeStamp");++ b.ToTable("Logs", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.UserEmailClaim", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<string>("Address")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("AddressDomain")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("AddressLocal")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("Address")+ .IsUnique();++ b.HasIndex("UserId");++ b.ToTable("UserEmailClaims");+ });++ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<bool>("IsPrimary")+ .HasColumnType("INTEGER");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("TEXT");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.ToTable("UserEncryptionKeys");+ });++ modelBuilder.Entity("AliasServerDb.Vault", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<int>("FileSize")+ .HasColumnType("INTEGER");++ b.Property<string>("Salt")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("TEXT");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("VaultBlob")+ .IsRequired()+ .HasColumnType("TEXT");++ b.Property<string>("Verifier")+ .IsRequired()+ .HasMaxLength(1000)+ .HasColumnType("TEXT");++ b.Property<string>("Version")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.ToTable("Vaults");+ });++ modelBuilder.Entity("AliasVault.WorkerStatus.Database.WorkerServiceStatus", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("INTEGER");++ b.Property<string>("CurrentStatus")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("TEXT");++ b.Property<string>("DesiredStatus")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("TEXT");++ b.Property<DateTime>("Heartbeat")+ .HasColumnType("TEXT");++ b.Property<string>("ServiceName")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("varchar");++ b.HasKey("Id");++ b.ToTable("WorkerServiceStatuses");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("INTEGER");++ b.Property<string>("FriendlyName")+ .HasColumnType("TEXT");++ b.Property<string>("Xml")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("DataProtectionKeys");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("INTEGER");++ b.Property<string>("ClaimType")+ .HasColumnType("TEXT");++ b.Property<string>("ClaimValue")+ .HasColumnType("TEXT");++ b.Property<string>("RoleId")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("RoleClaims", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("INTEGER");++ b.Property<string>("ClaimType")+ .HasColumnType("TEXT");++ b.Property<string>("ClaimValue")+ .HasColumnType("TEXT");++ b.Property<string>("UserId")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("UserClaims", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>+ {+ b.Property<string>("LoginProvider")+ .HasColumnType("TEXT");++ b.Property<string>("ProviderKey")+ .HasColumnType("TEXT");++ b.Property<string>("ProviderDisplayName")+ .HasColumnType("TEXT");++ b.Property<string>("UserId")+ .HasColumnType("TEXT");++ b.HasKey("LoginProvider", "ProviderKey");++ b.ToTable("UserLogins", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>+ {+ b.Property<string>("UserId")+ .HasColumnType("TEXT");++ b.Property<string>("RoleId")+ .HasColumnType("TEXT");++ b.HasKey("UserId", "RoleId");++ b.ToTable("UserRoles", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>+ {+ b.Property<string>("UserId")+ .HasColumnType("TEXT");++ b.Property<string>("LoginProvider")+ .HasColumnType("TEXT");++ b.Property<string>("Name")+ .HasColumnType("TEXT");++ b.Property<string>("Value")+ .HasColumnType("TEXT");++ b.HasKey("UserId", "LoginProvider", "Name");++ b.ToTable("UserTokens", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.HasOne("AliasServerDb.UserEncryptionKey", "EncryptionKey")+ .WithMany("Emails")+ .HasForeignKey("UserEncryptionKeyId")+ .OnDelete(DeleteBehavior.NoAction)+ .IsRequired();++ b.Navigation("EncryptionKey");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Attachments")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");+ });++ modelBuilder.Entity("AliasServerDb.UserEmailClaim", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("EmailClaims")+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("EncryptionKeys")+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.Vault", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("Vaults")+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Navigation("EmailClaims");++ b.Navigation("EncryptionKeys");++ b.Navigation("Vaults");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Navigation("Attachments");+ });++ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>+ {+ b.Navigation("Emails");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/src/Databases/AliasServerDb/Migrations/20240902134755_MoveSrpColsToVaultTable.cs b/src/Databases/AliasServerDb/Migrations/20240902134755_MoveSrpColsToVaultTable.csnew file mode 100644index 000000000..92d5bca06--- /dev/null+++ b/src/Databases/AliasServerDb/Migrations/20240902134755_MoveSrpColsToVaultTable.cs@@ -0,0 +1,66 @@+// <auto-generated />+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++namespace AliasServerDb.Migrations+{+ /// <inheritdoc />+ public partial class MoveSrpColsToVaultTable : Migration+ {+ /// <inheritdoc />+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.AddColumn<string>(+ name: "Salt",+ table: "Vaults",+ type: "TEXT",+ maxLength: 100,+ nullable: false,+ defaultValue: "");++ migrationBuilder.AddColumn<string>(+ name: "Verifier",+ table: "Vaults",+ type: "TEXT",+ maxLength: 1000,+ nullable: false,+ defaultValue: "");++ // Transfer data from AliasVaultUsers to Vaults+ migrationBuilder.Sql(@"+ UPDATE Vaults+ SET Salt = (SELECT Salt FROM AliasVaultUsers WHERE AliasVaultUsers.Id = Vaults.UserId),+ Verifier = (SELECT Verifier FROM AliasVaultUsers WHERE AliasVaultUsers.Id = Vaults.UserId)+ WHERE EXISTS (SELECT 1 FROM AliasVaultUsers WHERE AliasVaultUsers.Id = Vaults.UserId);+ ");++ // Create new vault entries for users without existing vaults+ migrationBuilder.Sql(@"+ INSERT INTO Vaults (UserId, VaultBlob, Version, Salt, Verifier, CreatedAt, UpdatedAt)+ SELECT+ Id,+ '',+ '0.0.0',+ Salt,+ Verifier,+ DATETIME('now'),+ DATETIME('now')+ FROM AliasVaultUsers+ WHERE Id NOT IN (SELECT DISTINCT UserId FROM Vaults);+ ");+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.DropColumn(+ name: "Salt",+ table: "Vaults");++ migrationBuilder.DropColumn(+ name: "Verifier",+ table: "Vaults");+ }+ }+}diff --git a/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex c215c2425..8b6aea37b 100644--- a/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -549,6 +549,11 @@ namespace AliasServerDb.Migrationsb.Property<int>("FileSize").HasColumnType("INTEGER");+ b.Property<string>("Salt")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("TEXT");+b.Property<DateTime>("UpdatedAt").HasColumnType("TEXT");@@ -561,6 +566,11 @@ namespace AliasServerDb.Migrations.IsRequired().HasColumnType("TEXT");+ b.Property<string>("Verifier")+ .IsRequired()+ .HasMaxLength(1000)+ .HasColumnType("TEXT");+b.Property<string>("Version").IsRequired().HasMaxLength(255)diff --git a/src/Databases/AliasServerDb/Vault.cs b/src/Databases/AliasServerDb/Vault.csindex b2f27f8aa..3bba5aa2c 100644--- a/src/Databases/AliasServerDb/Vault.cs+++ b/src/Databases/AliasServerDb/Vault.cs@@ -48,6 +48,24 @@ public class Vault/// </summary>public int FileSize { get; set; }+ /// <summary>+ /// Gets or sets the salt used for SRP authentication. Note: the login credentials are stored with the vault because+ /// the vault itself is encrypted with the same key derived from the user's password. So the password the user+ /// uses to log in to AliasVault needs to be the same as the vault to keep everything in-sync in case of vault+ /// backup restores.+ /// </summary>+ [StringLength(100)]+ public string Salt { get; set; } = null!;++ /// <summary>+ /// Gets or sets the verifier used for SRP authentication. Note: the login credentials are stored with the vault+ /// because the vault itself is encrypted with the same key derived from the user's password. So the password the+ /// user uses to log in to AliasVault needs to be the same as the vault to keep everything in-sync in case of vault+ /// backup restores.+ /// </summary>+ [StringLength(1000)]+ public string Verifier { get; set; } = null!;+/// <summary>/// Gets or sets created timestamp./// </summary>diff --git a/src/Tests/AliasVault.UnitTests/Vault/VaultRetentionManagerTests.cs b/src/Tests/AliasVault.UnitTests/Vault/VaultRetentionManagerTests.csindex f5d2d73d3..38b47a90b 100644--- a/src/Tests/AliasVault.UnitTests/Vault/VaultRetentionManagerTests.cs+++ b/src/Tests/AliasVault.UnitTests/Vault/VaultRetentionManagerTests.cs@@ -30,15 +30,15 @@ public class VaultRetentionManagerTestsnow = new DateTime(2023, 6, 1, 12, 0, 0); // Set a fixed "now" date for testing: June 1, 2023, 12:00 PMtestVaults =[- new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 12, 0, 0) },- new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 4, 0, 0) },- new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 30, 12, 0, 0) }, // 2 days ago- new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 29, 12, 0, 0) }, // 3 days ago- new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 28, 12, 0, 0) }, // 4 days ago- new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 18, 12, 0, 0) }, // 2 weeks ago- new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 11, 12, 0, 0) }, // 3 weeks ago- new Vault { Version = "1.0.2", UpdatedAt = new DateTime(2023, 5, 1, 12, 0, 0) }, // 1 month ago- new Vault { Version = "1.0.1", UpdatedAt = new DateTime(2023, 4, 1, 12, 0, 0) }, // 2 months ago+ new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 12, 0, 0), Salt = "abc", Verifier = "abc" },+ new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 4, 0, 0), Salt = "abc", Verifier = "abc" },+ new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 30, 12, 0, 0), Salt = "abc", Verifier = "abc" }, // 2 days ago+ new Vault { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 29, 12, 0, 0), Salt = "abc", Verifier = "abc" }, // 3 days ago+ new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 28, 12, 0, 0), Salt = "abc", Verifier = "abc" }, // 4 days ago+ new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 18, 12, 0, 0), Salt = "def", Verifier = "def" }, // 2 weeks ago+ new Vault { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 11, 12, 0, 0), Salt = "def", Verifier = "def" }, // 3 weeks ago+ new Vault { Version = "1.0.2", UpdatedAt = new DateTime(2023, 5, 1, 12, 0, 0), Salt = "def", Verifier = "def" }, // 1 month ago+ new Vault { Version = "1.0.1", UpdatedAt = new DateTime(2023, 4, 1, 12, 0, 0), Salt = "ghi", Verifier = "ghi" }, // 2 months ago];}@@ -118,6 +118,28 @@ public class VaultRetentionManagerTests});}+ /// <summary>+ /// Test the CredentialRetentionRule.+ /// </summary>+ [Test]+ public void CredentialRetentionRuleTest()+ {+ // Keep the latest 2 unique credentials.+ var rule = new CredentialRetentionRule { CredentialsToKeep = 2 };+ var result = rule.ApplyRule(testVaults, now).ToList();++ // Expecting two vaults to be kept:+ // - the latest+ // - the one from 2 weeks ago+ // The oldest vault should be excluded as that is the 3rd unique credential.+ Assert.Multiple(() =>+ {+ Assert.That(result, Has.Count.EqualTo(2));+ Assert.That(result[0].UpdatedAt, Is.EqualTo(new DateTime(2023, 5, 31, 12, 0, 0)));+ Assert.That(result[1].UpdatedAt, Is.EqualTo(new DateTime(2023, 5, 18, 12, 0, 0)));+ });+ }+/// <summary>/// Test the RetentionPolicy object./// </summary>