Skip to content

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

Update API DTO's to include algorithm identifiers and cleanup (#2469)

Leendert de Borst13965b068fb2
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/AuthLogsSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/AuthLogsSettings.tsx
index 6f84117e9..0b4e05458 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/security/AuthLogsSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/security/AuthLogsSettings.tsx
@@ -51,8 +51,8 @@ const AuthLogsSettings: React.FC = () => {
<p className="p-4 text-sm text-gray-500 dark:text-gray-400">{t('settings.securitySettings.authLogs.noLogs')}</p>
) : (
<div className="divide-y divide-gray-200 dark:divide-gray-700">
- {logs.map((log) => (
- <div key={log.id} className="p-4">
+ {logs.map((log, index) => (
+ <div key={index} className="p-4">
<div className="flex items-center justify-between gap-3">
<p className="font-medium text-gray-900 dark:text-white break-words">{authEventTypeName(log.eventType)}</p>
<span className={`shrink-0 text-sm font-semibold ${log.isSuccess ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}>
diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx
index a32875c96..d36f7e7bd 100644
--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx
@@ -1,5 +1,6 @@
import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
import { MobileLoginProtocol } from '@aliasvault/client/auth/MobileLoginProtocol';
+import { VaultKeyAlgorithm, type MobileLoginDetailsResponse, type MobileLoginRequestReference, type MobileLoginSubmitRequest } from '@aliasvault/models/webapi';
import { Ionicons } from '@expo/vector-icons';
import { router } from 'expo-router';
import { useState, useEffect, useRef } from 'react';
@@ -22,8 +23,6 @@ import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
-import type { MobileLoginDetailsResponse, MobileLoginRequestReference, MobileLoginSubmitRequest } from '@aliasvault/models/webapi';
-
/**
* A mobile login request whose public key was checked against the scanned QR code.
*/
@@ -114,6 +113,12 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
return;
}
+ if (details.algorithm !== VaultKeyAlgorithm.RsaOaepSha256) {
+ console.error(`Mobile login asks for an unsupported algorithm '${details.algorithm}'`);
+ showAlert(t('common.error'), t('common.errors.clientNotSupported'), () => router.replace('/(tabs)/settings'));
+ return;
+ }
+
const verificationCode = await MobileLoginProtocol.computeVerificationCode(details.clientPublicKey);
setRequest({ details, verificationCode, codeChoices: buildCodeChoices(verificationCode) });
} catch (error) {
@@ -183,7 +188,7 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
// Encrypt with the public key that was verified against the QR code.
const encryptedAccountKey = await NativeVaultManager.encryptAccountKeyForMobileLogin(request.details.clientPublicKey);
- const submitRequest: MobileLoginSubmitRequest = { requestId: scan.requestId, encryptedAccountKey };
+ const submitRequest: MobileLoginSubmitRequest = { requestId: scan.requestId, encryptedAccountKey, algorithm: request.details.algorithm };
await webApi.post<MobileLoginSubmitRequest, void>('auth/mobile-login/submit', submitRequest, false);
showResult(true);
diff --git a/apps/mobile-app/app/(tabs)/settings/security/auth-logs.tsx b/apps/mobile-app/app/(tabs)/settings/security/auth-logs.tsx
index 21ad19f31..013bc21b6 100644
--- a/apps/mobile-app/app/(tabs)/settings/security/auth-logs.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/security/auth-logs.tsx
@@ -152,11 +152,11 @@ export default function AuthLogsScreen() : React.ReactNode {
);
}
- return logs.map((item) => {
+ return logs.map((item, index) => {
const eventType = authEventTypeName(item.eventType);
return (
- <View key={item.id} style={styles.logItem}>
+ <View key={index} style={styles.logItem}>
<View style={styles.logHeader}>
<ThemedText style={styles.eventType}>{eventType}</ThemedText>
<ThemedText style={[
diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.ts
index 146f7d4b4..bd22b583c 100644
--- a/apps/mobile-app/hooks/useVaultMutate.ts
+++ b/apps/mobile-app/hooks/useVaultMutate.ts
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import Toast from 'react-native-toast-message';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
-import type { PasswordChangeInitiateResponse, PasswordChangeRequest } from '@aliasvault/models/webapi';
+import { VaultKeyAlgorithm, type PasswordChangeInitiateResponse, type PasswordChangeRequest } from '@aliasvault/models/webapi';
import { MasterPasswordService, PasswordChangedElsewhereError } from '@aliasvault/client/auth/MasterPasswordService';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
import { VaultSyncHoldReason } from '@aliasvault/client/sync/VaultSyncHold';
@@ -154,6 +154,7 @@ export function useVaultMutate() : {
newPasswordSalt: next.salt,
newPasswordVerifier: next.verifier,
newEncryptedAccountKey,
+ newEncryptedAccountKeyAlgorithm: VaultKeyAlgorithm.Aes256Gcm,
newEncryptionType: next.encryptionType,
newEncryptionSettings: next.encryptionSettings,
}, false);
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index b9c797c39..fcc001d47 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -479,6 +479,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
+ if (!VaultKeyAlgorithms.TryParse(model.EncryptedAccountKeyAlgorithm, out var unlockKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(unlockKeyAlgorithm))
+ {
+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
+ }
+
if (!IsValidKekDerivationParams(model.EncryptionType, model.EncryptionSettings) || !WithinSrpCredentialLimits(model.Salt, model.Verifier) || !IsValidSrpIdentity(model.SrpIdentity))
{
return ApiError.Result(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400);
@@ -553,7 +558,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
Id = Guid.NewGuid(),
UserId = user.Id,
Type = UnlockMethodType.Password,
- Algorithm = VaultKeyAlgorithm.Aes256Gcm,
+ Algorithm = unlockKeyAlgorithm,
EncryptedAccountKey = model.EncryptedAccountKey!,
Metadata = new VaultKeyMetadata
{
@@ -686,6 +691,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return ApiError.Result(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400);
}
+ if (!VaultKeyAlgorithms.TryParse(model.NewEncryptedAccountKeyAlgorithm, out var newUnlockKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(newUnlockKeyAlgorithm))
+ {
+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
+ }
+
// Validate the SRP session (actual current password check).
var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, userManager, user, SrpPurpose.PasswordChange, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
if (srpResult.Session is null)
@@ -718,6 +728,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
await writeContext.UserUnlockKeys.Where(x => x.Id == unlockKey.Id).ExecuteUpdateAsync(s => s
.SetProperty(x => x.Metadata, newMetadataJson)
.SetProperty(x => x.EncryptedAccountKey, model.NewEncryptedAccountKey)
+ .SetProperty(x => x.Algorithm, newUnlockKeyAlgorithm)
.SetProperty(x => x.UpdatedAt, now));
// Update the password last changed at timestamp for user.
@@ -854,6 +865,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_INVALID_PUBLIC_KEY, 400);
}
+ if (!VaultKeyAlgorithms.TryParse(model.Algorithm, out var algorithm) || !VaultKeyAlgorithms.IsAsymmetric(algorithm))
+ {
+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
+ }
+
// Check the IP blocklist.
if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))
{
@@ -880,6 +896,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
{
Id = requestId,
ClientPublicKey = model.ClientPublicKey,
+ Algorithm = algorithm,
PollSecretHash = MobileLoginRequestHelper.HashPollSecret(pollSecret),
CreatedAt = timeProvider.GetUtcNow().UtcDateTime,
ClientIpAddress = ipAddress,
@@ -1021,6 +1038,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return Ok(new MobileLoginDetailsResponse
{
ClientPublicKey = loginRequest.ClientPublicKey,
+ Algorithm = VaultKeyAlgorithms.ToToken(loginRequest.Algorithm),
IpAddress = loginRequest.ClientIpAddress,
Location = RequestClientInfo.DetermineCountry(),
ClientName = loginRequest.ClientName,
@@ -1054,6 +1072,12 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return MobileLoginNotAwaitingApproval(loginRequest);
}
+ // The Account Key must be encrypted with the algorithm the initiating client asked for.
+ if (model.Algorithm != VaultKeyAlgorithms.ToToken(loginRequest.Algorithm))
+ {
+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
+ }
+
// Store the answer in one transaction.
var fulfilledAt = timeProvider.GetUtcNow().UtcDateTime;
var mobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
index dd8418610..663aafef3 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
@@ -120,9 +120,9 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
UserId = m.UserId,
Username = usernames.GetValueOrDefault(m.UserId, string.Empty),
Role = KebabCaseEnumConverter.ToToken(m.Role),
- PublicKeyId = canAdminister ? publicKeys.GetValueOrDefault(m.UserId)?.PublicKeyId : null,
- PublicKey = canAdminister ? publicKeys.GetValueOrDefault(m.UserId)?.PublicKey : null,
- PublicKeySignature = canAdminister ? publicKeys.GetValueOrDefault(m.UserId)?.PublicKeySignature : null,
+ AccountPublicKeyId = canAdminister ? publicKeys.GetValueOrDefault(m.UserId)?.PublicKeyId : null,
+ AccountPublicKey = canAdminister ? publicKeys.GetValueOrDefault(m.UserId)?.PublicKey : null,
+ AccountPublicKeySignature = canAdminister ? publicKeys.GetValueOrDefault(m.UserId)?.PublicKeySignature : null,
SigningPublicKey = canAdminister ? publicKeys.GetValueOrDefault(m.UserId)?.SigningPublicKey : null,
})],
});
@@ -166,7 +166,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
// The public key the user's own grant is encrypted for must be one of theirs.
var selfPublicKeyId = await context.UserGrantKeys
- .Where(x => x.UserId == me.Id && x.PublicKey == model.SelfPublicKey)
+ .Where(x => x.UserId == me.Id && x.PublicKey == model.SelfAccountPublicKey)
.Select(x => (Guid?)x.Id)
.FirstOrDefaultAsync();
@@ -177,7 +177,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
// The caller signs their own grant like any other, so a reader can tell it was not made up by somebody else.
var signerPublicKey = await GrantHelper.GetPrimarySigningKeyAsync(context, me.Id);
- if (!Signing.Verify(signerPublicKey, Signing.GrantMessage(model.ManifestId, 0, me.Id, model.SelfPublicKey, model.Algorithm, model.SelfEncryptedVek), model.SelfGrantSignature))
+ if (!Signing.Verify(signerPublicKey, Signing.GrantMessage(model.ManifestId, 0, me.Id, model.SelfAccountPublicKey, model.Algorithm, model.SelfEncryptedVek), model.SelfGrantSignature))
{
return ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);
}
@@ -282,7 +282,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
}
// The key it was encrypted for must really be theirs.
- var recipientPublicKey = await context.UserGrantKeys.Where(k => k.Id == model.Grant.RecipientPublicKeyId && k.UserId == model.UserId).Select(k => k.PublicKey).FirstOrDefaultAsync();
+ var recipientPublicKey = await context.UserGrantKeys.Where(k => k.Id == model.Grant.RecipientAccountPublicKeyId && k.UserId == model.UserId).Select(k => k.PublicKey).FirstOrDefaultAsync();
if (recipientPublicKey is null)
{
return ApiError.Result(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404);
@@ -319,7 +319,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
EncryptedVek = model.Grant.EncryptedVek,
EncryptedName = model.Grant.EncryptedName,
EncryptedNameSignature = model.Grant.EncryptedName is null ? null : model.Grant.EncryptedNameSignature,
- UserGrantKeyId = model.Grant.RecipientPublicKeyId,
+ UserGrantKeyId = model.Grant.RecipientAccountPublicKeyId,
GrantSignature = model.Grant.Signature,
GrantSignerPublicKey = signerPublicKey,
VaultKeyVersion = manifestKeyVersion.Value,
@@ -730,7 +730,8 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
i.EncryptedName,
i.EncryptedNameSignature,
i.GrantSignerPublicKey,
- RecipientPublicKey = i.UserGrantKey != null ? i.UserGrantKey.PublicKey : null,
+ i.Algorithm,
+ RecipientAccountPublicKey = i.UserGrantKey != null ? i.UserGrantKey.PublicKey : null,
})
.ToListAsync();
@@ -757,7 +758,8 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
EncryptedName = i.EncryptedName,
EncryptedNameSignature = i.EncryptedNameSignature,
SignerPublicKey = i.GrantSignerPublicKey,
- RecipientPublicKey = i.RecipientPublicKey,
+ RecipientAccountPublicKey = i.RecipientAccountPublicKey,
+ Algorithm = VaultKeyAlgorithms.ToToken(i.Algorithm),
})];
}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs b/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs
index 21e36bea6..3f5e7c16f 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs
@@ -107,7 +107,6 @@ public class SecurityController(IAliasServerDbContextFactory dbContextFactory, U
.Take(50)
.Select(x => new AuthLogModel
{
- Id = x.Id,
Timestamp = x.Timestamp,
EventType = x.EventType,
Username = x.Username,
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
index aab722d67..aa0e5e62b 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
@@ -133,7 +133,7 @@ public class VaultController(
.ToDictionary(g => g.Key, g => g.Select(x => new BlobReference { Hash = x.Hash, Category = x.Category, SizeBytes = x.SizeBytes }).ToList());
var accessKeysByManifest = await GetAccessKeysAsync(context, user.Id, manifestIds);
- var encryptionPublicKeys = await GetEncryptionPublicKeysAsync(context, accessKeysByManifest.Values.Where(g => g.UserGrantKeyId != null).Select(g => g.UserGrantKeyId!.Value));
+ var accountPublicKeys = await GetAccountPublicKeysAsync(context, accessKeysByManifest.Values.Where(g => g.UserGrantKeyId != null).Select(g => g.UserGrantKeyId!.Value));
var administeredGroupIds = await GroupHelper.GetAdministeredGroupIdsAsync(context, user.Id);
var manifests = latestManifests.Select(m =>
@@ -153,7 +153,7 @@ public class VaultController(
KeyType = accessKey != null ? ManifestKeyTypes.ToToken(accessKey.Type) : null,
EncryptedVek = grant?.EncryptedVek,
Algorithm = grant != null ? VaultKeyAlgorithms.ToToken(grant.Algorithm) : null,
- EncryptionPublicKey = grant?.UserGrantKeyId != null ? encryptionPublicKeys.GetValueOrDefault(grant.UserGrantKeyId.Value) : null,
+ AccountPublicKey = grant?.UserGrantKeyId != null ? accountPublicKeys.GetValueOrDefault(grant.UserGrantKeyId.Value) : null,
GrantSignature = grant?.GrantSignature,
GrantSignerUserId = grant?.GrantSignerUserId,
GrantSignerPublicKey = grant?.GrantSignerPublicKey,
@@ -225,7 +225,7 @@ public class VaultController(
manifest.KeyVersion = accessKey.KeyVersion;
if (accessKey.UserGrantKeyId != null)
{
- manifest.EncryptionPublicKey = await context.UserGrantKeys.Where(k => k.Id == accessKey.UserGrantKeyId).Select(k => k.PublicKey).FirstOrDefaultAsync();
+ manifest.AccountPublicKey = await context.UserGrantKeys.Where(k => k.Id == accessKey.UserGrantKeyId).Select(k => k.PublicKey).FirstOrDefaultAsync();
}
}
@@ -399,6 +399,11 @@ public class VaultController(
{
return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
+
+ if (!VaultKeyAlgorithms.TryParse(accountKeys.EncryptedAccountKeyAlgorithm, out var unlockKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(unlockKeyAlgorithm))
+ {
+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
+ }
}
else if (personalWrite != null && !hasExistingUnlockKey)
{
@@ -441,7 +446,12 @@ public class VaultController(
}
// The SMTP service encrypts every incoming mail with the primary delivery key, so a malformed one would lose that mail.
- if (resolved.Any(r => !string.IsNullOrEmpty(r.Write.EncryptionPublicKey) && !RsaPublicKeyValidator.IsValid(r.Write.EncryptionPublicKey)))
+ if (resolved.Any(r => !string.IsNullOrEmpty(r.Write.DeliveryPublicKey) && (!VaultKeyAlgorithms.TryParse(r.Write.DeliveryPublicKeyAlgorithm, out var algorithm) || !VaultKeyAlgorithms.IsAsymmetric(algorithm))))
+ {
+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
+ }
+
+ if (resolved.Any(r => !string.IsNullOrEmpty(r.Write.DeliveryPublicKey) && !RsaPublicKeyValidator.IsValid(r.Write.DeliveryPublicKey)))
{
return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
@@ -532,7 +542,7 @@ public class VaultController(
Id = Guid.NewGuid(),
UserId = user.Id,
Type = UnlockMethodType.Password,
- Algorithm = VaultKeyAlgorithm.Aes256Gcm,
+ Algorithm = VaultKeyAlgorithms.Parse(accountKeys.EncryptedAccountKeyAlgorithm),
EncryptedAccountKey = accountKeys.EncryptedAccountKey!,
Metadata = new VaultKeyMetadata
{
@@ -636,7 +646,7 @@ public class VaultController(
* 6) Delivery keys. A manifest's keypair lives inside the manifest content, so its public half should only
* change in a write that changes that content.
*/
- var publishing = resolved.Where(r => !string.IsNullOrEmpty(r.Write.EncryptionPublicKey)).ToList();
+ var publishing = resolved.Where(r => !string.IsNullOrEmpty(r.Write.DeliveryPublicKey)).ToList();
if (publishing.Count > 0)
{
// Only admins are allowed to publish a new shared manifest's key.
@@ -644,7 +654,7 @@ public class VaultController(
var publishable = await GetAdminAccessSharedManifestIdsAsync(context, user.Id, sharedIds);
foreach (var (mw, row) in publishing.Where(r => r.Row.OwnerGroupId == user.PersonalGroupId || publishable.Contains(r.Row.ManifestId)))
{
- await PublishManifestPublicKeyAsync(context, row.ManifestId, mw.EncryptionPublicKey!);
+ await PublishManifestPublicKeyAsync(context, row.ManifestId, mw.DeliveryPublicKey!, VaultKeyAlgorithms.Parse(mw.DeliveryPublicKeyAlgorithm));
}
// Claim resolution below reads these rows back, so they must be visible to the query.
@@ -914,7 +924,7 @@ public class VaultController(
/// <summary>
/// Gets the account public key each grant's VEK was encrypted with (see <see cref="UserGrantKey"/>).
/// </summary>
- private static async Task<Dictionary<Guid, string>> GetEncryptionPublicKeysAsync(AliasServerDbContext context, IEnumerable<Guid> publicKeyIds)
+ private static async Task<Dictionary<Guid, string>> GetAccountPublicKeysAsync(AliasServerDbContext context, IEnumerable<Guid> publicKeyIds)
{
var ids = publicKeyIds.Distinct().ToList();
if (ids.Count == 0)
@@ -962,7 +972,7 @@ public class VaultController(
/// <returns>True when every change is signed.</returns>
private static async Task<bool> DeliveryKeyChangesAreSignedAsync(AliasServerDbContext context, string userId, List<(ManifestWrite Write, VaultManifest Row)> resolved, AccountKeysUpload? accountKeys)
{
- var publishing = resolved.Where(r => !string.IsNullOrEmpty(r.Write.EncryptionPublicKey)).ToList();
+ var publishing = resolved.Where(r => !string.IsNullOrEmpty(r.Write.DeliveryPublicKey)).ToList();
if (publishing.Count == 0)
{
return true;
@@ -973,8 +983,8 @@ public class VaultController(
// The upgrade push carries the signing key it signs with; it is stored in the same write.
var signingKey = accountKeys?.SigningPublicKey ?? await GrantHelper.GetPrimarySigningKeyAsync(context, userId);
- return publishing.All(r => primaryKeys.GetValueOrDefault(r.Row.ManifestId) == r.Write.EncryptionPublicKey
- || Signing.Verify(signingKey, Signing.DeliveryKeyMessage(r.Row.ManifestId, r.Write.EncryptionPublicKey!, r.Write.CurrentRevision), r.Write.EncryptionPublicKeySignature));
+ return publishing.All(r => primaryKeys.GetValueOrDefault(r.Row.ManifestId) == r.Write.DeliveryPublicKey
+ || Signing.Verify(signingKey, Signing.DeliveryKeyMessage(r.Row.ManifestId, r.Write.DeliveryPublicKey!, r.Write.CurrentRevision), r.Write.DeliveryPublicKeySignature));
}
/// <summary>
@@ -1373,7 +1383,8 @@ public class VaultController(
/// admin republishing must land on the same scope rather than a per-user copy.
/// </param>
/// <param name="newPublicKey">The public key to publish.</param>
- private async Task PublishManifestPublicKeyAsync(AliasServerDbContext context, Guid vaultManifestId, string newPublicKey)
+ /// <param name="algorithm">The algorithm of the public key.</param>
+ private async Task PublishManifestPublicKeyAsync(AliasServerDbContext context, Guid vaultManifestId, string newPublicKey, VaultKeyAlgorithm algorithm)
{
var scope = context.VaultManifestDeliveryKeys.Where(x => x.VaultManifestId == vaultManifestId);
@@ -1401,7 +1412,7 @@ public class VaultController(
context.VaultManifestDeliveryKeys.Add(new VaultManifestDeliveryKey
{
VaultManifestId = vaultManifestId,
- Algorithm = VaultKeyAlgorithm.RsaOaepSha256,
+ Algorithm = algorithm,
PublicKey = newPublicKey,
IsPrimary = true,
CreatedAt = timeProvider.GetUtcNow().UtcDateTime,
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
index ce3aa5b50..323fef8db 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
@@ -76,6 +76,7 @@ public class VaultKeyController(IAliasServerDbContextFactory dbContextFactory, U
{
Type = UnlockMethodTypes.ToToken(unlockKey.Type),
EncryptedAccountKey = unlockKey.EncryptedAccountKey,
+ Algorithm = VaultKeyAlgorithms.ToToken(unlockKey.Algorithm),
EncryptedVek = encryptedVek,
AccountPublicKey = accountKeypair?.PublicKey,
EncryptedAccountPrivateKey = accountKeypair?.EncryptedPrivateKey,
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginDetailsResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginDetailsResponse.cs
index 2b4e1cb2a..136a1ff34 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginDetailsResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginDetailsResponse.cs
@@ -17,6 +17,11 @@ public class MobileLoginDetailsResponse
/// </summary>
public required string ClientPublicKey { get; set; }
+ /// <summary>
+ /// Gets or sets the algorithm to encrypt the Account Key with, as a VaultKeyAlgorithm token.
+ /// </summary>
+ public required string Algorithm { get; set; }
+
/// <summary>
/// Gets or sets the anonymized IP address the request came from.
/// </summary>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginInitiateRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginInitiateRequest.cs
index b592010c1..b87fad4ff 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginInitiateRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginInitiateRequest.cs
@@ -19,4 +19,10 @@ public class MobileLoginInitiateRequest
/// </summary>
[Required]
public required string ClientPublicKey { get; set; }
+
+ /// <summary>
+ /// Gets or sets the algorithm the Account Key is to be encrypted with, as a VaultKeyAlgorithm token.
+ /// </summary>
+ [Required]
+ public required string Algorithm { get; set; }
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginSubmitRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginSubmitRequest.cs
index 5d270e201..b1255d985 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginSubmitRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginSubmitRequest.cs
@@ -27,4 +27,10 @@ public class MobileLoginSubmitRequest
[Required]
[StringLength(1024)]
public required string EncryptedAccountKey { get; set; }
+
+ /// <summary>
+ /// Gets or sets the algorithm of <see cref="EncryptedAccountKey"/>, as a VaultKeyAlgorithm token.
+ /// </summary>
+ [Required]
+ public required string Algorithm { get; set; }
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs
index 4e9636b5c..f37b9dbc7 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs
@@ -29,6 +29,9 @@ public class PasswordChangeRequest
/// account keypair and grants are untouched by a password change.</summary>
public required string NewEncryptedAccountKey { get; set; }
+ /// <summary>Gets or sets the algorithm of <see cref="NewEncryptedAccountKey"/>, as a VaultKeyAlgorithm token.</summary>
+ public required string NewEncryptedAccountKeyAlgorithm { get; set; }
+
/// <summary>Gets or sets the KDF type the client derived the new unlock key with.</summary>
public required string NewEncryptionType { get; set; }
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs
index 9c3f7e45d..f2c55ed35 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs
@@ -112,6 +112,11 @@ public class RegisterRequest
/// </summary>
public string? AccountPublicKeySignature { get; }
+ /// <summary>
+ /// Gets the algorithm of <see cref="EncryptedAccountKey"/>, as a VaultKeyAlgorithm token.
+ /// </summary>
+ public string? EncryptedAccountKeyAlgorithm { get; init; }
+
/// <summary>
/// Gets the registration invite code, required when public registration is disabled.
/// </summary>
@@ -120,7 +125,7 @@ public class RegisterRequest
/// <summary>
/// Gets a value indicating whether the client sent the complete account key hierarchy. A partial one is not usable.
/// </summary>
- public bool HasCompleteAccountKeys => !string.IsNullOrEmpty(EncryptedVek) && !string.IsNullOrEmpty(EncryptedAccountKey) && !string.IsNullOrEmpty(AccountPublicKey) && !string.IsNullOrEmpty(EncryptedAccountPrivateKey)
+ public bool HasCompleteAccountKeys => !string.IsNullOrEmpty(EncryptedVek) && !string.IsNullOrEmpty(EncryptedAccountKey) && !string.IsNullOrEmpty(EncryptedAccountKeyAlgorithm) && !string.IsNullOrEmpty(AccountPublicKey) && !string.IsNullOrEmpty(EncryptedAccountPrivateKey)
&& !string.IsNullOrEmpty(SigningPublicKey) && !string.IsNullOrEmpty(EncryptedSigningPrivateKey) && !string.IsNullOrEmpty(AccountPublicKeySignature);
/// <summary>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs
index efdc2d3fc..6890e653f 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs
@@ -18,6 +18,9 @@ public class VaultKeyResponse
/// <summary>Gets or sets the Account Key encrypted with the KEK derived from the unlock method.</summary>
public required string EncryptedAccountKey { get; set; }
+ /// <summary>Gets or sets the algorithm of <see cref="EncryptedAccountKey"/>, as a VaultKeyAlgorithm token.</summary>
+ public required string Algorithm { get; set; }
+
/// <summary>Gets or sets the account private key encrypted with the Account Key.</summary>
public string? EncryptedAccountPrivateKey { get; set; }
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
index 5ed1d08e5..4841c71da 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
@@ -23,7 +23,7 @@ public class CreateSharedManifestRequest
/// <summary>
/// Gets or sets the user's own account public key (JWK) the <see cref="SelfEncryptedVek"/> was encrypted with.
/// </summary>
- public required string SelfPublicKey { get; set; }
+ public required string SelfAccountPublicKey { get; set; }
/// <summary>Gets or sets the asymmetric algorithm the caller's own grant was encrypted with.</summary>
public required string Algorithm { get; set; }
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GroupMemberInfo.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GroupMemberInfo.cs
index e966d4fa0..5a15efe2d 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GroupMemberInfo.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GroupMemberInfo.cs
@@ -21,15 +21,15 @@ public class GroupMemberInfo
/// <summary>Gets or sets their role in the group.</summary>
public required string Role { get; set; }
- /// <summary>Gets or sets the id of the member's primary public key.</summary>
- public Guid? PublicKeyId { get; set; }
+ /// <summary>Gets or sets the id of the member's primary account public key.</summary>
+ public Guid? AccountPublicKeyId { get; set; }
- /// <summary>Gets or sets that public key itself (JWK).</summary>
- public string? PublicKey { get; set; }
+ /// <summary>Gets or sets that account public key itself (JWK).</summary>
+ public string? AccountPublicKey { get; set; }
- /// <summary>Gets or sets the member's signature over <see cref="PublicKey"/>.</summary>
- public string? PublicKeySignature { get; set; }
+ /// <summary>Gets or sets the member's signature over <see cref="AccountPublicKey"/>.</summary>
+ public string? AccountPublicKeySignature { get; set; }
- /// <summary>Gets or sets the member's signing public key, which <see cref="PublicKeySignature"/> verifies under.</summary>
+ /// <summary>Gets or sets the member's signing public key, which <see cref="AccountPublicKeySignature"/> verifies under.</summary>
public string? SigningPublicKey { get; set; }
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ManifestGrant.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ManifestGrant.cs
index 76c972652..50a2ed461 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ManifestGrant.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ManifestGrant.cs
@@ -17,8 +17,8 @@ public class ManifestGrant
/// <summary>Gets or sets the recipient this grant is for.</summary>
public required string RecipientUserId { get; set; }
- /// <summary>Gets or sets the id of the recipient public key used to encrypt (see <see cref="GroupMemberInfo.PublicKeyId"/>).</summary>
- public required Guid RecipientPublicKeyId { get; set; }
+ /// <summary>Gets or sets the id of the recipient account public key used to encrypt (see <see cref="GroupMemberInfo.AccountPublicKeyId"/>).</summary>
+ public required Guid RecipientAccountPublicKeyId { get; set; }
/// <summary>Gets or sets the manifest VEK encrypted with that public key (base64), decryptable only by the recipient.</summary>
public required string EncryptedVek { get; set; }
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ReceivedManifestInvitation.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ReceivedManifestInvitation.cs
index 043d559c4..99ad162ea 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ReceivedManifestInvitation.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ReceivedManifestInvitation.cs
@@ -39,6 +39,9 @@ public class ReceivedManifestInvitation
/// <summary>Gets or sets the inviter's signing public key that <see cref="EncryptedNameSignature"/> verifies under.</summary>
public string? SignerPublicKey { get; set; }
- /// <summary>Gets or sets the public half of the recipient's keypair the offer was encrypted to.</summary>
- public string? RecipientPublicKey { get; set; }
+ /// <summary>Gets or sets the recipient's account public key the offer was encrypted to.</summary>
+ public string? RecipientAccountPublicKey { get; set; }
+
+ /// <summary>Gets or sets the algorithm the offer was encrypted with, as a VaultKeyAlgorithm token.</summary>
+ public required string Algorithm { get; set; }
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/AuthLogModel.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/AuthLogModel.cs
index fd0939868..19e5623fa 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/AuthLogModel.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/AuthLogModel.cs
@@ -15,11 +15,6 @@ using AliasVault.Shared.Models.Enums;
/// </summary>
public class AuthLogModel
{
- /// <summary>
- /// Gets or sets the primary key for the auth log entry.
- /// </summary>
- public int Id { get; set; }
-
/// <summary>
/// Gets or sets the timestamp of the auth log entry.
/// </summary>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/AccountKeysUpload.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/AccountKeysUpload.cs
index 1cab954dc..ee9516ed7 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/AccountKeysUpload.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/AccountKeysUpload.cs
@@ -31,6 +31,9 @@ public class AccountKeysUpload
/// <summary>Gets or sets the Account Key encrypted with the KEK derived from the unlock method.</summary>
public string? EncryptedAccountKey { get; set; }
+ /// <summary>Gets or sets the algorithm of <see cref="EncryptedAccountKey"/>, as a VaultKeyAlgorithm token.</summary>
+ public string? EncryptedAccountKeyAlgorithm { get; set; }
+
/// <summary>Gets or sets the vault encryption key encrypted with the Account Key, as base64(IV | ciphertext | authTag).</summary>
public string? EncryptedVek { get; set; }
@@ -52,7 +55,7 @@ public class AccountKeysUpload
/// <summary>
/// Gets a value indicating whether every field is present. A partial upload is not usable.
/// </summary>
- public bool IsComplete => !string.IsNullOrEmpty(EncryptedAccountKey) && !string.IsNullOrEmpty(EncryptedVek) && !string.IsNullOrEmpty(AccountPublicKey) && !string.IsNullOrEmpty(EncryptedAccountPrivateKey)
+ public bool IsComplete => !string.IsNullOrEmpty(EncryptedAccountKey) && !string.IsNullOrEmpty(EncryptedAccountKeyAlgorithm) && !string.IsNullOrEmpty(EncryptedVek) && !string.IsNullOrEmpty(AccountPublicKey) && !string.IsNullOrEmpty(EncryptedAccountPrivateKey)
&& !string.IsNullOrEmpty(SigningPublicKey) && !string.IsNullOrEmpty(EncryptedSigningPrivateKey) && !string.IsNullOrEmpty(AccountPublicKeySignature);
/// <summary>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Manifest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Manifest.cs
index 7a1c5a605..04e719b21 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Manifest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Manifest.cs
@@ -51,9 +51,9 @@ public class Manifest
public string? Algorithm { get; set; }
/// <summary>
- /// Gets or sets the public key <see cref="EncryptedVek"/> was encrypted with.
+ /// Gets or sets the caller's account public key <see cref="EncryptedVek"/> was encrypted with.
/// </summary>
- public string? EncryptionPublicKey { get; set; }
+ public string? AccountPublicKey { get; set; }
/// <summary>Gets or sets the granter's signature over the grant in <see cref="EncryptedVek"/>.</summary>
public string? GrantSignature { get; set; }
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestWrite.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestWrite.cs
index 79fceb451..ea6bedefe 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestWrite.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestWrite.cs
@@ -34,13 +34,18 @@ public class ManifestWrite
public List<BlobReference> BlobReferences { get; set; } = [];
/// <summary>
- /// Gets or sets the public half of this manifest's active RSA key pair (used to e.g. encrypt incoming emails).
+ /// Gets or sets the public half of this manifest's delivery keypair (used to e.g. encrypt incoming emails).
/// </summary>
- public string? EncryptionPublicKey { get; set; }
+ public string? DeliveryPublicKey { get; set; }
/// <summary>
- /// Gets or sets the caller's signature over <see cref="EncryptionPublicKey"/>, required when it changes the manifest's primary key.
+ /// Gets or sets the algorithm of <see cref="DeliveryPublicKey"/>, as a VaultKeyAlgorithm token. Required when a key is sent.
+ /// </summary>
+ public string? DeliveryPublicKeyAlgorithm { get; set; }
+
+ /// <summary>
+ /// Gets or sets the caller's signature over <see cref="DeliveryPublicKey"/>, required when it changes the manifest's primary key.
/// </summary>
[StringLength(255)]
- public string? EncryptionPublicKeySignature { get; set; }
+ public string? DeliveryPublicKeySignature { get; set; }
}
diff --git a/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs b/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
index f874689f5..a0629e632 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
@@ -8,6 +8,7 @@
namespace AliasVault.Cryptography;
using AliasServerDb;
+using AliasVault.Shared.Models.Enums;
/// <summary>
/// Helper class for encrypting and decrypting email contents.
@@ -71,7 +72,12 @@ public static class EmailEncryption
// Encrypt the same symmetric key once per recipient manifest's delivery key.
foreach (var deliveryKey in deliveryKeys)
{
- email.DecryptionKeys.Add(new EmailDecryptionKey { VaultManifestDeliveryKeyId = deliveryKey.Id, EncryptedSymmetricKey = Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, deliveryKey.PublicKey) });
+ var encryptedSymmetricKey = deliveryKey.Algorithm switch
+ {
+ VaultKeyAlgorithm.RsaOaepSha256 => Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, deliveryKey.PublicKey),
+ _ => throw new NotSupportedException($"Delivery key algorithm {deliveryKey.Algorithm} is not supported."),
+ };
+ email.DecryptionKeys.Add(new EmailDecryptionKey { VaultManifestDeliveryKeyId = deliveryKey.Id, EncryptedSymmetricKey = encryptedSymmetricKey });
}
return email;
diff --git a/apps/web/src/components/settings/security/RecentAuthLogsSection.tsx b/apps/web/src/components/settings/security/RecentAuthLogsSection.tsx
index 7d62cc743..13f145dd7 100644
--- a/apps/web/src/components/settings/security/RecentAuthLogsSection.tsx
+++ b/apps/web/src/components/settings/security/RecentAuthLogsSection.tsx
@@ -50,8 +50,8 @@ const RecentAuthLogsSection = forwardRef<SectionHandle>((_, ref) => {
</tr>
</thead>
<tbody>
- {logs.map(log => (
- <tr key={log.id} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
+ {logs.map((log, index) => (
+ <tr key={index} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td className="px-6 py-4">{formatDateTime(log.timestamp)}</td>
<td className="px-6 py-4">{authEventTypeName(log.eventType)}</td>
<td className="px-6 py-4">{log.client}</td>
diff --git a/apps/web/src/services/RegistrationService.ts b/apps/web/src/services/RegistrationService.ts
index 2ea92942a..e99ee70cf 100644
--- a/apps/web/src/services/RegistrationService.ts
+++ b/apps/web/src/services/RegistrationService.ts
@@ -20,7 +20,7 @@ export const RegistrationService = {
const registered = await new SrpLoginService(webApi).register(username, password, inviteCode);
await setAuthTokens(registered.username, registered.token.token, registered.token.refreshToken);
- await VaultKeyService.cacheVaultKeyBlobs({ type: UnlockMethodType.Password, ...registered.keys.accountKeys, ...registered.derivationParams });
+ await VaultKeyService.cacheVaultKeyBlobs({ type: UnlockMethodType.Password, algorithm: registered.keys.accountKeys.encryptedAccountKeyAlgorithm, ...registered.keys.accountKeys, ...registered.derivationParams });
await vaultStore.storeUnlockKeyDerivationParams(registered.derivationParams);
await vaultStore.storeAccountKey(registered.derivedKey);
},
diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.ts
index 23f876d73..e4f364f8b 100644
--- a/core/client/src/auth/MasterPasswordService.ts
+++ b/core/client/src/auth/MasterPasswordService.ts
@@ -1,3 +1,5 @@
+import { VaultKeyAlgorithm, type PasswordChangeInitiateResponse, type PasswordChangeRequest } from '@aliasvault/models/webapi';
+
import { StorageKeys } from '../constants/StorageKeys';
import { getPlatform } from '../platform/ClientPlatform';
import { reencryptAccountKey } from '../rust/RustCore';
@@ -8,7 +10,6 @@ import { VaultKeyService } from './VaultKeyService';
import type { WebApiService } from '../api/WebApiService';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
-import type { PasswordChangeInitiateResponse, PasswordChangeRequest } from '@aliasvault/models/webapi';
/**
* Thrown when the entered master password does not decrypt the Account Key.
@@ -152,6 +153,7 @@ export class MasterPasswordService {
newPasswordSalt: next.salt,
newPasswordVerifier: next.verifier,
newEncryptedAccountKey,
+ newEncryptedAccountKeyAlgorithm: VaultKeyAlgorithm.Aes256Gcm,
newEncryptionType: next.encryptionType,
newEncryptionSettings: next.encryptionSettings,
}, false);
diff --git a/core/client/src/auth/MobileLoginService.ts b/core/client/src/auth/MobileLoginService.ts
index 8f4efabc5..68b6a27ef 100644
--- a/core/client/src/auth/MobileLoginService.ts
+++ b/core/client/src/auth/MobileLoginService.ts
@@ -1,10 +1,11 @@
+import { VaultKeyAlgorithm, type MobileLoginInitiateResponse, type MobileLoginPayload, type MobileLoginPollResponse } from '@aliasvault/models/webapi';
+
import EncryptionUtility from '../crypto/EncryptionUtility';
import { bytesToBase64 } from '../utilities/Base64';
import { MobileLoginProtocol } from './MobileLoginProtocol';
import type { WebApiService } from '../api/WebApiService';
-import type { MobileLoginInitiateResponse, MobileLoginPayload, MobileLoginPollResponse } from '@aliasvault/models/webapi';
/**
* Error codes for mobile login failures.
@@ -76,7 +77,7 @@ export class MobileLoginService {
const response = await this.api.rawFetch('auth/mobile-login/initiate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ clientPublicKey: publicKeyJwk }),
+ body: JSON.stringify({ clientPublicKey: publicKeyJwk, algorithm: VaultKeyAlgorithm.RsaOaepSha256 }),
});
if (!response.ok) {
diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.ts
index 41f357760..04fc4c9ad 100644
--- a/core/client/src/auth/VaultKeyService.ts
+++ b/core/client/src/auth/VaultKeyService.ts
@@ -2,7 +2,7 @@
* VaultKeyService with client-side helpers for key operations.
*/
-import { UnlockMethodType, type VaultKeyGetResponse, type VaultKeyResponse } from '@aliasvault/models/webapi';
+import { UnlockMethodType, VaultKeyAlgorithm, type VaultKeyGetResponse, type VaultKeyResponse } from '@aliasvault/models/webapi';
import { ApiRequestError } from '../api/errors/ApiRequestError';
import { AppErrorCode, formatErrorWithCode } from '../api/errors/AppErrorCodes';
@@ -79,6 +79,10 @@ export class VaultKeyService {
return unlockKeyBase64;
}
+ if (result.vaultKey.algorithm !== VaultKeyAlgorithm.Aes256Gcm) {
+ throw new Error(formatErrorWithCode(`Unsupported Account Key algorithm '${result.vaultKey.algorithm}'`, AppErrorCode.VAULT_VERSION_INCOMPATIBLE));
+ }
+
const keys = await VaultKeyService.openChain(unlockKeyBase64, result.vaultKey.encryptedAccountKey, result.vaultKey.encryptedVek ?? null, null);
await VaultKeyService.cacheVaultKeyBlobs(result.vaultKey);
return keys.accountKey;
diff --git a/core/client/src/rust/RustCoreTypes.ts b/core/client/src/rust/RustCoreTypes.ts
index fdb3aa0b6..ecec7bbd5 100644
--- a/core/client/src/rust/RustCoreTypes.ts
+++ b/core/client/src/rust/RustCoreTypes.ts
@@ -94,6 +94,7 @@ export type KeyChainOpenResult =
*/
export type AccountKeyBlobs = {
encryptedAccountKey: string;
+ encryptedAccountKeyAlgorithm: string;
encryptedVek: string;
accountPublicKey: string;
encryptedAccountPrivateKey: string;
diff --git a/core/client/src/sharing/FamilySharingView.ts b/core/client/src/sharing/FamilySharingView.ts
index fb1123b35..233404929 100644
--- a/core/client/src/sharing/FamilySharingView.ts
+++ b/core/client/src/sharing/FamilySharingView.ts
@@ -155,7 +155,7 @@ export function describeMemberAccess(group: GroupInfo, manifest: SharedManifestI
canRevoke: hasAccess && !isSelf && isAdmin,
canWithdraw: invitation !== null && !isSelf && isAdmin,
canInvite: !hasAccess && invitation === null && !isSelf && isAdmin && holdsManifestKey(manifest, ownUserId),
- isReadyForInvite: Boolean(member.publicKey),
+ isReadyForInvite: Boolean(member.accountPublicKey),
};
}
diff --git a/core/client/src/sharing/SharingService.ts b/core/client/src/sharing/SharingService.ts
index 543c30067..4b094c80e 100644
--- a/core/client/src/sharing/SharingService.ts
+++ b/core/client/src/sharing/SharingService.ts
@@ -1,4 +1,4 @@
-import { type DeleteSharedManifestInitiateResponse, type DeleteSharedManifestRequest, type GroupOverviewResponse, type ReceivedManifestInvitation } from '@aliasvault/models/webapi';
+import { VaultKeyAlgorithm, type DeleteSharedManifestInitiateResponse, type DeleteSharedManifestRequest, type GroupOverviewResponse, type ReceivedManifestInvitation } from '@aliasvault/models/webapi';
import { VaultKeyService } from '../auth/VaultKeyService';
import { EncryptionUtility } from '../crypto/EncryptionUtility';
@@ -49,12 +49,17 @@ export class SharingService {
const names: Record<string, string> = {};
for (const invitation of invitations) {
- if (!invitation.encryptedName || !invitation.recipientPublicKey) {
+ if (!invitation.encryptedName || !invitation.recipientAccountPublicKey) {
+ continue;
+ }
+
+ if (invitation.algorithm !== VaultKeyAlgorithm.RsaOaepSha256) {
+ devWarn(`[Sharing] Invitation ${invitation.id} is encrypted with an unsupported algorithm '${invitation.algorithm}'.`);
continue;
}
try {
- const name = await decryptName(invitation.encryptedName, invitation.recipientPublicKey);
+ const name = await decryptName(invitation.encryptedName, invitation.recipientAccountPublicKey);
if (name === null) {
devWarn(`[Sharing] This session holds no account private key that decrypts the name encrypted into invitation ${invitation.id}.`);
continue;
diff --git a/core/models/src/webapi/AuthLog.ts b/core/models/src/webapi/AuthLog.ts
index 54f0e1b69..36b5ac595 100644
--- a/core/models/src/webapi/AuthLog.ts
+++ b/core/models/src/webapi/AuthLog.ts
@@ -2,11 +2,6 @@
* Auth Log model.
*/
export type AuthLogModel = {
- /**
- * Gets or sets the primary key for the auth log entry.
- */
- id: number;
-
/**
* Gets or sets the timestamp of the auth log entry.
*/
diff --git a/core/models/src/webapi/Groups.ts b/core/models/src/webapi/Groups.ts
index 38f51613f..73fc2cc9d 100644
--- a/core/models/src/webapi/Groups.ts
+++ b/core/models/src/webapi/Groups.ts
@@ -16,9 +16,9 @@ export type GroupMemberInfo = {
userId: string;
username: string;
role: GroupRole;
- publicKeyId: string | null;
- publicKey: string | null;
- publicKeySignature: string | null;
+ accountPublicKeyId: string | null;
+ accountPublicKey: string | null;
+ accountPublicKeySignature: string | null;
signingPublicKey: string | null;
}
@@ -45,7 +45,8 @@ export type ReceivedManifestInvitation = {
encryptedName: string | null;
encryptedNameSignature: string | null;
signerPublicKey: string | null;
- recipientPublicKey: string | null;
+ recipientAccountPublicKey: string | null;
+ algorithm: string;
}
/**
diff --git a/core/models/src/webapi/MobileLogin.ts b/core/models/src/webapi/MobileLogin.ts
index 440f1b1d6..09b316e38 100644
--- a/core/models/src/webapi/MobileLogin.ts
+++ b/core/models/src/webapi/MobileLogin.ts
@@ -3,6 +3,7 @@
*/
export type MobileLoginInitiateRequest = {
clientPublicKey: string;
+ algorithm: string;
}
/**
@@ -61,6 +62,7 @@ export type MobileLoginRequestReference = {
*/
export type MobileLoginDetailsResponse = {
clientPublicKey: string;
+ algorithm: string;
ipAddress: string | null;
location: string | null;
clientName: string | null;
@@ -75,4 +77,5 @@ export type MobileLoginDetailsResponse = {
export type MobileLoginSubmitRequest = {
requestId: string;
encryptedAccountKey: string;
+ algorithm: string;
}
diff --git a/core/models/src/webapi/PasswordChangeRequest.ts b/core/models/src/webapi/PasswordChangeRequest.ts
index 2e624144c..82aae60f7 100644
--- a/core/models/src/webapi/PasswordChangeRequest.ts
+++ b/core/models/src/webapi/PasswordChangeRequest.ts
@@ -7,6 +7,7 @@ export type PasswordChangeRequest = {
newPasswordSalt: string;
newPasswordVerifier: string;
newEncryptedAccountKey: string;
+ newEncryptedAccountKeyAlgorithm: string;
newEncryptionType: string;
newEncryptionSettings: string;
};
diff --git a/core/models/src/webapi/VaultKey.ts b/core/models/src/webapi/VaultKey.ts
index 79c15a405..b417c1de1 100644
--- a/core/models/src/webapi/VaultKey.ts
+++ b/core/models/src/webapi/VaultKey.ts
@@ -4,6 +4,7 @@
export type VaultKeyResponse = {
type: string;
encryptedAccountKey: string;
+ algorithm: string;
encryptedAccountPrivateKey: string | null;
accountPublicKey: string | null;
signingPublicKey: string | null;
diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rs
index c977152c6..73c387e96 100644
--- a/core/rust/src/crypto/key_chain.rs
+++ b/core/rust/src/crypto/key_chain.rs
@@ -16,11 +16,21 @@ use super::signing::{self, generate_signing_key_pair};
use crate::common::encoding::{base64_decode, base64_encode, hex_encode_upper};
use crate::common::error::VaultResult;
+/// The algorithm this build encrypts every Account Key with, as a VaultKeyAlgorithm token.
+pub const ACCOUNT_KEY_WRAP_ALGORITHM: &str = "aes256-gcm";
+
+fn account_key_wrap_algorithm() -> String {
+ ACCOUNT_KEY_WRAP_ALGORITHM.to_string()
+}
+
/// The wrapped halves of an account key hierarchy: what the server stores.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountKeyBlobs {
pub encrypted_account_key: String,
+ /// The algorithm of `encrypted_account_key`, as a VaultKeyAlgorithm token.
+ #[serde(default = "account_key_wrap_algorithm")]
+ pub encrypted_account_key_algorithm: String,
pub encrypted_vek: String,
pub account_public_key: String,
pub encrypted_account_private_key: String,
@@ -190,6 +200,7 @@ pub fn create_account_key_hierarchy_with_key_pair(unlock_key_base64: &str, key_p
let account_keys = AccountKeyBlobs {
encrypted_account_key: wrap_account_key(&account_key, unlock_key_base64)?,
+ encrypted_account_key_algorithm: account_key_wrap_algorithm(),
encrypted_vek: wrap_key(&vault_encryption_key, &account_key, aad::PERSONAL_VEK)?,
account_public_key: key_pair.public_key.clone(),
encrypted_account_private_key: symmetric_encrypt_with_aad(&key_pair.private_key, &account_key, aad::ACCOUNT_PRIVATE_KEY)?,
diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rs
index 7d4b70173..1fd13c119 100644
--- a/core/rust/src/vault_sync/keys.rs
+++ b/core/rust/src/vault_sync/keys.rs
@@ -5,7 +5,7 @@ use std::collections::HashMap;
use super::errors::{SyncError, SyncResult};
use super::session::Host;
use super::state::{self, Ctx};
-use super::types::{ManifestDto, SharedManifestDto, VaultKeyGetResponse, VaultKeyResponse, ALGORITHM_RSA_OAEP_SHA256};
+use super::types::{ManifestDto, SharedManifestDto, VaultKeyGetResponse, VaultKeyResponse, ALGORITHM_AES256_GCM, ALGORITHM_RSA_OAEP_SHA256};
use super::http;
use crate::crypto;
@@ -23,6 +23,14 @@ pub(crate) async fn fetch_vault_key(host: &Host) -> SyncResult<Option<VaultKeyRe
}
}
+/// Refuse an Account Key encrypted with an algorithm this build cannot open.
+pub(crate) fn ensure_known_unlock_algorithm(vault_key: &VaultKeyResponse) -> SyncResult<()> {
+ if vault_key.algorithm == ALGORITHM_AES256_GCM {
+ return Ok(());
+ }
+ Err(SyncError::VaultVersionIncompatible(format!("the Account Key is encrypted with '{}', which this app cannot open; update the app", vault_key.algorithm)))
+}
+
/// Persist a server vault-key response's encrypted blobs.
pub(crate) async fn cache_vault_key_blobs(host: &Host, vault_key: &VaultKeyResponse) -> SyncResult<()> {
state::set(host, state::ENCRYPTED_ACCOUNT_KEY, &vault_key.encrypted_account_key).await?;
@@ -104,7 +112,7 @@ pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestD
ctx.warn(format!("[Sharing] Manifest {} grants its key under an unsupported algorithm \"{}\" (newer server?); leaving it closed.", record.manifest_id, record.algorithm)).await;
return Ok(None);
}
- let Some(private_key) = resolve_grant_private_key(ctx, &record.encryption_public_key) else {
+ let Some(private_key) = resolve_grant_private_key(ctx, &record.account_public_key) else {
ctx.warn(format!("[Sharing] This session holds no account private key that opens the grant on manifest {}; leaving it closed.", record.manifest_id)).await;
return Ok(None);
};
@@ -166,6 +174,7 @@ pub(crate) async fn resolve_vault_key(ctx: &mut Ctx) -> SyncResult<bool> {
match fetched {
Ok(response) => match response.vault_key {
Some(vault_key) if vault_key.encrypted_vek.is_some() => {
+ ensure_known_unlock_algorithm(&vault_key)?;
let encrypted_vek = vault_key.encrypted_vek.clone().unwrap_or_default();
open_chain(ctx, &vault_key.encrypted_account_key, &encrypted_vek, vault_key.encrypted_account_private_key.as_deref(), &unlock_key).await?;
cache_vault_key_blobs(&ctx.host, &vault_key).await?;
@@ -211,6 +220,7 @@ pub(crate) async fn accept_hierarchy_created_elsewhere(ctx: &mut Ctx) -> SyncRes
};
let Some(vault_key) = vault_key else { return Ok(true) };
let Some(encrypted_vek) = vault_key.encrypted_vek.clone() else { return Ok(true) };
+ ensure_known_unlock_algorithm(&vault_key)?;
// Hosts hold the unlock key and derive the vault key from the cached chain.
let accepted: SyncResult<()> = async {
diff --git a/core/rust/src/vault_sync/pull.rs b/core/rust/src/vault_sync/pull.rs
index 8e0b045df..afbec70f3 100644
--- a/core/rust/src/vault_sync/pull.rs
+++ b/core/rust/src/vault_sync/pull.rs
@@ -116,10 +116,10 @@ fn newer_format(label: &str, version: u32) -> SyncError {
SyncError::VaultVersionIncompatible(format!("{} has format version {}, this app reads up to {}; update the app", label, version, vault_codec::SCHEMA_VERSION))
}
-/// The grant a shared manifest is remembered by, when the snapshot carries one.
+/// The grant a shared manifest is remembered by, when the snapshot carries a complete one.
fn grant_of(dto: &ManifestDto) -> Option<(String, String, String)> {
- match (&dto.encrypted_vek, &dto.encryption_public_key) {
- (Some(vek), Some(public)) if !vek.is_empty() && !public.is_empty() => Some((vek.clone(), public.clone(), dto.algorithm.clone().unwrap_or_else(|| types::ALGORITHM_RSA_OAEP_SHA256.to_string()))),
+ match (&dto.encrypted_vek, &dto.account_public_key, &dto.algorithm) {
+ (Some(vek), Some(public), Some(algorithm)) if !vek.is_empty() && !public.is_empty() && !algorithm.is_empty() => Some((vek.clone(), public.clone(), algorithm.clone())),
_ => None,
}
}
@@ -176,9 +176,9 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
}
if dto.blob.as_deref().unwrap_or("").is_empty() {
// A shared manifest served without content yet (created but never written); its grant and revision are still tracked.
- let (encrypted_vek, encryption_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} was served without content and without a grant, refusing to assemble", dto.manifest_id)))?;
+ let (encrypted_vek, account_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} was served without content and without a grant, refusing to assemble", dto.manifest_id)))?;
let encrypted_name = served_encrypted_name(ctx, &previous_records, &dto.manifest_id);
- shared_records.insert(dto.manifest_id.clone(), SharedManifestDto { manifest_id: dto.manifest_id.clone(), encrypted_vek, encryption_public_key, algorithm, salt: vault_codec::generate_manifest_salt(), encrypted_name, can_administer: dto.can_administer });
+ shared_records.insert(dto.manifest_id.clone(), SharedManifestDto { manifest_id: dto.manifest_id.clone(), encrypted_vek, account_public_key, algorithm, salt: vault_codec::generate_manifest_salt(), encrypted_name, can_administer: dto.can_administer });
contentless_revisions.insert(dto.manifest_id.clone(), dto.revision);
continue;
}
@@ -195,7 +195,7 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
continue;
}
- let (encrypted_vek, encryption_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} carries no grant this account can re-open, refusing to assemble", entry.manifest_id)))?;
+ let (encrypted_vek, account_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} carries no grant this account can re-open, refusing to assemble", entry.manifest_id)))?;
let encrypted_name = served_encrypted_name(ctx, &previous_records, &entry.manifest_id);
if let Some(ciphertext) = &encrypted_name {
match open_manifest_name(ciphertext, &entry.manifest_id, &manifest_key) {
@@ -203,7 +203,7 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
None => ctx.warn(format!("[V2Pull] The name of shared manifest {} did not open with its key; leaving it unnamed.", entry.manifest_id)).await,
}
}
- shared_records.insert(entry.manifest_id.clone(), SharedManifestDto { manifest_id: entry.manifest_id.clone(), encrypted_vek, encryption_public_key, algorithm, salt: entry.manifest.manifest_salt.clone(), encrypted_name, can_administer: dto.can_administer });
+ shared_records.insert(entry.manifest_id.clone(), SharedManifestDto { manifest_id: entry.manifest_id.clone(), encrypted_vek, account_public_key, algorithm, salt: entry.manifest.manifest_salt.clone(), encrypted_name, can_administer: dto.can_administer });
resolved.push(entry);
}
keys::set_shared_manifest_records(&ctx.host, &shared_records, vek).await?;
@@ -401,7 +401,12 @@ async fn empty_personal_manifest(ctx: &Ctx, dto: &ManifestDto, vek: &str) -> Syn
/// The key that opens one snapshot manifest.
async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_id: &str, personal_vek: &str, is_personal: bool) -> SyncResult<String> {
- let key_type = dto.key_type.clone().unwrap_or_else(|| if is_personal { types::KEY_TYPE_ACCOUNT_KEY.to_string() } else { types::KEY_TYPE_GRANT_KEY.to_string() });
+ // Only a personal manifest that predates the account key hierarchy has no key type; a shared one always states it.
+ let key_type = match dto.key_type.clone() {
+ Some(key_type) => key_type,
+ None if is_personal => types::KEY_TYPE_ACCOUNT_KEY.to_string(),
+ None => return Err(SyncError::Snapshot(format!("shared manifest {} states no key type, refusing to assemble", dto.manifest_id))),
+ };
if key_type == types::KEY_TYPE_ACCOUNT_KEY {
if dto.manifest_id != personal_manifest_id {
return Err(SyncError::Snapshot(format!("manifest {} is unlocked by the account key hierarchy, but this session holds no key for it, refusing to assemble", dto.manifest_id)));
diff --git a/core/rust/src/vault_sync/push.rs b/core/rust/src/vault_sync/push.rs
index a7f29a0d7..4b1e8fba5 100644
--- a/core/rust/src/vault_sync/push.rs
+++ b/core/rust/src/vault_sync/push.rs
@@ -8,7 +8,7 @@ use crate::vault_model::{id_key, ids_equal, OVERFLOW_TABLE, TRASH_RETENTION_DEFA
use super::email_routing::build_email_routing;
use super::errors::{SyncError, SyncResult};
use super::state::{self, Ctx};
-use super::types::{BlobDto, BlobHashesRequest, BlobRef, BlobUploadRequest, BucketRevision, BucketWrite, Db, ManifestRevision, ManifestWrite, MissingBlobsResponse, VaultWriteMigration, VaultWriteRequest, VaultWriteResponse, VaultWriteStatus};
+use super::types::{BlobDto, BlobHashesRequest, BlobRef, BlobUploadRequest, BucketRevision, BucketWrite, Db, ManifestRevision, ManifestWrite, MissingBlobsResponse, VaultWriteMigration, VaultWriteRequest, VaultWriteResponse, VaultWriteStatus, ALGORITHM_RSA_OAEP_SHA256};
use super::blob_keys::{self, EncryptedBlob};
use super::{db, http, keys};
use crate::crypto;
@@ -641,8 +641,9 @@ async fn encrypt_changed_manifests(ctx: &Ctx, candidates: &[Candidate<'_>], base
current_revision: candidate.current_revision,
credentials_count: candidate.manifest.tables.get("Items").map(Vec::len).unwrap_or(0),
blob_references: blob_refs,
- encryption_public_key: manifest_key,
- encryption_public_key_signature: manifest_key_signature,
+ delivery_public_key_algorithm: manifest_key.as_ref().map(|_| ALGORITHM_RSA_OAEP_SHA256.to_string()),
+ delivery_public_key: manifest_key,
+ delivery_public_key_signature: manifest_key_signature,
});
written.insert(fingerprint_key, fingerprint);
}
diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rs
index 072ad44d3..05099a2f5 100644
--- a/core/rust/src/vault_sync/sharing.rs
+++ b/core/rust/src/vault_sync/sharing.rs
@@ -54,11 +54,11 @@ struct GroupMemberInfo {
#[serde(default)]
username: String,
#[serde(default)]
- public_key_id: Option<String>,
+ account_public_key_id: Option<String>,
#[serde(default)]
- public_key: Option<String>,
+ account_public_key: Option<String>,
#[serde(default)]
- public_key_signature: Option<String>,
+ account_public_key_signature: Option<String>,
#[serde(default)]
signing_public_key: Option<String>,
}
@@ -68,7 +68,7 @@ struct GroupMemberInfo {
struct CreateSharedManifestRequest<'a> {
manifest_id: &'a str,
self_encrypted_vek: &'a str,
- self_public_key: &'a str,
+ self_account_public_key: &'a str,
algorithm: &'a str,
self_grant_signature: &'a str,
encrypted_name: &'a str,
@@ -92,7 +92,7 @@ struct CreateSharedManifestResponse {
#[serde(rename_all = "camelCase")]
struct ManifestGrant {
recipient_user_id: String,
- recipient_public_key_id: String,
+ recipient_account_public_key_id: String,
encrypted_vek: String,
encrypted_name: Option<String>,
encrypted_name_signature: Option<String>,
@@ -221,7 +221,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
let response: CreateSharedManifestResponse = http::post(
&ctx.host,
&format!("Groups/{}/manifests", group.group_id),
- &CreateSharedManifestRequest { manifest_id: &requested_id, self_encrypted_vek: &self_encrypted_vek, self_public_key: &self_public_key, algorithm: ALGORITHM_RSA_OAEP_SHA256, self_grant_signature: &self_grant_signature, encrypted_name: &encrypted_name },
+ &CreateSharedManifestRequest { manifest_id: &requested_id, self_encrypted_vek: &self_encrypted_vek, self_account_public_key: &self_public_key, algorithm: ALGORITHM_RSA_OAEP_SHA256, self_grant_signature: &self_grant_signature, encrypted_name: &encrypted_name },
false,
)
.await?;
@@ -236,7 +236,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
SharedManifestDto {
manifest_id: manifest_id.clone(),
encrypted_vek: self_encrypted_vek,
- encryption_public_key: self_public_key,
+ account_public_key: self_public_key,
algorithm: ALGORITHM_RSA_OAEP_SHA256.to_string(),
salt: vault_codec::generate_manifest_salt(),
encrypted_name: Some(encrypted_name),
@@ -308,7 +308,7 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {
let group = administered_group(ctx, &target.group_id).await?;
let manifest = group.manifests.iter().find(|candidate| ids_equal(&candidate.manifest_id, &manifest_id)).ok_or_else(|| SyncError::Other("The shared manifest does not belong to the group".to_string()))?;
let member = group.members.iter().find(|candidate| candidate.user_id == user_id).ok_or_else(|| SyncError::Other("The recipient is not a member of the group".to_string()))?;
- let (Some(recipient_public_key), Some(recipient_public_key_id), Some(signature), Some(signing_public_key)) = (member.public_key.clone(), member.public_key_id.clone(), member.public_key_signature.as_deref(), member.signing_public_key.as_deref()) else {
+ let (Some(recipient_public_key), Some(recipient_public_key_id), Some(signature), Some(signing_public_key)) = (member.account_public_key.clone(), member.account_public_key_id.clone(), member.account_public_key_signature.as_deref(), member.signing_public_key.as_deref()) else {
return Ok(Err(Refusal::Api(INVITE_RECIPIENT_NOT_READY.to_string())));
};
@@ -336,7 +336,7 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {
let encrypted_name = name.map(|name| crypto::encrypt_with_public_key(name.as_bytes(), &recipient_public_key)).transpose()?;
let grant = ManifestGrant {
recipient_user_id: member.user_id.clone(),
- recipient_public_key_id,
+ recipient_account_public_key_id: recipient_public_key_id,
signature: crypto::signing::sign(&signing_key, &crypto::signing::grant_message(&manifest.manifest_id, manifest.key_version, &own_user_id, &recipient_public_key, ALGORITHM_RSA_OAEP_SHA256, &encrypted_vek))?,
encrypted_name_signature: encrypted_name.as_deref().map(|name| crypto::signing::sign(&signing_key, &crypto::signing::invitation_name_message(&manifest.manifest_id, &own_user_id, &recipient_public_key, name))).transpose()?,
encrypted_vek,
diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rs
index 90cf31e28..b359a8f30 100644
--- a/core/rust/src/vault_sync/tests/mod.rs
+++ b/core/rust/src/vault_sync/tests/mod.rs
@@ -430,7 +430,8 @@ fn push_creates_and_publishes_a_missing_personal_delivery_key() {
assert_eq!(result["success"], true, "{}", result);
let keys = active_delivery_keys(&host.local, PERSONAL_MANIFEST_ID);
assert_eq!(keys.len(), 1, "the push created exactly one keypair");
- assert_eq!(write["manifests"][0]["encryptionPublicKey"], json!(keys[0]), "the write publishes the new public key");
+ assert_eq!(write["manifests"][0]["deliveryPublicKey"], json!(keys[0]), "the write publishes the new public key");
+ assert_eq!(write["manifests"][0]["deliveryPublicKeyAlgorithm"], json!("rsa-oaep-sha256"), "the write states the key's algorithm");
// The keypair travels inside the manifest, so the other devices get the private half.
let blob = write["manifests"][0]["manifestBlob"].as_str().unwrap();
@@ -446,7 +447,7 @@ fn push_creates_and_publishes_a_missing_personal_delivery_key() {
let (again, second_write) = push_local_edit(&mut host, &vek, "Renamed again", &["Main"]);
assert_eq!(again["success"], true, "{}", again);
assert_eq!(active_delivery_keys(&host.local, PERSONAL_MANIFEST_ID), keys);
- assert_eq!(second_write["manifests"][0]["encryptionPublicKey"], json!(keys[0]));
+ assert_eq!(second_write["manifests"][0]["deliveryPublicKey"], json!(keys[0]));
}
#[test]
@@ -460,7 +461,7 @@ fn bucket_only_push_writes_the_manifest_while_the_personal_delivery_key_is_missi
assert_eq!(result["success"], true, "{}", result);
let keys = active_delivery_keys(&host.local, PERSONAL_MANIFEST_ID);
assert_eq!(keys.len(), 1);
- assert_eq!(write["manifests"][0]["encryptionPublicKey"], json!(keys[0]), "the full write publishes the key a bucket-only write could not");
+ assert_eq!(write["manifests"][0]["deliveryPublicKey"], json!(keys[0]), "the full write publishes the key a bucket-only write could not");
}
#[test]
@@ -851,7 +852,7 @@ fn status_check_reports_newer_server_state_without_touching_the_vault() {
/// The `GET v2/VaultKey/Password` answer for a hierarchy the server holds.
fn vault_key_body(hierarchy: &crypto::AccountKeyHierarchy) -> Value {
let blobs = &hierarchy.account_keys;
- json!({ "vaultKey": { "type": "password", "encryptedAccountKey": blobs.encrypted_account_key, "encryptedVek": blobs.encrypted_vek, "accountPublicKey": blobs.account_public_key, "encryptedAccountPrivateKey": blobs.encrypted_account_private_key, "signingPublicKey": blobs.signing_public_key, "encryptedSigningPrivateKey": blobs.encrypted_signing_private_key, "salt": "salt", "encryptionType": "Argon2Id", "encryptionSettings": "{}" } })
+ json!({ "vaultKey": { "type": "password", "encryptedAccountKey": blobs.encrypted_account_key, "algorithm": "aes256-gcm", "encryptedVek": blobs.encrypted_vek, "accountPublicKey": blobs.account_public_key, "encryptedAccountPrivateKey": blobs.encrypted_account_private_key, "signingPublicKey": blobs.signing_public_key, "encryptedSigningPrivateKey": blobs.encrypted_signing_private_key, "salt": "salt", "encryptionType": "Argon2Id", "encryptionSettings": "{}" } })
}
/// The cross-device race: this device logged in while the account was legacy (no cached chain, unlock key session), and
@@ -882,6 +883,23 @@ fn a_hierarchy_created_on_another_device_is_accepted_on_the_next_pull() {
assert_eq!(host.rekeyed_stores_found_the_chain, vec![true], "the chain is cached before the vault is stored under the VEK");
}
+/// An Account Key encrypted with an algorithm this build does not know asks for an app update instead of a wrong password.
+#[test]
+fn resolve_vault_key_with_an_unknown_unlock_algorithm_asks_for_an_app_update() {
+ let unlock_key = crypto::generate_key_base64();
+ let hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();
+ let mut host = TestHost::new(&unlock_key);
+ let mut body = vault_key_body(&hierarchy);
+ body["vaultKey"]["algorithm"] = json!("future-x");
+ host.respond("GET", "VaultKey/Password", body);
+
+ let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &unlock_key, false, 0)).unwrap());
+
+ assert_eq!(result["success"], false, "{}", result);
+ assert_eq!(result["logoutReason"], "vaultVersionIncompatible", "{}", result);
+ assert!(!host.state.contains_key(state::ENCRYPTED_ACCOUNT_KEY), "nothing is cached from a chain this build cannot open");
+}
+
/// Login: the host hands the password-derived key to `resolveVaultKey`; the server's chain opens with it, is
/// cached for offline unlock, and the VEK comes back as the key to store.
#[test]
diff --git a/core/rust/src/vault_sync/tests/unsupported_grant.rs b/core/rust/src/vault_sync/tests/unsupported_grant.rs
index 5cbb54cdb..f0258ad71 100644
--- a/core/rust/src/vault_sync/tests/unsupported_grant.rs
+++ b/core/rust/src/vault_sync/tests/unsupported_grant.rs
@@ -14,13 +14,18 @@ const SHARED_MANIFEST_ID: &str = "22222222-2222-4222-8222-222222222222";
/// Sync a fresh client against a personal snapshot plus a shared manifest granted under `algorithm` and `key_type`.
fn sync_with_shared_grant(algorithm: &str, key_type: &str, blob: &str) -> (TestHost, Value) {
+ sync_with_shared_manifest(json!({ "manifestId": SHARED_MANIFEST_ID, "blob": blob, "revision": 3, "blobReferences": [], "canAdminister": false, "keyType": key_type, "algorithm": algorithm, "encryptedVek": "future-grant", "accountPublicKey": "future-key" }))
+}
+
+/// Sync a fresh client against a personal snapshot plus the given shared manifest entry.
+fn sync_with_shared_manifest(shared: Value) -> (TestHost, Value) {
let vek = crypto::generate_key_base64();
let mut host = TestHost::new(&vek);
host.state.insert(state::ENCRYPTED_ACCOUNT_KEY.to_string(), json!("wrapped"));
let server_db = test_host::open_schema_db(&host.schema_sql);
insert_item(&server_db, "aaaaaaaa-0000-4000-8000-000000000001", "Server item", PERSONAL_MANIFEST_ID);
let (mut status, mut vault) = snapshot_of(&server_db, &vek, 7, &vault_codec::generate_manifest_salt());
- vault["manifests"].as_array_mut().unwrap().push(json!({ "manifestId": SHARED_MANIFEST_ID, "blob": blob, "revision": 3, "blobReferences": [], "canAdminister": false, "keyType": key_type, "algorithm": algorithm, "encryptedVek": "future-grant", "encryptionPublicKey": "future-key" }));
+ vault["manifests"].as_array_mut().unwrap().push(shared);
status["manifestRevisions"].as_array_mut().unwrap().push(json!({ "manifestId": SHARED_MANIFEST_ID, "revision": 3 }));
host.respond("GET", "Status", status);
host.respond("GET", "Vault", vault);
@@ -52,3 +57,15 @@ fn unknown_grant_algorithm_on_a_contentless_shared_manifest_asks_for_an_app_upda
let (host, result) = sync_with_shared_grant("future-x", "grant-key", "");
assert_told_to_update(&host, &result);
}
+
+/// A shared manifest without a key type or grant algorithm is refused, never guessed.
+#[test]
+fn shared_manifest_without_key_type_or_algorithm_is_refused() {
+ for missing in ["keyType", "algorithm"] {
+ let mut shared = json!({ "manifestId": SHARED_MANIFEST_ID, "blob": "bm90LXJlYWRhYmxl", "revision": 3, "blobReferences": [], "canAdminister": false, "keyType": "grant-key", "algorithm": "rsa-oaep-sha256", "encryptedVek": "grant", "accountPublicKey": "key" });
+ shared.as_object_mut().unwrap().remove(missing);
+ let (host, result) = sync_with_shared_manifest(shared);
+ assert_eq!(result["success"], false, "missing {}: {}", missing, result);
+ assert!(item_names(&host.local).is_empty(), "missing {}: nothing is materialized", missing);
+ }
+}
diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rs
index 946dc9601..f1474e564 100644
--- a/core/rust/src/vault_sync/types.rs
+++ b/core/rust/src/vault_sync/types.rs
@@ -575,7 +575,7 @@ pub struct ManifestDto {
#[serde(default)]
pub algorithm: Option<String>,
#[serde(default)]
- pub encryption_public_key: Option<String>,
+ pub account_public_key: Option<String>,
#[serde(default)]
pub grant_signature: Option<String>,
#[serde(default)]
@@ -624,6 +624,7 @@ pub struct EmailRoutingDto {
pub const KEY_TYPE_ACCOUNT_KEY: &str = "account-key";
pub const KEY_TYPE_GRANT_KEY: &str = "grant-key";
pub const ALGORITHM_RSA_OAEP_SHA256: &str = "rsa-oaep-sha256";
+pub const ALGORITHM_AES256_GCM: &str = crate::crypto::key_chain::ACCOUNT_KEY_WRAP_ALGORITHM;
/// One manifest element of `POST v2/Vault`.
#[derive(Debug, Clone, Serialize)]
@@ -636,9 +637,11 @@ pub struct ManifestWrite {
pub credentials_count: usize,
pub blob_references: Vec<BlobRef>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub encryption_public_key: Option<String>,
+ pub delivery_public_key: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub delivery_public_key_algorithm: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub encryption_public_key_signature: Option<String>,
+ pub delivery_public_key_signature: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
@@ -774,6 +777,8 @@ pub struct VaultKeyResponse {
#[serde(default)]
pub encrypted_account_key: String,
#[serde(default)]
+ pub algorithm: String,
+ #[serde(default)]
pub encrypted_account_private_key: Option<String>,
#[serde(default)]
pub account_public_key: Option<String>,
@@ -797,7 +802,9 @@ pub struct VaultKeyResponse {
pub struct SharedManifestDto {
pub manifest_id: String,
pub encrypted_vek: String,
- pub encryption_public_key: String,
+ /// The account public key the grant was encrypted to (stored as `encryptionPublicKey` before 0.31.0 shipped).
+ #[serde(alias = "encryptionPublicKey")]
+ pub account_public_key: String,
pub algorithm: String,
pub salt: String,
/// The manifest's name as the server last served it, encrypted with the manifest's own key.