diff --git a/.github/workflows/_ci-clients.yml b/.github/workflows/_ci-clients.yml index 6fe925c827..8b97f3a4d6 100644 --- a/.github/workflows/_ci-clients.yml +++ b/.github/workflows/_ci-clients.yml @@ -162,6 +162,7 @@ jobs: test/shared/hosted/relay_auth_isolation_test.dart test/features/onboarding/hosted_app_gate_environment_test.dart test/features/settings/builderlab_account_row_test.dart + test/features/settings/settings_sign_out_test.dart test/features/onboarding/hosted_journeys_test.dart test/features/onboarding/hosted_backup_consent_test.dart test/features/onboarding/onboarding_sign_out_test.dart diff --git a/mobile/lib/features/settings/settings_page.dart b/mobile/lib/features/settings/settings_page.dart index 7600223f00..ef3c680932 100644 --- a/mobile/lib/features/settings/settings_page.dart +++ b/mobile/lib/features/settings/settings_page.dart @@ -19,8 +19,7 @@ import '../../shared/auth/auth.dart'; import '../../shared/identity_transfer/nsec_export_sheet.dart'; import '../../shared/clipboard_utils.dart'; import '../../shared/hosted/hosted_environment.dart'; -import '../../shared/hosted/organization_environment.dart'; -import '../../shared/hosted/organization_sign_out.dart'; +import '../../shared/hosted/sign_out.dart'; import '../../shared/push/push_relay_capability_provider.dart'; import '../../shared/push/push_bootstrap.dart'; import '../../shared/relay/relay.dart'; @@ -246,21 +245,23 @@ class SettingsPage extends HookConsumerWidget { ], if (!wide && HostedEnvironment.enabled) const _BuilderlabAccountSection(), - // An internal build's only way out of its organization, rarely - // needed, so it sits last. - if (OrganizationEnvironment.enabled) - AppListCard( - verticalPadding: Grid.twelve, - children: [ - AppListRow( + // Rarely needed, so it sits last. + AppListCard( + verticalPadding: Grid.twelve, + children: [ + // Below Settings' own messenger, so a failure shows + // here rather than on the page underneath. + Builder( + builder: (rowContext) => AppListRow( key: const Key('settings-sign-out'), icon: BuzzIcons.logOut, title: 'Sign out', titleColor: context.colors.error, - onTap: () => confirmOrganizationSignOut(context, ref), + onTap: () => confirmSignOut(rowContext, ref), ), - ], - ), + ), + ], + ), if (packageInfo.hasData) _VersionFooter( version: packageInfo.data!.version, diff --git a/mobile/lib/shared/hosted/builderlab_account.dart b/mobile/lib/shared/hosted/builderlab_account.dart index dd4c10ba6f..f4d03ff23a 100644 --- a/mobile/lib/shared/hosted/builderlab_account.dart +++ b/mobile/lib/shared/hosted/builderlab_account.dart @@ -116,6 +116,12 @@ class BuilderlabAccountClient { // already pending can still reach their relays for a short while. ({String credential, DateTime until})? _signedOut; final _queue = SerialQueue(); + // Session storage changes, kept apart from [_queue] so signing out never + // waits behind a pending account request. + final _storageQueue = SerialQueue(); + // Advances at each sign-out, so a request already in flight cannot adopt or + // save a session afterwards. + int _sessionEpoch = 0; /// How long after sign-out [pushStopAssertion] can still issue. static const pushStopWindow = Duration(minutes: 10); @@ -143,7 +149,11 @@ class BuilderlabAccountClient { _restoring ??= _restore().whenComplete(() => _restoring = null); Future? _restoring; Future _restore() => _serial(() async { - final record = await _readRecord(); + // Read behind any sign-out still clearing, so this never adopts the + // session it is deleting. + final (epoch, record) = await _storageQueue.run( + () async => (_sessionEpoch, await _readRecord()), + ); if (record == null) { // Retries a removal that failed after an earlier sign-out. await _unshare(); @@ -151,13 +161,15 @@ class BuilderlabAccountClient { } try { final verified = await _verify(record.credential); + // Signed out while the check was pending. + if (epoch != _sessionEpoch) return null; if (verified.subject != record.subject) { throw AccountFailure.invalidResponse; } return _adopt(record.credential, verified); } on AccountFailure catch (failure) { if (failure == AccountFailure.signedOut) { - await _clear(); + await _clearSince(epoch); return null; } rethrow; @@ -172,51 +184,65 @@ class BuilderlabAccountClient { required String code, required String verifier, bool Function()? isCurrent, - }) => _serial(() async { - if (code.isEmpty || - !RegExp(r'^[A-Za-z0-9._~-]{43,128}$').hasMatch(verifier)) { - throw AccountFailure.invalidResponse; - } - final stored = await _readRecord(); - final result = await _request( - '/v1/auth/login/exchange', - body: {'code': code, 'code_verifier': verifier}, - ); - final credential = result['session_credential']; - if (credential is! String || - credential.isEmpty || - credential.length > 512) { - throw AccountFailure.invalidResponse; - } - final verified = await _verify(credential); - if (DateTime.tryParse( - result['expires_at'] is String ? result['expires_at'] as String : '', - ) != - verified.expiresAt) { - throw AccountFailure.invalidResponse; - } - if (stored != null && stored.subject != verified.subject) { - throw AccountFailure.differentAccount; - } - if (_disposed || (isCurrent != null && !isCurrent())) { - throw AccountFailure.unavailable; - } - final record = jsonEncode({ - 'origin': accountOrigin.toString(), - 'credential': credential, - 'subject': verified.subject, - 'expires_at': verified.expiresAt.toIso8601String(), - }); - try { - await _storage.write(key: _storageKey, value: record); - if (await _storage.read(key: _storageKey) != record) { - throw AccountFailure.storage; + }) { + // Taken at the call, so an exchange queued before a sign-out can never + // sign back in after it. + final epoch = _sessionEpoch; + return _serial(() async { + if (epoch != _sessionEpoch) throw AccountFailure.unavailable; + if (code.isEmpty || + !RegExp(r'^[A-Za-z0-9._~-]{43,128}$').hasMatch(verifier)) { + throw AccountFailure.invalidResponse; } - } catch (_) { - throw AccountFailure.storage; - } - return _adopt(credential, verified); - }); + final stored = await _readRecord(); + final result = await _request( + '/v1/auth/login/exchange', + body: {'code': code, 'code_verifier': verifier}, + ); + final credential = result['session_credential']; + if (credential is! String || + credential.isEmpty || + credential.length > 512) { + throw AccountFailure.invalidResponse; + } + final verified = await _verify(credential); + if (DateTime.tryParse( + result['expires_at'] is String + ? result['expires_at'] as String + : '', + ) != + verified.expiresAt) { + throw AccountFailure.invalidResponse; + } + if (stored != null && stored.subject != verified.subject) { + throw AccountFailure.differentAccount; + } + final record = jsonEncode({ + 'origin': accountOrigin.toString(), + 'credential': credential, + 'subject': verified.subject, + 'expires_at': verified.expiresAt.toIso8601String(), + }); + // Saved and adopted as one storage change, so a sign-out lands wholly + // before or after it. + return _storageQueue.run(() async { + if (_disposed || + epoch != _sessionEpoch || + (isCurrent != null && !isCurrent())) { + throw AccountFailure.unavailable; + } + try { + await _storage.write(key: _storageKey, value: record); + if (await _storage.read(key: _storageKey) != record) { + throw AccountFailure.storage; + } + } catch (_) { + throw AccountFailure.storage; + } + return _adopt(credential, verified); + }); + }); + } /// An unreadable record is a storage failure, never an absent session: its /// subject is unknown, so only an explicit [clearLocalSession] may drop it. @@ -341,6 +367,7 @@ class BuilderlabAccountClient { ); } return _serial(() async { + final epoch = _sessionEpoch; final credential = _credential; if (credential == null) throw AccountFailure.signedOut; _share(); @@ -366,7 +393,7 @@ class BuilderlabAccountClient { try { await _verify(credential); } on AccountFailure catch (failure) { - if (failure == AccountFailure.signedOut) await _clear(); + if (failure == AccountFailure.signedOut) await _clearSince(epoch); rethrow; } throw AccountFailure.denied; @@ -418,8 +445,31 @@ class BuilderlabAccountClient { ); }); - Future clearLocalSession() => _serial(_clear); + /// Runs at once, without waiting for pending account requests; none of them + /// can adopt or save a session after it. + Future clearLocalSession() { + if (_disposed) return Future.error(AccountFailure.unavailable); + _sessionEpoch++; + return _storageQueue.run(_clear); + } + + /// Ends a session a request found rejected, unless a sign-out already did. + Future _clearSince(int epoch) => _storageQueue.run(() async { + if (epoch == _sessionEpoch) await _clear(); + }); Future _clear() async { + // A session saved but not yet restored (an offline launch) still backs + // the push stops that follow, so read it before deleting it. + var signedOut = _credential; + if (signedOut == null) { + try { + signedOut = (await _readRecord())?.credential; + } on AccountFailure { + // Unreadable: there is no credential to keep. + } + } + // Nothing may share the credential again while it is being removed. + _unshared = null; // Attempt both removals so one failure never leaves the other copy live. var failed = false; try { @@ -433,15 +483,22 @@ class BuilderlabAccountClient { failed = true; } if (failed) { + // The record may already be gone, so an unrestored session's credential + // must survive for the retry's push stops. + if (_credential == null && signedOut != null) { + _signedOut = ( + credential: signedOut, + until: DateTime.now().add(pushStopWindow), + ); + } // The account stays signed in, so the extension gets its copy back. _unshared = _credential; _share(); throw AccountFailure.storage; } - final credential = _credential; - if (credential != null) { + if (signedOut != null) { _signedOut = ( - credential: credential, + credential: signedOut, until: DateTime.now().add(pushStopWindow), ); } diff --git a/mobile/lib/shared/hosted/hosted_flow.dart b/mobile/lib/shared/hosted/hosted_flow.dart index ab44779677..35f611d635 100644 --- a/mobile/lib/shared/hosted/hosted_flow.dart +++ b/mobile/lib/shared/hosted/hosted_flow.dart @@ -23,6 +23,7 @@ import 'hosted_join_policy.dart'; part 'hosted_flow_identity_recovery.dart'; part 'hosted_flow_backup_consent.dart'; +part 'hosted_flow_intent.dart'; enum HostedFlowStage { idle, @@ -1113,9 +1114,22 @@ class HostedFlow extends ChangeNotifier { }); } - Future leave({bool noCommunities = false}) async { + /// Ends the account session for a sign-out that also removes this device's + /// communities. Unlike [signOutAccount] it publishes no stage while it runs, + /// so hosted setup never covers the screen that asked, and a failure throws + /// to the caller instead of blocking the flow. + Future endAccountSession() async { + _abandon(); + await browser.cancel(); + await browser.clearIntent(); + await account.clearLocalSession(); + if (!_disposed && stage != HostedFlowStage.idle) { + _set(HostedFlowStage.idle); + } + } + + void _abandon({bool noCommunities = false}) { _nextGeneration(); - final generation = _generation; _target = null; _importRequested = false; _pairedPubkey = null; @@ -1124,6 +1138,11 @@ class HostedFlow extends ChangeNotifier { accountOnly = false; _clearCommunityBatch(); noCommunitiesToAdd = noCommunities; + } + + Future leave({bool noCommunities = false}) async { + _abandon(noCommunities: noCommunities); + final generation = _generation; try { await browser.cancel(); if (_disposed || generation != _generation) return; @@ -1136,46 +1155,6 @@ class HostedFlow extends ChangeNotifier { } } - static Map _encode(BuzzDeepLink target) { - if (target is HostedCreateCommunity) { - return {'type': 'create', 'name': target.name}; - } - if (target is NostrBindDeepLink) return {'type': 'bind', ...target.fields}; - if (target is AddCommunityDeepLink) { - return {'type': 'add', 'relay': target.relayUrl, 'name': target.name}; - } - final invite = target as InviteDeepLink; - return { - 'type': 'invite', - 'relay': invite.relayUrl, - 'code': invite.code, - if (invite.policyReceipt != null) 'policy_receipt': invite.policyReceipt!, - }; - } - - static BuzzDeepLink? _decode(Map intent) { - if (intent['type'] == 'create') { - final name = intent['name']; - return name != null && HostedCreateCommunity.validName(name) - ? HostedCreateCommunity(name) - : null; - } - final fields = Map.of(intent) - ..remove('type') - ..remove('import_identity') - ..remove('paired_pubkey') - ..remove('paired_protection'); - final host = switch (intent['type']) { - 'bind' => 'nostr-bind', - 'add' => 'add-community', - 'invite' => 'join', - _ => '', - }; - return parseBuzzDeepLink( - Uri(scheme: 'buzz', host: host, queryParameters: fields), - ); - } - @override void dispose() { _disposed = true; diff --git a/mobile/lib/shared/hosted/hosted_flow_intent.dart b/mobile/lib/shared/hosted/hosted_flow_intent.dart new file mode 100644 index 0000000000..44941b9a05 --- /dev/null +++ b/mobile/lib/shared/hosted/hosted_flow_intent.dart @@ -0,0 +1,43 @@ +part of 'hosted_flow.dart'; + +/// The browser sign-in intent that carries [target] through authentication. +Map _encode(BuzzDeepLink target) { + if (target is HostedCreateCommunity) { + return {'type': 'create', 'name': target.name}; + } + if (target is NostrBindDeepLink) return {'type': 'bind', ...target.fields}; + if (target is AddCommunityDeepLink) { + return {'type': 'add', 'relay': target.relayUrl, 'name': target.name}; + } + final invite = target as InviteDeepLink; + return { + 'type': 'invite', + 'relay': invite.relayUrl, + 'code': invite.code, + if (invite.policyReceipt != null) 'policy_receipt': invite.policyReceipt!, + }; +} + +/// The deep link a browser sign-in intent carried, or null if it's invalid. +BuzzDeepLink? _decode(Map intent) { + if (intent['type'] == 'create') { + final name = intent['name']; + return name != null && HostedCreateCommunity.validName(name) + ? HostedCreateCommunity(name) + : null; + } + final fields = Map.of(intent) + ..remove('type') + ..remove('import_identity') + ..remove('paired_pubkey') + ..remove('paired_protection'); + final host = switch (intent['type']) { + 'bind' => 'nostr-bind', + 'add' => 'add-community', + 'invite' => 'join', + _ => '', + }; + return parseBuzzDeepLink( + Uri(scheme: 'buzz', host: host, queryParameters: fields), + ); +} diff --git a/mobile/lib/shared/hosted/organization_sign_out.dart b/mobile/lib/shared/hosted/organization_sign_out.dart deleted file mode 100644 index 431647c4df..0000000000 --- a/mobile/lib/shared/hosted/organization_sign_out.dart +++ /dev/null @@ -1,50 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:hooks_riverpod/hooks_riverpod.dart'; - -import '../community/community_provider.dart'; -import 'account_identity_store.dart'; -import '../widgets/confirmation_dialog.dart'; -import '../widgets/feedback_snackbar.dart'; - -/// Signs an internal build out of its organization. Removing the -/// organization's community returns to the Sign in landing, which ends the -/// organization session; it is the only way an internal build signs out. -/// -/// The community's key stays on this device as a saved identity, so signing -/// back in reuses it even when the organization holds no backup of it. -Future confirmOrganizationSignOut( - BuildContext context, - WidgetRef ref, -) async { - final messenger = ScaffoldMessenger.of(context); - final navigator = Navigator.of(context); - try { - final community = await ref.read(activeCommunityProvider.future); - if (community == null || !context.mounted) return; - final confirmed = await showDestructiveConfirmation( - context: context, - title: 'Sign out?', - message: 'You’ll need to sign in again to use Buzz on this device.', - confirmLabel: 'Sign out', - ); - if (!confirmed || !context.mounted) return; - final nsec = community.nsec; - if (nsec != null && nsec.isNotEmpty) { - // A failure here keeps the community rather than delete the only copy - // of its key. - await AccountIdentityStore() - .forPairing(AccountIdentityStore.publicKeyForNsec(nsec)) - .create(nsec); - } - await ref - .read(communityListProvider.notifier) - .removeCommunity(community.id); - // Reveal the Sign in landing under the page that signed out. - navigator.popUntil((route) => route.isFirst); - } catch (e) { - messenger.showFeedbackSnackBar( - SnackBar(content: Text('Failed to sign out: $e')), - kind: ToastKind.error, - ); - } -} diff --git a/mobile/lib/shared/hosted/sign_out.dart b/mobile/lib/shared/hosted/sign_out.dart new file mode 100644 index 0000000000..88c79c6e5f --- /dev/null +++ b/mobile/lib/shared/hosted/sign_out.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../community/community.dart'; +import '../community/community_provider.dart'; +import 'account_identity_store.dart'; +import 'hosted_environment.dart'; +import 'hosted_flow_provider.dart'; +import '../widgets/confirmation_dialog.dart'; +import '../widgets/feedback_snackbar.dart'; + +/// Signs this device out: removes every community, and in a public build ends +/// the Builderlab session. Each community's key goes to this device's saved +/// identities first, so signing out never destroys a key that may exist +/// nowhere else; signing back in offers it again. In an internal build the +/// Sign in landing that follows ends the organization session. +Future confirmSignOut(BuildContext context, WidgetRef ref) async { + final messenger = ScaffoldMessenger.of(context); + final navigator = Navigator.of(context); + final list = ref.read(communityListProvider.notifier); + final flow = HostedEnvironment.enabled ? ref.read(hostedFlowProvider) : null; + try { + final communities = await ref.read(communityListProvider.future); + final active = await ref.read(activeCommunityProvider.future); + if (communities.isEmpty || !context.mounted) return; + final confirmed = await showDestructiveConfirmation( + context: context, + title: 'Sign out?', + message: + 'You’ll need to sign in again to use Buzz on this device. ' + 'Your identities stay saved on this device.', + confirmLabel: 'Sign out', + ); + if (!confirmed || !context.mounted) return; + // Every key is saved before any community is removed, so a failure + // leaves each community with its only copy of its key. + for (final community in communities) { + await keepCommunityKey(community); + } + // The session ends before any community is removed, so the Sign in + // landing never shows it and nothing started there can be cancelled by + // it. Removed communities' push-lease revocations authenticate with the + // push-stop credential it leaves behind. + await flow?.endAccountSession(); + // The active community goes last, so removing the others never switches + // to and connects another one. + for (final community in [ + ...communities.where((c) => c.id != active?.id), + ...communities.where((c) => c.id == active?.id), + ]) { + await list.removeCommunity(community.id); + } + // Reveal the Sign in landing under the page that signed out. + navigator.popUntil((route) => route.isFirst); + } catch (e) { + messenger.showFeedbackSnackBar( + SnackBar(content: Text('Failed to sign out: $e')), + kind: ToastKind.error, + ); + } +} + +/// Copies [community]'s key into this device's saved identities, where +/// signing in again offers it. A failure throws, so the caller keeps the +/// community rather than delete the only copy of its key. +Future keepCommunityKey(Community community) async { + final nsec = community.nsec; + if (nsec == null || nsec.isEmpty) return; + await AccountIdentityStore() + .forPairing(AccountIdentityStore.publicKeyForNsec(nsec)) + .create(nsec); +} diff --git a/mobile/test/features/settings/settings_page_loading_test.dart b/mobile/test/features/settings/settings_page_loading_test.dart index 4e0c6ac204..f591ffba07 100644 --- a/mobile/test/features/settings/settings_page_loading_test.dart +++ b/mobile/test/features/settings/settings_page_loading_test.dart @@ -62,6 +62,12 @@ void main() { 'buildSignature': '', }); await tester.pumpAndSettle(); + // At large text the footer starts below the fold. + await tester.scrollUntilVisible( + find.text('v0.16.0 (432)'), + 200, + scrollable: find.byType(Scrollable).first, + ); expect(find.text('v0.16.0 (432)'), findsOneWidget); expect(tester.takeException(), isNull); }); diff --git a/mobile/test/features/settings/settings_sign_out_test.dart b/mobile/test/features/settings/settings_sign_out_test.dart new file mode 100644 index 0000000000..81f001a2f2 --- /dev/null +++ b/mobile/test/features/settings/settings_sign_out_test.dart @@ -0,0 +1,290 @@ +import 'dart:async'; + +import 'package:buzz/features/settings/settings_page.dart'; +import 'package:buzz/hosted_app_gate.dart'; +import 'package:buzz/onboarding_app_entry.dart'; +import 'package:buzz/shared/auth/auth.dart'; +import 'package:buzz/shared/hosted/account_identity_store.dart'; +import 'package:buzz/shared/hosted/hosted_environment.dart'; +import 'package:buzz/shared/hosted/hosted_flow_provider.dart'; +import 'package:buzz/shared/relay/relay_session.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../helpers/hosted_communities_fixture.dart'; + +/// Runs in every build. A public build also signs out of Builderlab: +/// `--dart-define=BUZZ_DISTRIBUTION=public` +/// `--dart-define=BUZZ_BUILDERLAB_URL=https://app.builderlab.xyz` +/// `--dart-define=BUZZ_BUILDERLAB_RELAYS=communities.buzz.xyz` +void main() { + testWidgets( + 'Sign out removes every community but keeps each key on this device', + (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(390, 1600); + addTearDown(tester.view.reset); + FlutterSecureStorage.setMockInitialValues({}); + SharedPreferences.setMockInitialValues({}); + PackageInfo.setMockInitialValues( + appName: 'Buzz', + packageName: 'xyz.block.buzz', + version: '0.16.0', + buildNumber: '1', + buildSignature: '', + ); + final prefs = await SharedPreferences.getInstance(); + // Neither key is exported or backed up anywhere. + final activeKeys = nostr.Keys.generate(); + final otherKeys = nostr.Keys.generate(); + final active = Community.create( + name: 'Active', + relayUrl: 'wss://active.example.org', + nsec: activeKeys.nsec, + ); + final other = Community.create( + name: 'Other', + relayUrl: 'wss://other.example.org', + nsec: otherKeys.nsec, + ); + final storage = CommunityStorage(); + await storage.save(active); + await storage.save(other); + await storage.saveActiveId(active.id); + + HostedCommunitiesFixture? hosted; + final accountStorage = _AccountStorage(); + if (HostedEnvironment.enabled) { + hosted = HostedCommunitiesFixture(); + // A later launch whose session restore hasn't succeeded yet: the + // session is saved but not in memory. + await hosted.initialize( + accountStorage: accountStorage, + coldAccount: true, + ); + addTearDown(hosted.dispose); + await hosted.flow.leave(); + hosted.unavailable = true; + await expectLater(hosted.account.restore(), throwsA(anything)); + expect(hosted.account.account, isNull); + } + // Hosted setup must never cover Settings while it signs out. + final pushes = _Pushes(); + // The Builderlab session must be gone before the Sign in landing can + // show it or be interrupted by its end. + final sessionAtRemoval = []; + final removed = []; + // Revocations stay in flight until the landing has been checked. + final revocations = Completer(); + addTearDown(() { + if (!revocations.isCompleted) revocations.complete(); + }); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + communityStorageProvider.overrideWithValue(storage), + communitySnapshotWriterProvider.overrideWithValue((_) async {}), + communityPushLeaseRevocationEnqueuerProvider.overrideWithValue(( + community, + ) async { + removed.add(community.id); + sessionAtRemoval.add(hosted?.account.account != null); + return true; + }), + communityPushLeaseRevocationTriggerProvider.overrideWithValue( + () => revocations.future, + ), + relaySessionProvider.overrideWith(_OfflineSession.new), + if (hosted != null) + hostedFlowProvider.overrideWithValue(hosted.flow), + ], + child: MaterialApp( + theme: AppTheme.light(), + navigatorObservers: [pushes], + home: const _Root(), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open Settings')); + await tester.pumpAndSettle(); + + // Cancelling keeps everything. + await tester.tap(find.byKey(const Key('settings-sign-out'))); + await tester.pumpAndSettle(); + expect(find.text('Sign out?'), findsOneWidget); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(await storage.loadAll(), hasLength(2)); + + Future confirmSignOut() async { + await tester.tap(find.byKey(const Key('settings-sign-out'))); + await tester.pumpAndSettle(); + pushes.count = 0; + await tester.tap(find.widgetWithText(FilledButton, 'Sign out')); + } + + // Each failure keeps every community and shows its error in Settings. + Future signOutFails() async { + await confirmSignOut(); + await tester.pumpAndSettle(); + expect(pushes.count, 0); + expect(find.byType(SettingsPage), findsOneWidget); + expect(find.textContaining('Failed to sign out'), findsOneWidget); + expect(await storage.loadAll(), hasLength(2)); + expect(removed, isEmpty); + ScaffoldMessenger.of( + tester.element(find.byKey(const Key('settings-sign-out'))), + ).removeCurrentSnackBar(); + await tester.pumpAndSettle(); + } + + if (hosted != null) { + // The saved session can't be deleted, though it isn't restored yet. + accountStorage.failing = true; + await signOutFails(); + hosted.unavailable = false; + expect(await hosted.account.restore(), isNotNull); + // Nor once it is. + await signOutFails(); + expect(hosted.account.account, isNotNull); + accountStorage.failing = false; + // A pending browser sign-in can't be forgotten. + hosted.browser.clearIntentError = PlatformException(code: 'keychain'); + await signOutFails(); + expect(hosted.account.account, isNotNull); + hosted.browser.clearIntentError = null; + } + + // A session check still pending must not hold up signing out, nor + // restore the session when it finishes afterwards. + final heldCheck = Completer(); + Future? pendingRestore; + if (hosted != null) { + hosted.beforeMe = () => heldCheck.future; + pendingRestore = hosted.account.restore().then( + (restored) => restored, + onError: (Object error) => error, + ); + await tester.pump(); + } + addTearDown(() { + if (!heldCheck.isCompleted) heldCheck.complete(); + }); + + await confirmSignOut(); + // The landing animates, so it never settles. + await _pumpFor(tester); + + expect(pushes.count, 0); + expect(await storage.loadAll(), isEmpty); + expect(find.byType(SettingsPage), findsNothing); + expect(find.byType(OnboardingAppEntry), findsOneWidget); + expect(find.textContaining('Signed in as'), findsNothing); + // The active community goes last, so nothing switches to the other. + expect(removed, [other.id, active.id]); + final saved = await AccountIdentityStore().identities(); + expect( + saved.map((identity) => identity.pubkey), + containsAll([activeKeys.public, otherKeys.public]), + ); + if (hosted != null) { + expect(sessionAtRemoval, everyElement(isFalse)); + expect(hosted.account.account, isNull); + heldCheck.complete(); + expect(await pendingRestore, isNull); + expect(hosted.account.account, isNull); + expect(await hosted.account.restore(), isNull); + } + // Revocations finishing later change nothing on the landing. + revocations.complete(); + await _pumpFor(tester); + expect(find.byType(OnboardingAppEntry), findsOneWidget); + expect(find.textContaining('Signed in as'), findsNothing); + expect(hosted?.account.account, isNull); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await _pumpFor(tester); + }, + ); +} + +Future _pumpFor(WidgetTester tester) async { + for (var i = 0; i < 20; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +/// Fails to delete the Builderlab session while [failing], as an unavailable +/// Keychain would. +class _AccountStorage extends FlutterSecureStorage { + bool failing = false; + + @override + Future delete({ + required String key, + AppleOptions? iOptions, + AndroidOptions? aOptions, + LinuxOptions? lOptions, + WebOptions? webOptions, + AppleOptions? mOptions, + WindowsOptions? wOptions, + }) { + if (failing && key.startsWith('buzz_hosted_session_')) { + throw PlatformException(code: 'keychain', message: 'unavailable'); + } + return super.delete(key: key); + } +} + +/// Swaps in the Sign in landing once the device is signed out, as the app does. +class _Root extends ConsumerWidget { + const _Root(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final status = ref.watch(authProvider).value?.status; + if (status == null) return const SizedBox.shrink(); + if (status != AuthStatus.authenticated) return const OnboardingAppEntry(); + return HostedAppGate( + authenticated: true, + child: Scaffold( + body: TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SettingsPage( + profileHeader: const SizedBox.shrink(), + identityRecoveryPageBuilder: (_) => const SizedBox.shrink(), + ), + ), + ), + child: const Text('Open Settings'), + ), + ), + ); + } +} + +/// The relay boundary: nothing connects. +class _OfflineSession extends RelaySessionNotifier { + @override + SessionState build() => + const SessionState(status: SessionStatus.disconnected); +} + +/// Counts routes pushed since [count] was last reset. +class _Pushes extends NavigatorObserver { + int count = 0; + + @override + void didPush(Route route, Route? previousRoute) => count++; +} diff --git a/mobile/test/helpers/hosted_communities_fixture.dart b/mobile/test/helpers/hosted_communities_fixture.dart index f74d143c83..159d0e8731 100644 --- a/mobile/test/helpers/hosted_communities_fixture.dart +++ b/mobile/test/helpers/hosted_communities_fixture.dart @@ -7,6 +7,7 @@ import 'package:buzz/shared/hosted/browser_auth.dart'; import 'package:buzz/shared/hosted/builderlab_account.dart'; import 'package:buzz/shared/hosted/hosted_flow.dart'; import 'package:buzz/shared/hosted/hosted_identity_service.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:nostr/nostr.dart' as nostr; @@ -29,8 +30,14 @@ class DiscoveryBrowser extends BrowserAuth { @override Future initialize() async {} + + /// Thrown by [clearIntent] while set, as unavailable storage would. + Object? clearIntentError; @override - Future clearIntent() async {} + Future clearIntent() async { + if (clearIntentError case final error?) throw error; + } + @override Future cancel() async {} } @@ -92,72 +99,91 @@ class HostedCommunitiesFixture { bool rejectList = false; bool rejectCurrent = false; bool expired = false; + bool unavailable = false; String subject = 'owner'; Future Function(String)? beforeAdmission; Future Function()? beforeList; + Future Function()? beforeMe; Uri? opened; Map row(String name) => { 'community_url': 'wss://$name.communities.buzz.xyz', }; - Future initialize({bool backup = true, bool widget = false}) async { + Future initialize({ + bool backup = true, + bool widget = false, + FlutterSecureStorage? accountStorage, + bool coldAccount = false, + }) async { bound = keys.public; final expiry = DateTime.now() .toUtc() .add(const Duration(hours: 1)) .toIso8601String(); + final client = MockClient((request) async { + final path = request.url.path; + requests.add(path); + if (path.endsWith('/exchange')) { + return http.Response( + jsonEncode({'session_credential': 'fixture', 'expires_at': expiry}), + 200, + ); + } + if (path.endsWith('/me')) { + await beforeMe?.call(); + if (expired) return http.Response('{}', 401); + if (unavailable) return http.Response('{}', 503); + return http.Response( + jsonEncode({ + 'subject': subject, + 'email': 'owner@example.com', + 'expires_at': expiry, + }), + 200, + ); + } + if (path.endsWith('/current')) { + return http.Response( + jsonEncode({ + 'identity': {'pubkey_hex': bound}, + }), + 200, + ); + } + if (path.endsWith('/known-communities/list')) { + await beforeList?.call(); + if (rejectList) return http.Response('{}', 503); + return http.Response(jsonEncode({'communities': rows}), 200); + } + if (path.endsWith('/known-communities/add')) { + final body = jsonDecode(request.body) as Map; + return http.Response( + jsonEncode({ + 'community': {'community_url': body['community_url']}, + }), + 200, + ); + } + return http.Response('{}', 503); + }); account = BuilderlabAccountClient( - httpClient: MockClient((request) async { - final path = request.url.path; - requests.add(path); - if (path.endsWith('/exchange')) { - return http.Response( - jsonEncode({'session_credential': 'fixture', 'expires_at': expiry}), - 200, - ); - } - if (path.endsWith('/me')) { - if (expired) return http.Response('{}', 401); - return http.Response( - jsonEncode({ - 'subject': subject, - 'email': 'owner@example.com', - 'expires_at': expiry, - }), - 200, - ); - } - if (path.endsWith('/current')) { - return http.Response( - jsonEncode({ - 'identity': {'pubkey_hex': bound}, - }), - 200, - ); - } - if (path.endsWith('/known-communities/list')) { - await beforeList?.call(); - if (rejectList) return http.Response('{}', 503); - return http.Response(jsonEncode({'communities': rows}), 200); - } - if (path.endsWith('/known-communities/add')) { - final body = jsonDecode(request.body) as Map; - return http.Response( - jsonEncode({ - 'community': {'community_url': body['community_url']}, - }), - 200, - ); - } - return http.Response('{}', 503); - }), + storage: accountStorage, + httpClient: client, ); if (widget) { account.dispose(); account = WidgetDiscoveryAccount(this); } else { await account.exchange(code: 'code', verifier: 'a' * 43); + if (coldAccount) { + // A later process: the session is saved but not restored yet. + account.dispose(); + account = BuilderlabAccountClient( + storage: accountStorage, + httpClient: client, + ); + } } await store.create(keys.nsec); if (backup) { diff --git a/mobile/test/shared/hosted/builderlab_account_test.dart b/mobile/test/shared/hosted/builderlab_account_test.dart index d2e4321c7f..c5d356a731 100644 --- a/mobile/test/shared/hosted/builderlab_account_test.dart +++ b/mobile/test/shared/hosted/builderlab_account_test.dart @@ -5,6 +5,7 @@ import 'hosted_http_fixture.dart'; import 'dart:convert'; import 'package:buzz/shared/hosted/builderlab_account.dart'; +import 'package:buzz/shared/storage/serial_queue.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; @@ -185,7 +186,8 @@ void main() { onError: (Object error) => failure = error, ), ); - unawaited(client.clearLocalSession().then((_) => cleared = true)); + // Any queued account request waits for the deadline. + unawaited(client.restore().then((_) => cleared = true)); await tester.pump(); await tester.pump(const Duration(seconds: 20)); await tester.pump(const Duration(seconds: 5)); @@ -309,6 +311,141 @@ void main() { expect(verifications, 2); }); + test('a sign-out is never undone by a pending session check', () async { + FlutterSecureStorage.setMockInitialValues({ + storageKey: record('account-1', 'old'), + }); + final storage = _SessionStorage(); + var check = Completer(); + final client = BuilderlabAccountClient( + storage: storage, + httpClient: MockClient((request) async { + await check.future; + return http.Response( + jsonEncode({'subject': 'account-1', 'expires_at': expiry}), + 200, + ); + }), + ); + // A check already pending when sign-out starts doesn't hold it up. + final early = client.restore(); + await pumpEventQueue(); + await client.clearLocalSession(); + check.complete(); + expect(await early, isNull); + expect(client.account, isNull); + + // Nor does a check that starts while the session is being deleted. + FlutterSecureStorage.setMockInitialValues({ + storageKey: record('account-1', 'old'), + }); + check = Completer(); + final deleted = Completer(); + storage.holdDelete = deleted.future; + final clearing = client.clearLocalSession(); + final late = client.restore(); + await pumpEventQueue(); + deleted.complete(); + await clearing; + check.complete(); + expect(await late, isNull); + expect(client.account, isNull); + expect(await stored(), isNull); + }); + + test('an exchange queued before a sign-out cannot sign back in', () async { + FlutterSecureStorage.setMockInitialValues({ + storageKey: record('account-1', 'old'), + }); + final entered = Completer(); + final release = Completer(); + final client = BuilderlabAccountClient( + httpClient: MockClient((request) async { + if (request.url.path.endsWith('/exchange')) { + return http.Response( + jsonEncode({'session_credential': 'new', 'expires_at': expiry}), + 200, + ); + } + if (request.headers['X-BB-Session-Credential'] == 'old') { + if (!entered.isCompleted) entered.complete(); + await release.future; + } + return http.Response( + jsonEncode({'subject': 'account-1', 'expires_at': expiry}), + 200, + ); + }), + ); + addTearDown(() { + if (!release.isCompleted) release.complete(); + client.dispose(); + }); + final restoring = client.restore(); + await entered.future; + final exchanging = client + .exchange(code: 'code', verifier: verifier) + .then((value) => value, onError: (Object error) => error); + await client.clearLocalSession(); + release.complete(); + await restoring; + expect(await exchanging, AccountFailure.unavailable); + expect(client.account, isNull); + expect(await stored(), isNull); + }); + + test('signing out leaves the extension without the session', () async { + FlutterSecureStorage.setMockInitialValues({ + storageKey: record('account-1', 'old'), + }); + // Extension writes land in call order, as the iOS bridge does. + final writes = SerialQueue(); + var shareFails = true; + String? shared = 'old'; + final unshareStarted = Completer(); + final releaseUnshare = Completer(); + final client = BuilderlabAccountClient( + httpClient: MockClient( + (request) async => http.Response( + jsonEncode({'subject': 'account-1', 'expires_at': expiry}), + 200, + ), + ), + onSessionChanged: (credential) => writes.run(() async { + if (credential == null) { + if (!unshareStarted.isCompleted) unshareStarted.complete(); + await releaseUnshare.future; + } else if (shareFails) { + throw StateError('keychain unavailable'); + } + shared = credential; + }), + ); + addTearDown(() { + if (!releaseUnshare.isCompleted) releaseUnshare.complete(); + client.dispose(); + }); + // The first share fails, so the credential waits to be shared again. + await client.restore(); + await pumpEventQueue(); + shareFails = false; + final clearing = client.clearLocalSession(); + await unshareStarted.future; + // An account request arriving mid-removal must not share it again. + final request = client.currentIdentity().then( + (value) => value, + onError: (Object error) => error, + ); + await pumpEventQueue(); + releaseUnshare.complete(); + await clearing; + await request; + await writes.run(() async {}); + expect(client.account, isNull); + expect(await stored(), isNull); + expect(shared, isNull); + }); + test('login for another account keeps the existing session', () async { FlutterSecureStorage.setMockInitialValues({ storageKey: record('account-1', 'old'), @@ -459,6 +596,7 @@ void main() { class _SessionStorage extends FlutterSecureStorage { bool failDelete = false; + Future? holdDelete; @override Future delete({ @@ -471,6 +609,7 @@ class _SessionStorage extends FlutterSecureStorage { WindowsOptions? wOptions, }) async { if (failDelete) throw StateError('storage unavailable'); + await holdDelete; await super.delete(key: key); } } diff --git a/mobile/test/shared/hosted/organization_relay_auth_test.dart b/mobile/test/shared/hosted/organization_relay_auth_test.dart index 178288eec0..8e0232d4d7 100644 --- a/mobile/test/shared/hosted/organization_relay_auth_test.dart +++ b/mobile/test/shared/hosted/organization_relay_auth_test.dart @@ -47,8 +47,11 @@ void main() { late int assertionLifetime; late String Function(String relayUrl) tokenFor; - BuilderlabAccountClient organizationClient() => BuilderlabAccountClient( + BuilderlabAccountClient organizationClient({ + Future Function(String?)? onSessionChanged, + }) => BuilderlabAccountClient( accountOrigin: organization, + onSessionChanged: onSessionChanged, httpClient: MockClient((request) async { requests.add(request); expect(request.url.origin, organization.origin); @@ -390,6 +393,37 @@ void main() { ); }); + test('a push stop still gets an assertion after signing out a saved ' + 'session that was never restored, across a failed cleanup', () async { + // An offline launch keeps the saved session without adopting it. + await saveSession(); + // The first cleanup deletes the record, then fails to unshare. + var unshareFails = true; + final account = organizationClient( + onSessionChanged: (_) async { + if (unshareFails) throw StateError('unshare failed'); + }, + ); + final auth = relayAuth(account); + boundIdentity = {'pubkey_hex': keys.public}; + + await expectLater( + account.clearLocalSession(), + throwsA(AccountFailure.storage), + ); + unshareFails = false; + await account.clearLocalSession(); + expect(await account.restore(), isNull); + requests.clear(); + tokenFor = (_) => 'push-stop-token'; + expect(await auth.headers(relay, background: true), { + 'Nostr-Federated-Identity': 'Bearer push-stop-token', + }); + expect(requests.last.headers['X-BB-Session-Credential'], 'org-secret'); + expect(await auth.headers(relay), isEmpty); + expect(account.account, isNull); + }); + test('other relays never receive the organization assertion', () async { await saveSession(); final auth = relayAuth(organizationClient());