|
| 1 | +import os |
| 2 | +from unittest import mock |
| 3 | + |
| 4 | +import pytest |
| 5 | +from msgraph import GraphServiceClient |
| 6 | +from msgraph.generated.models.application import Application |
| 7 | +from msgraph.generated.models.password_credential import PasswordCredential |
| 8 | +from msgraph.generated.models.service_principal import ServicePrincipal |
| 9 | + |
| 10 | +from .mocks import MockAzureCredential |
| 11 | +from scripts import auth_init |
| 12 | +from scripts.auth_init import ( |
| 13 | + add_client_secret, |
| 14 | + client_app, |
| 15 | + create_application, |
| 16 | + create_or_update_application_with_secret, |
| 17 | + server_app_initial, |
| 18 | + server_app_permission_setup, |
| 19 | +) |
| 20 | + |
| 21 | +MOCK_OBJECT_ID = "OBJ123" |
| 22 | +MOCK_APP_ID = "APP123" |
| 23 | +MOCK_SECRET = "SECRET_VALUE" |
| 24 | +EXISTING_MOCK_OBJECT_ID = "OBJ999" |
| 25 | + |
| 26 | + |
| 27 | +@pytest.fixture |
| 28 | +def graph_client(monkeypatch): |
| 29 | + """GraphServiceClient whose network layer is intercepted to avoid real HTTP calls. |
| 30 | +
|
| 31 | + We exercise real request builders while intercepting the adapter's send_async. |
| 32 | + """ |
| 33 | + |
| 34 | + client = GraphServiceClient(credentials=MockAzureCredential(), scopes=["https://graph.microsoft.com/.default"]) |
| 35 | + |
| 36 | + calls = { |
| 37 | + "applications.post": [], |
| 38 | + "applications.patch": [], |
| 39 | + "applications.add_password.post": [], |
| 40 | + "service_principals.post": [], |
| 41 | + } |
| 42 | + created_ids = {"object_id": MOCK_OBJECT_ID, "app_id": MOCK_APP_ID} |
| 43 | + secret_text_value = {"value": MOCK_SECRET} |
| 44 | + |
| 45 | + async def fake_send_async(request_info, return_type, error_mapping=None): |
| 46 | + url = request_info.url or "" |
| 47 | + method = request_info.http_method.value |
| 48 | + if method == "POST" and url.endswith("/applications"): |
| 49 | + body = request_info.content |
| 50 | + calls["applications.post"].append(body) |
| 51 | + return Application( |
| 52 | + id=created_ids["object_id"], |
| 53 | + app_id=created_ids["app_id"], |
| 54 | + display_name=getattr(body, "display_name", None), |
| 55 | + ) |
| 56 | + if method == "POST" and url.endswith("/servicePrincipals"): |
| 57 | + calls["service_principals.post"].append(request_info.content) |
| 58 | + return ServicePrincipal() |
| 59 | + if method == "PATCH" and "/applications/" in url: |
| 60 | + calls["applications.patch"].append(request_info.content) |
| 61 | + return Application() |
| 62 | + if method == "POST" and url.endswith("/addPassword"): |
| 63 | + calls["applications.add_password.post"].append(request_info.content) |
| 64 | + return PasswordCredential(secret_text=secret_text_value["value"]) |
| 65 | + raise AssertionError(f"Unexpected request: {method} {url}") |
| 66 | + |
| 67 | + # Patch the adapter |
| 68 | + monkeypatch.setattr(client.request_adapter, "send_async", fake_send_async) |
| 69 | + |
| 70 | + client._test_calls = calls |
| 71 | + client._test_secret_text_value = secret_text_value |
| 72 | + client._test_ids = created_ids |
| 73 | + return client |
| 74 | + |
| 75 | + |
| 76 | +@pytest.mark.asyncio |
| 77 | +async def test_create_application_success(graph_client): |
| 78 | + graph = graph_client |
| 79 | + request = server_app_initial(42) |
| 80 | + object_id, app_id = await create_application(graph, request) |
| 81 | + assert object_id == MOCK_OBJECT_ID |
| 82 | + assert app_id == MOCK_APP_ID |
| 83 | + assert len(graph._test_calls["service_principals.post"]) == 1 |
| 84 | + |
| 85 | + |
| 86 | +@pytest.mark.asyncio |
| 87 | +async def test_create_application_missing_ids(graph_client, monkeypatch): |
| 88 | + graph = graph_client |
| 89 | + |
| 90 | + original_send_async = graph.request_adapter.send_async |
| 91 | + |
| 92 | + async def bad_send_async(request_info, return_type, error_mapping=None): |
| 93 | + url = request_info.url or "" |
| 94 | + method = request_info.http_method.value |
| 95 | + if method == "POST" and url.endswith("/applications"): |
| 96 | + return Application(id=None, app_id=None) |
| 97 | + return await original_send_async(request_info, return_type, error_mapping) |
| 98 | + |
| 99 | + monkeypatch.setattr(graph.request_adapter, "send_async", bad_send_async) |
| 100 | + with pytest.raises(ValueError): |
| 101 | + await create_application(graph, server_app_initial(1)) |
| 102 | + |
| 103 | + |
| 104 | +@pytest.mark.asyncio |
| 105 | +async def test_add_client_secret_success(graph_client): |
| 106 | + graph = graph_client |
| 107 | + secret = await add_client_secret(graph, MOCK_OBJECT_ID) |
| 108 | + assert secret == MOCK_SECRET |
| 109 | + assert len(graph._test_calls["applications.add_password.post"]) == 1 |
| 110 | + |
| 111 | + |
| 112 | +@pytest.mark.asyncio |
| 113 | +async def test_add_client_secret_missing_secret(graph_client): |
| 114 | + graph = graph_client |
| 115 | + graph._test_secret_text_value["value"] = None |
| 116 | + with pytest.raises(ValueError): |
| 117 | + await add_client_secret(graph, MOCK_OBJECT_ID) |
| 118 | + |
| 119 | + |
| 120 | +@pytest.mark.asyncio |
| 121 | +async def test_create_or_update_application_creates_and_adds_secret(graph_client, monkeypatch): |
| 122 | + graph = graph_client |
| 123 | + updates: list[tuple[str, str]] = [] |
| 124 | + |
| 125 | + def fake_update_env(name, val): |
| 126 | + updates.append((name, val)) |
| 127 | + |
| 128 | + # Ensure env vars not set |
| 129 | + with mock.patch.dict(os.environ, {}, clear=True): |
| 130 | + monkeypatch.setattr(auth_init, "update_azd_env", fake_update_env) |
| 131 | + |
| 132 | + # Force get_application to return None (not found) |
| 133 | + async def fake_get_application(graph_client, client_id): |
| 134 | + return None |
| 135 | + |
| 136 | + monkeypatch.setattr("scripts.auth_init.get_application", fake_get_application) |
| 137 | + object_id, app_id, created = await create_or_update_application_with_secret( |
| 138 | + graph, |
| 139 | + app_id_env_var="AZURE_SERVER_APP_ID", |
| 140 | + app_secret_env_var="AZURE_SERVER_APP_SECRET", |
| 141 | + request_app=server_app_initial(55), |
| 142 | + ) |
| 143 | + assert created is True |
| 144 | + assert object_id == MOCK_OBJECT_ID |
| 145 | + assert app_id == MOCK_APP_ID |
| 146 | + # Two updates: app id and secret |
| 147 | + assert {u[0] for u in updates} == {"AZURE_SERVER_APP_ID", "AZURE_SERVER_APP_SECRET"} |
| 148 | + assert len(graph._test_calls["applications.add_password.post"]) == 1 |
| 149 | + |
| 150 | + |
| 151 | +@pytest.mark.asyncio |
| 152 | +async def test_create_or_update_application_existing_adds_secret(graph_client, monkeypatch): |
| 153 | + graph = graph_client |
| 154 | + updates: list[tuple[str, str]] = [] |
| 155 | + |
| 156 | + def fake_update_env(name, val): |
| 157 | + updates.append((name, val)) |
| 158 | + |
| 159 | + with mock.patch.dict(os.environ, {"AZURE_SERVER_APP_ID": MOCK_APP_ID}, clear=True): |
| 160 | + monkeypatch.setattr(auth_init, "update_azd_env", fake_update_env) |
| 161 | + |
| 162 | + async def fake_get_application(graph_client, client_id): |
| 163 | + return EXISTING_MOCK_OBJECT_ID |
| 164 | + |
| 165 | + monkeypatch.setattr("scripts.auth_init.get_application", fake_get_application) |
| 166 | + object_id, app_id, created = await create_or_update_application_with_secret( |
| 167 | + graph, |
| 168 | + app_id_env_var="AZURE_SERVER_APP_ID", |
| 169 | + app_secret_env_var="AZURE_SERVER_APP_SECRET", |
| 170 | + request_app=server_app_initial(77), |
| 171 | + ) |
| 172 | + assert created is False |
| 173 | + assert object_id == EXISTING_MOCK_OBJECT_ID |
| 174 | + assert app_id == MOCK_APP_ID |
| 175 | + # Secret should be added since not in env |
| 176 | + assert any(name == "AZURE_SERVER_APP_SECRET" for name, _ in updates) |
| 177 | + # Application patch should have been called |
| 178 | + # Patch captured |
| 179 | + assert len(graph._test_calls["applications.patch"]) == 1 |
| 180 | + |
| 181 | + |
| 182 | +@pytest.mark.asyncio |
| 183 | +async def test_create_or_update_application_existing_with_secret(graph_client, monkeypatch): |
| 184 | + graph = graph_client |
| 185 | + with mock.patch.dict( |
| 186 | + os.environ, {"AZURE_SERVER_APP_ID": MOCK_APP_ID, "AZURE_SERVER_APP_SECRET": "EXISTING"}, clear=True |
| 187 | + ): |
| 188 | + |
| 189 | + async def fake_get_application(graph_client, client_id): |
| 190 | + return EXISTING_MOCK_OBJECT_ID |
| 191 | + |
| 192 | + monkeypatch.setattr("scripts.auth_init.get_application", fake_get_application) |
| 193 | + object_id, app_id, created = await create_or_update_application_with_secret( |
| 194 | + graph, |
| 195 | + app_id_env_var="AZURE_SERVER_APP_ID", |
| 196 | + app_secret_env_var="AZURE_SERVER_APP_SECRET", |
| 197 | + request_app=server_app_initial(88), |
| 198 | + ) |
| 199 | + assert created is False |
| 200 | + assert object_id == EXISTING_MOCK_OBJECT_ID |
| 201 | + assert app_id == MOCK_APP_ID |
| 202 | + # No secret added |
| 203 | + assert len(graph._test_calls["applications.add_password.post"]) == 0 |
| 204 | + |
| 205 | + |
| 206 | +def test_client_app_validation_errors(): |
| 207 | + # Server app without api |
| 208 | + server_app = server_app_initial(1) |
| 209 | + server_app.api = None |
| 210 | + with pytest.raises(ValueError): |
| 211 | + client_app("server_app_id", server_app, 2) |
| 212 | + |
| 213 | + # Server app with empty scopes |
| 214 | + # attach empty api |
| 215 | + server_app_permission = server_app_permission_setup("server_app") |
| 216 | + server_app_permission.api.oauth2_permission_scopes = [] |
| 217 | + with pytest.raises(ValueError): |
| 218 | + client_app("server_app_id", server_app_permission, 2) |
| 219 | + |
| 220 | + |
| 221 | +def test_client_app_success(): |
| 222 | + server_app_permission = server_app_permission_setup("server_app") |
| 223 | + c_app = client_app("server_app", server_app_permission, 123) |
| 224 | + assert c_app.web is not None |
| 225 | + assert c_app.spa is not None |
| 226 | + assert c_app.required_resource_access is not None |
| 227 | + assert len(c_app.required_resource_access) >= 1 |
| 228 | + |
| 229 | + |
| 230 | +def test_server_app_permission_setup(): |
| 231 | + # simulate after creation we know app id |
| 232 | + app_with_permissions = server_app_permission_setup("server_app_id") |
| 233 | + assert app_with_permissions.identifier_uris == ["api://server_app_id"] |
| 234 | + assert app_with_permissions.required_resource_access is not None |
| 235 | + assert len(app_with_permissions.required_resource_access) == 1 |
0 commit comments