From 43f0e635d9184f66b9e58c6413486eaa69664e33 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Thu, 22 Oct 2026 18:10:51 +0200 Subject: [PATCH 1/2] fix(auth): keep the session when a refresh is rate limited or answered by a proxy --- .../supabase_auth/lib/src/auth_client.dart | 40 ++- .../test/refresh_transient_failure_test.dart | 264 ++++++++++++++++++ 2 files changed, 298 insertions(+), 6 deletions(-) create mode 100644 packages/supabase_auth/test/refresh_transient_failure_test.dart diff --git a/packages/supabase_auth/lib/src/auth_client.dart b/packages/supabase_auth/lib/src/auth_client.dart index 1f5b58c27..8b9ecc1fe 100644 --- a/packages/supabase_auth/lib/src/auth_client.dart +++ b/packages/supabase_auth/lib/src/auth_client.dart @@ -1739,14 +1739,41 @@ class AuthClient { } } + /// Error codes with which the auth service rejects a refresh token for good. + static final _refreshTokenRejectionCodes = { + 'refresh_token_not_found', + 'refresh_token_already_used', + 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. A + /// `400` without an error code comes from a server that predates error + /// codes, which answers every rejected refresh token that way. + static bool _isTransientRefreshFailure(Object error) => switch (error) { + AuthRetryableException() || AuthUnknownException() => true, + AuthApiException(errorCode: null, :final statusCode) => statusCode != 400, + 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 +1806,7 @@ 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 && + return _isTransientRefreshFailure(e) && (clock.now().millisecondsSinceEpoch + nextBackOff.inMilliseconds - startedAt.millisecondsSinceEpoch) < @@ -2089,8 +2116,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, @@ -2137,7 +2165,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 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..d8af2a8bc --- /dev/null +++ b/packages/supabase_auth/test/refresh_transient_failure_test.dart @@ -0,0 +1,264 @@ +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 htmlPage = 'Sign in to the network'; + final storageKey = defaultPersistSessionKey(authUrl); + + late MockSupabaseHttpClient httpClient; + late TestAsyncStorage storage; + late AuthClient client; + late List states; + late List errors; + late Session stored; + + AuthClient createClient({ + SupabaseRetryOptions retryOptions = const SupabaseRetryOptions( + enabled: false, + ), + }) { + final authClient = AuthClient( + url: authUrl, + asyncStorage: storage, + httpClient: httpClient, + persistSession: true, + autoRefreshToken: false, + retryOptions: retryOptions, + ); + addTearDown(authClient.dispose); + final subscription = authClient.onAuthStateChange.listen( + states.add, + onError: errors.add, + ); + addTearDown(subscription.cancel); + return authClient; + } + + 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); + + setUp(() async { + httpClient = MockSupabaseHttpClient(); + storage = TestAsyncStorage(); + states = []; + errors = []; + client = createClient(); + stored = await signInTestUser(client); + await pumpEventQueue(); + states.clear(); + }); + + Future expectSessionKept() async { + await pumpEventQueue(); + expect(events(), isNot(contains(AuthChangeEvent.signedOut))); + expect(client.currentSession?.refreshToken, stored.refreshToken); + expect(await storage.getItem(storageKey), isNotNull); + } + + final transientFailures = { + '429 with a JSON error': ({times}) => stubRefreshJson( + {'code': 'over_request_rate_limit', 'msg': 'Request rate limit reached'}, + statusCode: 429, + times: times, + ), + '429 with a Retry-After header': ({times}) => stubRefreshJson( + {'code': 'over_request_rate_limit', 'msg': 'Request rate limit reached'}, + statusCode: 429, + headers: {'retry-after': '3600'}, + 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', () { + 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); + + // Close enough to expiry that every auto refresh tick refreshes. + final nearExpiry = stored.expiresAt!.subtract( + const Duration(seconds: 20), + ); + await withClock(Clock.fixed(nearExpiry), () async { + client.startAutoRefresh(); + await pumpEventQueue(); + await expectSessionKept(); + + client.startAutoRefresh(); + await pumpEventQueue(); + client.stopAutoRefresh(); + }); + + expect(events(), [AuthChangeEvent.tokenRefreshed]); + expect(client.currentSession?.refreshToken, 'refreshed-refresh-token'); + expect(httpClient.requestsTo('/token'), hasLength(2)); + }); + } + }); + + test('a 429 within the tick is retried after its Retry-After', () async { + client = createClient( + retryOptions: const SupabaseRetryOptions( + count: 1, + initialDelay: Duration(hours: 1), + ), + ); + stored = await signInTestUser(client); + await pumpEventQueue(); + states.clear(); + stubRefreshSuccess(); + stubRefreshJson( + {'code': 'over_request_rate_limit', 'msg': 'Request rate limit reached'}, + 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(httpClient.requestsTo('/token'), hasLength(2)); + }); + + group('a refresh token rejected with', () { + for (final code in [ + 'refresh_token_not_found', + 'session_not_found', + 'session_expired', + 'user_not_found', + 'user_banned', + 'validation_failed', + ]) { + test('$code signs out', () async { + stubRefreshJson({ + 'code': code, + 'msg': 'Invalid Refresh Token', + }, statusCode: 400); + + await expectLater( + client.refreshSession(), + throwsA( + isA().having( + (error) => error.errorCode, + 'errorCode', + code, + ), + ), + ); + await pumpEventQueue(); + + final signedOut = states.whereType().single; + expect(signedOut.reason, SignOutReason.sessionExpired); + expect(client.currentSession, isNull); + expect(await storage.getItem(storageKey), isNull); + expect(httpClient.requestsTo('/token'), hasLength(1)); + }); + } + + test('a 400 without a code from a server that predates codes signs ' + 'out', () async { + stubRefreshJson({ + 'error': 'invalid_grant', + 'error_description': 'Invalid Refresh Token: Refresh Token Not Found', + }, statusCode: 400); + + await expectLater( + client.refreshSession(), + throwsA(isA()), + ); + await pumpEventQueue(); + + expect( + states.whereType().single.reason, + SignOutReason.sessionExpired, + ); + expect(client.currentSession, isNull); + }); + }); +} From b96ee433b8939bb8ac1d9e94c3c7527d0d347fe6 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Thu, 22 Oct 2026 18:31:35 +0200 Subject: [PATCH 2/2] fix(auth): honour Retry-After across refresh ticks and only sign out on rejection codes --- .../supabase_auth/lib/src/auth_client.dart | 54 +++-- .../lib/src/types/error_code.dart | 6 + .../test/refresh_transient_failure_test.dart | 223 ++++++++++-------- .../test/src/token_refresh_race_test.dart | 4 +- 4 files changed, 176 insertions(+), 111 deletions(-) diff --git a/packages/supabase_auth/lib/src/auth_client.dart b/packages/supabase_auth/lib/src/auth_client.dart index 8b9ecc1fe..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); @@ -1741,8 +1755,8 @@ class AuthClient { /// Error codes with which the auth service rejects a refresh token for good. static final _refreshTokenRejectionCodes = { - 'refresh_token_not_found', - 'refresh_token_already_used', + ErrorCode.refreshTokenNotFound.code, + ErrorCode.refreshTokenAlreadyUsed.code, ErrorCode.sessionNotFound.code, ErrorCode.sessionExpired.code, ErrorCode.userNotFound.code, @@ -1754,12 +1768,9 @@ class AuthClient { /// /// 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. A - /// `400` without an error code comes from a server that predates error - /// codes, which answers every rejected refresh token that way. + /// 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(errorCode: null, :final statusCode) => statusCode != 400, AuthApiException(:final errorCode) => !_refreshTokenRejectionCodes.contains( errorCode, ), @@ -1806,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 _isTransientRefreshFailure(e) && + final retryable = + e is AuthRetryableException || + (_isTransientRefreshFailure(e) && retryAfterOf(e) != null); + return retryable && (clock.now().millisecondsSinceEpoch + nextBackOff.inMilliseconds - startedAt.millisecondsSinceEpoch) < @@ -1880,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())), ); @@ -1889,6 +1904,7 @@ class AuthClient { void _removeSession() { authLogger.fine('Removing session'); _currentSession = null; + _autoRefreshPausedUntil = null; _queueStorageWrite((storage) => storage.removeItem(_storageKey)); } @@ -2155,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( @@ -2185,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 index d8af2a8bc..a59932b34 100644 --- a/packages/supabase_auth/test/refresh_transient_failure_test.dart +++ b/packages/supabase_auth/test/refresh_transient_failure_test.dart @@ -14,7 +14,12 @@ 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; @@ -24,12 +29,19 @@ void main() { late List errors; late Session stored; - AuthClient createClient({ + setUp(() { + httpClient = MockSupabaseHttpClient(); + storage = TestAsyncStorage(); + states = []; + errors = []; + }); + + Future signIn({ SupabaseRetryOptions retryOptions = const SupabaseRetryOptions( enabled: false, ), - }) { - final authClient = AuthClient( + }) async { + client = AuthClient( url: authUrl, asyncStorage: storage, httpClient: httpClient, @@ -37,13 +49,15 @@ void main() { autoRefreshToken: false, retryOptions: retryOptions, ); - addTearDown(authClient.dispose); - final subscription = authClient.onAuthStateChange.listen( + addTearDown(client.dispose); + final subscription = client.onAuthStateChange.listen( states.add, onError: errors.add, ); addTearDown(subscription.cancel); - return authClient; + stored = await signInTestUser(client); + await pumpEventQueue(); + states.clear(); } void stubRefreshJson( @@ -94,16 +108,7 @@ void main() { Iterable events() => states.map((state) => state.event); - setUp(() async { - httpClient = MockSupabaseHttpClient(); - storage = TestAsyncStorage(); - states = []; - errors = []; - client = createClient(); - stored = await signInTestUser(client); - await pumpEventQueue(); - states.clear(); - }); + int refreshRequests() => httpClient.requestsTo('/token').length; Future expectSessionKept() async { await pumpEventQueue(); @@ -112,27 +117,28 @@ void main() { 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( - {'code': 'over_request_rate_limit', 'msg': 'Request rate limit reached'}, - statusCode: 429, - times: times, - ), - '429 with a Retry-After header': ({times}) => stubRefreshJson( - {'code': 'over_request_rate_limit', 'msg': 'Request rate limit reached'}, - statusCode: 429, - headers: {'retry-after': '3600'}, - times: times, - ), + '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, - ), + '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, @@ -141,6 +147,8 @@ void main() { }; group('a refresh answered with', () { + setUp(signIn); + for (final MapEntry(key: description, value: stubFailure) in transientFailures.entries) { test('$description keeps the session', () async { @@ -159,65 +167,110 @@ void main() { stubRefreshSuccess(); stubFailure(times: 1); - // Close enough to expiry that every auto refresh tick refreshes. - final nearExpiry = stored.expiresAt!.subtract( - const Duration(seconds: 20), - ); - await withClock(Clock.fixed(nearExpiry), () async { - client.startAutoRefresh(); - await pumpEventQueue(); - await expectSessionKept(); + await tick(); + await expectSessionKept(); - client.startAutoRefresh(); - await pumpEventQueue(); - client.stopAutoRefresh(); - }); + await tick(after: tickDuration); expect(events(), [AuthChangeEvent.tokenRefreshed]); expect(client.currentSession?.refreshToken, 'refreshed-refresh-token'); - expect(httpClient.requestsTo('/token'), hasLength(2)); + 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); + }); }); - test('a 429 within the tick is retried after its Retry-After', () async { - client = createClient( - retryOptions: const SupabaseRetryOptions( - count: 1, - initialDelay: Duration(hours: 1), + group('with retries enabled, a refresh answered with', () { + setUp( + () => signIn( + retryOptions: const SupabaseRetryOptions( + count: 2, + initialDelay: Duration(milliseconds: 1), + ), ), ); - stored = await signInTestUser(client); - await pumpEventQueue(); - states.clear(); - stubRefreshSuccess(); - stubRefreshJson( - {'code': 'over_request_rate_limit', 'msg': 'Request rate limit reached'}, - statusCode: 429, - headers: {'retry-after': '0'}, - times: 1, - ); - final session = await client.refreshSession().timeout( - const Duration(seconds: 5), - ); + 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(httpClient.requestsTo('/token'), hasLength(2)); + expect(session.refreshToken, 'refreshed-refresh-token'); + expect(refreshRequests(), 2); + }); }); group('a refresh token rejected with', () { + setUp(signIn); + for (final code in [ - 'refresh_token_not_found', - 'session_not_found', - 'session_expired', - 'user_not_found', - 'user_banned', - 'validation_failed', + ErrorCode.refreshTokenNotFound, + ErrorCode.sessionNotFound, + ErrorCode.sessionExpired, + ErrorCode.userNotFound, + ErrorCode.userBanned, + ErrorCode.validationFailed, ]) { - test('$code signs out', () async { + test('${code.code} signs out', () async { stubRefreshJson({ - 'code': code, + 'code': code.code, 'msg': 'Invalid Refresh Token', }, statusCode: 400); @@ -227,7 +280,7 @@ void main() { isA().having( (error) => error.errorCode, 'errorCode', - code, + code.code, ), ), ); @@ -237,28 +290,8 @@ void main() { expect(signedOut.reason, SignOutReason.sessionExpired); expect(client.currentSession, isNull); expect(await storage.getItem(storageKey), isNull); - expect(httpClient.requestsTo('/token'), hasLength(1)); + expect(refreshRequests(), 1); }); } - - test('a 400 without a code from a server that predates codes signs ' - 'out', () async { - stubRefreshJson({ - 'error': 'invalid_grant', - 'error_description': 'Invalid Refresh Token: Refresh Token Not Found', - }, statusCode: 400); - - await expectLater( - client.refreshSession(), - throwsA(isA()), - ); - await pumpEventQueue(); - - expect( - states.whereType().single.reason, - SignOutReason.sessionExpired, - ); - expect(client.currentSession, isNull); - }); }); } 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', }), ), ),