Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
51 changes: 37 additions & 14 deletions azure/durable_functions/models/DurableOrchestrationClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import List, Any, Optional, Dict, Union
from time import time
from asyncio import sleep
from urllib.parse import urlparse, quote
from urllib.parse import urlparse, urlsplit, quote
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

import azure.functions as func
Expand Down Expand Up @@ -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
----------
Expand All @@ -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)

Expand Down Expand Up @@ -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
----------
Expand All @@ -221,15 +229,14 @@ 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():
placeholder = self._orchestration_bindings.management_urls["id"]
for key, value in payload.items():
if not (request is None) and request.url:
payload[key] = self._replace_url_origin(request.url, payload[key])
payload[key] = payload[key].replace(
self._orchestration_bindings.management_urls["id"], instance_id)
value = self._replace_url_origin(request.url, value)
payload[key] = self._replace_instance_id(value, placeholder, instance_id)

return payload

Expand Down Expand Up @@ -653,10 +660,26 @@ 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 _replace_instance_id(value: str, placeholder: str, instance_id: str) -> str:
url = urlsplit(value)
if not url.scheme or not url.netloc:
# The payload's plain "id" value.
return value.replace(placeholder, instance_id, 1)
# The host appends only fixed operations after the instance segment, so the last
# path match is the instance ID. The authority and query remain unchanged.
index = url.path.rfind(placeholder)
if index < 0:
return value
path = url.path[:index] + instance_id + url.path[index + len(placeholder):]
return url._replace(path=path).geturl()

@staticmethod
def _parse_purge_instance_history_response(
Expand Down
172 changes: 172 additions & 0 deletions tests/models/test_http_management_compatibility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
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(
"request_url, base_url, expected_base",
[
(
"https://INSTANCEID.example.test/api/start",
BASE_URL,
"https://INSTANCEID.example.test/runtime/webhooks/durabletask",
),
(
None,
"https://notification.test/INSTANCEID-base/runtime/webhooks/durabletask",
"https://notification.test/INSTANCEID-base/runtime/webhooks/durabletask",
),
])
def test_instance_id_replaces_only_the_instance_path_segment(
request_url, base_url, expected_base):
query = "?taskHub=hub&code=synthetic-INSTANCEID"
data = binding("")
data["managementUrls"] = {
"id": "INSTANCEID",
"statusQueryGetUri": base_url + "/instances/INSTANCEID" + query,
"sendEventPostUri": base_url + "/instances/INSTANCEID/raiseEvent/{eventName}" + query,
}
client = DurableOrchestrationClient(json.dumps(data))
request = None if request_url is None else func.HttpRequest("GET", request_url, body=b"")

assert client.get_client_response_links(request, "actual") == {
"id": "actual",
"statusQueryGetUri": expected_base + "/instances/actual" + query,
"sendEventPostUri": expected_base + "/instances/actual/raiseEvent/{eventName}" + query,
}


@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))
Loading