diff --git a/packages/supabase_auth/lib/src/auth_client.dart b/packages/supabase_auth/lib/src/auth_client.dart index 1f5b58c27..dd1d4cd5c 100644 --- a/packages/supabase_auth/lib/src/auth_client.dart +++ b/packages/supabase_auth/lib/src/auth_client.dart @@ -74,9 +74,12 @@ class _SessionState { /// flow that started it when several flows can be pending at once. /// /// [retryOptions] configures how a token refresh that never reached the -/// service is retried. A refresh also stops retrying once the next backoff -/// would fall after the next refresh tick, so the count only caps how many -/// attempts a short backoff can squeeze into that window. +/// service, or that the service answered with a 5xx, is retried. Another +/// failure that keeps the session, such as a rate limit, is only retried +/// within the tick when its `Retry-After` header asks for it. A refresh also +/// stops retrying once the next backoff would fall after the next refresh +/// tick, so the count only caps how many attempts a short backoff can squeeze +/// into that window. /// /// [requestTimeout] bounds how long a request to the auth service may go /// without progress. A timed-out request is cancelled and throws an @@ -183,6 +186,10 @@ class AuthClient { Timer? _autoRefreshTicker; + /// Until when the auto refresh ticks skip refreshing, because a failed + /// refresh asked to wait through its `Retry-After` header. + DateTime? _autoRefreshPausedUntil; + /// Tracks all pending (in-flight) refreshes keyed by token. /// Concurrent calls with the same token return the existing /// [Completer.future] instead of starting a duplicate request. @@ -1659,8 +1666,8 @@ class AuthClient { // 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 + // `signedOut` event for a rejected token, or a stream exception for any + // other 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 { @@ -1672,7 +1679,8 @@ class AuthClient { /// Starts an auto-refresh process in the background. Close to the time of /// expiration a process is started to refresh the session. If refreshing - /// fails it will be retried for as long as necessary. + /// fails it will be retried for as long as necessary, after waiting out a + /// `Retry-After` the auth service asked for. /// /// Does nothing once the client has been disposed, so that a late call (for /// example from an app lifecycle observer that has not been removed yet) @@ -1730,6 +1738,12 @@ class AuthClient { authLogger.finer('Access token expires in $expiresInTicks ticks'); + final pausedUntil = _autoRefreshPausedUntil; + if (pausedUntil != null && now.isBefore(pausedUntil)) { + authLogger.finer('Auto refresh paused by Retry-After'); + return; + } + // Only tick if the next tick comes after the retry threshold if (expiresInTicks <= AuthConstants.autoRefreshTickThreshold) { await _callRefreshToken(refreshToken); @@ -1739,14 +1753,38 @@ class AuthClient { } } + /// Error codes with which the auth service rejects a refresh token for good. + static final _refreshTokenRejectionCodes = { + ErrorCode.refreshTokenNotFound.code, + ErrorCode.refreshTokenAlreadyUsed.code, + ErrorCode.sessionNotFound.code, + ErrorCode.sessionExpired.code, + ErrorCode.userNotFound.code, + ErrorCode.userBanned.code, + ErrorCode.validationFailed.code, + }; + + /// Whether a later refresh may get past [error], so the session is kept. + /// + /// Only an error response from the auth service that rejects the refresh + /// token ends the session. A rate limit, or a response the service did not + /// send, such as an HTML page from a captive portal or proxy, does not. + static bool _isTransientRefreshFailure(Object error) => switch (error) { + AuthRetryableException() || AuthUnknownException() => true, + AuthApiException(:final errorCode) => !_refreshTokenRejectionCodes.contains( + errorCode, + ), + _ => false, + }; + /// Generates a new JWT. /// [refreshToken] A valid refresh token that was returned on login. Future _refreshAccessToken(String refreshToken) async { final startedAt = clock.now(); var attempt = 0; Duration? retryAfterOf(Object outcome) { - final requested = outcome is AuthRetryableApiException - ? outcome.retryAfter + final requested = outcome is SupabaseApiException + ? parseRetryAfter(outcome.headers) : null; if (requested == null) { return null; @@ -1779,7 +1817,10 @@ class AuthClient { // how many attempts a short backoff can squeeze into the tick. final nextBackOff = retryAfterOf(e) ?? retryOptions.delay(attempt - 1); - return e is AuthRetryableException && + final retryable = + e is AuthRetryableException || + (_isTransientRefreshFailure(e) && retryAfterOf(e) != null); + return retryable && (clock.now().millisecondsSinceEpoch + nextBackOff.inMilliseconds - startedAt.millisecondsSinceEpoch) < @@ -1853,6 +1894,7 @@ class AuthClient { authLogger.fine('Saving session'); authLogger.finest('Saving session: $session'); _currentSession = session; + _autoRefreshPausedUntil = null; _queueStorageWrite( (storage) => storage.setItem(_storageKey, jsonEncode(session.toJson())), ); @@ -1862,6 +1904,7 @@ class AuthClient { void _removeSession() { authLogger.fine('Removing session'); _currentSession = null; + _autoRefreshPausedUntil = null; _queueStorageWrite((storage) => storage.removeItem(_storageKey)); } @@ -2089,8 +2132,9 @@ class AuthClient { /// Returns the refreshed [Session] 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. + /// when the auth service rejects the refresh token, or a stream error + /// ([notifyException]) for any other failure, which keeps the session so the + /// next tick tries again. /// /// A rejected [refreshToken] only affects the stored session that token /// belongs to. When the stored session holds a different refresh token, @@ -2127,7 +2171,7 @@ class AuthClient { existingSession != null && existingSession.refreshToken == refreshToken; if (error is AuthApiException && - error.errorCode == 'refresh_token_already_used' && + error.errorCode == ErrorCode.refreshTokenAlreadyUsed.code && ownsStoredSession && !existingSession.isExpired) { authLogger.fine( @@ -2137,7 +2181,7 @@ class AuthClient { return existingSession; } - if (error is! AuthRetryableException) { + if (!_isTransientRefreshFailure(error)) { // The server rejected [refreshToken], so only the session that token // was redeemed for is gone: the stored session when it held the // token, or no session at all when nothing was stored. A session @@ -2157,6 +2201,16 @@ class AuthClient { ); } } else if (!_isDisposed) { + final retryAfter = switch (error) { + AuthApiException(headers: final responseHeaders) || + AuthRetryableApiException( + headers: final responseHeaders, + ) => parseRetryAfter(responseHeaders), + _ => null, + }; + if (retryAfter != null) { + _autoRefreshPausedUntil = clock.now().add(retryAfter); + } notifyException(error, stack); } rethrow; diff --git a/packages/supabase_auth/lib/src/types/error_code.dart b/packages/supabase_auth/lib/src/types/error_code.dart index bff141d80..c9d65b47d 100644 --- a/packages/supabase_auth/lib/src/types/error_code.dart +++ b/packages/supabase_auth/lib/src/types/error_code.dart @@ -38,6 +38,12 @@ enum ErrorCode { /// The session has expired and must be refreshed. sessionExpired('session_expired'), + /// The refresh token does not exist, for example because it was revoked. + refreshTokenNotFound('refresh_token_not_found'), + + /// The refresh token was already exchanged for a new session. + refreshTokenAlreadyUsed('refresh_token_already_used'), + /// The request requires a session but none was provided. sessionMissing('session_missing'), diff --git a/packages/supabase_auth/test/refresh_transient_failure_test.dart b/packages/supabase_auth/test/refresh_transient_failure_test.dart new file mode 100644 index 000000000..a59932b34 --- /dev/null +++ b/packages/supabase_auth/test/refresh_transient_failure_test.dart @@ -0,0 +1,297 @@ +import 'dart:async'; + +import 'package:clock/clock.dart'; +import 'package:supabase_auth/supabase_auth.dart'; +import 'package:supabase_common/supabase_common.dart'; +import 'package:test/test.dart'; + +import 'utils.dart'; + +/// Only a refresh token the auth service rejects ends the session. A rate +/// limit, or a response from something in front of the service such as a +/// captive portal or proxy, keeps it so the next refresh can try again. +void main() { + const authUrl = 'http://localhost:9999'; + const refreshQuery = {'grant_type': 'refresh_token'}; + const apiVersionHeaders = {'x-sb-api-version': '2024-01-01'}; + const tickDuration = Duration(seconds: 10); + const htmlPage = 'Sign in to the network'; + const rateLimit = { + 'code': 'over_request_rate_limit', + 'msg': 'Request rate limit reached', + }; + final storageKey = defaultPersistSessionKey(authUrl); + + late MockSupabaseHttpClient httpClient; + late TestAsyncStorage storage; + late AuthClient client; + late List states; + late List errors; + late Session stored; + + setUp(() { + httpClient = MockSupabaseHttpClient(); + storage = TestAsyncStorage(); + states = []; + errors = []; + }); + + Future signIn({ + SupabaseRetryOptions retryOptions = const SupabaseRetryOptions( + enabled: false, + ), + }) async { + client = AuthClient( + url: authUrl, + asyncStorage: storage, + httpClient: httpClient, + persistSession: true, + autoRefreshToken: false, + retryOptions: retryOptions, + ); + addTearDown(client.dispose); + final subscription = client.onAuthStateChange.listen( + states.add, + onError: errors.add, + ); + addTearDown(subscription.cancel); + stored = await signInTestUser(client); + await pumpEventQueue(); + states.clear(); + } + + void stubRefreshJson( + Object? body, { + required int statusCode, + Map headers = const {}, + int? times, + }) { + httpClient.stub( + body, + method: HttpMethod.post.value, + path: '/token', + query: refreshQuery, + statusCode: statusCode, + headers: {...apiVersionHeaders, ...headers}, + times: times, + ); + } + + void stubRefreshHtml(int statusCode, {int? times}) { + httpClient.stubText( + htmlPage, + method: HttpMethod.post.value, + path: '/token', + query: refreshQuery, + statusCode: statusCode, + contentType: 'text/html; charset=utf-8', + times: times, + ); + } + + void stubRefreshSuccess() { + stubRefreshJson( + testSessionResponseJson( + accessToken: unsignedTestJwt({ + 'sub': testUserId, + 'exp': + DateTime.now() + .add(const Duration(hours: 1)) + .millisecondsSinceEpoch ~/ + 1000, + }), + refreshToken: 'refreshed-refresh-token', + ), + statusCode: 200, + ); + } + + Iterable events() => states.map((state) => state.event); + + int refreshRequests() => httpClient.requestsTo('/token').length; + + Future expectSessionKept() async { + await pumpEventQueue(); + expect(events(), isNot(contains(AuthChangeEvent.signedOut))); + expect(client.currentSession?.refreshToken, stored.refreshToken); + expect(await storage.getItem(storageKey), isNotNull); + } + + /// Runs an auto refresh tick at [now], close enough to the expiry of the + /// stored session that the tick refreshes it. + Future tick({Duration after = Duration.zero}) { + final now = stored.expiresAt! + .subtract(const Duration(seconds: 20)) + .add(after); + return withClock(Clock.fixed(now), () async { + client.startAutoRefresh(); + await pumpEventQueue(); + client.stopAutoRefresh(); + }); + } + + final transientFailures = { + '429 with a JSON error': ({times}) => + stubRefreshJson(rateLimit, statusCode: 429, times: times), + '429 with an HTML page': ({times}) => stubRefreshHtml(429, times: times), + '401 with an HTML page': ({times}) => stubRefreshHtml(401, times: times), + '403 with an HTML page': ({times}) => stubRefreshHtml(403, times: times), + '404 with an HTML page': ({times}) => stubRefreshHtml(404, times: times), + '403 with an empty body': ({times}) => + stubRefreshJson(null, statusCode: 403, times: times), + '401 with a JSON error without a code': ({times}) => stubRefreshJson( + {'message': 'Invalid API key'}, + statusCode: 401, + times: times, + ), + }; + + group('a refresh answered with', () { + setUp(signIn); + + for (final MapEntry(key: description, value: stubFailure) + in transientFailures.entries) { + test('$description keeps the session', () async { + stubFailure(); + + await expectLater( + client.refreshSession(), + throwsA(isA()), + ); + + await expectSessionKept(); + expect(errors, hasLength(1)); + }); + + test('$description is retried on the next tick', () async { + stubRefreshSuccess(); + stubFailure(times: 1); + + await tick(); + await expectSessionKept(); + + await tick(after: tickDuration); + + expect(events(), [AuthChangeEvent.tokenRefreshed]); + expect(client.currentSession?.refreshToken, 'refreshed-refresh-token'); + expect(refreshRequests(), 2); + }); + } + + test('a 429 with a Retry-After keeps the session', () async { + stubRefreshJson( + rateLimit, + statusCode: 429, + headers: {'retry-after': '3600'}, + ); + + await expectLater( + client.refreshSession(), + throwsA(isA()), + ); + + await expectSessionKept(); + }); + + test('a 429 with a Retry-After pauses the ticks until it passes', () async { + stubRefreshSuccess(); + stubRefreshJson( + rateLimit, + statusCode: 429, + headers: {'retry-after': '60'}, + times: 1, + ); + + await tick(); + await expectSessionKept(); + + await tick(after: tickDuration); + expect(refreshRequests(), 1); + + await tick(after: const Duration(seconds: 61)); + + expect(events(), [AuthChangeEvent.tokenRefreshed]); + expect(refreshRequests(), 2); + }); + }); + + group('with retries enabled, a refresh answered with', () { + setUp( + () => signIn( + retryOptions: const SupabaseRetryOptions( + count: 2, + initialDelay: Duration(milliseconds: 1), + ), + ), + ); + + for (final MapEntry(key: description, value: stubFailure) + in transientFailures.entries) { + test('$description is not retried within the tick', () async { + stubFailure(); + + await expectLater( + client.refreshSession(), + throwsA(isA()), + ); + + expect(refreshRequests(), 1); + }); + } + + test('a 429 is retried within the tick after its Retry-After', () async { + stubRefreshSuccess(); + stubRefreshJson( + rateLimit, + statusCode: 429, + headers: {'retry-after': '0'}, + times: 1, + ); + + final session = await client.refreshSession().timeout( + const Duration(seconds: 5), + ); + + expect(session.refreshToken, 'refreshed-refresh-token'); + expect(refreshRequests(), 2); + }); + }); + + group('a refresh token rejected with', () { + setUp(signIn); + + for (final code in [ + ErrorCode.refreshTokenNotFound, + ErrorCode.sessionNotFound, + ErrorCode.sessionExpired, + ErrorCode.userNotFound, + ErrorCode.userBanned, + ErrorCode.validationFailed, + ]) { + test('${code.code} signs out', () async { + stubRefreshJson({ + 'code': code.code, + 'msg': 'Invalid Refresh Token', + }, statusCode: 400); + + await expectLater( + client.refreshSession(), + throwsA( + isA().having( + (error) => error.errorCode, + 'errorCode', + code.code, + ), + ), + ); + await pumpEventQueue(); + + final signedOut = states.whereType().single; + expect(signedOut.reason, SignOutReason.sessionExpired); + expect(client.currentSession, isNull); + expect(await storage.getItem(storageKey), isNull); + expect(refreshRequests(), 1); + }); + } + }); +} diff --git a/packages/supabase_auth/test/src/token_refresh_race_test.dart b/packages/supabase_auth/test/src/token_refresh_race_test.dart index 3088f7ae0..7e902ba0e 100644 --- a/packages/supabase_auth/test/src/token_refresh_race_test.dart +++ b/packages/supabase_auth/test/src/token_refresh_race_test.dart @@ -79,8 +79,8 @@ class _DelayedTokenMockClient extends BaseClient { Stream.value( utf8.encode( jsonEncode({ - 'error': 'invalid_grant', - 'error_description': 'Token has been revoked', + 'code': 'refresh_token_not_found', + 'msg': 'Invalid Refresh Token: Refresh Token Not Found', }), ), ),