dabla commented on code in PR #71350: URL: https://github.com/apache/airflow/pull/71350#discussion_r3833678433
########## providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/analysis_services.py: ########## @@ -0,0 +1,285 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import time +from functools import cached_property +from typing import TYPE_CHECKING, Any, Literal, get_args +from urllib.parse import quote, unquote, urlsplit + +import requests +from azure.core.exceptions import AzureError +from azure.identity import ClientSecretCredential + +from airflow.providers.common.compat.sdk import AirflowException, BaseHook + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + from airflow.sdk import Connection + +TOKEN_SCOPE = "https://*.asazure.windows.net/.default" + +RefreshType = Literal["full", "clearValues", "calculate", "dataOnly", "automatic", "defragment"] +VALID_REFRESH_TYPES: frozenset[str] = frozenset(get_args(RefreshType)) + + +def _format_request_error(error: requests.RequestException) -> str: + response_body = getattr(error.response, "text", "").strip()[:1000] + response_detail = f"; response body: {response_body}" if response_body else "" + return f"{error}{response_detail}" + + +class AzureAnalysisServicesRefreshStatus: + """Azure Analysis Services model refresh statuses.""" + + SUCCEEDED = "succeeded" + FAILED = "failed" + CANCELLED = "cancelled" + TIMED_OUT = "timedOut" + NOT_STARTED = "notStarted" + IN_PROGRESS = "inProgress" + + FAILURE_STATUSES = frozenset({FAILED, CANCELLED, TIMED_OUT}) + VALID_STATUSES = frozenset({SUCCEEDED, FAILED, CANCELLED, TIMED_OUT, NOT_STARTED, IN_PROGRESS}) + + +class AzureAnalysisServicesRefreshException(AirflowException): + """Indicate that an Azure Analysis Services model refresh operation failed.""" + + +class AzureAnalysisServicesHook(BaseHook): + """ + Interact with the Azure Analysis Services asynchronous refresh REST API. + + :param azure_analysis_services_conn_id: The Azure Analysis Services connection ID. + :param request_timeout: Timeout in seconds for each HTTP request. + + The connection must define the region endpoint in ``host``, the service principal client ID in + ``login``, the client secret in ``password``, and the Microsoft Entra tenant ID in the + ``tenantId`` extra field. + """ + + conn_type: str = "azure_analysis_services" + conn_name_attr: str = "azure_analysis_services_conn_id" + default_conn_name: str = "azure_analysis_services_default" + hook_name: str = "Azure Analysis Services" + + def __init__( + self, + azure_analysis_services_conn_id: str = default_conn_name, + request_timeout: float = 60, + ) -> None: + super().__init__() + if request_timeout <= 0: + raise ValueError("request_timeout must be greater than zero") + self.azure_analysis_services_conn_id = azure_analysis_services_conn_id + self.request_timeout = request_timeout + self._credential: TokenCredential | None = None + + @cached_property + def connection(self) -> Connection: + """Return the Azure Analysis Services connection.""" + return self.get_connection(self.azure_analysis_services_conn_id) + + @classmethod + def get_connection_form_widgets(cls) -> dict[str, Any]: + """Return connection widgets to add to the connection form.""" + from flask_appbuilder.fieldwidgets import BS3TextFieldWidget + from flask_babel import lazy_gettext + from wtforms import StringField + + return { + "tenantId": StringField(lazy_gettext("Tenant ID"), widget=BS3TextFieldWidget()), + } + + @classmethod + def get_ui_field_behaviour(cls) -> dict[str, Any]: + """Return custom field behaviour for the connection form.""" + return { + "hidden_fields": ["schema", "port", "extra"], + "relabeling": { + "host": "Region Endpoint", + "login": "Client ID", + "password": "Client Secret", + }, + "placeholders": { + "host": "westus.asazure.windows.net", + }, + } + + def get_conn(self) -> TokenCredential: + """Return and cache the service principal credential.""" + if self._credential is not None: + return self._credential + + connection = self.connection + tenant_id = connection.extra_dejson.get("tenantId") + if not connection.login: + raise ValueError("Client ID is required for Azure Analysis Services authentication") + if not connection.password: + raise ValueError("Client secret is required for Azure Analysis Services authentication") + if not isinstance(tenant_id, str) or not tenant_id: + raise ValueError("Tenant ID is required for Azure Analysis Services authentication") + + self._credential = ClientSecretCredential( + tenant_id=tenant_id, + client_id=connection.login, + client_secret=connection.password, + ) + return self._credential + + def get_refresh_status(self, server_name: str, database: str, refresh_id: str) -> str: + """Return the validated status of an Azure Analysis Services model refresh.""" + refresh_url = f"{self._get_refreshes_url(server_name, database)}/{quote(refresh_id, safe='')}" + try: + response = requests.get( + refresh_url, + headers=self._get_headers(), + timeout=self.request_timeout, + ) + response.raise_for_status() + except requests.RequestException as error: + raise AzureAnalysisServicesRefreshException( + f"Failed to get status for Azure Analysis Services refresh {refresh_id}: " + f"{_format_request_error(error)}" + ) from error + + try: + response_body = response.json() + except ValueError as error: + raise AzureAnalysisServicesRefreshException( + f"Azure Analysis Services returned a non-JSON status response for refresh {refresh_id}" + ) from error + + if not isinstance(response_body, dict): + raise AzureAnalysisServicesRefreshException( + f"Azure Analysis Services returned an invalid status response for refresh {refresh_id}" + ) + status = response_body.get("status") + if not isinstance(status, str) or status not in AzureAnalysisServicesRefreshStatus.VALID_STATUSES: + raise AzureAnalysisServicesRefreshException( + f"Azure Analysis Services returned unknown status {status!r} for refresh {refresh_id}" + ) + return status + + def trigger_refresh(self, server_name: str, database: str, refresh_type: RefreshType = "full") -> str: + """Trigger a model refresh and return its refresh ID.""" + if refresh_type not in VALID_REFRESH_TYPES: + raise ValueError( + f"Invalid refresh_type {refresh_type!r}. Valid values are: {sorted(VALID_REFRESH_TYPES)}" + ) + + try: + response = requests.post( + self._get_refreshes_url(server_name, database), + json={"Type": refresh_type}, + headers=self._get_headers(), + timeout=self.request_timeout, + ) + response.raise_for_status() + except requests.RequestException as error: + raise AzureAnalysisServicesRefreshException( + f"Failed to trigger an Azure Analysis Services model refresh: {_format_request_error(error)}" + ) from error + + location = response.headers.get("Location") + if not location: + raise AzureAnalysisServicesRefreshException( + "Azure Analysis Services did not return a refresh ID in the Location header" + ) + try: + location_parts = [part for part in urlsplit(location).path.split("/") if part] + except ValueError as error: + raise AzureAnalysisServicesRefreshException( + "Azure Analysis Services returned an invalid refresh Location header" + ) from error + if len(location_parts) < 2 or location_parts[-2] != "refreshes": + raise AzureAnalysisServicesRefreshException( + "Azure Analysis Services returned an invalid refresh Location header" + ) + return unquote(location_parts[-1]) + + def wait_for_refresh( + self, + server_name: str, + database: str, + refresh_id: str, + check_interval: float = 60, + timeout: float = 60 * 60 * 24 * 7, + ) -> None: + """Poll until the refresh reaches a terminal status or the timeout expires.""" + if check_interval <= 0: + raise ValueError("check_interval must be greater than zero") + if timeout <= 0: + raise ValueError("timeout must be greater than zero") + + deadline = time.monotonic() + timeout + while True: + status = self.get_refresh_status(server_name, database, refresh_id) + self.log.info("Refresh %s status: %s", refresh_id, status) + if status == AzureAnalysisServicesRefreshStatus.SUCCEEDED: + return + if status in AzureAnalysisServicesRefreshStatus.FAILURE_STATUSES: + raise AzureAnalysisServicesRefreshException( + f"Azure Analysis Services refresh {refresh_id} finished with status {status}" + ) + + remaining = deadline - time.monotonic() + if remaining <= 0: + raise AzureAnalysisServicesRefreshException( + f"Timeout waiting for Azure Analysis Services refresh {refresh_id} to complete" + ) + time.sleep(min(check_interval, remaining)) + + def _get_base_url(self) -> str: + host = (self.connection.host or "").strip().rstrip("/") + parsed_host = urlsplit(f"//{host}") + if ( + not host Review Comment: **[warning]** `_get_base_url` does not validate `userinfo` in the host string — bearer token can be sent to an attacker-controlled domain. The validation guards against `path`, `query`, and `fragment` but omits `parsed_host.userinfo`. An input like `[email protected]` passes every check (`hostname` is `evil.example`, all other parts are empty) and the method returns `https://[email protected]`. HTTP clients will connect to `evil.example` and send the AAS bearer token there. A port component is similarly unchecked: `evil.example:9999` passes and the returned URL targets a non-standard port. Suggested fix — add both guards to the condition: ```python if ( not host or not parsed_host.hostname or parsed_host.userinfo # <-- add this or parsed_host.port # <-- add this or parsed_host.path or parsed_host.query or parsed_host.fragment ): raise ValueError(...) ``` **[nit]** While fixing the above, consider extracting the validation into a dedicated `_assert_host` method. `_get_base_url` would then read as a clean two-liner, and the host validation can be unit-tested in isolation without going through `_get_base_url`: ```python def _assert_host(self, host: str, parsed: SplitResult) -> None: if ( not host or not parsed.hostname or parsed.userinfo or parsed.port or parsed.path or parsed.query or parsed.fragment ): raise ValueError( "A valid region endpoint without a URL scheme or path is required in the " "Azure Analysis Services connection host" ) def _get_base_url(self) -> str: host = (self.connection.host or "").strip().rstrip("/") self._assert_host(host, urlsplit(f"//{host}")) return f"https://{host}" ``` Open for debate — the method is small enough that it is not strictly necessary, but it makes the intent and the test surface explicit. --- Drafted-by: Claude Sonnet 4.6 (claude-sonnet-4.6); reviewed by @dabla before posting ########## providers/microsoft/azure/pyproject.toml: ########## @@ -99,6 +99,7 @@ dependencies = [ # It was added in https://github.com/apache/airflow/pull/47990/files # maybe this should be set from upstream "msal-extensions>=1.3.0", + "requests>=2.32.0,<3", Review Comment: **[blocker]** `requests` must not be added as a new dependency -- `httpx` is already a transitive dependency of the provider via `kiota-http` and is the established HTTP client across the provider. Beyond the dependency concern, switching to `httpx.AsyncClient` eliminates the `asyncio.to_thread` workaround in the trigger entirely: `httpx` has native async support, so `get_refresh_status` and `trigger_refresh` can be made proper `async` methods on the hook, and the trigger can `await` them directly. **`pyproject.toml`** -- remove the added line: ```diff - "requests>=2.32.0,<3", ``` **`hooks/analysis_services.py`** -- swap to `httpx.AsyncClient` and make the methods async: ```diff -import requests +import httpx ``` ```diff - def get_refresh_status(self, server_name: str, database: str, refresh_id: str) -> dict: + async def get_refresh_status(self, server_name: str, database: str, refresh_id: str) -> dict: try: - response = requests.get(refresh_url, headers=self._get_headers(), timeout=self.request_timeout) + async with httpx.AsyncClient() as client: + response = await client.get(refresh_url, headers=self._get_headers(), timeout=self.request_timeout) response.raise_for_status() - except requests.RequestException as error: + except httpx.HTTPError as error: raise AzureAnalysisServicesRefreshError(...) from error ``` ```diff - def trigger_refresh(self, server_name: str, database: str, refresh_type: str) -> dict: + async def trigger_refresh(self, server_name: str, database: str, refresh_type: str) -> dict: try: - response = requests.post(url, json={"Type": refresh_type}, headers=self._get_headers(), timeout=self.request_timeout) + async with httpx.AsyncClient() as client: + response = await client.post(url, json={"Type": refresh_type}, headers=self._get_headers(), timeout=self.request_timeout) response.raise_for_status() - except requests.RequestException as error: + except httpx.HTTPError as error: raise AzureAnalysisServicesRefreshError(...) from error ``` **`triggers/analysis_services.py`** -- drop `asyncio.to_thread` and await directly: ```diff -import asyncio ... - result = await asyncio.to_thread(self.hook.get_refresh_status, ...) + result = await self.hook.get_refresh_status(...) ``` The `response.raise_for_status()`, `response.json()`, `response.headers`, and `response.text` APIs are identical in `httpx`. Test mocks will need updating accordingly (`mock.AsyncMock(spec=httpx.Response)`). --- Drafted-by: Claude Sonnet 4.6 (claude-sonnet-4.6); reviewed by @dabla before posting ########## providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_analysis_services.py: ########## @@ -0,0 +1,388 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from unittest import mock + +import pytest +import requests +from azure.core.credentials import AccessToken +from azure.core.exceptions import ClientAuthenticationError + +from airflow.models import Connection +from airflow.providers.microsoft.azure.hooks.analysis_services import ( + TOKEN_SCOPE, + VALID_REFRESH_TYPES, + AzureAnalysisServicesHook, + AzureAnalysisServicesRefreshException, + AzureAnalysisServicesRefreshStatus, +) + +CONN_ID = "azure_analysis_services_test" +HOST = "westus.asazure.windows.net" +SERVER_NAME = "testserver" +DATABASE = "Adventure Works" +REFRESH_ID = "refresh-id" +REQUEST_TIMEOUT = 30 +HEADERS = {"Authorization": "Bearer token", "Content-Type": "application/json"} +MODULE = "airflow.providers.microsoft.azure.hooks.analysis_services" + + +def build_response( + *, headers: dict[str, str] | None = None, body: object | None = None, text: str = "" +) -> mock.Mock: + """Build a response mock with the requested headers and JSON body.""" + response = mock.Mock(spec=requests.Response) + response.headers = headers or {} + response.json.return_value = body + response.text = text + return response + + +class TestAzureAnalysisServicesHook: + @pytest.fixture(autouse=True) + def setup_connection(self, create_mock_connection): + create_mock_connection( + Connection( + conn_id=CONN_ID, + conn_type="azure_analysis_services", + host=HOST, + login="client-id", + password="client-secret", + extra={"tenantId": "tenant-id"}, + ) + ) + + @pytest.mark.parametrize("request_timeout", [0, -1]) + def test_rejects_invalid_request_timeout(self, request_timeout): + with pytest.raises(ValueError, match="request_timeout must be greater than zero"): + AzureAnalysisServicesHook(CONN_ID, request_timeout=request_timeout) + + def test_defines_connection_form_widget(self): + pytest.importorskip("flask_appbuilder") + assert set(AzureAnalysisServicesHook.get_connection_form_widgets()) == {"tenantId"} + + def test_defines_connection_ui_field_behaviour(self): + assert AzureAnalysisServicesHook.get_ui_field_behaviour() == { + "hidden_fields": ["schema", "port", "extra"], + "relabeling": { + "host": "Region Endpoint", + "login": "Client ID", + "password": "Client Secret", + }, + "placeholders": {"host": "westus.asazure.windows.net"}, + } + + @mock.patch(f"{MODULE}.ClientSecretCredential", autospec=True) + def test_get_conn_creates_and_caches_credential(self, credential_class): + hook = AzureAnalysisServicesHook(CONN_ID) + + first_credential = hook.get_conn() + second_credential = hook.get_conn() + + credential_class.assert_called_once_with( + tenant_id="tenant-id", + client_id="client-id", + client_secret="client-secret", + ) + assert first_credential is credential_class.return_value + assert second_credential is first_credential + + @mock.patch(f"{MODULE}.BaseHook.get_connection", autospec=True) + def test_caches_connection(self, get_connection): + get_connection.return_value = Connection( + conn_id=CONN_ID, + conn_type="azure_analysis_services", + host=HOST, + login="client-id", + password="client-secret", + extra={"tenantId": "tenant-id"}, + ) + hook = AzureAnalysisServicesHook(CONN_ID) + + first_connection = hook.connection + second_connection = hook.connection + + get_connection.assert_called_once_with(CONN_ID) + assert second_connection is first_connection + + @pytest.mark.parametrize( + ("login", "password", "extra", "message"), + [ + (None, "secret", {"tenantId": "tenant"}, "Client ID is required"), + ("client", None, {"tenantId": "tenant"}, "Client secret is required"), + ("client", "secret", {}, "Tenant ID is required"), + ("client", "secret", {"tenantId": 123}, "Tenant ID is required"), + ], + ) + def test_get_conn_requires_service_principal_fields( + self, create_mock_connection, login, password, extra, message + ): + create_mock_connection( + Connection( + conn_id="invalid-auth", + conn_type="azure_analysis_services", + host=HOST, + login=login, + password=password, + extra=extra, + ) + ) + + with pytest.raises(ValueError, match=message): + AzureAnalysisServicesHook("invalid-auth").get_conn() + + @mock.patch(f"{MODULE}.ClientSecretCredential", autospec=True) + def test_get_headers_uses_literal_token_scope(self, credential_class): + credential_class.return_value.get_token.return_value = AccessToken("token", 0) + + headers = AzureAnalysisServicesHook(CONN_ID)._get_headers() + + credential_class.return_value.get_token.assert_called_once_with(TOKEN_SCOPE) + assert TOKEN_SCOPE == "https://*.asazure.windows.net/.default" + assert headers == HEADERS + + @mock.patch(f"{MODULE}.ClientSecretCredential", autospec=True) + def test_get_headers_wraps_authentication_errors(self, credential_class): + credential_class.return_value.get_token.side_effect = ClientAuthenticationError("bad credential") + + with pytest.raises(AzureAnalysisServicesRefreshException, match="Failed to authenticate"): + AzureAnalysisServicesHook(CONN_ID)._get_headers() Review Comment: **[nit]** `test_rejects_invalid_region_endpoint` does not cover the `userinfo` and port injection cases identified in comment [1]. The existing parametrize values are `[None, "", "https://westus.asazure.windows.net", "host/path"]`. Adding `"[email protected]"` and `"evil.example:9999"` would both fail today (they pass `_get_base_url` without raising), confirming the gap and ensuring it stays fixed after any future refactor. ```python @pytest.mark.parametrize( "host", [ None, "", "https://westus.asazure.windows.net", "host/path", "[email protected]", # userinfo injection "evil.example:9999", # non-standard port ], ) def test_rejects_invalid_region_endpoint(self, host, create_mock_connection): ... ``` --- Drafted-by: Claude Sonnet 4.6 (claude-sonnet-4.6); reviewed by @dabla before posting -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
