|
| 1 | +# Copyright 2026-present MongoDB, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Test connectivity and authentication through an Atlas Secure Frontend Processor (SFP/Monguard).""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import os |
| 20 | +import sys |
| 21 | +import unittest |
| 22 | +from typing import Any |
| 23 | + |
| 24 | +import pytest |
| 25 | + |
| 26 | +sys.path[0:0] = [""] |
| 27 | + |
| 28 | +from bson import ObjectId |
| 29 | +from pymongo.asynchronous.mongo_client import AsyncMongoClient |
| 30 | +from pymongo.server_api import ServerApi |
| 31 | +from test.asynchronous import AsyncPyMongoTestCase |
| 32 | + |
| 33 | +_IS_SYNC = False |
| 34 | + |
| 35 | +pytestmark = pytest.mark.sfp |
| 36 | + |
| 37 | +# Each authenticated test must run under each of these variations: |
| 38 | +# no additional configuration, a compressor enabled, and Server API v1. |
| 39 | +VARIATIONS: dict[str, dict[str, Any]] = { |
| 40 | + "baseline": {}, |
| 41 | + "compressor": {"compressors": "zlib"}, |
| 42 | + "server_api": {"server_api": ServerApi("1")}, |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +def _require_env(name: str) -> str: |
| 47 | + value = os.environ.get(name) |
| 48 | + if not value: |
| 49 | + raise Exception(f"Must set {name} env variable to test.") |
| 50 | + return value |
| 51 | + |
| 52 | + |
| 53 | +class TestAtlasSFP(AsyncPyMongoTestCase): |
| 54 | + async def assert_ping(self, client: AsyncMongoClient) -> None: |
| 55 | + response = await client.admin.command("ping") |
| 56 | + self.assertEqual(response["ok"], 1) |
| 57 | + |
| 58 | + async def assert_connection_status(self, client: AsyncMongoClient, authenticated: bool) -> None: |
| 59 | + response = await client.admin.command("connectionStatus") |
| 60 | + self.assertEqual(response["ok"], 1) |
| 61 | + users = response["authInfo"]["authenticatedUsers"] |
| 62 | + if authenticated: |
| 63 | + self.assertGreaterEqual(len(users), 1) |
| 64 | + else: |
| 65 | + self.assertEqual(users, []) |
| 66 | + |
| 67 | + async def assert_crud(self, client: AsyncMongoClient) -> None: |
| 68 | + # Use a unique collection name for each test run and drop it |
| 69 | + # afterward, regardless of test success or failure. |
| 70 | + collection = client.db[f"sfp_test_{ObjectId()}"] |
| 71 | + self.addAsyncCleanup(collection.drop) |
| 72 | + result = await collection.insert_one({"_id": 0}) |
| 73 | + self.assertEqual(result.inserted_id, 0) |
| 74 | + document = await collection.find_one({"_id": 0}) |
| 75 | + self.assertEqual(document, {"_id": 0}) |
| 76 | + |
| 77 | + async def test_unauthenticated(self): |
| 78 | + client = self.simple_client(_require_env("SFP_ATLAS_URI")) |
| 79 | + await self.assert_ping(client) |
| 80 | + await self.assert_connection_status(client, authenticated=False) |
| 81 | + |
| 82 | + async def test_scram_sha_256(self): |
| 83 | + uri = _require_env("SFP_ATLAS_URI") |
| 84 | + username = _require_env("SFP_ATLAS_USER") |
| 85 | + password = _require_env("SFP_ATLAS_PASSWORD") |
| 86 | + for variation, kwargs in VARIATIONS.items(): |
| 87 | + with self.subTest(variation=variation): |
| 88 | + client = self.simple_client( |
| 89 | + uri, |
| 90 | + username=username, |
| 91 | + password=password, |
| 92 | + authMechanism="SCRAM-SHA-256", |
| 93 | + **kwargs, |
| 94 | + ) |
| 95 | + await self.assert_ping(client) |
| 96 | + await self.assert_connection_status(client, authenticated=True) |
| 97 | + await self.assert_crud(client) |
| 98 | + |
| 99 | + async def test_x509(self): |
| 100 | + uri = _require_env("SFP_ATLAS_X509_URI") |
| 101 | + cert = _require_env("SFP_ATLAS_X509_CERT") |
| 102 | + for variation, kwargs in VARIATIONS.items(): |
| 103 | + with self.subTest(variation=variation): |
| 104 | + client = self.simple_client(uri, tlsCertificateKeyFile=cert, **kwargs) |
| 105 | + await self.assert_ping(client) |
| 106 | + await self.assert_connection_status(client, authenticated=True) |
| 107 | + await self.assert_crud(client) |
| 108 | + |
| 109 | + |
| 110 | +if __name__ == "__main__": |
| 111 | + unittest.main() |
0 commit comments