Properly handle the case where the token could not be decrypted

This commit is contained in:
Roland Geider
2026-06-14 20:51:52 +02:00
parent db458acee4
commit eae855bef4
2 changed files with 37 additions and 1 deletions

View File

@@ -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();

View File

@@ -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