Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigateway): implement MOCK integration response selection based on status code (#3327)
Matheus André8d011cb983b9
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.mdindex 153c97ed4b..a767cba06c 100644--- a/docs/services/api-gateway.md+++ b/docs/services/api-gateway.md@@ -186,7 +186,7 @@ These management-plane operations have no handler in v1. Calls will return `404`- Client Certificates (5 operations)- `GetExport` / `ImportDocumentationParts`-The execute plane (actual proxied HTTP traffic via `/restapis/{id}/{stage}/_user_request_/…`) is implemented separately and is not counted as management-plane operations. It supports `AWS_PROXY` (Lambda proxy), `AWS` (Lambda with VTL request/response templates), and `MOCK` integrations; other integration types return an error.+The execute plane (actual proxied HTTP traffic via `/restapis/{id}/{stage}/_user_request_/…`) is implemented separately and is not counted as management-plane operations. It supports `AWS_PROXY` (Lambda proxy), `AWS` (Lambda with VTL request/response templates), and `MOCK` integrations; other integration types return an error. A `MOCK` integration renders its request template and uses the `statusCode` it produces to pick the integration response, exactly as AWS does: the first response whose `selectionPattern` matches wins, otherwise the response without a pattern (the default) answers. This is what makes CORS preflights declared with a `204` response (CDK's `addCorsPreflight`) carry their `Access-Control-*` headers.### Examplesdiff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.javaindex b4f09445e5..d3ac4e1a77 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@@ -57,6 +57,7 @@ import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;import java.util.regex.Matcher;import java.util.regex.Pattern;+import java.util.regex.PatternSyntaxException;/*** Executes API Gateway stage requests, routing them through the configured@@ -1342,11 +1343,54 @@ public class ApiGatewayExecuteController {private Response invokeMock(String region, String httpMethod, String path, String stageName,ApiGatewayResource resource, Integration integration,HttpHeaders headers, UriInfo uriInfo, byte[] body) {- // Use the "200" integration response if present, else return empty 200- IntegrationResponse ir = integration.getIntegrationResponses().get("200");- if (ir == null) {+ String requestId = UUID.randomUUID().toString();+ String bodyStr = body != null && body.length > 0 ? new String(body) : null;++ Map<String, String> headerMap = new HashMap<>();+ for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {+ if (!e.getValue().isEmpty()) {+ headerMap.put(e.getKey(), e.getValue().get(0));+ }+ }+ Map<String, String> queryMap = new HashMap<>();+ for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {+ if (!e.getValue().isEmpty()) {+ queryMap.put(e.getKey(), e.getValue().get(0));+ }+ }+ Map<String, String> pathMap = new HashMap<>(extractPathParams(resource.getPath(), path));++ VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(+ bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,+ resource.getPath(), requestId, regionResolver.getAccountId(), null);++ // A MOCK has no backend: the request template *is* the integration response, and the+ // "statusCode" it renders is what the integration responses' selectionPatterns are+ // matched against. Previously only the integration response keyed "200" was ever+ // consulted, so a preflight declared with any other status (CDK's addCorsPreflight+ // emits a single "204" response) came back as a bare 200 with no CORS headers.+ Map<String, IntegrationResponse> integrationResponses = integration.getIntegrationResponses();+ if (integrationResponses == null || integrationResponses.isEmpty()) {+ // Leniency: AWS fails with a 500 configuration error when no output mapping exists;+ // Floci keeps answering an empty 200 so a bare MOCK stays usable as a stub. Checked+ // before rendering the request template so a malformed template cannot break the stub.return Response.ok().build();}+ Integer mockStatus = resolveMockStatusCode(integration, resource, httpMethod, headers, bodyStr, vtlCtx);+ if (mockStatus == null) {+ // A request template that does not render is a configuration error on AWS too.+ return Response.status(500)+ .entity(jsonMessage("Internal server error"))+ .type(MediaType.APPLICATION_JSON).build();+ }+ IntegrationResponse ir = selectMockIntegrationResponse(integrationResponses, mockStatus);+ if (ir == null) {+ LOG.warnv("execute-api: MOCK {0} {1} produced statusCode {2} but no integration response "+ + "matches it and none is the default", httpMethod, resource.getPath(), mockStatus);+ return Response.status(500)+ .entity(jsonMessage("Internal server error"))+ .type(MediaType.APPLICATION_JSON).build();+ }String template = ir.responseTemplates() != null? ir.responseTemplates().getOrDefault("application/json", "") : "";@@ -1357,25 +1401,10 @@ public class ApiGatewayExecuteController {if (!template.isEmpty()) {// Evaluate the response template through VTL (supports $context.responseOverride etc.)- String requestId = UUID.randomUUID().toString();- String bodyStr = body != null && body.length > 0 ? new String(body) : null;-- Map<String, String> headerMap = new HashMap<>();- for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {- if (!e.getValue().isEmpty()) headerMap.put(e.getKey(), e.getValue().get(0));- }- Map<String, String> queryMap = new HashMap<>();- for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {- if (!e.getValue().isEmpty()) queryMap.put(e.getKey(), e.getValue().get(0));- }- Map<String, String> pathMap = new HashMap<>(extractPathParams(resource.getPath(), path));-- VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(- bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,- resource.getPath(), requestId, regionResolver.getAccountId(), null);-VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);- if (result.statusOverride() != null) status = result.statusOverride();+ if (result.statusOverride() != null) {+ status = result.statusOverride();+ }responseBody = result.body();vtlHeaderOverrides = result.headerOverrides();}@@ -1405,7 +1434,9 @@ public class ApiGatewayExecuteController {if (ir.responseParameters() != null) {for (Map.Entry<String, String> param : ir.responseParameters().entrySet()) {String dest = param.getKey(); // method.response.header.X-Foo- if (!dest.startsWith("method.response.header.")) continue;+ if (!dest.startsWith("method.response.header.")) {+ continue;+ }String headerName = dest.substring("method.response.header.".length());if (vtlOverriddenHeaders.contains(headerName.toLowerCase(Locale.ROOT))) {continue; // a VTL $context.responseOverride for this header takes precedence@@ -1421,6 +1452,102 @@ public class ApiGatewayExecuteController {return rb.build();}+ /**+ * Matches the {@code statusCode} a MOCK request template renders, e.g. {@code {"statusCode": 200}}.+ * The key is accepted unquoted because API Gateway tolerates the {@code { statusCode: 200 }}+ * shorthand that CDK's {@code addCorsPreflight} emits.+ */+ private static final Pattern MOCK_STATUS_CODE = Pattern.compile(+ "[\"']?statusCode[\"']?\\s*:\\s*[\"']?(\\d{3})[\"']?");++ /**+ * Resolves the status code a MOCK integration "returns" by rendering its request template+ * (chosen by the request's Content-Type, falling back to {@code application/json} and then+ * to the only template configured) and reading the {@code statusCode} the <em>rendered</em>+ * output declares, so VTL conditionals decide exactly as they do on AWS. Without a template+ * the passthrough request body is inspected instead. Defaults to 200 when nothing declares+ * one, and returns {@code null} when the template fails to render: that is a configuration+ * error the caller must surface, not a successful mock.+ */+ private Integer resolveMockStatusCode(Integration integration, ApiGatewayResource resource, String httpMethod,+ HttpHeaders headers, String bodyStr,+ VtlTemplateEngine.VtlContext vtlCtx) {+ String template = selectRequestTemplate(integration.getRequestTemplates(), headers);+ String source;+ if (template != null && !template.isEmpty()) {+ try {+ source = vtlEngine.evaluate(template, vtlCtx).body();+ } catch (RuntimeException e) {+ // Log identifiers only: the template body is API-owner content and may embed secrets.+ LOG.warnv("execute-api: MOCK request template for {0} {1} failed to render: {2}",+ httpMethod, resource.getPath(), e.getMessage());+ return null;+ }+ } else {+ source = bodyStr;+ }+ Integer status = parseMockStatusCode(source);+ return status != null ? status : 200;+ }++ private static String selectRequestTemplate(Map<String, String> templates, HttpHeaders headers) {+ if (templates == null || templates.isEmpty()) {+ return null;+ }+ String contentType = headers != null ? headers.getHeaderString("Content-Type") : null;+ if (contentType != null) {+ String mediaType = contentType.split(";", 2)[0].trim();+ for (Map.Entry<String, String> e : templates.entrySet()) {+ if (e.getKey().equalsIgnoreCase(mediaType)) {+ return e.getValue();+ }+ }+ }+ String json = templates.get("application/json");+ if (json != null) {+ return json;+ }+ return templates.size() == 1 ? templates.values().iterator().next() : null;+ }++ private static Integer parseMockStatusCode(String text) {+ if (text == null || text.isEmpty()) {+ return null;+ }+ Matcher m = MOCK_STATUS_CODE.matcher(text);+ return m.find() ? Integer.valueOf(m.group(1)) : null;+ }++ /**+ * Picks the integration response for a MOCK status code the way API Gateway does: the first+ * response whose {@code selectionPattern} matches the status code wins, otherwise the response+ * without a pattern (the default) is used. Returns {@code null} when neither exists.+ */+ private static IntegrationResponse selectMockIntegrationResponse(+ Map<String, IntegrationResponse> integrationResponses, int mockStatus) {+ String statusText = String.valueOf(mockStatus);+ IntegrationResponse defaultResponse = null;+ for (IntegrationResponse ir : integrationResponses.values()) {+ if (ir.selectionPattern() == null || ir.selectionPattern().isEmpty()) {+ if (defaultResponse == null) {+ defaultResponse = ir;+ }+ continue;+ }+ try {+ if (Pattern.matches(ir.selectionPattern(), statusText)) {+ return ir;+ }+ } catch (PatternSyntaxException e) {+ // A malformed selectionPattern cannot match anything; keep evaluating the others+ // so a valid pattern or the default response still answers.+ LOG.warnv("execute-api: ignoring invalid selectionPattern {0} on integration response {1}: {2}",+ ir.selectionPattern(), ir.statusCode(), e.getDescription());+ }+ }+ return defaultResponse;+ }+// ──────────────────────────── API Gateway v2 dispatch ────────────────────────────private static Response httpApiCorsPreflight(Api.Cors cors, String requestOrigin) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayMockStatusCodeSelectionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayMockStatusCodeSelectionIntegrationTest.javanew file mode 100644index 0000000000..7874e5d22e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayMockStatusCodeSelectionIntegrationTest.java@@ -0,0 +1,286 @@+package io.github.hectorvent.floci.services.apigateway;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;++/**+ * A MOCK integration answers with the integration response API Gateway <em>selects</em> for the+ * {@code statusCode} its request template renders, not with whichever response happens to be+ * keyed {@code "200"} (#2847).+ *+ * <p>The regression this guards: CDK's {@code addCorsPreflight} declares a single {@code 204}+ * integration response carrying the {@code Access-Control-Allow-*} headers and a+ * {@code { statusCode: 200 }} request template. Floci used to look up {@code "200"} only, found+ * nothing, and returned a bare 200, so browser preflights against CDK-built REST APIs failed+ * with a missing {@code Access-Control-Allow-Origin}.</p>+ */+@QuarkusTest+class ApiGatewayMockStatusCodeSelectionIntegrationTest {++ private static final String STAGE = "api";++ private String apiId;+ private String resourceId;++ @BeforeEach+ void createRestApiAndResource() {+ apiId = given()+ .contentType(ContentType.JSON)+ .body("{\"name\":\"mock-status-selection-test-api\"}")+ .when().post("/restapis")+ .then()+ .statusCode(201)+ .body("id", notNullValue())+ .extract().path("id");++ String rootId = given()+ .when().get("/restapis/" + apiId + "/resources")+ .then()+ .statusCode(200)+ .extract().path("item[0].id");++ resourceId = given()+ .contentType(ContentType.JSON)+ .body("{\"pathPart\":\"items\"}")+ .when().post("/restapis/" + apiId + "/resources/" + rootId)+ .then()+ .statusCode(201)+ .extract().path("id");+ }++ @AfterEach+ void cleanup() {+ if (apiId != null) {+ given().when().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ @Test+ void cdkShapedPreflightUsesTheSingle204IntegrationResponse() {+ // Exactly what aws-cdk-lib's Resource.addCorsPreflight synthesizes: an unquoted+ // "{ statusCode: 200 }" request template and one "204" integration/method response.+ putMethod("OPTIONS");+ putMockIntegration("OPTIONS", "{ statusCode: 200 }");+ putIntegrationResponse("OPTIONS", "204", "",+ "\"method.response.header.Access-Control-Allow-Origin\":\"'*'\","+ + "\"method.response.header.Access-Control-Allow-Methods\":\"'OPTIONS,GET,POST'\","+ + "\"method.response.header.Access-Control-Allow-Headers\":\"'Content-Type,Authorization'\"");+ putMethodResponse("OPTIONS", "204");+ deploy();++ given()+ .header("Origin", "http://localhost:3000")+ .header("Access-Control-Request-Method", "POST")+ .when().options("/execute-api/" + apiId + "/" + STAGE + "/items")+ .then()+ .statusCode(204)+ .header("Access-Control-Allow-Origin", equalTo("*"))+ .header("Access-Control-Allow-Methods", equalTo("OPTIONS,GET,POST"))+ .header("Access-Control-Allow-Headers", equalTo("Content-Type,Authorization"));++ given()+ .header("Origin", "http://localhost:3000")+ .header("Access-Control-Request-Method", "POST")+ .when().options("/restapis/" + apiId + "/" + STAGE + "/_user_request_/items")+ .then()+ .statusCode(204)+ .header("Access-Control-Allow-Origin", equalTo("*"));+ }++ @Test+ void selectionPatternMatchingTheMockStatusCodeWinsOverTheDefault() {+ putMethod("GET");+ putMockIntegration("GET", "{\"statusCode\": 404}");+ putIntegrationResponse("GET", "200", "",+ "\"method.response.header.X-Selected\":\"'default'\"");+ putIntegrationResponse("GET", "404", "4\\\\d{2}",+ "\"method.response.header.X-Selected\":\"'not-found'\","+ + "\"method.response.header.Access-Control-Allow-Origin\":\"'*'\"");+ putMethodResponse("GET", "200");+ putMethodResponse("GET", "404");+ deploy();++ given()+ .when().get("/execute-api/" + apiId + "/" + STAGE + "/items")+ .then()+ .statusCode(404)+ .header("X-Selected", equalTo("not-found"))+ .header("Access-Control-Allow-Origin", equalTo("*"));+ }++ @Test+ void defaultIntegrationResponseAnswersWhenNoPatternMatches() {+ putMethod("GET");+ putMockIntegration("GET", "{\"statusCode\": 200}");+ putIntegrationResponse("GET", "200", "",+ "\"method.response.header.X-Selected\":\"'default'\"");+ putIntegrationResponse("GET", "500", "5\\\\d{2}",+ "\"method.response.header.X-Selected\":\"'error'\"");+ putMethodResponse("GET", "200");+ putMethodResponse("GET", "500");+ deploy();++ given()+ .when().get("/execute-api/" + apiId + "/" + STAGE + "/items")+ .then()+ .statusCode(200)+ .header("X-Selected", equalTo("default"));+ }++ @Test+ void onlyTheRenderedRequestTemplateDecidesTheStatusCode() {+ // The raw template mentions 404, but VTL never emits it: AWS renders first and only then+ // reads statusCode, so the default (200) response must answer, not the 404 one.+ putMethod("GET");+ putMockIntegration("GET", "#if(false){\"statusCode\": 404}#end{\"statusCode\": 200}");+ putIntegrationResponse("GET", "200", "",+ "\"method.response.header.X-Selected\":\"'default'\"");+ putIntegrationResponse("GET", "404", "4\\\\d{2}",+ "\"method.response.header.X-Selected\":\"'not-found'\"");+ putMethodResponse("GET", "200");+ putMethodResponse("GET", "404");+ deploy();++ given()+ .when().get("/execute-api/" + apiId + "/" + STAGE + "/items")+ .then()+ .statusCode(200)+ .header("X-Selected", equalTo("default"));+ }++ @Test+ void invalidSelectionPatternIsSkippedAndTheDefaultStillAnswers() {+ putMethod("GET");+ putMockIntegration("GET", "{\"statusCode\": 200}");+ putIntegrationResponse("GET", "200", "",+ "\"method.response.header.X-Selected\":\"'default'\"");+ putIntegrationResponse("GET", "500", "[unterminated",+ "\"method.response.header.X-Selected\":\"'broken'\"");+ putMethodResponse("GET", "200");+ putMethodResponse("GET", "500");+ deploy();++ given()+ .when().get("/execute-api/" + apiId + "/" + STAGE + "/items")+ .then()+ .statusCode(200)+ .header("X-Selected", equalTo("default"));+ }++ @Test+ void requestTemplateThatFailsToRenderIsAConfigurationError() {+ // An unterminated #if is a VTL parse error. AWS surfaces that as a 500 configuration+ // error; it must never be masked by picking the 200/default response.+ putMethod("GET");+ putMockIntegration("GET", "#if($input.params('x') == 'y') {\"statusCode\": 200}");+ putIntegrationResponse("GET", "200", "",+ "\"method.response.header.X-Selected\":\"'default'\"");+ putMethodResponse("GET", "200");+ deploy();++ given()+ .when().get("/execute-api/" + apiId + "/" + STAGE + "/items")+ .then()+ .statusCode(500)+ .header("X-Selected", nullValue())+ .body("message", equalTo("Internal server error"));+ }++ @Test+ void bareMockWithoutIntegrationResponsesStaysAnEmpty200EvenIfTheTemplateIsBroken() {+ // Documented leniency: a MOCK with no integration responses is a stub answering an empty+ // 200, and that must hold before the request template is ever rendered.+ putMethod("GET");+ putMockIntegration("GET", "#if($input.params('x') == 'y') {\"statusCode\": 200}");+ deploy();++ given()+ .when().get("/execute-api/" + apiId + "/" + STAGE + "/items")+ .then()+ .statusCode(200)+ .header("Content-Length", equalTo("0"));+ }++ @Test+ void mockWithNoMatchingResponseAndNoDefaultIsAConfigurationError() {+ putMethod("GET");+ putMockIntegration("GET", "{\"statusCode\": 200}");+ putIntegrationResponse("GET", "404", "4\\\\d{2}",+ "\"method.response.header.X-Selected\":\"'not-found'\"");+ putMethodResponse("GET", "404");+ deploy();++ given()+ .when().get("/execute-api/" + apiId + "/" + STAGE + "/items")+ .then()+ .statusCode(500)+ .header("X-Selected", nullValue())+ .body("message", equalTo("Internal server error"));+ }++ private void putMethod(String httpMethod) {+ given()+ .contentType(ContentType.JSON)+ .body("{\"authorizationType\":\"NONE\"}")+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod)+ .then()+ .statusCode(201);+ }++ private void putMockIntegration(String httpMethod, String requestTemplate) {+ String escaped = requestTemplate.replace("\\", "\\\\").replace("\"", "\\\"");+ given()+ .contentType(ContentType.JSON)+ .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"" + escaped + "\"}}")+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod + "/integration")+ .then()+ .statusCode(201);+ }++ private void putIntegrationResponse(String httpMethod, String statusCode, String selectionPattern,+ String responseParametersJson) {+ given()+ .contentType(ContentType.JSON)+ .body("{\"selectionPattern\":\"" + selectionPattern + "\",\"responseParameters\":{"+ + responseParametersJson + "}}")+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod+ + "/integration/responses/" + statusCode)+ .then()+ .statusCode(201);+ }++ private void putMethodResponse(String httpMethod, String statusCode) {+ given()+ .contentType(ContentType.JSON)+ .body("{\"responseParameters\":{}}")+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod+ + "/responses/" + statusCode)+ .then()+ .statusCode(201);+ }++ private void deploy() {+ String deploymentId = given()+ .contentType(ContentType.JSON)+ .body("{\"description\":\"v1\"}")+ .when().post("/restapis/" + apiId + "/deployments")+ .then()+ .statusCode(201)+ .extract().path("id");++ given()+ .contentType(ContentType.JSON)+ .body("{\"stageName\":\"" + STAGE + "\",\"deploymentId\":\"" + deploymentId + "\"}")+ .when().post("/restapis/" + apiId + "/stages")+ .then()+ .statusCode(201);+ }+}