We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[Task] API to use Managed Identity to authenticate against Cosmos DB
**Is your feature request related to a problem?

Currently the API use an API key `STATE_STORE_KEY` to authenticate against Cosmos DB. The API uses Managed Identity to authenticate against Azure Service Bus.

**Describe the solution you'd like

Using the same simplified access pattern to authenticate from the API to Azure resource.

Note: looks like Cosmos data-plane doesn't really support managed identity (in Python at least) but there might be a way to do this:
https://github.com/MicrosoftDocs/azure-docs/issues/29762
https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-linux-vm-access-cosmos-db


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `management_api_app/core/config.py`
Content:
```
1 from starlette.config import Config
2 
3 
4 config = Config(".env")
5 
6 # API settings
7 API_PREFIX = "/api"
8 PROJECT_NAME: str = config("PROJECT_NAME", default="Azure TRE API")
9 DEBUG: bool = config("DEBUG", cast=bool, default=False)
10 VERSION = "0.0.0"
11 
12 # Resource Info
13 RESOURCE_LOCATION: str = config("RESOURCE_LOCATION", default="")
14 TRE_ID: str = config("TRE_ID", default="")
15 
16 # State store configuration
17 STATE_STORE_ENDPOINT: str = config("STATE_STORE_ENDPOINT", default="")      # Cosmos DB endpoint
18 STATE_STORE_KEY: str = config("STATE_STORE_KEY", default="")                # Cosmos DB access key
19 STATE_STORE_DATABASE = "AzureTRE"
20 STATE_STORE_RESOURCES_CONTAINER = "Resources"
21 STATE_STORE_RESOURCE_TEMPLATES_CONTAINER = "ResourceTemplates"
22 
23 # Service bus configuration
24 SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE: str = config("SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE", default="")
25 SERVICE_BUS_RESOURCE_REQUEST_QUEUE: str = config("SERVICE_BUS_RESOURCE_REQUEST_QUEUE", default="")
26 SERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE: str = config("SERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE", default="")
27 
28 # Managed identity configuration
29 MANAGED_IDENTITY_CLIENT_ID: str = config("MANAGED_IDENTITY_CLIENT_ID", default="")
30 
31 # Logging and monitoring
32 APP_INSIGHTS_INSTRUMENTATION_KEY: str = config("APPINSIGHTS_INSTRUMENTATIONKEY", default="")
33 
34 # Authentication
35 API_CLIENT_ID: str = config("API_CLIENT_ID", default="")
36 API_CLIENT_SECRET: str = config("API_CLIENT_SECRET", default="")
37 SWAGGER_UI_CLIENT_ID: str = config("SWAGGER_UI_CLIENT_ID", default="")
38 AAD_TENANT_ID: str = config("AAD_TENANT_ID", default="")
39 
40 AAD_INSTANCE: str = config("AAD_INSTANCE", default="https://login.microsoftonline.com")
41 API_AUDIENCE: str = config("API_AUDIENCE", default=API_CLIENT_ID)
42
```

Path: `management_api_app/services/health_checker.py`
Content:
```
1 from azure.core import exceptions
2 from azure.cosmos import CosmosClient
3 
4 from core.config import STATE_STORE_ENDPOINT, STATE_STORE_KEY
5 from models.schemas.status import StatusEnum
6 from resources import strings
7 
8 
9 def create_state_store_status() -> (StatusEnum, str):
10     status = StatusEnum.ok
11     message = ""
12     try:
13         client = CosmosClient(STATE_STORE_ENDPOINT, STATE_STORE_KEY)    # noqa: F841 - flake 8 client is not used
14     except exceptions.ServiceRequestError:
15         status = StatusEnum.not_ok
16         message = strings.STATE_STORE_ENDPOINT_NOT_RESPONDING
17     except:     # noqa: E722 flake8 - no bare excepts
18         status = StatusEnum.not_ok
19         message = strings.UNSPECIFIED_ERROR
20     return status, message
21
```

Path: `management_api_app/api/dependencies/database.py`
Content:
```
1 import logging
2 from typing import Callable, Type
3 
4 from azure.cosmos import CosmosClient
5 from fastapi import Depends, FastAPI, HTTPException
6 from starlette.requests import Request
7 from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
8 
9 from core import config
10 from db.errors import UnableToAccessDatabase
11 from db.repositories.base import BaseRepository
12 from resources import strings
13 
14 
15 def connect_to_db() -> CosmosClient:
16     logging.debug(f"Connecting to {config.STATE_STORE_ENDPOINT}")
17 
18     try:
19         if config.DEBUG:
20             # ignore TLS(setup is pain) when on dev container and connecting to cosmosdb on windows host.
21             cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, config.STATE_STORE_KEY,
22                                          connection_verify=False)
23         else:
24             cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, config.STATE_STORE_KEY)
25         logging.debug("Connection established")
26         return cosmos_client
27     except Exception as e:
28         logging.debug(f"Connection to state store could not be established: {e}")
29 
30 
31 def get_db_client(app: FastAPI) -> CosmosClient:
32     if not app.state.cosmos_client:
33         app.state.cosmos_client = connect_to_db()
34     return app.state.cosmos_client
35 
36 
37 def get_db_client_from_request(request: Request) -> CosmosClient:
38     return get_db_client(request.app)
39 
40 
41 def get_repository(repo_type: Type[BaseRepository]) -> Callable[[CosmosClient], BaseRepository]:
42     def _get_repo(client: CosmosClient = Depends(get_db_client_from_request)) -> BaseRepository:
43         try:
44             return repo_type(client)
45         except UnableToAccessDatabase:
46             raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=strings.STATE_STORE_ENDPOINT_NOT_RESPONDING)
47 
48     return _get_repo
49
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/management_api_app/api/dependencies/database.py b/management_api_app/api/dependencies/database.py
--- a/management_api_app/api/dependencies/database.py
+++ b/management_api_app/api/dependencies/database.py
@@ -2,6 +2,8 @@
 from typing import Callable, Type
 
 from azure.cosmos import CosmosClient
+from azure.identity import DefaultAzureCredential
+from azure.mgmt.cosmosdb import CosmosDBManagementClient
 from fastapi import Depends, FastAPI, HTTPException
 from starlette.requests import Request
 from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
@@ -16,18 +18,30 @@
     logging.debug(f"Connecting to {config.STATE_STORE_ENDPOINT}")
 
     try:
+        primary_master_key = get_store_key()
         if config.DEBUG:
             # ignore TLS(setup is pain) when on dev container and connecting to cosmosdb on windows host.
-            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, config.STATE_STORE_KEY,
-                                         connection_verify=False)
+            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key, connection_verify=False)
         else:
-            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, config.STATE_STORE_KEY)
+            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key)
         logging.debug("Connection established")
         return cosmos_client
     except Exception as e:
         logging.debug(f"Connection to state store could not be established: {e}")
 
 
+def get_store_key() -> str:
+    if config.STATE_STORE_KEY:
+        primary_master_key = config.STATE_STORE_KEY
+    else:
+        credential = DefaultAzureCredential(managed_identity_client_id=config.MANAGED_IDENTITY_CLIENT_ID, exclude_shared_token_cache_credential=True)
+        cosmosdb_client = CosmosDBManagementClient(credential, subscription_id=config.SUBSCRIPTION_ID)
+        database_keys = cosmosdb_client.database_accounts.list_keys(resource_group_name=config.RESOURCE_GROUP_NAME, account_name=config.COSMOSDB_ACCOUNT_NAME)
+        primary_master_key = database_keys.primary_master_key
+
+    return primary_master_key
+
+
 def get_db_client(app: FastAPI) -> CosmosClient:
     if not app.state.cosmos_client:
         app.state.cosmos_client = connect_to_db()
diff --git a/management_api_app/core/config.py b/management_api_app/core/config.py
--- a/management_api_app/core/config.py
+++ b/management_api_app/core/config.py
@@ -16,9 +16,13 @@
 # State store configuration
 STATE_STORE_ENDPOINT: str = config("STATE_STORE_ENDPOINT", default="")      # Cosmos DB endpoint
 STATE_STORE_KEY: str = config("STATE_STORE_KEY", default="")                # Cosmos DB access key
+COSMOSDB_ACCOUNT_NAME: str = config("COSMOSDB_ACCOUNT_NAME", default="")                # Cosmos DB account name
 STATE_STORE_DATABASE = "AzureTRE"
 STATE_STORE_RESOURCES_CONTAINER = "Resources"
 STATE_STORE_RESOURCE_TEMPLATES_CONTAINER = "ResourceTemplates"
+SUBSCRIPTION_ID: str = config("SUBSCRIPTION_ID", default="")
+RESOURCE_GROUP_NAME: str = config("RESOURCE_GROUP_NAME", default="")
+
 
 # Service bus configuration
 SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE: str = config("SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE", default="")
diff --git a/management_api_app/services/health_checker.py b/management_api_app/services/health_checker.py
--- a/management_api_app/services/health_checker.py
+++ b/management_api_app/services/health_checker.py
@@ -1,7 +1,8 @@
 from azure.core import exceptions
 from azure.cosmos import CosmosClient
 
-from core.config import STATE_STORE_ENDPOINT, STATE_STORE_KEY
+from api.dependencies.database import get_store_key
+from core import config
 from models.schemas.status import StatusEnum
 from resources import strings
 
@@ -10,7 +11,8 @@
     status = StatusEnum.ok
     message = ""
     try:
-        client = CosmosClient(STATE_STORE_ENDPOINT, STATE_STORE_KEY)    # noqa: F841 - flake 8 client is not used
+        primary_master_key = get_store_key()
+        client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key)    # noqa: F841 - flake 8 client is not used
     except exceptions.ServiceRequestError:
         status = StatusEnum.not_ok
         message = strings.STATE_STORE_ENDPOINT_NOT_RESPONDING

{"golden_diff": "diff --git a/management_api_app/api/dependencies/database.py b/management_api_app/api/dependencies/database.py\n--- a/management_api_app/api/dependencies/database.py\n+++ b/management_api_app/api/dependencies/database.py\n@@ -2,6 +2,8 @@\n from typing import Callable, Type\n \n from azure.cosmos import CosmosClient\n+from azure.identity import DefaultAzureCredential\n+from azure.mgmt.cosmosdb import CosmosDBManagementClient\n from fastapi import Depends, FastAPI, HTTPException\n from starlette.requests import Request\n from starlette.status import HTTP_503_SERVICE_UNAVAILABLE\n@@ -16,18 +18,30 @@\n     logging.debug(f\"Connecting to {config.STATE_STORE_ENDPOINT}\")\n \n     try:\n+        primary_master_key = get_store_key()\n         if config.DEBUG:\n             # ignore TLS(setup is pain) when on dev container and connecting to cosmosdb on windows host.\n-            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, config.STATE_STORE_KEY,\n-                                         connection_verify=False)\n+            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key, connection_verify=False)\n         else:\n-            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, config.STATE_STORE_KEY)\n+            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key)\n         logging.debug(\"Connection established\")\n         return cosmos_client\n     except Exception as e:\n         logging.debug(f\"Connection to state store could not be established: {e}\")\n \n \n+def get_store_key() -> str:\n+    if config.STATE_STORE_KEY:\n+        primary_master_key = config.STATE_STORE_KEY\n+    else:\n+        credential = DefaultAzureCredential(managed_identity_client_id=config.MANAGED_IDENTITY_CLIENT_ID, exclude_shared_token_cache_credential=True)\n+        cosmosdb_client = CosmosDBManagementClient(credential, subscription_id=config.SUBSCRIPTION_ID)\n+        database_keys = cosmosdb_client.database_accounts.list_keys(resource_group_name=config.RESOURCE_GROUP_NAME, account_name=config.COSMOSDB_ACCOUNT_NAME)\n+        primary_master_key = database_keys.primary_master_key\n+\n+    return primary_master_key\n+\n+\n def get_db_client(app: FastAPI) -> CosmosClient:\n     if not app.state.cosmos_client:\n         app.state.cosmos_client = connect_to_db()\ndiff --git a/management_api_app/core/config.py b/management_api_app/core/config.py\n--- a/management_api_app/core/config.py\n+++ b/management_api_app/core/config.py\n@@ -16,9 +16,13 @@\n # State store configuration\n STATE_STORE_ENDPOINT: str = config(\"STATE_STORE_ENDPOINT\", default=\"\")      # Cosmos DB endpoint\n STATE_STORE_KEY: str = config(\"STATE_STORE_KEY\", default=\"\")                # Cosmos DB access key\n+COSMOSDB_ACCOUNT_NAME: str = config(\"COSMOSDB_ACCOUNT_NAME\", default=\"\")                # Cosmos DB account name\n STATE_STORE_DATABASE = \"AzureTRE\"\n STATE_STORE_RESOURCES_CONTAINER = \"Resources\"\n STATE_STORE_RESOURCE_TEMPLATES_CONTAINER = \"ResourceTemplates\"\n+SUBSCRIPTION_ID: str = config(\"SUBSCRIPTION_ID\", default=\"\")\n+RESOURCE_GROUP_NAME: str = config(\"RESOURCE_GROUP_NAME\", default=\"\")\n+\n \n # Service bus configuration\n SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE: str = config(\"SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE\", default=\"\")\ndiff --git a/management_api_app/services/health_checker.py b/management_api_app/services/health_checker.py\n--- a/management_api_app/services/health_checker.py\n+++ b/management_api_app/services/health_checker.py\n@@ -1,7 +1,8 @@\n from azure.core import exceptions\n from azure.cosmos import CosmosClient\n \n-from core.config import STATE_STORE_ENDPOINT, STATE_STORE_KEY\n+from api.dependencies.database import get_store_key\n+from core import config\n from models.schemas.status import StatusEnum\n from resources import strings\n \n@@ -10,7 +11,8 @@\n     status = StatusEnum.ok\n     message = \"\"\n     try:\n-        client = CosmosClient(STATE_STORE_ENDPOINT, STATE_STORE_KEY)    # noqa: F841 - flake 8 client is not used\n+        primary_master_key = get_store_key()\n+        client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key)    # noqa: F841 - flake 8 client is not used\n     except exceptions.ServiceRequestError:\n         status = StatusEnum.not_ok\n         message = strings.STATE_STORE_ENDPOINT_NOT_RESPONDING\n", "issue": "[Task] API to use Managed Identity to authenticate against Cosmos DB\n**Is your feature request related to a problem?\r\n\r\nCurrently the API use an API key `STATE_STORE_KEY` to authenticate against Cosmos DB. The API uses Managed Identity to authenticate against Azure Service Bus.\r\n\r\n**Describe the solution you'd like\r\n\r\nUsing the same simplified access pattern to authenticate from the API to Azure resource.\r\n\r\nNote: looks like Cosmos data-plane doesn't really support managed identity (in Python at least) but there might be a way to do this:\r\nhttps://github.com/MicrosoftDocs/azure-docs/issues/29762\r\nhttps://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-linux-vm-access-cosmos-db\r\n\n", "before_files": [{"content": "from starlette.config import Config\n\n\nconfig = Config(\".env\")\n\n# API settings\nAPI_PREFIX = \"/api\"\nPROJECT_NAME: str = config(\"PROJECT_NAME\", default=\"Azure TRE API\")\nDEBUG: bool = config(\"DEBUG\", cast=bool, default=False)\nVERSION = \"0.0.0\"\n\n# Resource Info\nRESOURCE_LOCATION: str = config(\"RESOURCE_LOCATION\", default=\"\")\nTRE_ID: str = config(\"TRE_ID\", default=\"\")\n\n# State store configuration\nSTATE_STORE_ENDPOINT: str = config(\"STATE_STORE_ENDPOINT\", default=\"\")      # Cosmos DB endpoint\nSTATE_STORE_KEY: str = config(\"STATE_STORE_KEY\", default=\"\")                # Cosmos DB access key\nSTATE_STORE_DATABASE = \"AzureTRE\"\nSTATE_STORE_RESOURCES_CONTAINER = \"Resources\"\nSTATE_STORE_RESOURCE_TEMPLATES_CONTAINER = \"ResourceTemplates\"\n\n# Service bus configuration\nSERVICE_BUS_FULLY_QUALIFIED_NAMESPACE: str = config(\"SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE\", default=\"\")\nSERVICE_BUS_RESOURCE_REQUEST_QUEUE: str = config(\"SERVICE_BUS_RESOURCE_REQUEST_QUEUE\", default=\"\")\nSERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE: str = config(\"SERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE\", default=\"\")\n\n# Managed identity configuration\nMANAGED_IDENTITY_CLIENT_ID: str = config(\"MANAGED_IDENTITY_CLIENT_ID\", default=\"\")\n\n# Logging and monitoring\nAPP_INSIGHTS_INSTRUMENTATION_KEY: str = config(\"APPINSIGHTS_INSTRUMENTATIONKEY\", default=\"\")\n\n# Authentication\nAPI_CLIENT_ID: str = config(\"API_CLIENT_ID\", default=\"\")\nAPI_CLIENT_SECRET: str = config(\"API_CLIENT_SECRET\", default=\"\")\nSWAGGER_UI_CLIENT_ID: str = config(\"SWAGGER_UI_CLIENT_ID\", default=\"\")\nAAD_TENANT_ID: str = config(\"AAD_TENANT_ID\", default=\"\")\n\nAAD_INSTANCE: str = config(\"AAD_INSTANCE\", default=\"https://login.microsoftonline.com\")\nAPI_AUDIENCE: str = config(\"API_AUDIENCE\", default=API_CLIENT_ID)\n", "path": "management_api_app/core/config.py"}, {"content": "from azure.core import exceptions\nfrom azure.cosmos import CosmosClient\n\nfrom core.config import STATE_STORE_ENDPOINT, STATE_STORE_KEY\nfrom models.schemas.status import StatusEnum\nfrom resources import strings\n\n\ndef create_state_store_status() -> (StatusEnum, str):\n    status = StatusEnum.ok\n    message = \"\"\n    try:\n        client = CosmosClient(STATE_STORE_ENDPOINT, STATE_STORE_KEY)    # noqa: F841 - flake 8 client is not used\n    except exceptions.ServiceRequestError:\n        status = StatusEnum.not_ok\n        message = strings.STATE_STORE_ENDPOINT_NOT_RESPONDING\n    except:     # noqa: E722 flake8 - no bare excepts\n        status = StatusEnum.not_ok\n        message = strings.UNSPECIFIED_ERROR\n    return status, message\n", "path": "management_api_app/services/health_checker.py"}, {"content": "import logging\nfrom typing import Callable, Type\n\nfrom azure.cosmos import CosmosClient\nfrom fastapi import Depends, FastAPI, HTTPException\nfrom starlette.requests import Request\nfrom starlette.status import HTTP_503_SERVICE_UNAVAILABLE\n\nfrom core import config\nfrom db.errors import UnableToAccessDatabase\nfrom db.repositories.base import BaseRepository\nfrom resources import strings\n\n\ndef connect_to_db() -> CosmosClient:\n    logging.debug(f\"Connecting to {config.STATE_STORE_ENDPOINT}\")\n\n    try:\n        if config.DEBUG:\n            # ignore TLS(setup is pain) when on dev container and connecting to cosmosdb on windows host.\n            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, config.STATE_STORE_KEY,\n                                         connection_verify=False)\n        else:\n            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, config.STATE_STORE_KEY)\n        logging.debug(\"Connection established\")\n        return cosmos_client\n    except Exception as e:\n        logging.debug(f\"Connection to state store could not be established: {e}\")\n\n\ndef get_db_client(app: FastAPI) -> CosmosClient:\n    if not app.state.cosmos_client:\n        app.state.cosmos_client = connect_to_db()\n    return app.state.cosmos_client\n\n\ndef get_db_client_from_request(request: Request) -> CosmosClient:\n    return get_db_client(request.app)\n\n\ndef get_repository(repo_type: Type[BaseRepository]) -> Callable[[CosmosClient], BaseRepository]:\n    def _get_repo(client: CosmosClient = Depends(get_db_client_from_request)) -> BaseRepository:\n        try:\n            return repo_type(client)\n        except UnableToAccessDatabase:\n            raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=strings.STATE_STORE_ENDPOINT_NOT_RESPONDING)\n\n    return _get_repo\n", "path": "management_api_app/api/dependencies/database.py"}], "after_files": [{"content": "from starlette.config import Config\n\n\nconfig = Config(\".env\")\n\n# API settings\nAPI_PREFIX = \"/api\"\nPROJECT_NAME: str = config(\"PROJECT_NAME\", default=\"Azure TRE API\")\nDEBUG: bool = config(\"DEBUG\", cast=bool, default=False)\nVERSION = \"0.0.0\"\n\n# Resource Info\nRESOURCE_LOCATION: str = config(\"RESOURCE_LOCATION\", default=\"\")\nTRE_ID: str = config(\"TRE_ID\", default=\"\")\n\n# State store configuration\nSTATE_STORE_ENDPOINT: str = config(\"STATE_STORE_ENDPOINT\", default=\"\")      # Cosmos DB endpoint\nSTATE_STORE_KEY: str = config(\"STATE_STORE_KEY\", default=\"\")                # Cosmos DB access key\nCOSMOSDB_ACCOUNT_NAME: str = config(\"COSMOSDB_ACCOUNT_NAME\", default=\"\")                # Cosmos DB account name\nSTATE_STORE_DATABASE = \"AzureTRE\"\nSTATE_STORE_RESOURCES_CONTAINER = \"Resources\"\nSTATE_STORE_RESOURCE_TEMPLATES_CONTAINER = \"ResourceTemplates\"\nSUBSCRIPTION_ID: str = config(\"SUBSCRIPTION_ID\", default=\"\")\nRESOURCE_GROUP_NAME: str = config(\"RESOURCE_GROUP_NAME\", default=\"\")\n\n\n# Service bus configuration\nSERVICE_BUS_FULLY_QUALIFIED_NAMESPACE: str = config(\"SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE\", default=\"\")\nSERVICE_BUS_RESOURCE_REQUEST_QUEUE: str = config(\"SERVICE_BUS_RESOURCE_REQUEST_QUEUE\", default=\"\")\nSERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE: str = config(\"SERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE\", default=\"\")\n\n# Managed identity configuration\nMANAGED_IDENTITY_CLIENT_ID: str = config(\"MANAGED_IDENTITY_CLIENT_ID\", default=\"\")\n\n# Logging and monitoring\nAPP_INSIGHTS_INSTRUMENTATION_KEY: str = config(\"APPINSIGHTS_INSTRUMENTATIONKEY\", default=\"\")\n\n# Authentication\nAPI_CLIENT_ID: str = config(\"API_CLIENT_ID\", default=\"\")\nAPI_CLIENT_SECRET: str = config(\"API_CLIENT_SECRET\", default=\"\")\nSWAGGER_UI_CLIENT_ID: str = config(\"SWAGGER_UI_CLIENT_ID\", default=\"\")\nAAD_TENANT_ID: str = config(\"AAD_TENANT_ID\", default=\"\")\n\nAAD_INSTANCE: str = config(\"AAD_INSTANCE\", default=\"https://login.microsoftonline.com\")\nAPI_AUDIENCE: str = config(\"API_AUDIENCE\", default=API_CLIENT_ID)\n", "path": "management_api_app/core/config.py"}, {"content": "from azure.core import exceptions\nfrom azure.cosmos import CosmosClient\n\nfrom api.dependencies.database import get_store_key\nfrom core import config\nfrom models.schemas.status import StatusEnum\nfrom resources import strings\n\n\ndef create_state_store_status() -> (StatusEnum, str):\n    status = StatusEnum.ok\n    message = \"\"\n    try:\n        primary_master_key = get_store_key()\n        client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key)    # noqa: F841 - flake 8 client is not used\n    except exceptions.ServiceRequestError:\n        status = StatusEnum.not_ok\n        message = strings.STATE_STORE_ENDPOINT_NOT_RESPONDING\n    except:     # noqa: E722 flake8 - no bare excepts\n        status = StatusEnum.not_ok\n        message = strings.UNSPECIFIED_ERROR\n    return status, message\n", "path": "management_api_app/services/health_checker.py"}, {"content": "import logging\nfrom typing import Callable, Type\n\nfrom azure.cosmos import CosmosClient\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.cosmosdb import CosmosDBManagementClient\nfrom fastapi import Depends, FastAPI, HTTPException\nfrom starlette.requests import Request\nfrom starlette.status import HTTP_503_SERVICE_UNAVAILABLE\n\nfrom core import config\nfrom db.errors import UnableToAccessDatabase\nfrom db.repositories.base import BaseRepository\nfrom resources import strings\n\n\ndef connect_to_db() -> CosmosClient:\n    logging.debug(f\"Connecting to {config.STATE_STORE_ENDPOINT}\")\n\n    try:\n        primary_master_key = get_store_key()\n        if config.DEBUG:\n            # ignore TLS(setup is pain) when on dev container and connecting to cosmosdb on windows host.\n            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key, connection_verify=False)\n        else:\n            cosmos_client = CosmosClient(config.STATE_STORE_ENDPOINT, primary_master_key)\n        logging.debug(\"Connection established\")\n        return cosmos_client\n    except Exception as e:\n        logging.debug(f\"Connection to state store could not be established: {e}\")\n\n\ndef get_store_key() -> str:\n    if config.STATE_STORE_KEY:\n        primary_master_key = config.STATE_STORE_KEY\n    else:\n        credential = DefaultAzureCredential(managed_identity_client_id=config.MANAGED_IDENTITY_CLIENT_ID, exclude_shared_token_cache_credential=True)\n        cosmosdb_client = CosmosDBManagementClient(credential, subscription_id=config.SUBSCRIPTION_ID)\n        database_keys = cosmosdb_client.database_accounts.list_keys(resource_group_name=config.RESOURCE_GROUP_NAME, account_name=config.COSMOSDB_ACCOUNT_NAME)\n        primary_master_key = database_keys.primary_master_key\n\n    return primary_master_key\n\n\ndef get_db_client(app: FastAPI) -> CosmosClient:\n    if not app.state.cosmos_client:\n        app.state.cosmos_client = connect_to_db()\n    return app.state.cosmos_client\n\n\ndef get_db_client_from_request(request: Request) -> CosmosClient:\n    return get_db_client(request.app)\n\n\ndef get_repository(repo_type: Type[BaseRepository]) -> Callable[[CosmosClient], BaseRepository]:\n    def _get_repo(client: CosmosClient = Depends(get_db_client_from_request)) -> BaseRepository:\n        try:\n            return repo_type(client)\n        except UnableToAccessDatabase:\n            raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=strings.STATE_STORE_ENDPOINT_NOT_RESPONDING)\n\n    return _get_repo\n", "path": "management_api_app/api/dependencies/database.py"}]}