diff --git a/packages/gotrue/lib/src/gotrue_client.dart b/packages/gotrue/lib/src/gotrue_client.dart index 66c7560d7..4700eb394 100644 --- a/packages/gotrue/lib/src/gotrue_client.dart +++ b/packages/gotrue/lib/src/gotrue_client.dart @@ -82,7 +82,7 @@ class GoTrueClient { /// [Completer.future] instead of starting a duplicate request. final Map> _pendingRefreshes = {}; - /// Set by [dispose] to prevent [_executeRefresh] from mutating state + /// Set by [dispose] to prevent [_doRefresh] from mutating state /// or emitting events on closed stream controllers. bool _isDisposed = false; @@ -1121,48 +1121,61 @@ class GoTrueClient { /// Recover session from stringified [Session]. Future recoverSession(String jsonStr) async { + final String refreshToken; try { final session = Session.fromJson(json.decode(jsonStr)); if (session == null) { _log.warning("Can't recover session from string, session is null"); await signOut(); - throw notifyException( - AuthException('Current session is missing data.'), - ); + // The `catch` below notifies subscribers, so throw without notifying + // here to avoid emitting the error onto the stream twice. + throw AuthException('Current session is missing data.'); } - if (session.isExpired) { - _log.fine('Session from recovery is expired'); + if (!session.isExpired) { + final shouldEmitEvent = _currentSession == null || + _currentSession!.user.id != session.user.id; + _saveSession(session); - final existingSession = _currentSession; - if (existingSession != null && - !existingSession.isExpired && - existingSession.user.id == session.user.id) { - _log.fine( - 'Session was already refreshed elsewhere, skipping recovery'); - return AuthResponse(session: existingSession); + if (shouldEmitEvent) { + notifyAllSubscribers(AuthChangeEvent.tokenRefreshed); } - final refreshToken = session.refreshToken; - if (_autoRefreshToken && refreshToken != null) { - return await _callRefreshToken(refreshToken); - } - await signOut(); - throw notifyException(AuthException('Session expired.')); + return AuthResponse(session: session); } - final shouldEmitEvent = _currentSession == null || - _currentSession!.user.id != session.user.id; - _saveSession(session); - if (shouldEmitEvent) { - notifyAllSubscribers(AuthChangeEvent.tokenRefreshed); + _log.fine('Session from recovery is expired'); + + final existingSession = _currentSession; + if (existingSession != null && + !existingSession.isExpired && + existingSession.user.id == session.user.id) { + _log.fine('Session was already refreshed elsewhere, skipping recovery'); + return AuthResponse(session: existingSession); } - return AuthResponse(session: session); + final token = session.refreshToken; + if (!_autoRefreshToken || token == null) { + await signOut(); + throw AuthException('Session expired.'); + } + refreshToken = token; } catch (error, stackTrace) { notifyException(error, stackTrace); rethrow; } + + // Run the refresh outside the try/catch above so its error is not + // re-notified: `_callRefreshToken` already reports the outcome (a + // `signedOut` event for an invalid token, or a stream exception for a + // retryable failure). The refresh resolves through a completer, so its + // error would otherwise be rooted at `_doRefresh`; rethrowing with the + // current stack keeps `recoverSession` and the caller in the stack trace. + try { + return await _callRefreshToken(refreshToken); + } catch (error) { + Error.throwWithStackTrace(error, StackTrace.current); + } } /// Starts an auto-refresh process in the background. Close to the time of expiration a process is started to @@ -1401,52 +1414,57 @@ class GoTrueClient { return existing.future; } + // The completer is kept as an external handle so [dispose] can cancel an + // in-flight refresh: the network request itself cannot be interrupted, so + // a hung refresh can only be resolved by completing this completer. final completer = Completer(); completer.future.ignore(); _pendingRefreshes[refreshToken] = completer; - unawaited(_executeRefresh(refreshToken, completer)); + unawaited( + _doRefresh(refreshToken).then( + (response) { + if (!completer.isCompleted) completer.complete(response); + }, + onError: (Object error, StackTrace stack) { + if (!completer.isCompleted) completer.completeError(error, stack); + }, + ).whenComplete(() => _pendingRefreshes.remove(refreshToken)), + ); return completer.future; } - /// Executes a single token refresh. - Future _executeRefresh( - String refreshToken, - Completer completer, - ) async { - if (_isDisposed) return; - + /// Performs a single token refresh, applies the outcome to the local session + /// and notifies subscribers. + /// + /// Returns the refreshed [AuthResponse] or throws the underlying error. This + /// is the single place that emits refresh outcomes: [AuthChangeEvent.tokenRefreshed] + /// on success, [AuthChangeEvent.signedOut] when the refresh token is invalid, + /// or a stream error ([notifyException]) for a retryable/unexpected failure. + Future _doRefresh(String refreshToken) async { final versionBeforeRefresh = _sessionVersion; + _log.fine('Refresh access token'); try { - _log.fine('Refresh access token'); - final data = await _refreshAccessToken(refreshToken); - if (_isDisposed) return; - final session = data.session; if (session == null) { throw AuthSessionMissingException(); } - // Guard: if the session was mutated while we were awaiting - // the network request (e.g. a concurrent signIn or signOut), - // discard this result to avoid overwriting the newer session. - if (_sessionVersion != versionBeforeRefresh) { - _log.fine( - 'Session changed during refresh ' - '(version $versionBeforeRefresh → $_sessionVersion). ' - 'Discarding stale refresh result.', - ); - if (!completer.isCompleted) completer.complete(data); - return; + // Discard the result if the client was disposed or the session was + // mutated (e.g. a concurrent signIn or signOut) while we were awaiting + // the network request, so we don't overwrite the newer session. + if (_isDisposed || _sessionVersion != versionBeforeRefresh) { + _log.fine('Session changed during refresh, discarding stale result.'); + return data; } _saveSession(session); notifyAllSubscribers(AuthChangeEvent.tokenRefreshed); - if (!completer.isCompleted) completer.complete(data); + return data; } on AuthException catch (error, stack) { final existingSession = _currentSession; if (error is AuthApiException && @@ -1455,15 +1473,12 @@ class GoTrueClient { !existingSession.isExpired) { _log.fine('Refresh token already used but current session is still ' 'valid, returning it instead of signing out'); - final response = AuthResponse(session: existingSession); - if (!completer.isCompleted) completer.complete(response); - return; + return AuthResponse(session: existingSession); } if (error is! AuthRetryableFetchException) { - // Only remove the session if it hasn't been replaced - // while we were refreshing — otherwise we'd sign out a - // user who just signed in. + // Only remove the session if it hasn't been replaced while we were + // refreshing, otherwise we'd sign out a user who just signed in. if (!_isDisposed && _sessionVersion == versionBeforeRefresh) { _removeSession(); notifyAllSubscribers(AuthChangeEvent.signedOut); @@ -1471,19 +1486,12 @@ class GoTrueClient { } else if (!_isDisposed) { notifyException(error, stack); } - - if (!completer.isCompleted) { - completer.completeError(error, stack); - } + rethrow; } catch (error, stack) { - if (!completer.isCompleted) { - completer.completeError(error, stack); - } if (!_isDisposed) { notifyException(error, stack); } - } finally { - _pendingRefreshes.remove(refreshToken); + rethrow; } } diff --git a/packages/gotrue/test/client_test.dart b/packages/gotrue/test/client_test.dart index ed626e1d9..74bd11da8 100644 --- a/packages/gotrue/test/client_test.dart +++ b/packages/gotrue/test/client_test.dart @@ -574,6 +574,12 @@ void main() { ]), ); + Object? streamError; + final errorSubscription = stream.listen( + (_) {}, + onError: (Object error) => streamError = error, + ); + final expiredSession = getSessionData( DateTime.now().subtract(Duration(hours: 1)), ); @@ -582,8 +588,10 @@ void main() { client.recoverSession(expiredSession.sessionString), throwsA(isA()), ); - expect(stream, emitsError(isA())); + await pumpEventQueue(); + await errorSubscription.cancel(); + expect(streamError, isNull); expect(client.currentSession, isNull); }); diff --git a/packages/gotrue/test/refresh_token_race_test.dart b/packages/gotrue/test/refresh_token_race_test.dart index 3c1600b5d..97ee644e0 100644 --- a/packages/gotrue/test/refresh_token_race_test.dart +++ b/packages/gotrue/test/refresh_token_race_test.dart @@ -442,5 +442,61 @@ void main() { reason: 'Should not attempt refresh when current session is valid for same user'); }); + + test('recoverSession stays in the stack trace when the refresh fails', + () async { + final httpClient = RefreshTokenTrackingHttpClient(); + // Force the refresh to fail by pre-consuming the persisted refresh token. + httpClient.markTokenAsUsed('-yeS4omysFs9tpUYBws9Rg'); + final client = GoTrueClient( + url: gotrueUrl, + asyncStorage: TestAsyncStorage(), + httpClient: httpClient, + ); + + Object? caught; + StackTrace? trace; + try { + await client.recoverSession(createExpiredSessionForUser1()); + } catch (error, stackTrace) { + caught = error; + trace = stackTrace; + } + + expect(caught, isA()); + expect(trace, isNotNull); + // The refresh runs fire-and-forget internally, so `recoverSession` only + // appears in the asynchronous stack trace because it rethrows with the + // current stack. + expect(trace!.toString(), contains('recoverSession')); + }); + + test('recoverSession emits a single error for an expired session', + () async { + final client = GoTrueClient( + url: gotrueUrl, + asyncStorage: TestAsyncStorage(), + autoRefreshToken: false, + httpClient: RefreshTokenTrackingHttpClient(), + ); + + var errorCount = 0; + final subscription = client.onAuthStateChange.listen( + (_) {}, + onError: (_) => errorCount++, + ); + + await expectLater( + client.recoverSession(createExpiredSessionForUser1()), + throwsA(isA()), + ); + await pumpEventQueue(); + + // The error must reach the stream exactly once, not be re-notified by the + // surrounding catch on top of the explicit notification. + expect(errorCount, 1); + + await subscription.cancel(); + }); }); }