Skip to content

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

Add E2E test for API project and logging (#113)

Leendert de Borstad8ceff2a877
diff --git a/src/AliasVault.Admin/AliasVault.Admin.csproj b/src/AliasVault.Admin/AliasVault.Admin.csproj
index 137e4ff98..7b526ff63 100644
--- a/src/AliasVault.Admin/AliasVault.Admin.csproj
+++ b/src/AliasVault.Admin/AliasVault.Admin.csproj
@@ -40,6 +40,7 @@
<ItemGroup>
<ProjectReference Include="..\Databases\AliasServerDb\AliasServerDb.csproj" />
+ <ProjectReference Include="..\Utilities\AliasVault.Logging\AliasVault.Logging.csproj" />
<ProjectReference Include="..\Utilities\AliasVault.RazorComponents\AliasVault.RazorComponents.csproj" />
</ItemGroup>
diff --git a/src/AliasVault.Admin/Main/App.razor b/src/AliasVault.Admin/Main/App.razor
index 082694ee3..45749aa19 100644
--- a/src/AliasVault.Admin/Main/App.razor
+++ b/src/AliasVault.Admin/Main/App.razor
@@ -69,5 +69,4 @@
private IComponentRenderMode? RenderModeForPage => HttpContext.Request.Path.StartsWithSegments("/user")
? null
: InteractiveServer;
-
}
diff --git a/src/AliasVault.Admin/Program.cs b/src/AliasVault.Admin/Program.cs
index fd77719cd..ea991e1fc 100644
--- a/src/AliasVault.Admin/Program.cs
+++ b/src/AliasVault.Admin/Program.cs
@@ -7,11 +7,13 @@
using System.Data.Common;
using System.Globalization;
+using System.Reflection;
using AliasServerDb;
using AliasVault.Admin;
using AliasVault.Admin.Auth.Providers;
using AliasVault.Admin.Main;
using AliasVault.Admin.Services;
+using AliasVault.Logging;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Sqlite;
@@ -20,6 +22,7 @@ using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
+builder.Services.ConfigureLogging(builder.Configuration, Assembly.GetExecutingAssembly().GetName().Name!);
// Create global config object, get values from environment variables.
Config config = new Config();
@@ -96,11 +99,11 @@ if (app.Environment.IsDevelopment())
}
else
{
+ app.UseHttpsRedirection();
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
-app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
diff --git a/src/AliasVault.Api/AliasVault.Api.csproj b/src/AliasVault.Api/AliasVault.Api.csproj
index fde356662..e9b9a6d26 100644
--- a/src/AliasVault.Api/AliasVault.Api.csproj
+++ b/src/AliasVault.Api/AliasVault.Api.csproj
@@ -7,6 +7,7 @@
<RootNamespace>AliasVault.Api</RootNamespace>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
+ <DefineConstants Condition="'$(E2ETEST)' == 'true'">$(DefineConstants);E2ETEST</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
@@ -38,6 +39,7 @@
<ProjectReference Include="..\AliasGenerators\AliasGenerators.csproj" />
<ProjectReference Include="..\AliasVault.Shared\AliasVault.Shared.csproj" />
<ProjectReference Include="..\Databases\AliasServerDb\AliasServerDb.csproj" />
+ <ProjectReference Include="..\Utilities\AliasVault.Logging\AliasVault.Logging.csproj" />
<ProjectReference Include="..\Utilities\Cryptography\Cryptography.csproj" />
<ProjectReference Include="..\Utilities\FaviconExtractor\FaviconExtractor.csproj" />
</ItemGroup>
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.cs
index 44dd7cf90..4a7f4c59b 100644
--- a/src/AliasVault.Api/Controllers/AuthController.cs
+++ b/src/AliasVault.Api/Controllers/AuthController.cs
@@ -20,13 +20,14 @@ using Asp.Versioning;
using Cryptography.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Tokens;
/// <summary>
/// Auth controller for handling authentication.
/// </summary>
-/// <param name="context">AliasServerDbContext instance.</param>
+/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
/// <param name="userManager">UserManager instance.</param>
/// <param name="signInManager">SignInManager instance.</param>
/// <param name="configuration">IConfiguration instance.</param>
@@ -35,7 +36,7 @@ using Microsoft.IdentityModel.Tokens;
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
[ApiVersion("1")]
-public class AuthController(AliasServerDbContext context, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider) : ControllerBase
+public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider) : ControllerBase
{
/// <summary>
/// Error message for invalid email or password.
@@ -114,6 +115,8 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVault
[HttpPost("refresh")]
public async Task<IActionResult> Refresh([FromBody] TokenModel tokenModel)
{
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
var principal = GetPrincipalFromExpiredToken(tokenModel.Token);
if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
{
@@ -164,6 +167,8 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVault
[HttpPost("revoke")]
public async Task<IActionResult> Revoke([FromBody] TokenModel model)
{
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
var principal = GetPrincipalFromExpiredToken(model.Token);
if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
{
@@ -330,6 +335,8 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVault
/// <returns>TokenModel which includes new access and refresh token.</returns>
private async Task<TokenModel> GenerateNewTokensForUser(AliasVaultUser user)
{
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
var token = GenerateJwtToken(user);
var refreshToken = GenerateRefreshToken();
diff --git a/src/AliasVault.Api/Controllers/RootController.cs b/src/AliasVault.Api/Controllers/RootController.cs
index 968c0d8eb..955cd8806 100644
--- a/src/AliasVault.Api/Controllers/RootController.cs
+++ b/src/AliasVault.Api/Controllers/RootController.cs
@@ -16,7 +16,7 @@ using Microsoft.EntityFrameworkCore;
/// </summary>
[ApiController]
[Route("/")]
-public class RootController(AliasServerDbContext context) : ControllerBase
+public class RootController(IDbContextFactory<AliasServerDbContext> dbContextFactory) : ControllerBase
{
/// <summary>
/// Root endpoint that returns a 200 OK if the database connection is successful
@@ -26,8 +26,10 @@ public class RootController(AliasServerDbContext context) : ControllerBase
[HttpGet]
[ProducesResponseType<int>(StatusCodes.Status200OK)]
[ProducesResponseType<int>(StatusCodes.Status500InternalServerError)]
- public IActionResult Get()
+ public async Task<IActionResult> Get()
{
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
try
{
var appliedMigrations = context.Database.GetAppliedMigrations();
diff --git a/src/AliasVault.Api/Controllers/TestController.cs b/src/AliasVault.Api/Controllers/TestController.cs
index a4535b7d5..c80828c32 100644
--- a/src/AliasVault.Api/Controllers/TestController.cs
+++ b/src/AliasVault.Api/Controllers/TestController.cs
@@ -5,10 +5,17 @@
// </copyright>
//-----------------------------------------------------------------------
+/*
+ * Note: this file is used for E2E testing purposes only. It contains test endpoints that are called by pages on
+ * the client for testing purposes. Because certain endpoints that simulate exceptions are prone to Denial-Of-Service
+ * attack surfaces we don't include this file in the production build.
+ */
+
namespace AliasVault.Api.Controllers;
using AliasServerDb;
using Asp.Versioning;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
@@ -22,10 +29,22 @@ public class TestController(UserManager<AliasVaultUser> userManager) : Authentic
/// <summary>
/// Authenticated test request.
/// </summary>
- /// <returns>List of aliases in JSON format.</returns>
+ /// <returns>Static OK.</returns>
[HttpGet("")]
public IActionResult TestCall()
{
return Ok();
}
+
+ /// <summary>
+ /// Test request that throws an exception. Used for testing error handling.
+ /// </summary>
+ /// <returns>Static OK.</returns>
+ [AllowAnonymous]
+ [HttpGet("Error")]
+ public IActionResult TestCallError()
+ {
+ // Throw an exception here to test error handling.
+ throw new Exception("Test error");
+ }
}
diff --git a/src/AliasVault.Api/Controllers/VaultController.cs b/src/AliasVault.Api/Controllers/VaultController.cs
index 607e12b7b..89b82d526 100644
--- a/src/AliasVault.Api/Controllers/VaultController.cs
+++ b/src/AliasVault.Api/Controllers/VaultController.cs
@@ -19,11 +19,11 @@ using Microsoft.EntityFrameworkCore;
/// <summary>
/// Vault controller for handling CRUD operations on the database for encrypted vault entities.
/// </summary>
-/// <param name="context">DbContext instance.</param>
+/// <param name="dbContextFactory">DbContext instance.</param>
/// <param name="userManager">UserManager instance.</param>
/// <param name="timeProvider">ITimeProvider instance.</param>
[ApiVersion("1")]
-public class VaultController(AliasServerDbContext context, UserManager<AliasVaultUser> userManager, ITimeProvider timeProvider) : AuthenticatedRequestController(userManager)
+public class VaultController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager, ITimeProvider timeProvider) : AuthenticatedRequestController(userManager)
{
/// <summary>
/// Default retention policy for vaults.
@@ -46,6 +46,8 @@ public class VaultController(AliasServerDbContext context, UserManager<AliasVaul
[HttpGet("")]
public async Task<IActionResult> GetVault()
{
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
var user = await GetCurrentUserAsync();
if (user == null)
{
@@ -76,6 +78,8 @@ public class VaultController(AliasServerDbContext context, UserManager<AliasVaul
[HttpPost("")]
public async Task<IActionResult> Update([FromBody] Shared.Models.WebApi.Vault model)
{
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
var user = await GetCurrentUserAsync();
if (user == null)
{
diff --git a/src/AliasVault.Api/Program.cs b/src/AliasVault.Api/Program.cs
index dda7f78ae..73c88d179 100644
--- a/src/AliasVault.Api/Program.cs
+++ b/src/AliasVault.Api/Program.cs
@@ -6,9 +6,11 @@
//-----------------------------------------------------------------------
using System.Data.Common;
+using System.Reflection;
using System.Text;
using AliasServerDb;
using AliasVault.Api.Jwt;
+using AliasVault.Logging;
using AliasVault.Shared.Providers.Time;
using Asp.Versioning;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@@ -21,6 +23,7 @@ using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
+builder.Services.ConfigureLogging(builder.Configuration, Assembly.GetExecutingAssembly().GetName().Name!);
builder.Services.AddSingleton<ITimeProvider, SystemTimeProvider>();
builder.Services.AddScoped<TimeValidationJwtBearerEvents>();
@@ -41,7 +44,7 @@ builder.Services.AddSingleton<DbConnection>(container =>
return connection;
});
-builder.Services.AddDbContext<AliasServerDbContext>((container, options) =>
+builder.Services.AddDbContextFactory<AliasServerDbContext>((container, options) =>
{
var connection = container.GetRequiredService<DbConnection>();
options.UseSqlite(connection).UseLazyLoadingProxies();
@@ -163,8 +166,11 @@ if (app.Environment.IsDevelopment())
app.UseSwagger();
app.UseSwaggerUI();
}
+else
+{
+ app.UseHttpsRedirection();
+}
-app.UseHttpsRedirection();
app.UseCors("CorsPolicy");
app.UseAuthentication();
@@ -175,7 +181,7 @@ app.MapControllers();
using (var scope = app.Services.CreateScope())
{
var container = scope.ServiceProvider;
- var db = container.GetRequiredService<AliasServerDbContext>();
+ var db = container.GetRequiredService<IDbContextFactory<AliasServerDbContext>>().CreateDbContext();
await db.Database.MigrateAsync();
}
diff --git a/src/AliasVault.Api/appsettings.Development.json b/src/AliasVault.Api/appsettings.Development.json
index 43b43db8a..42ef3acff 100644
--- a/src/AliasVault.Api/appsettings.Development.json
+++ b/src/AliasVault.Api/appsettings.Development.json
@@ -1,8 +1,9 @@
{
- "Logging": {
- "LogLevel": {
- "Default": "Debug",
- "Microsoft.AspNetCore": "Debug"
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.Hosting.Lifetime": "Information",
+ "Microsoft.EntityFrameworkCore": "Warning"
+ }
}
- }
}
diff --git a/src/AliasVault.Api/appsettings.json b/src/AliasVault.Api/appsettings.json
index b1e8ed26e..102d3665a 100644
--- a/src/AliasVault.Api/appsettings.json
+++ b/src/AliasVault.Api/appsettings.json
@@ -1,8 +1,9 @@
{
"Logging": {
"LogLevel": {
- "Default": "Information",
- "Microsoft.AspNetCore": "Warning"
+ "Default": "Warning",
+ "Microsoft.Hosting.Lifetime": "Information",
+ "Microsoft.EntityFrameworkCore": "Warning"
}
},
"Jwt": {
diff --git a/src/Services/AliasVault.SmtpService/Program.cs b/src/Services/AliasVault.SmtpService/Program.cs
index d43270646..eb12bd6a5 100644
--- a/src/Services/AliasVault.SmtpService/Program.cs
+++ b/src/Services/AliasVault.SmtpService/Program.cs
@@ -50,7 +50,6 @@ builder.Services.AddDbContextFactory<AliasServerDbContext>((container, options)
});
builder.Services.AddTransient<IMessageStore, DatabaseMessageStore>();
-
builder.Services.AddSingleton(
provider =>
{
diff --git a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
index 6012233c7..f0d5ce876 100644
--- a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
+++ b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
@@ -12,11 +12,13 @@
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<DocumentationFile>bin\Debug\net8.0\AliasVault.E2ETests.xml</DocumentationFile>
+ <DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<DocumentationFile>bin\Release\net8.0\AliasVault.E2ETests.xml</DocumentationFile>
+ <DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
diff --git a/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs
index 41217550c..b848e22c6 100644
--- a/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs
@@ -39,6 +39,11 @@ public class ClientPlaywrightTest : PlaywrightTest
/// </summary>
protected AliasServerDbContext ApiDbContext => _apiFactory.GetDbContext();
+ /// <summary>
+ /// Gets or sets the base URL where the WebAPI project runs on including random port.
+ /// </summary>
+ protected string ApiBaseUrl { get; set; } = string.Empty;
+
/// <summary>
/// Tear down the Playwright test which runs after all tests are done in the class.
/// </summary>
@@ -71,6 +76,7 @@ public class ClientPlaywrightTest : PlaywrightTest
}
AppBaseUrl = "http://localhost:" + appPort + "/";
+ ApiBaseUrl = "http://localhost:" + apiPort + "/";
// Start WebAPI in-memory.
_apiFactory.HostUrl = "http://localhost:" + apiPort;
@@ -89,7 +95,7 @@ public class ClientPlaywrightTest : PlaywrightTest
{
var response = new
{
- ApiUrl = "http://localhost:" + apiPort,
+ ApiUrl = ApiBaseUrl.TrimEnd('/'),
};
await route.FulfillAsync(
new RouteFulfillOptions
@@ -104,7 +110,7 @@ public class ClientPlaywrightTest : PlaywrightTest
{
var response = new
{
- ApiUrl = "http://localhost:" + apiPort,
+ ApiUrl = ApiBaseUrl.TrimEnd('/'),
};
await route.FulfillAsync(
new RouteFulfillOptions
diff --git a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs
index 7467b23a6..35b518e2b 100644
--- a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs
+++ b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs
@@ -13,7 +13,6 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
@@ -27,13 +26,27 @@ public class WebApplicationAdminFactoryFixture<TEntryPoint> : WebApplicationFact
/// <summary>
/// The DbConnection instance that is created for the test.
/// </summary>
- private DbConnection? _dbConnection;
+ private DbConnection _dbConnection;
/// <summary>
- /// The DbContext instance that is created for the test.
+ /// The DbContextFactory instance that is created for the test.
+ /// </summary>
+ private IDbContextFactory<AliasServerDbContext> _dbContextFactory = null!;
+
+ /// <summary>
+ /// The cached DbContext instance that can be used during the test.
/// </summary>
private AliasServerDbContext? _dbContext;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebApplicationAdminFactoryFixture{TEntryPoint}"/> class.
+ /// </summary>
+ public WebApplicationAdminFactoryFixture()
+ {
+ _dbConnection = new SqliteConnection("DataSource=:memory:");
+ _dbConnection.Open();
+ }
+
/// <summary>
/// Gets or sets the URL the web application host will listen on.
/// </summary>
@@ -45,18 +58,25 @@ public class WebApplicationAdminFactoryFixture<TEntryPoint> : WebApplicationFact
/// <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;
}
+ /// <summary>
+ /// Disposes the DbConnection instance.
+ /// </summary>
+ /// <returns>ValueTask.</returns>
+ public override ValueTask DisposeAsync()
+ {
+ _dbConnection.Dispose();
+ return base.DisposeAsync();
+ }
+
/// <inheritdoc />
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
@@ -70,63 +90,28 @@ public class WebApplicationAdminFactoryFixture<TEntryPoint> : WebApplicationFact
builder.ConfigureServices((context, services) =>
{
- // Remove the existing AliasServerDbContext registration.
- var dbContextDescriptor = services.SingleOrDefault(
- d => d.ServiceType ==
- typeof(DbContextOptions<AliasServerDbContext>));
-
- if (dbContextDescriptor is null)
- {
- throw new InvalidOperationException(
- "No DbContextOptions<AliasServerDbContext> registered.");
- }
-
- services.Remove(dbContextDescriptor);
-
- // Remove the existing AliasServerDbContextFactory registration.
+ // Remove the existing DbContextFactory registration
var dbContextFactoryDescriptor = services.SingleOrDefault(
- d => d.ServiceType ==
- typeof(IDbContextFactory<AliasServerDbContext>));
+ d => d.ServiceType == typeof(IDbContextFactory<AliasServerDbContext>));
- if (dbContextFactoryDescriptor is null)
- {
- throw new InvalidOperationException(
- "No IDbContextFactory<AliasServerDbContext> registered.");
- }
-
- services.Remove(dbContextFactoryDescriptor);
+ services.Remove(dbContextFactoryDescriptor ?? throw new InvalidOperationException("No IDbContextFactory<AliasServerDbContext> registered."));
// Remove the existing DbConnection registration.
var dbConnectionDescriptor = services.SingleOrDefault(
- d => d.ServiceType ==
- typeof(DbConnection));
+ d => d.ServiceType == typeof(DbConnection));
- if (dbConnectionDescriptor is null)
- {
- throw new InvalidOperationException(
- "No DbContextOptions<AliasServerDbContext> registered.");
- }
+ services.Remove(dbConnectionDescriptor ?? throw new InvalidOperationException("No DbContextOptions<AliasServerDbContext> registered."));
- services.Remove(dbConnectionDescriptor);
+ // Add the DbConnection as a singleton
+ services.AddSingleton(_dbConnection);
- // Create a new DbConnection and AliasServerDbContext with an in-memory database.
- services.AddSingleton<DbConnection>(container =>
- {
- _dbConnection = new SqliteConnection("DataSource=:memory:");
- _dbConnection.Open();
-
- return _dbConnection;
- });
-
- services.AddDbContext<AliasServerDbContext>((container, options) =>
+ // Add the DbContextFactory
+ services.AddDbContextFactory<AliasServerDbContext>((container, options) =>
{
var connection = container.GetRequiredService<DbConnection>();
- options.UseSqlite(connection);
+ options.UseSqlite(connection).UseLazyLoadingProxies();
});
- // Add the IDbContextFactory<AliasServerDbContext> as a scoped service
- services.AddScoped<IDbContextFactory<AliasServerDbContext>, PooledDbContextFactory<AliasServerDbContext>>();
-
// Enable detailed errors for server-side Blazor.
services.AddServerSideBlazor()
.AddCircuitOptions(options =>
@@ -146,6 +131,9 @@ public class WebApplicationAdminFactoryFixture<TEntryPoint> : WebApplicationFact
var host = builder.Build();
host.Start();
+ // Get the DbContextFactory instance and store it for later use during tests.
+ _dbContextFactory = host.Services.GetRequiredService<IDbContextFactory<AliasServerDbContext>>();
+
// This delay prevents "ERR_CONNECTION_REFUSED" errors
// which happened like 1 out of 10 times when running tests.
Thread.Sleep(100);
diff --git a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs
index 5b2ef995e..3aa2d73dc 100644
--- a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs
+++ b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs
@@ -27,13 +27,27 @@ public class WebApplicationApiFactoryFixture<TEntryPoint> : WebApplicationFactor
/// <summary>
/// The DbConnection instance that is created for the test.
/// </summary>
- private DbConnection? _dbConnection;
+ private DbConnection _dbConnection;
/// <summary>
- /// The DbContext instance that is created for the test.
+ /// The DbContextFactory instance that is created for the test.
+ /// </summary>
+ private IDbContextFactory<AliasServerDbContext> _dbContextFactory = null!;
+
+ /// <summary>
+ /// The cached DbContext instance that can be used during the test.
/// </summary>
private AliasServerDbContext? _dbContext;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebApplicationApiFactoryFixture{TEntryPoint}"/> class.
+ /// </summary>
+ public WebApplicationApiFactoryFixture()
+ {
+ _dbConnection = new SqliteConnection("DataSource=:memory:");
+ _dbConnection.Open();
+ }
+
/// <summary>
/// Gets or sets the URL the web application host will listen on.
/// </summary>
@@ -50,18 +64,25 @@ public class WebApplicationApiFactoryFixture<TEntryPoint> : WebApplicationFactor
/// <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;
}
+ /// <summary>
+ /// Disposes the DbConnection instance.
+ /// </summary>
+ /// <returns>ValueTask.</returns>
+ public override ValueTask DisposeAsync()
+ {
+ _dbConnection.Dispose();
+ return base.DisposeAsync();
+ }
+
/// <inheritdoc />
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
@@ -72,61 +93,36 @@ public class WebApplicationApiFactoryFixture<TEntryPoint> : WebApplicationFactor
builder.ConfigureServices((context, services) =>
{
- // Replace the ITimeProvider registration with a TestTimeProvider.
+ // Remove the existing DbContextFactory registration
var timeProviderDescriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(ITimeProvider));
- if (timeProviderDescriptor is null)
- {
- throw new InvalidOperationException(
- "No ITimeProvider registered.");
- }
-
- services.Remove(timeProviderDescriptor);
-
- // Add TestTimeProvider
- services.AddSingleton<ITimeProvider>(TimeProvider);
-
- // Remove the existing AliasServerDbContext registration.
- var dbContextDescriptor = services.SingleOrDefault(
- d => d.ServiceType ==
- typeof(DbContextOptions<AliasServerDbContext>));
+ services.Remove(timeProviderDescriptor ?? throw new InvalidOperationException("No ITimeProvider registered."));
- if (dbContextDescriptor is null)
- {
- throw new InvalidOperationException(
- "No DbContextOptions<AliasServerDbContext> registered.");
- }
+ // Remove the existing DbContextFactory registration
+ var dbContextFactoryDescriptor = services.SingleOrDefault(
+ d => d.ServiceType == typeof(IDbContextFactory<AliasServerDbContext>));
- services.Remove(dbContextDescriptor);
+ services.Remove(dbContextFactoryDescriptor ?? throw new InvalidOperationException("No IDbContextFactory<AliasServerDbContext> registered."));
// Remove the existing DbConnection registration.
var dbConnectionDescriptor = services.SingleOrDefault(
- d => d.ServiceType ==
- typeof(DbConnection));
+ d => d.ServiceType == typeof(DbConnection));
- if (dbConnectionDescriptor is null)
- {
- throw new InvalidOperationException(
- "No DbContextOptions<AliasServerDbContext> registered.");
- }
+ services.Remove(dbConnectionDescriptor ?? throw new InvalidOperationException("No DbContextOptions<AliasServerDbContext> registered."));
- services.Remove(dbConnectionDescriptor);
+ // Add the DbConnection as a singleton
+ services.AddSingleton(_dbConnection);
- // Create a new DbConnection and AliasServerDbContext with an in-memory database.
- services.AddSingleton<DbConnection>(container =>
- {
- _dbConnection = new SqliteConnection("DataSource=:memory:");
- _dbConnection.Open();
-
- return _dbConnection;
- });
-
- services.AddDbContext<AliasServerDbContext>((container, options) =>
+ // Add the DbContextFactory
+ services.AddDbContextFactory<AliasServerDbContext>((container, options) =>
{
var connection = container.GetRequiredService<DbConnection>();
- options.UseSqlite(connection);
+ options.UseSqlite(connection).UseLazyLoadingProxies();
});
+
+ // Add TestTimeProvider
+ services.AddSingleton<ITimeProvider>(TimeProvider);
});
}
@@ -140,6 +136,9 @@ public class WebApplicationApiFactoryFixture<TEntryPoint> : WebApplicationFactor
var host = builder.Build();
host.Start();
+ // Get the DbContextFactory instance and store it for later use during tests.
+ _dbContextFactory = host.Services.GetRequiredService<IDbContextFactory<AliasServerDbContext>>();
+
// This delay prevents "ERR_CONNECTION_REFUSED" errors
// which happened like 1 out of 10 times when running tests.
Thread.Sleep(100);
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTest.cs
new file mode 100644
index 000000000..59b5a1b01
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTest.cs
@@ -0,0 +1,43 @@
+//-----------------------------------------------------------------------
+// <copyright file="ApiLoggingTest.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.E2ETests.Tests.Client;
+
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// End-to-end tests for making sure errors and warnings in API are logged to database.
+/// </summary>
+[TestFixture]
+[NonParallelizable]
+public class ApiLoggingTest : ClientPlaywrightTest
+{
+ /// <summary>
+ /// Test if an error in the API is logged to the database.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ [Test]
+ public async Task ApiDbLogTest()
+ {
+ // Call webapi endpoint that throws an exception.
+ try
+ {
+ await Page.GotoAsync(ApiBaseUrl + "api/v1/Test/Error");
+ await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);
+ }
+ catch
+ {
+ // Ignore exception as this is expected.
+ }
+
+ // Read from database to check if the log entry was created.
+ var logEntry = await ApiDbContext.Logs.Where(x => x.Application == "AliasVault.Api").OrderByDescending(x => x.Id).FirstOrDefaultAsync();
+
+ Assert.That(logEntry, Is.Not.Null, "Log entry for triggered exception not found in database. Check Serilog configuration and /api/v1/Test/Error endpoint.");
+ Assert.That(logEntry.Exception, Does.Contain("Test error"), "Log entry in database does not contain expected message. Check exception and Serilog configuration.");
+ }
+}
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs
index acf2e7845..756030055 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs
@@ -8,7 +8,7 @@
namespace AliasVault.E2ETests.Tests.Client;
/// <summary>
-/// End-to-end tests for the credential management.
+/// End-to-end tests for the client database persistence.
/// </summary>
[TestFixture]
[NonParallelizable]
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs
index 7b6733114..12dfe6620 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs
@@ -10,7 +10,7 @@ namespace AliasVault.E2ETests.Tests.Client;
using AliasServerDb;
/// <summary>
-/// End-to-end tests for the credential management.
+/// End-to-end tests for upgrading client databases.
/// </summary>
[TestFixture]
[NonParallelizable]