Skip to content

fix(msal): stop re-probing the secure store on every launch - #3166

Merged
kazo0 merged 1 commit into
dev/sb/auth-providers-fixesfrom
dev/sb/msal-cache-persistence-check
Aug 26, 2026
Merged

kazo0 merged 1 commit into
dev/sb/auth-providers-fixesfrom
dev/sb/msal-cache-persistence-check

Conversation

@kazo0

@kazo0 kazo0 commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

GitHub Issue (If applicable): closes #

Stacked on dev/sb/auth-providers-fixes — this fix builds on MsalStorageDefaults and AllowUnprotectedTokenCacheFallback, neither of which is on main yet.

PR Type

  • Bugfix

What is the current behavior?

MsalAuthenticationProvider.SetupStorageCore calls MsalCacheHelper.VerifyPersistence() on every storage setup. The check writes, reads and deletes a probe entry in the platform's secure store, so it costs three round-trips per app start.

On macOS it can never be granted once and for all. MSAL's validation accessor builds its probe entry with a fresh Guid in the keychain service name:

// MacKeychainAccessor.CreateForPersistenceValidation(), Microsoft.Identity.Client.Extensions.Msal
new MacKeychainAccessor(_cacheFilePath + ".test", _service + Guid.NewGuid(), _account, _logger)

macOS gates keychain access with a per-item ACL, so an entry that never has the same name twice is a first-ever access every time. The user is prompted, answers Always Allow, the entry is deleted at the end of the check, and the next launch asks again — three prompts on every single start, with no way to make them stop.

What is the new behavior?

The check runs once per cache location instead of once per launch, and the guarantee it was providing is preserved by a cheaper mechanism.

It could not simply be deleted: it was the only thing reporting a broken store, because MsalCacheHelper handles the two directions differently. Storage.ReadData() rethrows, but AfterAccessNotification catches and logs "Could not write the token cache. Ignoring." Dropping the check would have traded a startup error for silent loss of the refresh token.

Two properties of the accessors make the replacement possible:

  1. Every ICacheAccessor.Write ends in FileIOWithRetries.TouchFile(_cacheFilePath), so the cache file tracks whether a write landed — on macOS too, where the payload lives in the keychain.
  2. TokenCache.OnAfterAccessAsync invokes the synchronous TokenCacheCallback and then the asynchronous one. RegisterCache uses only the synchronous slots, so the provider can attach SetAfterAccessAsync without displacing it.

Hence:

  • MsalConfiguration.VerifyCachePersistence — Auto (default), Always, Never. The decision lives in MsalStorageDefaults.ShouldVerifyPersistence(mode, cacheAlreadyPersisted) as a pure function; the provider supplies cacheAlreadyPersisted from File.Exists.
  • ArmWriteVerification / OnAfterCacheAccessAsync — confirm the first state-changing write reached the store. If it did not, log an error and null _setupStorageTask so the next SetupStorage rebuilds; that rebuild sees no cache file, so it probes even under Auto and either recovers or takes the AllowUnprotectedTokenCacheFallback path.
  • The unprotected-file fallback still verifies unconditionally — it only runs because the protected store already failed, and a plain file carries none of the cost that justifies skipping.

Steady-state macOS launches now make zero extra secure-store round-trips.

specs/015-msal-cache-persistence-check/spec.md records the design, the IL evidence behind each claim, and the risks (chiefly that TouchFile-on-write is an MSAL implementation detail rather than a contract; if it ever goes away, Auto degrades to "never probe" and the write watchdog fires loudly rather than silently).

Verification

Measured on the net10.0-desktop head of Uno.Samples/UI/Authentication.MsalExtensionsDemo on macOS 26.5.2:

Before After
Keychain prompts at startup 3 0
Keychain item mdat advances yes yes — cache still read and written
SecurityAgent (macOS prompt UI) spawned yes never

Also confirms the change is inert where it should be: the packed lib/net9.0-browserwasm1.0 assembly contains only the new enum, not the provider methods, so the #if !UNO_EXT_MSAL_NOSTORAGE guard keeps it out of the WebAssembly path.

PR Checklist

  • Tested code with current supported SDKs
  • Docs have been added/updated which fit documentation template (for bug fixes / features)
  • Unit Tests and/or UI Tests for the changes have been added (for bug fixes / features) (if applicable)
  • Wasm UI Tests are not showing unexpected any differences. Validate PR Screenshots Compare Test Run results.
  • Contains NO breaking changes
  • Updated the Release Notes

Notes on the checklist:

  • Tests — Given_MsalStorageDefaults gains 5 cases covering the decision table (Auto both ways, Always, Never) and pinning Auto as both the configuration default and default(MsalCachePersistenceCheck). dotnet test on Uno.Extensions.Authentication.MSAL.Tests: 44 passed, 0 failed. MsalCachePersistenceCheck.cs is linked into that project alongside the other MSAL sources.
  • Docs — HowTo-MsalAuthentication.md documents the setting and its table; UpdatingExtensions.md carries the behavior-change entry alongside the other MSAL 7.0 changes.
  • No breaking changes — additive configuration with a default that only reduces work. Always restores the previous behavior exactly.
  • Wasm UI Tests — unchecked pending CI; the change is compiled out of the WebAssembly path, so no snapshot movement is expected.

🤖 Generated with Claude Code

https://claude.ai/code/session_01RhtkcHHpbm6XiDagFY6VaS

MsalCacheHelper.VerifyPersistence() ran on every storage setup, costing a
write, a read and a delete against the platform's secure store per app start.

On macOS it could never be granted once and for all. MSAL's validation
accessor builds its probe entry with a fresh Guid in the keychain service
name:

    // MacKeychainAccessor.CreateForPersistenceValidation()
    new MacKeychainAccessor(_cacheFilePath + ".test",
                            _service + Guid.NewGuid(), _account, _logger)

macOS gates keychain access with a per-item ACL, so an entry that never has
the same name twice is a first-ever access every time: the user is prompted,
answers "Always Allow", the entry is deleted at the end of the check, and the
next launch asks again. Three prompts on every start, with no way to make
them stop.

The call could not simply be dropped. It was the only thing reporting a
broken store, because MsalCacheHelper handles the two directions
differently: Storage.ReadData() rethrows, but AfterAccessNotification catches
and logs "Could not write the token cache. Ignoring." Removing the check
would have traded a startup error for silent loss of the refresh token.

Two properties of the accessors make a cheaper equivalent possible. Every
ICacheAccessor.Write ends in FileIOWithRetries.TouchFile(_cacheFilePath), so
the cache file tracks whether a write landed - on macOS too, where the
payload lives in the keychain. And TokenCache.OnAfterAccessAsync invokes the
synchronous callback and then the asynchronous one, so the provider can
attach SetAfterAccessAsync without displacing RegisterCache.

So:

- MsalConfiguration.VerifyCachePersistence (Auto default, Always, Never),
  with the decision in MsalStorageDefaults.ShouldVerifyPersistence as a pure
  function; the provider supplies cacheAlreadyPersisted from File.Exists.
- ArmWriteVerification / OnAfterCacheAccessAsync confirm the first
  state-changing write reached the store and, when it did not, log and reset
  _setupStorageTask so the next setup rebuilds - probing even under Auto,
  since the file is missing, and taking the
  AllowUnprotectedTokenCacheFallback path if the store is genuinely broken.
- The unprotected-file fallback still verifies unconditionally: it only runs
  because the protected store already failed, and a plain file carries none
  of the cost that justifies skipping.

Steady-state macOS launches now make zero extra secure-store round-trips.
Verified on the net10.0-desktop head of Authentication.MsalExtensionsDemo:
three keychain prompts at startup before, none after, with the keychain
item's mdat still advancing so the cache is demonstrably read and written.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RhtkcHHpbm6XiDagFY6VaS
@mergify

mergify Bot commented Aug 26, 2026

Copy link
Copy Markdown

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@kazo0
kazo0 merged commit 9153dd1 into dev/sb/auth-providers-fixes Aug 26, 2026
5 checks passed
@kazo0
kazo0 deleted the dev/sb/msal-cache-persistence-check branch August 26, 2026 17:41
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.

1 participant