Files
buzz/mobile/test/features/settings/settings_sign_out_test.dart
Tom Brow 5b92e02e2a fix(mobile): sign out from Settings in every build, keeping keys on the device (#9421)
Public and Nostr-only builds had no way to sign out. The only route was
Switch community → Edit, remove every community, then tap Back to get a
"Sign out of BuilderLab?" prompt. Removing a community that way also
deletes its key from the phone, even when the user never exported or
backed it up.

Settings now ends with **Sign out** in every build (internal builds
already had it). After confirming:

- Each community's key is first copied into this device's saved
identities, the same thing internal Sign out already did. Sign-in offers
them again, so signing out never destroys a key that may exist nowhere
else. If saving fails, nothing is removed.
- In a public build, the Builderlab session ends next, before anything
is removed. The Sign in landing that follows never shows the old
session, and nothing started there can be cancelled by it. If the
session or a pending browser sign-in can't be cleared, including a saved
session not yet restored after launch, Sign out stops with an error and
keeps every community. Ending the session never waits behind a pending
account request, such as a stalled session check at launch, and no such
request can restore the session once it finishes later. This path never
shows the hosted setup page over Settings. The removed communities'
push-lease tombstones still publish afterwards: the outbox authenticates
them with the push-stop credential the session leaves behind for 10
minutes, including a saved session that was never restored (an offline
launch), even when a first cleanup attempt failed partway.
- Every community is removed, the active one last, so removing the
others never switches to (and connects) another community on the way
out.
- A Sign out failure now shows its error in Settings. The row used
Settings' outer context, so the snackbar went to the page underneath.

Nothing else changes: the switcher, per-community Remove and the
onboarding landing's Back → "Sign out of BuilderLab?" path behave as
before. Internal Sign out keeps its behavior (one community, key kept,
the landing then ends the organization session). The only new UI is one
row at the bottom of Settings.

| Before | After |
| --- | --- |
| <img width="300" alt="before"
src="https://github.com/user-attachments/assets/f49f7869-3401-4e05-aa7b-debe7a7d425c">
| <img width="300" alt="after"
src="https://github.com/user-attachments/assets/99731c6a-035e-447b-987a-7fa0d8e767cc">
|

Demo (public build, simulator): Sign out → confirm → back at the Buzz
landing, signed out of Builderlab.


https://github.com/user-attachments/assets/da64082b-3b73-46d0-8578-771fca7dec22

### Validation

- Added tests: `settings_sign_out_test.dart`, a Settings journey with
two communities whose keys aren't backed up. Cancelling keeps
everything. Confirming removes both (active last) and both keys end up
in saved identities. The root swaps Settings for the real
`OnboardingAppEntry` as the app does. The authenticated root is wrapped
in the real `HostedAppGate`, and no route may be pushed while Sign out
runs. In a public build it fails three ways, each showing the error in
Settings and removing nothing: a saved session that isn't restored yet
can't be deleted, a restored one can't be deleted, and a pending browser
sign-in can't be cleared. Then, with revocations held pending, the
landing appears with the session already gone and no "Signed in as", and
releasing the revocations changes nothing. It runs in the default lane
and in the CI public-build lane (added to `_ci-clients.yml`). Confirmed
it fails when the key save is removed, when the session ends after the
landing appears, when sign-out goes through the flow's published stages,
when a failed clear is detected only by a missing in-memory session,
when a browser cleanup failure is swallowed, and when the error goes to
the page underneath.
- `organization_relay_auth_test.dart`: a push stop still gets an
assertion after signing out a saved session that was never restored,
including a failed cleanup followed by a successful retry (fails without
the fix).
- Sign-out never waits on a pending account request: the Settings
journey holds `/v1/auth/me` during the final sign-out and checks that
its later completion restores nothing (without the fix, Sign out stalls
and both communities stay). `builderlab_account_test.dart` covers a
session check already pending, one that starts while the session is
being deleted, an exchange queued before the sign-out, and an account
request during the removal that must not share the credential with the
notification extension again.
- Focused existing validation: `internal_build_entry_test.dart` with the
internal-build defines passes.
- Full `just mobile-test` (4,848 passed, 74 skipped) and `just
mobile-check` are clean.
- Automated app run at
([d36150c](d36150ccaf)):
fresh iPhone 17 Pro simulator, public-build Debug signed in to a
Builderlab community. Opened Settings from the community menu (Sign out
is the last row), confirmed Sign out, and landed on the Buzz landing
(Scan a QR code / sign in with email) with no community and no
Builderlab session, and no hosted setup page in between. The screens
match the demo above, which was recorded at an earlier head. Re-signing
in through Builderlab wasn't exercised in the simulator; the journey
test covers the saved identities that sign-in offers. Later commits
change only session-clearing internals, and the tests above cover them.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-15 19:31:04 +00:00

291 lines
10 KiB
Dart

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 = <bool>[];
final removed = <String>[];
// Revocations stay in flight until the landing has been checked.
final revocations = Completer<void>();
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<void> 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<void> 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<void>();
Future<Object?>? pendingRestore;
if (hosted != null) {
hosted.beforeMe = () => heldCheck.future;
pendingRestore = hosted.account.restore().then<Object?>(
(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<void> _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<void> 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<void>(
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<dynamic> route, Route<dynamic>? previousRoute) => count++;
}