From 44112aa12dbf916576415ef565029d228f4d311e Mon Sep 17 00:00:00 2001 From: Tobias Macey Date: Thu, 22 Aug 2024 06:43:15 -0400 Subject: [PATCH] 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. --- xmodule/mongo_utils.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/xmodule/mongo_utils.py b/xmodule/mongo_utils.py index b86abd28b466..5aecbfc405df 100644 --- a/xmodule/mongo_utils.py +++ b/xmodule/mongo_utils.py @@ -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)