mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(apigateway): apply MOCK integration response headers (#1822)
* fix(apigateway): apply mock response headers for OPTIONS * refactor(apigateway): drop the OPTIONS route in favour of #1955 Both this PR and #1955 added an @OPTIONS method on the same @Path in ApiGatewayExecuteController and ApiGatewayUserRequestController, so whichever merged second would not have compiled. #1955's version is the more complete one: it covers ApiGatewayAwsExecuteController (the /_aws/execute-api path) as well, forwards the request body, and skips GlobalCorsFilter for deployed-API paths -- without which a real browser preflight is short-circuited before it ever reaches the route. This PR keeps only its own contribution: invokeMock returned early on the empty-response-template path and dropped static method.response.header.* mappings. ApiGatewayMockCorsHeadersTest now exercises that over GET, since the dropped-header bug is verb-agnostic, leaving the two PRs independently mergeable in either order. * test(dynamodb): retain Quarkus port for cleanup * chore: rerun CI after autoscaling test flake --------- Co-authored-by: abanna <abanna@users.noreply.github.com>
This commit is contained in:
1 parent
5d61e95239
commit
a49c3e57f6
3 files changed
+316
-31
No files matched your search
+61
-31
@@ -44,6 +44,7 @@ import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
@@ -1235,43 +1236,72 @@ public class ApiGatewayExecuteController {
|
||||
String template = ir.responseTemplates() != null
|
||||
? ir.responseTemplates().getOrDefault("application/json", "") : "";
|
||||
|
||||
if (template.isEmpty()) {
|
||||
return Response.status(Integer.parseInt(ir.statusCode()))
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
int status = Integer.parseInt(ir.statusCode());
|
||||
String responseBody = null;
|
||||
Map<String, String> vtlHeaderOverrides = new HashMap<>();
|
||||
|
||||
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();
|
||||
responseBody = result.body();
|
||||
vtlHeaderOverrides = result.headerOverrides();
|
||||
}
|
||||
|
||||
// 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));
|
||||
Response.ResponseBuilder rb = Response.status(status).type(MediaType.APPLICATION_JSON);
|
||||
if (responseBody != null) {
|
||||
rb.entity(responseBody);
|
||||
}
|
||||
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);
|
||||
|
||||
int status = result.statusOverride() != null
|
||||
? result.statusOverride()
|
||||
: Integer.parseInt(ir.statusCode());
|
||||
|
||||
Response.ResponseBuilder rb = Response.status(status)
|
||||
.entity(result.body())
|
||||
.type(MediaType.APPLICATION_JSON);
|
||||
|
||||
for (Map.Entry<String, String> hdr : result.headerOverrides().entrySet()) {
|
||||
// $context.responseOverride header assignments (VTL) take precedence.
|
||||
for (Map.Entry<String, String> hdr : vtlHeaderOverrides.entrySet()) {
|
||||
rb.header(hdr.getKey(), hdr.getValue());
|
||||
}
|
||||
// Header names a VTL $context.responseOverride already set (HTTP header names are
|
||||
// case-insensitive); these win, so skip a responseParameters entry for the same header
|
||||
// rather than adding a second value for it.
|
||||
Set<String> vtlOverriddenHeaders = new HashSet<>();
|
||||
for (String name : vtlHeaderOverrides.keySet()) {
|
||||
vtlOverriddenHeaders.add(name.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
// Apply static header mappings from the integration response's responseParameters.
|
||||
// This is what makes MOCK-integration CORS work (e.g. OPTIONS preflight returning
|
||||
// Access-Control-Allow-Origin/-Methods/-Headers). A MOCK has no backend, so only
|
||||
// static ('literal') and response-body-JSONPath sources resolve; header sources
|
||||
// (integration.response.header.*) yield null and are skipped.
|
||||
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;
|
||||
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
|
||||
}
|
||||
String headerValue = resolveResponseParameter(param.getValue(),
|
||||
new HashMap<>(), responseBody != null ? responseBody : "{}");
|
||||
if (headerValue != null) {
|
||||
rb.header(headerName, headerValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rb.build();
|
||||
}
|
||||
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* Regression test for MOCK-integration response parameters: a MOCK integration whose "200"
|
||||
* integration response declares static {@code responseParameters} (e.g. {@code
|
||||
* method.response.header.Access-Control-Allow-Origin -> '*'}) must emit those as real HTTP
|
||||
* response headers. Previously {@code invokeMock} returned early on the empty-response-template
|
||||
* path and dropped the static header mappings entirely.
|
||||
*
|
||||
* <p>The integration is shaped like the CORS methods API-Gateway OpenAPI import produces (mock
|
||||
* integration, {@code requestTemplates {"statusCode":200}}, NO responseTemplates), because that
|
||||
* is the configuration the bug was found with. It is exercised over GET rather than OPTIONS:
|
||||
* the dropped-header bug is verb-agnostic, and routing OPTIONS to the configured method is a
|
||||
* separate fix owned by #1955, which also skips {@code GlobalCorsFilter} for deployed-API paths
|
||||
* so a real browser preflight reaches the route at all.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApiGatewayMockCorsHeadersTest {
|
||||
|
||||
private String apiId;
|
||||
private String rootId;
|
||||
private String resourceId;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
createRestApi();
|
||||
setupMockIntegration();
|
||||
createDeploymentAndStage();
|
||||
}
|
||||
|
||||
private void createRestApi() {
|
||||
apiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"mock-cors-test-api\"}")
|
||||
.when().post("/restapis")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("id", notNullValue())
|
||||
.extract().path("id");
|
||||
}
|
||||
|
||||
private void setupMockIntegration() {
|
||||
rootId = given()
|
||||
.when().get("/restapis/" + apiId + "/resources")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("item[0].id");
|
||||
|
||||
resourceId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"pathPart\":\"cors\"}")
|
||||
.when().post("/restapis/" + apiId + "/resources/" + rootId)
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().path("id");
|
||||
|
||||
// No authorization, mirroring an OpenAPI-imported CORS method.
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"authorizationType\":\"NONE\"}")
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"responseParameters\":{}}")
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/responses/200")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
// Classic CORS mock: request template short-circuits to 200; NO response template.
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
// Static CORS headers as integration-response responseParameters.
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"selectionPattern\":\"\",\"responseParameters\":{"
|
||||
+ "\"method.response.header.Access-Control-Allow-Origin\":\"'*'\","
|
||||
+ "\"method.response.header.Access-Control-Allow-Methods\":\"'GET,OPTIONS,POST'\","
|
||||
+ "\"method.response.header.Access-Control-Allow-Headers\":\"'Content-Type,Authorization,X-Custom-CFN-Header'\""
|
||||
+ "}}")
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
}
|
||||
|
||||
private void createDeploymentAndStage() {
|
||||
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\":\"api\",\"deploymentId\":\"" + deploymentId + "\"}")
|
||||
.when().post("/restapis/" + apiId + "/stages")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mockIntegrationEmitsStaticResponseParameterHeaders() {
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/api/cors")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.header("Access-Control-Allow-Methods", equalTo("GET,OPTIONS,POST"))
|
||||
.header("Access-Control-Allow-Headers", equalTo("Content-Type,Authorization,X-Custom-CFN-Header"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void alsoViaUserRequestPath() {
|
||||
given()
|
||||
.when().get("/restapis/" + apiId + "/api/_user_request_/cors")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
if (apiId != null) {
|
||||
given().when().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
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 java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Regression test for header precedence when a MOCK integration response sets the same header via
|
||||
* both a VTL {@code $context.responseOverride.header[...]} assignment and a static
|
||||
* {@code responseParameters} mapping. AWS lets the VTL responseOverride win; Floci must emit a
|
||||
* single value for that header, not two (the responseParameters value must be skipped).
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApiGatewayMockVtlHeaderPrecedenceTest {
|
||||
|
||||
private String apiId;
|
||||
private String rootId;
|
||||
private String resourceId;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
createRestApi();
|
||||
setupPostMockWithVtlOverrideAndResponseParameters();
|
||||
deploy();
|
||||
}
|
||||
|
||||
private void createRestApi() {
|
||||
apiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"mock-vtl-precedence-api\"}")
|
||||
.when().post("/restapis")
|
||||
.then().statusCode(201).body("id", notNullValue())
|
||||
.extract().path("id");
|
||||
}
|
||||
|
||||
private void setupPostMockWithVtlOverrideAndResponseParameters() {
|
||||
rootId = given().when().get("/restapis/" + apiId + "/resources")
|
||||
.then().statusCode(200).extract().path("item[0].id");
|
||||
|
||||
resourceId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"pathPart\":\"echo\"}")
|
||||
.when().post("/restapis/" + apiId + "/resources/" + rootId)
|
||||
.then().statusCode(201).extract().path("id");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"authorizationType\":\"NONE\"}")
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
|
||||
.then().statusCode(201);
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"responseParameters\":{}}")
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/responses/200")
|
||||
.then().statusCode(201);
|
||||
|
||||
// MOCK: request template short-circuits to 200.
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
|
||||
.then().statusCode(201);
|
||||
|
||||
// Integration response sets X-Precedence via VTL responseOverride AND via responseParameters.
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"selectionPattern\":\"\","
|
||||
+ "\"responseTemplates\":{\"application/json\":"
|
||||
+ "\"#set($context.responseOverride.header[\\\"X-Precedence\\\"] = \\\"from-vtl\\\")\"},"
|
||||
+ "\"responseParameters\":{\"method.response.header.X-Precedence\":\"'from-params'\"}}")
|
||||
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration/responses/200")
|
||||
.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\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}")
|
||||
.when().post("/restapis/" + apiId + "/stages")
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
@Test
|
||||
void vtlResponseOverrideWinsWithoutDuplicatingTheHeader() {
|
||||
List<String> values = given()
|
||||
.contentType(ContentType.JSON).body("{}")
|
||||
.when().post("/execute-api/" + apiId + "/test/echo")
|
||||
.then().statusCode(200)
|
||||
.extract().headers().getValues("X-Precedence");
|
||||
// Exactly one value, and it is the VTL override — not the responseParameters value, and not both.
|
||||
assertEquals(1, values.size(), "expected a single X-Precedence header, got: " + values);
|
||||
assertEquals("from-vtl", values.get(0));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
if (apiId != null) {
|
||||
given().when().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user