Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor smtpserver and taskrunner so all tests pass (#190)
Leendert de Borst78a872a67d5e
diff --git a/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs b/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.csindex 75fde18e0..9284bbf91 100644--- a/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs+++ b/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs@@ -35,7 +35,7 @@ public class TaskRunnerWorker({await using var dbContext = await dbContextFactory.CreateDbContextAsync(stoppingToken);var settings = await settingsService.GetAllSettingsAsync();- var now = DateTime.Now;+ var now = DateTime.UtcNow;var today = now.Date;// Check for on-demand run request@@ -95,7 +95,7 @@ public class TaskRunnerWorker(/// <param name="stoppingToken">The cancellation token.</param>private async Task ExecuteMaintenanceTasks(TaskRunnerJob job, AliasServerDbContext dbContext, CancellationToken stoppingToken){- logger.LogWarning("Starting maintenance tasks at {Time} (On-demand: {IsOnDemand})", DateTime.Now, job.IsOnDemand);+ logger.LogWarning("Starting maintenance tasks at {Time} (On-demand: {IsOnDemand})", DateTime.UtcNow, job.IsOnDemand);try{@@ -124,7 +124,7 @@ public class TaskRunnerWorker(}finally{- job.EndTime = TimeOnly.FromDateTime(DateTime.Now);+ job.EndTime = TimeOnly.FromDateTime(DateTime.UtcNow);await dbContext.SaveChangesAsync(stoppingToken);}diff --git a/src/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs b/src/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.csindex c00305141..5b5097671 100644--- a/src/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs+++ b/src/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs@@ -36,7 +36,7 @@ public class ServerSettingsService(IAliasServerDbContextFactory dbContextFactoryreturn cachedValue;}- await using var dbContext = dbContextFactory.CreateDbContext();+ await using var dbContext = await dbContextFactory.CreateDbContextAsync();var setting = await dbContext.ServerSettings.FirstOrDefaultAsync(x => x.Key == key);_cache[key] = setting?.Value;@@ -57,7 +57,7 @@ public class ServerSettingsService(IAliasServerDbContextFactory dbContextFactoryreturn;}- await using var dbContext = dbContextFactory.CreateDbContext();+ await using var dbContext = await dbContextFactory.CreateDbContextAsync();var setting = await dbContext.ServerSettings.FirstOrDefaultAsync(x => x.Key == key);var now = DateTime.UtcNow;@@ -96,7 +96,7 @@ public class ServerSettingsService(IAliasServerDbContextFactory dbContextFactory/// <returns>The settings.</returns>public async Task<ServerSettingsModel> GetAllSettingsAsync(){- await using var dbContext = dbContextFactory.CreateDbContext();+ await using var dbContext = await dbContextFactory.CreateDbContextAsync();var settings = await dbContext.ServerSettings.ToDictionaryAsync(x => x.Key, x => x.Value);// Create model with defaultsdiff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/Shard1/EmailDecryptionTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/Shard1/EmailDecryptionTests.csindex b3bd432da..4145ab0af 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/Shard1/EmailDecryptionTests.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/Shard1/EmailDecryptionTests.cs@@ -212,6 +212,7 @@ public class EmailDecryptionTests : ClientPlaywrightTest{await _testHost.StopAsync();_testHost.Dispose();+ await _testHostBuilder.DisposeAsync();}/// <summary>diff --git a/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs b/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.csindex 53ad2f620..54f5fc481 100644--- a/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs+++ b/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs@@ -105,6 +105,7 @@ public class SmtpServerTests{await _testHost.StopAsync();_testHost.Dispose();+ await _testHostBuilder.DisposeAsync();}/// <summary>diff --git a/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs b/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.csindex 54f561814..0525c0f5d 100644--- a/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs+++ b/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs@@ -9,46 +9,50 @@ namespace AliasVault.IntegrationTests.SmtpServer;using System.Data.Common;using AliasServerDb;+using AliasServerDb.Configuration;using AliasVault.SmtpService;using AliasVault.SmtpService.Handlers;using AliasVault.SmtpService.Workers;using global::SmtpServer;using global::SmtpServer.Storage;-using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;+using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;+using Npgsql;/// <summary>/// Builder class for creating a test host for the SmtpServiceWorker in order to run integration tests against it./// </summary>-public class TestHostBuilder+public class TestHostBuilder : IAsyncDisposable{/// <summary>- /// The DbConnection instance that is created for the test.+ /// The DbContextFactory instance that is created for the test./// </summary>- private DbConnection? _dbConnection;+ private IAliasServerDbContextFactory _dbContextFactory = null!;/// <summary>- /// The DbContext instance that is created for the test.+ /// The cached DbContext instance that can be used during the test./// </summary>private AliasServerDbContext? _dbContext;+ /// <summary>+ /// The temporary database name for the test.+ /// </summary>+ private string? _tempDbName;+/// <summary>/// Returns the DbContext instance for the test. This can be used to seed the database with test data./// </summary>/// <returns>AliasServerDbContext instance.</returns>public AliasServerDbContext GetDbContext(){- if (_dbContext == null)+ if (_dbContext != null){- var options = new DbContextOptionsBuilder<AliasServerDbContext>()- .UseSqlite(_dbConnection!)- .Options;-- _dbContext = new AliasServerDbContext(options);+ return _dbContext;}+ _dbContext = _dbContextFactory.CreateDbContext();return _dbContext;}@@ -58,40 +62,55 @@ public class TestHostBuilder/// <returns>IHost.</returns>public IHost Build(){- // Create a persistent in-memory database for the duration of the test.- var dbConnection = new SqliteConnection("DataSource=:memory:");- dbConnection.Open();+ _tempDbName = $"aliasdb_test_{Guid.NewGuid()}";++ // Create a connection to 'postgres' database to ensure the test database exists+ using (var conn = new NpgsqlConnection("Host=localhost;Port=5432;Database=postgres;Username=aliasvault;Password=password"))+ {+ conn.Open();+ using (var cmd = conn.CreateCommand())+ {+ cmd.CommandText = $"""+ CREATE DATABASE "{_tempDbName}";+ """;+ cmd.ExecuteNonQuery();+ }+ }++ // Create a connection to the new test database+ var dbConnection = new NpgsqlConnection($"Host=localhost;Port=5432;Database={_tempDbName};Username=aliasvault;Password=password");return Build(dbConnection);}- /// <summary>+ /// <summary>/// Builds the SmtpService test host with a provided database connection./// </summary>/// <param name="dbConnection">The database connection to use for the test.</param>/// <returns>IHost.</returns>public IHost Build(DbConnection dbConnection){- // Create a persistent in-memory database for the duration of the test.- _dbConnection = dbConnection;-var builder = Host.CreateDefaultBuilder().ConfigureServices((context, services) =>{+ // Override configuration+ var configuration = new ConfigurationBuilder()+ .AddJsonFile("appsettings.json", optional: true)+ .AddInMemoryCollection(new Dictionary<string, string?>+ {+ ["DatabaseProvider"] = "postgresql",+ ["ConnectionStrings:AliasServerDbContext"] = dbConnection.ConnectionString,+ })+ .Build();++ services.AddSingleton<IConfiguration>(configuration);+services.AddSingleton(new Config{AllowedToDomains = new List<string> { "example.tld" },SmtpTlsEnabled = "false",});- services.AddSingleton(_dbConnection);-- services.AddDbContextFactory<AliasServerDbContext>((sp, options) =>- {- var connection = sp.GetRequiredService<DbConnection>();- options.UseSqlite(connection);- });-services.AddTransient<IMessageStore, DatabaseMessageStore>();services.AddSingleton<SmtpServer>(provider =>@@ -112,18 +131,59 @@ public class TestHostBuilderreturn new SmtpServer(options.Build(), provider.GetRequiredService<IServiceProvider>());});+ services.AddAliasVaultDatabaseConfiguration(configuration);services.AddHostedService<SmtpServerWorker>();// Ensure the in-memory database is populated with tablesvar serviceProvider = services.BuildServiceProvider();using (var scope = serviceProvider.CreateScope()){- var dbContextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AliasServerDbContext>>();- var dbContext = dbContextFactory.CreateDbContext();+ _dbContextFactory = scope.ServiceProvider.GetRequiredService<IAliasServerDbContextFactory>();+ var dbContext = _dbContextFactory.CreateDbContext();dbContext.Database.Migrate();}});return builder.Build();}++ /// <summary>+ /// Disposes of the test host and cleans up the temporary database.+ /// </summary>+ /// <returns>A <see cref="ValueTask"/> representing the asynchronous operation.</returns>+ public async ValueTask DisposeAsync()+ {+ if (_dbContext != null)+ {+ await _dbContext.DisposeAsync();+ _dbContext = null;+ }++ if (!string.IsNullOrEmpty(_tempDbName))+ {+ // Create a connection to 'postgres' database to drop the test database+ using var conn = new NpgsqlConnection("Host=localhost;Port=5432;Database=postgres;Username=aliasvault;Password=password");+ await conn.OpenAsync();++ // First terminate existing connections+ using (var cmd = conn.CreateCommand())+ {+ cmd.CommandText = $"""+ SELECT pg_terminate_backend(pid)+ FROM pg_stat_activity+ WHERE datname = '{_tempDbName}';+ """;+ await cmd.ExecuteNonQueryAsync();+ }++ // Then drop the database+ using (var cmd = conn.CreateCommand())+ {+ cmd.CommandText = $"""+ DROP DATABASE IF EXISTS "{_tempDbName}";+ """;+ await cmd.ExecuteNonQueryAsync();+ }+ }+ }}diff --git a/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.csindex baec7b378..d703dd769 100644--- a/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs+++ b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs@@ -7,6 +7,7 @@namespace AliasVault.IntegrationTests.TaskRunner;+using AliasVault.Shared.Models.Enums;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Hosting;@@ -45,6 +46,7 @@ public class TaskRunnerTests{await _testHost.StopAsync();_testHost.Dispose();+ await _testHostBuilder.DisposeAsync();}/// <summary>@@ -58,7 +60,7 @@ public class TaskRunnerTestsawait InitializeWithTestData();// Assert- var dbContext = _testHostBuilder.GetDbContext();+ await using var dbContext = await _testHostBuilder.GetDbContextAsync();var emails = await dbContext.Emails.ToListAsync();Assert.That(emails, Has.Count.EqualTo(50));}@@ -74,7 +76,7 @@ public class TaskRunnerTestsawait InitializeWithTestData();// Assert- var dbContext = _testHostBuilder.GetDbContext();+ await using var dbContext = await _testHostBuilder.GetDbContextAsync();var generalLogs = await dbContext.Logs.ToListAsync();Assert.That(generalLogs, Has.Count.EqualTo(50), "Only recent general logs should remain");}@@ -90,7 +92,7 @@ public class TaskRunnerTestsawait InitializeWithTestData();// Assert- var dbContext = _testHostBuilder.GetDbContext();+ await using var dbContext = await _testHostBuilder.GetDbContextAsync();// Check auth logsvar authLogs = await dbContext.AuthLogs.ToListAsync();@@ -105,7 +107,8 @@ public class TaskRunnerTestspublic async Task MaintenanceTimeInFutureDoesNotRun(){// Seed database with generic test data.- await SeedData.SeedDatabase(_testHostBuilder.GetDbContext());+ await using var dbContext = await _testHostBuilder.GetDbContextAsync();+ await SeedData.SeedDatabase(dbContext);// Update maintenance time in database to future to ensure the task runner doesn't execute yet.@@ -120,7 +123,6 @@ public class TaskRunnerTests}// Update maintenance time in database- var dbContext = _testHostBuilder.GetDbContext();var maintenanceTimeSetting = await dbContext.ServerSettings.FirstAsync(s => s.Key == "MaintenanceTime");maintenanceTimeSetting.Value = futureTime.ToString("HH:mm");@@ -145,14 +147,13 @@ public class TaskRunnerTestspublic async Task MaintenanceTimeExcludedDayDoesNotRun(){// Seed database with generic test data.- await SeedData.SeedDatabase(_testHostBuilder.GetDbContext());+ await using var dbContext = await _testHostBuilder.GetDbContextAsync();+ await SeedData.SeedDatabase(dbContext);// Get current day of week (1-7, Monday = 1, Sunday = 7)var currentDay = (int)DateTime.Now.DayOfWeek + 1;// Update maintenance settings in database to exclude current day- var dbContext = _testHostBuilder.GetDbContext();-// Set maintenance time to midnightvar maintenanceTimeSetting = await dbContext.ServerSettings.FirstAsync(s => s.Key == "MaintenanceTime");@@ -185,7 +186,44 @@ public class TaskRunnerTests/// <returns>Task.</returns>protected async Task InitializeWithTestData(){- await SeedData.SeedDatabase(_testHostBuilder.GetDbContext());+ await using var dbContext = await _testHostBuilder.GetDbContextAsync();+ await SeedData.SeedDatabase(dbContext);await _testHost.StartAsync();++ // Wait for the maintenance job to complete instead of using a fixed delay+ await WaitForMaintenanceJobCompletion();+ }++ /// <summary>+ /// Waits for the maintenance job to complete.+ /// </summary>+ /// <param name="timeoutSeconds">The timeout in seconds.</param>+ /// <returns>Task.</returns>+ protected async Task WaitForMaintenanceJobCompletion(int timeoutSeconds = 10)+ {+ var startTime = DateTime.Now;+ var timeout = startTime.AddSeconds(timeoutSeconds);++ while (DateTime.Now < timeout)+ {+ await using var dbContext = await _testHostBuilder.GetDbContextAsync();+ var job = await dbContext.TaskRunnerJobs+ .OrderByDescending(j => j.Id)+ .FirstOrDefaultAsync();++ if (job != null && (job.Status == TaskRunnerJobStatus.Finished || job.Status == TaskRunnerJobStatus.Error))+ {+ if (job.Status == TaskRunnerJobStatus.Error)+ {+ Assert.Fail($"Maintenance job failed with error: {job.ErrorMessage}");+ }++ return;+ }++ await Task.Delay(500); // Poll every 500ms+ }++ Assert.Fail($"Maintenance job did not complete within {timeoutSeconds} seconds");}}diff --git a/src/Tests/AliasVault.IntegrationTests/TaskRunner/TestHostBuilder.cs b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TestHostBuilder.csindex 7bcad8ded..835c48d75 100644--- a/src/Tests/AliasVault.IntegrationTests/TaskRunner/TestHostBuilder.cs+++ b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TestHostBuilder.cs@@ -7,45 +7,44 @@namespace AliasVault.IntegrationTests.TaskRunner;-using System.Data.Common;using AliasServerDb;+using AliasServerDb.Configuration;using AliasVault.Shared.Server.Services;-using AliasVault.TaskRunner;using AliasVault.TaskRunner.Tasks;using AliasVault.TaskRunner.Workers;-using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;+using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;+using Npgsql;/// <summary>/// Builder class for creating a test host for the TaskRunner in order to run integration tests against it./// </summary>-public class TestHostBuilder+public class TestHostBuilder : IAsyncDisposable{/// <summary>- /// The DbConnection instance that is created for the test.+ /// The DbContextFactory instance that is created for the test./// </summary>- private DbConnection? _dbConnection;+ private IAliasServerDbContextFactory _dbContextFactory = null!;+ /// <summary>+ /// The cached DbContext instance that can be used during the test.+ /// </summary>private AliasServerDbContext? _dbContext;/// <summary>- /// Returns the DbContext instance for the test.+ /// The temporary database name for the test.+ /// </summary>+ private string? _tempDbName;++ /// <summary>+ /// Returns the DbContext instance for the test. This can be used to seed the database with test data./// </summary>/// <returns>AliasServerDbContext instance.</returns>- public AliasServerDbContext GetDbContext()+ public async Task<AliasServerDbContext> GetDbContextAsync(){- if (_dbContext == null)- {- var options = new DbContextOptionsBuilder<AliasServerDbContext>()- .UseSqlite(_dbConnection!)- .Options;-- _dbContext = new AliasServerDbContext(options);- }-- return _dbContext;+ return await _dbContextFactory.CreateDbContextAsync();}/// <summary>@@ -54,21 +53,37 @@ public class TestHostBuilder/// <returns>IHost.</returns>public IHost Build(){- // Create a persistent in-memory database for the duration of the test- var dbConnection = new SqliteConnection("DataSource=:memory:");- dbConnection.Open();- _dbConnection = dbConnection;+ // Create a temporary database for the test+ _tempDbName = $"aliasdb_test_{Guid.NewGuid()}";+ // Create a connection to 'postgres' database to create the test database+ using (var conn = new NpgsqlConnection("Host=localhost;Port=5432;Database=postgres;Username=aliasvault;Password=password"))+ {+ conn.Open();+ using (var cmd = conn.CreateCommand())+ {+ cmd.CommandText = $"""+ CREATE DATABASE "{_tempDbName}";+ """;+ cmd.ExecuteNonQuery();+ }+ }++ // Create the connection to the new test database+ var dbConnection = new NpgsqlConnection($"Host=localhost;Port=5432;Database={_tempDbName};Username=aliasvault;Password=password");var builder = Host.CreateDefaultBuilder().ConfigureServices((context, services) =>{- services.AddSingleton(_dbConnection);-- services.AddDbContextFactory<AliasServerDbContext>((sp, options) =>- {- var connection = sp.GetRequiredService<DbConnection>();- options.UseSqlite(connection);- });+ // Override configuration+ var configuration = new ConfigurationBuilder()+ .AddJsonFile("appsettings.json", optional: true)+ .AddInMemoryCollection(new Dictionary<string, string?>+ {+ ["DatabaseProvider"] = "postgresql",+ ["ConnectionStrings:AliasServerDbContext"] = dbConnection.ConnectionString,+ })+ .Build();+ services.AddSingleton<IConfiguration>(configuration);// Add server settings serviceservices.AddSingleton<ServerSettingsService>();@@ -78,19 +93,61 @@ public class TestHostBuilderservices.AddTransient<IMaintenanceTask, EmailCleanupTask>();services.AddTransient<IMaintenanceTask, EmailQuotaCleanupTask>();+ services.AddAliasVaultDatabaseConfiguration(configuration);+// Add the TaskRunner workerservices.AddHostedService<TaskRunnerWorker>();- // Ensure the in-memory database is populated with tables+ // Ensure the database is populated with tablesvar serviceProvider = services.BuildServiceProvider();using (var scope = serviceProvider.CreateScope()){- var dbContextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AliasServerDbContext>>();- var dbContext = dbContextFactory.CreateDbContext();+ _dbContextFactory = scope.ServiceProvider.GetRequiredService<IAliasServerDbContextFactory>();+ var dbContext = _dbContextFactory.CreateDbContext();dbContext.Database.Migrate();}});return builder.Build();}++ /// <summary>+ /// Disposes of the test host and cleans up the temporary database.+ /// </summary>+ /// <returns>A <see cref="ValueTask"/> representing the asynchronous operation.</returns>+ public async ValueTask DisposeAsync()+ {+ if (_dbContext != null)+ {+ await _dbContext.DisposeAsync();+ _dbContext = null;+ }++ if (!string.IsNullOrEmpty(_tempDbName))+ {+ // Create a connection to 'postgres' database to drop the test database+ using var conn = new NpgsqlConnection("Host=localhost;Port=5432;Database=postgres;Username=aliasvault;Password=password");+ await conn.OpenAsync();++ // First terminate existing connections+ using (var cmd = conn.CreateCommand())+ {+ cmd.CommandText = $"""+ SELECT pg_terminate_backend(pid)+ FROM pg_stat_activity+ WHERE datname = '{_tempDbName}';+ """;+ await cmd.ExecuteNonQueryAsync();+ }++ // Then drop the database+ using (var cmd = conn.CreateCommand())+ {+ cmd.CommandText = $"""+ DROP DATABASE IF EXISTS "{_tempDbName}";+ """;+ await cmd.ExecuteNonQueryAsync();+ }+ }+ }}