Skip to content

AuthService.LoadAsync races on concurrent first-token reads and can wipe a valid token #119

Closed

Description

@zhollis21

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 GetAccessTokenAsync calls on a cold AccessToken perform 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

  1. added
    bug
    p3-medium
    on Aug 22, 2026
  2. zhollis21 commented on Aug 22, 2026

    @zhollis21
    OwnerAuthor

    Correcting a claim I made while planning #62

    While scoping #62 I said this issue was not unblocked by the Core extraction, because AuthService uses Android.Webkit and 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

    AuthService touches three platform things:

    • WebAuthenticator — the OAuth round trip
    • Android.Webkit.CookieManager — clearing cookies on sign-out
    • SecureStorage — token + expiry persistence

    None 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:

    // Core — the logic this issue is about
    public sealed class TokenStore(ISecureTokenStorage storage, ILogger<TokenStore> logger)
    {
        private readonly SemaphoreSlim _loadGate = new(1, 1);
        // AccessToken / ExpiresAt, LoadAsync with the double-check inside the gate
    }
    
    // Core — the seam
    public interface ISecureTokenStorage
    {
        Task<string?> GetAsync(string key);
        Task SetAsync(string key, string value);
        void Remove(string key);
    }

    AuthService keeps WebAuthenticator + CookieManager and delegates token state to TokenStore; MauiSecureTokenStorage in src/AniSprinkles/Services/Maui/ wraps SecureStorage.Default, alongside the other adapters #62 added.

    Then this issue's acceptance criteria become ordinary tests:

    • "Concurrent GetAccessTokenAsync calls on a cold token perform exactly one read" — a gated fake storage, two concurrent callers, assert one call.
    • "A failing read cannot clear token state published by a successful one" — first read succeeds, second throws, assert the token survives. This is the actual reported bug and it is the one that is impossible to reach today.
    • "Cancellation still propagates to the caller that owns the token" — cancel one caller's token, assert the other completes.

    Recommendation

    The SemaphoreSlim fix 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.

  3. zhollis21 commented on Aug 24, 2026

    @zhollis21
    OwnerAuthor

    Verification notes (kickoff)

    Re-checked against origin/main @ 57f4d4e. Everything the body describes is still present.

    The code is unchanged.

    • AuthService is still registered singleton — MauiProgram.cs:135.
    • GetAccessTokenAsync still calls LoadAsync on an unsynchronized AccessToken is null check — AuthService.cs:24-27.
    • LoadAsync still has no gate, and its fallback catch still assigns AccessToken = null; ExpiresAt = null — AuthService.cs:162-198, catch at :192-197.

    Two more observations about LoadAsync worth having on the record.

    • The read publishes to the shared property before the expiry is read: AccessToken is assigned at AuthService.cs:172, ExpiresAt at :173-177. A concurrent caller reaching the AccessToken is null check at :24 in between sees a non-null token whose ExpiresAt has not been read, and IsExpired() (:200) returns false for a null ExpiresAt.
    • Nothing records that a load has happened — AccessToken stays null when SecureStorage holds no token, and SignOutAsync (:119) sets it back to null. So AccessToken is null at :24 is 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.

    • Extract AniSprinkles.Core class library to unblock PageModel/Services unit tests #62 closed, merged as Extract AniSprinkles.Core so PageModels can be tested (#62, #117) #123 (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 for MauiSecureTokenStorage.
    • AuthService.cs is still under src/AniSprinkles/Services/, i.e. the MAUI app project, which tests/ 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 to AuthService's project, not to the test suite.
  4. zhollis21 commented on Aug 24, 2026

    @zhollis21
    OwnerAuthor

    Updated during planning. Two corrections to the proposal:

    • The double-check is now on a _loaded flag, not on AccessToken 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.
    • Reading into locals is not an alternative to the gate, it is part of the fix. LoadAsync publishes AccessToken one line before it reads the expiry, so a caller can observe a token with no ExpiresAt loaded and IsExpired() returns false for that.

    The Notes section is also updated: #62 has closed, so this ships as a Core TokenStore behind an ISecureTokenStorage seam and the acceptance criteria become tests rather than being unverifiable.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugp3-medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions