Repository navigation
fix(auth): keep the session when a refresh is rate limited or answered by a proxy - #2033
Merged
spydon merged 2 commits intoOct 23, 2026
Conversation
Contributor
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 5 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…on rejection codes
spydon
deleted the
lukasklingsbo/sdk-2340-fixauth-a-refresh-rejected-with-429-or-a-non-json-4xx-signs
branch
October 23, 2026 08:48
spydon
added a commit
that referenced
this pull request
Oct 26, 2026
…s skipped or lost (#2053) Fixes [SDK-2374](https://linear.app/supabase/issue/SDK-2374/fixauth-signout-must-not-report-success-when-the-server-revoke-was). `signOut` could return normally although the server never revoked anything. Global and others sign out now throw and keep the session instead of reporting success. A local sign out now waits for its revoke, so `dispose()` can no longer abort it, and logs a failure instead of throwing, since the app has no session left to retry with. ## Global and others sign out When `getSession()` fails to refresh (429, a proxy page, an unknown error code) the session is kept since #2033, and `signOut(scope: global | others)` used to fall back to the stored, expired access token. GoTrue answers `/logout` with 403 `bad_jwt` for it, which counted as "already signed out", so the call succeeded while every other device stayed signed in. - When the refresh fails and the stored access token has expired, `signOut` rethrows the refresh error and keeps the session. A token still inside the expiry margin is used as before, but only if no other sign in replaced the session meanwhile. - When the refresh token was rejected, the failed refresh has already signed this device out, but nothing was revoked on the server. `signOut` used to return normally here. It now rethrows, so the other devices are not silently left signed in. - `_revokeSessions` used to ignore every 401, 403 and 404 from `/logout`. GoTrue (checked against v2.197) answers an expired or forged access token with 403 `bad_jwt`, and a session or user that is already gone with 403 `session_not_found` or `user_not_found`. It now reads the error code: only `session_not_found` and `user_not_found` count as already signed out, so `bad_jwt` throws. For a server that answers without an error code, a 404 still counts as signed out, and a 401 or 403 counts as signed out only when neither the message nor the client clock says the token has expired. - When another sign in replaces the session while `getSession()` refreshes it, global sign out still revokes the refreshed session but no longer removes the newer one from the device. - When the refresh token was rejected, a failure to remove the pending PKCE verifiers is logged, so the refresh error still reaches the caller. ## Local sign out `signOut()` still removes the session from the device first, so it works offline, and `AuthSignedOut` is emitted synchronously when it is called, so an app can navigate right away without awaiting it. It then awaits the revoke instead of firing it in the background: - An expired access token is refreshed first with the captured refresh token, without storing the result, in a single attempt so the logout request still fits in the timeout. When the server rejects that refresh token as not found, already used, or for a missing session or user, the session is already unusable, which counts as success. When the refresh fails transiently and the token is only inside the expiry margin, it revokes with that token. - The revoke is bounded by 10 seconds (`AuthConstants.signOutRevokeTimeout`, internal), so a hung request cannot block the caller forever. - A network failure, 5xx or timeout is logged at warning level, not thrown. The tokens are already gone from the device, so the app could not retry, and an exception would only report something it cannot act on. The internal sign outs in `setInitialSession` and `recoverSession` (missing or unrefreshable stored session) keep revoking in the background and only log a failure, so they still throw their own exception right away. ## Documentation - `MIGRATION.md`: the `signOut()` section describes the awaited, non throwing local revoke, that the app can navigate without awaiting it, and that global and others also throw for an expired token that cannot be refreshed. - `auth-setup` skill: new "Sign out" section covering the same behavior, synced with `melos run sync-skills`. ## Tests Built on `supabase_test`, with `/logout` answering as GoTrue does: 403 `bad_jwt` for an expired or forged token, 403 `session_not_found` for a session that is already gone. - Local: signs out and logs a warning while offline, on a 5xx, after the timeout and when an expired token cannot be refreshed. Removes the session before the returned future completes, waits for the revoke, refreshes an expired token before revoking, treats a refresh token the server already revoked as revoked, and revokes with a token inside the expiry margin when the refresh is rate limited. - Global: throws and keeps the session while offline and can be retried, throws and keeps an expired session that cannot be refreshed, throws on a 401 without an error code for a token that expired while the request was in flight, throws on a `bad_jwt` whose message says the token expired while the client still thinks it is valid, throws on a `bad_jwt` for an invalid signature, keeps a sign in made while the expired session was refreshed, throws when the refresh token was rejected, and still throws the refresh error when the PKCE verifiers cannot be removed. - Others: throws while offline, throws and keeps an expired session that cannot be refreshed, and throws when the refresh token was rejected. - `user_scoped_session_test.dart`: the malformed refresh body tests now expect the throw, since their stub answered `/logout` with success for an expired token, which GoTrue never does. - `supabase_flutter` `widget_test.dart` now stubs `/logout` with `MockSupabaseHttpClient`. On web the real request never finished inside the fake time of `testWidgets`, so the revoke timeout was left pending. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Behavior Changes** * Local sign-out clears the device session and emits the signed-out event immediately, including when offline. It waits up to 10 seconds for server revocation; revocation failures are logged without throwing. * Global and other-device sign-out contact the server first, refreshing an expired access token when needed. If revocation fails, the session is retained and an exception is raised so the operation can be retried. Global sign-out clears the local session only after successful revocation. * **Documentation** * Added guidance on sign-out behavior, leaving local sign-out unawaited during navigation, and handling exceptions from global sign-out. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes SDK-2340.
Problem
A token refresh that failed with anything other than a 5xx or a transport error removed the session and emitted
AuthSignedOut(reason: SignOutReason.sessionExpired). That included a 429 rate limit and any non-JSON 4xx, such as the HTML page a captive portal or corporate proxy answers with. Users on hotel wifi, behind a proxy, or briefly rate limited were signed out for good and lost their persisted session.Change
The refresh path now ends the session only when the auth service rejects the refresh token, meaning a JSON error with one of the codes GoTrue's refresh grant returns for a dead token:
refresh_token_not_foundrefresh_token_already_used(the existing rule that keeps a still valid session still applies)session_not_foundsession_expireduser_not_founduser_bannedvalidation_failed(malformed refresh token, or one not issued by this server)ErrorCodegainsrefreshTokenNotFoundandrefreshTokenAlreadyUsed, so the set and the existingrefresh_token_already_usedcheck no longer use string literals.Every other failure keeps the session and the persisted copy, reports the error on
onAuthStateChange, and is retried on the next auto refresh tick:Retry-Afterasks for it, so the client doesn't add requests against a rate limit.Retry-After, the auto refresh ticks skip refreshing until it has passed. Saving or removing a session clears the pause.The classification lives in the refresh path only.
fetch.dartstill throws the same exception types, so a 429 fromsignInWithPasswordremains anAuthApiExceptionwithover_request_rate_limit.token_refresh_race_test.dartstubbed the rejected refresh with the pre-2024invalid_grantbody. v3 requires a server on API version2024-01-01or newer, which always sendscode, so the stub now sendsrefresh_token_not_found.Decision
The ticket asked for an SDK-wide decision. This PR implements the proposed rule: sign out only on a known refresh-token rejection code, and treat everything else as retryable. supabase-js has the same problem today: a 429 or a non-JSON 4xx is not an
AuthRetryableFetchErrorthere, so the session is removed once the access token has expired. The parity ticket is SDK-2364.Open decision: whether this rule is the one we want across SDKs. It fails open. A JSON error with a code the client doesn't know, for example a future rejection code, or a gateway's
401 Invalid API key, keeps the expired session and tries again every tick instead of signing out. That seemed the better failure mode than losing a valid session.Not changed
200from a proxy, for example) still signs out, asmissing_session_response_test.dartpins. A proxy page with a200is HTML, which already counts as a retryable fetch failure.AuthFetch._handleError. That would change the exception types every auth call throws, which is a wider breaking change than this fix needs.Tests
refresh_transient_failure_test.dartcovers 429 (JSON, HTML), 401/403/404 HTML, 403 with an empty body, and a JSON 401 without a code (an API gateway rejecting the key). For each one it checks that:signedOutIt also covers a 429 with
Retry-Afterkeeping the session and pausing the ticks until the delay has passed, a 429 retried within the tick afterRetry-After: 0, and that each rejection code still signs out withSignOutReason.sessionExpired.