-
Notifications
You must be signed in to change notification settings - Fork 377
fix(jwt): race conditions and IAM reliability issues with identity verification enabled #2613
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nan-li
wants to merge
4
commits into
feat/identity_verification_5.8
Choose a base branch
from
fix/jwt_misc_race_conditions
base: feat/identity_verification_5.8
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
03a333c
Fix race condition: purge anonymous ops AFTER queue is loaded
nan-li 89cca43
Replay JWT invalidated event to late-registered listeners
nan-li b48dc10
Fix IAM fetch stuck after login when identity verification is enabled
nan-li f94d780
Retry IAM fetch after JWT refresh on 401/403 response
nan-li File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
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
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
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 In
addJwtInvalidatedListener, the listener is subscribed (makinghasSubscribers=true) insidejwtInvalidatedLock, but the pending-replay delivery happens synchronously outside the lock, creating two problems. First, a concurrentfireJwtInvalidatedcall in that narrow window will also fire to the newly-registered listener, so the developer'sonUserJwtInvalidatedmay be invoked twice in rapid succession. Second, the replay runs synchronously on the caller's thread rather than throughjwtInvalidatedAppCallbackScope.launch(Dispatchers.Default), violating the async delivery contract documented onfireJwtInvalidatedand missing therunCatchingprotection present on the normal path. Fix: schedule the pending replay viajwtInvalidatedAppCallbackScope.launch { runCatching { ... } }inside thesynchronizedblock, matching the documented asynchronous contract.Extended reasoning...
What the bugs are and how they manifest
addJwtInvalidatedListener(UserManager.kt lines 61–71) has two related defects introduced in the pending-replay logic.Bug 1 — double-delivery race: The listener is subscribed to
jwtInvalidatedNotifierinsidejwtInvalidatedLock(which makeshasSubscribers == truevisible to other threads immediately). The lock is then released, and only after that release does the method calllistener.onUserJwtInvalidated(UserJwtInvalidatedEvent(it))directly. In the window between lock release and that direct call, a concurrent thread runningfireJwtInvalidated(externalId)can acquire the lock, observehasSubscribers == true, and schedule a coroutine (viajwtInvalidatedAppCallbackScope.launch) that also fires to every subscriber. When that coroutine executes it calls the same listener for the same (or coincident) externalId, resulting in twoonUserJwtInvalidatedinvocations in quick succession.Bug 2 — synchronous replay on caller thread: The
fireJwtInvalidatedmethod is documented as delivering events "asynchronously so the caller … is not blocked by developer code" and usesjwtInvalidatedAppCallbackScope.launchthroughout. The replay path at lines 68–70 is synchronous and unprotected byrunCatching. If a developer registers the listener on the main thread and a pending event exists, the callback fires synchronously on the main thread beforeaddJwtInvalidatedListenerreturns — and any exception from developer code propagates up to the registration call, unlike the normal path that catches and logs it.Specific code path that triggers it
Between (A)'s lock release and (B)'s synchronous call, step (C) can observe
hasSubscribers == trueand schedule an async coroutine. Both (B) and the coroutine then deliver to the same listener.Addressing the refutation
A refutation argues that the concurrent
fireJwtInvalidatedin the race window represents a new 401 event rather than a re-delivery of the buffered startup event, so two callbacks are technically correct. This is valid for the case where a genuine second 401 fires while the listener is being registered — those truly are separate events. However, the race is indistinguishable to the developer (both deliveries carry the same externalId), and the probability of a genuine concurrent 401 during the few-instruction window is low enough that in practice developers will treat this as a spurious duplicate. More importantly, both bugs are independently present regardless of this race: Bug 2 (synchronous delivery + missingrunCatching) exists even without any concurrent thread.Why existing code doesn't prevent it
EventProducer.subscribeuses the synchronized list's own internal lock, separate fromjwtInvalidatedLock. Once the listener is added insidejwtInvalidatedLock, it becomes visible tojwtInvalidatedNotifier.hasSubscriberson other threads immediately, before the outer lock is released. There is no mechanism to suppress concurrentfireJwtInvalidatedcalls in the window between the lock release and the synchronous delivery.Impact
A developer's
onUserJwtInvalidatedcallback called twice causes duplicate token-refresh requests, double-posted analytics, or unexpected state-machine transitions. The synchronous delivery can cause an ANR if the callback does I/O and is called on the main thread. An unguarded developer exception in the replay path crashes or corrupts state at the registration call site instead of being logged and swallowed.Step-by-step proof (double delivery)
fireJwtInvalidated('alice')is called → buffered:pendingJwtInvalidatedExternalId = 'alice'.addJwtInvalidatedListener(listener). Lock acquired; listener subscribed (hasSubscribers=true); pendingExternalId='alice' captured; pending cleared; lock released.fireJwtInvalidated('alice'). Lock acquired; hasSubscribers=true → launches coroutine to fire 'alice' to all listeners. Lock released.addJwtInvalidatedListenerdelivers 'alice' synchronously to listener (step B above).listener.onUserJwtInvalidated('alice')has been called twice.How to fix
Schedule the replay via the same async path used for normal delivery, inside the lock, before releasing it:
Scheduling the coroutine inside the lock ensures that any concurrent
fireJwtInvalidatedthat acquires the lock afterwards will see the pending state already cleared, and its own coroutine will be the only remaining delivery of that event.