diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java index c8d49a12a5..e5a1d7e453 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java @@ -813,6 +813,13 @@ public class ApiGatewayExecuteController { bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod, resource.getPath(), requestId, regionResolver.getAccountId(), null); + // AWS selects the request template by the *incoming* request Content-Type. Capture it + // before parameter mapping runs, since an integration.request.header.Content-Type + // override (common for SQS query-protocol integrations) would otherwise clobber it and + // misdirect template selection. + String incomingContentType = headerMap.getOrDefault("Content-Type", + headerMap.getOrDefault("content-type", "application/json")); + // Apply request parameter mapping (method.request.* → integration.request.*) Map integrationReqParams = integration.getRequestParameters(); if (integrationReqParams != null && !integrationReqParams.isEmpty()) { @@ -835,8 +842,6 @@ public class ApiGatewayExecuteController { // Content-Type negotiation and passthrough behavior String transformedBody; Map requestTemplates = integration.getRequestTemplates(); - String incomingContentType = headerMap.getOrDefault("Content-Type", - headerMap.getOrDefault("content-type", "application/json")); if (requestTemplates != null && !requestTemplates.isEmpty()) { // Try exact match first, then wildcard fallback @@ -879,13 +884,23 @@ public class ApiGatewayExecuteController { transformedBody = bodyStr != null ? bodyStr : ""; } - // Dispatch to service + // Dispatch to service. + // + // A path-style integration URI (arn:...:{service}:path/...) carries no action: the + // rendered template body is the AWS query protocol (form-urlencoded, + // "Action=SendMessage&..."). Action-style URIs (arn:...:{service}:action/{Action}) + // carry the action in the URI and render a JSON body. Response serviceResponse; String errorType = null; String errorMessage = null; try { - JsonNode requestJson = objectMapper.readTree(transformedBody); - serviceResponse = serviceRouter.invoke(target.service(), target.action(), requestJson, region); + if (target.action() == null) { + MultivaluedMap formParams = parseFormUrlEncoded(transformedBody); + serviceResponse = serviceRouter.invokeQuery(target.service(), formParams, region); + } else { + JsonNode requestJson = objectMapper.readTree(transformedBody); + serviceResponse = serviceRouter.invoke(target.service(), target.action(), requestJson, region); + } } catch (AwsException e) { errorType = e.getErrorCode(); errorMessage = e.getMessage(); @@ -1810,6 +1825,27 @@ public class ApiGatewayExecuteController { return objectMapper.createObjectNode().put("message", message).toString(); } + /** + * Parses an {@code application/x-www-form-urlencoded} body into a {@link MultivaluedMap}, + * matching the form parameters an AWS query-protocol handler expects. Both keys and values + * are URL-decoded. Parameters without a value (e.g. a bare {@code "Key"}) map to an empty string. + */ + private MultivaluedMap parseFormUrlEncoded(String body) { + MultivaluedMap params = new MultivaluedHashMap<>(); + if (body == null || body.isEmpty()) { + return params; + } + for (String pair : body.split("&")) { + if (pair.isEmpty()) continue; + int eq = pair.indexOf('='); + String key = eq >= 0 ? pair.substring(0, eq) : pair; + String value = eq >= 0 ? pair.substring(eq + 1) : ""; + params.add(URLDecoder.decode(key, StandardCharsets.UTF_8), + URLDecoder.decode(value, StandardCharsets.UTF_8)); + } + return params; + } + // ──────────────────────────── Path matching ──────────────────────────── /** diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java index 4d940746e9..d3570d9f5f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java @@ -13,10 +13,12 @@ import io.github.hectorvent.floci.services.kms.KmsJsonHandler; import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler; import io.github.hectorvent.floci.services.sns.SnsJsonHandler; import io.github.hectorvent.floci.services.sqs.SqsJsonHandler; +import io.github.hectorvent.floci.services.sqs.SqsQueryHandler; import io.github.hectorvent.floci.services.ssm.SsmJsonHandler; import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; @@ -35,6 +37,7 @@ public class AwsServiceRouter { private final StepFunctionsJsonHandler stepFunctionsHandler; private final DynamoDbJsonHandler dynamoDbHandler; private final SqsJsonHandler sqsHandler; + private final SqsQueryHandler sqsQueryHandler; private final SnsJsonHandler snsHandler; private final EventBridgeHandler eventBridgeHandler; private final SsmJsonHandler ssmHandler; @@ -50,6 +53,7 @@ public class AwsServiceRouter { public AwsServiceRouter(StepFunctionsJsonHandler stepFunctionsHandler, DynamoDbJsonHandler dynamoDbHandler, SqsJsonHandler sqsHandler, + SqsQueryHandler sqsQueryHandler, SnsJsonHandler snsHandler, EventBridgeHandler eventBridgeHandler, SsmJsonHandler ssmHandler, @@ -63,6 +67,7 @@ public class AwsServiceRouter { this.stepFunctionsHandler = stepFunctionsHandler; this.dynamoDbHandler = dynamoDbHandler; this.sqsHandler = sqsHandler; + this.sqsQueryHandler = sqsQueryHandler; this.snsHandler = snsHandler; this.eventBridgeHandler = eventBridgeHandler; this.ssmHandler = ssmHandler; @@ -81,8 +86,16 @@ public class AwsServiceRouter { public record IntegrationTarget(String region, String service, String action) {} /** - * Parses an integration URI like - * {@code arn:aws:apigateway:us-east-1:states:action/StartExecution}. + * Parses an integration URI in either of the two forms AWS accepts: + * + *
    + *
  • action — {@code arn:aws:apigateway:{region}:{service}:action/{Action}}. + * The action is encoded in the URI and the request template renders a JSON body.
  • + *
  • path — {@code arn:aws:apigateway:{region}:{service}:path/{resourcePath}}. + * The action is not in the URI; it is carried in the rendered request body + * (the AWS query protocol, e.g. {@code Action=SendMessage&...}). For this form + * {@link IntegrationTarget#action()} is {@code null}.
  • + *
* * @return parsed target, or null if the URI format is not recognized */ @@ -90,20 +103,27 @@ public class AwsServiceRouter { if (uri == null || !uri.startsWith("arn:aws:apigateway:")) { return null; } - // arn:aws:apigateway:{region}:{service}:action/{Action} + // arn:aws:apigateway:{region}:{service}:{action/{Action}|path/{resourcePath}} String[] parts = uri.split(":"); if (parts.length < 6) { return null; } String region = parts[3]; String service = parts[4]; - // parts[5] should be "action/{ActionName}" - String actionPart = parts[5]; - if (!actionPart.startsWith("action/")) { - return null; + // parts[5] is either "action/{ActionName}" or "path/{resourcePath}". + // A path may itself contain ':' (rare), so re-join the remainder. + String resourceSpec = parts.length > 6 + ? String.join(":", java.util.Arrays.copyOfRange(parts, 5, parts.length)) + : parts[5]; + if (resourceSpec.startsWith("action/")) { + String action = resourceSpec.substring("action/".length()); + return new IntegrationTarget(region, service, action); } - String action = actionPart.substring("action/".length()); - return new IntegrationTarget(region, service, action); + if (resourceSpec.startsWith("path/")) { + // Action is supplied by the rendered request body (query protocol). + return new IntegrationTarget(region, service, null); + } + return null; } /** @@ -143,4 +163,40 @@ public class AwsServiceRouter { e.getMessage() != null ? e.getMessage() : "Service invocation failed", 500); } } + + /** + * Dispatches an AWS query-protocol (form-encoded) integration request. + * + *

Used for {@code path/}-style integration URIs whose VTL request template renders an + * {@code application/x-www-form-urlencoded} body in the AWS query protocol, e.g. + * {@code Action=SendMessage&QueueUrl=...&MessageBody=...}. The {@code Action} parameter + * selects the operation, mirroring {@link io.github.hectorvent.floci.core.common.AwsQueryController}. + * + * @param service the AWS service name from the URI (e.g., "sqs") + * @param params the parsed form parameters, including {@code Action} + * @param region the AWS region + * @return the service response (query-protocol XML) + */ + public Response invokeQuery(String service, MultivaluedMap params, String region) { + String action = params.getFirst("Action"); + LOG.debugv("AWS query integration dispatch: {0}:{1} in {2}", service, action, region); + + if (action == null || action.isBlank()) { + throw new AwsException("MissingAction", + "The request must contain the parameter Action", 400); + } + + try { + return switch (service) { + case "sqs" -> sqsQueryHandler.handle(action, params, region); + default -> throw new AwsException("UnknownService", + "Unsupported AWS query-protocol service integration: " + service, 400); + }; + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw new AwsException("InternalError", + e.getMessage() != null ? e.getMessage() : "Service invocation failed", 500); + } + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewaySqsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewaySqsIntegrationTest.java new file mode 100644 index 0000000000..75a1c85bb7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewaySqsIntegrationTest.java @@ -0,0 +1,171 @@ +package io.github.hectorvent.floci.services.apigateway; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Integration tests for the API Gateway → SQS AWS integration using the path-style + * integration URI ({@code arn:aws:apigateway:{region}:sqs:path/{account}/{queue}}) and an + * {@code application/x-www-form-urlencoded} request template that renders the SQS query + * protocol ({@code Action=SendMessage&QueueUrl=...&MessageBody=...}). + * + *

This mirrors the canonical AWS recipe for exposing an SQS queue through API Gateway — + * the same pattern real services and LocalStack use. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewaySqsIntegrationTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + private static final String QUEUE_NAME = "apigw-sqs-test"; + + private static String apiId; + private static String rootId; + private static String resourceId; + private static String queueUrl; + + // ──────────────── Setup: SQS queue ──────────────── + + @Test @Order(0) + void setup_createQueue() { + queueUrl = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue") + .formParam("QueueName", QUEUE_NAME) + .when().post("/") + .then().statusCode(200) + .body(containsString("")) + .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl"); + assertNotNull(queueUrl); + } + + // ──────────────── Setup: API Gateway REST API ──────────────── + + @Test @Order(1) + void setup_createRestApi() { + apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"sqs-integration-test\",\"description\":\"APIGW → SQS\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + assertNotNull(apiId); + } + + @Test @Order(2) + void setup_getRootResource() { + rootId = given() + .when().get("/restapis/" + apiId + "/resources") + .then().statusCode(200) + .extract().path("item[0].id"); + assertNotNull(rootId); + } + + @Test @Order(3) + void setup_createResource() { + resourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"send\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId) + .then().statusCode(201) + .extract().path("id"); + assertNotNull(resourceId); + } + + @Test @Order(4) + void setup_configureMethod() throws Exception { + // POST method, no auth. + given() + .contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST") + .then().statusCode(201); + + // AWS integration targeting SQS via the path-style URI. The request template renders + // the SQS query protocol; the Content-Type override marks the body form-urlencoded. + var integrationNode = mapper.createObjectNode(); + integrationNode.put("type", "AWS"); + integrationNode.put("httpMethod", "POST"); + integrationNode.put("uri", "arn:aws:apigateway:us-east-1:sqs:path/000000000000/" + QUEUE_NAME); + integrationNode.put("passthroughBehavior", "NEVER"); + + var reqParams = mapper.createObjectNode(); + reqParams.put("integration.request.header.Content-Type", "'application/x-www-form-urlencoded'"); + integrationNode.set("requestParameters", reqParams); + + var reqTemplates = mapper.createObjectNode(); + String vtl = "Action=SendMessage" + + "&QueueUrl=$util.urlEncode(\"" + queueUrl + "\")" + + "&MessageBody=$util.urlEncode($input.body)"; + reqTemplates.put("application/json", vtl); + integrationNode.set("requestTemplates", reqTemplates); + + given() + .contentType(ContentType.JSON) + .body(mapper.writeValueAsString(integrationNode)) + .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration") + .then().statusCode(201); + + // Default 200 integration response (no response template — pass the SQS XML through). + given() + .contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"\"}") + .when().put("/restapis/" + apiId + "/resources/" + resourceId + + "/methods/POST/integration/responses/200") + .then().statusCode(201); + } + + @Test @Order(5) + void setup_deployAndCreateStage() { + String deploymentId = given() + .contentType(ContentType.JSON) + .body("{\"description\":\"test\"}") + .when().post("/restapis/" + apiId + "/deployments") + .then().statusCode(201) + .extract().path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}") + .when().post("/restapis/" + apiId + "/stages") + .then().statusCode(201); + } + + // ──────────────── Test: APIGW → SQS SendMessage ──────────────── + + @Test @Order(10) + void sqsIntegration_sendMessage() { + // The integration returns the SQS query-protocol XML response. + given() + .contentType(ContentType.JSON) + .body("{\"hello\":\"world\"}") + .when().post("/execute-api/" + apiId + "/test/send") + .then() + .statusCode(200) + .body(containsString("")) + .body(containsString("")); + } + + @Test @Order(11) + void sqsIntegration_messageLandsOnQueue() { + // The body the producer POSTed should be the MessageBody now sitting on the queue. + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ReceiveMessage") + .formParam("QueueUrl", queueUrl) + .formParam("MaxNumberOfMessages", "1") + .when().post("/") + .then().statusCode(200) + .body(containsString("{"hello":"world"}")); + } +}