|
| 1 | +# The MIT License (MIT) |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + |
| 4 | +# cspell:ignore reranker |
| 5 | +"""Regression test for lazy initialization of _InferenceService with AAD credentials. |
| 6 | +
|
| 7 | +Verifies that constructing a CosmosClient with AAD credentials does not crash |
| 8 | +when AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT is not set. |
| 9 | +""" |
| 10 | +import base64 |
| 11 | +import json |
| 12 | +import os |
| 13 | +import time |
| 14 | +import unittest |
| 15 | +from io import StringIO |
| 16 | + |
| 17 | +import pytest |
| 18 | +from azure.core.credentials import AccessToken |
| 19 | + |
| 20 | +import azure.cosmos.cosmos_client as cosmos_client |
| 21 | +import test_config |
| 22 | +from azure.cosmos import DatabaseProxy, ContainerProxy |
| 23 | + |
| 24 | + |
| 25 | +def _remove_padding(encoded_string): |
| 26 | + while encoded_string.endswith("="): |
| 27 | + encoded_string = encoded_string[0:len(encoded_string) - 1] |
| 28 | + return encoded_string |
| 29 | + |
| 30 | + |
| 31 | +def get_test_item(num): |
| 32 | + test_item = { |
| 33 | + 'pk': 'pk', |
| 34 | + 'id': 'LazyInit_' + str(num), |
| 35 | + 'test_object': True, |
| 36 | + } |
| 37 | + return test_item |
| 38 | + |
| 39 | + |
| 40 | +class CosmosEmulatorCredential(object): |
| 41 | + """Fake AAD credential for the Cosmos emulator.""" |
| 42 | + def get_token(self, *scopes, **kwargs): |
| 43 | + aad_header_cosmos_emulator = "{\"typ\":\"JWT\",\"alg\":\"RS256\",\"x5t\":\"" \ |
| 44 | + "CosmosEmulatorPrimaryMaster\",\"kid\":\"CosmosEmulatorPrimaryMaster\"}" |
| 45 | + aad_claim_cosmos_emulator_format = { |
| 46 | + "aud": "https://localhost.localhost", |
| 47 | + "iss": "https://sts.fake-issuer.net/7b1999a1-dfd7-440e-8204-00170979b984", |
| 48 | + "iat": int(time.time()), "nbf": int(time.time()), |
| 49 | + "exp": int(time.time() + 7200), "aio": "", "appid": "localhost", |
| 50 | + "appidacr": "1", "idp": "https://localhost:8081/", |
| 51 | + "oid": "96313034-4739-43cb-93cd-74193adbe5b6", "rh": "", "sub": "localhost", |
| 52 | + "tid": "EmulatorFederation", "uti": "", "ver": "1.0", |
| 53 | + "scp": "user_impersonation", |
| 54 | + "groups": ["7ce1d003-4cb3-4879-b7c5-74062a35c66e", |
| 55 | + "e99ff30c-c229-4c67-ab29-30a6aebc3e58", |
| 56 | + "5549bb62-c77b-4305-bda9-9ec66b85d9e4", |
| 57 | + "c44fd685-5c58-452c-aaf7-13ce75184f65", |
| 58 | + "be895215-eab5-43b7-9536-9ef8fe130330"]} |
| 59 | + emulator_key = test_config.TestConfig.masterKey |
| 60 | + first = _remove_padding(str(base64.urlsafe_b64encode(aad_header_cosmos_emulator.encode("utf-8")), "utf-8")) |
| 61 | + str_io_obj = StringIO() |
| 62 | + json.dump(aad_claim_cosmos_emulator_format, str_io_obj) |
| 63 | + second = _remove_padding( |
| 64 | + str(base64.urlsafe_b64encode(str(str_io_obj.getvalue()).replace(" ", "").encode("utf-8")), "utf-8")) |
| 65 | + third = _remove_padding(str(base64.urlsafe_b64encode(emulator_key.encode("utf-8")), "utf-8")) |
| 66 | + return AccessToken(first + "." + second + "." + third, int(time.time() + 7200)) |
| 67 | + |
| 68 | + |
| 69 | +@pytest.mark.cosmosEmulator |
| 70 | +@pytest.mark.cosmosLong |
| 71 | +class TestAADInferenceServiceLazyInit(unittest.TestCase): |
| 72 | + """Verify AAD client construction succeeds without the semantic reranker env var. |
| 73 | +
|
| 74 | + Before the fix, _InferenceService was eagerly initialized during CosmosClient |
| 75 | + construction whenever AAD credentials were used, causing a ValueError if |
| 76 | + AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT was missing. |
| 77 | + """ |
| 78 | + |
| 79 | + client: cosmos_client.CosmosClient = None |
| 80 | + database: DatabaseProxy = None |
| 81 | + container: ContainerProxy = None |
| 82 | + configs = test_config.TestConfig |
| 83 | + host = configs.host |
| 84 | + masterKey = configs.masterKey |
| 85 | + credential = CosmosEmulatorCredential() if configs.is_emulator else configs.credential |
| 86 | + |
| 87 | + def setUp(self): |
| 88 | + """Save the env var state before each test.""" |
| 89 | + self._saved_endpoint = os.environ.get("AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT") |
| 90 | + |
| 91 | + def tearDown(self): |
| 92 | + """Ensure the env var is always unset after each test to prevent leakage.""" |
| 93 | + os.environ.pop("AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT", None) |
| 94 | + |
| 95 | + def test_aad_client_construction_without_inference_endpoint(self): |
| 96 | + """Constructing a CosmosClient with AAD creds must not raise when |
| 97 | + AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT is unset.""" |
| 98 | + os.environ.pop("AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT", None) |
| 99 | + |
| 100 | + client = cosmos_client.CosmosClient(self.host, self.credential) |
| 101 | + db = client.get_database_client(self.configs.TEST_DATABASE_ID) |
| 102 | + container = db.get_container_client(self.configs.TEST_SINGLE_PARTITION_CONTAINER_ID) |
| 103 | + |
| 104 | + item = get_test_item(0) |
| 105 | + container.create_item(item) |
| 106 | + read_result = container.read_item(item=item['id'], partition_key='pk') |
| 107 | + assert read_result['id'] == item['id'] |
| 108 | + |
| 109 | + query_results = list(container.query_items( |
| 110 | + query='SELECT * FROM c WHERE c.id=@id', |
| 111 | + parameters=[{"name": "@id", "value": item['id']}], |
| 112 | + partition_key='pk' |
| 113 | + )) |
| 114 | + assert len(query_results) == 1 |
| 115 | + |
| 116 | + container.delete_item(item=item['id'], partition_key='pk') |
| 117 | + |
| 118 | + def test_aad_client_construction_with_inference_endpoint(self): |
| 119 | + """Constructing a CosmosClient with AAD creds must also work when |
| 120 | + AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT IS set.""" |
| 121 | + os.environ["AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT"] = "https://example.com" |
| 122 | + |
| 123 | + client = cosmos_client.CosmosClient(self.host, self.credential) |
| 124 | + db = client.get_database_client(self.configs.TEST_DATABASE_ID) |
| 125 | + container = db.get_container_client(self.configs.TEST_SINGLE_PARTITION_CONTAINER_ID) |
| 126 | + |
| 127 | + item = get_test_item(1) |
| 128 | + container.create_item(item) |
| 129 | + read_result = container.read_item(item=item['id'], partition_key='pk') |
| 130 | + assert read_result['id'] == item['id'] |
| 131 | + container.delete_item(item=item['id'], partition_key='pk') |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + unittest.main() |
0 commit comments