Skip to content

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

Bump unlock key LastUsedAt (#2159)

Leendert de Borst4090fae51162
diff --git a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
index 39a9efb7c..7113bd74c 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
@@ -818,10 +818,10 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Validate the SRP session (actual password check).
await using var context = await dbContextFactory.CreateDbContextAsync();
- var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
- if (serverSession is null)
+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (srpResult.Session is null)
{
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, srpResult.FailureReason);
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
}
@@ -983,21 +983,21 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Validate the SRP session (actual password check).
await using var context = await dbContextFactory.CreateDbContextAsync();
- var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
- if (serverSession is null)
+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (srpResult.Session is null)
{
- if (activeSessionFound)
+ if (srpResult.ActiveSessionFound)
{
// Incorrect password: increment failed login attempts which then locks out
// the account when the limit is reached.
await userManager.AccessFailedAsync(user);
}
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, srpResult.FailureReason);
return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
}
- return (user, serverSession, null);
+ return (user, srpResult.Session, null);
}
/// <summary>
diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
index e06a24a16..377fd4de9 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
@@ -247,17 +247,17 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
}
// Validate the SRP session (actual password check).
- var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
- if (serverSession is null)
+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
+ if (srpResult.Session is null)
{
- if (activeSessionFound)
+ if (srpResult.ActiveSessionFound)
{
// The password was wrong: increment failed login attempts which then locks out
// the account when the limit is reached.
await GetUserManager().AccessFailedAsync(user);
}
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, srpResult.FailureReason);
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index 802d9a860..80f4b798f 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -612,17 +612,17 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
}
// Validate the SRP session (actual current password check).
- var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
- if (serverSession is null)
+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
+ if (srpResult.Session is null)
{
- if (activeSessionFound)
+ if (srpResult.ActiveSessionFound)
{
// The password was wrong: increment failed login attempts which then locks out
// the account when the limit is reached.
await userManager.AccessFailedAsync(user);
}
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, srpResult.FailureReason);
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
}
@@ -993,10 +993,10 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Validate the SRP session (actual password check).
await using var context = await dbContextFactory.CreateDbContextAsync();
- var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
- if (serverSession is null)
+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (srpResult.Session is null)
{
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, srpResult.FailureReason);
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
}
@@ -1244,21 +1244,24 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Validate the SRP session (actual password check).
await using var context = await dbContextFactory.CreateDbContextAsync();
- var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
- if (serverSession is null)
+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (srpResult.Session is null)
{
- if (activeSessionFound)
+ if (srpResult.ActiveSessionFound)
{
// Incorrect password: increment failed login attempts which then locks out
// the account when the limit is reached.
await userManager.AccessFailedAsync(user);
}
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, srpResult.FailureReason);
return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
}
- return (user, serverSession, null);
+ // Record usage of this unlock method for statistics purposes.
+ await AuthHelper.TouchUnlockKeyLastUsedAsync(context, srpResult.UnlockKeyId, timeProvider.UtcNow);
+
+ return (user, srpResult.Session, null);
}
/// <summary>
diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
index dd40d212d..76d49432a 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
@@ -451,10 +451,10 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
}
// Validate the SRP session (actual password check).
- var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, me, model.ClientPublicEphemeral, model.ClientSessionProof);
- if (serverSession is null)
+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, me, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (srpResult.Session is null)
{
- await authLoggingService.LogAuthEventFailAsync(me.UserName!, AuthEventType.SharedVaultDeletion, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ await authLoggingService.LogAuthEventFailAsync(me.UserName!, AuthEventType.SharedVaultDeletion, srpResult.FailureReason);
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
index eb81c14b6..2c9f71c97 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
@@ -64,7 +64,7 @@ public class VaultKeyController(IAliasServerDbContextFactory dbContextFactory, U
.FirstOrDefaultAsync();
// Get the KEK derivation parameters.
- var (salt, _, encryptionType, encryptionSettings) = VaultKeyMetadata.Parse(unlockKey.Metadata).RequireSrpCredentials();
+ var credentials = VaultKeyMetadata.Parse(unlockKey.Metadata).RequireSrpCredentials();
return Ok(new VaultKeyGetResponse
{
@@ -75,9 +75,9 @@ public class VaultKeyController(IAliasServerDbContextFactory dbContextFactory, U
EncryptedVek = encryptedVek,
AccountPublicKey = accountKeypair?.PublicKey,
EncryptedAccountPrivateKey = accountKeypair?.EncryptedPrivateKey,
- Salt = salt,
- EncryptionType = encryptionType,
- EncryptionSettings = encryptionSettings,
+ Salt = credentials.Salt,
+ EncryptionType = credentials.EncryptionType,
+ EncryptionSettings = credentials.EncryptionSettings,
},
});
}
diff --git a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs
index e0da77294..0bf4cca29 100644
--- a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs
+++ b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs
@@ -9,6 +9,7 @@ namespace AliasVault.Api.Helpers;
using AliasServerDb;
using AliasVault.Api.Headers;
+using AliasVault.Api.Models;
using AliasVault.Cryptography.Client;
using AliasVault.Shared.Models.Enums;
using Microsoft.EntityFrameworkCore;
@@ -38,33 +39,33 @@ public static class AuthHelper
/// <param name="user">The user object.</param>
/// <param name="clientEphemeral">The client ephemeral value.</param>
/// <param name="clientSessionProof">The client session proof.</param>
- /// <returns>Tuple with the SrpSession (null if validation failed) and whether an active SRP session existed.</returns>
- public static async Task<(SrpSession? Session, bool ActiveSessionFound)> ValidateSrpSessionAsync(IMemoryCache cache, AliasServerDbContext context, AliasVaultUser user, string clientEphemeral, string clientSessionProof)
+ /// <returns>The validation outcome, carrying the unlock method whose secret was proven.</returns>
+ public static async Task<SrpValidationResult> ValidateSrpSessionAsync(IMemoryCache cache, AliasServerDbContext context, AliasVaultUser user, string clientEphemeral, string clientSessionProof)
{
// Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).
var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();
if (!cache.TryGetValue(CachePrefixEphemeral + srpIdentity, out var serverSecretEphemeral) || serverSecretEphemeral is not string)
{
- // No login was initiated for this user, or the server ephemeral has expired. Return false to indicate that no active session was found.
- return (null, false);
+ // No login was initiated for this user, or the server ephemeral has expired.
+ return new SrpValidationResult(null, false, null);
}
// Retrieve latest vault of user which contains the current salt and verifier.
- var latestVaultEncryptionSettings = await GetUserLatestVaultEncryptionSettingsAsync(context, user);
+ var credentials = await GetUserLatestVaultEncryptionSettingsAsync(context, user);
// Use SrpIdentity for the SRP session derivation. This is the fixed identity that was used
// when the verifier was originally created, ensuring username changes don't break authentication.
var serverSession = Srp.DeriveSessionServer(
serverSecretEphemeral.ToString() ?? string.Empty,
clientEphemeral,
- latestVaultEncryptionSettings.Salt,
+ credentials.Salt,
srpIdentity,
- latestVaultEncryptionSettings.Verifier,
+ credentials.Verifier,
clientSessionProof);
// If validation failed, serverSession will be null here.
- return (serverSession, true);
+ return new SrpValidationResult(serverSession, true, credentials.UnlockKeyId);
}
/// <summary>
@@ -72,14 +73,14 @@ public static class AuthHelper
/// </summary>
/// <param name="context">Database context.</param>
/// <param name="user">User object.</param>
- /// <returns>Tuple with salt, verifier, encryption type and encryption settings.</returns>
- public static async Task<(string Salt, string Verifier, string EncryptionType, string EncryptionSettings)> GetUserLatestVaultEncryptionSettingsAsync(AliasServerDbContext context, AliasVaultUser user)
+ /// <returns>The credentials the user authenticates with, and the unlock key they came from.</returns>
+ public static async Task<UserSrpCredentials> GetUserLatestVaultEncryptionSettingsAsync(AliasServerDbContext context, AliasVaultUser user)
{
// Get the user's current SRP salt/verifier and key derivation settings for the account-key KEK/VEK model.
var passwordKey = await context.UserUnlockKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password);
if (passwordKey is not null)
{
- return VaultKeyMetadata.Parse(passwordKey.Metadata).RequireSrpCredentials();
+ return VaultKeyMetadata.Parse(passwordKey.Metadata).RequireSrpCredentials() with { UnlockKeyId = passwordKey.Id };
}
// Get the user's current SRP salt/verifier and key derivation settings for the legacy model.
@@ -89,7 +90,25 @@ public static class AuthHelper
.FirstAsync();
// The SRP columns are null once a user moved to the unlock-key model, which the branch above already covers.
- return (latestVault.Salt ?? string.Empty, latestVault.Verifier ?? string.Empty, latestVault.EncryptionType ?? string.Empty, latestVault.EncryptionSettings ?? string.Empty);
+ return new UserSrpCredentials(latestVault.Salt ?? string.Empty, latestVault.Verifier ?? string.Empty, latestVault.EncryptionType ?? string.Empty, latestVault.EncryptionSettings ?? string.Empty);
+ }
+
+ /// <summary>
+ /// Records that an unlock method was successfully used to authenticate, for usage statistics across the
+ /// unlock methods a user has enrolled.
+ /// </summary>
+ /// <param name="context">Database context.</param>
+ /// <param name="unlockKeyId">The unlock key that was proven, as returned by <see cref="ValidateSrpSessionAsync"/>.</param>
+ /// <param name="now">The timestamp to record.</param>
+ /// <returns>Task.</returns>
+ public static async Task TouchUnlockKeyLastUsedAsync(AliasServerDbContext context, Guid? unlockKeyId, DateTime now)
+ {
+ if (unlockKeyId is null)
+ {
+ return;
+ }
+
+ await context.UserUnlockKeys.Where(x => x.Id == unlockKeyId.Value).ExecuteUpdateAsync(s => s.SetProperty(x => x.LastUsedAt, now));
}
/// <summary>
diff --git a/apps/server/AliasVault.Api/Models/SrpValidationResult.cs b/apps/server/AliasVault.Api/Models/SrpValidationResult.cs
new file mode 100644
index 000000000..645d2714b
--- /dev/null
+++ b/apps/server/AliasVault.Api/Models/SrpValidationResult.cs
@@ -0,0 +1,26 @@
+//-----------------------------------------------------------------------
+// <copyright file="SrpValidationResult.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.Models;
+
+using AliasServerDb;
+using SecureRemotePassword;
+
+/// <summary>
+/// The outcome of checking a client's SRP proof against the credentials of the unlock method it authenticates with.
+/// </summary>
+/// <param name="Session">The derived server session, or null when the proof did not validate.</param>
+/// <param name="ActiveSessionFound">Whether a server ephemeral was still cached, i.e. whether the client actually initiated this exchange.</param>
+/// <param name="UnlockKeyId">The unlock method whose secret was proven, or null for a legacy user that has no unlock key yet.</param>
+public sealed record SrpValidationResult(SrpSession? Session, bool ActiveSessionFound, Guid? UnlockKeyId)
+{
+ /// <summary>
+ /// Gets the reason to log when <see cref="Session"/> is null: a cached ephemeral means the client got the
+ /// secret wrong, no ephemeral means it never initiated the exchange or took too long over it.
+ /// </summary>
+ public AuthFailureReason FailureReason => ActiveSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound;
+}
diff --git a/apps/server/Databases/AliasServerDb/UserSrpCredentials.cs b/apps/server/Databases/AliasServerDb/UserSrpCredentials.cs
new file mode 100644
index 000000000..9a1e4e395
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/UserSrpCredentials.cs
@@ -0,0 +1,18 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserSrpCredentials.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 AliasServerDb;
+
+/// <summary>
+/// The SRP credentials and KEK derivation parameters that one unlock method authenticates with.
+/// </summary>
+/// <param name="Salt">The SRP salt.</param>
+/// <param name="Verifier">The SRP verifier the server checks a client's proof against.</param>
+/// <param name="EncryptionType">The KDF the client derives its KEK with, e.g. Argon2Id.</param>
+/// <param name="EncryptionSettings">The parameters belonging to the KDF named by <paramref name="EncryptionType"/>.</param>
+/// <param name="UnlockKeyId">The <see cref="UserUnlockKey"/> these credentials came from, or null for a legacy user whose credentials still live on the vault manifest.</param>
+public sealed record UserSrpCredentials(string Salt, string Verifier, string EncryptionType, string EncryptionSettings, Guid? UnlockKeyId = null);
diff --git a/apps/server/Databases/AliasServerDb/VaultKeyMetadata.cs b/apps/server/Databases/AliasServerDb/VaultKeyMetadata.cs
index 6b5297d60..7febb8210 100644
--- a/apps/server/Databases/AliasServerDb/VaultKeyMetadata.cs
+++ b/apps/server/Databases/AliasServerDb/VaultKeyMetadata.cs
@@ -74,14 +74,14 @@ public sealed class VaultKeyMetadata
/// <summary>
/// Helper method to return the SRP credentials and KDF parameters.
/// </summary>
- /// <returns>Tuple with salt, verifier, encryption type and encryption settings.</returns>
- public (string Salt, string SrpVerifier, string EncryptionType, string EncryptionSettings) RequireSrpCredentials()
+ /// <returns>The credentials, without the unlock key id which only the caller that loaded the row knows.</returns>
+ public UserSrpCredentials RequireSrpCredentials()
{
if (Salt is null || SrpVerifier is null || EncryptionType is null || EncryptionSettings is null)
{
throw new InvalidOperationException("Vault key metadata is missing SRP credentials.");
}
- return (Salt, SrpVerifier, EncryptionType, EncryptionSettings);
+ return new UserSrpCredentials(Salt, SrpVerifier, EncryptionType, EncryptionSettings);
}
}