From 3b68495018fdd5b867bf17d8cc41e5ca2279f79f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ronald=20Li=20=F0=9F=9B=A0=EF=B8=8F?= <137369375+RonCodes88@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:58:02 -0800 Subject: [PATCH] feat(sfn): apply the EventBridge connection to HTTP Tasks (#7479) * feat(sfn): apply the EventBridge connection to HTTP Tasks An HTTP Task now resolves the connection named by InvocationConfig or Authentication. Its authorization, headers, query parameters and body parameters are merged over the task's, and the connection's value wins on a duplicate key, as the AWS HTTP Task guide describes. The body is merged before Transform encodes it. A string body with connection body parameters fails with States.Runtime, and an unknown connection fails with Events.ConnectionResource.ResourceNotFound. The connection logic is the API destination's: EventBridgeInvoker exposes it as connectionHttpParameters, so both callers share one implementation, OAuth client credentials included. * fix(sfn): keep case-distinct query parameters and bound OAuth by the HTTP Task timeout A connection query parameter now replaces only a task parameter of the exact same name, since query names are case-sensitive. The connection's OAuth token exchange now spends the task's TimeoutSeconds, so the API request gets only the time left. * chore: retrigger CI --- docs/services/step-functions.md | 14 +- .../eventbridge/EventBridgeInvoker.java | 31 ++- .../services/stepfunctions/AslExecutor.java | 95 ++++++--- .../stepfunctions/AslExecutorFixture.java | 10 +- .../AslExecutorHttpInvokeTest.java | 190 +++++++++++++++++- 5 files changed, 298 insertions(+), 42 deletions(-) diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 212890cb69..9d66b2ad9d 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -849,8 +849,18 @@ Floci currently supports object roots and scalar `COMMAS` arrays. Non-object roo (other than an absent or null body) and `COMMAS` arrays containing objects or arrays fail explicitly instead of being silently coerced. These are Floci limitations, not documented AWS restrictions; their exact AWS behavior has not been verified. -EventBridge connection lookup and connection-level parameter merging are not -implemented by the HTTP Task. + +## HTTP Task connections + +The EventBridge connection named by `InvocationConfig.ConnectionArn` or +`Authentication.ConnectionArn` authorizes the request: `BASIC` and `OAUTH_CLIENT_CREDENTIALS` +set the `Authorization` header and `API_KEY` sets the named header, as for an API destination. +The connection's `InvocationHttpParameters` are merged over the task's `Headers`, +`QueryParameters` and `RequestBody`, and the connection's value wins on a duplicate key, as +[AWS merges them](https://docs.aws.amazon.com/step-functions/latest/dg/call-https-apis.html#http-task-data-merge). +Body parameters are merged before `Transform` encodes the body. A `RequestBody` that is not a +JSON object fails the task with `States.Runtime` when the connection has body parameters, and a +connection that does not exist fails it with `Events.ConnectionResource.ResourceNotFound`. ## Executions abandoned by a restart diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java index 6d8563b279..3837e665e6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java @@ -612,14 +612,14 @@ public class EventBridgeInvoker { HttpParameters httpParameters = target.getHttpParameters(); JsonNode authNode = readAuthParameters(connection); - JsonNode invocationHttp = authNode.path("InvocationHttpParameters"); + ConnectionHttpParameters connectionParameters = invocationHttpParameters(authNode); // The connection's parameters are applied last so a target cannot override what the connection configures Map queryParams = new LinkedHashMap<>(); if (httpParameters != null && httpParameters.getQueryStringParameters() != null) { queryParams.putAll(httpParameters.getQueryStringParameters()); } - queryParams.putAll(readKeyValues(invocationHttp.path("QueryStringParameters"))); + queryParams.putAll(connectionParameters.queryStringParameters()); String resolvedUrl = appendQueryParameters( substitutePathParameters(rawUrl, httpParameters != null ? httpParameters.getPathParameterValues() : null), @@ -631,7 +631,7 @@ public class EventBridgeInvoker { if (httpParameters != null && httpParameters.getHeaderParameters() != null) { httpParameters.getHeaderParameters().forEach((name, value) -> putHeader(headers, name, value)); } - readKeyValues(invocationHttp.path("HeaderParameters")).forEach((name, value) -> putHeader(headers, name, value)); + connectionParameters.headers().forEach((name, value) -> putHeader(headers, name, value)); applyConnectionAuth(connection, authNode, headers); String method = destination.getHttpMethod() != null ? destination.getHttpMethod().toUpperCase() : "POST"; @@ -640,7 +640,7 @@ public class EventBridgeInvoker { headers.put("Content-Type", "application/json; charset=utf-8"); } String body = hasBody - ? mergeBodyParameters(payload, readKeyValues(invocationHttp.path("BodyParameters"))) + ? mergeBodyParameters(payload, connectionParameters.bodyParameters()) : null; HttpRequest request; @@ -825,6 +825,29 @@ public class EventBridgeInvoker { } } + /** + * The parameters a connection adds to a request it authorizes, with its authorization among the headers. + * Callers apply them over their own: on a conflict, the connection's value wins. + */ + public ConnectionHttpParameters connectionHttpParameters(String connectionArn, String region) { + Connection connection = eventBridgeService.findConnectionByArn(connectionArn, region); + JsonNode authNode = readAuthParameters(connection); + ConnectionHttpParameters parameters = invocationHttpParameters(authNode); + applyConnectionAuth(connection, authNode, parameters.headers()); + return parameters; + } + + private static ConnectionHttpParameters invocationHttpParameters(JsonNode authNode) { + JsonNode invocationHttp = authNode.path("InvocationHttpParameters"); + return new ConnectionHttpParameters(readKeyValues(invocationHttp.path("HeaderParameters")), + readKeyValues(invocationHttp.path("QueryStringParameters")), + readKeyValues(invocationHttp.path("BodyParameters"))); + } + + public record ConnectionHttpParameters(Map headers, Map queryStringParameters, + Map bodyParameters) { + } + private static Map readKeyValues(JsonNode params) { Map result = new LinkedHashMap<>(); for (JsonNode param : params) { diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index cd2ab91de0..6a194c4989 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -43,6 +43,8 @@ import io.github.hectorvent.floci.services.ecs.model.LaunchType; import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeInvoker; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeInvoker.ConnectionHttpParameters; import io.github.hectorvent.floci.services.lambda.LambdaArnUtils; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; @@ -267,6 +269,7 @@ public class AslExecutor { private final EcsService ecsService; private final EcsJsonHandler ecsJsonHandler; private final EventBridgeHandler eventBridgeHandler; + private final EventBridgeInvoker eventBridgeInvoker; private final SchedulerService schedulerService; private final SchedulerController schedulerController; private final RdsDataService rdsDataService; @@ -317,7 +320,7 @@ public class AslExecutor { ServiceRegistry serviceRegistry, NestedTaskCredentials nestedTaskCredentials, LambdaTaskAuthorizer lambdaTaskAuthorizer, ApiGatewayTaskInvoker apiGatewayTaskInvoker, EmrTaskInvoker emrTaskInvoker, EmrServerlessTaskInvoker emrServerlessTaskInvoker, - SdkManagementTaskInvoker sdkManagementTaskInvoker) { + SdkManagementTaskInvoker sdkManagementTaskInvoker, EventBridgeInvoker eventBridgeInvoker) { this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler, sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service, ecsService, ecsJsonHandler, @@ -325,7 +328,7 @@ public class AslExecutor { objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness, Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry, nestedTaskCredentials, lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker, emrTaskInvoker, - emrServerlessTaskInvoker, sdkManagementTaskInvoker, null); + emrServerlessTaskInvoker, sdkManagementTaskInvoker, null, eventBridgeInvoker); } AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver, @@ -345,7 +348,7 @@ public class AslExecutor { Duration expressMaxExecutionTimeOverride, LongSupplier nanoTimeOverride, ApiGatewayTaskInvoker apiGatewayTaskInvoker, EmrTaskInvoker emrTaskInvoker, EmrServerlessTaskInvoker emrServerlessTaskInvoker, SdkManagementTaskInvoker sdkManagementTaskInvoker, - NestedWaiter nestedWaiter) { + NestedWaiter nestedWaiter, EventBridgeInvoker eventBridgeInvoker) { this.apiGatewayTaskInvoker = apiGatewayTaskInvoker; this.emrTaskInvoker = emrTaskInvoker; this.emrServerlessTaskInvoker = emrServerlessTaskInvoker; @@ -367,6 +370,7 @@ public class AslExecutor { this.ecsService = ecsService; this.ecsJsonHandler = ecsJsonHandler; this.eventBridgeHandler = eventBridgeHandler; + this.eventBridgeInvoker = eventBridgeInvoker; this.schedulerService = schedulerService; this.schedulerController = schedulerController; this.rdsDataService = rdsDataService; @@ -414,7 +418,7 @@ public class AslExecutor { eventBridgeHandler, schedulerService, schedulerController, rdsDataService, objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness, Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null, null, null, - null, null, null); + null, null, null, null); } // Kept for tests that do not exercise the Redshift Data API integration. @@ -436,7 +440,7 @@ public class AslExecutor { eventBridgeHandler, schedulerService, schedulerController, rdsDataService, objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null, null, null, null, - null); + null, null); } AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore, @@ -5115,12 +5119,10 @@ public class AslExecutor { } /** - * Implements the Step Functions HTTP Task request flow for direct task-provided - * fields. EventBridge connection lookup and connection-level header, query - * parameter, and body merging are intentionally not implemented yet. - * - * TODO: Resolve Authentication/InvocationConfig ConnectionArn through the - * EventBridge connection store and merge connection credentials/parameters. + * Implements the Step Functions HTTP Task request flow. The EventBridge connection's + * authorization, headers, query parameters and body parameters are merged over the + * task's, the connection's value winning on a conflict, as + * documented. * * TODO: Add HTTP retry support. This can be done via Mutiny's retry mechanism * but most likely better to be done at a higher level to support other tasks. @@ -5148,17 +5150,27 @@ public class AslExecutor { } validateHttpMethod(method); - validateConnectionArn(input); + String connectionArn = connectionArn(input); validateHttpHeaders(headers); + // The connection's OAuth token exchange spends the same TimeoutSeconds as the request. + long deadlineNanos = nanoTime.getAsLong() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis); + ConnectionHttpParameters connection = connectionHttpParameters(connectionArn, region); + long remainingMillis = TimeUnit.NANOSECONDS.toMillis(deadlineNanos - nanoTime.getAsLong()); + if (remainingMillis <= 0) { + throw new FailStateException("States.Http.Socket", "The timeout period of " + timeoutMillis + + "ms has been exceeded while authorizing with the connection"); + } - HttpRequestPayload requestPayload = requestPayload(requestBody, requestBodyEncoding, + HttpRequestPayload requestPayload = requestPayload( + mergeConnectionBody(requestBody, connection.bodyParameters()), requestBodyEncoding, input.path("Transform").path("RequestEncodingOptions")); MultiMap requestHeaders = requestHeaders(headers, requestPayload.contentType()); - MultiMap requestQueryParameters = queryParameters(queryParameters); + connection.headers().forEach(requestHeaders::set); + MultiMap requestQueryParameters = queryParameters(queryParameters, connection.queryStringParameters()); try { HttpRequest request = webClient.requestAbs(HttpMethod.valueOf(method), rawUri) - .timeout(timeoutMillis) + .timeout(remainingMillis) .putHeaders(requestHeaders) .putHeader("User-Agent", "Amazon|StepFunctions|HttpInvoke|" + region); request.queryParams().addAll(requestQueryParameters); @@ -5323,7 +5335,7 @@ public class AslExecutor { } } - private void validateConnectionArn(JsonNode input) { + private String connectionArn(JsonNode input) { String connectionArn = input.path("InvocationConfig").path("ConnectionArn").asText(null); if (connectionArn == null || connectionArn.isBlank()) { connectionArn = input.path("Authentication").path("ConnectionArn").asText(null); @@ -5332,6 +5344,36 @@ public class AslExecutor { throw new FailStateException("States.Runtime", "ConnectionArn is required for HTTP task Authentication or InvocationConfig"); } + return connectionArn; + } + + private ConnectionHttpParameters connectionHttpParameters(String connectionArn, String region) { + try { + return eventBridgeInvoker.connectionHttpParameters(connectionArn, region); + } catch (AwsException e) { + String error = "ResourceNotFoundException".equals(e.getErrorCode()) + ? "Events.ConnectionResource.ResourceNotFound" + : "Events.ConnectionResource.InternalError"; + throw new FailStateException(error, e.getMessage()); + } + } + + // A string body cannot take the connection's body parameters; AWS fails the task rather than drop them + private JsonNode mergeConnectionBody(JsonNode requestBody, Map bodyParameters) { + if (bodyParameters.isEmpty()) { + return requestBody; + } + ObjectNode merged; + if (requestBody.isMissingNode() || requestBody.isNull()) { + merged = objectMapper.createObjectNode(); + } else if (requestBody instanceof ObjectNode objectBody) { + merged = objectBody.deepCopy(); + } else { + throw new FailStateException("States.Runtime", + "The RequestBody cannot be merged with the connection's body parameters: it is not a JSON object"); + } + bodyParameters.forEach(merged::put); + return merged; } /** @@ -5359,16 +5401,21 @@ public class AslExecutor { } } - private MultiMap queryParameters(JsonNode queryParameters) { + /** + * The task's query parameters with the connection's merged over them. Query names are + * case-sensitive, so a connection parameter replaces only a task parameter of the same name. + */ + private MultiMap queryParameters(JsonNode queryParameters, Map connectionParameters) { MultiMap params = MultiMap.caseInsensitiveMultiMap(); - if (queryParameters.isMissingNode() || queryParameters.isNull()) { - return params; + if (!queryParameters.isMissingNode() && !queryParameters.isNull()) { + if (!queryParameters.isObject()) { + throw new FailStateException("States.Runtime", "QueryParameters must be a JSON object for HTTP task"); + } + queryParameters.properties().stream() + .filter(entry -> !connectionParameters.containsKey(entry.getKey())) + .forEach(entry -> addQueryParameterValues(params, entry.getKey(), entry.getValue())); } - if (!queryParameters.isObject()) { - throw new FailStateException("States.Runtime", "QueryParameters must be a JSON object for HTTP task"); - } - - queryParameters.properties().forEach(entry -> addQueryParameterValues(params, entry.getKey(), entry.getValue())); + connectionParameters.forEach(params::add); return params; } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFixture.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFixture.java index 6203feeb5b..42bd04a258 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFixture.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; import io.github.hectorvent.floci.services.ecs.EcsService; import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeInvoker; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; import io.github.hectorvent.floci.services.lambda.LambdaTargetResolver; @@ -122,6 +123,7 @@ final class AslExecutorFixture { private AslExecutor.NestedWaiter nestedWaiter; private EmrTaskInvoker emrTaskInvoker; private EmrServerlessTaskInvoker emrServerlessTaskInvoker; + private EventBridgeInvoker eventBridgeInvoker; private Builder() { } @@ -291,6 +293,11 @@ final class AslExecutorFixture { return this; } + Builder eventBridgeInvoker(EventBridgeInvoker eventBridgeInvoker) { + this.eventBridgeInvoker = eventBridgeInvoker; + return this; + } + AslExecutor build() { return new AslExecutor(lambdaExecutor, targetResolver != null ? targetResolver : new LambdaTargetResolver(functionStore, null), @@ -300,7 +307,8 @@ final class AslExecutorFixture { jsonataEvaluator != null ? jsonataEvaluator : new JsonataEvaluator(objectMapper), sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSeconds, redshiftDataHandler, serviceRegistry, null, lambdaTaskAuthorizer, expressMaxExecutionTime, - nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker, null, nestedWaiter); + nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker, null, nestedWaiter, + eventBridgeInvoker); } } } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java index 066be24ecd..2969ea5183 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorHttpInvokeTest.java @@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeInvoker; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; import io.github.hectorvent.floci.services.stepfunctions.model.Execution; import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent; import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine; @@ -25,13 +27,17 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; +import java.util.Base64; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -43,16 +49,18 @@ class AslExecutorHttpInvokeTest { private static final String REGION = "us-west-2"; private static final String ACCOUNT = "000000000000"; - private static final String CONNECTION_ARN = - "arn:aws:events:%s:%s:connection/test/11111111-1111-1111-1111-111111111111" + private static final String MISSING_CONNECTION_ARN = + "arn:aws:events:%s:%s:connection/missing/11111111-1111-1111-1111-111111111111" .formatted(REGION, ACCOUNT); private final ObjectMapper objectMapper = new ObjectMapper(); private final List receivedRequests = new CopyOnWriteArrayList<>(); + private final List connectionNames = new ArrayList<>(); private HttpServer server; private String baseUrl; private AslExecutor executor; + private String connectionArn; @Inject Vertx vertx; @@ -60,6 +68,12 @@ class AslExecutorHttpInvokeTest { @Inject EmulatorConfig emulatorConfig; + @Inject + EventBridgeService eventBridgeService; + + @Inject + EventBridgeInvoker eventBridgeInvoker; + private record RecordedRequest(String method, String path, String query, MultiMap headers, String body) { String firstHeader(String name) { @@ -137,6 +151,16 @@ class AslExecutorHttpInvokeTest { .subscribe().with(it -> { }); }); + router.post("/token-slow") + .handler(ctx -> { + Uni.createFrom().voidItem() + .onItem().delayIt().by(Duration.ofSeconds(2)) + .onItem().transformToUni(ignore -> ctx.response() + .putHeader("Content-Type", "application/json") + .end(Buffer.newInstance(JsonObject.of("access_token", "token").toBuffer()))) + .subscribe().with(it -> { + }); + }); router.get("/form") .handler(ctx -> { ctx.response() @@ -157,7 +181,9 @@ class AslExecutorHttpInvokeTest { .config(emulatorConfig) .vertx(vertx) .customResourceLiveness(null) + .eventBridgeInvoker(eventBridgeInvoker) .build(); + connectionArn = createConnection("BASIC", basicAuth("")); } private void recordRequest(final RoutingContext ctx, String body) { @@ -175,6 +201,7 @@ class AslExecutorHttpInvokeTest { @AfterEach void tearDown() { server.closeAndAwait(); + connectionNames.forEach(name -> eventBridgeService.deleteConnection(name, REGION)); } @Test @@ -205,7 +232,7 @@ class AslExecutorHttpInvokeTest { } } } - """.formatted(baseUrl, CONNECTION_ARN), "{}"); + """.formatted(baseUrl, connectionArn), "{}"); assertEquals("SUCCEEDED", execution.getStatus()); JsonNode output = objectMapper.readTree(execution.getOutput()); @@ -252,7 +279,7 @@ class AslExecutorHttpInvokeTest { } } } - """.formatted(CONNECTION_ARN), """ + """.formatted(connectionArn), """ { "endpoint": "%s/text", "method": "POST", @@ -300,7 +327,7 @@ class AslExecutorHttpInvokeTest { } } } - """.formatted(baseUrl, CONNECTION_ARN), """ + """.formatted(baseUrl, connectionArn), """ { "customerId": null } @@ -332,7 +359,7 @@ class AslExecutorHttpInvokeTest { } } } - """.formatted(baseUrl, CONNECTION_ARN), "{}"); + """.formatted(baseUrl, connectionArn), "{}"); assertEquals("FAILED", execution.getStatus()); assertEquals("States.Http.StatusCode.429", execution.getError()); @@ -363,7 +390,7 @@ class AslExecutorHttpInvokeTest { } } } - """.formatted(baseUrl, CONNECTION_ARN), "{}"); + """.formatted(baseUrl, connectionArn), "{}"); assertEquals("FAILED", execution.getStatus()); assertEquals("States.Runtime", execution.getError()); @@ -417,7 +444,7 @@ class AslExecutorHttpInvokeTest { } } } - """.formatted(CONNECTION_ARN), """ + """.formatted(connectionArn), """ { "endpoint": "%s/jsonslow", "method": "GET", @@ -427,7 +454,8 @@ class AslExecutorHttpInvokeTest { assertEquals("FAILED", execution.getStatus()); assertEquals("States.Http.Socket", execution.getError()); - assertThat(execution.getCause(), startsWith("The timeout period of 1000ms has been exceeded while executing GET /jsonslow for server")); + assertThat(execution.getCause(), matchesPattern( + "The timeout period of \\d+ms has been exceeded while executing GET /jsonslow for server.*")); } @Test @@ -457,7 +485,7 @@ class AslExecutorHttpInvokeTest { } } } - """.formatted(CONNECTION_ARN), """ + """.formatted(connectionArn), """ { "endpoint": "%s/form", "method": "GET", @@ -514,6 +542,146 @@ class AslExecutorHttpInvokeTest { assertEquals(0, receivedRequests.size()); } + @Test + void basicConnectionAuthorizesTheRequest() { + Execution execution = run(getJsonDefinition(connectionArn), "{}"); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + assertEquals("Basic " + Base64.getEncoder().encodeToString("user:secret".getBytes(StandardCharsets.UTF_8)), + onlyRequest().firstHeader("Authorization")); + } + + @Test + void connectionParametersAreMergedOverTheTasksAndWinOnDuplicateKeys() throws Exception { + // The data merging example of the AWS HTTP Task guide, with its API_KEY connection. + String apiKeyConnection = createConnection("API_KEY", """ + {"ApiKeyAuthParameters":{"ApiKeyName":"ApiKey","ApiKeyValue":"key_value"}, + "InvocationHttpParameters":{ + "BodyParameters":[{"Key":"BodyParam","Value":"connection_body_param"}], + "HeaderParameters":[{"Key":"Header-Param","Value":"connection_header_param"}], + "QueryStringParameters":[{"Key":"QueryParam","Value":"connection_query_param"}]}} + """); + + Execution execution = run(""" + {"StartAt":"CallHttp","States":{"CallHttp":{"Type":"Task", + "Resource":"arn:aws:states:::http:invoke","Parameters":{ + "ApiEndpoint":"%s/text","Method":"POST", + "Authentication":{"ConnectionArn":"%s"}, + "Headers":{"Request-Id":"my_request_id","header-param":"state_machine_header_param"}, + "RequestBody":{"Job":"Software Engineer","BodyParam":"state_machine_body_param"}, + "QueryParameters":{"QueryParam":"state_machine_query_param"} + },"End":true}}} + """.formatted(baseUrl, apiKeyConnection), "{}"); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + RecordedRequest request = onlyRequest(); + assertEquals("/text?QueryParam=connection_query_param", request.path()); + assertEquals(List.of("key_value"), request.headerValues("ApiKey")); + assertEquals(List.of("connection_header_param"), request.headerValues("Header-Param")); + assertEquals(List.of("my_request_id"), request.headerValues("Request-Id")); + assertEquals(objectMapper.readTree(""" + {"Job":"Software Engineer","BodyParam":"connection_body_param"} + """), objectMapper.readTree(request.body())); + } + + @Test + void connectionBodyParametersAreMergedBeforeTheBodyIsUrlEncoded() { + connectionArn = createConnection("BASIC", basicAuth(""" + ,"InvocationHttpParameters":{"BodyParameters":[{"Key":"mode","Value":"live"}]}""")); + + Execution execution = runForm("{\"items\":[\"a\",\"b\"]}", "{\"ArrayFormat\":\"REPEAT\"}"); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + assertEquals("items=a&items=b&mode=live", onlyRequest().body()); + } + + @Test + void stringRequestBodyCannotTakeConnectionBodyParameters() { + String bodyConnection = createConnection("BASIC", basicAuth(""" + ,"InvocationHttpParameters":{"BodyParameters":[{"Key":"mode","Value":"live"}]}""")); + + Execution execution = run(""" + {"StartAt":"CallHttp","States":{"CallHttp":{"Type":"Task", + "Resource":"arn:aws:states:::http:invoke","Parameters":{ + "ApiEndpoint":"%s/text","Method":"POST", + "InvocationConfig":{"ConnectionArn":"%s"}, + "RequestBody":"plain text" + },"End":true}}} + """.formatted(baseUrl, bodyConnection), "{}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.Runtime", execution.getError()); + assertEquals(0, receivedRequests.size()); + } + + @Test + void connectionQueryParameterReplacesOnlyTheSameCaseSensitiveName() { + String queryConnection = createConnection("BASIC", basicAuth(""" + ,"InvocationHttpParameters":{"QueryStringParameters":[{"Key":"foo","Value":"connection"}]}""")); + + Execution execution = run(""" + {"StartAt":"CallHttp","States":{"CallHttp":{"Type":"Task", + "Resource":"arn:aws:states:::http:invoke","Parameters":{ + "ApiEndpoint":"%s/json","Method":"GET", + "InvocationConfig":{"ConnectionArn":"%s"}, + "QueryParameters":{"Foo":"task"} + },"End":true}}} + """.formatted(baseUrl, queryConnection), "{}"); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + assertEquals("/json?Foo=task&foo=connection", onlyRequest().path()); + } + + @Test + void oauthTokenExchangeSpendsTheTasksTimeout() { + String oauthConnection = createConnection("OAUTH_CLIENT_CREDENTIALS", """ + {"OAuthParameters":{"AuthorizationEndpoint":"%s/token-slow","HttpMethod":"POST", + "ClientParameters":{"ClientID":"cid","ClientSecret":"csecret"}}} + """.formatted(baseUrl)); + + Execution execution = run(""" + {"StartAt":"CallHttp","States":{"CallHttp":{"Type":"Task", + "Resource":"arn:aws:states:::http:invoke","Parameters":{ + "ApiEndpoint":"%s/json","Method":"GET","TimeoutSeconds":1, + "InvocationConfig":{"ConnectionArn":"%s"} + },"End":true}}} + """.formatted(baseUrl, oauthConnection), "{}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.Http.Socket", execution.getError()); + assertEquals(0, receivedRequests.size()); + } + + @Test + void missingConnectionFailsWithConnectionResourceNotFound() { + Execution execution = run(getJsonDefinition(MISSING_CONNECTION_ARN), "{}"); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("Events.ConnectionResource.ResourceNotFound", execution.getError()); + assertEquals(0, receivedRequests.size()); + } + + private String getJsonDefinition(String connection) { + return """ + {"StartAt":"CallHttp","States":{"CallHttp":{"Type":"Task", + "Resource":"arn:aws:states:::http:invoke","Parameters":{ + "ApiEndpoint":"%s/json","Method":"GET", + "InvocationConfig":{"ConnectionArn":"%s"} + },"End":true}}} + """.formatted(baseUrl, connection); + } + + private String createConnection(String authorizationType, String authParameters) { + String name = "http-task-" + UUID.randomUUID(); + connectionNames.add(name); + return eventBridgeService.createConnection(name, null, authorizationType, authParameters, null, null, REGION) + .getConnectionArn(); + } + + private static String basicAuth(String moreAuthParameters) { + return "{\"BasicAuthParameters\":{\"Username\":\"user\",\"Password\":\"secret\"}" + moreAuthParameters + "}"; + } + private Execution runForm(String body, String options) { return run(""" {"StartAt":"CallHttp","States":{"CallHttp":{"Type":"Task", @@ -524,7 +692,7 @@ class AslExecutorHttpInvokeTest { "RequestBody.$":"$.body", "Transform":{"RequestBodyEncoding":"URL_ENCODED","RequestEncodingOptions":%s} },"End":true}}} - """.formatted(baseUrl, CONNECTION_ARN, options), "{\"body\":" + body + "}"); + """.formatted(baseUrl, connectionArn, options), "{\"body\":" + body + "}"); } private Execution run(String definition, String input) {