Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add JWT auth tokens E2E tests (#63)
Leendert de Borst4170e754ead8
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.csindex 04bebbee0..0c56c8fe4 100644--- a/src/AliasVault.Api/Controllers/AuthController.cs+++ b/src/AliasVault.Api/Controllers/AuthController.cs@@ -15,6 +15,7 @@ using AliasServerDb;using AliasVault.Shared.Models;using AliasVault.Shared.Models.WebApi;using AliasVault.Shared.Models.WebApi.Auth;+using AliasVault.Shared.Providers;using Asp.Versioning;using Cryptography.Models;using Microsoft.AspNetCore.Identity;@@ -30,10 +31,11 @@ using Microsoft.IdentityModel.Tokens;/// <param name="signInManager">SignInManager instance.</param>/// <param name="configuration">IConfiguration instance.</param>/// <param name="cache">IMemoryCache instance for persisting SRP values during multi-step login process.</param>+/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing..</param>[Route("api/v{version:apiVersion}/[controller]")][ApiController][ApiVersion("1")]-public class AuthController(AliasServerDbContext context, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache) : ControllerBase+public class AuthController(AliasServerDbContext context, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider) : ControllerBase{/// <summary>/// Error message for invalid email or password.@@ -128,7 +130,7 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVault// Remove any existing refresh tokens for this user and device.var deviceIdentifier = GenerateDeviceIdentifier(Request);var existingToken = context.AspNetUserRefreshTokens.Where(t => t.UserId == user.Id && t.DeviceIdentifier == deviceIdentifier).FirstOrDefault();- if (existingToken == null || existingToken.Value != tokenModel.RefreshToken || existingToken.ExpireDate < DateTime.Now)+ if (existingToken == null || existingToken.Value != tokenModel.RefreshToken || existingToken.ExpireDate < timeProvider.UtcNow){return Unauthorized("Refresh token expired");}@@ -145,8 +147,8 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVaultUserId = user.Id,DeviceIdentifier = deviceIdentifier,Value = newRefreshToken,- ExpireDate = DateTime.Now.AddDays(30),- CreatedAt = DateTime.Now,+ ExpireDate = timeProvider.UtcNow.AddDays(30),+ CreatedAt = timeProvider.UtcNow,});await context.SaveChangesAsync();@@ -314,7 +316,7 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVaultissuer: configuration["Jwt:Issuer"] ?? string.Empty,audience: configuration["Jwt:Issuer"] ?? string.Empty,claims: claims,- expires: DateTime.Now.AddMinutes(10),+ expires: timeProvider.UtcNow.AddMinutes(10),signingCredentials: creds);return new JwtSecurityTokenHandler().WriteToken(token);@@ -345,8 +347,8 @@ public class AuthController(AliasServerDbContext context, UserManager<AliasVaultUserId = user.Id,DeviceIdentifier = deviceIdentifier,Value = refreshToken,- ExpireDate = DateTime.Now.AddDays(30),- CreatedAt = DateTime.Now,+ ExpireDate = timeProvider.UtcNow.AddDays(30),+ CreatedAt = DateTime.UtcNow,});await context.SaveChangesAsync();diff --git a/src/AliasVault.Api/Controllers/Vault/VaultRetentionManager.cs b/src/AliasVault.Api/Controllers/Vault/VaultRetentionManager.csindex f82f3ad90..1ce90153a 100644--- a/src/AliasVault.Api/Controllers/Vault/VaultRetentionManager.cs+++ b/src/AliasVault.Api/Controllers/Vault/VaultRetentionManager.cs@@ -24,12 +24,11 @@ public static class VaultRetentionManager/// </summary>/// <param name="retentionPolicy">List of retention policies to apply.</param>/// <param name="existingVaults">List of existing vaults for a certain user.</param>+ /// <param name="now">DateTime which represents current time.</param>/// <param name="newVault">New encrypted vault to be added that is also taken into account for calculating retention policy.</param>/// <returns>List of vaults to delete according to the retention policies.</returns>- public static List<Vault> ApplyRetention(RetentionPolicy retentionPolicy, List<Vault> existingVaults, Vault? newVault = null)+ public static List<Vault> ApplyRetention(RetentionPolicy retentionPolicy, List<Vault> existingVaults, DateTime now, Vault? newVault = null){- var now = DateTime.UtcNow;-// Add the new vault to the list of existing vaults if providedif (newVault is not null){diff --git a/src/AliasVault.Api/Controllers/VaultController.cs b/src/AliasVault.Api/Controllers/VaultController.csindex 967dfa062..ef763515e 100644--- a/src/AliasVault.Api/Controllers/VaultController.cs+++ b/src/AliasVault.Api/Controllers/VaultController.cs@@ -10,6 +10,7 @@ namespace AliasVault.Api.Controllers;using AliasServerDb;using AliasVault.Api.Controllers.Vault;using AliasVault.Api.Controllers.Vault.RetentionRules;+using AliasVault.Shared.Providers;using Asp.Versioning;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;@@ -20,8 +21,9 @@ using Microsoft.EntityFrameworkCore;/// </summary>/// <param name="context">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) : AuthenticatedRequestController(userManager)+public class VaultController(AliasServerDbContext context, UserManager<AliasVaultUser> userManager, ITimeProvider timeProvider) : AuthenticatedRequestController(userManager){/// <summary>/// Default retention policy for vaults.@@ -84,8 +86,8 @@ public class VaultController(AliasServerDbContext context, UserManager<AliasVaul{UserId = user.Id,VaultBlob = model.Blob,- CreatedAt = DateTime.UtcNow,- UpdatedAt = DateTime.UtcNow,+ CreatedAt = timeProvider.UtcNow,+ UpdatedAt = timeProvider.UtcNow,};// Run the vault retention manager to keep the required vaults according@@ -97,7 +99,7 @@ public class VaultController(AliasServerDbContext context, UserManager<AliasVaul.Select(x => new AliasServerDb.Vault { Id = x.Id, UpdatedAt = x.UpdatedAt }).ToListAsync();- var vaultsToDelete = VaultRetentionManager.ApplyRetention(_retentionPolicy, existingVaults, newVault);+ var vaultsToDelete = VaultRetentionManager.ApplyRetention(_retentionPolicy, existingVaults, timeProvider.UtcNow, newVault);// Delete vaults that are not needed anymore.context.Vaults.RemoveRange(vaultsToDelete);diff --git a/src/AliasVault.Api/Jwt/TimeValidationJwtBearerEvents.cs b/src/AliasVault.Api/Jwt/TimeValidationJwtBearerEvents.csnew file mode 100644index 000000000..d62347ede--- /dev/null+++ b/src/AliasVault.Api/Jwt/TimeValidationJwtBearerEvents.cs@@ -0,0 +1,41 @@+// -----------------------------------------------------------------------+// <copyright file="TimeValidationJwtBearerEvents.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.Jwt;++using System.IdentityModel.Tokens.Jwt;+using AliasVault.Shared.Providers;+using Microsoft.AspNetCore.Authentication.JwtBearer;+using Microsoft.IdentityModel.JsonWebTokens;++/// <summary>+/// JwtBearerEvents implementation that validates the token expiration time based on+/// the current time provided by an ITimeProvider. This is used to be able to+/// test the token expiration logic in unit tests.+/// </summary>+public class TimeValidationJwtBearerEvents(ITimeProvider timeProvider) : JwtBearerEvents+{+ /// <summary>+ /// Validates the token expiration time based on the current time provided by the ITimeProvider.+ /// </summary>+ /// <param name="context">TokenValidatedContext.</param>+ /// <returns>Async task.</returns>+ public override Task TokenValidated(TokenValidatedContext context)+ {+ var jwtToken = context.SecurityToken as JsonWebToken;+ if (jwtToken != null)+ {+ var now = timeProvider.UtcNow;+ if (jwtToken.ValidTo < now)+ {+ context.Fail("Token has expired.");+ }+ }++ return Task.CompletedTask;+ }+}diff --git a/src/AliasVault.Api/Program.cs b/src/AliasVault.Api/Program.csindex d8bd5d156..e484f2395 100644--- a/src/AliasVault.Api/Program.cs+++ b/src/AliasVault.Api/Program.cs@@ -8,6 +8,8 @@using System.Data.Common;using System.Text;using AliasServerDb;+using AliasVault.Api.Jwt;+using AliasVault.Shared.Providers;using Asp.Versioning;using Microsoft.AspNetCore.Authentication.JwtBearer;using Microsoft.AspNetCore.Identity;@@ -19,6 +21,9 @@ using Microsoft.OpenApi.Models;var builder = WebApplication.CreateBuilder(args);var configuration = builder.Configuration;+builder.Services.AddSingleton<ITimeProvider, SystemTimeProvider>();+builder.Services.AddScoped<TimeValidationJwtBearerEvents>();+builder.Services.AddLogging(logging =>{logging.AddConsole();@@ -92,6 +97,10 @@ builder.Services.AddAuthentication(options =>IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),ClockSkew = TimeSpan.Zero,};++ // Add custom event handler for validating token expiration time in order+ // to be able to mutate current time for testing the token expiration logic in unit tests.+ options.EventsType = typeof(TimeValidationJwtBearerEvents);});// Configure CORSdiff --git a/src/AliasVault.Shared/Providers/ITimeProvider.cs b/src/AliasVault.Shared/Providers/ITimeProvider.csnew file mode 100644index 000000000..96fb27a6c--- /dev/null+++ b/src/AliasVault.Shared/Providers/ITimeProvider.cs@@ -0,0 +1,19 @@+// -----------------------------------------------------------------------+// <copyright file="ITimeProvider.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.Shared.Providers;++/// <summary>+/// Time provider interface for getting the current time. We use this to be able to mock the time in tests.+/// </summary>+public interface ITimeProvider+{+ /// <summary>+ /// Gets current time in UTC.+ /// </summary>+ DateTime UtcNow { get; }+}diff --git a/src/AliasVault.Shared/Providers/SystemTimeProvider.cs b/src/AliasVault.Shared/Providers/SystemTimeProvider.csnew file mode 100644index 000000000..cc4b6a6d2--- /dev/null+++ b/src/AliasVault.Shared/Providers/SystemTimeProvider.cs@@ -0,0 +1,19 @@+// -----------------------------------------------------------------------+// <copyright file="SystemTimeProvider.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.Shared.Providers;++/// <summary>+/// Default time provider that uses the system clock.+/// </summary>+public class SystemTimeProvider : ITimeProvider+{+ /// <summary>+ /// Gets current time in UTC.+ /// </summary>+ public DateTime UtcNow => DateTime.UtcNow;+}diff --git a/src/AliasVault.Shared/Providers/TestTimeProvider.cs b/src/AliasVault.Shared/Providers/TestTimeProvider.csnew file mode 100644index 000000000..26c7b967b--- /dev/null+++ b/src/AliasVault.Shared/Providers/TestTimeProvider.cs@@ -0,0 +1,39 @@+// -----------------------------------------------------------------------+// <copyright file="TestTimeProvider.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.Shared.Providers;++/// <summary>+/// Test time provider that allows mutating the current time for testing purposes.+/// </summary>+public class TestTimeProvider : ITimeProvider+{+ private DateTime _currentTime = DateTime.UtcNow;++ /// <summary>+ /// Gets current time in UTC.+ /// </summary>+ public DateTime UtcNow => _currentTime;++ /// <summary>+ /// Set the current time to a specific date and time.+ /// </summary>+ /// <param name="dateTime">DateTime to set current time to.</param>+ public void SetUtcNow(DateTime dateTime)+ {+ _currentTime = dateTime;+ }++ /// <summary>+ /// Advance current time by a specific time span.+ /// </summary>+ /// <param name="timeSpan">Amount of time to advance current time by.</param>+ public void AdvanceBy(TimeSpan timeSpan)+ {+ _currentTime = _currentTime.Add(timeSpan);+ }+}diff --git a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.csindex d2b82a3f3..9b2012fdd 100644--- a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs+++ b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs@@ -7,6 +7,7 @@namespace AliasVault.E2ETests.Common;+using AliasVault.Shared.Providers;using Microsoft.Playwright;/// <summary>@@ -14,7 +15,7 @@ using Microsoft.Playwright;/// </summary>public class PlaywrightTest{- private static readonly object _lock = new object();+ private static readonly object _lock = new();private static int _basePort = 5600;private static int _currentPort = _basePort;@@ -28,6 +29,11 @@ public class PlaywrightTest/// </summary>private readonly WebApplicationWasmFactoryFixture<AliasVault.E2ETests.WebApp.Server.Program> _wasmFactory = new();+ /// <summary>+ /// Gets the time provider instance for mutating the current WebApi time in tests.+ /// </summary>+ protected TestTimeProvider ApiTimeProvider => _apiFactory.TimeProvider;+/// <summary>/// Gets or sets base URL where the Blazor WASM app runs on including random port./// </summary>diff --git a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.csindex efc62be53..5ebcc4ded 100644--- a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs+++ b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs@@ -9,6 +9,7 @@ namespace AliasVault.E2ETests.Infrastructure;using System.Data.Common;using AliasServerDb;+using AliasVault.Shared.Providers;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Mvc.Testing;using Microsoft.Data.Sqlite;@@ -28,6 +29,11 @@ public class WebApplicationApiFactoryFixture<TEntryPoint> : WebApplicationFactor/// </summary>public string HostUrl { get; set; } = "https://localhost:5001";+ /// <summary>+ /// Gets the time provider instance for mutating the current time in tests.+ /// </summary>+ public TestTimeProvider TimeProvider { get; private set; } = new();+/// <inheritdoc />protected override void ConfigureWebHost(IWebHostBuilder builder){@@ -38,6 +44,21 @@ public class WebApplicationApiFactoryFixture<TEntryPoint> : WebApplicationFactorbuilder.ConfigureServices((context, services) =>{+ // Replace the ITimeProvider registration with a TestTimeProvider.+ 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 ==diff --git a/src/Tests/AliasVault.E2ETests/Tests/JwtTokenTests.cs b/src/Tests/AliasVault.E2ETests/Tests/JwtTokenTests.csnew file mode 100644index 000000000..80868cccc--- /dev/null+++ b/src/Tests/AliasVault.E2ETests/Tests/JwtTokenTests.cs@@ -0,0 +1,106 @@+//-----------------------------------------------------------------------+// <copyright file="JwtTokenTests.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;++/// <summary>+/// End-to-end tests for JWT token handling.+/// </summary>+[Parallelizable(ParallelScope.Self)]+[TestFixture]+public class JwtTokenTests : PlaywrightTest+{+ /// <summary>+ /// Test that when the JWT token expires the client automatically refreshes it with the refresh token.+ /// </summary>+ /// <returns>Async task.</returns>+ [Order(1)]+ [Test]+ public async Task RefreshTokenTest()+ {+ // Soft navigate to "aliases" page to verify that it works.+ await NavigateUsingBlazorRouter("aliases");+ await WaitForURLAsync("**/aliases", "Find all of your aliases below");++ // Increase the time by 1 hour to make the JWT token expire.+ ApiTimeProvider.AdvanceBy(TimeSpan.FromHours(1));++ // Soft navigate to another page to trigger the JWT token refresh+ // and check if the page is loaded successfully.+ await NavigateUsingBlazorRouter("dbtest");+ await WaitForURLAsync("**/dbtest", "Find all of your aliases below.");++ var pageContent = await Page.TextContentAsync("body");+ Assert.That(pageContent, Does.Contain("Find all of your aliases below"), "No index content after unlocking database.");+ }++ /// <summary>+ /// Test that when the JWT token expires the unlock page logic still works where if the+ /// user enters the master key password they are logged in again without errors.+ /// </summary>+ /// <returns>Async task.</returns>+ [Order(2)]+ [Test]+ public async Task RefreshTokenUnlockPageTest()+ {+ // Soft navigate to "aliases" page to verify that it works.+ var startUrl = "dbtest";+ await NavigateUsingBlazorRouter(startUrl);+ await WaitForURLAsync("**/" + startUrl, "Find all of your aliases below");++ // Hard reload the page to trigger the unlock page to show up.+ await Page.ReloadAsync();+ await WaitForURLAsync("**/unlock", "unlock");++ // Increase the time by 24 hours to make the JWT token expire.+ ApiTimeProvider.AdvanceBy(TimeSpan.FromHours(24));++ // Check if by entering password the JWT token is refreshed and the+ // unlock page is replaced by the alias listing page.+ await InputHelper.FillInputFields(new Dictionary<string, string>+ {+ { "password", TestUserPassword },+ });++ var submitButton = Page.GetByRole(AriaRole.Button, new() { Name = "Unlock" });+ await submitButton.ClickAsync();++ // Check if we get redirected back to the page we were trying to access.+ await WaitForURLAsync("**/" + startUrl, "AliasVault");++ var pageContent = await Page.TextContentAsync("body");+ Assert.That(pageContent, Does.Contain("Find all of your aliases below"), "No index content after unlocking database with a expired JWT token.");+ }++ /// <summary>+ /// Test that when the refresh token expires the client automatically logs out the user.+ /// </summary>+ /// <returns>Async task.</returns>+ [Order(3)]+ [Test]+ public async Task RefreshTokenExpiredTest()+ {+ // Soft navigate to "aliases" page to verify that it works.+ await NavigateUsingBlazorRouter("aliases");+ await WaitForURLAsync("**/aliases", "Find all of your aliases below");++ // Increase the time by 1 year to make the JWT token AND refresh token expire.+ ApiTimeProvider.AdvanceBy(TimeSpan.FromDays(365));++ // Soft navigate to another page to trigger the JWT token refresh+ // and check if the page is loaded successfully.+ // Not all pages do a webapi call on load everytime so we need to navigate to a page that does.+ await NavigateUsingBlazorRouter("dbtest");+ await NavigateUsingBlazorRouter("aliases");+ await NavigateUsingBlazorRouter("dbtest");++ await WaitForURLAsync("**/user/login", "Login");++ var pageContent = await Page.TextContentAsync("body");+ Assert.That(pageContent, Does.Contain("Login"), "No redirect to login while refresh token should be expired.");+ }+}diff --git a/src/Tests/AliasVault.UnitTests/Vault/VaultRetentionManagerTests.cs b/src/Tests/AliasVault.UnitTests/Vault/VaultRetentionManagerTests.csindex 94e4bcf68..948739e8b 100644--- a/src/Tests/AliasVault.UnitTests/Vault/VaultRetentionManagerTests.cs+++ b/src/Tests/AliasVault.UnitTests/Vault/VaultRetentionManagerTests.cs@@ -122,7 +122,7 @@ public class VaultRetentionManagerTests// - 2 vaults from the last 2 weeks, where 1 is the same as the last 2 days because it's in the past.// - 1 vault from the last month, which is the same as the last 2 days one because it's in the past// Total expected: 3 to be kept so 9 deleted.- var vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults).ToList();+ var vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults, DateTime.UtcNow).ToList();// Remove the vaults from the list of test vaults that are expected to be keptvar vaultsToKeep = new List<Vault>(testVaults);@@ -162,7 +162,7 @@ public class VaultRetentionManagerTests// With the test data set of 9 vaults, we expect to keep:// - 1 vault which is the new vault created now (not in the list)// - 1 vault from the past which is the latest one in the list.- var vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults, newVault).ToList();+ var vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults, DateTime.UtcNow, newVault).ToList();// Remove the vaults from the list of test vaults that are expected to be keptvar vaultsToKeep = new List<Vault>(testVaults);@@ -188,7 +188,7 @@ public class VaultRetentionManagerTests// With the test data set of 9 vaults, we expect to keep:// - 1 vault which is the latest one. Even though we have no rules, we should always keep the latest one.- var vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults).ToList();+ var vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults, DateTime.UtcNow).ToList();// Remove the vaults from the list of test vaults that are expected to be keptvar vaultsToKeep = new List<Vault>(testVaults);