fix: Respect the authsource kwarg for MongoDB connections (#35239)

* fix: Respect the authsource kwarg for MongoDB connections

The changes for upgrading to PyMongo 4.4 introduced an authentication
bug in Mongo connections. The `authSource` parameter was being
hard-coded to use the database being connected to. In Mongo the `admin`
db is typically the source of authentication, so unless the user was
explicitly created in the target db then any attempts to connect would
result in authentication failures.

This restores the behavior of allowing for the lowercased `authsource`
kwarg to be used for the `authSource` connection parameter, while
otherwise respecting the operator's configuration parameters.

* fix: Respect the authsource kwarg for MongoDB connections

The changes for upgrading to PyMongo 4.4 introduced an authentication
bug in Mongo connections. The `authSource` parameter was being
hard-coded to use the database being connected to. In Mongo the `admin`
db is typically the source of authentication, so unless the user was
explicitly created in the target db then any attempts to connect would
result in authentication failures.

This restores the behavior of allowing for the lowercased `authsource`
kwarg to be used for the `authSource` connection parameter, while
otherwise respecting the operator's configuration parameters.
This commit is contained in:
Tobias Macey
2024-08-22 06:43:15 -04:00
committed by GitHub
parent f93d16f31a
commit 44112aa12d

View File

@@ -30,8 +30,11 @@ def connect_to_mongodb(
handles AutoReconnect errors by retrying read operations, since these exceptions
typically indicate a temporary step-down condition for MongoDB.
"""
# If the MongoDB server uses a separate authentication database that should be specified here
auth_source = kwargs.get('authsource', '') or None
# If the MongoDB server uses a separate authentication database that should be specified here.
# Convert the lowercased authsource parameter to the camel-cased authSource expected by MongoClient.
auth_source = db
if auth_source_key := {'authSource', 'authsource'}.intersection(set(kwargs.keys())):
auth_source = kwargs.pop(auth_source_key.pop()) or db
# sanitize a kwarg which may be present and is no longer expected
# AED 2020-03-02 TODO: Remove this when 'auth_source' will no longer exist in kwargs
@@ -63,7 +66,7 @@ def connect_to_mongodb(
}
if user is not None and password is not None and not db.startswith('test_'):
connection_params.update({'username': user, 'password': password, 'authSource': db})
connection_params.update({'username': user, 'password': password, 'authSource': auth_source})
mongo_conn = pymongo.MongoClient(**connection_params)