PYTHON-4301 Fix MONGODB-AWS credential caching (#1562)

This commit is contained in:
Steven Silvester 2024-03-27 12:37:53 -05:00 committed by GitHub
parent 3699f513fa
commit 9a206a3896
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 4 deletions

View File

@ -44,6 +44,14 @@ def _authenticate_aws(credentials: MongoCredential, conn: Connection) -> None:
"install with: python -m pip install 'pymongo[aws]'"
)
# Delayed import.
from pymongo_auth_aws.auth import ( # type:ignore[import]
set_cached_credentials,
set_use_cached_credentials,
)
set_use_cached_credentials(True)
if conn.max_wire_version < 9:
raise ConfigurationError("MONGODB-AWS authentication requires MongoDB version 4.4 or later")
@ -87,12 +95,12 @@ def _authenticate_aws(credentials: MongoCredential, conn: Connection) -> None:
break
except pymongo_auth_aws.PyMongoAuthAwsError as exc:
# Clear the cached credentials if we hit a failure in auth.
pymongo_auth_aws.set_cached_credentials(None)
set_cached_credentials(None)
# Convert to OperationFailure and include pymongo-auth-aws version.
raise OperationFailure(
f"{exc} (pymongo-auth-aws version {pymongo_auth_aws.__version__})"
) from None
except Exception:
# Clear the cached credentials if we hit a failure in auth.
pymongo_auth_aws.set_cached_credentials(None)
set_cached_credentials(None)
raise

View File

@ -60,8 +60,13 @@ class TestAuthAWS(unittest.TestCase):
def setup_cache(self):
if os.environ.get("AWS_ACCESS_KEY_ID", None) or "@" in self.uri:
self.skipTest("Not testing cached credentials")
if not hasattr(auth, "set_cached_credentials"):
self.skipTest("Cached credentials not available")
# Make a connection to ensure that we enable caching.
client = MongoClient(self.uri)
client.get_database().test.find_one()
client.close()
self.assertTrue(auth.get_use_cached_credentials())
# Ensure cleared credentials.
auth.set_cached_credentials(None)