Repository navigation
Description
Problem
AuthService is registered as a singleton (MauiProgram.cs), and LoadAsync — which populates AccessToken from SecureStorage on first use — has no synchronization. GetAccessTokenAsync calls it whenever AccessToken is null, so two callers arriving before the first load completes both enter it.
Since #116 that method has a fallback catch treating an unreadable token as "signed out":
catch (Exception ex)
{
_logger.LogError(ex, "AUTH token-load failed; treating as signed out.");
AccessToken = null;
ExpiresAt = null;
}That is right for a single caller and wrong for concurrent ones. If invocation A reads successfully and publishes a valid token while invocation B throws, B's catch wipes A's result — transiently reporting a signed-in user as signed out. Callers that sampled auth in between will render the signed-out state, and the browse surfaces will treat it as an auth flip worth invalidating results over.
Before #116 there was no catch at all, so the exception propagated instead. That was a crash rather than a silent wipe, which is why the clobbering is new even though the missing synchronization is not.
How concurrent entry happens
GetAccessTokenAsync is called from ten sites across six page models, most from OnAppearing paths, plus the background airing-notification work. Tab switches are sequential, but a page appearing while background work is already in flight is not.
Proposal
Serialize the first load and re-check inside the gate, so only one invocation ever performs it:
private readonly SemaphoreSlim _loadGate = new(1, 1);
private async Task LoadAsync(CancellationToken cancellationToken)
{
await _loadGate.WaitAsync(cancellationToken);
try
{
if (AccessToken is not null)
{
return; // another caller already loaded it
}
// ... existing read + catch ...
}
finally
{
_loadGate.Release();
}
}The double-check is most of the fix — the second caller returns without reading, so it has nothing to fail at and nothing to clear — but on its own it is not enough, and the agreed plan does two more things.
AccessToken is also null for a signed-out user, and nothing records that a load has happened, so AccessToken is not null is false for the second caller whenever SecureStorage holds no token: both callers read, which fails the first acceptance criterion below. The gate therefore carries a separate _loaded flag rather than re-testing the token.
And reading into locals is not an alternative but a second requirement. LoadAsync assigns AccessToken at :172 before reading the expiry at :173, so a caller reaching the AccessToken is null check at :24 in between sees a token whose ExpiresAt has not been read — and IsExpired() returns false for a null expiry. Both values are read into locals and published together inside the gate.
Note WaitAsync(cancellationToken) can throw OperationCanceledException, which is correct — that is the caller's own cancellation, and matches the filtered rethrow already in place.
Notes
Found by review on #116. #62 has since closed, and the plan agreed here takes the split described in the comment below: the token state, the load gate and the expiry check move to a Core TokenStore behind an ISecureTokenStorage seam, with MauiSecureTokenStorage in src/AniSprinkles/Services/Maui/. AuthService keeps WebAuthenticator and CookieManager and delegates token state. IAuthService is unchanged, so CIAuthService and SimAuthService need no edits. All three acceptance criteria below become ordinary tests.
Acceptance
- Concurrent
GetAccessTokenAsynccalls on a coldAccessTokenperform exactly one SecureStorage read. - A failing read cannot clear token state published by a successful one.
- Cancellation still propagates to the caller that owns the token.
Activity
zhollis21 commentedon Aug 22, 2026
Correcting a claim I made while planning #62
While scoping #62 I said this issue was not unblocked by the Core extraction, because
AuthServiceusesAndroid.Webkitand stays in the MAUI app project. The first half is true and it did stay there — but the conclusion was too strong, and it is worth writing down before someone takes it at face value.The platform dependency is narrower than the class
AuthServicetouches three platform things:WebAuthenticator— the OAuth round tripAndroid.Webkit.CookieManager— clearing cookies on sign-outSecureStorage— token + expiry persistenceNone of those are the subject of this issue. What this issue is about is the concurrency contract around the token: single-flight the first load, publish once, and never let a failing read clear state a successful one already published. That is pure state-machine logic over an async read, and it has no Android in it.
The shape that makes it testable
Split along that line:
AuthServicekeepsWebAuthenticator+CookieManagerand delegates token state toTokenStore;MauiSecureTokenStorageinsrc/AniSprinkles/Services/Maui/wrapsSecureStorage.Default, alongside the other adapters #62 added.Then this issue's acceptance criteria become ordinary tests:
GetAccessTokenAsynccalls on a cold token perform exactly one read" — a gated fake storage, two concurrent callers, assert one call.Recommendation
The
SemaphoreSlimfix in the proposal above is still right and still ~10 lines. But landing it without the split means shipping a concurrency fix with no executable check — which is the exact pattern #62's evidence comment catalogued, where three of six #116 defects were regressions introduced by the previous round's fix. The split is maybe an hour and turns all three acceptance criteria into tests.zhollis21 commentedon Aug 24, 2026
Verification notes (kickoff)
Re-checked against
origin/main@57f4d4e. Everything the body describes is still present.The code is unchanged.
AuthServiceis still registered singleton —MauiProgram.cs:135.GetAccessTokenAsyncstill callsLoadAsyncon an unsynchronizedAccessToken is nullcheck —AuthService.cs:24-27.LoadAsyncstill has no gate, and its fallback catch still assignsAccessToken = null; ExpiresAt = null—AuthService.cs:162-198, catch at:192-197.Two more observations about
LoadAsyncworth having on the record.AccessTokenis assigned atAuthService.cs:172,ExpiresAtat:173-177. A concurrent caller reaching theAccessToken is nullcheck at:24in between sees a non-null token whoseExpiresAthas not been read, andIsExpired()(:200) returns false for a nullExpiresAt.AccessTokenstays null when SecureStorage holds no token, andSignOutAsync(:119) sets it back to null. SoAccessToken is nullat:24is true on every call for a signed-out user, and a null-check inside a gate is still true for the second caller.#62 is closed and the seam the comment above describes exists.
490fdd5).src/AniSprinkles.Core/is in place.src/AniSprinkles/Services/Maui/exists and holds four adapters —MauiDialogService,MauiExternalBrowser,MauiShellNavigationService,MauiUserFeedback— matching the layout the plan comment names forMauiSecureTokenStorage.AuthService.csis still undersrc/AniSprinkles/Services/, i.e. the MAUI app project, whichtests/does not reference.AniSprinkles.Core/Services/Abstractions/holds the existing seam interfaces.tests/AniSprinkles.UnitTests/now has 50 files, including page-model tests, so the "untestable under the current setup" note in the body is out of date as a general statement — it is specific toAuthService's project, not to the test suite.zhollis21 commentedon Aug 24, 2026
Updated during planning. Two corrections to the proposal:
_loadedflag, not onAccessToken is not null. The token is also null when the user is signed out, so the null re-test lets both callers read and misses the first acceptance criterion.LoadAsyncpublishesAccessTokenone line before it reads the expiry, so a caller can observe a token with noExpiresAtloaded andIsExpired()returns false for that.The Notes section is also updated: #62 has closed, so this ships as a Core
TokenStorebehind anISecureTokenStorageseam and the acceptance criteria become tests rather than being unverifiable.Token load races, display-setting re-rendering, and settings-save dur…
Token load races, display-setting re-rendering, and settings-save dur…