Skip to content

Commit

Permalink
store: Handle invalid API key on register-queue
Browse files Browse the repository at this point in the history
The method loadPerAccount has two call sites, i.e. places
where we send register-queue requests:

1. _reloadPerAccount through [UpdateMachine._handlePollError]
   (e.g.: expired event queue)
2. perAccount through [PerAccountStoreWidget]
   (e.g.: loading for the first time)

Both sites already expect [AccountNotFoundException] by assuming that
the `loadPerAccount` fail is irrecoverable and is handled elsewhere.

This partly addresses zulip#890 by handling authentication errors for
register-queue.

Fixes: zulip#737

Signed-off-by: Zixuan James Li <[email protected]>
  • Loading branch information
PIG208 committed Feb 18, 2025
1 parent 9be7c76 commit 554aac6
Show file tree
Hide file tree
Showing 13 changed files with 205 additions and 7 deletions.
7 changes: 7 additions & 0 deletions assets/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,13 @@
"@topicValidationErrorMandatoryButEmpty": {
"description": "Topic validation error when topic is required but was empty."
},
"errorInvalidApiKeyMessage": "Your account at {url} could not be authenticated. Please try logging in again or use another account.",
"@errorInvalidApiKeyMessage": {
"description": "Error message in the dialog for invalid API key.",
"placeholders": {
"url": {"type": "String", "example": "http://chat.example.com/"}
}
},
"errorInvalidResponse": "The server sent an invalid response",
"@errorInvalidResponse": {
"description": "Error message when an API call returned an invalid response."
Expand Down
6 changes: 6 additions & 0 deletions lib/generated/l10n/zulip_localizations.dart
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,12 @@ abstract class ZulipLocalizations {
/// **'Topics are required in this organization.'**
String get topicValidationErrorMandatoryButEmpty;

/// Error message in the dialog for invalid API key.
///
/// In en, this message translates to:
/// **'Your account at {url} could not be authenticated. Please try logging in again or use another account.'**
String errorInvalidApiKeyMessage(String url);

/// Error message when an API call returned an invalid response.
///
/// In en, this message translates to:
Expand Down
5 changes: 5 additions & 0 deletions lib/generated/l10n/zulip_localizations_ar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ class ZulipLocalizationsAr extends ZulipLocalizations {
@override
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';

@override
String errorInvalidApiKeyMessage(String url) {
return 'Your account at $url could not be authenticated. Please try logging in again or use another account.';
}

@override
String get errorInvalidResponse => 'The server sent an invalid response';

Expand Down
5 changes: 5 additions & 0 deletions lib/generated/l10n/zulip_localizations_en.dart
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ class ZulipLocalizationsEn extends ZulipLocalizations {
@override
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';

@override
String errorInvalidApiKeyMessage(String url) {
return 'Your account at $url could not be authenticated. Please try logging in again or use another account.';
}

@override
String get errorInvalidResponse => 'The server sent an invalid response';

Expand Down
5 changes: 5 additions & 0 deletions lib/generated/l10n/zulip_localizations_ja.dart
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ class ZulipLocalizationsJa extends ZulipLocalizations {
@override
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';

@override
String errorInvalidApiKeyMessage(String url) {
return 'Your account at $url could not be authenticated. Please try logging in again or use another account.';
}

@override
String get errorInvalidResponse => 'The server sent an invalid response';

Expand Down
5 changes: 5 additions & 0 deletions lib/generated/l10n/zulip_localizations_nb.dart
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ class ZulipLocalizationsNb extends ZulipLocalizations {
@override
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';

@override
String errorInvalidApiKeyMessage(String url) {
return 'Your account at $url could not be authenticated. Please try logging in again or use another account.';
}

@override
String get errorInvalidResponse => 'The server sent an invalid response';

Expand Down
5 changes: 5 additions & 0 deletions lib/generated/l10n/zulip_localizations_pl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ class ZulipLocalizationsPl extends ZulipLocalizations {
@override
String get topicValidationErrorMandatoryButEmpty => 'Wątki są wymagane przez tę organizację.';

@override
String errorInvalidApiKeyMessage(String url) {
return 'Your account at $url could not be authenticated. Please try logging in again or use another account.';
}

@override
String get errorInvalidResponse => 'Nieprawidłowa odpowiedź serwera';

Expand Down
5 changes: 5 additions & 0 deletions lib/generated/l10n/zulip_localizations_ru.dart
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ class ZulipLocalizationsRu extends ZulipLocalizations {
@override
String get topicValidationErrorMandatoryButEmpty => 'Темы обязательны в этой организации.';

@override
String errorInvalidApiKeyMessage(String url) {
return 'Your account at $url could not be authenticated. Please try logging in again or use another account.';
}

@override
String get errorInvalidResponse => 'Получен недопустимый ответ сервера';

Expand Down
5 changes: 5 additions & 0 deletions lib/generated/l10n/zulip_localizations_sk.dart
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ class ZulipLocalizationsSk extends ZulipLocalizations {
@override
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';

@override
String errorInvalidApiKeyMessage(String url) {
return 'Your account at $url could not be authenticated. Please try logging in again or use another account.';
}

@override
String get errorInvalidResponse => 'Server poslal nesprávnu odpoveď';

Expand Down
47 changes: 41 additions & 6 deletions lib/model/store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import '../api/backoff.dart';
import '../api/route/realm.dart';
import '../log.dart';
import '../notifications/receive.dart';
import 'actions.dart';
import 'autocomplete.dart';
import 'database.dart';
import 'emoji.dart';
Expand Down Expand Up @@ -149,7 +150,34 @@ abstract class GlobalStore extends ChangeNotifier {
/// and/or [perAccountSync].
Future<PerAccountStore> loadPerAccount(int accountId) async {
assert(_accounts.containsKey(accountId));
final store = await doLoadPerAccount(accountId);
final PerAccountStore store;
try {
store = await doLoadPerAccount(accountId);
} catch (e) {
switch (e) {
case HttpException(httpStatus: 401):
// The API key is invalid and the store can never be loaded
// unless the user retries manually.
final account = getAccount(accountId);
if (account == null) {
// The account was logged out during `await doLoadPerAccount`.
// Here, that seems possible only by the user's own action;
// the logout can't have been done programmatically.
// Even if it were, it would have come with its own UI feedback.
// Anyway, skip showing feedback, to not be confusing or repetitive.
throw AccountNotFoundException();
}
final zulipLocalizations = GlobalLocalizations.zulipLocalizations;
reportErrorToUserModally(
zulipLocalizations.errorCouldNotConnectTitle,
message: zulipLocalizations.errorInvalidApiKeyMessage(
account.realmUrl.toString()));
await logOutAccount(this, accountId);
throw AccountNotFoundException();
default:
rethrow;
}
}
if (!_accounts.containsKey(accountId)) {
// TODO(#1354): handle this earlier
// [removeAccount] was called during [doLoadPerAccount].
Expand Down Expand Up @@ -914,12 +942,19 @@ class UpdateMachine {
try {
return await registerQueue(connection);
} catch (e, s) {
assert(debugLog('Error fetching initial snapshot: $e'));
// Print stack trace in its own log entry; log entries are truncated
// at 1 kiB (at least on Android), and stack can be longer than that.
assert(debugLog('Stack:\n$s'));
assert(debugLog('Backing off, then will retry…'));
// TODO(#890): tell user if initial-fetch errors persist, or look non-transient
switch (e) {
case HttpException(httpStatus: 401):
// We cannot recover from this error through retrying.
// Leave it to [GlobalStore.loadPerAccount].
rethrow;
default:
assert(debugLog('Error fetching initial snapshot: $e'));
// Print stack trace in its own log entry; log entries are truncated
// at 1 kiB (at least on Android), and stack can be longer than that.
assert(debugLog('Stack:\n$s'));
}
assert(debugLog('Backing off, then will retry…'));
await (backoffMachine ??= BackoffMachine()).wait();
assert(debugLog('… Backoff wait complete, retrying initial fetch.'));
}
Expand Down
33 changes: 32 additions & 1 deletion test/model/store_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,29 @@ void main() {
check(completers(1)).length.equals(1);
});

test('GlobalStore.perAccount loading fails with HTTP status code 401', () => awaitFakeAsync((async) async {
final globalStore = LoadingTestGlobalStore(accounts: [eg.selfAccount]);
final future = globalStore.perAccount(eg.selfAccount.id);

globalStore.completers[eg.selfAccount.id]!
.single.completeError(eg.apiExceptionUnauthorized());
await check(future).throws<AccountNotFoundException>();
}));

test('GlobalStore.perAccount account is logged out while loading; then fails with HTTP status code 401', () => awaitFakeAsync((async) async {
final globalStore = LoadingTestGlobalStore(accounts: [eg.selfAccount]);
final future = globalStore.perAccount(eg.selfAccount.id);

await logOutAccount(globalStore, eg.selfAccount.id);
check(globalStore.takeDoRemoveAccountCalls())
.single.equals(eg.selfAccount.id);

globalStore.completers[eg.selfAccount.id]!
.single.completeError(eg.apiExceptionUnauthorized());
await check(future).throws<AccountNotFoundException>();
check(globalStore.takeDoRemoveAccountCalls()).isEmpty();
}));

// TODO test insertAccount

group('GlobalStore.updateAccount', () {
Expand Down Expand Up @@ -997,7 +1020,7 @@ void main() {
}

void checkReloadFailure({
required Future<void> Function() completeLoading,
required FutureOr<void> Function() completeLoading,
}) {
awaitFakeAsync((async) async {
await prepareReload(async);
Expand Down Expand Up @@ -1027,6 +1050,14 @@ void main() {
test('user logged out before new store is loaded', () => awaitFakeAsync((async) async {
checkReloadFailure(completeLoading: logOutAndCompleteWithNewStore);
}));

void completeWithApiExceptionUnauthorized() {
completers().single.completeError(eg.apiExceptionUnauthorized());
}

test('new store is not loaded, gets HTTP 401 error instead', () => awaitFakeAsync((async) async {
checkReloadFailure(completeLoading: completeWithApiExceptionUnauthorized);
}));
});

group('UpdateMachine.registerNotificationToken', () {
Expand Down
4 changes: 4 additions & 0 deletions test/model/test_store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ class TestGlobalStore extends GlobalStore {

static const Duration removeAccountDuration = Duration(milliseconds: 1);
Duration? loadPerAccountDuration;
Object? loadPerAccountException;

/// Consume the log of calls made to [doRemoveAccount].
List<int> takeDoRemoveAccountCalls() {
Expand All @@ -150,6 +151,9 @@ class TestGlobalStore extends GlobalStore {
if (loadPerAccountDuration != null) {
await Future<void>.delayed(loadPerAccountDuration!);
}
if (loadPerAccountException != null) {
throw loadPerAccountException!;
}
final initialSnapshot = _initialSnapshots[accountId]!;
final store = PerAccountStore.fromInitialSnapshot(
globalStore: this,
Expand Down
80 changes: 80 additions & 0 deletions test/widgets/app_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,18 @@ void main() {
group('_PreventEmptyStack', () {
late List<Route<void>> pushedRoutes;
late List<Route<void>> removedRoutes;
late List<Route<void>> poppedRoutes;

Future<void> prepare(WidgetTester tester) async {
addTearDown(testBinding.reset);

pushedRoutes = [];
removedRoutes = [];
poppedRoutes = [];
final testNavObserver = TestNavigatorObserver();
testNavObserver.onPushed = (route, prevRoute) => pushedRoutes.add(route);
testNavObserver.onRemoved = (route, prevRoute) => removedRoutes.add(route);
testNavObserver.onPopped = (route, prevRoute) => poppedRoutes.add(route);

await tester.pumpWidget(ZulipApp(navigatorObservers: [testNavObserver]));
await tester.pump(); // start to load account
Expand All @@ -91,6 +94,83 @@ void main() {
check(removedRoutes).single.isA<WidgetRoute>().page.isA<HomePage>();
check(pushedRoutes).single.isA<WidgetRoute>().page.isA<ChooseAccountPage>();
});

testWidgets('push route when popping last route on stack', (tester) async {
await testBinding.globalStore.insertAccount(eg.selfAccount.toCompanion(false));

testBinding.globalStore.loadPerAccountDuration = Duration.zero;
testBinding.globalStore.loadPerAccountException = eg.apiExceptionUnauthorized();
await prepare(tester);
// The navigator stack should contain only a home page route.

await tester.pump(Duration.zero); // got the error
await tester.pump(TestGlobalStore.removeAccountDuration);
// The navigator stack should contain only a dialog route.
// The home page route was removed because of account logout.
check(testBinding.globalStore.takeDoRemoveAccountCalls())
.single.equals(eg.selfAccount.id);
check(removedRoutes).single.isA<WidgetRoute>().page.isA<HomePage>();
check(poppedRoutes).isEmpty();
check(pushedRoutes).single.isA<DialogRoute<void>>();
pushedRoutes.clear();

await tester.tap(find.byWidget(checkErrorDialog(tester,
expectedTitle: 'Could not connect',
expectedMessage:
'Your account at ${eg.selfAccount.realmUrl} could not be authenticated.'
' Please try logging in again or use another account.')));
// The navigator stack should contain only a choose-account page route.
// After the error dialog is dismissed, it becomes empty,
// so a choose-account page route should be pushed.
check(poppedRoutes).single.isA<DialogRoute<void>>();
check(pushedRoutes).single.isA<WidgetRoute>().page.isA<ChooseAccountPage>();
});

testWidgets('do not push route to non-empty navigator stack', (tester) async {
await testBinding.globalStore.insertAccount(eg.selfAccount.toCompanion(false));

// Set up long enough loading time to later navigate to the choose-account
// page from the loading page via the "Try another account" button.
const loadPerAccountDuration = Duration(seconds: 30);
assert(loadPerAccountDuration > kTryAnotherAccountWaitPeriod);
testBinding.globalStore.loadPerAccountDuration = loadPerAccountDuration;
testBinding.globalStore.loadPerAccountException = eg.apiExceptionUnauthorized();
await prepare(tester);
// The navigator stack should contain only a home page route.

await tester.pump(kTryAnotherAccountWaitPeriod);
await tester.tap(find.text('Try another account'));
await tester.pump(); // tap the button
// The navigator stack should contain the home page route
// and a choose-account page route.
check(removedRoutes).isEmpty();
check(poppedRoutes).isEmpty();
check(pushedRoutes).single.isA<WidgetRoute>().page.isA<ChooseAccountPage>();
pushedRoutes.clear();

await tester.pump(loadPerAccountDuration); // got the error
await tester.pump(TestGlobalStore.removeAccountDuration);
// The navigator stack should contain the choose-account page route
// and a dialog route.
// The home page route was removed because of account logout.
check(testBinding.globalStore.takeDoRemoveAccountCalls())
.single.equals(eg.selfAccount.id);
check(removedRoutes).single.isA<WidgetRoute>().page.isA<HomePage>();
check(poppedRoutes).isEmpty();
check(pushedRoutes).single.isA<DialogRoute<void>>();
pushedRoutes.clear();

await tester.tap(find.byWidget(checkErrorDialog(tester,
expectedTitle: 'Could not connect',
expectedMessage:
'Your account at ${eg.selfAccount.realmUrl} could not be authenticated.'
' Please try logging in again or use another account.')));
// The navigator stack should contain only the choose-account page route.
// No routes should be pushed after dismissing the error dialog,
// because the navigator stack was non-empty.
check(poppedRoutes).single.isA<DialogRoute<void>>();
check(pushedRoutes).isEmpty();
});
});

group('ChooseAccountPage', () {
Expand Down

0 comments on commit 554aac6

Please sign in to comment.