diff --git a/lib/providers/auth_credentials_storage.dart b/lib/providers/auth_credentials_storage.dart index 69bbe4a14..c7ba6efb3 100644 --- a/lib/providers/auth_credentials_storage.dart +++ b/lib/providers/auth_credentials_storage.dart @@ -124,7 +124,14 @@ class AuthCredentialsStorage { await _prefs.setString(PREFS_SERVER_URL, serverUrl); if (refreshToken != null) { - await _secureStorage.writeRefreshToken(refreshToken); + try { + await _secureStorage.writeRefreshToken(refreshToken); + } catch (e, s) { + // A locked or unavailable keyring must not abort login. The session + // works now, but the refresh token cannot be persisted, so there is no + // auto-login after a restart until the keyring becomes available. + _logger.warning('Could not persist refresh token, auto-login disabled', e, s); + } } await clearLegacy(); @@ -144,7 +151,14 @@ class AuthCredentialsStorage { await _prefs.remove(PREFS_ACCESS_EXPIRES_AT); } if (refreshToken != null) { - await _secureStorage.writeRefreshToken(refreshToken); + try { + await _secureStorage.writeRefreshToken(refreshToken); + } catch (e, s) { + // A locked or unavailable keyring must not abort login. The session + // works now, but the refresh token cannot be persisted, so there is no + // auto-login after a restart until the keyring becomes available. + _logger.warning('Could not persist refresh token, auto-login disabled', e, s); + } } } @@ -158,7 +172,13 @@ class AuthCredentialsStorage { await _prefs.remove(PREFS_ACCESS_EXPIRES_AT); await _prefs.remove(PREFS_TOKEN_TYPE); await _prefs.remove(PREFS_SERVER_URL); - await _secureStorage.deleteRefreshToken(); + try { + await _secureStorage.deleteRefreshToken(); + } catch (e, s) { + // A locked or unavailable keyring must not abort logout; the refresh + // token is unreadable anyway, so wiping it is best-effort. + _logger.warning('Could not delete refresh token, keyring unavailable', e, s); + } } /// Wipes only the legacy `PREFS_USER` blob. Used by the JWT-migration diff --git a/test/providers/auth_credentials_storage_test.dart b/test/providers/auth_credentials_storage_test.dart new file mode 100644 index 000000000..37f749d0d --- /dev/null +++ b/test/providers/auth_credentials_storage_test.dart @@ -0,0 +1,108 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:logging/logging.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/helpers/consts.dart'; +import 'package:wger/helpers/shared_preferences.dart'; +import 'package:wger/providers/auth_credential.dart'; +import 'package:wger/providers/auth_credentials_storage.dart'; +import 'package:wger/providers/secure_token_storage.dart'; + +import '../fake_auth_environment.dart'; +import 'auth_credentials_storage_test.mocks.dart'; + +@GenerateMocks([SecureTokenStorage]) +void main() { + installFakeAuthEnvironment(); + + late MockSecureTokenStorage secureStorage; + late AuthCredentialsStorage storage; + late List logs; + late StreamSubscription logSub; + + setUp(() { + secureStorage = MockSecureTokenStorage(); + storage = AuthCredentialsStorage(secureStorage); + logs = []; + logSub = Logger.root.onRecord.listen(logs.add); + }); + + tearDown(() => logSub.cancel()); + + bool loggedKeyringWarning() => logs.any( + (r) => r.loggerName == 'AuthCredentialsStorage' && r.level == Level.WARNING, + ); + + // A locked or unavailable keyring (e.g. a Flatpak without an unlocked Secret + // Service) raises a PlatformException from the secure-storage plugin. It must + // not abort the auth flow: the refresh-token write/delete is best-effort and + // logged, while the rest of the credential bundle still goes through. + group('tolerates a locked keyring', () { + final keyringLocked = PlatformException(code: 'KeyringLocked', message: 'KeyringLocked'); + + test('saveJwt persists the prefs, logs, and does not rethrow', () async { + when(secureStorage.writeRefreshToken(any)).thenThrow(keyringLocked); + + await expectLater( + storage.saveJwt( + credential: const JwtCredential(accessToken: 'access'), + serverUrl: 'https://wger.example', + refreshToken: 'refresh', + ), + completes, + ); + + verify(secureStorage.writeRefreshToken('refresh')).called(1); + expect(await PreferenceHelper.asyncPref.getString(PREFS_ACCESS_TOKEN), 'access'); + expect(await PreferenceHelper.asyncPref.getString(PREFS_SERVER_URL), 'https://wger.example'); + expect(loggedKeyringWarning(), isTrue); + }); + + test('updateJwt persists the prefs and does not rethrow', () async { + when(secureStorage.writeRefreshToken(any)).thenThrow(keyringLocked); + + await expectLater( + storage.updateJwt( + credential: const JwtCredential(accessToken: 'access2'), + refreshToken: 'refresh', + ), + completes, + ); + + expect(await PreferenceHelper.asyncPref.getString(PREFS_ACCESS_TOKEN), 'access2'); + expect(loggedKeyringWarning(), isTrue); + }); + + test('clearJwt clears the prefs, logs, and does not rethrow', () async { + when(secureStorage.deleteRefreshToken()).thenThrow(keyringLocked); + await PreferenceHelper.asyncPref.setString(PREFS_ACCESS_TOKEN, 'stale'); + + await expectLater(storage.clearJwt(), completes); + + verify(secureStorage.deleteRefreshToken()).called(1); + expect(await PreferenceHelper.asyncPref.getString(PREFS_ACCESS_TOKEN), isNull); + expect(loggedKeyringWarning(), isTrue); + }); + }); +} diff --git a/test/providers/auth_credentials_storage_test.mocks.dart b/test/providers/auth_credentials_storage_test.mocks.dart new file mode 100644 index 000000000..5f117afc2 --- /dev/null +++ b/test/providers/auth_credentials_storage_test.mocks.dart @@ -0,0 +1,59 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/providers/auth_credentials_storage_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/providers/secure_token_storage.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [SecureTokenStorage]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockSecureTokenStorage extends _i1.Mock implements _i2.SecureTokenStorage { + MockSecureTokenStorage() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Future writeRefreshToken(String? token) => + (super.noSuchMethod( + Invocation.method(#writeRefreshToken, [token]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future readRefreshToken() => + (super.noSuchMethod( + Invocation.method(#readRefreshToken, []), + returnValue: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteRefreshToken() => + (super.noSuchMethod( + Invocation.method(#deleteRefreshToken, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +}