diff --git a/lib/core/network/auth_notifier.dart b/lib/core/network/auth_notifier.dart index f6ade9af5..eb794ad78 100644 --- a/lib/core/network/auth_notifier.dart +++ b/lib/core/network/auth_notifier.dart @@ -49,6 +49,11 @@ import 'package:wger/features/trophies/providers/trophy_notifier.dart'; part 'auth_notifier.g.dart'; +/// Ceiling for the refresh POST. Callers are deduplicated onto one in-flight +/// refresh, so a request that never answers would block them all, PowerSync's +/// credential fetch included. +const tokenRefreshTimeout = Duration(seconds: 15); + @Riverpod(keepAlive: true) class AuthNotifier extends _$AuthNotifier { final _logger = Logger('AuthNotifier'); @@ -614,11 +619,13 @@ class AuthNotifier extends _$AuthNotifier { final appVersion = current.applicationVersion ?? await PackageInfo.fromPlatform(); final http.Response response; try { - response = await _api.postTokenRefresh( - refreshToken: refreshToken, - serverUrl: serverUrl, - appVersion: appVersion, - ); + response = await _api + .postTokenRefresh( + refreshToken: refreshToken, + serverUrl: serverUrl, + appVersion: appVersion, + ) + .timeout(tokenRefreshTimeout); } on Exception catch (e, s) { _logger.warning( 'refreshAccessToken: network error, keeping session so local data stays accessible', diff --git a/lib/powersync/connector.dart b/lib/powersync/connector.dart index cf70f1462..8363b813d 100644 --- a/lib/powersync/connector.dart +++ b/lib/powersync/connector.dart @@ -17,6 +17,7 @@ */ // This file performs setup of the PowerSync database +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -103,6 +104,11 @@ class DjangoConnector extends PowerSyncBackendConnector { /// Resets on app restart. final Set _reportedFailedOps = {}; + /// Ceiling for one token fetch. On token expiry the SDK awaits the fetch + /// inline in its sync loop, so a request that never answers would freeze + /// sync, disconnect() included, until the process restarts. + static const credentialFetchTimeout = Duration(seconds: 30); + /// Spacing between repeated "backend unreachable" log lines while the /// credential fetch keeps failing, so PowerSync's retry loop doesn't /// flood the app logs during a longer outage. @@ -140,7 +146,7 @@ class DjangoConnector extends PowerSyncBackendConnector { // https://docs.powersync.com/usage/installation/authentication-setup/custom final Map session; try { - session = await apiClient.getPowersyncToken(); + session = await apiClient.getPowersyncToken().timeout(credentialFetchTimeout); } on http.ClientException catch (e) { // Backend unreachable. Null would mean "not logged in" to the SDK and // surface as a CredentialsException; rethrowing keeps it a connection @@ -150,6 +156,9 @@ class DjangoConnector extends PowerSyncBackendConnector { } on SocketException catch (e) { _logUnreachable(e.message); rethrow; + } on TimeoutException { + _logUnreachable('token fetch timed out after ${credentialFetchTimeout.inSeconds}s'); + rethrow; } _logReachableAgain(); diff --git a/test/core/network/auth_notifier_powersync_test.dart b/test/core/network/auth_notifier_powersync_test.dart index e2ee8cf22..50a8c311c 100644 --- a/test/core/network/auth_notifier_powersync_test.dart +++ b/test/core/network/auth_notifier_powersync_test.dart @@ -21,6 +21,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart'; +import 'package:fake_async/fake_async.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart' show AppLifecycleState; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -967,6 +968,41 @@ void main() { verifyNever(mockSecureStorage.writeRefreshToken(any)); }); + test('a hanging refresh POST times out and keeps the session', () { + // Callers are deduplicated onto one in-flight refresh, so a POST that + // never answers would block them all, PowerSync's credential fetch + // included. The timeout must land in the keep-session branch. + fakeAsync((async) { + var seeded = false; + seedHeadlessBundle().then((_) => seeded = true); + async.flushMicrotasks(); + expect(seeded, isTrue); + + when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'old-refresh'); + when( + mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')), + ).thenAnswer((_) => Completer().future); + + final container = makeContainer(); + AuthState? state; + container.read(authProvider.future).then((s) => state = s); + async.flushMicrotasks(); + expect(state, isNotNull); + + var completed = false; + container.read(authProvider.notifier).refreshAccessToken().then((_) => completed = true); + + async.elapse(tokenRefreshTimeout - const Duration(seconds: 1)); + expect(completed, isFalse); + + async.elapse(const Duration(seconds: 2)); + expect(completed, isTrue); + + expect(container.read(authProvider).value!.isAuth, isTrue); + verifyNever(mockSecureStorage.writeRefreshToken(any)); + }); + }); + test('clearSessionOnly keeps the DB-owner marker (the local DB is preserved)', () async { // An involuntary clear keeps the local DB on disk, so its owner marker // must survive too: it is what lets a *different* user signing in later diff --git a/test/powersync/connector_test.dart b/test/powersync/connector_test.dart index 2b0e3222a..1fea3be55 100644 --- a/test/powersync/connector_test.dart +++ b/test/powersync/connector_test.dart @@ -21,6 +21,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:drift/drift.dart' show GeneratedColumnWithTypeConverter; +import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; @@ -384,6 +385,33 @@ void main() { await expectLater(connector.fetchCredentials(), throwsA(isA())); }); + test('times out when the token request hangs', () { + // On token expiry the SDK awaits fetchCredentials inline in its sync + // loop; without the ceiling a request that never answers freezes sync + // (disconnect included) until process restart. + fakeAsync((async) { + final mockApi = MockApiClient(); + final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi); + when( + mockApi.getPowersyncToken(), + ).thenAnswer((_) => Completer>().future); + + Object? error; + connector.fetchCredentials().then( + (_) {}, + onError: (Object e) { + error = e; + }, + ); + + async.elapse(DjangoConnector.credentialFetchTimeout - const Duration(seconds: 1)); + expect(error, isNull); + + async.elapse(const Duration(seconds: 2)); + expect(error, isA()); + }); + }); + test('anchors expiresAt to the local clock via the token lifetime', () async { final mockApi = MockApiClient(); final connector = DjangoConnector(