Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 37 additions & 24 deletions packages/gotrue/lib/src/gotrue_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1139,48 +1139,61 @@ class GoTrueClient {

/// Recover session from stringified [Session].
Future<AuthResponse> 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 runs fire-and-forget internally, so its
// error would otherwise be rooted at `_executeRefresh`; rethrowing with the
// current stack keeps `recoverSession` and the caller in the stack trace.
try {
return await _callRefreshToken(refreshToken);
Comment thread
spydon marked this conversation as resolved.
} 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
Expand Down
10 changes: 9 additions & 1 deletion packages/gotrue/test/client_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
);
Expand All @@ -582,8 +588,10 @@ void main() {
client.recoverSession(expiredSession.sessionString),
throwsA(isA<AuthException>()),
);
expect(stream, emitsError(isA<AuthException>()));

await pumpEventQueue();
await errorSubscription.cancel();
expect(streamError, isNull);
expect(client.currentSession, isNull);
});

Expand Down
56 changes: 56 additions & 0 deletions packages/gotrue/test/refresh_token_race_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<AuthException>());
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<AuthException>()),
);
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();
});
});
}
Loading