Skip to content

Commit 9a206a3

Browse files
authored
PYTHON-4301 Fix MONGODB-AWS credential caching (#1562)
1 parent 3699f51 commit 9a206a3

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

pymongo/auth_aws.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ def _authenticate_aws(credentials: MongoCredential, conn: Connection) -> None:
4444
"install with: python -m pip install 'pymongo[aws]'"
4545
)
4646

47+
# Delayed import.
48+
from pymongo_auth_aws.auth import ( # type:ignore[import]
49+
set_cached_credentials,
50+
set_use_cached_credentials,
51+
)
52+
53+
set_use_cached_credentials(True)
54+
4755
if conn.max_wire_version < 9:
4856
raise ConfigurationError("MONGODB-AWS authentication requires MongoDB version 4.4 or later")
4957

@@ -87,12 +95,12 @@ def bson_decode(self, data: _ReadableBuffer) -> Mapping[str, Any]:
8795
break
8896
except pymongo_auth_aws.PyMongoAuthAwsError as exc:
8997
# Clear the cached credentials if we hit a failure in auth.
90-
pymongo_auth_aws.set_cached_credentials(None)
98+
set_cached_credentials(None)
9199
# Convert to OperationFailure and include pymongo-auth-aws version.
92100
raise OperationFailure(
93101
f"{exc} (pymongo-auth-aws version {pymongo_auth_aws.__version__})"
94102
) from None
95103
except Exception:
96104
# Clear the cached credentials if we hit a failure in auth.
97-
pymongo_auth_aws.set_cached_credentials(None)
105+
set_cached_credentials(None)
98106
raise

test/auth_aws/test_auth_aws.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,13 @@ def test_connect_uri(self):
6060
def setup_cache(self):
6161
if os.environ.get("AWS_ACCESS_KEY_ID", None) or "@" in self.uri:
6262
self.skipTest("Not testing cached credentials")
63-
if not hasattr(auth, "set_cached_credentials"):
64-
self.skipTest("Cached credentials not available")
63+
64+
# Make a connection to ensure that we enable caching.
65+
client = MongoClient(self.uri)
66+
client.get_database().test.find_one()
67+
client.close()
68+
69+
self.assertTrue(auth.get_use_cached_credentials())
6570

6671
# Ensure cleared credentials.
6772
auth.set_cached_credentials(None)

0 commit comments

Comments
 (0)