diff --git a/lib/providers/auth_notifier.dart b/lib/providers/auth_notifier.dart index 6ab9741c4..c175f8617 100644 --- a/lib/providers/auth_notifier.dart +++ b/lib/providers/auth_notifier.dart @@ -750,7 +750,17 @@ class AuthNotifier extends _$AuthNotifier { return; } - final refreshToken = await _storage.readRefreshToken(); + final String? refreshToken; + try { + refreshToken = await _storage.readRefreshToken(); + } on Exception catch (e, s) { + // Secure storage can fail to decrypt the token, e.g. after an Android + // backup/restore onto a new device leaves the encrypted blob behind, etc. + _logger.warning('refreshAccessToken: secure storage read failed, clearing session', e, s); + await clearSessionOnly(); + showSessionExpiredSnackbar(); + return; + } if (refreshToken == null || refreshToken.isEmpty) { _logger.warning('refreshAccessToken: no refresh token in secure storage, clearing session'); await clearSessionOnly(); diff --git a/test/auth/auth_notifier_powersync_test.dart b/test/auth/auth_notifier_powersync_test.dart index 95c84b9bc..4483cc5a5 100644 --- a/test/auth/auth_notifier_powersync_test.dart +++ b/test/auth/auth_notifier_powersync_test.dart @@ -1164,6 +1164,32 @@ void main() { verifyNever(mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body'))); }); + test( + 'secure storage read throws (post-restore Keystore loss) → clears session, no throw', + () async { + // Android backup/restore onto a new device restores the encrypted refresh + // token but not the Keystore key it was sealed with, so the read throws. + // Must clear the session, not let the exception escape and loop into a + // fatal dialog on every refresh attempt. + await PreferenceHelper.asyncPref.setBool(PREFS_HAS_EVER_SYNCED, true); + when( + mockSecureStorage.readRefreshToken(), + ).thenThrow(PlatformException(code: 'BadPaddingException')); + + final container = makeContainer(); + await container.read(authProvider.future); + + // Must complete normally; before the fix the exception escaped here. + await container.read(authProvider.notifier).refreshAccessToken(); + + expect(container.read(authProvider).value!.status, AuthStatus.loggedOut); + expect(await PreferenceHelper.asyncPref.getBool(PREFS_HAS_EVER_SYNCED), true); + verifyNever( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ); + }, + ); + test('non-200 response → clears session, keeps DB', () async { // Server reachable + non-200 means the refresh token is genuinely // rejected (typical for a refresh token that expired server-side after