diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAwsStatusSelectionCompatibilityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAwsStatusSelectionCompatibilityTest.java new file mode 100644 index 0000000000..38386fdffa --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayAwsStatusSelectionCompatibilityTest.java @@ -0,0 +1,87 @@ +package com.floci.test; + +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.apigateway.ApiGatewayClient; +import software.amazon.awssdk.services.apigateway.model.IntegrationType; +import software.amazon.awssdk.services.sqs.SqsClient; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class ApiGatewayAwsStatusSelectionCompatibilityTest { + + @Test + void sdkConfiguredAwsIntegrationSelectsResponsesByBackendStatus() throws Exception { + String queueName = TestFixtures.uniqueName("apigw-status-selection"); + try (ApiGatewayClient apiGateway = TestFixtures.apiGatewayClient(); + SqsClient sqs = TestFixtures.sqsClient()) { + String apiId = apiGateway.createRestApi(request -> request.name(queueName)).id(); + String queueUrl = null; + try { + String rootId = apiGateway.getResources(request -> request.restApiId(apiId)).items().stream() + .filter(resource -> "/".equals(resource.path())).findFirst().orElseThrow().id(); + String resourceId = apiGateway.createResource(request -> request.restApiId(apiId) + .parentId(rootId).pathPart("send")).id(); + apiGateway.putMethod(request -> request.restApiId(apiId).resourceId(resourceId) + .httpMethod("POST").authorizationType("NONE")); + apiGateway.putIntegration(request -> request.restApiId(apiId).resourceId(resourceId) + .httpMethod("POST").type(IntegrationType.AWS).integrationHttpMethod("POST") + .uri(TestFixtures.arn("apigateway", "sqs", "path/000000000000/" + queueName)) + .credentials(TestFixtures.globalArn("iam", "000000000000", "role/apigw-sqs")) + .requestParameters(Map.of("integration.request.header.Content-Type", + "'application/x-www-form-urlencoded'")) + .requestTemplates(Map.of("application/json", + "Action=SendMessage&MessageBody=$util.urlEncode($input.body)"))); + response(apiGateway, apiId, resourceId, "200", null, "default"); + response(apiGateway, apiId, resourceId, "502", "4\\d{2}", "error"); + apiGateway.createDeployment(request -> request.restApiId(apiId).stageName("test")); + assertResponse(apiId, 502, "error"); + + response(apiGateway, apiId, resourceId, "502", ".*NonExistentQueue.*", "error"); + apiGateway.createDeployment(request -> request.restApiId(apiId).stageName("test")); + assertResponse(apiId, 200, "default"); + + queueUrl = sqs.createQueue(request -> request.queueName(queueName)).queueUrl(); + response(apiGateway, apiId, resourceId, "201", "2\\d{2}", "queued"); + apiGateway.createDeployment(request -> request.restApiId(apiId).stageName("test")); + assertResponse(apiId, 201, "queued"); + String createdQueueUrl = queueUrl; + assertThat(sqs.receiveMessage(request -> request.queueUrl(createdQueueUrl) + .maxNumberOfMessages(1)).messages()) + .singleElement().satisfies(message -> assertThat(message.body()).isEqualTo("{\"value\":1}")); + } finally { + try { + apiGateway.deleteRestApi(request -> request.restApiId(apiId)); + } finally { + if (queueUrl != null) { + String createdQueueUrl = queueUrl; + sqs.deleteQueue(request -> request.queueUrl(createdQueueUrl)); + } + } + } + } + } + + private static void response(ApiGatewayClient apiGateway, String apiId, String resourceId, + String status, String pattern, String result) { + apiGateway.putMethodResponse(request -> request.restApiId(apiId).resourceId(resourceId) + .httpMethod("POST").statusCode(status)); + apiGateway.putIntegrationResponse(request -> request.restApiId(apiId).resourceId(resourceId) + .httpMethod("POST").statusCode(status).selectionPattern(pattern) + .responseTemplates(Map.of("application/json", "{\"result\":\"" + result + "\"}"))); + } + + private static void assertResponse(String apiId, int status, String result) throws Exception { + URI uri = TestFixtures.endpoint().resolve("/execute-api/" + apiId + "/test/send"); + HttpRequest request = HttpRequest.newBuilder(uri).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString("{\"value\":1}")).build(); + HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).isEqualTo(status); + assertThat(response.body()).isEqualTo("{\"result\":\"" + result + "\"}"); + } +} 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 c29fcbf519..53e427b0eb 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 @@ -846,8 +846,8 @@ public class ApiGatewayExecuteController { * entirely from mapping templates and explicit {@code integration.request.*} parameter * mappings — inbound headers and query parameters that were not mapped are not * forwarded. The backend's response then runs through the method's integration responses, where - * {@code selectionPattern} is matched against the backend's HTTP status code (for - * {@code AWS}/Lambda integrations it is matched against the error message instead). + * {@code selectionPattern} is matched against the backend's HTTP status code. + * Lambda integrations use error text instead. */ private Response invokeHttpIntegration(GatewayResponseScope scope, String region, String apiId, String httpMethod, String path, @@ -1743,6 +1743,8 @@ public class ApiGatewayExecuteController { // "Action=SendMessage&..."). Action-style URIs (arn:...:{service}:action/{Action}) // carry the action in the URI and render a JSON body. Response serviceResponse; + int serviceStatus = 500; + String backendStatusMatchString = null; String errorType = null; String errorMessage = null; try { @@ -1784,6 +1786,8 @@ public class ApiGatewayExecuteController { serviceResponse = serviceRouter.invoke(target.service(), target.action(), requestJson, region); } } catch (AwsException e) { + serviceStatus = e.getHttpStatus(); + backendStatusMatchString = Integer.toString(serviceStatus); errorType = e.getErrorCode(); errorMessage = e.getMessage(); serviceResponse = null; @@ -1795,9 +1799,9 @@ public class ApiGatewayExecuteController { // Build response body string String responseBodyStr; - int serviceStatus; if (serviceResponse != null) { serviceStatus = serviceResponse.getStatus(); + backendStatusMatchString = Integer.toString(serviceStatus); Object entity = serviceResponse.getEntity(); if (entity instanceof JsonNode jsonNode) { try { @@ -1826,19 +1830,16 @@ public class ApiGatewayExecuteController { } } } else { - serviceStatus = 500; responseBodyStr = String.format("{\"errorMessage\":\"%s\",\"errorType\":\"%s\"}", errorMessage != null ? errorMessage.replace("\"", "\\\"") : "Unknown error", errorType != null ? errorType : "UnknownError"); } - // AWS matches selectionPattern against the error response body/message for AWS/Lambda - // integrations. We match against both errorType and errorMessage to catch patterns like - // ".*ResourceNotFoundException.*". (HTTP integrations match the status code instead — - // see invokeHttpIntegration.) String errorMatchString = errorType != null ? errorType + (errorMessage != null ? ": " + errorMessage : "") : errorMessage; + String selectionMatchString = "lambda".equals(target.service()) + ? errorMatchString : backendStatusMatchString; // Case-insensitive: an integration.response.header.X-Foo mapping must resolve regardless of // the casing the backend or client library used for the header name. @@ -1855,7 +1856,7 @@ public class ApiGatewayExecuteController { vtlAuthorizerContext, httpRequestMappingContext(scope, requestId, authorizerResult)); int fallbackStatus = errorType != null ? 500 : (serviceStatus >= 400 ? serviceStatus : 200); - return mapIntegrationResponse(integration, errorMatchString, responseBodyStr, fallbackStatus, + return mapIntegrationResponse(integration, selectionMatchString, responseBodyStr, fallbackStatus, serviceResponseHeaders, responseMappingCtx, MediaType.APPLICATION_JSON); } @@ -1919,8 +1920,8 @@ public class ApiGatewayExecuteController { * {@code $context.responseOverride} assignments and {@code responseParameters} header mappings. * * @param selectionMatchString what {@code selectionPattern} regexes are tested against — the - * error message for {@code AWS}/Lambda integrations, the backend's - * HTTP status code for {@code HTTP} integrations + * error text for Lambda integrations, the backend's HTTP status + * code for other {@code AWS} and {@code HTTP} integrations * @param fallbackStatus status used when no integration response is configured or matched */ private Response mapIntegrationResponse(Integration integration, String selectionMatchString, diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsIntegrationTest.java index 1170e1c328..8b508c03f1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsIntegrationTest.java @@ -494,7 +494,7 @@ class ApiGatewayAwsIntegrationTest { null, // no request template — passthrough Map.of( "200", new IntegrationResponseConfig("", ""), - "400", new IntegrationResponseConfig(".*ResourceNotFoundException.*", "") + "400", new IntegrationResponseConfig("4\\d{2}", "") )); redeploy(); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsStatusSelectionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsStatusSelectionIntegrationTest.java new file mode 100644 index 0000000000..6c141eb693 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsStatusSelectionIntegrationTest.java @@ -0,0 +1,212 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@QuarkusTest +class ApiGatewayAwsStatusSelectionIntegrationTest { + + private static final String ACCOUNT_ID = "000000000000"; + private static final String LAMBDA_FUNCTION = "aws-status-selection"; + private static final String MESSAGE = "{\"hello\":\"status-selection\"}"; + + @InjectMock + LambdaService lambdaService; + + private final List apiIds = new ArrayList<>(); + private final List queueUrls = new ArrayList<>(); + + @AfterEach + void cleanup() { + for (String apiId : apiIds) { + given().delete("/restapis/" + apiId).then().statusCode(202); + } + for (String queueUrl : queueUrls) { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteQueue").formParam("QueueUrl", queueUrl) + .post("/").then().statusCode(200); + } + } + + @Test + void sqsErrorStatusSelectsMatchingIntegrationResponse() { + String queueName = "missing-status-" + UUID.randomUUID(); + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "SendMessage").formParam("QueueUrl", queueName) + .formParam("MessageBody", MESSAGE).post("/") + .then().statusCode(400).body(containsString("NonExistentQueue")); + String apiId = sqsApi(queueName, 502, "4\\d{2}"); + + given().contentType(ContentType.JSON).body(MESSAGE) + .post("/execute-api/" + apiId + "/test/send") + .then().statusCode(502).body("result", equalTo("matched")); + } + + @Test + void sqsErrorTextDoesNotSelectIntegrationResponse() { + String apiId = sqsApi("missing-error-text-" + UUID.randomUUID(), 502, ".*NonExistentQueue.*"); + + given().contentType(ContentType.JSON).body(MESSAGE) + .post("/execute-api/" + apiId + "/test/send") + .then().statusCode(200).body("result", equalTo("default")); + } + + @Test + void sqsSuccessStatusSelectsMatchingIntegrationResponse() { + String queueName = "success-status-" + UUID.randomUUID(); + String queueUrl = createQueue(queueName); + String apiId = sqsApi(queueName, 201, "2\\d{2}"); + + given().contentType(ContentType.JSON).body(MESSAGE) + .post("/execute-api/" + apiId + "/test/send") + .then().statusCode(201).body("result", equalTo("matched")); + assertMessageQueued(queueUrl); + } + + @Test + void sqsSuccessWithoutMatchingPatternUsesDefaultResponse() { + String queueName = "success-default-" + UUID.randomUUID(); + String queueUrl = createQueue(queueName); + String apiId = sqsApi(queueName, 502, "4\\d{2}"); + + given().contentType(ContentType.JSON).body(MESSAGE) + .post("/execute-api/" + apiId + "/test/send") + .then().statusCode(200).body("result", equalTo("default")); + assertMessageQueued(queueUrl); + } + + @Test + void malformedActionRequestDoesNotMatchBackendStatusPattern() { + // Replacing the default 200 entry leaves only the backend-status pattern. + String apiId = awsApi(Map.of( + "type", "AWS", + "httpMethod", "POST", + "uri", "arn:aws:apigateway:us-east-1:sqs:action/SendMessage", + "requestTemplates", Map.of("application/json", "not-json")), 200, "5\\d{2}"); + + given().contentType(ContentType.JSON).body(MESSAGE) + .post("/execute-api/" + apiId + "/test/send") + .then().statusCode(500).body(containsString("InternalError")); + } + + @Test + void lambdaSuccessDoesNotMatchHttpStatusPattern() { + when(lambdaService.invoke(eq("us-east-1"), eq(LAMBDA_FUNCTION), any(byte[].class), + eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult(200, null, "{}".getBytes(StandardCharsets.UTF_8), null, "success")); + String apiId = lambdaApi(201, "2\\d{2}"); + + given().contentType(ContentType.JSON).body(MESSAGE) + .post("/execute-api/" + apiId + "/test/send") + .then().statusCode(200).body("result", equalTo("default")); + verify(lambdaService).invoke(eq("us-east-1"), eq(LAMBDA_FUNCTION), + eq(MESSAGE.getBytes(StandardCharsets.UTF_8)), eq(InvocationType.RequestResponse)); + } + + @Test + void lambdaFunctionErrorStillMatchesErrorTextPattern() { + byte[] errorPayload = "{\"errorMessage\":\"boom\"}".getBytes(StandardCharsets.UTF_8); + when(lambdaService.invoke(eq("us-east-1"), eq(LAMBDA_FUNCTION), any(byte[].class), + eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult(200, "Unhandled", errorPayload, null, "function-error")); + String apiId = lambdaApi(502, ".*boom.*"); + + given().contentType(ContentType.JSON).body(MESSAGE) + .post("/execute-api/" + apiId + "/test/send") + .then().statusCode(502).body("result", equalTo("matched")); + verify(lambdaService).invoke(eq("us-east-1"), eq(LAMBDA_FUNCTION), + eq(MESSAGE.getBytes(StandardCharsets.UTF_8)), eq(InvocationType.RequestResponse)); + } + + private String createQueue(String queueName) { + String queueUrl = given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue").formParam("QueueName", queueName) + .post("/").then().statusCode(200) + .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl"); + queueUrls.add(queueUrl); + return queueUrl; + } + + private static void assertMessageQueued(String queueUrl) { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "ReceiveMessage").formParam("QueueUrl", queueUrl) + .formParam("MaxNumberOfMessages", "1").post("/") + .then().statusCode(200).body(containsString("status-selection")); + } + + private String sqsApi(String queueName, int matchedStatus, String pattern) { + return awsApi(Map.of( + "type", "AWS", + "httpMethod", "POST", + "uri", "arn:aws:apigateway:us-east-1:sqs:path/" + ACCOUNT_ID + "/" + queueName, + "credentials", "arn:aws:iam::" + ACCOUNT_ID + ":role/apigw-sqs", + "requestParameters", Map.of( + "integration.request.header.Content-Type", "'application/x-www-form-urlencoded'"), + "requestTemplates", Map.of( + "application/json", "Action=SendMessage&MessageBody=$util.urlEncode($input.body)")), + matchedStatus, pattern); + } + + private String lambdaApi(int matchedStatus, String pattern) { + return awsApi(Map.of( + "type", "AWS", + "httpMethod", "POST", + "uri", "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/" + + "arn:aws:lambda:us-east-1:" + ACCOUNT_ID + ":function:" + LAMBDA_FUNCTION + "/invocations", + "requestTemplates", Map.of("application/json", "$input.body")), matchedStatus, pattern); + } + + private String awsApi(Map integrationRequest, int matchedStatus, String pattern) { + String apiId = given().contentType(ContentType.JSON).body(Map.of("name", "aws-status-selection")) + .post("/restapis").then().statusCode(201).extract().path("id"); + apiIds.add(apiId); + String rootId = given().get("/restapis/" + apiId + "/resources") + .then().statusCode(200).extract().path("item[0].id"); + String resourceId = given().contentType(ContentType.JSON).body(Map.of("pathPart", "send")) + .post("/restapis/" + apiId + "/resources/" + rootId) + .then().statusCode(201).extract().path("id"); + String methodPath = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST"; + given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE")) + .put(methodPath).then().statusCode(201); + given().contentType(ContentType.JSON).body(integrationRequest) + .put(methodPath + "/integration").then().statusCode(201); + integrationResponse(methodPath, 200, "", "default"); + integrationResponse(methodPath, matchedStatus, pattern, "matched"); + + String deploymentId = given().contentType(ContentType.JSON).body(Map.of("stageName", "test")) + .post("/restapis/" + apiId + "/deployments") + .then().statusCode(201).extract().path("id"); + given().get("/restapis/" + apiId + "/stages/test") + .then().statusCode(200).body("deploymentId", equalTo(deploymentId)); + return apiId; + } + + private static void integrationResponse(String methodPath, int status, String pattern, String result) { + given().contentType(ContentType.JSON).body(Map.of()) + .put(methodPath + "/responses/" + status).then().statusCode(201); + given().contentType(ContentType.JSON).body(Map.of( + "selectionPattern", pattern, + "responseTemplates", Map.of("application/json", "{\"result\": \"" + result + "\"}"))) + .put(methodPath + "/integration/responses/" + status).then().statusCode(201); + } +}