diff --git a/CHANGELOG.md b/CHANGELOG.md index 72a1c909..ea99c63a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## Unreleased +* Preserve host-provided Durable Functions management URL query parameters and support null, empty, or `?`-prefixed binding queries without extra URL separators. Key-free URLs are controlled by the host's opt-in setting; existing URL authentication remains unchanged by default. * Send a unique `hostname:pid:uuid` identifier in the `workerid` gRPC header for each worker instance, matching Python. Retain the ID across requests and reconnects while keeping IDs distinct for workers sharing a channel or builder. * Write self-describing v2 blob payload tokens by default while retaining v1 and v2 reads from the configured storage endpoint and container. Require complete token formats for direct downloads and account for URL token length in worker action-size estimates. Upgrade readers before deploying v2 writers; changing storage locations requires explicit migration or a store configured for the original location. * Add explicit primary-account-wide and additional-account read scopes for Azure Blob payloads while retaining configured-container access by default. Additional accounts require identity authentication and exact HTTPS account service endpoints. Preserve named and nested v1/v2 references and ignore legacy v2 URL query and fragment suffixes. diff --git a/azurefunctions/README.md b/azurefunctions/README.md index 132daa00..e33873fd 100644 --- a/azurefunctions/README.md +++ b/azurefunctions/README.md @@ -228,3 +228,44 @@ Server: Kestrel ``` At this point, you now have a fully function Durable Functions for Java development environment! + +## Opt-in management URL key exclusion + +The examples above show the default behavior: management URLs contain the Durable +system key in `code`. The Java SDK preserves the query parameters supplied by the +Functions host; it does not remove keys or return authentication headers. + +On a host extension version that supports the option, an app can exclude the key +from generated management URLs by adding the following to `host.json`: + +```json +{ + "extensions": { + "durableTask": { + "httpSettings": { + "excludeManagementKeyFromUrls": true + } + } + } +} +``` + +This setting defaults to `false`. Before enabling it, ensure every HTTP management +caller can obtain an authorized Durable system key independently and send it in +`x-functions-key` on each request. Following `Location` alone will not authenticate +key-free URLs. For example, with the key and returned status URL supplied through +environment variables: + +```bash +curl -i -H "x-functions-key: ${DURABLE_SYSTEM_KEY}" "${STATUS_QUERY_GET_URI}" +``` + +Do not log the key, append it to URLs, or forward it to unrelated origins. The +option does not redact incoming requests or existing logs, and callers that +continue sending `code` in query strings can still expose keys in HTTP logs. + +The repository's CI currently tests the default mode. An authenticated opt-in CI +leg is tracked as a follow-up in the E2E workflow until the released host extension +bundle supports this setting. Local opt-in E2E runs require authentication and the +setting enabled on the host, the same setting enabled for the test process, and +the host's independently obtained system key in `E2E_TEST_DURABLE_SYSTEM_KEY`. diff --git a/azurefunctions/src/main/java/com/microsoft/durabletask/azurefunctions/DurableClientContext.java b/azurefunctions/src/main/java/com/microsoft/durabletask/azurefunctions/DurableClientContext.java index 34d7d549..468fa59c 100644 --- a/azurefunctions/src/main/java/com/microsoft/durabletask/azurefunctions/DurableClientContext.java +++ b/azurefunctions/src/main/java/com/microsoft/durabletask/azurefunctions/DurableClientContext.java @@ -120,11 +120,11 @@ public HttpResponseMessage createCheckStatusResponse(HttpRequestMessage reque // More info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded. // One potential workaround is to set ASPNETCORE_FORWARDEDHEADERS_ENABLED to true. - // Construct the response as an HTTP 202 with a JSON object payload + HttpManagementPayload payload = this.getClientResponseLinks(request, instanceId); return request.createResponseBuilder(HttpStatus.ACCEPTED) - .header("Location", this.getInstanceStatusURL(request, instanceId) + "?" + this.requiredQueryStringParameters) + .header("Location", payload.getStatusQueryGetUri()) .header("Content-Type", "application/json") - .body(this.getClientResponseLinks(request, instanceId)) + .body(payload) .build(); } diff --git a/azurefunctions/src/main/java/com/microsoft/durabletask/azurefunctions/HttpManagementPayload.java b/azurefunctions/src/main/java/com/microsoft/durabletask/azurefunctions/HttpManagementPayload.java index 43e16ac9..c4bf89ab 100644 --- a/azurefunctions/src/main/java/com/microsoft/durabletask/azurefunctions/HttpManagementPayload.java +++ b/azurefunctions/src/main/java/com/microsoft/durabletask/azurefunctions/HttpManagementPayload.java @@ -8,6 +8,9 @@ /** * The class that holds the webhook URLs to manage orchestration instances. + * The Functions host controls whether these URLs include a system key. + * When {@code httpSettings.excludeManagementKeyFromUrls} is enabled, callers + * must obtain a key separately and send it in the {@code x-functions-key} request header. */ public class HttpManagementPayload { private final String id; @@ -25,21 +28,28 @@ public class HttpManagementPayload { * * @param instanceId The ID of the orchestration instance * @param instanceStatusURL The base webhook url of the orchestration instance - * @param requiredQueryStringParameters The query parameters to include with the http request + * @param requiredQueryStringParameters The query parameters supplied by the Functions host, preserved unchanged */ public HttpManagementPayload( String instanceId, String instanceStatusURL, String requiredQueryStringParameters) { + String query = requiredQueryStringParameters == null ? "" : requiredQueryStringParameters; + if (query.startsWith("?")) { + query = query.substring(1); + } + + String querySuffix = query.isEmpty() ? "" : "?" + query; + String reasonSuffix = "?reason={text}" + (query.isEmpty() ? "" : "&" + query); this.id = instanceId; - this.purgeHistoryDeleteUri = instanceStatusURL + "?" + requiredQueryStringParameters; - this.restartPostUri = instanceStatusURL + "/restart?" + requiredQueryStringParameters; - this.rewindPostUri = instanceStatusURL + "/rewind?reason={text}&" + requiredQueryStringParameters; - this.sendEventPostUri = instanceStatusURL + "/raiseEvent/{eventName}?" + requiredQueryStringParameters; - this.statusQueryGetUri = instanceStatusURL + "?" + requiredQueryStringParameters; - this.terminatePostUri = instanceStatusURL + "/terminate?reason={text}&" + requiredQueryStringParameters; - this.resumePostUri = instanceStatusURL + "/resume?reason={text}&" + requiredQueryStringParameters; - this.suspendPostUri = instanceStatusURL + "/suspend?reason={text}&" + requiredQueryStringParameters; + this.purgeHistoryDeleteUri = instanceStatusURL + querySuffix; + this.restartPostUri = instanceStatusURL + "/restart" + querySuffix; + this.rewindPostUri = instanceStatusURL + "/rewind" + reasonSuffix; + this.sendEventPostUri = instanceStatusURL + "/raiseEvent/{eventName}" + querySuffix; + this.statusQueryGetUri = instanceStatusURL + querySuffix; + this.terminatePostUri = instanceStatusURL + "/terminate" + reasonSuffix; + this.resumePostUri = instanceStatusURL + "/resume" + reasonSuffix; + this.suspendPostUri = instanceStatusURL + "/suspend" + reasonSuffix; } /** diff --git a/azurefunctions/src/test/java/com/microsoft/durabletask/azurefunctions/DurableClientContextTest.java b/azurefunctions/src/test/java/com/microsoft/durabletask/azurefunctions/DurableClientContextTest.java new file mode 100644 index 00000000..b0b61dc9 --- /dev/null +++ b/azurefunctions/src/test/java/com/microsoft/durabletask/azurefunctions/DurableClientContextTest.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.durabletask.azurefunctions; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.microsoft.azure.functions.HttpRequestMessage; +import com.microsoft.azure.functions.HttpResponseMessage; +import com.microsoft.azure.functions.HttpStatus; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.net.URI; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class DurableClientContextTest { + private final Gson gson = new Gson(); + + @ParameterizedTest + // The host owns key filtering; these query spellings verify opaque SDK pass-through. + @ValueSource(strings = { + "taskHub=hub&connection=storage&code=synthetic%2Bkey", + "CoDe=synthetic%2Bkey&site=example", + "%63ode=synthetic%2Bkey&site=example&CODE=duplicate", + "taskHub=hub&connection=storage", + "" + }) + void bindingQueryPassesThroughToPayloadAndLocation(String query) { + JsonObject binding = new JsonObject(); + binding.addProperty("rpcBaseUrl", "http://127.0.0.1:12345"); + binding.addProperty("requiredQueryStringParameters", query); + assertCheckStatusResponse(binding, query.isEmpty() ? "" : "?" + query); + } + + @Test + void bindingQueriesRemainScopedToEachContext() { + DurableClientContext first = this.gson.fromJson( + "{\"requiredQueryStringParameters\":\"code=first\"}", DurableClientContext.class); + DurableClientContext second = this.gson.fromJson( + "{\"requiredQueryStringParameters\":\"\"}", DurableClientContext.class); + HttpRequestMessage request = request(); + + assertTrue(first.createHttpManagementPayload(request, "instance").getStatusQueryGetUri().endsWith("?code=first")); + assertEquals("https://example.com/runtime/webhooks/durabletask/instances/instance", + second.createHttpManagementPayload(request, "instance").getStatusQueryGetUri()); + } + + private void assertCheckStatusResponse(JsonObject binding, String query) { + DurableClientContext context = this.gson.fromJson(binding, DurableClientContext.class); + HttpRequestMessage request = request(); + HttpResponseMessage.Builder builder = mock(HttpResponseMessage.Builder.class, RETURNS_SELF); + HttpResponseMessage response = mock(HttpResponseMessage.class); + when(request.createResponseBuilder(HttpStatus.ACCEPTED)).thenReturn(builder); + when(builder.build()).thenReturn(response); + + assertSame(response, context.createCheckStatusResponse(request, "instance")); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(builder).body(body.capture()); + HttpManagementPayload payload = (HttpManagementPayload) body.getValue(); + String expectedUrl = "https://example.com/runtime/webhooks/durabletask/instances/instance" + query; + assertEquals(expectedUrl, payload.getStatusQueryGetUri()); + verify(builder).header("Location", expectedUrl); + JsonObject json = this.gson.toJsonTree(payload).getAsJsonObject(); + assertTrue(json.entrySet().stream().allMatch(entry -> entry.getValue().isJsonPrimitive() + && entry.getValue().getAsJsonPrimitive().isString())); + assertFalse(this.gson.toJson(payload).contains("starter-key")); + } + + private static HttpRequestMessage request() { + HttpRequestMessage request = mock(HttpRequestMessage.class); + when(request.getUri()).thenReturn(URI.create("https://example.com/api/start?code=starter-key")); + return request; + } +} diff --git a/azurefunctions/src/test/java/com/microsoft/durabletask/azurefunctions/HttpManagementPayloadTest.java b/azurefunctions/src/test/java/com/microsoft/durabletask/azurefunctions/HttpManagementPayloadTest.java index 2798164b..a3497b8d 100644 --- a/azurefunctions/src/test/java/com/microsoft/durabletask/azurefunctions/HttpManagementPayloadTest.java +++ b/azurefunctions/src/test/java/com/microsoft/durabletask/azurefunctions/HttpManagementPayloadTest.java @@ -2,6 +2,10 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Arrays; import static org.junit.jupiter.api.Assertions.*; @@ -12,7 +16,7 @@ public class HttpManagementPayloadTest { private static final String INSTANCE_ID = "test-instance-id"; private static final String INSTANCE_STATUS_URL = "http://localhost:7071/runtime/webhooks/durabletask/instances/test-instance-id"; - private static final String QUERY_STRING = "code=abc123"; + private static final String QUERY_STRING = "taskHub=hub&connection=storage"; private HttpManagementPayload createPayload() { return new HttpManagementPayload(INSTANCE_ID, INSTANCE_STATUS_URL, QUERY_STRING); @@ -80,4 +84,31 @@ public void getRewindPostUri_ReturnsCorrectUrl() { HttpManagementPayload payload = createPayload(); assertEquals(INSTANCE_STATUS_URL + "/rewind?reason={text}&" + QUERY_STRING, payload.getRewindPostUri()); } + + @ParameterizedTest + @ValueSource(strings = { + "code=synthetic%2Bkey%2F%3D&site=value%2Bone", + "site=value%2Bone&CoDe=synthetic%2Bkey%2F%3D", + "%63ode=synthetic%2Bkey%2F%3D&site=value%2Bone&CODE=duplicate" + }) + void hostQueryIsPreservedWithoutMovingKeysToMetadata(String query) { + HttpManagementPayload payload = new HttpManagementPayload(INSTANCE_ID, INSTANCE_STATUS_URL, query); + + assertEquals(INSTANCE_STATUS_URL + "?" + query, payload.getStatusQueryGetUri()); + for (String url : Arrays.asList( + payload.getStatusQueryGetUri(), payload.getSendEventPostUri(), payload.getTerminatePostUri(), + payload.getRewindPostUri(), payload.getPurgeHistoryDeleteUri(), payload.getRestartPostUri(), + payload.getSuspendPostUri(), payload.getResumePostUri())) { + assertTrue(url.endsWith(query)); + } + } + + @Test + void missingOrEmptyQueryDoesNotAddNullOrTrailingSeparators() { + for (String query : new String[] { null, "" }) { + HttpManagementPayload payload = new HttpManagementPayload(INSTANCE_ID, INSTANCE_STATUS_URL, query); + assertEquals(INSTANCE_STATUS_URL, payload.getStatusQueryGetUri()); + assertEquals(INSTANCE_STATUS_URL + "/terminate?reason={text}", payload.getTerminatePostUri()); + } + } } diff --git a/endtoendtests/src/test/java/com/functions/EndToEndTests.java b/endtoendtests/src/test/java/com/functions/EndToEndTests.java index f596ed4e..a89af172 100644 --- a/endtoendtests/src/test/java/com/functions/EndToEndTests.java +++ b/endtoendtests/src/test/java/com/functions/EndToEndTests.java @@ -4,6 +4,9 @@ import io.restassured.http.ContentType; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; +import io.restassured.specification.QueryableRequestSpecification; +import io.restassured.specification.RequestSpecification; +import io.restassured.specification.SpecificationQuerier; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Tag; @@ -11,24 +14,34 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import java.net.URI; import java.time.Duration; import java.time.Instant; import java.util.HashSet; +import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; -import static io.restassured.RestAssured.get; -import static io.restassured.RestAssured.post; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; @Tag("e2e") public class EndToEndTests { + private static final String EXCLUDE_KEY_SETTING = + "AzureFunctionsJobHost__extensions__durableTask__httpSettings__excludeManagementKeyFromUrls"; + private static final String SYSTEM_KEY = System.getenv("E2E_TEST_DURABLE_SYSTEM_KEY"); @BeforeAll public static void setup() { + if (Boolean.parseBoolean(System.getenv(EXCLUDE_KEY_SETTING)) + && (SYSTEM_KEY == null || SYSTEM_KEY.isEmpty())) { + throw new IllegalStateException( + "E2E_TEST_DURABLE_SYSTEM_KEY is required when management URL key exclusion is enabled."); + } RestAssured.baseURI = "http://localhost"; // Use port 8080 for Docker, 7071 for local func start String port = System.getenv("FUNCTIONS_PORT"); @@ -70,6 +83,61 @@ public void generalFunctions(String functionName) throws InterruptedException { assertTrue(pass); } + @Test + public void managementUrlsFollowHostSetting() throws InterruptedException { + Response response = post("/api/StartOrchestration"); + assertEquals(202, response.statusCode()); + JsonPath management = response.jsonPath(); + Map payload = management.getMap(""); + assertFalse(payload.containsKey("requiredHeaders")); + boolean excludeKey = Boolean.parseBoolean(System.getenv(EXCLUDE_KEY_SETTING)); + for (Map.Entry entry : payload.entrySet()) { + if (entry.getKey().endsWith("Uri")) { + String url = (String) entry.getValue(); + assertEquals(!excludeKey, url.toLowerCase(java.util.Locale.ROOT).contains("code=")); + } + } + String statusUrl = management.getString("statusQueryGetUri"); + assertEquals(statusUrl, response.header("Location")); + if (excludeKey) { + assertEquals(401, RestAssured.given().redirects().follow(false).get(statusUrl).statusCode()); + assertEquals(401, RestAssured.given().redirects().follow(false) + .header("x-functions-key", "invalid-system-key").get(statusUrl).statusCode()); + } else { + int status = RestAssured.given().redirects().follow(false).get(statusUrl).statusCode(); + assertTrue(status == 200 || status == 202); + } + assertTrue(pollingCheck(statusUrl, "Completed", null, Duration.ofSeconds(30))); + } + + @Test + public void requestsWithoutManagementCredentialsKeepDefaultHttpBehavior() { + RequestSpecification request = requestFor( + "https://proxy.example/runtime/webhooks/durabletask/instances/test", null); + QueryableRequestSpecification specification = SpecificationQuerier.query(request); + + assertFalse(specification.getHeaders().hasHeaderWithName("x-functions-key")); + assertEquals(RestAssured.config.getRedirectConfig().followsRedirects(), + specification.getConfig().getRedirectConfig().followsRedirects()); + } + + @Test + public void managementCredentialsAreScopedToTrustedEndpoints() { + String key = "synthetic-management-key"; + String path = "/runtime/webhooks/durabletask/instances/test"; + String trustedUrl = RestAssured.baseURI + ":" + RestAssured.port + path; + QueryableRequestSpecification management = SpecificationQuerier.query(requestFor(trustedUrl, key)); + assertEquals(key, management.getHeaders().getValue("x-functions-key")); + + assertThrows(AssertionError.class, + () -> requestFor("http://untrusted.example:" + RestAssured.port + path, key)); + QueryableRequestSpecification anonymous = SpecificationQuerier.query( + requestFor("https://proxy.example/api/start", key)); + assertFalse(anonymous.getHeaders().hasHeaderWithName("x-functions-key")); + assertEquals(RestAssured.config.getRedirectConfig().followsRedirects(), + anonymous.getConfig().getRedirectConfig().followsRedirects()); + } + @Test public void retryTest() throws InterruptedException { String startOrchestrationPath = "/api/RetriableOrchestration"; @@ -132,8 +200,7 @@ public void continueAsNewExternalEvent() throws InterruptedException { sendEventPostUri = sendEventPostUri.replace("{eventName}", "event"); // empty request body - RestAssured - .given() + requestFor(sendEventPostUri) .contentType(ContentType.JSON) // Set the request content type .body("{}") .post(sendEventPostUri) @@ -167,7 +234,9 @@ public void restart(boolean restartWithNewInstanceId) throws InterruptedExceptio Response statusResponse = get(statusQueryGetUri); String instanceId = statusResponse.jsonPath().get("instanceId"); - String restartPostUri = jsonPath.get("restartPostUri") + "&restartWithNewInstanceId=" + restartWithNewInstanceId; + String restartUrl = jsonPath.get("restartPostUri"); + String restartPostUri = restartUrl + (restartUrl.contains("?") ? "&" : "?") + + "restartWithNewInstanceId=" + restartWithNewInstanceId; Response restartResponse = post(restartPostUri); JsonPath restartJsonPath = restartResponse.jsonPath(); String restartStatusQueryGetUri = restartJsonPath.get("statusQueryGetUri"); @@ -216,8 +285,7 @@ public void suspendResume() throws InterruptedException { sendEventPostUri = sendEventPostUri.replace("{eventName}", "test"); String requestBody = "{\"value\":\"Test\"}"; - RestAssured - .given() + requestFor(sendEventPostUri) .contentType(ContentType.JSON) // Set the request content type .body(requestBody) // Set the request body .post(sendEventPostUri) @@ -311,8 +379,7 @@ public void externalEventDeserializeFail() throws InterruptedException { sendEventPostUri = sendEventPostUri.replace("{eventName}", "event"); String requestBody = "{\"value\":\"Test\"}"; - RestAssured - .given() + requestFor(sendEventPostUri) .contentType(ContentType.JSON) // Set the request content type .body(requestBody) // Set the request body .post(sendEventPostUri) @@ -590,6 +657,39 @@ public void callHttp() throws InterruptedException { assertEquals(200, output); } + private RequestSpecification requestFor(String url) { + return requestFor(url, SYSTEM_KEY); + } + + private RequestSpecification requestFor(String url, String systemKey) { + RequestSpecification request = RestAssured.given(); + if (systemKey != null && !systemKey.isEmpty() + && (url.startsWith("http://") || url.startsWith("https://"))) { + int queryStart = url.indexOf('?'); + URI target = URI.create(queryStart < 0 ? url : url.substring(0, queryStart)); + if (!target.getPath().startsWith("/runtime/webhooks/durabletask/")) { + return request; + } + + URI base = URI.create(RestAssured.baseURI); + assertEquals(base.getScheme(), target.getScheme(), "Unexpected management URL scheme"); + assertEquals(base.getHost(), target.getHost(), "Unexpected management URL host"); + int port = target.getPort() < 0 + ? ("https".equals(target.getScheme()) ? 443 : 80) : target.getPort(); + assertEquals(RestAssured.port, port, "Unexpected management URL port"); + request.header("x-functions-key", systemKey).redirects().follow(false); + } + return request; + } + + private Response get(String url) { + return requestFor(url).get(url); + } + + private Response post(String url, Object... pathParameters) { + return requestFor(url).post(url, pathParameters); + } + private boolean pollingCheck(String statusQueryGetUri, String expectedState, Set continueStates,