Skip to content

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

Add integration tests for TaskRunner (#221)

Leendert de Borst3c0905d0b03a
diff --git a/src/Tests/AliasVault.IntegrationTests/AliasVault.IntegrationTests.csproj b/src/Tests/AliasVault.IntegrationTests/AliasVault.IntegrationTests.csproj
index 919028678..759ed0011 100644
--- a/src/Tests/AliasVault.IntegrationTests/AliasVault.IntegrationTests.csproj
+++ b/src/Tests/AliasVault.IntegrationTests/AliasVault.IntegrationTests.csproj
@@ -44,6 +44,7 @@
<ItemGroup>
<ProjectReference Include="..\..\Services\AliasVault.SmtpService\AliasVault.SmtpService.csproj" />
+ <ProjectReference Include="..\..\Services\AliasVault.TaskRunner\AliasVault.TaskRunner.csproj" />
<ProjectReference Include="..\..\Utilities\Cryptography\AliasVault.Cryptography.Server\AliasVault.Cryptography.Server.csproj" />
</ItemGroup>
diff --git a/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
new file mode 100644
index 000000000..011f50d91
--- /dev/null
+++ b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
@@ -0,0 +1,265 @@
+//-----------------------------------------------------------------------
+// <copyright file="TaskRunnerTests.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.IntegrationTests.TaskRunner;
+
+using AliasServerDb;
+using AliasVault.Shared.Models.Enums;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Hosting;
+
+/// <summary>
+/// Integration tests for TaskRunner service.
+/// </summary>
+[TestFixture]
+public class TaskRunnerTests
+{
+ /// <summary>
+ /// The test host instance.
+ /// </summary>
+ private IHost _testHost;
+
+ /// <summary>
+ /// The test host builder instance.
+ /// </summary>
+ private TestHostBuilder _testHostBuilder;
+
+ /// <summary>
+ /// Setup logic for every test.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [SetUp]
+ public async Task Setup()
+ {
+ _testHostBuilder = new TestHostBuilder();
+ _testHost = _testHostBuilder.Build();
+
+ // Seed the database before starting the service.
+ await SeedDatabase();
+
+ // Start the service so it can run the tasks on the test data.
+ await _testHost.StartAsync();
+ }
+
+ /// <summary>
+ /// Tear down logic for every test.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [TearDown]
+ public async Task TearDown()
+ {
+ await _testHost.StopAsync();
+ _testHost.Dispose();
+ }
+
+ /// <summary>
+ /// Tests the EmailCleanup task.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task EmailCleanup()
+ {
+ // Assert
+ var dbContext = _testHostBuilder.GetDbContext();
+ var emails = await dbContext.Emails.ToListAsync();
+ Assert.That(emails.Count, Is.EqualTo(50));
+ }
+
+ /// <summary>
+ /// Tests the LogCleanup task.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task LogCleanup()
+ {
+ // Assert
+ var dbContext = _testHostBuilder.GetDbContext();
+
+ // Check general logs
+ var generalLogs = await dbContext.Logs.ToListAsync();
+ Assert.That(generalLogs.Count, Is.EqualTo(50), "Only recent general logs should remain");
+ }
+
+ /// <summary>
+ /// Tests the LogCleanup task.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task AuthLogCleanup()
+ {
+ // Assert
+ var dbContext = _testHostBuilder.GetDbContext();
+
+ // Check auth logs
+ var authLogs = await dbContext.AuthLogs.ToListAsync();
+ Assert.That(authLogs.Count, Is.EqualTo(50), "Only recent auth logs should remain");
+ }
+
+ /// <summary>
+ /// Seeds the database with test data.
+ /// </summary>
+ private async Task SeedDatabase()
+ {
+ // Seed the database with settings
+ var dbContext = _testHostBuilder.GetDbContext();
+
+ // Configure maintenance settings
+ var settings = new List<ServerSetting>
+ {
+ new() { Key = "EmailRetentionDays", Value = "30" },
+ new() { Key = "GeneralLogRetentionDays", Value = "45" },
+ new() { Key = "AuthLogRetentionDays", Value = "60" },
+ new() { Key = "MaxEmailsPerUser", Value = "100" },
+ new() { Key = "MaintenanceTime", Value = "03:30" },
+ new() { Key = "TaskRunnerDays", Value = "1,2,3,4,5,6,7" },
+ };
+
+ await dbContext.ServerSettings.AddRangeAsync(settings);
+
+ // Create test user
+ var user = new AliasVaultUser
+ {
+ UserName = "testuser",
+ Email = "[email protected]",
+ };
+ dbContext.AliasVaultUsers.Add(user);
+ await dbContext.SaveChangesAsync();
+
+ // Create encryption key for the user
+ var encryptionKey = new UserEncryptionKey
+ {
+ Id = Guid.NewGuid(),
+ UserId = user.Id,
+ PublicKey = "test-encryption-key",
+ CreatedAt = DateTime.UtcNow,
+ UpdatedAt = DateTime.UtcNow,
+ };
+ dbContext.UserEncryptionKeys.Add(encryptionKey);
+ await dbContext.SaveChangesAsync();
+
+ // Seed old emails (older than 30 days)
+ var oldEmails = new List<Email>();
+ for (int i = 0; i < 50; i++)
+ {
+ oldEmails.Add(new Email
+ {
+ Subject = $"Old Email {i}",
+ From = "[email protected]",
+ FromLocal = "sender",
+ FromDomain = "example.com",
+ ToLocal = "testuser",
+ ToDomain = "example.tld",
+ Date = DateTime.UtcNow.AddDays(-45),
+ DateSystem = DateTime.UtcNow.AddDays(-45),
+ MessagePlain = "Test message",
+ MessagePreview = "Test message",
+ MessageSource = "Test source",
+ EncryptedSymmetricKey = "dummy-key",
+ UserEncryptionKeyId = encryptionKey.Id,
+ });
+ }
+
+ await dbContext.Emails.AddRangeAsync(oldEmails);
+
+ // Seed recent emails (within 30 days)
+ var recentEmails = new List<Email>();
+ for (int i = 0; i < 50; i++)
+ {
+ recentEmails.Add(new Email
+ {
+ Subject = $"Recent Email {i}",
+ From = "[email protected]",
+ FromLocal = "sender",
+ FromDomain = "example.com",
+ ToLocal = "testuser",
+ ToDomain = "example.tld",
+ Date = DateTime.UtcNow.AddDays(-1),
+ DateSystem = DateTime.UtcNow.AddDays(-1),
+ MessagePlain = "Test message",
+ MessagePreview = "Test message",
+ MessageSource = "Test source",
+ EncryptedSymmetricKey = "dummy-key",
+ UserEncryptionKeyId = encryptionKey.Id,
+ });
+ }
+
+ await dbContext.Emails.AddRangeAsync(recentEmails);
+
+ // Add old general logs (older than 45 days)
+ var oldLogs = new List<Log>();
+ for (int i = 0; i < 50; i++)
+ {
+ oldLogs.Add(new Log
+ {
+ Application = "TestApp",
+ SourceContext = "TestContext",
+ Message = $"Old Log {i}",
+ MessageTemplate = $"Old Log {i}",
+ Level = "Information",
+ TimeStamp = DateTime.UtcNow.AddDays(-60),
+ Exception = string.Empty,
+ Properties = "{}",
+ LogEvent = "{}",
+ });
+ }
+
+ await dbContext.Logs.AddRangeAsync(oldLogs);
+
+ // Add recent logs (within 45 days)
+ var recentLogs = new List<Log>();
+ for (int i = 0; i < 50; i++)
+ {
+ recentLogs.Add(new Log
+ {
+ Application = "TestApp",
+ SourceContext = "TestContext",
+ Message = $"Recent Log {i}",
+ MessageTemplate = $"Recent Log {i}",
+ Level = "Information",
+ TimeStamp = DateTime.UtcNow.AddDays(-1),
+ Exception = string.Empty,
+ Properties = "{}",
+ LogEvent = "{}",
+ });
+ }
+
+ await dbContext.Logs.AddRangeAsync(recentLogs);
+
+ // Add old auth logs (older than 60 days)
+ var oldAuthLogs = new List<AuthLog>();
+ for (int i = 0; i < 50; i++)
+ {
+ oldAuthLogs.Add(new AuthLog
+ {
+ Username = "testuser",
+ EventType = AuthEventType.Login,
+ IsSuccess = true,
+ Timestamp = DateTime.UtcNow.AddDays(-70),
+ });
+ }
+
+ await dbContext.AuthLogs.AddRangeAsync(oldAuthLogs);
+
+ var recentAuthLogs = new List<AuthLog>();
+ for (int i = 0; i < 50; i++)
+ {
+ recentAuthLogs.Add(new AuthLog
+ {
+ Username = "testuser",
+ EventType = AuthEventType.Login,
+ IsSuccess = true,
+ Timestamp = DateTime.UtcNow.AddDays(-1),
+ });
+ }
+
+ await dbContext.AuthLogs.AddRangeAsync(recentAuthLogs);
+
+ await dbContext.SaveChangesAsync();
+ }
+}
diff --git a/src/Tests/AliasVault.IntegrationTests/TaskRunner/TestHostBuilder.cs b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TestHostBuilder.cs
new file mode 100644
index 000000000..50b231fea
--- /dev/null
+++ b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TestHostBuilder.cs
@@ -0,0 +1,97 @@
+//-----------------------------------------------------------------------
+// <copyright file="TestHostBuilder.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.IntegrationTests.TaskRunner;
+
+using System.Data.Common;
+using AliasServerDb;
+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.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+
+/// <summary>
+/// Builder class for creating a test host for the TaskRunner in order to run integration tests against it.
+/// </summary>
+public class TestHostBuilder
+{
+ /// <summary>
+ /// The DbConnection instance that is created for the test.
+ /// </summary>
+ private DbConnection? _dbConnection;
+
+ private AliasServerDbContext? _dbContext;
+
+ /// <summary>
+ /// Returns the DbContext instance for the test.
+ /// </summary>
+ /// <returns>AliasServerDbContext instance.</returns>
+ public AliasServerDbContext GetDbContext()
+ {
+ if (_dbContext == null)
+ {
+ var options = new DbContextOptionsBuilder<AliasServerDbContext>()
+ .UseSqlite(_dbConnection!)
+ .Options;
+
+ _dbContext = new AliasServerDbContext(options);
+ }
+
+ return _dbContext;
+ }
+
+ /// <summary>
+ /// Builds the TaskRunner test host.
+ /// </summary>
+ /// <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;
+
+ var builder = Host.CreateDefaultBuilder()
+ .ConfigureServices((context, services) =>
+ {
+ services.AddSingleton(new Config());
+ services.AddSingleton(_dbConnection);
+
+ services.AddDbContextFactory<AliasServerDbContext>((sp, options) =>
+ {
+ var connection = sp.GetRequiredService<DbConnection>();
+ options.UseSqlite(connection);
+ });
+
+ // Add server settings service
+ services.AddSingleton<ServerSettingsService>();
+
+ // Add maintenance tasks
+ services.AddTransient<IMaintenanceTask, LogCleanupTask>();
+ services.AddTransient<IMaintenanceTask, EmailCleanupTask>();
+ services.AddTransient<IMaintenanceTask, EmailQuotaCleanupTask>();
+
+ // Add the TaskRunner worker
+ services.AddHostedService<TaskRunnerWorker>();
+
+ // Ensure the in-memory database is populated with tables
+ var serviceProvider = services.BuildServiceProvider();
+ using (var scope = serviceProvider.CreateScope())
+ {
+ var dbContextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AliasServerDbContext>>();
+ var dbContext = dbContextFactory.CreateDbContext();
+ dbContext.Database.Migrate();
+ }
+ });
+
+ return builder.Build();
+ }
+}