Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add V1 API legacy filter for upgraded accounts (#2492)
Leendert de Borsta009ece28193
diff --git a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/AuthController.csindex 30ea4af10..b75309acb 100644--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs@@ -12,6 +12,7 @@ using System.Security.Claims;using System.Security.Cryptography;using System.Text;using AliasServerDb;+using AliasVault.Api.Filters;using AliasVault.Api.Headers;using AliasVault.Api.Helpers;using AliasVault.Api.Models;@@ -82,6 +83,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// Status endpoint called by client to check if user is still authenticated and get sync status./// </summary>/// <returns>Returns status response if valid authentication is provided, otherwise it will return 401 unauthorized.</returns>+ [AllowAfterV2Migration][Authorize][HttpGet("status")]public async Task<IActionResult> Status()@@ -120,7 +122,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// A caller on this v1 endpoint cannot serve a user whose vault has moved to the v2 storage format. Reporting// the client as unsupported makes it show its built-in "please update" message and log out cleanly, instead// of running into a hard failure on the vault endpoints later on.- clientSupported = clientSupported && !await LegacyVaultHelper.HasMigratedToV2Async(context, user.Id);+ clientSupported = clientSupported && !await LegacyVaultHelper.HasMigratedToV2Async(context, cache, user.Id);return Ok(new StatusResponse{@@ -153,7 +155,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM{// Log the attempt internallyawait authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);- return UpgradeRequiredResponse();+ return LegacyVaultHelper.UpgradeRequiredResult();}// Check if the account is locked out.@@ -177,7 +179,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// A v1 client can only answer a legacy verifier; for an upgraded one it would report a wrong password.if (latestVaultEncryptionSettings.EncryptionType != Defaults.LegacyEncryptionType){- return UpgradeRequiredResponse();+ return LegacyVaultHelper.UpgradeRequiredResult();}var srpIdentity = AuthHelper.GetSrpIdentity(user);@@ -393,6 +395,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// </summary>/// <param name="model">Token model.</param>/// <returns>IActionResult.</returns>+ [AllowAfterV2Migration][HttpPost("revoke")]public async Task<IActionResult> Revoke([FromBody] TokenModel model){@@ -436,6 +439,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// </summary>/// <param name="model">Token model.</param>/// <returns>IActionResult.</returns>+ [AllowAfterV2Migration][HttpPost("revoke-token")]public async Task<IActionResult> RevokeToken([FromBody] TokenModel model){@@ -1001,10 +1005,4 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn new TokenModel { Token = accessToken, RefreshToken = refreshToken };}-- /// <summary>- /// The response for an account a v1 client cannot sign in to.- /// </summary>- /// <returns>IActionResult.</returns>- private ObjectResult UpgradeRequiredResponse() => StatusCode(426, new { error = "UPGRADE_REQUIRED", message = "Your client is out of date. Please update to access this vault." });}diff --git a/apps/server/AliasVault.Api/Controllers/V1/Tests/TestController.cs b/apps/server/AliasVault.Api/Controllers/V1/Tests/TestController.csdeleted file mode 100644index facba2362..000000000--- a/apps/server/AliasVault.Api/Controllers/V1/Tests/TestController.cs+++ /dev/null@@ -1,495 +0,0 @@-//------------------------------------------------------------------------// <copyright file="TestController.cs" company="aliasvault">-// Copyright (c) aliasvault. All rights reserved.-// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.-// </copyright>-//-------------------------------------------------------------------------/*- * Note: this file is used for E2E testing purposes only. It contains test endpoints that are used by- * E2E tests (browser extension Playwright tests, mobile app UI tests) to manipulate server state.- *- * These endpoints are only available in DEBUG builds.- */--namespace AliasVault.Api.Controllers.V1.Tests;--using AliasServerDb;-using AliasVault.Api.Controllers.Abstracts;-using AliasVault.Api.Controllers.Tests;-using AliasVault.Shared.Server.Services;-using Asp.Versioning;-using Microsoft.AspNetCore.Authorization;-using Microsoft.AspNetCore.Identity;-using Microsoft.AspNetCore.Mvc;-using Microsoft.EntityFrameworkCore;--#if DEBUG--/// <summary>-/// Test controller that contains test endpoints for E2E testing purposes.-/// All endpoints are hidden from Swagger and only work in Development environment.-/// </summary>-/// <param name="userManager">UserManager instance.</param>-/// <param name="environment">IWebHostEnvironment instance.</param>-/// <param name="dbContextFactory">DbContext factory instance.</param>-/// <param name="serverSettingsService">ServerSettingsService instance.</param>-[ApiVersion("1")]-public class TestController(- UserManager<AliasVaultUser> userManager,- IWebHostEnvironment environment,- IAliasServerDbContextFactory dbContextFactory,- ServerSettingsService serverSettingsService) : AuthenticatedRequestController(userManager)-{- /// <summary>- /// Authenticated test request. Used to verify authentication is working.- /// </summary>- /// <returns>Static OK.</returns>- [HttpGet("")]- public IActionResult TestCall()- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- return Ok();- }-- /// <summary>- /// Test request that throws an exception. Used for testing error handling.- /// </summary>- /// <returns>Never returns - always throws.</returns>- [AllowAnonymous]- [HttpGet("Error")]- public IActionResult TestCallError()- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- // Throw an exception here to test error handling.- throw new ArgumentException("Test error");- }-- /// <summary>- /// Delete the newest vault revisions for the current user.- /// Used for testing RPO (Recovery Point Objective) recovery scenarios.- /// </summary>- /// <param name="count">Number of newest revisions to delete.</param>- /// <returns>OK with the number of deleted revisions, or NotFound in production.</returns>- [HttpDelete("vault-revisions/{count:int}")]- public async Task<IActionResult> DeleteVaultRevisions(int count)- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- if (count <= 0)- {- return BadRequest("Count must be greater than 0");- }-- var user = await GetCurrentUserAsync();- if (user == null)- {- return Unauthorized();- }-- await using var context = await dbContextFactory.CreateDbContextAsync();-- var deletedRevisions = await PopNewestRevisionsAsync(context, user.Id, count);- if (deletedRevisions.Count == 0)- {- return Ok(new { deleted = 0, message = "No revisions found to delete" });- }-- return Ok(new- {- deleted = deletedRevisions.Count,- deletedRevisions,- message = $"Deleted {deletedRevisions.Count} vault revision(s)",- });- }-- /// <summary>- /// Get vault revision information for the current user.- /// Used for E2E tests to verify vault state.- /// </summary>- /// <returns>Vault revision information.</returns>- [HttpGet("vault-revisions")]- public async Task<IActionResult> GetVaultRevisions()- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- var user = await GetCurrentUserAsync();- if (user == null)- {- return Unauthorized();- }-- await using var context = await dbContextFactory.CreateDbContextAsync();-- return Ok(await BuildRevisionInfoAsync(context, user.Id));- }-- /// <summary>- /// Block the current user's account.- /// Used for testing forced logout scenarios.- /// After calling this, any subsequent API calls to /status will return 401.- /// </summary>- /// <returns>OK with the blocked status.</returns>- [HttpPost("block-user")]- public async Task<IActionResult> BlockUser()- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- var user = await GetCurrentUserAsync();- if (user == null)- {- return Unauthorized();- }-- await using var context = await dbContextFactory.CreateDbContextAsync();-- // Find the user in the new context and block them- var dbUser = await context.AliasVaultUsers.FindAsync(user.Id);- if (dbUser == null)- {- return NotFound("User not found");- }-- dbUser.Blocked = true;- await context.SaveChangesAsync();-- return Ok(new- {- blocked = true,- message = $"User {user.UserName} has been blocked",- });- }-- /// <summary>- /// Unblock the current user's account.- /// Used for testing - allows re-enabling the account after forced logout test.- /// Note: This uses the JWT token which is still valid even for blocked users,- /// so the user can unblock themselves for testing purposes.- /// </summary>- /// <returns>OK with the blocked status.</returns>- [HttpPost("unblock-user")]- public async Task<IActionResult> UnblockUser()- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- var user = await GetCurrentUserAsync();- if (user == null)- {- return Unauthorized();- }-- await using var context = await dbContextFactory.CreateDbContextAsync();-- // Find the user in the new context and unblock them- var dbUser = await context.AliasVaultUsers.FindAsync(user.Id);- if (dbUser == null)- {- return NotFound("User not found");- }-- dbUser.Blocked = false;- await context.SaveChangesAsync();-- return Ok(new- {- blocked = false,- message = $"User {user.UserName} has been unblocked",- });- }-- /// <summary>- /// Get vault revision information for a user by username.- /// Anonymous endpoint for E2E tests that cannot access auth tokens.- /// Only available in DEBUG builds.- /// </summary>- /// <param name="username">The username to look up.</param>- /// <returns>Vault revision information.</returns>- [AllowAnonymous]- [HttpGet("vault-revisions/by-username/{username}")]- public async Task<IActionResult> GetVaultRevisionsByUsername(string username)- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- await using var context = await dbContextFactory.CreateDbContextAsync();-- var user = await context.AliasVaultUsers- .FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());-- if (user == null)- {- return NotFound($"User '{username}' not found");- }-- return Ok(await BuildRevisionInfoAsync(context, user.Id));- }-- /// <summary>- /// Delete the newest vault revisions for a user by username.- /// Anonymous endpoint for E2E tests that cannot access auth tokens.- /// Only available in DEBUG builds.- /// </summary>- /// <param name="username">The username to look up.</param>- /// <param name="count">Number of newest revisions to delete.</param>- /// <returns>OK with the number of deleted revisions.</returns>- [AllowAnonymous]- [HttpDelete("vault-revisions/by-username/{username}/{count:int}")]- public async Task<IActionResult> DeleteVaultRevisionsByUsername(string username, int count)- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- if (count <= 0)- {- return BadRequest("Count must be greater than 0");- }-- await using var context = await dbContextFactory.CreateDbContextAsync();-- var user = await context.AliasVaultUsers- .FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());-- if (user == null)- {- return NotFound($"User '{username}' not found");- }-- var deletedRevisions = await PopNewestRevisionsAsync(context, user.Id, count);- if (deletedRevisions.Count == 0)- {- return Ok(new { deleted = 0, message = "No revisions found to delete" });- }-- return Ok(new- {- deleted = deletedRevisions.Count,- deletedRevisions,- message = $"Deleted {deletedRevisions.Count} vault revision(s)",- });- }-- /// <summary>- /// Block a user's account by username.- /// Anonymous endpoint for E2E tests that cannot access auth tokens.- /// Only available in DEBUG builds.- /// </summary>- /// <param name="username">The username to block.</param>- /// <returns>OK with the blocked status.</returns>- [AllowAnonymous]- [HttpPost("block-user/by-username/{username}")]- public async Task<IActionResult> BlockUserByUsername(string username)- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- await using var context = await dbContextFactory.CreateDbContextAsync();-- var user = await context.AliasVaultUsers- .FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());-- if (user == null)- {- return NotFound($"User '{username}' not found");- }-- user.Blocked = true;- await context.SaveChangesAsync();-- return Ok(new- {- blocked = true,- message = $"User {user.UserName} has been blocked",- });- }-- /// <summary>- /// Unblock a user's account by username.- /// Anonymous endpoint for E2E tests that cannot access auth tokens.- /// Only available in DEBUG builds.- /// </summary>- /// <param name="username">The username to unblock.</param>- /// <returns>OK with the blocked status.</returns>- [AllowAnonymous]- [HttpPost("unblock-user/by-username/{username}")]- public async Task<IActionResult> UnblockUserByUsername(string username)- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- await using var context = await dbContextFactory.CreateDbContextAsync();-- var user = await context.AliasVaultUsers- .FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());-- if (user == null)- {- return NotFound($"User '{username}' not found");- }-- user.Blocked = false;- await context.SaveChangesAsync();-- return Ok(new- {- blocked = false,- message = $"User {user.UserName} has been unblocked",- });- }-- /// <summary>- /// Set a server setting by key/value. Used by E2E tests to tune runtime limits- /// (e.g. disabling the per-IP registration rate limit by setting it to 0).- /// Anonymous endpoint for E2E tests that cannot access auth tokens.- /// Only available in DEBUG builds.- /// </summary>- /// <param name="request">The setting to update.</param>- /// <returns>OK with the updated key and value.</returns>- [AllowAnonymous]- [HttpPost("server-settings")]- public async Task<IActionResult> SetServerSetting([FromBody] SetServerSettingRequest request)- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- if (string.IsNullOrWhiteSpace(request.Key))- {- return BadRequest("Key is required");- }-- await serverSettingsService.SetSettingAsync(request.Key, request.Value);-- return Ok(new- {- key = request.Key,- value = request.Value,- });- }-- /// <summary>- /// Get a server setting by key.- /// Anonymous endpoint for E2E tests that cannot access auth tokens.- /// Only available in DEBUG builds.- /// </summary>- /// <param name="key">The setting key to read.</param>- /// <returns>OK with the current key and value (value may be null if unset).</returns>- [AllowAnonymous]- [HttpGet("server-settings/{key}")]- public async Task<IActionResult> GetServerSetting(string key)- {- if (!environment.IsDevelopment())- {- return NotFound();- }-- var value = await serverSettingsService.GetSettingAsync(key);-- return Ok(new- {- key,- value,- });- }-- /// <summary>- /// Builds the revision info payload for a user: the current revision of the personal manifest plus all history- /// revisions, newest first.- /// </summary>- private static async Task<object> BuildRevisionInfoAsync(AliasServerDbContext context, string userId)- {- var current = await context.VaultManifests- .Where(v => context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == v.OwnerGroupId))- .Select(v => new { v.RevisionNumber, v.CreatedAt, v.UpdatedAt })- .FirstOrDefaultAsync();-- var history = await context.VaultManifestsHistory- .Where(v => context.VaultManifests.Any(m => m.ManifestId == v.ManifestId && context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == m.OwnerGroupId)))- .OrderByDescending(v => v.RevisionNumber)- .Select(v => new { v.RevisionNumber, v.CreatedAt, v.UpdatedAt })- .ToListAsync();-- var revisions = history.ToList();- if (current != null)- {- revisions.Insert(0, current);- }-- revisions = revisions.OrderByDescending(v => v.RevisionNumber).ToList();-- return new- {- count = revisions.Count,- currentRevision = current?.RevisionNumber ?? 0,- revisions,- };- }-- /// <summary>- /// Deletes the newest <paramref name="count"/> revisions of the user's personal manifest by rolling the current row- /// back to the newest history revision each time (the inverse of the archive-then-update upload flow). When no- /// history remains, the manifest row itself is deleted. Returns the revision numbers that were discarded.- /// </summary>- private static async Task<List<long>> PopNewestRevisionsAsync(AliasServerDbContext context, string userId, int count)- {- var deletedRevisions = new List<long>();- var current = await context.VaultManifests.FirstOrDefaultAsync(v => context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == v.OwnerGroupId));-- for (var i = 0; i < count && current != null; i++)- {- deletedRevisions.Add(current.RevisionNumber);-- // Drop the blob references of the revision being discarded.- await context.VaultBlobReferences.Where(r => r.ManifestId == current.ManifestId && r.RevisionNumber == current.RevisionNumber).ExecuteDeleteAsync();-- var newestHistory = await context.VaultManifestsHistory- .Where(h => h.ManifestId == current.ManifestId)- .OrderByDescending(h => h.RevisionNumber)- .FirstOrDefaultAsync();-- if (newestHistory == null)- {- context.VaultManifests.Remove(current);- current = null;- }- else- {- current.CopyPayloadFrom(newestHistory);- context.VaultManifestsHistory.Remove(newestHistory);- }-- await context.SaveChangesAsync();- }-- return deletedRevisions;- }-}-#endifdiff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.csindex dd216a646..e7a940bb7 100644--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs@@ -71,13 +71,6 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContreturn Unauthorized();}- // v2 storage-format guard: once the user has migrated to manifest-v1, v1 vault endpoints refuse to serve so- // outdated clients can't accidentally overwrite the new format with a legacy SQLite blob.- if (await LegacyVaultHelper.HasMigratedToV2Async(context, user.Id))- {- return UpgradeRequired();- }-// Logic to retrieve vault for the user: the current revision of the user's personal manifest.var vault = await context.VaultManifests.FirstOrDefaultAsync(x => x.OwnerGroupId == user.PersonalGroupId);@@ -145,11 +138,6 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContreturn Unauthorized();}- if (await LegacyVaultHelper.HasMigratedToV2Async(context, user.Id))- {- return UpgradeRequired();- }-// Compare the logged-in username with the username in the provided vault model.// If they do not match reject the request. This is important because it's// possible that a user has logged in with a different username than the one@@ -233,11 +221,6 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContreturn Unauthorized();}- if (await LegacyVaultHelper.HasMigratedToV2Async(context, user.Id))- {- return UpgradeRequired();- }-// Compare the logged-in username with the username in the provided vault model.// If they do not match reject the request. This is important because it's// possible that a user has logged in with a different username than the one@@ -328,22 +311,6 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContreturn archivedRevision;}- /// <summary>- /// HTTP 426 Upgrade Required: returned to legacy v1 clients hitting a migrated user. This is a backstop only:- /// the status endpoint already reports such clients as unsupported, so a well-behaved client logs out with a- /// proper "update your client" message before it ever calls a vault endpoint.- /// </summary>- private IActionResult UpgradeRequired()- {- return StatusCode(- 426,- new- {- error = "UPGRADE_REQUIRED",- message = "Your client is out of date. Please update to access this vault.",- });- }-/// <summary>/// Apply vault retention policies to the history revisions of a manifest and delete the ones that are not/// covered by the retention policies (plus their blob references). Runs after the previous current revision hasdiff --git a/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.csindex 7ea5b1528..1786f2dc2 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs@@ -25,6 +25,7 @@ using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;+using Microsoft.Extensions.Caching.Memory;#if DEBUG@@ -38,6 +39,7 @@ using Microsoft.EntityFrameworkCore;/// <param name="serverSettingsService">ServerSettingsService instance.</param>/// <param name="registrationInviteService">RegistrationInviteService instance.</param>/// <param name="capabilityService">CapabilityService instance.</param>+/// <param name="cache">IMemoryCache instance.</param>[ApiVersion("2")]public class TestController(UserManager<AliasVaultUser> userManager,@@ -45,7 +47,8 @@ public class TestController(IAliasServerDbContextFactory dbContextFactory,ServerSettingsService serverSettingsService,RegistrationInviteService registrationInviteService,- CapabilityService capabilityService) : AuthenticatedRequestController(userManager)+ CapabilityService capabilityService,+ IMemoryCache cache) : AuthenticatedRequestController(userManager){/// <summary>/// Authenticated test request. Used to verify authentication is working.@@ -432,6 +435,7 @@ public class TestController(Verifier = request.Verifier,});await context.SaveChangesAsync();+ LegacyVaultHelper.ForgetMigrationState(cache, user.Id);return Ok(new{diff --git a/apps/server/AliasVault.Api/Filters/AllowAfterV2MigrationAttribute.cs b/apps/server/AliasVault.Api/Filters/AllowAfterV2MigrationAttribute.csnew file mode 100644index 000000000..4fabdbe0d--- /dev/null+++ b/apps/server/AliasVault.Api/Filters/AllowAfterV2MigrationAttribute.cs@@ -0,0 +1,16 @@+//-----------------------------------------------------------------------+// <copyright file="AllowAfterV2MigrationAttribute.cs" company="aliasvault">+// Copyright (c) aliasvault. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Api.Filters;++/// <summary>+/// Exempts a v1 action from <see cref="LegacyApiGuardFilter"/>, so it stays reachable for users who migrated to v2.+/// </summary>+[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]+public sealed class AllowAfterV2MigrationAttribute : Attribute+{+}diff --git a/apps/server/AliasVault.Api/Filters/LegacyApiGuardFilter.cs b/apps/server/AliasVault.Api/Filters/LegacyApiGuardFilter.csnew file mode 100644index 000000000..8c8ef1e2c--- /dev/null+++ b/apps/server/AliasVault.Api/Filters/LegacyApiGuardFilter.cs@@ -0,0 +1,143 @@+//-----------------------------------------------------------------------+// <copyright file="LegacyApiGuardFilter.cs" company="aliasvault">+// Copyright (c) aliasvault. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Api.Filters;++using System.IdentityModel.Tokens.Jwt;+using System.Security.Claims;+using AliasServerDb;+using AliasVault.Api.Helpers;+using AliasVault.Auth;+using AliasVault.Shared.Models.WebApi.V1.Auth;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Identity;+using Microsoft.AspNetCore.Mvc.Controllers;+using Microsoft.AspNetCore.Mvc.Filters;+using Microsoft.EntityFrameworkCore;+using Microsoft.Extensions.Caching.Memory;++/// <summary>+/// Refuses every v1 request on behalf of a user who migrated to the v2 storage format, so v1 code paths can no+/// longer act on such an account. Registered globally; exempt an action with <see cref="AllowAfterV2MigrationAttribute"/>.+/// </summary>+/// <param name="dbContextFactory">AliasServerDbContext factory.</param>+/// <param name="userManager">UserManager instance.</param>+/// <param name="cache">Memory cache for the migration state.</param>+public sealed class LegacyApiGuardFilter(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IMemoryCache cache) : IAsyncActionFilter+{+ /// <inheritdoc />+ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)+ {+ if (context.HttpContext.RequestedApiVersion?.MajorVersion != 1 || IsExempt(context))+ {+ await next();+ return;+ }++ await using var dbContext = await dbContextFactory.CreateDbContextAsync();+ foreach (var userId in await ResolveUserIdsAsync(context, dbContext))+ {+ if (userId is null || await LegacyVaultHelper.HasMigratedToV2Async(dbContext, cache, userId))+ {+ context.Result = LegacyVaultHelper.UpgradeRequiredResult();+ return;+ }+ }++ await next();+ }++ /// <summary>+ /// Whether the action or its controller carries <see cref="AllowAfterV2MigrationAttribute"/>.+ /// </summary>+ /// <param name="context">The action context.</param>+ /// <returns>True when the action is exempt.</returns>+ private static bool IsExempt(ActionExecutingContext context)+ {+ return context.ActionDescriptor is ControllerActionDescriptor descriptor+ && (descriptor.MethodInfo.IsDefined(typeof(AllowAfterV2MigrationAttribute), true) || descriptor.ControllerTypeInfo.IsDefined(typeof(AllowAfterV2MigrationAttribute), true));+ }++ /// <summary>+ /// Reads the subject of a JWT without validating it. Only used to refuse a request, never to allow one.+ /// </summary>+ /// <param name="token">The JWT.</param>+ /// <returns>The user id, or null when the token cannot be read.</returns>+ private static string? ReadUnvalidatedSubject(string? token)+ {+ var handler = new JwtSecurityTokenHandler();+ if (string.IsNullOrWhiteSpace(token) || !handler.CanReadToken(token))+ {+ return null;+ }++ return handler.ReadJwtToken(token).Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;+ }++ /// <summary>+ /// Adds the owner of the refresh token and the subject of the access token, when known.+ /// </summary>+ /// <param name="dbContext">Database context.</param>+ /// <param name="tokens">The token pair from the request body.</param>+ /// <param name="userIds">The list to add to.</param>+ /// <returns>Task.</returns>+ private static async Task AddTokenUserIdsAsync(AliasServerDbContext dbContext, TokenModel tokens, List<string?> userIds)+ {+ var subject = ReadUnvalidatedSubject(tokens.Token);+ if (subject is not null)+ {+ userIds.Add(subject);+ }++ if (string.IsNullOrWhiteSpace(tokens.RefreshToken))+ {+ return;+ }++ var tokenHash = RefreshTokenHasher.Hash(tokens.RefreshToken);+ var owner = await dbContext.AliasVaultUserRefreshTokens.Where(t => t.TokenHash == tokenHash).Select(t => t.UserId).FirstOrDefaultAsync();+ if (owner is not null)+ {+ userIds.Add(owner);+ }+ }++ /// <summary>+ /// Collects the users this request acts on. A null entry stands for a username that does not exist.+ /// </summary>+ /// <param name="context">The action context.</param>+ /// <param name="dbContext">Database context.</param>+ /// <returns>The user ids to check.</returns>+ private async Task<List<string?>> ResolveUserIdsAsync(ActionExecutingContext context, AliasServerDbContext dbContext)+ {+ var userIds = new List<string?>();++ var principalUserId = context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);+ if (principalUserId is not null)+ {+ userIds.Add(principalUserId);+ }++ foreach (var argument in context.ActionArguments.Values)+ {+ switch (argument)+ {+ case LoginInitiateRequest login:+ userIds.Add((await userManager.FindByNameAsync(login.Username))?.Id);+ break;+ case ValidateLoginRequest validate:+ userIds.Add((await userManager.FindByNameAsync(validate.Username))?.Id);+ break;+ case TokenModel tokens:+ await AddTokenUserIdsAsync(dbContext, tokens, userIds);+ break;+ }+ }++ return userIds;+ }+}diff --git a/apps/server/AliasVault.Api/Helpers/LegacyVaultHelper.cs b/apps/server/AliasVault.Api/Helpers/LegacyVaultHelper.csindex f793f5ec7..58a562be4 100644--- a/apps/server/AliasVault.Api/Helpers/LegacyVaultHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/LegacyVaultHelper.cs@@ -8,24 +8,64 @@namespace AliasVault.Api.Helpers;using AliasServerDb;+using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;+using Microsoft.Extensions.Caching.Memory;/// <summary>/// Helpers for the legacy (v1) API surface which only understands the "sqlite-blob" storage format./// </summary>public static class LegacyVaultHelper{+ /// <summary>+ /// Cache key prefix for users known to have migrated.+ /// </summary>+ private const string CachePrefixMigrated = "LegacyVaultMigrated_";++ /// <summary>+ /// How long a positive answer is cached. Kept short because the admin legacy rollback (another process) can revert an account.+ /// </summary>+ private static readonly TimeSpan MigratedCacheLifetime = TimeSpan.FromMinutes(1);+/// <summary>/// True once the user has any vault row in the v2 (manifest-v1) storage format or any vault key record. Such a/// user can no longer be served by the v1 API: their vault blob is gone and their data is encrypted under the/// KEK/VEK hierarchy which v1-only clients cannot open./// </summary>/// <param name="context">Database context.</param>+ /// <param name="cache">Memory cache holding the users already known to have migrated.</param>/// <param name="userId">The id of the user to check.</param>/// <returns>True when the user has migrated to the v2 storage format.</returns>- public static async Task<bool> HasMigratedToV2Async(AliasServerDbContext context, string userId)+ public static async Task<bool> HasMigratedToV2Async(AliasServerDbContext context, IMemoryCache cache, string userId){- return await context.VaultManifests.AnyAsync(x => x.StorageFormat == VaultManifestBase.ManifestStorageFormat && context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == x.OwnerGroupId))- || await context.VaultManifestAccessKeys.AnyAsync(x => x.UserId == userId);+ if (cache.TryGetValue(CachePrefixMigrated + userId, out _))+ {+ return true;+ }++ var migrated = await context.AliasVaultUsers+ .Where(u => u.Id == userId)+ .Select(u => context.VaultManifestAccessKeys.Any(k => k.UserId == userId) || context.VaultManifests.Any(m => m.OwnerGroupId == u.PersonalGroupId && m.StorageFormat == VaultManifestBase.ManifestStorageFormat))+ .FirstOrDefaultAsync();++ if (migrated)+ {+ cache.Set(CachePrefixMigrated + userId, true, MigratedCacheLifetime);+ }++ return migrated;}++ /// <summary>+ /// Drops the cached migration state of a user, for test endpoints that turn an account back into a legacy one.+ /// </summary>+ /// <param name="cache">Memory cache.</param>+ /// <param name="userId">The id of the user.</param>+ public static void ForgetMigrationState(IMemoryCache cache, string userId) => cache.Remove(CachePrefixMigrated + userId);++ /// <summary>+ /// The HTTP 426 response a v1 client gets for an account it can no longer serve.+ /// </summary>+ /// <returns>The 426 result.</returns>+ public static ObjectResult UpgradeRequiredResult() => new(new { error = "UPGRADE_REQUIRED", message = "Your client is out of date. Please update to access this vault." }) { StatusCode = StatusCodes.Status426UpgradeRequired };}diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.csindex 4bc61deed..bd698578f 100644--- a/apps/server/AliasVault.Api/Program.cs+++ b/apps/server/AliasVault.Api/Program.cs@@ -12,6 +12,7 @@ using System.Text.Json;using AliasServerDb;using AliasServerDb.Configuration;using AliasVault.Api;+using AliasVault.Api.Filters;using AliasVault.Api.Helpers;using AliasVault.Api.Jwt;using AliasVault.Api.Services;@@ -164,7 +165,11 @@ builder.Services.AddCors(options =>.AllowAnyHeader());});-builder.Services.AddControllers(options => options.InputFormatters.Insert(0, new BinaryFrameInputFormatter()))+builder.Services.AddControllers(options =>+ {+ options.InputFormatters.Insert(0, new BinaryFrameInputFormatter());+ options.Filters.Add<LegacyApiGuardFilter>();+ }).AddJsonOptions(options =>{// Ensure consistent date formatting regardless of server localediff --git a/apps/web/tests/e2e/11-authentication.spec.ts b/apps/web/tests/e2e/11-authentication.spec.tsindex 3093b34aa..0fb940894 100644--- a/apps/web/tests/e2e/11-authentication.spec.ts+++ b/apps/web/tests/e2e/11-authentication.spec.ts@@ -48,4 +48,53 @@ test.describe('11. Authentication', () => {await app.expectItemView('Return after unlock');});});++ test('11.4 should refuse every v1 endpoint for a v2 account', async ({ apiUrl, testUser }) => {+ /**+ * Call a v1 endpoint, authenticated as the test user unless the token is null.+ */+ const v1 = (method: string, path: string, body?: unknown, token: string | null = testUser.token): Promise<Response> => fetch(`${apiUrl}/v1/${path}`, {+ method,+ headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },+ body: body === undefined ? undefined : JSON.stringify(body),+ });++ await test.step('the status endpoint answers, reporting the client as unsupported', async () => {+ const status = await v1('GET', 'Auth/status');+ expect(status.status).toBe(200);+ expect(((await status.json()) as { clientVersionSupported: boolean }).clientVersionSupported).toBe(false);+ });++ await test.step('authenticated endpoints are refused', async () => {+ const requests: [string, string, unknown?][] = [+ ['GET', 'Vault'],+ ['GET', 'Auth/change-password/initiate'],+ ['GET', 'TwoFactorAuth/status'],+ ['POST', 'TwoFactorAuth/enable'],+ ['POST', 'TwoFactorAuth/disable', '000000'],+ ['GET', 'Security/sessions'],+ ['GET', 'Security/authlogs'],+ ['GET', 'EmailBox/[email protected]'],+ ['GET', 'Email/1'],+ ['DELETE', 'Email/1'],+ ['POST', 'Identity/CheckEmail/[email protected]'],+ ['GET', 'Favicon/Extract?url=https://example.com'],+ ];+ for (const [method, path, body] of requests) {+ expect((await v1(method, path, body)).status, `${method} /v1/${path}`).toBe(426);+ }+ });++ await test.step('sign-in endpoints are refused', async () => {+ const proof = { username: testUser.username, clientPublicEphemeral: 'aa', clientSessionProof: 'aa', rememberMe: false };+ expect((await v1('POST', 'Auth/login', { username: testUser.username }, null)).status).toBe(426);+ expect((await v1('POST', 'Auth/validate', proof, null)).status).toBe(426);+ expect((await v1('POST', 'Auth/validate-2fa', { ...proof, code2Fa: 123456 }, null)).status).toBe(426);+ expect((await v1('POST', 'Auth/refresh', { token: testUser.token, refreshToken: 'unknown' }, null)).status).toBe(426);+ });++ await test.step('logging out still works', async () => {+ expect((await v1('POST', 'Auth/revoke', { token: testUser.token, refreshToken: 'unknown' }, null)).status).toBe(200);+ });+ });});diff --git a/apps/web/tests/e2e/90-vault-upgrade.spec.ts b/apps/web/tests/e2e/90-vault-upgrade.spec.tsindex cd042227c..a9bb9a352 100644--- a/apps/web/tests/e2e/90-vault-upgrade.spec.ts+++ b/apps/web/tests/e2e/90-vault-upgrade.spec.ts@@ -289,8 +289,10 @@ test.describe('90. Vault upgrades', () => {return ((await response.json()) as { encryptionType: string }).encryptionType;};- await test.step('the upgraded vault still has the verifier of the 0.1.0 vault', async () => {+ await test.step('the upgraded vault still has the verifier of the 0.1.0 vault, which v1 may no longer use', async () => {expect(await encryptionType()).toBe('Argon2Id');+ const v1 = await fetch(`${apiUrl}/v1/Auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: testUser.username }) });+ expect(v1.status).toBe(426);});await test.step('a password login replaces it with the split verifier', async () => {