RUBY-3604 Fix multithread auth race condition #2912
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.
Fixes: https://jira.mongodb.org/browse/RUBY-3604
This PR fixes a race-condition that we occasionally see when multiple threads are simultaneously authenticating with the database.
Details of the failure:
While the cache is being written to, the value will go through a phase, such that if it is retrieved a particular moment, it will return false (value is never actually set to false by the code, somehow the underlying Ruby code behaves this way). The cache code does check if the value is nil, but will consider the value false to be a cache hit. As a result, The methods client_key and server_key in scram_conversion_base.rb may incorrectly return false instead of the value from the block. This will result in an error "no implicit conversion of false into String" when attempting to use the "false" value for authentication.
In our testing, we found that protecting the cache with a mutex resolves this problem.
Of note is that the two other caches in this library are already made theadsafe. These are Mongo::Auth::Aws::CredentialsCache (auth/aws/credentials_cache.rb) [not to be confused with Mongo::Auth::CredentialCache] which is protected with a Mutex and Mongo::QueryCache (query_cache.rb) which is protected with a ThreadLocal variable.