diff --git a/azure/durable_functions/models/DurableOrchestrationBindings.py b/azure/durable_functions/models/DurableOrchestrationBindings.py index 8c8d857..00d5845 100644 --- a/azure/durable_functions/models/DurableOrchestrationBindings.py +++ b/azure/durable_functions/models/DurableOrchestrationBindings.py @@ -9,6 +9,9 @@ class DurableOrchestrationBindings: Provides information relevant to the creation and management of durable functions. + + URL query parameters are supplied by the Functions host and preserved as-is. + The host controls whether generated URLs contain a system key. """ # parameter names are as defined by JSON schema and do not conform to PEP8 naming conventions diff --git a/azure/durable_functions/models/DurableOrchestrationClient.py b/azure/durable_functions/models/DurableOrchestrationClient.py index c3d32c6..d844c79 100644 --- a/azure/durable_functions/models/DurableOrchestrationClient.py +++ b/azure/durable_functions/models/DurableOrchestrationClient.py @@ -142,7 +142,12 @@ def create_check_status_response( return func.HttpResponse(**response_args) def create_http_management_payload(self, instance_id: str) -> Dict[str, str]: - """Create a dictionary of orchestrator management urls. + """Create a dictionary of orchestrator management URLs. + + The host's ``httpSettings.excludeManagementKeyFromUrls`` option defaults + to false. When enabled, HTTP callers must obtain a key independently and + send it through ``x-functions-key``. The SDK does not return credentials; + SDK management operations use the local RPC endpoint. Parameters ---------- @@ -152,7 +157,7 @@ def create_http_management_payload(self, instance_id: str) -> Dict[str, str]: Returns ------- Dict[str, str] - a dictionary object of orchestrator instance management urls + A dictionary of orchestrator instance management URLs. """ return self.get_client_response_links(None, instance_id) @@ -209,7 +214,10 @@ async def read_entity_state( def get_client_response_links( self, request: Optional[func.HttpRequest], instance_id: str) -> Dict[str, str]: - """Create a dictionary of orchestrator management urls. + """Create a dictionary of orchestrator management URLs. + + The request overrides the URL scheme and authority without changing + host-provided query strings. Parameters ---------- @@ -221,15 +229,15 @@ def get_client_response_links( Returns ------- Dict[str, str] - a dictionary object of orchestrator instance management urls + A dictionary of orchestrator instance management URLs. """ payload = self._orchestration_bindings.management_urls.copy() - for key, _ in payload.items(): if not (request is None) and request.url: payload[key] = self._replace_url_origin(request.url, payload[key]) + # Replace only the ID placeholder, preserving matching text in query values. payload[key] = payload[key].replace( - self._orchestration_bindings.management_urls["id"], instance_id) + self._orchestration_bindings.management_urls["id"], instance_id, 1) return payload @@ -653,10 +661,12 @@ def _get_json_input(client_input: object) -> Optional[str]: def _replace_url_origin(request_url: str, value_url: str) -> str: request_parsed_url = urlparse(request_url) value_parsed_url = urlparse(value_url) - request_url_origin = '{url.scheme}://{url.netloc}/'.format(url=request_parsed_url) - value_url_origin = '{url.scheme}://{url.netloc}/'.format(url=value_parsed_url) - value_url = value_url.replace(value_url_origin, request_url_origin) - return value_url + # Management payloads also contain a plain instance ID. + if not value_parsed_url.scheme or not value_parsed_url.netloc: + return value_url + return value_parsed_url._replace( + scheme=request_parsed_url.scheme, + netloc=request_parsed_url.netloc).geturl() @staticmethod def _parse_purge_instance_history_response( diff --git a/tests/models/test_http_management_compatibility.py b/tests/models/test_http_management_compatibility.py new file mode 100644 index 0000000..c6659e9 --- /dev/null +++ b/tests/models/test_http_management_compatibility.py @@ -0,0 +1,139 @@ +import copy +import json +from unittest.mock import AsyncMock +from urllib.parse import urlsplit + +import azure.functions as func +import pytest + +from azure.durable_functions.models.DurableOrchestrationBindings import ( + DurableOrchestrationBindings) +from azure.durable_functions.models.DurableOrchestrationClient import ( + DurableOrchestrationClient) + + +BASE_URL = "https://notification.test/runtime/webhooks/durabletask" +QUERIES = [ + "taskHub=hub&connection=storage&code=synthetic-INSTANCEID%2Bkey%2F%3D", + "CoDe=synthetic-INSTANCEID%2Bkey%2F%3D&site=value%2Bone", + "%63ode=synthetic-INSTANCEID%2Bkey%2F%3D&CODE=duplicate", + "taskHub=hub&connection=storage", + "taskHub=hub&connection=storage&metadata=https://notification.test/info", + "code=synthetic-INSTANCEID%2Bkey%2F%3D&metadata=https://notification.test/INSTANCEID", + "", +] + + +def binding(query): + suffix = "?" + query if query else "" + reason = "?reason={text}" + ("&" + query if query else "") + return { + "taskHubName": "hub", + "rpcBaseUrl": "http://rpc.test/durabletask/", + "creationUrls": { + "createNewInstancePostUri": + BASE_URL + "/orchestrators/{functionName}[/{instanceId}]" + suffix, + }, + "managementUrls": { + "id": "INSTANCEID", + "statusQueryGetUri": BASE_URL + "/instances/INSTANCEID" + suffix, + "sendEventPostUri": + BASE_URL + "/instances/INSTANCEID/raiseEvent/{eventName}" + suffix, + "terminatePostUri": BASE_URL + "/instances/INSTANCEID/terminate" + reason, + }, + } + + +@pytest.mark.parametrize( + "value_url, expected_url", + [ + ( + "https://notification.test/https://notification.test/path" + "?metadata=https://notification.test/info#https://notification.test/fragment", + "http://frontend.test:8080/https://notification.test/path" + "?metadata=https://notification.test/info#https://notification.test/fragment", + ), + ( + "https://notification.test?metadata=https://notification.test/info", + "http://frontend.test:8080?metadata=https://notification.test/info", + ), + ("INSTANCEID", "INSTANCEID"), + ]) +def test_replace_url_origin_changes_only_scheme_and_authority(value_url, expected_url): + request_url = "http://frontend.test:8080/api/start?code=starter-key#request-fragment" + + assert DurableOrchestrationClient._replace_url_origin(request_url, value_url) == expected_url + + +@pytest.mark.parametrize("query", QUERIES) +def test_binding_preserves_host_urls_and_query_strings(query): + data = binding(query) + original = copy.deepcopy(data) + bindings = DurableOrchestrationBindings(**data) + + assert bindings.creation_urls == data["creationUrls"] + assert bindings.management_urls == data["managementUrls"] + assert data == original + + +@pytest.mark.parametrize("query", QUERIES) +def test_response_preserves_host_query_and_string_only_payload(query): + data = binding(query) + original = copy.deepcopy(data) + client = DurableOrchestrationClient(json.dumps(data)) + request = func.HttpRequest( + "GET", "https://frontend.test/api/start?code=starter-key", body=b"") + + response = client.create_check_status_response(request, "instance") + payload = json.loads(response.get_body()) + + notification_origin = "https://notification.test" + expected = { + key: ( + "https://frontend.test" + value[len(notification_origin):] + if value.startswith(notification_origin) else value + ).replace("INSTANCEID", "instance", 1) + for key, value in data["managementUrls"].items() + } + assert response.status_code == 202 + assert response.headers["Location"] == payload["statusQueryGetUri"] + assert response.headers["Retry-After"] == "10" + assert payload == expected + for key, original_url in data["managementUrls"].items(): + if key != "id": + assert urlsplit(payload[key]).query == urlsplit(original_url).query + assert all(isinstance(value, str) for value in payload.values()) + assert "requiredHeaders" not in payload + assert "starter-key" not in json.dumps(payload) + assert "{eventName}" in payload["sendEventPostUri"] + assert data == original + + +@pytest.mark.parametrize("query", QUERIES) +def test_payload_instances_do_not_modify_the_binding(query): + data = binding(query) + original = copy.deepcopy(data) + client = DurableOrchestrationClient(json.dumps(data)) + first = client.create_http_management_payload("first") + first["statusQueryGetUri"] = "changed" + second = client.create_http_management_payload("second") + + assert second["id"] == "second" + assert second["statusQueryGetUri"] == \ + data["managementUrls"]["statusQueryGetUri"].replace("INSTANCEID", "second", 1) + assert data == original + + +@pytest.mark.parametrize("query", QUERIES) +@pytest.mark.asyncio +async def test_management_uses_rpc_without_public_key_credentials(query): + client = DurableOrchestrationClient(json.dumps(binding(query))) + client._post_async_request = AsyncMock(return_value=[202, {"id": "instance"}]) + + assert await client.start_new("Allowed", "instance") == "instance" + + args, kwargs = client._post_async_request.await_args + assert args[0] == "http://rpc.test/durabletask/orchestrators/Allowed/instance" + assert "headers" not in kwargs + assert "code" not in urlsplit(args[0]).query + assert "synthetic" not in str((args, kwargs))