Skip to content

Conversation

@4gust
Copy link
Collaborator

@4gust 4gust commented Aug 28, 2025

PR: Fix Concurrent Cache Access in AcquireToken Method

Summary

This PR addresses a potential race condition in the AcquireToken method by properly synchronizing access to the cache using a mutex. Issue number #569


Changes

  • Introduced cacheAccessorMu.Lock() / defer cacheAccessorMu.Unlock() around cache operations to ensure thread-safe access.
  • Removed the canRefresh atomic variable, which was previously used to prevent concurrent refreshes which is no longer needed as whole cache is in mutex

Testing

  • Validated using the existing TestAcquireTokenConcurrency unit test to ensure correct behavior under concurrent conditions.

Breaking Changes

  • None. This is an internal, non-breaking implementation change that does not affect the public API.

@4gust 4gust requested review from bgavrilMS and rayluo as code owners August 28, 2025 14:49
@4gust 4gust requested a review from chlowell August 28, 2025 14:49
@sonarqubecloud
Copy link

httpClient: shared.DefaultClient,
retryPolicyEnabled: true,
source: source,
canRefresh: &zero,
Copy link
Contributor

Choose a reason for hiding this comment

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

Also remove the declaration of zero

Comment on lines +1297 to +1299
for err := range errors {
t.Error(err)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider this approach instead. If there were 100 identical errors, would you want to see all of them in go test output?


// Mock client should only need to respond once if caching works correctly
mockClient := mock.NewClient()
// Add multiple responses in case caching fails (but we'll verify it doesn't)
Copy link
Contributor

Choose a reason for hiding this comment

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

if you simply appended 1 response the mock would panic when it gets a second request and you wouldn't have to count the requests yourself

return
}

// Capture the token received
Copy link
Contributor

Choose a reason for hiding this comment

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

why? There can only be one token because the mock client returns a static value, and you don't need this to know whether the goroutine succeeded because if it didn't it would have written an error to the channel

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.

[Bug] Concurrent managedidentity.Client.AcquireToken() calls cause multiple token requests to identity provider before caching

4 participants