Skip to content

fix(gotrue): prevent stale token refresh from overwriting concurrent session changes - #1351

Merged
spydon merged 7 commits into
supabase:mainfrom
brunovsiqueira:fix/gotrue-token-refresh-races
Jun 11, 2026
Merged

spydon merged 7 commits into
supabase:mainfrom
brunovsiqueira:fix/gotrue-token-refresh-races

Conversation

@brunovsiqueira

@brunovsiqueira brunovsiqueira commented Apr 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes race conditions in GoTrueClient._callRefreshToken() where an in-flight token refresh could overwrite a newer session established by a concurrent signIn, signOut, or setSession call.

  • Session version guard via _SessionState: session and version are encapsulated in a _SessionState helper whose setter auto-increments the version on every write. _executeRefresh snapshots the version before the network round-trip and discards the result if it changed, preventing stale refreshes from overwriting a newer session.
  • Token-aware dedup: the old Completer pattern ignored the refreshToken parameter, so _callRefreshToken(tokenB) would silently return tokenA's in-flight future. Now, same-token calls de-duplicate correctly while different-token calls each run their own request, tracked in a Map<String, Completer<AuthResponse>> _pendingRefreshes.
  • TOCTOU fix in _autoRefreshTokenTick: reads _currentSession into a local variable once so that refreshToken and expiresAt come from the same snapshot.
  • Defensive error handling: a failed refresh no longer calls _removeSession() and emits signedOut if the session was replaced by a concurrent operation while the refresh was in-flight. All completer.complete/completeError calls are guarded with !completer.isCompleted for dispose safety. If a refresh_token_already_used error is received but the current session is still valid, the result is resolved with the existing session instead of signing the user out.
  • Dispose guard: _isDisposed flag prevents _executeRefresh from mutating state or emitting events on closed stream controllers after dispose(). All pending completers are resolved with an AuthException('Disposed') on teardown.

Test results: before vs after

All 8 race condition tests were run against main (old code) and this branch. 7 of 8 fail on main, all 8 pass after the fix:

Test Before (main) After (this PR) Failure on main
signOut during in-flight refresh does not restore session ❌ ✅ Session restored after signOut (expected null, got Session)
signIn during in-flight refresh preserves new session ❌ ✅ Old refresh overwrote new session
concurrent refresh with same token deduplicates ✅ ✅ (already worked)
concurrent refresh with different tokens both execute ❌ ✅ Second token silently dropped (1 request instead of 2)
A-B-A pattern deduplicates correctly ❌ ✅ Second token silently dropped
dispose completes active refresh with error ❌ ✅ Timed out (30s) -- completer never resolved
refresh failure does not sign out if session changed ❌ ✅ Session nulled despite concurrent signIn
refresh failure signs out when session unchanged ❌ ✅ signedOut event not emitted

Related issues

Test plan

  • 8 race condition tests in packages/gotrue/test/src/token_refresh_race_test.dart
  • All existing gotrue unit tests pass
  • All supabase_flutter tests pass
  • dart analyze clean (only pre-existing deprecation infos)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses race conditions in packages/gotrue token refresh flow where an in-flight refresh could overwrite a newer session established concurrently (e.g., via signIn, signOut, or setSession), and improves refresh de-duplication behavior.

Changes:

  • Add a monotonic session version counter to detect and discard stale refresh results.
  • Replace the previous global refresh completer with a same-token de-dup + different-token serialization mechanism.
  • Add a new test suite covering common token refresh race scenarios.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.

File Description
packages/gotrue/lib/src/gotrue_client.dart Introduces session version guarding and a serialized refresh queue with same-token de-duplication.
packages/gotrue/test/src/token_refresh_race_test.dart Adds unit tests to validate refresh concurrency behavior and stale-result handling.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@Vinzent03

Copy link
Copy Markdown
Collaborator

I'm starting to think if this is the correct solution to fix this. Couldn't we more adopt how auth-js does this? I haven't looked too much into their solution, but they are locking their session, which could be a more generally solution.

@grdsdev

grdsdev commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

@Vinzent03 JS also have many issues related to token refresh, so JS may not be the right solution, I think both needs to rethink how token refresh is implemented, not saying this is the right approach, I didn't have enough time yet to review it.

@grdsdev

grdsdev commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

@brunovsiqueira thanks a lot for your contribution, those are a lot of complex changes, and really hard scenarios to manually test.

Did you face all the issues this PR claims to fix when using the library?

Also, can you fix CI by formatting the test file, that seems like the only issue.

@brunovsiqueira

brunovsiqueira commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey @grdsdev
I didnt experience the issues myself. It was done as a follow up from #1340 where @icnahom suggested applying the same serial queue pattern to token refresh, and the race conditions matched symptoms reported in #1158.

I added unit tests to reproduce the race conditions, then did the refactor, and the race conditions tests got fixed. Thats how I "tested" it, but I didnt experience them myself.

Fixed the test file formatting in ad7c342.

@icnahom

icnahom commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

Hey @grdsdev I didnt experience the issues myself. It was done as a follow up from #1340 where @icnahom suggested applying the same serial queue pattern to token refresh, and the race conditions matched symptoms reported in #1158.

Not familiar with the token refresh issue, but I can investigate.

@brunovsiqueira

Copy link
Copy Markdown
Contributor Author

Sorry, it was @grdsdev who suggested applying the same pattern to token refresh 😅

@Vinzent03

Copy link
Copy Markdown
Collaborator

Interesting that the js SDK has issues with this as well. So I think we can be a bit more freely on how to fix this.
I don't quite get why we need to run two token refreshes in parallel if we gonna ignore the previous ones either way? Instead of using a counter, I think we can rely on iat claim of the jwt https://supabase.com/docs/guides/auth/jwt-fields#required-claims to favor the most recent one.

@brunovsiqueira
brunovsiqueira force-pushed the fix/gotrue-token-refresh-races branch from ad7c342 to 100065a Compare May 15, 2026 15:30
@brunovsiqueira
brunovsiqueira requested a review from a team as a code owner May 15, 2026 15:30
@brunovsiqueira

Copy link
Copy Markdown
Contributor Author

@Vinzent03 Good points. The serial queue (_pendingRefreshOperation) was there to avoid a wasted HTTP call when two different tokens race.
But since _sessionVersion already guarantees correctness, I dropped the serial queue to keep things simpler (see 100065a).

Regarding iat: it doesn't cover all cases: signOut() nulls the session (no JWT to compare), updateUser() changes the user without changing the token (same iat), and iat is optional. The counter catches every mutation path uniformly. So kept as is.

@brunovsiqueira

Copy link
Copy Markdown
Contributor Author

Hi team.

Anything pending to merge this PR in?

@spydon

spydon commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Hi team.

Anything pending to merge this PR in?

Hey @brunovsiqueira, sorry for the wait!
I just joined the team this monday and I'll have a sync with Vinzent next week, I'll make sure to get his thoughts on this one then.

@spydon

spydon commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

@brunovsiqueira what about doing something like this instead? So that we don't have to do _sessionVersion++ everywhere:

class _SessionState {
  Session? _session;
  int version = 0;

  Session? get session => _session;
  set session(Session? value) {
    version++;
    _session = value;
  }
}

Session? get _currentSession => _sessionState.session;
set _currentSession(Session? value) => _sessionState.session = value;

Like this we make sure that everywhere where _currentSession is mutated we update the version.

@spydon
spydon force-pushed the fix/gotrue-token-refresh-races branch from 100065a to 21d0415 Compare June 10, 2026 15:42

@spydon spydon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution @brunovsiqueira, I'll try to get out a new version with this today :)

brunovsiqueira and others added 7 commits June 10, 2026 17:51
- Replace single _activeRefresh record with Map<String, Completer> to
  fix A-B-A dedup bug: refresh(A) → refresh(B) → refresh(A) now
  correctly deduplicates the second A call instead of enqueuing a third
  network request.

- Bump _sessionVersion in updateUser and setInitialSession, which were
  writing _currentSession directly and bypassing the version guard.

- Add _isDisposed flag checked in _executeRefresh to prevent mutating
  state or emitting events on closed stream controllers after dispose().

- Pass stack traces to completeError for better debugging.

- Add A-B-A dedup test case.
…uard

Remove _pendingRefreshOperation serial future chain. Different-token
refreshes now run concurrently — the _sessionVersion guard already
ensures only the latest result is applied, making the queue redundant
for correctness. This simplifies the code at the cost of an occasional
extra HTTP request in the rare different-token race scenario.
Introduce a small _SessionState helper so every write to _currentSession
automatically bumps version, removing the need to manually call
_sessionVersion++ before each assignment.
…attern

The de2adf9 main commit added a refresh_token_already_used handler that
completed the old _refreshTokenCompleter. Adapt it to use the new
Completer<AuthResponse> parameter from _executeRefresh instead.
@spydon
spydon force-pushed the fix/gotrue-token-refresh-races branch from 21d0415 to d45302c Compare June 10, 2026 15:53
@brunovsiqueira

Copy link
Copy Markdown
Contributor Author

@spydon sorry for the late reply.
The proposed refactor looks good to me, glad you already implemented that. Thank you very much!

@spydon

spydon commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

@spydon sorry for the late reply. The proposed refactor looks good to me, glad you already implemented that. Thank you very much!

Haha don't worry about it, your reply was like a month faster than ours 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auto Refresh is not working

7 participants