Skip to content

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

Update unlock and decrypt phase error codes to be more specific (#2159)

Leendert de Borst8b4fc9fe92db
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 9637dceca..e606fddfa 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
-import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+import { AppErrorCode, formatErrorWithCode, getErrorMessage, hasErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import { WebApiService } from '@aliasvault/client/api/WebApiService';
import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';
@@ -255,20 +255,31 @@ export async function handleGetVault(
return { success: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };
}
- // The popup receives the database as base64: messages carry strings, not bytes.
- const decryptedVault = bytesToBase64(await decryptVaultBlob(encryptedVault, encryptionKey));
+ let decryptedBytes: Uint8Array;
+ try {
+ decryptedBytes = await decryptVaultBlob(encryptedVault, encryptionKey);
+ } catch (error) {
+ logFailure('Failed to decrypt the stored vault', error);
+ // E-203: the stored vault does not decrypt with the session key
+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.VAULT_DECRYPT_FAILED) };
+ }
return {
success: true,
- vault: decryptedVault,
+ // The popup receives the database as base64: messages carry strings, not bytes.
+ vault: bytesToBase64(decryptedBytes),
publicEmailDomains: publicEmailDomains ?? [],
privateEmailDomains: privateEmailDomains ?? [],
hiddenPrivateEmailDomains: hiddenPrivateEmailDomains ?? []
};
} catch (error) {
logFailure('Failed to get vault', error);
- // E-203: Vault decryption failed during get
- return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.VAULT_DECRYPT_FAILED) };
+ // Keep an already-coded error (the key chain reports its own failures) instead of masking it.
+ if (hasErrorCode(error)) {
+ return { success: false, error: getErrorMessage(error, '') };
+ }
+ // E-601: reading the vault or its key from storage failed
+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.STORAGE_READ_FAILED) };
}
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index ad266e1fd..d6479eaef 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -1,4 +1,4 @@
-import { hasErrorCode, getErrorMessage, extractErrorCode, AppErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
+import { hasErrorCode, getErrorMessage, extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
@@ -288,8 +288,8 @@ const Unlock: React.FC = () => {
});
/*
- * Fetch the account key chain, check the unlock key opens it and cache it as-is. Throws a decrypt-failed
- * (E-203) error on a wrong password.
+ * Fetch the account key chain, check the unlock key opens it and cache it as-is. Throws an unlock-key-rejected
+ * (E-206) error on a wrong password.
*/
unlockKey = credentials.passwordHashBase64;
await VaultKeyService.refreshKeyChain(unlockKey, webApi);
@@ -308,8 +308,8 @@ const Unlock: React.FC = () => {
const credentials = await SrpAuthService.prepareCredentials(password, storedParams.salt, storedParams.encryptionSettings);
/*
- * Offline: check the unlock key opens the locally cached account key chain. Throws a decrypt-failed
- * (E-203) error on a wrong password.
+ * Offline: check the unlock key opens the locally cached account key chain. Throws an unlock-key-rejected
+ * (E-206) error on a wrong password.
*/
unlockKey = credentials.passwordHashBase64;
await VaultKeyService.verifyUnlockKey(unlockKey);
@@ -361,9 +361,7 @@ const Unlock: React.FC = () => {
// Check if it's a version incompatibility error
await app.logout(err.message);
} else if (hasErrorCode(err)) {
- // Check if it's a decryption failure (E-203): this means wrong password
- const errorCode = extractErrorCode(getErrorMessage(err, ''));
- if (errorCode === AppErrorCode.VAULT_DECRYPT_FAILED) {
+ if (await VaultKeyService.isWrongUnlockKey(extractErrorCode(getErrorMessage(err, '')))) {
await handlePasswordFailedAttempt();
} else {
// Other error codes, show the formatted message as-is
@@ -486,10 +484,8 @@ const Unlock: React.FC = () => {
setError(t('settings.unlockMethod.invalidPinFormat'));
setPin('');
} else if (hasErrorCode(err)) {
- // Check if it's a decryption failure, this means wrong PIN
- const errorCode = extractErrorCode(getErrorMessage(err, ''));
- if (errorCode === AppErrorCode.VAULT_DECRYPT_FAILED) {
- // Decryption failed during PIN unlock = wrong PIN, treat as incorrect PIN
+ if (await VaultKeyService.isWrongUnlockKey(extractErrorCode(getErrorMessage(err, '')))) {
+ // The key the PIN restored does not unlock the vault, treat as incorrect PIN
logExpected('[Unlock] The entered PIN did not decrypt the vault', err);
setError(t('settings.unlockMethod.incorrectPin', { attemptsRemaining: 3 }));
} else {
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt
index a51e3c2d3..5ef093f9a 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt
@@ -215,6 +215,8 @@ class UnlockCoordinator(
val errorMessage = when (e) {
is AppError.KeystoreKeyNotFound -> "Please unlock vault in the app first"
is AppError.VaultDecryptFailed,
+ is AppError.UnlockKeyRejected,
+ is AppError.KeyChainUnreadable,
is AppError.DatabaseOpenFailed,
is AppError.DatabaseBackupFailed,
-> "Failed to decrypt vault"
@@ -249,6 +251,8 @@ class UnlockCoordinator(
return when (e) {
is AppError.KeystoreKeyNotFound -> "Please unlock vault in the app first"
is AppError.VaultDecryptFailed,
+ is AppError.UnlockKeyRejected,
+ is AppError.KeyChainUnreadable,
is AppError.DatabaseOpenFailed,
is AppError.DatabaseBackupFailed,
-> "Failed to decrypt vault"
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
index 02465aefc..41de47e65 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/AppError.kt
@@ -123,13 +123,45 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
// Decryption errors
/**
- * Error indicating failed to decrypt vault.
+ * Error indicating the locally stored vault does not decrypt with the session key.
*/
class VaultDecryptFailed(
message: String = "Failed to decrypt vault",
cause: Throwable? = null,
) : AppError(message, cause)
+ /**
+ * Error indicating the unlock key does not open the account key (wrong password or PIN).
+ */
+ class UnlockKeyRejected(
+ message: String = "The unlock key does not open the account key",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating the account key opened, the vault encryption key under it did not.
+ */
+ class KeyChainUnreadable(
+ message: String,
+ cause: Throwable? = null,
+ ) : AppError("The account key does not open the vault encryption key: $message", cause)
+
+ /**
+ * Error indicating the session key does not open the key chain the server holds; only a re-login recovers.
+ */
+ class KeyOutOfSync(
+ message: String = "Vault encryption key out of sync with the server; log in again",
+ cause: Throwable? = null,
+ ) : AppError(message, cause)
+
+ /**
+ * Error indicating a server manifest or bucket fails its hash check or does not decrypt.
+ */
+ class ServerVaultDecryptFailed(
+ message: String,
+ cause: Throwable? = null,
+ ) : AppError("Server vault could not be opened: $message", cause)
+
/**
* Error indicating base64 decode failed after decryption.
*/
@@ -438,6 +470,10 @@ sealed class AppError(message: String, cause: Throwable? = null) : Exception(mes
is BiometricNotAvailable -> "E-514"
is BiometricNotEnrolled -> "E-515"
is BiometricLockout -> "E-516"
+ is UnlockKeyRejected -> "E-517"
+ is KeyChainUnreadable -> "E-518"
+ is KeyOutOfSync -> "E-519"
+ is ServerVaultDecryptFailed -> "E-520"
is StorageReadFailed -> "E-601"
is StorageWriteFailed -> "E-602"
is DatabaseInitFailed -> "E-603"
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
index 9a1fc42db..b595737e3 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
@@ -242,8 +242,17 @@ class VaultCrypto(
val encryptedAccountKey = chain.optString("encryptedAccountKey").takeIf { it.isNotEmpty() } ?: return SessionKeys(derivedKey, null)
val encryptedVek = chain.optString("encryptedVek").takeIf { it.isNotEmpty() } ?: error("Account key chain is missing the encrypted VEK")
- val accountKey = decrypt(Base64.decode(encryptedAccountKey, Base64.NO_WRAP), derivedKey)
- val vaultEncryptionKey = decrypt(Base64.decode(encryptedVek, Base64.NO_WRAP), accountKey)
+ val accountKey = try {
+ decrypt(Base64.decode(encryptedAccountKey, Base64.NO_WRAP), derivedKey)
+ } catch (e: Exception) {
+ throw AppError.UnlockKeyRejected(cause = e)
+ }
+ // The account key opened, so a failure here is a damaged chain and never a wrong password.
+ val vaultEncryptionKey = try {
+ decrypt(Base64.decode(encryptedVek, Base64.NO_WRAP), accountKey)
+ } catch (e: Exception) {
+ throw AppError.KeyChainUnreadable(e.message ?: "decrypt failed", e)
+ }
// A private key that does not open must not fail the unlock; grants stay closed until the next login.
val accountPrivateKey = chain.optString("encryptedAccountPrivateKey").takeIf { it.isNotEmpty() }?.let {
@@ -329,9 +338,12 @@ class VaultCrypto(
try {
openSession(Base64.decode(result, Base64.NO_WRAP))
callback.onSuccess(Base64.encodeToString(key(), Base64.NO_WRAP))
+ } catch (e: AppError) {
+ Log.e(TAG, "The unlock key from the keystore does not open the account key chain", e)
+ callback.onError(e)
} catch (e: Exception) {
Log.e(TAG, "The unlock key from the keystore does not open the account key chain", e)
- callback.onError(AppError.VaultDecryptFailed(cause = e))
+ callback.onError(AppError.UnlockKeyRejected(cause = e))
}
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
index 6ae7ffd09..872f2a396 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
@@ -264,7 +264,11 @@ class VaultSync(
"E-509" -> AppError.SyncEngineFailed(message)
"E-502" -> AppError.SyncVaultFetchFailed(message)
"E-202" -> AppError.EncryptionKeyNotFound()
- "E-203", "E-503" -> AppError.VaultDecryptFailed()
+ "E-203" -> AppError.VaultDecryptFailed()
+ "E-206" -> AppError.UnlockKeyRejected()
+ "E-207" -> AppError.KeyChainUnreadable(message)
+ "E-208" -> AppError.KeyOutOfSync()
+ "E-503" -> AppError.ServerVaultDecryptFailed(message)
"E-601" -> AppError.StorageReadFailed(message)
"E-602" -> AppError.StorageWriteFailed(message)
"E-603" -> AppError.DatabaseInitFailed(message)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
index fecc540c7..13ee81aba 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
@@ -4,7 +4,6 @@ import android.util.Base64
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
-import net.aliasvault.app.R
import net.aliasvault.app.rustcore.JnaInitializer
import net.aliasvault.app.utils.AppInfo
import net.aliasvault.app.vaultstore.models.VaultSql
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index c856f2d68..e6dde24ed 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -23,6 +23,17 @@ import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
+/**
+ * Whether a failed unlock means the entered password was wrong.
+ * @param errorCode - the error code the unlock failed with
+ */
+async function isWrongUnlockKey(errorCode: AppErrorCode): Promise<boolean> {
+ if (errorCode === AppErrorCode.UNLOCK_KEY_REJECTED) {
+ return true;
+ }
+ return errorCode === AppErrorCode.VAULT_DECRYPT_FAILED && (await NativeVaultManager.getAccountKeyChain()) === null;
+}
+
/**
* Unlock screen.
*/
@@ -148,7 +159,7 @@ export default function UnlockScreen() : React.ReactNode {
// Haptic feedback for authentication error
HapticsUtility.notification(Haptics.NotificationFeedbackType.Error);
- if (!errorCode || errorCode === AppErrorCode.VAULT_DECRYPT_FAILED) {
+ if (!errorCode || await isWrongUnlockKey(errorCode)) {
setError(t('auth.errors.incorrectPassword'));
} else {
const translationKey = getErrorTranslationKey(errorCode);
@@ -236,11 +247,7 @@ export default function UnlockScreen() : React.ReactNode {
// Haptic feedback for authentication error
HapticsUtility.notification(Haptics.NotificationFeedbackType.Error);
- /*
- * During unlock, VAULT_DECRYPT_FAILED indicates wrong password.
- * This is thrown when decryption fails due to incorrect encryption key.
- */
- if (!errorCode || errorCode === AppErrorCode.VAULT_DECRYPT_FAILED) {
+ if (!errorCode || await isWrongUnlockKey(errorCode)) {
// Treat as incorrect password - show error and allow retry
setError(t('auth.errors.incorrectPassword'));
} else {
diff --git a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
index b649f389d..4ff02a603 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
@@ -25,7 +25,16 @@ public enum AppError: Error {
case syncVaultFetchFailed(message: String)
// Decryption errors
+ /// The locally stored vault does not decrypt with the session key.
case vaultDecryptFailed
+ /// The unlock key does not open the account key (wrong password or PIN).
+ case unlockKeyRejected
+ /// The account key opened, the vault encryption key under it did not.
+ case keyChainUnreadable(message: String)
+ /// The session key does not open the key chain the server holds; only a re-login recovers.
+ case keyOutOfSync
+ /// A server manifest or bucket fails its hash check or does not decrypt.
+ case serverVaultDecryptFailed(message: String)
case base64DecodeFailed
case databaseTempWriteFailed
case databaseOpenFailed
@@ -149,6 +158,14 @@ public enum AppError: Error {
return "E-515"
case .biometricLockout:
return "E-516"
+ case .unlockKeyRejected:
+ return "E-517"
+ case .keyChainUnreadable:
+ return "E-518"
+ case .keyOutOfSync:
+ return "E-519"
+ case .serverVaultDecryptFailed:
+ return "E-520"
case .storageReadFailed:
return "E-601"
case .storageWriteFailed:
@@ -217,6 +234,14 @@ public enum AppError: Error {
return "Server vault could not be assembled: \(message)"
case .vaultDecryptFailed:
return "Failed to decrypt vault"
+ case .unlockKeyRejected:
+ return "The unlock key does not open the account key"
+ case .keyChainUnreadable(let message):
+ return "The account key does not open the vault encryption key: \(message)"
+ case .keyOutOfSync:
+ return "Vault encryption key out of sync with the server; log in again"
+ case .serverVaultDecryptFailed(let message):
+ return "Server vault could not be opened: \(message)"
case .encryptionKeyNotFound:
return "Encryption key not available"
case .base64DecodeFailed:
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
index c7908175d..20e7b1424 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
@@ -230,8 +230,11 @@ internal final class VaultSync {
private static let codedErrors: [String: (String) -> AppError] = [
"E-202": { _ in .encryptionKeyNotFound },
"E-203": { _ in .vaultDecryptFailed },
+ "E-206": { _ in .unlockKeyRejected },
+ "E-207": { .keyChainUnreadable(message: $0) },
+ "E-208": { _ in .keyOutOfSync },
"E-502": { .syncVaultFetchFailed(message: $0) },
- "E-503": { _ in .vaultDecryptFailed },
+ "E-503": { .serverVaultDecryptFailed(message: $0) },
"E-505": { _ in .serverUnavailable(statusCode: 0) },
"E-506": { .serverError(message: $0) },
"E-507": { .syncResponseInvalid(message: $0) },
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index 85535ae99..d9c726dc2 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -122,8 +122,16 @@ extension VaultStore {
throw NSError(domain: "VaultStore", code: 41, userInfo: [NSLocalizedDescriptionKey: "Account key chain is missing the encrypted VEK"])
}
- let accountKey = try unwrapKey(encryptedAccountKey, with: derivedKey)
- let vaultEncryptionKey = try unwrapKey(encryptedVek, with: accountKey)
+ guard let accountKey = try? unwrapKey(encryptedAccountKey, with: derivedKey) else {
+ throw AppError.unlockKeyRejected
+ }
+ // The account key opened, so a failure here is a damaged chain and never a wrong password.
+ let vaultEncryptionKey: Data
+ do {
+ vaultEncryptionKey = try unwrapKey(encryptedVek, with: accountKey)
+ } catch {
+ throw AppError.keyChainUnreadable(message: error.localizedDescription)
+ }
// A private key that does not open must not fail the unlock; grants stay closed until the next login.
var accountPrivateKey: String?
@@ -322,9 +330,12 @@ extension VaultStore {
do {
try openSession(unlockKey: keyData)
+ } catch let vaultError as AppError {
+ print("The unlock key from the keychain does not open the account key chain: \(vaultError.message)")
+ throw vaultError
} catch {
print("The unlock key from the keychain does not open the account key chain: \(error)")
- throw AppError.vaultDecryptFailed
+ throw AppError.unlockKeyRejected
}
return
}
diff --git a/apps/mobile-app/utils/types/errors/AppErrorCodes.ts b/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
index 166a4f791..0724431e2 100644
--- a/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
+++ b/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
@@ -51,7 +51,7 @@ export enum AppErrorCode {
SYNC_VAULT_FETCH_FAILED = 'E-404', // Sync engine: the server's vault snapshot cannot be assembled
// Decryption/Encryption errors (E-5xx) - from AppError.kt
- VAULT_DECRYPT_FAILED = 'E-501',
+ VAULT_DECRYPT_FAILED = 'E-501', // AppError: the locally stored vault does not decrypt with the session key
ENCRYPTION_KEY_NOT_FOUND = 'E-502', // AppError: encryption key not available
BASE64_DECODE_FAILED = 'E-503', // AppError: base64 decode failed after decryption
DATABASE_TEMP_WRITE_FAILED = 'E-504', // AppError: could not write temp file
@@ -67,6 +67,10 @@ export enum AppErrorCode {
BIOMETRIC_NOT_AVAILABLE = 'E-514', // iOS: biometric not available on device
BIOMETRIC_NOT_ENROLLED = 'E-515', // iOS: no biometrics enrolled on device
BIOMETRIC_LOCKOUT = 'E-516', // iOS: biometric locked out due to too many failed attempts
+ UNLOCK_KEY_REJECTED = 'E-517', // AppError: the unlock key does not open the account key (wrong password or PIN)
+ KEY_CHAIN_UNREADABLE = 'E-518', // AppError: the account key opened, the vault encryption key under it did not
+ KEY_OUT_OF_SYNC = 'E-519', // Sync engine: the session key does not open the key chain the server holds (re-login needed)
+ SERVER_VAULT_DECRYPT_FAILED = 'E-520', // Sync engine: a server manifest or bucket fails its hash check or does not decrypt
// Database/Storage errors (E-6xx) - from VaultSync.kt
STORAGE_READ_FAILED = 'E-601', // Sync engine: a state, database or at-rest vault read failed
@@ -249,6 +253,10 @@ export function getErrorTranslationKey(code: AppErrorCode): string {
[AppErrorCode.BIOMETRIC_NOT_AVAILABLE]: 'common.errors.unknownErrorTryAgain',
[AppErrorCode.BIOMETRIC_NOT_ENROLLED]: 'common.errors.unknownErrorTryAgain',
[AppErrorCode.BIOMETRIC_LOCKOUT]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.UNLOCK_KEY_REJECTED]: 'auth.errors.incorrectPassword',
+ [AppErrorCode.KEY_CHAIN_UNREADABLE]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.KEY_OUT_OF_SYNC]: 'auth.errors.sessionExpired',
+ [AppErrorCode.SERVER_VAULT_DECRYPT_FAILED]: 'common.errors.unknownErrorTryAgain',
// Database/Storage errors
[AppErrorCode.STORAGE_READ_FAILED]: 'common.errors.unknownErrorTryAgain',
diff --git a/core/client/src/api/errors/AppErrorCodes.ts b/core/client/src/api/errors/AppErrorCodes.ts
index c13a69cb2..afc2d33fe 100644
--- a/core/client/src/api/errors/AppErrorCodes.ts
+++ b/core/client/src/api/errors/AppErrorCodes.ts
@@ -33,9 +33,12 @@ export enum AppErrorCode {
// Vault retrieval errors (E-2xx) - handleGetVault
VAULT_NOT_FOUND = 'E-201', // No encrypted vault in storage
VAULT_LOCKED = 'E-202', // No encryption key available
- VAULT_DECRYPT_FAILED = 'E-203', // Decryption failed
+ VAULT_DECRYPT_FAILED = 'E-203', // The locally stored vault does not decrypt with the session key
VAULT_METADATA_READ_FAILED = 'E-204', // Failed to read vault metadata
VAULT_LOAD_TIMEOUT = 'E-205', // Background did not return the vault in time
+ UNLOCK_KEY_REJECTED = 'E-206', // The unlock key does not open the account key (wrong password)
+ KEY_CHAIN_UNREADABLE = 'E-207', // The account key opened, the vault encryption key under it did not
+ KEY_OUT_OF_SYNC = 'E-208', // The session key does not open the key chain the server holds (re-login needed)
// Item/credential operations (E-3xx) - handleCreateItem, handleUpdateItem, etc.
ITEM_CREATE_FAILED = 'E-301',
@@ -139,6 +142,9 @@ export function getErrorTranslationKey(code: AppErrorCode): string {
[AppErrorCode.VAULT_DECRYPT_FAILED]: 'common.errors.unknownErrorTryAgain',
[AppErrorCode.VAULT_METADATA_READ_FAILED]: 'common.errors.unknownErrorTryAgain',
[AppErrorCode.VAULT_LOAD_TIMEOUT]: 'common.errors.vaultLoadTimeout',
+ [AppErrorCode.UNLOCK_KEY_REJECTED]: 'common.errors.wrongPassword',
+ [AppErrorCode.KEY_CHAIN_UNREADABLE]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.KEY_OUT_OF_SYNC]: 'common.errors.sessionExpired',
// Item/credential operations (E-3xx)
[AppErrorCode.ITEM_CREATE_FAILED]: 'common.errors.unknownErrorTryAgain',
diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.ts
index 135cb618f..a0b7c9440 100644
--- a/core/client/src/auth/MasterPasswordService.ts
+++ b/core/client/src/auth/MasterPasswordService.ts
@@ -93,7 +93,7 @@ export class MasterPasswordService {
return PasswordVerificationResult.Success;
} catch (error) {
const code = error instanceof Error ? extractErrorCode(error.message) : null;
- return code === AppErrorCode.VAULT_DECRYPT_FAILED ? PasswordVerificationResult.InvalidPassword : PasswordVerificationResult.VerificationError;
+ return code === AppErrorCode.UNLOCK_KEY_REJECTED ? PasswordVerificationResult.InvalidPassword : PasswordVerificationResult.VerificationError;
}
} catch (error) {
logDefect('[MasterPassword] Password verification failed unexpectedly', error);
diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.ts
index 72fe4142b..651727611 100644
--- a/core/client/src/auth/VaultKeyService.ts
+++ b/core/client/src/auth/VaultKeyService.ts
@@ -59,7 +59,7 @@ export class VaultKeyService {
* and cache it for offline unlock.
* @param unlockKeyBase64 - the password-derived key (the KEK)
* @param webApi - the API client to use
- * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when the key does not open the chain (wrong password).
+ * @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).
*/
public static async refreshKeyChain(unlockKeyBase64: string, webApi?: WebApiService): Promise<void> {
const result = await VaultKeyService.fetchVaultKey(webApi);
@@ -82,7 +82,7 @@ export class VaultKeyService {
/**
* Check offline that the unlock key opens the locally cached chain. A legacy account has no chain to check against.
* @param unlockKeyBase64 - the password-derived key (the KEK), typed in or restored by PIN
- * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when the key does not open the chain (wrong password).
+ * @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).
*/
public static async verifyUnlockKey(unlockKeyBase64: string): Promise<void> {
await VaultKeyService.openKeyChain(unlockKeyBase64);
@@ -98,6 +98,18 @@ export class VaultKeyService {
return (await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY) as string | null) !== null;
}
+ /**
+ * Whether a failed unlock means the entered password or PIN was wrong. A key chain rejects a wrong key itself;
+ * a legacy account has no chain, so there the stored vault failing to decrypt is the only signal.
+ * @param code - the error code the unlock failed with
+ */
+ public static async isWrongUnlockKey(code: AppErrorCode | null): Promise<boolean> {
+ if (code === AppErrorCode.UNLOCK_KEY_REJECTED) {
+ return true;
+ }
+ return code === AppErrorCode.VAULT_DECRYPT_FAILED && !await VaultKeyService.hasLocalVaultKey();
+ }
+
/**
* The unlock key of this session (the password-derived KEK), or null when the vault is locked.
*/
@@ -153,7 +165,7 @@ export class VaultKeyService {
* Open the locally cached chain with the unlock key. Without a cached chain (legacy account) the unlock key is
* the vault encryption key.
* @param unlockKeyBase64 - the password-derived key (the KEK)
- * @throws Error with {@link AppErrorCode.VAULT_DECRYPT_FAILED} when the key does not open the chain.
+ * @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain.
*/
public static async openKeyChain(unlockKeyBase64: string): Promise<SessionKeys> {
const storage = getPlatform().storage;
@@ -180,8 +192,10 @@ export class VaultKeyService {
throw new Error('Vault key chain is missing the encrypted VEK');
}
- const accountKey = await VaultKeyService.decryptKeyOrThrow(encryptedAccountKey, unlockKeyBase64);
- const vaultEncryptionKey = await VaultKeyService.decryptKeyOrThrow(encryptedVek, accountKey);
+ // E-206: the unlock key does not open the account key, which for the password key type means a wrong password.
+ const accountKey = await VaultKeyService.decryptKeyOrThrow(encryptedAccountKey, unlockKeyBase64, AppErrorCode.UNLOCK_KEY_REJECTED);
+ // E-207: the account key opened, so a failure here is a damaged chain and never a wrong password.
+ const vaultEncryptionKey = await VaultKeyService.decryptKeyOrThrow(encryptedVek, accountKey, AppErrorCode.KEY_CHAIN_UNREADABLE);
let accountPrivateKey: string | null = null;
if (encryptedAccountPrivateKey) {
@@ -213,17 +227,16 @@ export class VaultKeyService {
}
/**
- * Decrypt an encrypted key blob, mapping an AES-GCM authentication failure onto the standard decrypt-failed
- * error code so existing wrong-password handling applies.
+ * Decrypt an encrypted key blob, reporting a failure under the code of the chain step it belongs to.
* @param encryptedKey - encrypted key blob
- * @param decryptingKeyBase64 - the key that decrypts it (the KEK derived from the unlock method)
+ * @param decryptingKeyBase64 - the key that decrypts it
+ * @param failureCode - the error code a failure of this step carries
*/
- private static async decryptKeyOrThrow(encryptedKey: string, decryptingKeyBase64: string): Promise<string> {
+ private static async decryptKeyOrThrow(encryptedKey: string, decryptingKeyBase64: string, failureCode: AppErrorCode): Promise<string> {
try {
return await EncryptionUtility.decryptVaultEncryptionKey(encryptedKey, decryptingKeyBase64);
} catch {
- // E-203: decrypt failed, which for the password key type means the entered password is wrong.
- throw new Error(formatErrorWithCode('Failed to decrypt vault encryption key', AppErrorCode.VAULT_DECRYPT_FAILED));
+ throw new Error(formatErrorWithCode('Failed to decrypt key chain', failureCode));
}
}
}
diff --git a/core/rust/src/vault_sync/errors.rs b/core/rust/src/vault_sync/errors.rs
index 0c15af5cf..42ff5cc03 100644
--- a/core/rust/src/vault_sync/errors.rs
+++ b/core/rust/src/vault_sync/errors.rs
@@ -16,6 +16,15 @@ pub enum ErrorCode {
/// The stored vault does not decrypt with the session key.
#[serde(rename = "E-203")]
VaultDecryptFailed,
+ /// The unlock key does not open the account key (wrong password).
+ #[serde(rename = "E-206")]
+ UnlockKeyRejected,
+ /// The account key opened, the vault encryption key under it did not.
+ #[serde(rename = "E-207")]
+ KeyChainUnreadable,
+ /// The session key does not open the key chain the server holds; only a re-login recovers.
+ #[serde(rename = "E-208")]
+ KeyOutOfSync,
/// The server's snapshot cannot be assembled into a vault.
#[serde(rename = "E-502")]
SyncVaultFetchFailed,
@@ -118,6 +127,12 @@ pub enum SyncError {
/// The stored vault does not decrypt with the session key.
#[error("Vault could not be decrypted: {0}")]
VaultDecryptFailed(String),
+ /// The unlock key does not open the account key (wrong password).
+ #[error("The unlock key does not open the account key")]
+ UnlockKeyRejected,
+ /// The account key opened, the vault encryption key under it did not.
+ #[error("The account key does not open the vault encryption key: {0}")]
+ KeyChainUnreadable(String),
/// The session key matches neither the server's KEK nor its VEK; only a re-login recovers.
#[error("Vault encryption key out of sync with the server; log in again")]
KeyOutOfSync,
@@ -168,7 +183,10 @@ impl SyncError {
SyncError::PayloadTooLarge => Failure::Coded(ErrorCode::UploadTooLarge),
SyncError::Http { .. } => Failure::Coded(ErrorCode::SyncServerError),
SyncError::VaultLocked => Failure::Coded(ErrorCode::VaultLocked),
- SyncError::VaultDecryptFailed(_) | SyncError::KeyOutOfSync => Failure::Coded(ErrorCode::VaultDecryptFailed),
+ SyncError::VaultDecryptFailed(_) => Failure::Coded(ErrorCode::VaultDecryptFailed),
+ SyncError::UnlockKeyRejected => Failure::Coded(ErrorCode::UnlockKeyRejected),
+ SyncError::KeyChainUnreadable(_) => Failure::Coded(ErrorCode::KeyChainUnreadable),
+ SyncError::KeyOutOfSync => Failure::Coded(ErrorCode::KeyOutOfSync),
SyncError::ServerVaultUnreadable(_) => Failure::Coded(ErrorCode::SyncVaultDecryptFailed),
SyncError::Snapshot(_) => Failure::Coded(ErrorCode::SyncVaultFetchFailed),
SyncError::MergeFailed(_) => Failure::Coded(ErrorCode::MergeFailed),
@@ -205,6 +223,10 @@ mod tests {
fn codes_and_reasons_serialize_to_the_client_vocabulary() {
assert_eq!(serde_json::to_string(&ErrorCode::VaultLocked).unwrap(), "\"E-202\"");
assert_eq!(serde_json::to_string(&ErrorCode::UploadTimeout).unwrap(), "\"E-805\"");
+ assert_eq!(SyncError::VaultDecryptFailed(String::new()).failure(), Failure::Coded(ErrorCode::VaultDecryptFailed));
+ assert_eq!(SyncError::UnlockKeyRejected.failure(), Failure::Coded(ErrorCode::UnlockKeyRejected));
+ assert_eq!(SyncError::KeyChainUnreadable(String::new()).failure(), Failure::Coded(ErrorCode::KeyChainUnreadable));
+ assert_eq!(SyncError::KeyOutOfSync.failure(), Failure::Coded(ErrorCode::KeyOutOfSync));
assert_eq!(serde_json::to_string(&LogoutReason::PasswordChanged).unwrap(), "\"passwordChanged\"");
assert_eq!(SyncError::Auth.failure(), Failure::Logout(LogoutReason::SessionExpired));
assert_eq!(SyncError::Host { command: CommandKind::DbOpen, message: String::new() }.failure(), Failure::Coded(ErrorCode::DatabaseInitFailed));
diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rs
index 9766da223..b29aed079 100644
--- a/core/rust/src/vault_sync/keys.rs
+++ b/core/rust/src/vault_sync/keys.rs
@@ -8,6 +8,7 @@ use super::state::{self, Ctx};
use super::types::{SharedManifestDto, VaultKeyGetResponse, VaultKeyResponse, ALGORITHM_RSA_OAEP_SHA256};
use super::{db, http};
use crate::crypto;
+use zeroize::Zeroizing;
/// Whether this device holds a vault key.
pub(crate) async fn has_local_vault_key(host: &Host) -> SyncResult<bool> {
@@ -136,9 +137,17 @@ async fn clear_cached_chain(host: &Host) -> SyncResult<()> {
Ok(())
}
+/// Walk a key chain, telling a key that does not open the account key (wrong password) apart from a chain whose VEK
+/// does not open under its own account key. Returns the VEK and the Account Key.
+fn walk_chain(encrypted_account_key: &str, encrypted_vek: &str, kek: &str) -> SyncResult<(Zeroizing<String>, Zeroizing<String>)> {
+ let account_key = crypto::unwrap_key(encrypted_account_key, kek).map_err(|_| SyncError::UnlockKeyRejected)?;
+ let vek = crypto::unwrap_key(encrypted_vek, &account_key).map_err(|e| SyncError::KeyChainUnreadable(e.to_string()))?;
+ Ok((vek, account_key))
+}
+
/// Open a key chain with the password-derived key: the VEK becomes the session key and the private key is staged.
async fn open_chain(ctx: &mut Ctx, encrypted_account_key: &str, encrypted_vek: &str, encrypted_private_key: Option<&str>, kek: &str) -> SyncResult<()> {
- let (vek, account_key) = crypto::resolve_vault_encryption_key(encrypted_account_key, encrypted_vek, kek).map_err(|_| SyncError::VaultDecryptFailed("the password-derived key does not open the account key chain".to_string()))?;
+ let (vek, account_key) = walk_chain(encrypted_account_key, encrypted_vek, kek)?;
ctx.set_encryption_key(vek.to_string());
stage_account_private_key(ctx, &account_key, encrypted_private_key).await;
Ok(())
@@ -184,7 +193,8 @@ pub(crate) async fn resolve_vault_key(ctx: &mut Ctx) -> SyncResult<bool> {
/// hierarchy exists, the stored vault is brought under the VEK and the session key swapped, which the host adopts
/// through the store command. Callers gate this on the absence of a cached chain and on a sync that pulls or
/// pushes: another device's migration shows up as a revision change, so that is when it becomes visible.
-/// False only when the session key does not open the server's chain, which requires a re-login.
+/// False only when the session key does not open the server's chain, which requires a re-login; any other failure
+/// is returned as itself.
pub(crate) async fn adopt_hierarchy_created_elsewhere(ctx: &mut Ctx) -> SyncResult<bool> {
if ctx.vault_key_probed {
return Ok(true);
@@ -203,7 +213,7 @@ pub(crate) async fn adopt_hierarchy_created_elsewhere(ctx: &mut Ctx) -> SyncResu
// Hosts hold the unlock key and derive the vault key from the cached chain.
let adopted: SyncResult<()> = async {
- let (vek, account_key) = crypto::resolve_vault_encryption_key(&vault_key.encrypted_account_key, &encrypted_vek, &session_key)?;
+ let (vek, account_key) = walk_chain(&vault_key.encrypted_account_key, &encrypted_vek, &session_key)?;
cache_vault_key_blobs(&ctx.host, &vault_key).await?;
adopt_vek(ctx, &session_key, &vek).await?;
stage_account_private_key(ctx, &account_key, vault_key.encrypted_account_private_key.as_deref()).await;
@@ -216,10 +226,12 @@ pub(crate) async fn adopt_hierarchy_created_elsewhere(ctx: &mut Ctx) -> SyncResu
ctx.log("[VaultSync] Another device created the account's key hierarchy; adopted it and swapped the session key to the VEK.").await;
Ok(true)
}
- Err(error) => {
- ctx.warn(format!("[VaultSync] The session key does not open the key hierarchy the server holds, forcing re-login: {}", error)).await;
+ Err(SyncError::UnlockKeyRejected) => {
+ ctx.warn("[VaultSync] The session key does not open the key hierarchy the server holds; a re-login is needed.").await;
Ok(false)
}
+ // A storage failure or an unreadable stored vault is its own failure, not a key mismatch.
+ Err(error) => Err(error),
}
}
diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rs
index e2d8599f8..86e8a3985 100644
--- a/core/rust/src/vault_sync/tests/mod.rs
+++ b/core/rust/src/vault_sync/tests/mod.rs
@@ -692,7 +692,7 @@ fn resolve_vault_key_opens_the_cached_chain_when_the_server_is_unreachable() {
assert_eq!(result["encryptionKey"], hierarchy.vault_encryption_key);
}
-/// A key that does not open the chain is reported as a decrypt failure, never silently kept.
+/// A key that does not open the chain is reported as a rejected unlock key, never silently kept.
#[test]
fn resolve_vault_key_refuses_a_key_that_does_not_open_the_chain() {
let hierarchy = crypto::create_account_key_hierarchy(&crypto::generate_key_base64()).unwrap();
@@ -703,10 +703,25 @@ fn resolve_vault_key_refuses_a_key_that_does_not_open_the_chain() {
let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &wrong_kek, false, 0)).unwrap());
assert_eq!(result["success"], false);
- assert_eq!(result["errorCode"], "E-203");
+ assert_eq!(result["errorCode"], "E-206");
assert!(result.get("encryptionKey").is_none());
}
+/// A chain whose VEK does not open under its own account key is not reported as a wrong password.
+#[test]
+fn resolve_vault_key_tells_an_unreadable_chain_apart_from_a_wrong_password() {
+ let kek = crypto::generate_key_base64();
+ let mut hierarchy = crypto::create_account_key_hierarchy(&kek).unwrap();
+ hierarchy.account_keys.encrypted_vek = crypto::wrap_key(&crypto::generate_key_base64(), &crypto::generate_key_base64()).unwrap();
+ let mut host = TestHost::new(&kek);
+ host.respond("GET", "VaultKey/Password", vault_key_body(&hierarchy));
+
+ let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &kek, false, 0)).unwrap());
+
+ assert_eq!(result["success"], false);
+ assert_eq!(result["errorCode"], "E-207");
+}
+
/// The sync trusts the key it is given: a KEK handed to a device that caches the chain is not upgraded any more,
/// so the run fails to open the vault instead of silently swapping keys. Resolving the key is the host's job.
#[test]