fix(profiles): treat vault decrypt failures as lost credentials
A failed MAC check (key/ciphertext divergence: restored backup, clobbered prefs, racing key generation across isolates) threw from CredentialVault.reveal on the startup profile-settings path and crash-looped the app until data was wiped — one device logged 31 fatals in 16 minutes on 2.8.0. Decrypt failure now means the credential is lost, never a crash: reveal() returns null, ProfileConnectionRegistry maps it onto the existing empty-token lazy-fetch sentinel and heals the row so later boots re-acquire the token instead of re-failing, and revealConnectionConfig degrades tokens to empty strings without marking them migrated. Key init also reloads prefs before deciding to generate and re-reads after writing, adopting whatever landed so all isolates converge on a single key instead of orphaning ciphertext.
This commit is contained in:
@@ -2,7 +2,9 @@ import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:cryptography/cryptography.dart';
|
||||
import 'package:flutter/foundation.dart' show visibleForTesting;
|
||||
|
||||
import '../utils/app_logger.dart';
|
||||
import 'base_shared_preferences_service.dart';
|
||||
|
||||
/// Encrypts credentials before they are persisted in Drift config/token
|
||||
@@ -21,6 +23,12 @@ class CredentialVault {
|
||||
static final AesGcm _algorithm = AesGcm.with256bits();
|
||||
static Future<SecretKey>? _secretKey;
|
||||
|
||||
/// Drops the memoized key so tests can simulate key loss/divergence.
|
||||
@visibleForTesting
|
||||
static void resetKeyForTesting() {
|
||||
_secretKey = null;
|
||||
}
|
||||
|
||||
static bool isProtected(String? value) => value != null && value.startsWith(_prefix);
|
||||
|
||||
static Future<String> protect(String value) async {
|
||||
@@ -30,16 +38,26 @@ class CredentialVault {
|
||||
return '$_prefix${jsonEncode({'n': base64Encode(box.nonce), 'c': base64Encode(box.cipherText), 'm': base64Encode(box.mac.bytes)})}';
|
||||
}
|
||||
|
||||
static Future<String> reveal(String value) async {
|
||||
/// Decrypts a protected value, or returns it unchanged when it isn't
|
||||
/// protected. Returns null when decryption fails — a failed MAC check
|
||||
/// (key/ciphertext divergence: restored backup, clobbered prefs, racing
|
||||
/// key generation) or a corrupt payload means the credential is *lost*,
|
||||
/// never a reason to crash; callers treat null as "re-acquire the token".
|
||||
static Future<String?> reveal(String value) async {
|
||||
if (!isProtected(value)) return value;
|
||||
final payload = jsonDecode(value.substring(_prefix.length)) as Map<String, dynamic>;
|
||||
final box = SecretBox(
|
||||
base64Decode(payload['c'] as String),
|
||||
nonce: base64Decode(payload['n'] as String),
|
||||
mac: Mac(base64Decode(payload['m'] as String)),
|
||||
);
|
||||
final clear = await _algorithm.decrypt(box, secretKey: await _getSecretKey());
|
||||
return utf8.decode(clear);
|
||||
try {
|
||||
final payload = jsonDecode(value.substring(_prefix.length)) as Map<String, dynamic>;
|
||||
final box = SecretBox(
|
||||
base64Decode(payload['c'] as String),
|
||||
nonce: base64Decode(payload['n'] as String),
|
||||
mac: Mac(base64Decode(payload['m'] as String)),
|
||||
);
|
||||
final clear = await _algorithm.decrypt(box, secretKey: await _getSecretKey());
|
||||
return utf8.decode(clear);
|
||||
} catch (e) {
|
||||
appLogger.w('CredentialVault: failed to decrypt stored credential, treating as lost', error: e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<Map<String, Object?>> protectConnectionConfig(String kind, Map<String, Object?> config) async {
|
||||
@@ -70,8 +88,11 @@ class CredentialVault {
|
||||
var migrated = false;
|
||||
final token = tokenKey == null ? null : copy[tokenKey];
|
||||
if (token is String && token.isNotEmpty) {
|
||||
migrated = !isProtected(token);
|
||||
copy[tokenKey!] = await reveal(token);
|
||||
final revealed = await reveal(token);
|
||||
// An undecryptable token becomes the empty string — the shared
|
||||
// "no credential, re-auth" shape — and must not be rewritten back.
|
||||
migrated = revealed != null && !isProtected(token);
|
||||
copy[tokenKey!] = revealed ?? '';
|
||||
}
|
||||
if (kind == 'plex') {
|
||||
final result = await _revealPlexServers(copy['servers']);
|
||||
@@ -109,8 +130,9 @@ class CredentialVault {
|
||||
final server = Map<String, dynamic>.from(raw);
|
||||
final token = server['accessToken'];
|
||||
if (token is String && token.isNotEmpty) {
|
||||
migrated = migrated || !isProtected(token);
|
||||
server['accessToken'] = await reveal(token);
|
||||
final revealed = await reveal(token);
|
||||
migrated = migrated || (revealed != null && !isProtected(token));
|
||||
server['accessToken'] = revealed ?? '';
|
||||
}
|
||||
servers.add(server);
|
||||
}
|
||||
@@ -120,12 +142,31 @@ class CredentialVault {
|
||||
static Future<SecretKey> _getSecretKey() {
|
||||
return _secretKey ??= () async {
|
||||
final prefs = await BaseSharedPreferencesService.sharedCache();
|
||||
// The cached snapshot can predate a key written by another isolate
|
||||
// (background downloader, first-run migration); generating "fresh" over
|
||||
// it would clobber the real key and orphan every stored ciphertext.
|
||||
// Reload before deciding, and after writing re-read and adopt whatever
|
||||
// actually landed so all isolates converge on a single key.
|
||||
try {
|
||||
await prefs.reloadCache();
|
||||
} catch (e) {
|
||||
appLogger.d('CredentialVault: prefs reload before key check failed', error: e);
|
||||
}
|
||||
final stored = prefs.getString(_keyPref);
|
||||
if (stored != null && stored.isNotEmpty) {
|
||||
return SecretKey(base64Decode(stored));
|
||||
}
|
||||
final bytes = List<int>.generate(32, (_) => Random.secure().nextInt(256));
|
||||
await prefs.setString(_keyPref, base64Encode(bytes));
|
||||
try {
|
||||
await prefs.reloadCache();
|
||||
final settled = prefs.getString(_keyPref);
|
||||
if (settled != null && settled.isNotEmpty) {
|
||||
return SecretKey(base64Decode(settled));
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.d('CredentialVault: prefs re-read after key write failed', error: e);
|
||||
}
|
||||
return SecretKey(bytes);
|
||||
}();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user