Keep the basic-auth login out of the Hive box (secure storage on mobile, session storage on web) (#5163)

This commit is contained in:
Dat Dang authored and GitHub committed 2026-11-26 10:47:48 +07:00
1 parent 11514a0c20
commit d764ec2391
41 files changed
+2496 -30

No files matched your search

+4 -2
View File
@@ -780,9 +780,11 @@ class HtmlUtils {
final url = html.Url.createObjectUrlFromBlob(blob);
html.window.open(url, '_blank');
// noopener: the new tab must not inherit a copy of this tab's sessionStorage (the login).
html.window.open(url, '_blank', windowFeatures(noOpener: true));
html.Url.revokeObjectUrl(url);
// The new tab fetches the blob after open() returns; revoking at once can race it.
Future.delayed(const Duration(minutes: 1), () => html.Url.revokeObjectUrl(url));
}
static String windowFeatures({String? size, required bool noOpener}) =>
+21
View File
@@ -10,3 +10,24 @@ Categories: UX, UI, Product, Architecture, Infra, Tech.
- Decided by: Benoit Tellier, after the twake-qa security review of twake-calendar-side-service (SEV-1, 2026-11-23); the pipeline of twake-contacts-frontend is the model.
- Why: the agents are persistent and shared, so code of a pull request that runs before the check can read a credential bound later in the same build, or leave a process behind for a later one. A review is tied to a commit by GitHub, unlike a comment, so a commit pushed after the approval is not built until a member reviews it again.
- Scope: `Jenkinsfile` and `JenkinsfileMobile`. The backend teardown in `post` runs only for an authorized build.
## 2026-11-25, [Architecture] On web basic auth, a sign out in one tab invalidates the login copy of every other tab through a marker in localStorage
- Decision: the basic-auth login of a tab lives in its sessionStorage next to a tag holding the sign-out marker (`basicAuthSignOutMarker` in localStorage) it was saved under. A user sign out replaces the marker. A tab whose tag no longer matches the marker rejects its requests, removes its own login copy and tag, and goes to the login page. Only the marker is read for this check, and the tab never clears shared data (Hive, marker, composer snapshots).
- Decided by: Dat H. Pham, in linagora/tmail-flutter#5163.
- Why: sessionStorage is per tab, so no other tab learns of a sign out, and the password stayed usable in the tabs left open. Another tab may already be signed in again, so a leaving tab must not touch shared data.
- Scope: web basic auth only; OIDC and mobile are unchanged. `authentication_info_cache_manager.dart`, `sign_out_marker_storage.dart`, `basic_auth_tab_guard.dart` and the request interceptors.
## 2026-11-25, [UX] A tab signed out from another tab keeps its open drafts
- Decision: before a tab with a revoked login goes to the login page, it saves a reload snapshot of every open composer. It leaves without the browser leave prompt.
- Decided by: Dat H. Pham, in linagora/tmail-flutter#5163.
- Why: the user loses nothing typed, and the dashboard prompt cannot trap a tab that has already dropped its login.
- Scope: `basic_auth_tab_guard.dart`, `composer_manager.dart`.
## 2026-11-25, [UX] On web basic auth, a same-origin app route opened in a new tab inherits the login
- Decision: same-origin app routes open in a new tab without `noopener`, so the tab inherits a copy of the sessionStorage login and does not ask for it again. Other links and print tabs open with `noopener`. A tab with an opener removes the composer and identity drafts it copied, then detaches the opener.
- Decided by: Dat H. Pham, in linagora/tmail-flutter#5163.
- Why: the new tab keeps working without a second sign in, and a draft stays owned by the one tab that created it.
- Scope: `app_route_tab_environment.dart`, `html_utils.dart`, `child_tab_session_cleaner.dart`, `mailbox_action_handler_mixin.dart`, `email_action_controller.dart`.
+14
View File
@@ -14,6 +14,8 @@ import flutter_local_notifications
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
excludeDocumentsFromBackup()
if let payload = launchOptions?[.remoteNotification] as? [AnyHashable : Any] {
currentNotificationTap = AppDelegate.notificationTap(of: payload)
}
@@ -237,6 +239,18 @@ extension AppDelegate {
)
}
// Hive boxes (key + encrypted data), logs and exports live here; keep them out of iCloud/iTunes backups.
private func excludeDocumentsFromBackup() {
guard var url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
var values = URLResourceValues()
values.isExcludedFromBackup = true
do {
try url.setResourceValues(values)
} catch {
NSLog("[AppDelegate] excludeDocumentsFromBackup failed: \(error)")
}
}
private func updateApplicationStateInUserDefaults(_ appIsActive: Bool) {
let appGroupId = (Bundle.main.object(forInfoDictionaryKey: "AppGroupId") as? String) ?? "group.\(Bundle.main.bundleIdentifier!)"
let userDefaults = UserDefaults(suiteName: appGroupId)
+9
View File
@@ -533,7 +533,15 @@ abstract class BaseController extends GetxController
}
}
// Web basic auth keeps one login copy per tab; a user sign out must invalidate the others.
void _revokeOtherTabsOnWebBasicAuth() {
if (PlatformInfo.isWeb && !isAuthenticatedWithOidc) {
cachingManager.revokeOtherTabs();
}
}
Future<void> _handleLogoutAction(Session? session, AccountId? accountId) async {
_revokeOtherTabsOnWebBasicAuth();
if (session == null || accountId == null) {
await clearDataAndGoToLoginPage();
return;
@@ -569,6 +577,7 @@ abstract class BaseController extends GetxController
}) async {
_LogoutToSignInOutcome outcome;
try {
_revokeOtherTabsOnWebBasicAuth();
await removeDelegatedComposerSnapshotsOnLogout(
session: session,
personalAccountId: accountId,
@@ -20,14 +20,19 @@ import 'package:tmail_ui_user/features/mailbox/presentation/utils/mailbox_action
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller.dart';
import 'package:tmail_ui_user/main/localizations/app_localizations.dart';
import 'package:tmail_ui_user/main/routes/route_navigation.dart';
import 'package:tmail_ui_user/main/utils/app_utils.dart';
import 'package:tmail_ui_user/main/utils/app_route_tab_environment.dart';
import 'package:tmail_ui_user/main/utils/toast_manager.dart';
mixin MailboxActionHandlerMixin {
AccountId? get activeAccountId;
bool get isAuthenticatedWithOidc;
AppRouteTabEnvironment get tabEnvironment => const AppRouteTabEnvironment();
void openMailboxInNewTabAction(PresentationMailbox mailbox) {
AppUtils.launchLink(mailbox.mailboxRouteWeb.toString());
tabEnvironment.openInNewTab(
mailbox.mailboxRouteWeb.toString(),
isBasicAuth: !isAuthenticatedWithOidc,
);
}
void markAsReadMailboxAction(
@@ -100,6 +100,9 @@ class CachingManager {
}
}
/// Web basic auth: invalidates the login copies held by other tabs.
void revokeOtherTabs() => _authenticationInfoCacheManager.revokeOtherTabs();
Future<void> clearAccountDataCached() async {
try {
await Future.wait([
@@ -98,22 +98,24 @@ class HiveCacheConfig {
}
Future<void> initializeEncryptionKey() async {
final encryptionKeyCacheManager = getBinding<EncryptionKeyCacheManager>() ?? getBinding<EncryptionKeyCacheManager>(tag: BindingTag.isolateTag);
final encryptionKeyCacheManager = _encryptionKeyCacheManager();
if (encryptionKeyCacheManager == null) {
log('HiveCacheConfig::_initializeEncryptionKey(): encryptionKeyCacheManager not found');
log('HiveCacheConfig::initializeEncryptionKey(): encryptionKeyCacheManager not found');
return;
}
final encryptionKeyCache = await encryptionKeyCacheManager.getEncryptionKeyStored();
if (encryptionKeyCache == null) {
final secureKey = Hive.generateSecureKey();
final secureKeyEncode = base64Encode(secureKey);
log('HiveCacheConfig::_initializeEncryptionKey(): secureKeyEncode: $secureKeyEncode');
await encryptionKeyCacheManager.storeEncryptionKey(EncryptionKeyCache(secureKeyEncode));
final boxKey = Hive.generateSecureKey();
await encryptionKeyCacheManager.storeEncryptionKey(EncryptionKeyCache(base64Encode(boxKey)));
}
}
EncryptionKeyCacheManager? _encryptionKeyCacheManager() =>
getBinding<EncryptionKeyCacheManager>() ??
getBinding<EncryptionKeyCacheManager>(tag: BindingTag.isolateTag);
Future<Uint8List?> getEncryptionKey() async {
final encryptionKeyCacheManager = getBinding<EncryptionKeyCacheManager>() ?? getBinding<EncryptionKeyCacheManager>(tag: BindingTag.isolateTag);
final encryptionKeyCacheManager = _encryptionKeyCacheManager();
if (encryptionKeyCacheManager == null) {
// No key → an encrypted box (incl. the OIDC token box) opens without a
// cipher and cannot be decrypted, surfacing later as a "no token" startup
@@ -0,0 +1,13 @@
import 'package:universal_html/html.dart' as html;
/// Direct, single-key access to the sign-out marker in localStorage.
/// Reads are O(1); the storage managers iterate every entry.
class SignOutMarkerStorage {
static const String markerKey = 'basicAuthSignOutMarker';
String? read() => html.window.localStorage[markerKey];
void write(String marker) => html.window.localStorage[markerKey] = marker;
void remove() => html.window.localStorage.remove(markerKey);
}
@@ -344,6 +344,9 @@ class ComposerController extends BaseController
void registerReloadCacheAction(ComposerReloadCacheAction action) =>
_reloadCacheAction = action;
/// Writes this composer's reload snapshot now, as beforeunload would.
void saveReloadSnapshot() => _reloadCacheAction?.call();
@visibleForTesting
set isEmailBodyLoaded(bool value) => _isEmailBodyLoaded = value;
@@ -510,7 +513,7 @@ class ComposerController extends BaseController
@override
Future<void> onBeforeUnloadBrowserListener(html.Event event) {
_reloadCacheAction?.call();
saveReloadSnapshot();
return Future.value();
}
@@ -71,6 +71,13 @@ class ComposerManager extends GetxController {
}
}
// Same write each composer does on beforeunload, so a forced page leave keeps every draft.
void saveAllReloadSnapshots() {
for (final id in composers.keys.toList()) {
composers[id]?.controller.saveReloadSnapshot();
}
}
void _arrangeComposerIfNeeded() {
if (currentContext != null && composerIdsQueue.isNotEmpty) {
arrangeComposerWhenComposerQueueChanged(
@@ -1,31 +1,331 @@
import 'dart:convert';
import 'package:core/utils/app_logger.dart';
import 'package:core/utils/platform_info.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:tmail_ui_user/features/caching/clients/authentication_info_cache_client.dart';
import 'package:tmail_ui_user/features/caching/interaction/cache_manager_interaction.dart';
import 'package:tmail_ui_user/features/caching/utils/session_storage_manager.dart';
import 'package:tmail_ui_user/features/caching/utils/sign_out_marker_storage.dart';
import 'package:tmail_ui_user/features/login/data/model/authentication_info_cache.dart';
import 'package:tmail_ui_user/features/login/domain/exceptions/authentication_exception.dart';
import 'package:uuid/uuid.dart';
class AuthenticationInfoCacheManager extends CacheManagerInteraction {
static const String _usernameField = 'username';
static const String _passwordField = 'password';
static const String _key = AuthenticationInfoCache.keyCacheValue;
/// Web: sessionStorage key holding the sign-out marker this tab logged in under.
static const String signOutTagKey = 'basicAuthSignOutTag';
// Own iOS service: KeychainSharingManager.delete() calls deleteAll() on the shared one.
static const FlutterSecureStorage defaultSecureStorage = FlutterSecureStorage(
iOptions: IOSOptions(
accountName: 'tmail_auth_info_store',
accessibility: KeychainAccessibility.first_unlock_this_device,
),
);
final AuthenticationInfoCacheClient _authenticationInfoCacheClient;
final SessionStorageManager _sessionStorageManager;
final FlutterSecureStorage _secureStorage;
final SignOutMarkerStorage _markerStorage;
AuthenticationInfoCacheManager(this._authenticationInfoCacheClient);
// Login whose secure write failed; keeps this run signed in until the next cold start.
AuthenticationInfoCache? _unsavedLogin;
Future<void> storeAuthenticationInfo(AuthenticationInfoCache authenticationInfoCache) {
return _authenticationInfoCacheClient.insertItem(
AuthenticationInfoCache.keyCacheValue,
authenticationInfoCache);
}
// Set once the Hive box is emptied this run; later reads skip the purge.
bool _legacyHivePurged = false;
// Web: marker value this tab's login was stored under. A copy is valid only
// while the shared marker still equals it.
String? _tabTag;
// Bumped by clear(); a read that started before a logout must not move the login back.
int _clearGeneration = 0;
AuthenticationInfoCacheManager(
this._authenticationInfoCacheClient,
this._sessionStorageManager, {
this._secureStorage = defaultSecureStorage,
SignOutMarkerStorage? markerStorage,
}) : _markerStorage = markerStorage ?? SignOutMarkerStorage();
Future<void> storeAuthenticationInfo(AuthenticationInfoCache authenticationInfoCache) =>
_saveLogin(authenticationInfoCache, keepLegacyOnFailure: false);
Future<AuthenticationInfoCache> getAuthenticationInfoStored() async {
final authenticationInfoCache = await _authenticationInfoCacheClient.getItem(AuthenticationInfoCache.keyCacheValue);
if (authenticationInfoCache != null) {
return authenticationInfoCache;
} else {
final generation = _clearGeneration;
final unsaved = _unsavedLogin;
if (unsaved != null) {
return unsaved;
}
final stored = _decode(await _readOwnedLogin());
if (stored != null) {
await _purgeLegacyHive();
_throwIfClearedSince(generation);
return stored;
}
final legacy = await _authenticationInfoCacheClient.getItem(_key);
if (legacy == null) {
throw NotFoundAuthenticationInfoCache();
}
_throwIfClearedSince(generation);
// One-time move of an earlier login out of the Hive box; kept there if the move fails.
await _saveLogin(legacy, keepLegacyOnFailure: true);
_throwIfClearedSince(generation);
return legacy;
}
bool get _isForeignCopy => PlatformInfo.isWeb && !_isCopyTagCurrent();
Future<String?> _readOwnedLogin() async {
final raw = await _readOutsideHive();
if (raw != null && _isForeignCopy) {
// A login copied from, or left over by, a signed-out session: never reuse it or the legacy login.
await _removeOutsideHive();
throw NotFoundAuthenticationInfoCache();
}
return raw;
}
// A read that started before a logout must not hand out the logged-out password.
void _throwIfClearedSince(int generation) {
if (generation != _clearGeneration) {
throw NotFoundAuthenticationInfoCache();
}
}
Future<void> clear() {
return _authenticationInfoCacheClient.clearAllData();
Future<void> clear() async {
_clearGeneration++;
_unsavedLogin = null;
_tabTag = null;
await _removeOutsideHive();
await _authenticationInfoCacheClient.clearAllData();
}
Future<void> _saveLogin(AuthenticationInfoCache login, {required bool keepLegacyOnFailure}) async {
final generation = _clearGeneration;
final saved = await _writeOutsideHive(jsonEncode({
_usernameField: login.username,
_passwordField: login.password,
}));
if (generation != _clearGeneration) {
// Logout ran while the write was pending; undo it.
await _removeOutsideHive();
return;
}
_unsavedLogin = saved ? null : login;
// A new login supersedes the Hive copy even when the secure write failed.
if (saved || !keepLegacyOnFailure) {
await _purgeLegacyHive();
}
}
// True only when secure storage reads the value back; fss 8 on iOS can drop a write without throwing.
Future<bool> _writeOutsideHive(String value) async {
if (PlatformInfo.isWeb) return _writeTaggedSessionLogin(value);
try {
await _secureStorage.write(key: _key, value: value);
if (await _secureStorage.read(key: _key) == value) {
return true;
}
logError('$runtimeType::_writeOutsideHive: secure_write_verify_failed=true');
} catch (e, st) {
// Login still works this run through _unsavedLogin.
logError('$runtimeType::_writeOutsideHive: secure_write_failed=true', exception: e, stackTrace: st);
}
// A failed overwrite must not leave the previous login for the next cold start.
await _removeOutsideHive();
return false;
}
// The password reaches sessionStorage only together with a tag; no marker means no copy.
bool _writeTaggedSessionLogin(String value) {
final marker = _ensureMarker();
if (marker == null) {
_tabTag = null;
_sessionStorageManager.remove(_key);
_sessionStorageManager.remove(signOutTagKey);
return false;
}
_sessionStorageManager.save(_key, value);
_tagThisTab(marker);
// Another tab may have replaced the marker meanwhile; follow it once.
final latest = _readMarker();
if (latest != null && latest != marker) {
_tagThisTab(latest);
}
return true;
}
String? _ensureMarker() {
try {
final existing = _markerStorage.read();
if (existing != null && existing.isNotEmpty) return existing;
final created = const Uuid().v4();
_markerStorage.write(created);
return created;
} catch (e) {
logWarning('$runtimeType::_ensureMarker: $e');
return null;
}
}
String? _readMarker() {
try {
return _markerStorage.read();
} catch (e) {
logWarning('$runtimeType::_readMarker: $e');
return null;
}
}
void _tagThisTab(String marker) {
_sessionStorageManager.save(signOutTagKey, marker);
_tabTag = marker;
}
// Remembers the tag even when stale, so this tab's in-memory login stays blocked.
bool _isCopyTagCurrent() {
String? tag;
try {
tag = _sessionStorageManager.get(signOutTagKey);
} catch (_) {
return false;
}
_tabTag = tag;
return tag.isNotEmpty && tag == _readMarker();
}
/// Web only. A tab opened by the app inherits a login copy and its tag but
/// never reads them when it shows no account screen (EML preview); without
/// the tag it could not tell that a sign out elsewhere revoked the copy.
void adoptInheritedTabTag() {
if (!PlatformInfo.isWeb || _tabTag != null) return;
try {
final login = _sessionStorageManager.get(_key);
final tag = _sessionStorageManager.get(signOutTagKey);
if (login.isNotEmpty && tag.isNotEmpty) _tabTag = tag;
} catch (_) {
// No inherited login in this tab.
}
}
/// Web only. True when a sign out in another tab replaced the marker this
/// tab's login was stored under. Cheap: one direct localStorage lookup.
bool isLoginRevokedInThisTab() {
final tag = _tabTag;
if (!PlatformInfo.isWeb || tag == null) return false;
return _readMarker() != tag;
}
/// Web only. Called by the tab where the user signs out: replaces the marker
/// so every other tab's copy becomes invalid, and keeps this tab valid until
/// its own sign out finishes. If the marker cannot be rewritten it is removed.
void revokeOtherTabs() {
if (!PlatformInfo.isWeb) return;
final rotated = const Uuid().v4();
try {
_markerStorage.write(rotated);
} catch (e) {
logWarning('$runtimeType::revokeOtherTabs: marker_write_failed=true | $e');
_removeMarker();
// No marker left to match: stop checking this tab so its own sign out
// requests still go out. Its stored copy is removed by the clear that follows.
_tabTag = null;
return;
}
if (_tabTag != null) {
_tagThisTab(rotated);
}
}
/// Web only. Removes just this tab's login copy and its tag from sessionStorage.
/// The tab stays flagged as revoked, so its in-memory login remains blocked.
void dropLoginCopyInThisTab() {
if (!PlatformInfo.isWeb) return;
try {
_sessionStorageManager.remove(_key);
_sessionStorageManager.remove(signOutTagKey);
} catch (e) {
logWarning('$runtimeType::dropLoginCopyInThisTab: $e');
}
}
void _removeMarker() {
try {
_markerStorage.remove();
} catch (e) {
logWarning('$runtimeType::_removeMarker: $e');
}
}
Future<String?> _readOutsideHive() async {
try {
return PlatformInfo.isWeb
? _sessionStorageManager.get(_key)
: await _secureStorage.read(key: _key);
} catch (_) {
// Absent (NotFoundDataWithThisKeyException) or secure storage unavailable.
return null;
}
}
Future<void> _removeOutsideHive() async {
try {
await _putOutsideHive(null);
// fss 8 iOS reports a failed Keychain delete as a normal result.
if (await _readOutsideHive() == null) return;
logWarning('$runtimeType::_removeOutsideHive: delete_verify_failed=true');
} catch (e) {
logWarning('$runtimeType::_removeOutsideHive: $e');
}
try {
// An empty value decodes to no login, so a failed delete cannot resurrect it.
await _putOutsideHive('');
} catch (e) {
logWarning('$runtimeType::_removeOutsideHive: blank_failed=true | $e');
}
}
// A null value removes the entry.
Future<void> _putOutsideHive(String? value) async {
if (PlatformInfo.isWeb) {
if (value == null) {
_sessionStorageManager.remove(_key);
_sessionStorageManager.remove(signOutTagKey);
} else {
_sessionStorageManager.save(_key, value);
}
} else {
value == null
? await _secureStorage.delete(key: _key)
: await _secureStorage.write(key: _key, value: value);
}
}
AuthenticationInfoCache? _decode(String? raw) {
if (raw == null) return null;
try {
final json = jsonDecode(raw) as Map<String, dynamic>;
return AuthenticationInfoCache(
json[_usernameField] as String,
json[_passwordField] as String);
} catch (_) {
return null;
}
}
Future<void> _purgeLegacyHive() async {
if (_legacyHivePurged) return;
try {
await _authenticationInfoCacheClient.clearAllData();
_legacyHivePurged = true;
} catch (e) {
logWarning('$runtimeType::_purgeLegacyHive: $e');
}
}
@override
@@ -41,4 +341,4 @@ class AuthenticationInfoCacheManager extends CacheManagerInteraction {
logWarning('$runtimeType::migrateHiveToIsolatedHive(): ❌ Migrate Hive box "${_authenticationInfoCacheClient.tableName}" → IsolatedHive FAILED, Error: $e');
}
}
}
}
@@ -51,6 +51,9 @@ class AuthorizationInterceptors extends QueuedInterceptorsWrapper {
final RefreshTokenErrorClassifier? _injectedErrorClassifier;
/// Web basic auth: true once another tab's sign out invalidated this tab's login.
final bool Function()? _isBasicLoginRevoked;
late final RefreshTokenErrorClassifier _errorClassifier =
_injectedErrorClassifier ??
(PlatformInfo.isWeb
@@ -72,6 +75,7 @@ class AuthorizationInterceptors extends QueuedInterceptorsWrapper {
this._accountCacheManager,
this._iosSharingManager, {
RefreshTokenErrorClassifier? errorClassifier,
this._isBasicLoginRevoked,
}) : _injectedErrorClassifier = errorClassifier;
void setBasicAuthorization(UserName userName, Password password) {
@@ -164,6 +168,20 @@ class AuthorizationInterceptors extends QueuedInterceptorsWrapper {
return;
}
if (_isRevokedBasicLogin) {
_rejectRevokedLogin(options, handler);
return;
}
_attachAuthorization(options);
log('AuthorizationInterceptors::onRequest(): URL = ${options.uri} | DATA = ${options.data}');
super.onRequest(options, handler);
}
bool get _isRevokedBasicLogin =>
_authenticationType == AuthenticationType.basic &&
_isBasicLoginRevoked?.call() == true;
void _attachAuthorization(RequestOptions options) {
switch(_authenticationType) {
case AuthenticationType.basic:
if (_authorization != null) {
@@ -178,8 +196,15 @@ class AuthorizationInterceptors extends QueuedInterceptorsWrapper {
case AuthenticationType.none:
break;
}
log('AuthorizationInterceptors::onRequest(): URL = ${options.uri} | DATA = ${options.data}');
super.onRequest(options, handler);
}
// Synchronous on purpose: a request without credentials would earn a 401 that wipes shared data.
void _rejectRevokedLogin(RequestOptions options, RequestInterceptorHandler handler) {
options.headers.remove(HttpHeaders.authorizationHeader);
handler.reject(DioException(
requestOptions: options,
error: const CredentialRevokedException(),
));
}
@override
@@ -22,6 +22,11 @@ class GetCredentialInteractor {
try {
final baseUrl = await credentialRepository.getBaseUrl();
final authenticationInfo = await credentialRepository.getAuthenticationInfoStored();
// A failed overwrite or late migration can leave another account's login; drop it for every reader.
if (authenticationInfo.username != personalAccount.id) {
await credentialRepository.removeAuthenticationInfo();
return Left(GetCredentialFailure(NotFoundAuthenticationInfoCache()));
}
if (isCredentialValid(baseUrl)) {
return Right(GetCredentialViewState(
baseUrl,
@@ -0,0 +1,96 @@
import 'dart:async';
import 'package:core/utils/app_logger.dart';
import 'package:core/utils/platform_info.dart';
import 'package:get/get.dart';
import 'package:tmail_ui_user/features/caching/utils/sign_out_marker_storage.dart';
import 'package:tmail_ui_user/features/composer/presentation/manager/composer_manager.dart';
import 'package:tmail_ui_user/features/login/data/local/authentication_info_cache_manager.dart';
import 'package:tmail_ui_user/features/login/presentation/tab_guard/tab_guard_browser.dart';
import 'package:tmail_ui_user/main/utils/twake_app_manager.dart';
/// Web basic auth: once another tab signed out, this tab must stop using its
/// copy of the login and leave. It never clears shared data (Hive, marker,
/// composer snapshots): another tab may already be signed in again.
class BasicAuthTabGuard {
final AuthenticationInfoCacheManager _cacheManager;
final TabGuardBrowser _browser;
final void Function() _saveOpenComposers;
final List<StreamSubscription<dynamic>> _subscriptions = [];
bool _hasLeft = false;
BasicAuthTabGuard(
this._cacheManager,
this._browser,
this._saveOpenComposers,
);
factory BasicAuthTabGuard.forApp() => BasicAuthTabGuard(
Get.find<AuthenticationInfoCacheManager>(),
WebTabGuardBrowser(),
_saveComposersIfDashboardExists,
);
static void _saveComposersIfDashboardExists() {
if (Get.isRegistered<ComposerManager>()) {
Get.find<ComposerManager>().saveAllReloadSnapshots();
}
// Drafts are saved, so the dashboard beforeunload must not ask to stay.
if (Get.isRegistered<TwakeAppManager>()) {
Get.find<TwakeAppManager>().setExecutingBeforeReconnect(true);
}
}
void start() {
if (!PlatformInfo.isWeb || _subscriptions.isNotEmpty) return;
_cacheManager.adoptInheritedTabTag();
checkAndLeaveIfRevoked();
_subscriptions
..add(_browser.storageEventKeys.listen(_onStorageEvent))
..add(_browser.pageActivations.listen((_) => checkAndLeaveIfRevoked()));
}
void dispose() {
for (final subscription in _subscriptions) {
subscription.cancel();
}
_subscriptions.clear();
}
/// Called from inside request handling: only schedules, never works inline.
void onRevokedRequest() => scheduleMicrotask(checkAndLeaveIfRevoked);
// EML preview content also writes to localStorage, so only the marker key counts.
void _onStorageEvent(String? key) {
if (key == null || key == SignOutMarkerStorage.markerKey) {
checkAndLeaveIfRevoked();
}
}
void checkAndLeaveIfRevoked() {
if (_hasLeft || !_cacheManager.isLoginRevokedInThisTab()) return;
_hasLeft = true;
_leave();
}
void _leave() {
try {
_cacheManager.dropLoginCopyInThisTab();
if (_browser.isEmlPreviewRoute && _browser.tryCloseTab()) return;
_saveOpenComposers();
} catch (e) {
logWarning('$runtimeType::_leave: $e');
}
_browser.replaceWithLoginPage();
}
}
/// Request-time probe for the interceptors: also wakes the guard, which does the leaving.
bool isBasicLoginRevokedAndNotifyGuard() {
final revoked = Get.find<AuthenticationInfoCacheManager>().isLoginRevokedInThisTab();
if (revoked && Get.isRegistered<BasicAuthTabGuard>()) {
Get.find<BasicAuthTabGuard>().onRevokedRequest();
}
return revoked;
}
@@ -0,0 +1,59 @@
import 'dart:async';
import 'package:tmail_ui_user/main/routes/app_routes.dart';
import 'package:universal_html/html.dart' as html;
/// Browser access the tab guard needs, kept apart so its decisions run without a browser.
abstract class TabGuardBrowser {
/// Key of every `storage` event; null when the whole storage was cleared.
Stream<String?> get storageEventKeys;
/// Fires when the page becomes visible or is restored from the back/forward cache.
Stream<void> get pageActivations;
bool get isEmlPreviewRoute;
/// Returns whether the tab is gone afterwards.
bool tryCloseTab();
void replaceWithLoginPage();
}
class WebTabGuardBrowser implements TabGuardBrowser {
@override
Stream<String?> get storageEventKeys =>
html.window.onStorage.map((event) => event.key);
@override
Stream<void> get pageActivations => Stream.multi((controller) {
final subscriptions = [
html.document.onVisibilityChange
.where((_) => html.document.visibilityState == 'visible')
.listen((_) => controller.add(null)),
html.window.onPageShow.listen((_) => controller.add(null)),
];
controller.onCancel = () {
for (final subscription in subscriptions) {
subscription.cancel();
}
};
});
@override
bool get isEmlPreviewRoute =>
Uri.base.path.endsWith(AppRoutes.emailEMLPreviewer);
@override
bool tryCloseTab() {
html.window.close();
return html.window.closed ?? false;
}
// Relative to <base href>, like every other web route URL, so sub-path deployments stay inside the app.
@override
void replaceWithLoginPage() {
final base = Uri.parse(html.document.baseUri ?? Uri.base.origin);
final login = base.resolve(AppRoutes.login.substring(1));
html.window.location.replace(login.toString());
}
}
@@ -34,12 +34,14 @@ import 'package:tmail_ui_user/main/localizations/app_localizations.dart';
import 'package:tmail_ui_user/main/routes/app_routes.dart';
import 'package:tmail_ui_user/main/routes/dialog_router.dart';
import 'package:tmail_ui_user/main/routes/route_navigation.dart';
import 'package:tmail_ui_user/main/utils/app_utils.dart';
import 'package:tmail_ui_user/main/utils/app_route_tab_environment.dart';
mixin EmailActionController {
final mailboxDashBoardController = Get.find<MailboxDashBoardController>();
AccountId? get activeAccountId;
bool get isAuthenticatedWithOidc;
AppRouteTabEnvironment get tabEnvironment => const AppRouteTabEnvironment();
final responsiveUtils = Get.find<ResponsiveUtils>();
final imagePaths = Get.find<ImagePaths>();
@@ -390,7 +392,10 @@ mixin EmailActionController {
}
void openEmailInNewTabAction(PresentationEmail email) {
AppUtils.launchLink(email.routeWebAsString);
tabEnvironment.openInNewTab(
email.routeWebAsString,
isBasicAuth: !isAuthenticatedWithOidc,
);
}
void archiveMessage(PresentationEmail email) {
+4 -1
View File
@@ -27,6 +27,7 @@ import 'package:tmail_ui_user/features/caching/clients/state_cache_client.dart';
import 'package:tmail_ui_user/features/caching/clients/token_oidc_cache_client.dart';
import 'package:tmail_ui_user/features/caching/manager/sentry_configuration_cache_manager.dart';
import 'package:tmail_ui_user/features/caching/manager/session_cache_manger.dart';
import 'package:tmail_ui_user/features/caching/utils/session_storage_manager.dart';
import 'package:tmail_ui_user/features/cleanup/data/local/recent_login_url_cache_manager.dart';
import 'package:tmail_ui_user/features/cleanup/data/local/recent_login_username_cache_manager.dart';
import 'package:tmail_ui_user/features/cleanup/data/local/recent_search_cache_manager.dart';
@@ -91,7 +92,9 @@ class LocalBindings extends Bindings {
Get.put(EncryptionKeyCacheClient());
Get.put(EncryptionKeyCacheManager(Get.find<EncryptionKeyCacheClient>()));
Get.put(AuthenticationInfoCacheClient());
Get.put(AuthenticationInfoCacheManager(Get.find<AuthenticationInfoCacheClient>()));
Get.put(AuthenticationInfoCacheManager(
Get.find<AuthenticationInfoCacheClient>(),
Get.find<SessionStorageManager>()));
Get.put(OidcConfigurationCacheClient());
Get.put(OidcConfigurationCacheManager(Get.find<SharedPreferences>(), Get.find<OidcConfigurationCacheClient>()));
Get.put(LanguageCacheManager(Get.find<SharedPreferences>()));
@@ -22,6 +22,7 @@ import 'package:tmail_ui_user/features/login/data/network/dns_lookup/dns_lookup_
import 'package:tmail_ui_user/features/login/data/network/interceptors/authorization_interceptors.dart';
import 'package:tmail_ui_user/features/login/data/network/oidc_http_client.dart';
import 'package:tmail_ui_user/features/login/data/utils/library_platform/app_auth_plugin/app_auth_plugin.dart';
import 'package:tmail_ui_user/features/login/presentation/tab_guard/basic_auth_tab_guard.dart';
import 'package:tmail_ui_user/features/mailbox/data/local/mailbox_cache_manager.dart';
import 'package:tmail_ui_user/features/mailbox/data/local/state_cache_manager.dart';
import 'package:tmail_ui_user/features/mailbox/data/network/mailbox_api.dart';
@@ -103,6 +104,7 @@ class NetworkBindings extends Bindings {
Get.find<TokenOidcCacheManager>(),
Get.find<AccountCacheManager>(),
Get.find<IOSSharingManager>(),
isBasicLoginRevoked: isBasicLoginRevokedAndNotifyGuard,
));
dio.interceptors.add(Get.find<DynamicUrlInterceptors>());
dio.interceptors.add(Get.find<AuthorizationInterceptors>());
@@ -12,6 +12,7 @@ import 'package:tmail_ui_user/features/login/data/network/authentication_client/
import 'package:tmail_ui_user/features/login/data/network/interceptors/authorization_interceptors.dart';
import 'package:tmail_ui_user/features/login/data/network/oidc_http_client.dart';
import 'package:tmail_ui_user/features/login/data/utils/library_platform/app_auth_plugin/app_auth_plugin.dart';
import 'package:tmail_ui_user/features/login/presentation/tab_guard/basic_auth_tab_guard.dart';
import 'package:tmail_ui_user/features/mailbox/data/local/mailbox_cache_manager.dart';
import 'package:tmail_ui_user/features/mailbox/data/local/state_cache_manager.dart';
import 'package:tmail_ui_user/features/mailbox/data/network/mailbox_isolate_worker.dart';
@@ -54,6 +55,7 @@ class NetworkIsolateBindings extends Bindings {
Get.find<TokenOidcCacheManager>(tag: BindingTag.isolateTag),
Get.find<AccountCacheManager>(tag: BindingTag.isolateTag),
Get.find<IOSSharingManager>(tag: BindingTag.isolateTag),
isBasicLoginRevoked: isBasicLoginRevokedAndNotifyGuard,
);
Get.put(authorizationInterceptors, tag: BindingTag.isolateTag);
@@ -14,6 +14,16 @@ class BadCredentialsException extends AuthenticationException {
String get exceptionName => 'BadCredentialsException';
}
/// This tab's basic login was revoked by a sign out in another tab.
/// Not a server rejection: it must never be treated as [BadCredentialsException].
class CredentialRevokedException extends AuthenticationException {
const CredentialRevokedException()
: super(message: 'Login was revoked by a sign out in another tab');
@override
String get exceptionName => 'CredentialRevokedException';
}
class RefreshTokenFailedException extends AuthenticationException {
/// The server rejection that killed the session, for the caller to log.
final Object? cause;
@@ -57,6 +57,10 @@ class RemoteExceptionThrower extends ExceptionThrower {
throw RefreshTokenFailedException();
}
if (error.error is CredentialRevokedException) {
throw const CredentialRevokedException();
}
final response = error.response;
if (response != null) {
return _responseHandler.handle(response, stackTrace);
+6
View File
@@ -3,10 +3,13 @@ import 'package:core/presentation/utils/web_selection/web_selection_coordinator.
import 'package:core/utils/build_utils.dart';
import 'package:core/utils/platform_info.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:tmail_ui_user/features/caching/config/hive_cache_config.dart';
import 'package:tmail_ui_user/features/login/presentation/tab_guard/basic_auth_tab_guard.dart';
import 'package:tmail_ui_user/main.dart';
import 'package:tmail_ui_user/main/bindings/main_bindings.dart';
import 'package:tmail_ui_user/main/utils/asset_preloader.dart';
import 'package:tmail_ui_user/main/utils/child_tab_session_cleaner.dart';
import 'package:tmail_ui_user/main/utils/cozy_integration.dart';
import 'package:url_strategy/url_strategy.dart';
import 'package:worker_manager/worker_manager.dart';
@@ -17,6 +20,8 @@ Future<void> runTmail() async {
}
Future<void> runTmailPreload() async {
// Before any binding can restore the drafts copied from the opener tab.
if (PlatformInfo.isWeb) ChildTabSessionCleaner().run();
ThemeUtils.setSystemLightUIStyle();
await Future.wait([
@@ -35,5 +40,6 @@ Future<void> runTmailPreload() async {
if (PlatformInfo.isWeb) {
setPathUrlStrategy();
WebSelectionCoordinator.instance.start();
Get.put(BasicAuthTabGuard.forApp()).start();
}
}
@@ -0,0 +1,39 @@
import 'package:core/utils/html/html_utils.dart';
import 'package:core/utils/platform_info.dart';
import 'package:tmail_ui_user/main/utils/app_utils.dart';
/// Platform access of [openInNewTab], replaceable in tests.
class AppRouteTabEnvironment {
const AppRouteTabEnvironment();
bool get isWeb => PlatformInfo.isWeb;
String currentOrigin() => Uri.base.origin;
/// Opens an app route in a new tab. On web basic auth, same-origin routes are
/// opened without noopener so the tab inherits this tab's login; every other
/// case goes through [launch] and keeps noopener.
void openInNewTab(String url, {required bool isBasicAuth}) {
if (isBasicAuth && canShareSession(url)) {
if (openTabKeepingSession(url)) return;
}
launch(url);
}
/// True when [url] is an absolute http(s) url on this app's origin, on web.
bool canShareSession(String url) {
if (!isWeb) return false;
try {
// Uri.origin throws for relative and non-http(s) urls.
return Uri.parse(url).origin == currentOrigin();
} catch (_) {
return false;
}
}
/// Returns false only when opening throws. A blocked popup is not detected.
bool openTabKeepingSession(String url) =>
HtmlUtils.openNewWindowByUrl(url, isFullScreen: true);
void launch(String url) => AppUtils.launchLink(url);
}
+11
View File
@@ -0,0 +1,11 @@
/// Browser access the cleanup needs, kept apart so it runs without a browser.
abstract class ChildTabBrowser {
/// May throw when the opener cannot be inspected.
bool get hasOpener;
void detachOpener();
List<String> get sessionStorageKeys;
void removeSessionStorageKey(String key);
}
@@ -0,0 +1,2 @@
export 'child_tab_browser_stub.dart'
if (dart.library.html) 'child_tab_browser_web.dart';
@@ -0,0 +1,16 @@
import 'package:tmail_ui_user/main/utils/child_tab_browser.dart';
/// Only the web build has tabs and a tab opener.
class PlatformChildTabBrowser implements ChildTabBrowser {
@override
bool get hasOpener => false;
@override
void detachOpener() {}
@override
List<String> get sessionStorageKeys => const [];
@override
void removeSessionStorageKey(String key) {}
}
+25
View File
@@ -0,0 +1,25 @@
import 'package:tmail_ui_user/main/utils/child_tab_browser.dart';
import 'package:web/web.dart' as web;
/// Reads the raw JS values: `dart:html` wraps a JS `null` opener into a
/// non-null object, so `window.opener != null` there is always true.
class PlatformChildTabBrowser implements ChildTabBrowser {
@override
bool get hasOpener => web.window.opener != null;
@override
void detachOpener() => web.window.opener = null;
@override
List<String> get sessionStorageKeys {
final storage = web.window.sessionStorage;
return [
for (var i = 0; i < storage.length; i++)
if (storage.key(i) case final key?) key,
];
}
@override
void removeSessionStorageKey(String key) =>
web.window.sessionStorage.removeItem(key);
}
@@ -0,0 +1,37 @@
import 'package:core/utils/app_logger.dart';
import 'package:model/email/email_action_type.dart';
import 'package:tmail_ui_user/features/identity_creator/data/datasource_impl/local_identity_creator_data_source_impl.dart';
import 'package:tmail_ui_user/main/utils/child_tab_browser.dart';
import 'package:tmail_ui_user/main/utils/child_tab_browser_platform.dart';
export 'package:tmail_ui_user/main/utils/child_tab_browser.dart';
/// A tab opened by the app inherits a copy of its opener's sessionStorage.
/// This drops the copied composer and identity drafts, then detaches the opener
/// so a later reload of this tab keeps the drafts the tab creates itself.
class ChildTabSessionCleaner {
// Key prefixes, as built by the composer and identity creator caches (TupleKey joins with '|').
static final List<String> copiedDraftKeyPrefixes = [
'${EmailActionType.reopenComposerBrowser.name}|',
'${LocalIdentityCreatorDataSourceImpl.sessionStorageKeyword}|',
];
ChildTabSessionCleaner([ChildTabBrowser? browser])
: _browser = browser ?? PlatformChildTabBrowser();
final ChildTabBrowser _browser;
void run() {
try {
if (!_browser.hasOpener) return;
for (final key in _browser.sessionStorageKeys) {
if (copiedDraftKeyPrefixes.any(key.startsWith)) {
_browser.removeSessionStorageKey(key);
}
}
_browser.detachOpener();
} catch (e) {
logWarning('ChildTabSessionCleaner::run: $e');
}
}
}
@@ -258,6 +258,10 @@ void main() {
expect(mockBaseController.validateUrgentException(const BadCredentialsException()), isTrue);
});
test('should return false when exception is CredentialRevokedException', () {
expect(mockBaseController.validateUrgentException(const CredentialRevokedException()), isFalse);
});
test('should return true when exception is ConnectionError', () {
expect(mockBaseController.validateUrgentException(const ConnectionError()), isTrue);
});
@@ -797,6 +801,32 @@ void main() {
expect(mockBaseController.events, ['removeAllComposerCache', 'logout']);
});
testWidgets('web basic logout revokes the other tabs, OIDC does not', (tester) async {
PlatformInfo.isTestingForWeb = true;
registerCacheRemoval();
await tester.pumpWidget(const SizedBox());
for (final (type, calls) in [
(AuthenticationType.basic, 1),
(AuthenticationType.oidc, 0),
]) {
clearInteractions(mockCachingManager);
when(mockAuthorizationInterceptors.authenticationType).thenReturn(type);
when(mockLogoutOidcInteractor.execute()).thenAnswer((_) => const Stream.empty());
mockBaseController.logout(
tester.element(find.byType(SizedBox)),
SessionFixtures.aliceSession,
AccountFixtures.aliceAccountId,
'alice@example.com',
);
await tester.pumpAndSettle();
calls == 0
? verifyNever(mockCachingManager.revokeOtherTabs())
: verify(mockCachingManager.revokeOtherTabs()).called(calls);
}
});
});
group('BaseController::logoutToSignInNewAccount', () {
@@ -872,6 +902,26 @@ void main() {
onFailureCallback: onFailure,
);
test('web basic session: revokes the other tabs, OIDC does not', () async {
PlatformInfo.isTestingForWeb = true;
addTearDown(() => PlatformInfo.isTestingForWeb = false);
when(mockLogoutOidcInteractor.execute()).thenAnswer(
(_) => Stream.value(Right<Failure, Success>(LogoutOidcSuccess())));
for (final (type, calls) in [
(AuthenticationType.basic, 1),
(AuthenticationType.oidc, 0),
]) {
clearInteractions(mockCachingManager);
when(mockAuthorizationInterceptors.authenticationType).thenReturn(type);
await logout(onSuccess: () {}, onFailure: ({exception}) => fail('$exception'));
calls == 0
? verifyNever(mockCachingManager.revokeOtherTabs())
: verify(mockCachingManager.revokeOtherTabs()).called(calls);
}
});
test('basic session: completes only after the success callback completed', () async {
when(mockAuthorizationInterceptors.authenticationType).thenReturn(AuthenticationType.basic);
final signIn = Completer<void>();
@@ -0,0 +1,61 @@
import 'package:core/presentation/resources/image_paths.dart';
import 'package:core/presentation/utils/responsive_utils.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:jmap_dart_client/jmap/account_id.dart';
import 'package:model/email/presentation_email.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller.dart';
import 'package:tmail_ui_user/features/thread/presentation/mixin/email_action_controller.dart';
import 'package:tmail_ui_user/main/utils/app_route_tab_environment.dart';
class _RecordingTabEnvironment extends AppRouteTabEnvironment {
final List<bool> isBasicAuthCalls = [];
@override
void openInNewTab(String url, {required bool isBasicAuth}) =>
isBasicAuthCalls.add(isBasicAuth);
}
// EmailActionController finds the dashboard at construction; nothing else is used.
class _FakeDashboardController extends Fake implements MailboxDashBoardController {
@override
InternalFinalCallback<void> get onStart => InternalFinalCallback<void>(callback: () {});
@override
InternalFinalCallback<void> get onDelete => InternalFinalCallback<void>(callback: () {});
}
class _EmailHost with EmailActionController {
_EmailHost(this.isAuthenticatedWithOidc, this.tabEnvironment);
@override
final bool isAuthenticatedWithOidc;
@override
final AppRouteTabEnvironment tabEnvironment;
@override
AccountId? get activeAccountId => null;
}
void main() {
final email = PresentationEmail(routeWeb: Uri.parse('https://app.example.com/#/dashboard'));
group('openEmailInNewTabAction', () {
setUp(() {
Get.put<MailboxDashBoardController>(_FakeDashboardController());
Get.put(ResponsiveUtils());
Get.put(ImagePaths());
});
tearDown(Get.reset);
for (final (isOidc, isBasicAuth) in [(false, true), (true, false)]) {
test('oidc=$isOidc opens with isBasicAuth=$isBasicAuth', () {
final environment = _RecordingTabEnvironment();
_EmailHost(isOidc, environment).openEmailInNewTabAction(email);
expect(environment.isBasicAuthCalls, [isBasicAuth]);
});
}
});
}
@@ -0,0 +1,42 @@
@TestOn('chrome')
import 'package:flutter_test/flutter_test.dart';
import 'package:jmap_dart_client/jmap/account_id.dart';
import 'package:jmap_dart_client/jmap/core/id.dart';
import 'package:jmap_dart_client/jmap/mail/mailbox/mailbox.dart';
import 'package:model/mailbox/presentation_mailbox.dart';
import 'package:tmail_ui_user/features/base/mixin/mailbox_action_handler_mixin.dart';
import 'package:tmail_ui_user/main/utils/app_route_tab_environment.dart';
class _RecordingTabEnvironment extends AppRouteTabEnvironment {
final List<bool> isBasicAuthCalls = [];
@override
void openInNewTab(String url, {required bool isBasicAuth}) =>
isBasicAuthCalls.add(isBasicAuth);
}
class _MailboxHost with MailboxActionHandlerMixin {
_MailboxHost(this.isAuthenticatedWithOidc, this.tabEnvironment);
@override
final bool isAuthenticatedWithOidc;
@override
final AppRouteTabEnvironment tabEnvironment;
@override
AccountId? get activeAccountId => null;
}
void main() {
final mailbox = PresentationMailbox(MailboxId(Id('folder-id')));
for (final (isOidc, isBasicAuth) in [(false, true), (true, false)]) {
test('openMailboxInNewTabAction: oidc=$isOidc opens with isBasicAuth=$isBasicAuth', () {
final environment = _RecordingTabEnvironment();
_MailboxHost(isOidc, environment).openMailboxInNewTabAction(mailbox);
expect(environment.isBasicAuthCalls, [isBasicAuth]);
});
}
}
@@ -85,6 +85,14 @@ void main() {
expect(Get.isRegistered<ComposerController>(tag: '3'), isFalse);
});
test('saveAllReloadSnapshots writes the snapshot of every open composer', () {
composerManager.saveAllReloadSnapshots();
verify(mockController1.saveReloadSnapshot()).called(1);
verify(mockController2.saveReloadSnapshot()).called(1);
verify(mockController3.saveReloadSnapshot()).called(1);
});
// Only test for desktop with minWidth = 1200
group('ComposerManager::arrangeComposerWhenComposerQueueChanged::', () {
test('Should keep all hidden composers unchanged when screen width changes', () {
@@ -0,0 +1,300 @@
import 'package:core/utils/platform_info.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/features/login/data/local/authentication_info_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/model/authentication_info_cache.dart';
import 'package:tmail_ui_user/features/login/domain/exceptions/authentication_exception.dart';
import 'authentication_info_cache_test_doubles.dart';
void main() {
const key = AuthenticationInfoCacheManager.signOutTagKey;
const loginKey = AuthenticationInfoCache.keyCacheValue;
final info = AuthenticationInfoCache('alice@example.com', 'alice');
late FakeHiveLoginBox hive;
late FakeSignOutMarkerStorage marker;
setUp(() {
PlatformInfo.isTestingForWeb = true;
FlutterSecureStorage.setMockInitialValues({});
hive = FakeHiveLoginBox();
marker = FakeSignOutMarkerStorage();
});
tearDown(() => PlatformInfo.isTestingForWeb = false);
// Each manager + session storage pair models one browser tab sharing the same localStorage.
(AuthenticationInfoCacheManager, FakeSessionStorage) newTab() {
final session = FakeSessionStorage();
final manager = AuthenticationInfoCacheManager(
hive.mock,
session,
secureStorage: const FlutterSecureStorage(),
markerStorage: marker,
);
return (manager, session);
}
// A tab opened by the app: the browser copies sessionStorage, the in-memory state is new.
(AuthenticationInfoCacheManager, FakeSessionStorage) openChildTab(FakeSessionStorage parent) {
final (manager, session) = newTab();
session.values.addAll(parent.values);
return (manager, session);
}
group('login store', () {
test('creates the marker and tags the stored login with it', () async {
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
expect(marker.value, isNotEmpty);
expect(session.values[key], marker.value);
expect(manager.isLoginRevokedInThisTab(), isFalse);
});
test('keeps an existing marker', () async {
marker.value = 'existing';
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
expect(marker.value, 'existing');
expect(session.values[key], 'existing');
});
test('re-tags when another tab changed the marker during the login', () async {
marker.replaceAfterNextWrite = 'other-tab';
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
expect(marker.value, 'other-tab');
expect(session.values[key], 'other-tab');
expect(manager.isLoginRevokedInThisTab(), isFalse);
expect(await manager.getAuthenticationInfoStored(), info);
});
test('does not write the password when the marker cannot be written', () async {
marker.failWrites = true;
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
expect(session.values.containsKey(loginKey), isFalse);
expect(session.values.containsKey(key), isFalse);
expect(await manager.getAuthenticationInfoStored(), info);
expect(manager.isLoginRevokedInThisTab(), isFalse);
});
test('a failed marker write does not leave the previous login in session storage', () async {
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
marker.value = null;
marker.failWrites = true;
await manager.storeAuthenticationInfo(AuthenticationInfoCache('bob@example.com', 'bob'));
expect(session.values.containsKey(loginKey), isFalse);
expect(manager.isLoginRevokedInThisTab(), isFalse);
});
});
group('login read', () {
test('a tag that differs from the marker deletes the copy and throws', () async {
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
marker.value = 'rotated';
hive.item = info;
await expectLater(
manager.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
expect(session.values.containsKey(loginKey), isFalse);
expect(session.values.containsKey(key), isFalse);
// Hive keeps its item: the legacy login is not consulted or moved.
expect(hive.item, info);
expect(hive.insertCalls, 0);
});
test('a missing marker is a mismatch', () async {
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
marker.value = null;
hive.item = info;
await expectLater(
manager.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
expect(session.values.containsKey(loginKey), isFalse);
});
test('a copy without a tag is a mismatch', () async {
marker.value = 'current';
final (manager, session) = newTab();
session.values[loginKey] = '{"username":"alice@example.com","password":"alice"}';
hive.item = info;
await expectLater(
manager.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
expect(session.values.containsKey(loginKey), isFalse);
expect(hive.item, info);
});
test('a tab keeps reporting revoked after its copy was deleted', () async {
final (manager, _) = newTab();
await manager.storeAuthenticationInfo(info);
marker.value = 'rotated';
await manager.getAuthenticationInfoStored().then((_) {}, onError: (_) {});
expect(manager.isLoginRevokedInThisTab(), isTrue);
});
});
group('sign out', () {
test('clear forgets the tag, so a later sign out elsewhere does not revoke this tab', () async {
final (manager, _) = newTab();
await manager.storeAuthenticationInfo(info);
await manager.clear();
marker.value = 'rotated-by-other-tab';
expect(manager.isLoginRevokedInThisTab(), isFalse);
});
test('clear does not rotate the marker', () async {
final (manager, _) = newTab();
await manager.storeAuthenticationInfo(info);
final before = marker.value;
await manager.clear();
expect(marker.value, before);
expect(manager.isLoginRevokedInThisTab(), isFalse);
});
test('clear keeps another tab signed in', () async {
final (tabA, sessionA) = newTab();
await tabA.storeAuthenticationInfo(info);
final (tabB, _) = openChildTab(sessionA);
await tabB.getAuthenticationInfoStored();
await tabA.clear();
expect(await tabB.getAuthenticationInfoStored(), info);
expect(tabB.isLoginRevokedInThisTab(), isFalse);
});
test('revokeOtherTabs rotates the marker and keeps the calling tab valid', () async {
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
final before = marker.value;
manager.revokeOtherTabs();
expect(marker.value, isNot(before));
expect(session.values[key], marker.value);
expect(manager.isLoginRevokedInThisTab(), isFalse);
expect(await manager.getAuthenticationInfoStored(), info);
});
test('revokeOtherTabs revokes another tab holding the old tag', () async {
final (tabA, sessionA) = newTab();
await tabA.storeAuthenticationInfo(info);
final (tabB, sessionB) = openChildTab(sessionA);
expect(await tabB.getAuthenticationInfoStored(), info);
expect(tabB.isLoginRevokedInThisTab(), isFalse);
tabA.revokeOtherTabs();
expect(tabB.isLoginRevokedInThisTab(), isTrue);
await expectLater(
tabB.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
expect(sessionB.values.containsKey(loginKey), isFalse);
});
test('revokeOtherTabs removes the marker when the new one cannot be written', () async {
final (tabA, sessionA) = newTab();
await tabA.storeAuthenticationInfo(info);
final (tabB, _) = openChildTab(sessionA);
await tabB.getAuthenticationInfoStored();
marker.failWrites = true;
tabA.revokeOtherTabs();
expect(marker.value, isNull);
expect(tabB.isLoginRevokedInThisTab(), isTrue);
});
test('the signing-out tab can still send its own requests when the marker cannot be rewritten', () async {
final (tabA, _) = newTab();
await tabA.storeAuthenticationInfo(info);
marker.failWrites = true;
tabA.revokeOtherTabs();
expect(tabA.isLoginRevokedInThisTab(), isFalse);
});
test('revokeOtherTabs rotates for a tab whose login lives only in memory', () async {
marker.failWrites = true;
final (manager, session) = newTab();
await manager.storeAuthenticationInfo(info);
marker.failWrites = false;
marker.value = 'other-tab-login';
manager.revokeOtherTabs();
expect(marker.value, isNot('other-tab-login'));
expect(session.values.containsKey(loginKey), isFalse);
});
test('revokeOtherTabs does nothing outside web', () async {
final (manager, _) = newTab();
await manager.storeAuthenticationInfo(info);
final before = marker.value;
PlatformInfo.isTestingForWeb = false;
manager.revokeOtherTabs();
expect(marker.value, before);
});
});
group('isLoginRevokedInThisTab', () {
test('is false when the tab has no login tag', () {
marker.value = 'anything';
final (manager, _) = newTab();
expect(manager.isLoginRevokedInThisTab(), isFalse);
});
test('is false outside web even if the marker changed', () async {
final (manager, _) = newTab();
await manager.storeAuthenticationInfo(info);
marker.value = 'rotated';
PlatformInfo.isTestingForWeb = false;
expect(manager.isLoginRevokedInThisTab(), isFalse);
});
test('is true when the marker changed or disappeared', () async {
final (manager, _) = newTab();
await manager.storeAuthenticationInfo(info);
marker.value = 'rotated';
expect(manager.isLoginRevokedInThisTab(), isTrue);
marker.value = null;
expect(manager.isLoginRevokedInThisTab(), isTrue);
});
});
}
@@ -0,0 +1,136 @@
import 'dart:async';
import 'dart:convert';
import 'package:core/utils/platform_info.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/features/login/data/local/authentication_info_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/model/authentication_info_cache.dart';
import 'package:tmail_ui_user/features/login/domain/exceptions/authentication_exception.dart';
import 'authentication_info_cache_test_doubles.dart';
void main() {
const key = AuthenticationInfoCache.keyCacheValue;
final alice = AuthenticationInfoCache('alice@example.com', 'alice-pw');
final bob = AuthenticationInfoCache('bob@example.com', 'bob-pw');
late FakeHiveLoginBox client;
late FakeSecureStorage storage;
setUp(() {
PlatformInfo.isTestingForWeb = false;
client = FakeHiveLoginBox();
storage = FakeSecureStorage();
});
AuthenticationInfoCacheManager newManager() =>
AuthenticationInfoCacheManager(client.mock, FakeSessionStorage(), secureStorage: storage);
// Starts a read, logs out while [hold] blocks it, then expects the read to find no login.
Future<void> expectReadAcrossLogoutFindsNothing(
AuthenticationInfoCacheManager manager,
Completer<void> hold,
) async {
final pending = manager.getAuthenticationInfoStored();
await pumpEventQueue();
await manager.clear();
hold.complete();
await expectLater(pending, throwsA(isA<NotFoundAuthenticationInfoCache>()));
}
group('mobile secure login', () {
test('a throwing overwrite does not leave the previous account for the next cold start', () async {
storage.values[key] = jsonEncode({'username': alice.username, 'password': alice.password});
storage.throwOnWrite = true;
final manager = newManager();
await manager.storeAuthenticationInfo(bob);
expect(await manager.getAuthenticationInfoStored(), bob);
// Cold start: the old account must not come back for downloads.
expect(
newManager().getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('a dropped new login does not leave the earlier Hive login for the next cold start', () async {
client.item = alice;
storage.dropAllWrites = true;
await newManager().storeAuthenticationInfo(bob);
expect(client.item, isNull);
expect(
newManager().getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('repeated reads clear the Hive box at most once', () async {
await newManager().storeAuthenticationInfo(alice);
final manager = newManager();
client.clearCalls = 0;
await manager.getAuthenticationInfoStored();
await manager.getAuthenticationInfoStored();
await manager.getAuthenticationInfoStored();
expect(client.clearCalls, lessThanOrEqualTo(1));
});
test('a throwing delete on logout still leaves no login for the next cold start', () async {
await newManager().storeAuthenticationInfo(alice);
storage.throwOnDelete = true;
await newManager().clear();
expect(
newManager().getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('a delete that reports success but keeps the login still logs out', () async {
await newManager().storeAuthenticationInfo(alice);
storage.dropDeletes = true;
await newManager().clear();
expect(
newManager().getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('a Hive read pending during logout does not move the login back', () async {
client.item = alice;
client.holdGet = Completer<void>();
final manager = newManager();
await expectReadAcrossLogoutFindsNothing(manager, client.holdGet!);
expect(
newManager().getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('a secure write pending during logout does not persist the login', () async {
client.item = alice;
storage.holdWrite = Completer<void>();
final manager = newManager();
await expectReadAcrossLogoutFindsNothing(manager, storage.holdWrite!);
expect(storage.values.containsKey(key), isFalse);
});
test('a secure read pending during logout does not return the password', () async {
storage.values[key] = jsonEncode({'username': alice.username, 'password': alice.password});
storage.holdRead = Completer<void>();
final manager = newManager();
await expectReadAcrossLogoutFindsNothing(manager, storage.holdRead!);
});
});
}
@@ -0,0 +1,255 @@
import 'dart:convert';
import 'package:core/utils/platform_info.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/features/login/data/local/authentication_info_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/model/authentication_info_cache.dart';
import 'package:tmail_ui_user/features/login/domain/exceptions/authentication_exception.dart';
import 'authentication_info_cache_test_doubles.dart';
void main() {
late FakeHiveLoginBox client;
late FakeSessionStorage session;
late FakeSignOutMarkerStorage marker;
late AuthenticationInfoCacheManager manager;
final info = AuthenticationInfoCache('alice@example.com', 'alice');
const key = AuthenticationInfoCache.keyCacheValue;
setUp(() {
client = FakeHiveLoginBox();
session = FakeSessionStorage();
FlutterSecureStorage.setMockInitialValues({});
marker = FakeSignOutMarkerStorage();
manager = AuthenticationInfoCacheManager(
client.mock,
session,
secureStorage: const FlutterSecureStorage(),
markerStorage: marker,
);
});
tearDown(() => PlatformInfo.isTestingForWeb = false);
group('web', () {
setUp(() => PlatformInfo.isTestingForWeb = true);
test('store keeps the login in session storage and empties the Hive box', () async {
client.item = info;
await manager.storeAuthenticationInfo(info);
expect(session.values.containsKey(key), isTrue);
expect(client.insertCalls, 0);
expect(client.item, isNull);
});
test('get reads from session storage first without another Hive purge', () async {
await manager.storeAuthenticationInfo(info);
client.clearCalls = 0;
final result = await manager.getAuthenticationInfoStored();
expect(result, info);
expect(client.clearCalls, 0);
});
test('get retries the Hive purge after a failed store purge', () async {
client.item = info;
client.clearFailures = 1;
await manager.storeAuthenticationInfo(info);
expect(client.item, info);
await manager.getAuthenticationInfoStored();
expect(client.item, isNull);
});
test('get moves an earlier Hive login to session storage', () async {
client.item = info;
final result = await manager.getAuthenticationInfoStored();
expect(result, info);
expect(session.values.containsKey(key), isTrue);
expect(client.item, isNull);
});
test('get throws when neither store has a login', () async {
expect(
manager.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('get ignores a malformed session value', () async {
marker.value = 'marker';
session.values[key] = 'not json';
session.values[AuthenticationInfoCacheManager.signOutTagKey] = 'marker';
client.item = info;
expect(await manager.getAuthenticationInfoStored(), info);
});
test('clear removes the session value and empties the Hive box', () async {
await manager.storeAuthenticationInfo(info);
await manager.clear();
expect(session.values.containsKey(key), isFalse);
expect(client.item, isNull);
});
});
group('mobile', () {
const secure = FlutterSecureStorage();
Future<AuthenticationInfoCache?> readSecure() async {
final raw = await secure.read(key: key);
if (raw == null) return null;
final json = jsonDecode(raw) as Map<String, dynamic>;
return AuthenticationInfoCache(json['username'] as String, json['password'] as String);
}
test('store writes to secure storage and empties the Hive box', () async {
client.item = info;
await manager.storeAuthenticationInfo(info);
expect(await readSecure(), info);
expect(client.item, isNull);
expect(session.values, isEmpty);
});
test('get reads secure storage and retries the Hive purge', () async {
client.item = info;
client.clearFailures = 1;
await manager.storeAuthenticationInfo(info);
expect(client.item, info);
expect(await manager.getAuthenticationInfoStored(), info);
expect(client.item, isNull);
});
test('get ignores a malformed secure value and migrates Hive', () async {
await const FlutterSecureStorage().write(key: key, value: 'not json');
client.item = info;
expect(await manager.getAuthenticationInfoStored(), info);
expect(await readSecure(), info);
expect(client.item, isNull);
});
test('get moves an earlier Hive login to secure storage', () async {
client.item = info;
expect(await manager.getAuthenticationInfoStored(), info);
expect(await readSecure(), info);
expect(client.item, isNull);
});
test('get throws when neither store has a login', () async {
expect(
manager.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('unavailable secure storage keeps the Hive login', () async {
manager = AuthenticationInfoCacheManager(client.mock, session, secureStorage: FakeSecureStorage()..isUnavailable = true);
client.item = info;
expect(await manager.getAuthenticationInfoStored(), info);
expect(client.item, info);
expect(await manager.getAuthenticationInfoStored(), info);
});
test('a dropped secure write keeps the Hive login', () async {
manager = AuthenticationInfoCacheManager(client.mock, session, secureStorage: FakeSecureStorage()..dropAllWrites = true);
client.item = info;
expect(await manager.getAuthenticationInfoStored(), info);
expect(client.item, info);
expect(client.clearCalls, 0);
});
test('a dropped secure write on a fresh login keeps it for this run', () async {
manager = AuthenticationInfoCacheManager(client.mock, session, secureStorage: FakeSecureStorage()..dropAllWrites = true);
await manager.storeAuthenticationInfo(info);
expect(await manager.getAuthenticationInfoStored(), info);
expect(client.insertCalls, 0);
});
test('a dropped overwrite clears the earlier secure login', () async {
final bob = AuthenticationInfoCache('bob@example.com', 'bob');
final storage = FakeSecureStorage()
..dropAllWrites = true
..values[key] = jsonEncode({'username': info.username, 'password': info.password});
manager = AuthenticationInfoCacheManager(client.mock, session, secureStorage: storage);
await manager.storeAuthenticationInfo(bob);
expect(await manager.getAuthenticationInfoStored(), bob);
expect(storage.values.containsKey(key), isFalse);
// Cold start: no stale login survives.
manager = AuthenticationInfoCacheManager(client.mock, session, secureStorage: storage);
expect(
manager.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('a later successful store clears the in-memory login and purges Hive', () async {
final storage = FakeSecureStorage()..writesToDrop = 1;
manager = AuthenticationInfoCacheManager(client.mock, session, secureStorage: storage);
client.item = info;
await manager.storeAuthenticationInfo(info);
expect(await manager.getAuthenticationInfoStored(), info);
expect(client.item, isNull);
expect(storage.values, isEmpty);
await manager.storeAuthenticationInfo(info);
expect(storage.values[key], isNotNull);
// Stale memory would still return the login after secure storage is wiped.
storage.values.clear();
expect(
manager.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('clear drops a login kept for this run', () async {
manager = AuthenticationInfoCacheManager(client.mock, session, secureStorage: FakeSecureStorage()..dropAllWrites = true);
await manager.storeAuthenticationInfo(info);
expect(await manager.getAuthenticationInfoStored(), info);
await manager.clear();
expect(
manager.getAuthenticationInfoStored(),
throwsA(isA<NotFoundAuthenticationInfoCache>()),
);
});
test('clear removes the secure value and empties the Hive box', () async {
await manager.storeAuthenticationInfo(info);
client.item = info;
await manager.clear();
expect(await readSecure(), isNull);
expect(client.item, isNull);
});
});
}
@@ -0,0 +1,155 @@
import 'dart:async';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:tmail_ui_user/features/caching/clients/authentication_info_cache_client.dart';
import 'package:tmail_ui_user/features/caching/exceptions/local_storage_exception.dart';
import 'package:tmail_ui_user/features/caching/utils/session_storage_manager.dart';
import 'package:tmail_ui_user/features/caching/utils/sign_out_marker_storage.dart';
import 'package:tmail_ui_user/features/login/data/model/authentication_info_cache.dart';
import 'authentication_info_cache_test_doubles.mocks.dart';
@GenerateNiceMocks([
MockSpec<AuthenticationInfoCacheClient>(),
])
// Hive login box: one item, counts inserts and clears; clearFailures makes the next clears throw.
class FakeHiveLoginBox {
final mock = MockAuthenticationInfoCacheClient();
AuthenticationInfoCache? item;
int insertCalls = 0;
int clearCalls = 0;
int clearFailures = 0;
Completer<void>? holdGet;
FakeHiveLoginBox() {
when(mock.insertItem(any, any, isolated: anyNamed('isolated'))).thenAnswer((invocation) async {
insertCalls++;
item = invocation.positionalArguments[1] as AuthenticationInfoCache;
});
when(mock.getItem(any, isolated: anyNamed('isolated'))).thenAnswer((_) async {
final value = item;
await holdGet?.future;
return value;
});
when(mock.clearAllData(isolated: anyNamed('isolated'))).thenAnswer((_) async {
clearCalls++;
if (clearFailures > 0) {
clearFailures--;
throw Exception('clear failed');
}
item = null;
});
}
}
// Shared across fake tabs the way localStorage is; failWrites models a full quota.
class FakeSignOutMarkerStorage implements SignOutMarkerStorage {
String? value;
bool failWrites = false;
// Simulates another tab replacing the marker right after this write lands.
String? replaceAfterNextWrite;
@override
String? read() => value;
@override
void write(String marker) {
if (failWrites) throw Exception('QuotaExceededError');
value = marker;
final other = replaceAfterNextWrite;
if (other != null) {
replaceAfterNextWrite = null;
value = other;
}
}
@override
void remove() => value = null;
}
// Same noSuchMethod approach as FakeSecureStorage: SessionStorageManager exposes dart:html types.
class FakeSessionStorage implements SessionStorageManager {
final Map<String, String> values = {};
@override
dynamic noSuchMethod(Invocation invocation) {
final args = invocation.positionalArguments;
switch (invocation.memberName) {
case #save:
values[args[0] as String] = args[1] as String;
return null;
case #get:
return values[args[0] as String] ?? (throw const NotFoundDataWithThisKeyException());
case #remove:
values.remove(args[0] as String);
return null;
}
return super.noSuchMethod(invocation);
}
}
// Map-backed secure storage; dropped writes model fss 8 iOS OSStatus results that look like success.
// Handles write/read/delete in one noSuchMethod: mocking FlutterSecureStorage pulls dart:html into the VM test.
class FakeSecureStorage implements FlutterSecureStorage {
final Map<String, String> values = {};
bool isUnavailable = false;
bool dropAllWrites = false;
int writesToDrop = 0;
bool throwOnWrite = false;
bool throwOnDelete = false;
bool dropDeletes = false;
Completer<void>? holdWrite;
// Holds only the next read, so a later verify read inside clear() is not blocked.
Completer<void>? holdRead;
@override
dynamic noSuchMethod(Invocation invocation) {
if (isUnavailable) throw UnimplementedError();
final key = invocation.namedArguments[#key] as String;
switch (invocation.memberName) {
case #write:
return _writeAfterHold(invocation);
case #read:
return _readAfterHold(key);
case #delete:
return _delete(key);
}
return super.noSuchMethod(invocation);
}
Future<void> _writeAfterHold(Invocation invocation) async {
await holdWrite?.future;
_write(invocation);
}
Future<String?> _readAfterHold(String key) async {
final snapshot = values[key];
final hold = holdRead;
holdRead = null;
await hold?.future;
return snapshot;
}
Future<void> _delete(String key) async {
if (throwOnDelete) throw Exception('delete failed');
if (!dropDeletes) values.remove(key);
}
void _write(Invocation invocation) {
if (throwOnWrite) throw Exception('keystore unavailable');
if (dropAllWrites) return;
if (writesToDrop > 0) {
writesToDrop--;
return;
}
final key = invocation.namedArguments[#key] as String;
final value = invocation.namedArguments[#value] as String?;
if (value == null) {
values.remove(key);
} else {
values[key] = value;
}
}
}
@@ -0,0 +1,175 @@
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:jmap_dart_client/jmap/core/user_name.dart';
import 'package:model/account/password.dart';
import 'package:tmail_ui_user/features/login/data/local/account_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/local/token_oidc_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/network/authentication_client/authentication_client_base.dart';
import 'package:tmail_ui_user/features/login/data/network/interceptors/authorization_interceptors.dart';
import 'package:tmail_ui_user/main/exceptions/remote/authentication_exception.dart';
import 'package:tmail_ui_user/main/exceptions/thrower/remote_exception_thrower.dart';
import 'package:tmail_ui_user/main/utils/ios_sharing_manager.dart';
import '../../../../../fixtures/oidc_fixtures.dart';
class _FakeAuthenticationClient extends Fake implements AuthenticationClientBase {}
class _FakeTokenOidcCacheManager extends Fake implements TokenOidcCacheManager {}
class _FakeAccountCacheManager extends Fake implements AccountCacheManager {}
class _FakeIOSSharingManager extends Fake implements IOSSharingManager {}
void main() {
var revoked = false;
var checks = 0;
AuthorizationInterceptors newInterceptors({bool withCallback = true}) {
return AuthorizationInterceptors(
Dio(),
_FakeAuthenticationClient(),
_FakeTokenOidcCacheManager(),
_FakeAccountCacheManager(),
_FakeIOSSharingManager(),
isBasicLoginRevoked: withCallback
? () {
checks++;
return revoked;
}
: null,
);
}
setUp(() {
revoked = false;
checks = 0;
});
// dio completes the handler future normally on next and with the state on reject;
// the state type is not exported, so only its data is read.
Future<({bool rejected, dynamic data})> intercept(
AuthorizationInterceptors interceptors,
RequestOptions options,
) async {
final handler = RequestInterceptorHandler();
interceptors.onRequest(options, handler);
try {
final state = await handler.future;
return (rejected: false, data: state.data);
} catch (state) {
return (rejected: true, data: (state as dynamic).data);
}
}
RequestOptions request({Map<String, dynamic>? headers}) =>
RequestOptions(path: 'https://jmap.example.com/jmap', headers: headers);
group('basic login', () {
late AuthorizationInterceptors interceptors;
setUp(() {
interceptors = newInterceptors()
..setBasicAuthorization(UserName('alice'), Password('secret'));
});
test('revoked login rejects the request with CredentialRevokedException', () async {
revoked = true;
final options = request();
final state = await intercept(interceptors, options);
expect(state.rejected, isTrue);
final error = state.data as DioException;
expect(error.error, isA<CredentialRevokedException>());
expect(options.headers.containsKey(HttpHeaders.authorizationHeader), isFalse);
});
test('revoked login strips an Authorization header the request already carried', () async {
revoked = true;
final options = request(headers: {HttpHeaders.authorizationHeader: 'Basic leaked'});
final state = await intercept(interceptors, options);
expect(state.rejected, isTrue);
expect(options.headers.containsKey(HttpHeaders.authorizationHeader), isFalse);
});
test('valid login still attaches credentials and continues', () async {
final options = request();
final state = await intercept(interceptors, options);
expect(state.rejected, isFalse);
expect(options.headers[HttpHeaders.authorizationHeader], startsWith('Basic '));
});
test('a request that opts out of authorization skips the revocation check', () async {
revoked = true;
final options = RequestOptions(
path: 'https://guessed.example.org/.well-known/webfinger',
extra: {AuthorizationInterceptors.skipAuthorizationKey: true},
);
final state = await intercept(interceptors, options);
expect(state.rejected, isFalse);
expect(checks, 0);
});
test('without a callback the request is sent as before', () async {
final plain = newInterceptors(withCallback: false)
..setBasicAuthorization(UserName('alice'), Password('secret'));
final state = await intercept(plain, request());
expect(state.rejected, isFalse);
});
});
group('other authentication types', () {
test('oidc is never checked for revocation', () async {
revoked = true;
final interceptors = newInterceptors()
..setTokenAndAuthorityOidc(
newToken: OIDCFixtures.tokenOidcNotExpiredYet,
newConfig: OIDCFixtures.oidcConfiguration,
);
final options = request();
final state = await intercept(interceptors, options);
expect(state.rejected, isFalse);
expect(options.headers[HttpHeaders.authorizationHeader], startsWith('Bearer '));
expect(checks, 0);
});
test('unauthenticated requests are never checked for revocation', () async {
revoked = true;
final state = await intercept(newInterceptors(), request());
expect(state.rejected, isFalse);
expect(checks, 0);
});
});
group('CredentialRevokedException', () {
test('is not mapped to BadCredentialsException by the remote exception thrower', () {
final error = DioException(
requestOptions: RequestOptions(path: '/jmap'),
error: const CredentialRevokedException(),
);
expect(
() => RemoteExceptionThrower().handleDioError(error),
throwsA(isA<CredentialRevokedException>()),
);
expect(
() => RemoteExceptionThrower().handleDioError(error),
throwsA(isNot(isA<BadCredentialsException>())),
);
});
});
}
@@ -0,0 +1,54 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:model/account/authentication_type.dart';
import 'package:model/account/personal_account.dart';
import 'package:tmail_ui_user/features/login/data/model/authentication_info_cache.dart';
import 'package:tmail_ui_user/features/login/domain/repository/credential_repository.dart';
import 'package:tmail_ui_user/features/login/domain/state/get_credential_state.dart';
import 'package:tmail_ui_user/features/login/domain/usecases/get_credential_interactor.dart';
class _FakeCredentialRepository implements CredentialRepository {
_FakeCredentialRepository(this.stored);
final AuthenticationInfoCache stored;
int removeCalls = 0;
@override
Future<Uri> getBaseUrl() async => Uri.parse('https://jmap.example.com');
@override
Future<AuthenticationInfoCache> getAuthenticationInfoStored() async => stored;
@override
Future<void> removeAuthenticationInfo() async => removeCalls++;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
void main() {
final bobAccount = PersonalAccount(
'bob@example.com',
AuthenticationType.basic,
isSelected: true,
);
test('a stored login of another account does not sign the current one in', () async {
final repository = _FakeCredentialRepository(AuthenticationInfoCache('alice@example.com', 'alice-pw'));
final interactor = GetCredentialInteractor(repository);
final result = await interactor.execute(personalAccount: bobAccount);
expect(result.fold((f) => f, (s) => s), isA<GetCredentialFailure>());
expect(repository.removeCalls, 1);
});
test('the stored login of the current account signs it in', () async {
final repository = _FakeCredentialRepository(AuthenticationInfoCache('bob@example.com', 'bob-pw'));
final interactor = GetCredentialInteractor(repository);
final result = await interactor.execute(personalAccount: bobAccount);
expect(result.fold((f) => f, (s) => s), isA<GetCredentialViewState>());
expect(repository.removeCalls, 0);
});
}
@@ -0,0 +1,319 @@
import 'dart:async';
import 'package:core/presentation/utils/responsive_utils.dart';
import 'package:core/utils/platform_info.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:tmail_ui_user/features/caching/utils/sign_out_marker_storage.dart';
import 'package:tmail_ui_user/features/composer/presentation/manager/composer_manager.dart';
import 'package:tmail_ui_user/features/login/data/local/authentication_info_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/model/authentication_info_cache.dart';
import 'package:tmail_ui_user/features/login/presentation/tab_guard/basic_auth_tab_guard.dart';
import 'package:tmail_ui_user/features/login/presentation/tab_guard/tab_guard_browser.dart';
import 'package:tmail_ui_user/main/utils/twake_app_manager.dart';
import '../../data/local/authentication_info_cache_test_doubles.dart';
class FakeTabGuardBrowser implements TabGuardBrowser {
final storageKeys = StreamController<String?>.broadcast(sync: true);
final activations = StreamController<void>.broadcast(sync: true);
final List<String> calls;
@override
bool isEmlPreviewRoute = false;
bool closeSucceeds = true;
FakeTabGuardBrowser(this.calls);
@override
Stream<String?> get storageEventKeys => storageKeys.stream;
@override
Stream<void> get pageActivations => activations.stream;
@override
bool tryCloseTab() {
calls.add('close');
return closeSucceeds;
}
@override
void replaceWithLoginPage() => calls.add('login');
}
class _FakeComposerManager extends ComposerManager {
int savedAll = 0;
@override
void saveAllReloadSnapshots() => savedAll++;
}
void main() {
const loginKey = AuthenticationInfoCache.keyCacheValue;
const tagKey = AuthenticationInfoCacheManager.signOutTagKey;
const markerKey = SignOutMarkerStorage.markerKey;
late FakeHiveLoginBox hive;
late FakeSignOutMarkerStorage marker;
late FakeSessionStorage session;
late AuthenticationInfoCacheManager manager;
late FakeTabGuardBrowser browser;
late BasicAuthTabGuard guard;
late List<String> calls;
AuthenticationInfoCacheManager newTab(FakeSessionStorage storage) =>
AuthenticationInfoCacheManager(
hive.mock,
storage,
secureStorage: const FlutterSecureStorage(),
markerStorage: marker,
);
setUp(() async {
PlatformInfo.isTestingForWeb = true;
FlutterSecureStorage.setMockInitialValues({});
hive = FakeHiveLoginBox();
marker = FakeSignOutMarkerStorage();
session = FakeSessionStorage();
manager = newTab(session);
await manager.storeAuthenticationInfo(AuthenticationInfoCache('alice@example.com', 'alice'));
calls = [];
browser = FakeTabGuardBrowser(calls);
guard = BasicAuthTabGuard(manager, browser, () => calls.add('save'))..start();
});
tearDown(() {
guard.dispose();
PlatformInfo.isTestingForWeb = false;
});
// Another tab signs out: it replaces the shared marker.
void signOutElsewhere() => marker.value = 'rotated-by-other-tab';
test('revoked: drops only the login copy, saves composers, then goes to login', () {
session.values['composerSnapshot'] = 'draft';
signOutElsewhere();
browser.storageKeys.add(markerKey);
expect(calls, ['save', 'login']);
expect(session.values.containsKey(loginKey), isFalse);
expect(session.values.containsKey(tagKey), isFalse);
expect(session.values['composerSnapshot'], 'draft');
});
test('never touches Hive or the shared marker', () {
signOutElsewhere();
final clearsBefore = hive.clearCalls;
browser.storageKeys.add(markerKey);
expect(hive.clearCalls, clearsBefore);
expect(marker.value, 'rotated-by-other-tab');
});
test('leaves once even when several signals arrive', () async {
signOutElsewhere();
browser.storageKeys.add(markerKey);
browser.storageKeys.add(null);
browser.activations.add(null);
guard.onRevokedRequest();
guard.onRevokedRequest();
await Future<void>.delayed(Duration.zero);
expect(calls.where((c) => c == 'login'), hasLength(1));
expect(calls.where((c) => c == 'save'), hasLength(1));
});
test('not revoked: nothing happens on any signal', () async {
browser.storageKeys.add(markerKey);
browser.storageKeys.add(null);
browser.activations.add(null);
guard.onRevokedRequest();
await Future<void>.delayed(Duration.zero);
expect(calls, isEmpty);
expect(session.values.containsKey(loginKey), isTrue);
});
test('storage event for another key is ignored', () {
signOutElsewhere();
browser.storageKeys.add('emlPreviewContent');
expect(calls, isEmpty);
});
test('cleared storage (null key) triggers a check', () {
signOutElsewhere();
browser.storageKeys.add(null);
expect(calls, ['save', 'login']);
});
test('page becoming active triggers a check', () {
signOutElsewhere();
browser.activations.add(null);
expect(calls, ['save', 'login']);
});
test('revoked request schedules the check instead of running it inline', () async {
signOutElsewhere();
guard.onRevokedRequest();
expect(calls, isEmpty);
await Future<void>.delayed(Duration.zero);
expect(calls, ['save', 'login']);
});
test('EML preview tab closes first and stops when the tab is gone', () {
browser.isEmlPreviewRoute = true;
signOutElsewhere();
browser.storageKeys.add(markerKey);
expect(calls, ['close']);
});
test('EML preview tab that stays open continues to the login page', () {
browser
..isEmlPreviewRoute = true
..closeSucceeds = false;
signOutElsewhere();
browser.storageKeys.add(markerKey);
expect(calls, ['close', 'save', 'login']);
});
test('the tab that signs out is not kicked by its own marker change', () {
manager.revokeOtherTabs();
browser.storageKeys.add(markerKey);
browser.activations.add(null);
guard.onRevokedRequest();
expect(calls, isEmpty);
expect(session.values.containsKey(loginKey), isTrue);
});
test('another tab signing out does not kick a tab that logged in afterwards', () async {
signOutElsewhere();
final fresh = newTab(FakeSessionStorage());
await fresh.storeAuthenticationInfo(AuthenticationInfoCache('bob@example.com', 'bob'));
expect(fresh.isLoginRevokedInThisTab(), isFalse);
});
test('a tab that never read its inherited login still leaves after a sign out elsewhere', () {
final childSession = FakeSessionStorage()..values.addAll(session.values);
final childGuard = BasicAuthTabGuard(newTab(childSession), browser, () => calls.add('save'))..start();
addTearDown(childGuard.dispose);
guard.dispose();
browser.isEmlPreviewRoute = true;
signOutElsewhere();
browser.storageKeys.add(markerKey);
expect(calls, ['close']);
expect(childSession.values.containsKey(loginKey), isFalse);
expect(childSession.values.containsKey(tagKey), isFalse);
});
test('a restored tab with a stale copy leaves once at start, not again on activation', () async {
signOutElsewhere();
final restoredSession = FakeSessionStorage()..values.addAll(session.values);
final restoredCalls = <String>[];
final restoredBrowser = FakeTabGuardBrowser(restoredCalls);
final restoredGuard = BasicAuthTabGuard(
newTab(restoredSession), restoredBrowser, () => restoredCalls.add('save'))..start();
addTearDown(restoredGuard.dispose);
expect(restoredCalls, ['save', 'login']);
expect(restoredSession.values.containsKey(loginKey), isFalse);
restoredBrowser.activations.add(null);
expect(restoredCalls, ['save', 'login']);
});
test('a tab without any login is never kicked', () {
final emptyGuard = BasicAuthTabGuard(newTab(FakeSessionStorage()), browser, () => calls.add('save'))..start();
addTearDown(emptyGuard.dispose);
guard.dispose();
signOutElsewhere();
browser.storageKeys.add(markerKey);
expect(calls, isEmpty);
});
group('isBasicLoginRevokedAndNotifyGuard', () {
setUp(() {
Get.put<AuthenticationInfoCacheManager>(manager);
Get.put<BasicAuthTabGuard>(guard);
});
tearDown(Get.reset);
test('not revoked: false and the guard stays idle', () async {
expect(isBasicLoginRevokedAndNotifyGuard(), isFalse);
await Future<void>.delayed(Duration.zero);
expect(calls, isEmpty);
});
test('revoked: true and the guard leaves', () async {
signOutElsewhere();
expect(isBasicLoginRevokedAndNotifyGuard(), isTrue);
await Future<void>.delayed(Duration.zero);
expect(calls, ['save', 'login']);
});
});
test('forApp: a kicked tab skips the dashboard leave prompt', () {
final twakeAppManager = TwakeAppManager()..setHasComposer(true);
Get.put<AuthenticationInfoCacheManager>(manager);
Get.put<TwakeAppManager>(twakeAppManager);
addTearDown(Get.reset);
final appGuard = BasicAuthTabGuard.forApp();
signOutElsewhere();
appGuard.checkAndLeaveIfRevoked();
expect(twakeAppManager.isExecutingBeforeReconnect, isTrue);
});
test('forApp: a kicked tab saves the open composers before it leaves', () {
Get.put(ResponsiveUtils());
final composerManager = _FakeComposerManager();
Get.put<ComposerManager>(composerManager);
Get.put<AuthenticationInfoCacheManager>(manager);
addTearDown(Get.reset);
final appGuard = BasicAuthTabGuard.forApp();
signOutElsewhere();
appGuard.checkAndLeaveIfRevoked();
expect(composerManager.savedAll, 1);
});
test('inert when not on web', () {
guard.dispose();
PlatformInfo.isTestingForWeb = false;
signOutElsewhere();
final inert = BasicAuthTabGuard(manager, browser, () => calls.add('save'))..start();
browser.storageKeys.add(markerKey);
inert.checkAndLeaveIfRevoked();
expect(calls, isEmpty);
});
}
+101
View File
@@ -1,8 +1,11 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/main/utils/app_route_tab_environment.dart';
import 'package:tmail_ui_user/main/utils/app_utils.dart';
void main() {
openAppRouteInNewTabTests();
group('AppUtils.launchLink', () {
const urlLauncherChannel = MethodChannel('plugins.flutter.io/url_launcher');
late List<String> launchedUrls;
@@ -67,3 +70,101 @@ void main() {
});
});
}
class _FakeAppRouteTabEnvironment extends AppRouteTabEnvironment {
_FakeAppRouteTabEnvironment({
this.web = true,
this.origin = 'https://mail.example.com',
this.originThrows = false,
this.tabOpens = true,
});
final bool web;
final String origin;
final bool originThrows;
final bool tabOpens;
final List<String> tabOpened = [];
final List<String> launched = [];
@override
bool get isWeb => web;
@override
String currentOrigin() {
if (originThrows) throw StateError('no origin');
return origin;
}
@override
bool openTabKeepingSession(String url) {
tabOpened.add(url);
return tabOpens;
}
@override
void launch(String url) => launched.add(url);
}
void _openRoute(
_FakeAppRouteTabEnvironment environment,
String url, {
bool isBasicAuth = true,
}) {
environment.openInNewTab(url, isBasicAuth: isBasicAuth);
}
void openAppRouteInNewTabTests() {
const sameOriginUrl = 'https://mail.example.com/#/email/1';
group('AppRouteTabEnvironment.openInNewTab', () {
test('web, basic auth, same origin keeps the session and skips launchLink', () {
final environment = _FakeAppRouteTabEnvironment();
_openRoute(environment, sameOriginUrl);
expect(environment.tabOpened, [sameOriginUrl]);
expect(environment.launched, isEmpty);
});
test('falls back to launchLink when the browser refuses the tab', () {
final environment = _FakeAppRouteTabEnvironment(tabOpens: false);
_openRoute(environment, sameOriginUrl);
expect(environment.launched, [sameOriginUrl]);
});
final launchLinkCases = <String, _FakeAppRouteTabEnvironment Function()>{
'not web': () => _FakeAppRouteTabEnvironment(web: false),
'different origin': () =>
_FakeAppRouteTabEnvironment(origin: 'https://other.example.com'),
'origin check throwing': () =>
_FakeAppRouteTabEnvironment(originThrows: true),
};
launchLinkCases.forEach((name, build) {
test('$name goes through launchLink', () {
final environment = build();
_openRoute(environment, sameOriginUrl);
expect(environment.tabOpened, isEmpty);
expect(environment.launched, [sameOriginUrl]);
});
});
test('OIDC goes through launchLink', () {
final environment = _FakeAppRouteTabEnvironment();
_openRoute(environment, sameOriginUrl, isBasicAuth: false);
expect(environment.tabOpened, isEmpty);
expect(environment.launched, [sameOriginUrl]);
});
for (final url in ['/email/1', 'null', 'javascript:alert(1)', 'mailto:a@b.c']) {
test('"$url" goes through launchLink', () {
final environment = _FakeAppRouteTabEnvironment();
_openRoute(environment, url);
expect(environment.tabOpened, isEmpty);
expect(environment.launched, [url]);
});
}
});
}
@@ -0,0 +1,84 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/main/utils/child_tab_browser_platform.dart';
import 'package:tmail_ui_user/main/utils/child_tab_session_cleaner.dart';
class _FakeChildTabBrowser implements ChildTabBrowser {
_FakeChildTabBrowser({this.opener = true, this.openerThrows = false});
bool opener;
final bool openerThrows;
final Map<String, String> storage = {};
@override
bool get hasOpener {
if (openerThrows) throw StateError('cross-origin opener');
return opener;
}
@override
void detachOpener() => opener = false;
@override
List<String> get sessionStorageKeys => storage.keys.toList();
@override
void removeSessionStorageKey(String key) => storage.remove(key);
}
void main() {
const composerKey = 'reopenComposerBrowser|account|user|composer-1';
const identityKey = 'identityCreatorSessionStorage|account|user';
const keptKeys = ['authenticationInfoCache', 'basicAuthSignOutTag', 'auth_info', 'other'];
_FakeChildTabBrowser browserWithCopiedStorage({
bool opener = true,
bool openerThrows = false,
}) {
final browser = _FakeChildTabBrowser(opener: opener, openerThrows: openerThrows);
browser.storage
..[composerKey] = 'draft'
..[identityKey] = 'identity'
..addEntries(keptKeys.map((k) => MapEntry(k, 'v')));
return browser;
}
group('ChildTabSessionCleaner', () {
test('with an opener removes only composer and identity snapshots and detaches it', () {
final browser = browserWithCopiedStorage();
ChildTabSessionCleaner(browser).run();
expect(browser.storage.keys, unorderedEquals(keptKeys));
expect(browser.opener, isFalse);
});
test('without an opener removes nothing', () {
final browser = browserWithCopiedStorage(opener: false);
ChildTabSessionCleaner(browser).run();
expect(browser.storage.keys, containsAll([composerKey, identityKey, ...keptKeys]));
});
test('a reload after detaching keeps the draft the tab created itself', () {
final browser = browserWithCopiedStorage();
ChildTabSessionCleaner(browser).run();
const ownDraftKey = 'reopenComposerBrowser|account|user|composer-2';
browser.storage[ownDraftKey] = 'own draft';
ChildTabSessionCleaner(browser).run();
expect(browser.storage.containsKey(ownDraftKey), isTrue);
});
test('an opener that cannot be inspected neither crashes nor removes anything', () {
final browser = browserWithCopiedStorage(openerThrows: true);
expect(() => ChildTabSessionCleaner(browser).run(), returnsNormally);
expect(browser.storage.keys, containsAll([composerKey, identityKey, ...keptKeys]));
});
test('the platform browser used by default reports no opener outside the web build', () {
expect(PlatformChildTabBrowser().hasOpener, isFalse);
expect(() => ChildTabSessionCleaner().run(), returnsNormally);
});
});
}