Skip to content

fix(auth): keep the session when a refresh is rate limited or answered by a proxy - #2033

Merged
spydon merged 2 commits into
mainfrom
lukasklingsbo/sdk-2340-fixauth-a-refresh-rejected-with-429-or-a-non-json-4xx-signs
Oct 23, 2026
Merged

spydon merged 2 commits into
mainfrom
lukasklingsbo/sdk-2340-fixauth-a-refresh-rejected-with-429-or-a-non-json-4xx-signs

Conversation

@spydon

@spydon spydon commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

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_found
  • refresh_token_already_used (the existing rule that keeps a still valid session still applies)
  • session_not_found
  • session_expired
  • user_not_found
  • user_banned
  • validation_failed (malformed refresh token, or one not issued by this server)

ErrorCode gains refreshTokenNotFound and refreshTokenAlreadyUsed, so the set and the existing refresh_token_already_used check 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:

  • Within a tick only network failures and 5xx are retried with backoff, as before. A 429 or a proxy page is retried within the tick only when its Retry-After asks for it, so the client doesn't add requests against a rate limit.
  • When a failed refresh carries 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.dart still throws the same exception types, so a 429 from signInWithPassword remains an AuthApiException with over_request_rate_limit.

token_refresh_race_test.dart stubbed the rejected refresh with the pre-2024 invalid_grant body. v3 requires a server on API version 2024-01-01 or newer, which always sends code, so the stub now sends refresh_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 AuthRetryableFetchError there, 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

  • A 2xx without a session (an empty 200 from a proxy, for example) still signs out, as missing_session_response_test.dart pins. A proxy page with a 200 is HTML, which already counts as a retryable fetch failure.
  • 429 and undecodable 4xx are not reclassified in 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.dart covers 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:

  • the session and persisted session are kept with no signedOut
  • the next auto refresh tick refreshes successfully
  • with retries enabled, there is no extra request within the tick

It also covers a 429 with Retry-After keeping the session and pausing the ticks until the delay has passed, a 429 retried within the tick after Retry-After: 0, and that each rejection code still signs out with SignOutReason.sessionExpired.

@github-actions github-actions Bot added the auth This issue or pull request is related to authentication label Oct 22, 2026
@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
📥 Commits

Reviewing files that changed from the base of the PR and between 6083d66 and b96ee43.

📒 Files selected for processing: 4
  • packages/supabase_auth/lib/src/auth_client.dart
  • packages/supabase_auth/lib/src/types/error_code.dart
  • packages/supabase_auth/test/refresh_transient_failure_test.dart
  • packages/supabase_auth/test/src/token_refresh_race_test.dart
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@spydon
spydon merged commit 8f8c504 into main Oct 23, 2026
45 of 47 checks passed
@spydon
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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auth This issue or pull request is related to authentication

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant