diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index f7ab4318f1..9f66b35cac 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -108,7 +108,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. +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. ### Examples 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 af7a69e8e3..0eff923d63 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 @@ -1046,15 +1046,38 @@ public class ApiGatewayExecuteController { // 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, + // Lambda path-style integrations (arn:aws:apigateway:{region}:lambda:path/...) are + // handled specially: the function name is extracted from the URI and the rendered + // request template body is passed directly as the Lambda payload — just like + // AWS_PROXY, but with request/response VTL mapping applied. + // + // For other services: 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 { - if (target.action() == null) { + if ("lambda".equals(target.service())) { + String functionName = functionNameFromUri(integration.getUri()); + if (functionName == null || functionName.isBlank()) { + throw new AwsException("InvalidParameterValueException", + "Cannot resolve Lambda function name from URI: " + integration.getUri(), 400); + } + byte[] payload = transformedBody != null ? transformedBody.getBytes(StandardCharsets.UTF_8) : new byte[0]; + InvokeResult invokeResult = lambdaService.invoke(region, functionName, payload, InvocationType.RequestResponse); + String lambdaResponseBody = invokeResult.getPayload() != null + ? new String(invokeResult.getPayload(), StandardCharsets.UTF_8) : "{}"; + int lambdaStatus = invokeResult.getStatusCode() > 0 ? invokeResult.getStatusCode() : 200; + if (invokeResult.getFunctionError() != null) { + errorType = invokeResult.getFunctionError(); + errorMessage = lambdaResponseBody; + } + serviceResponse = Response.status(lambdaStatus) + .entity(lambdaResponseBody) + .type(MediaType.APPLICATION_JSON).build(); + } else if (target.action() == null) { MultivaluedMap formParams = parseFormUrlEncoded(transformedBody); if ("sqs".equals(target.service()) && target.path() != null) { @@ -1191,13 +1214,18 @@ public class ApiGatewayExecuteController { } Response.ResponseBuilder rb = Response.status(finalStatus) - .entity(finalBody) - .type(MediaType.APPLICATION_JSON); + .entity(finalBody); + + String contentType = null; // Apply $context.responseOverride header assignments. if (templateResult != null && !templateResult.headerOverrides().isEmpty()) { for (Map.Entry hdr : templateResult.headerOverrides().entrySet()) { - rb.header(hdr.getKey(), hdr.getValue()); + if ("Content-Type".equalsIgnoreCase(hdr.getKey())) { + contentType = hdr.getValue(); + } else { + rb.header(hdr.getKey(), hdr.getValue()); + } } } @@ -1216,11 +1244,16 @@ public class ApiGatewayExecuteController { String headerName = dest.substring("method.response.header.".length()); String headerValue = resolveResponseParameter(source, serviceResponseHeaders, responseBodyStr); if (headerValue != null) { - rb.header(headerName, headerValue); + if ("Content-Type".equalsIgnoreCase(headerName)) { + contentType = headerValue; + } else { + rb.header(headerName, headerValue); + } } } } + rb.type(contentType != null ? contentType : MediaType.APPLICATION_JSON); return rb.build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java index ce1e3eb24e..282f723f53 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java @@ -163,16 +163,23 @@ public final class LambdaArnUtils { } /** - * Extracts the Lambda function name from an API Gateway integration URI. + * Extracts the Lambda function reference from an API Gateway integration URI. * Handles formats like: * * + *

Any trailing {@code :qualifier} (alias or version) is preserved in the returned + * value (e.g. {@code myFn:PROD}) so downstream {@code invoke} calls, which resolve the + * reference via {@link #resolve(String)}, target the configured alias/version rather + * than reducing to the bare function name and invoking {@code $LATEST}. + * * @param uri the integration URI (may be null) - * @return the extracted function name, or null if the URI is null or unparseable + * @return the extracted function reference (name, optionally with {@code :qualifier}), + * or null if the URI is null or unparseable */ public static String extractFunctionNameFromUri(String uri) { if (uri == null) { @@ -189,8 +196,16 @@ public final class LambdaArnUtils { String embeddedArn = String.join("/", java.util.Arrays.copyOfRange(parts, 3, parts.length)); return extractFunctionNameFromUri(embeddedArn); } - // Standard Lambda ARN: parts[0] is "function:myFn", strip the "function:" prefix + // Standard Lambda ARN: parts[0] is "function:myFn" or "function:myFn:qualifier". + // Strip only the leading "function:" resource-type prefix, preserving any + // trailing :qualifier (alias/version) so the invoke target is not lost. String functionPart = parts[0]; + String functionPrefix = "function:"; + if (functionPart.startsWith(functionPrefix)) { + return functionPart.substring(functionPrefix.length()); + } + // Fallback for malformed/non-standard resources: every real Lambda ARN resource + // starts with "function:" and is handled above, so this only fires on unexpected input. int colon = functionPart.lastIndexOf(':'); return colon >= 0 ? functionPart.substring(colon + 1) : functionPart; } catch (IllegalArgumentException e) { diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsLambdaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsLambdaIntegrationTest.java new file mode 100644 index 0000000000..0a7d7a8384 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsLambdaIntegrationTest.java @@ -0,0 +1,296 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import io.restassured.response.Response; +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 java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Regression tests for API Gateway AWS (non-proxy) Lambda integration. + * + *

Covers two bugs fixed in {@code ApiGatewayExecuteController#invokeAwsIntegration}: + *

    + *
  1. AWS type with a Lambda path-style URI was incorrectly routed through the query-protocol + * (form-urlencoded) dispatch path, returning + * {@code "The request must contain the parameter Action"} instead of invoking the Lambda.
  2. + *
  3. If a {@code Content-Type} header was set via {@code responseParameters} mapping or a VTL + * {@code $context.responseOverride}, it was added on top of an already-set + * {@code APPLICATION_JSON} type, producing duplicate {@code Content-Type} response headers.
  4. + *
+ */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayAwsLambdaIntegrationTest { + + private static final String LAMBDA_BASE_PATH = "/2015-03-31/functions"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/lambda-role"; + private static final String REGION = "us-east-1"; + + // Echo function: returns the received event body back in the response body. + private static final String ECHO_FUNCTION = "apigw-aws-lambda-echo"; + + private static String apiId; + private static String rootId; + private static String echoResourceId; + private static String ctHeaderResourceId; + + // ──────────────────────────── Lambda setup ──────────────────────────── + + @Test + @Order(1) + void setup_createEchoLambda() throws Exception { + // Returns the raw event payload as the response body so the test can + // assert that the VTL-rendered request template reached the function. + // AWS (non-proxy) integrations pass the raw Lambda return value through + // the integration response pipeline — do not wrap in a proxy envelope. + createNodeLambda(ECHO_FUNCTION, """ + exports.handler = async (event) => event; + """); + } + + // ──────────────────────────── API Gateway setup ──────────────────────────── + + @Test + @Order(2) + void setup_createRestApi() { + apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"aws-lambda-integration-regression\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + assertNotNull(apiId); + } + + @Test + @Order(3) + void setup_getRootResource() { + rootId = given() + .when().get("/restapis/" + apiId + "/resources") + .then().statusCode(200) + .extract().path("item[0].id"); + assertNotNull(rootId); + } + + // ──────────────────────────── Resource 1: /echo — AWS Lambda integration ──────────────────────────── + + @Test + @Order(4) + void setup_createEchoResource() { + echoResourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"echo\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId) + .then().statusCode(201) + .extract().path("id"); + assertNotNull(echoResourceId); + } + + @Test + @Order(5) + void setup_configureEchoMethod() { + String functionArn = "arn:aws:lambda:" + REGION + ":000000000000:function:" + ECHO_FUNCTION; + String integrationUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + functionArn + "/invocations"; + + given() + .contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when().put("/restapis/" + apiId + "/resources/" + echoResourceId + "/methods/POST") + .then().statusCode(201); + + // AWS (non-proxy) Lambda integration with a VTL request template + given() + .contentType(ContentType.JSON) + .body(""" + { + "type": "AWS", + "httpMethod": "POST", + "uri": "%s", + "requestTemplates": { + "application/json": "{\\"forwarded\\": $input.json('$')}" + } + } + """.formatted(integrationUri)) + .when().put("/restapis/" + apiId + "/resources/" + echoResourceId + "/methods/POST/integration") + .then().statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}") + .when().put("/restapis/" + apiId + "/resources/" + echoResourceId + + "/methods/POST/integration/responses/200") + .then().statusCode(201); + } + + // ──────────────────────────── Resource 2: /ct-header — Content-Type header dedup ──────────────────────────── + + @Test + @Order(6) + void setup_createCtHeaderResource() { + ctHeaderResourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"ct-header\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId) + .then().statusCode(201) + .extract().path("id"); + assertNotNull(ctHeaderResourceId); + } + + @Test + @Order(7) + void setup_configureCtHeaderMethod() { + String functionArn = "arn:aws:lambda:" + REGION + ":000000000000:function:" + ECHO_FUNCTION; + String integrationUri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/" + + functionArn + "/invocations"; + + given() + .contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when().put("/restapis/" + apiId + "/resources/" + ctHeaderResourceId + "/methods/POST") + .then().statusCode(201); + + given() + .contentType(ContentType.JSON) + .body(""" + { + "type": "AWS", + "httpMethod": "POST", + "uri": "%s", + "requestTemplates": { + "application/json": "{\\"input\\": $input.json('$')}" + } + } + """.formatted(integrationUri)) + .when().put("/restapis/" + apiId + "/resources/" + ctHeaderResourceId + "/methods/POST/integration") + .then().statusCode(201); + + // Integration response with a responseParameters Content-Type mapping. + // Before the fix, this caused a second Content-Type header to be added on + // top of the ResponseBuilder's already-set APPLICATION_JSON type. + given() + .contentType(ContentType.JSON) + .body(""" + { + "selectionPattern": "", + "responseTemplates": {"application/json": ""}, + "responseParameters": { + "method.response.header.Content-Type": "'application/json'" + } + } + """) + .when().put("/restapis/" + apiId + "/resources/" + ctHeaderResourceId + + "/methods/POST/integration/responses/200") + .then().statusCode(201); + } + + @Test + @Order(8) + void setup_deployStage() { + String deploymentId = given() + .contentType(ContentType.JSON) + .body("{\"description\":\"regression-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); + } + + // ──────────────────────────── Regression test 1: AWS Lambda dispatch ──────────────────────────── + + /** + * Regression: AWS type Lambda integration must dispatch to Lambda rather than falling + * through to the query-protocol path. Before the fix, Floci returned 500 with + * {@code "The request must contain the parameter Action"}. + * + *

This test verifies the dispatch routing is correct. Actual Lambda execution + * requires Docker and is covered by compatibility tests. + */ + @Test + @Order(10) + void awsLambdaIntegration_doesNotReturnQueryProtocolError() { + given() + .contentType(ContentType.JSON) + .body("{\"hello\":\"world\"}") + .when().post("/execute-api/" + apiId + "/test/echo") + .then() + // Must not be a 500 from the query-protocol dispatcher + .statusCode(not(equalTo(500))) + // Exact regression: the old error from invokeQuery must not appear + .body(not(containsString("must contain the parameter Action"))); + } + + // ──────────────────────────── Regression test 2: duplicate Content-Type header ──────────────────────────── + + /** + * Regression: When a {@code responseParameters} mapping sets {@code Content-Type}, + * the response must contain exactly one {@code Content-Type} header. Before the fix, + * two values were present — one from the eager {@code .type(APPLICATION_JSON)} call + * and one added by the response parameter mapping. + */ + @Test + @Order(12) + void awsLambdaIntegration_responseParametersContentType_notDuplicated() { + Response response = given() + .contentType(ContentType.JSON) + .body("{\"check\":\"ct\"}") + .when().post("/execute-api/" + apiId + "/test/ct-header") + .then() + .statusCode(200) + .extract().response(); + + // Must be exactly one Content-Type header value, not two + assertEquals(1, response.getHeaders().getList("Content-Type").size(), + "Content-Type header must appear exactly once in the response"); + assertThat(response.getHeader("Content-Type"), containsString("application/json")); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private static void createNodeLambda(String functionName, String handlerSource) throws Exception { + String zipBase64 = Base64.getEncoder().encodeToString(makeZip("index.js", handlerSource)); + given() + .contentType(ContentType.JSON) + .body(""" + { + "FunctionName": "%s", + "Runtime": "nodejs20.x", + "Role": "%s", + "Handler": "index.handler", + "Timeout": 30, + "Code": {"ZipFile": "%s"} + } + """.formatted(functionName, ROLE_ARN, zipBase64)) + .when().post(LAMBDA_BASE_PATH) + .then().statusCode(201); + } + + private static byte[] makeZip(String filename, String content) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + zos.putNextEntry(new ZipEntry(filename)); + zos.write(content.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + } + return baos.toByteArray(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java index 65ba7d1417..061ef4c92d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java @@ -142,4 +142,29 @@ class LambdaArnUtilsTest { String uri = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations"; assertEquals("myFn", LambdaArnUtils.extractFunctionNameFromUri(uri)); } + + @ParameterizedTest + @CsvSource({ + // Qualified targets (alias / numbered version) must preserve the :qualifier + // so downstream invoke resolves the configured target instead of $LATEST. + "arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations, myFn:PROD", + "arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD, myFn:PROD", + "arn:aws:lambda:us-east-1:000000000000:function:myFn:1/invocations, myFn:1", + "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations, myFn:PROD", + "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn:42/invocations, myFn:42", + }) + void extractFunctionNameFromUri_preservesQualifier(String uri, String expected) { + assertEquals(expected, LambdaArnUtils.extractFunctionNameFromUri(uri)); + } + + @Test + void extractFunctionNameFromUri_qualifiedRef_resolvesToNameAndQualifier() { + // The extracted "myFn:PROD" must resolve into a distinct name + qualifier, + // which is what invoke() relies on to target the alias/version. + String extracted = LambdaArnUtils.extractFunctionNameFromUri( + "arn:aws:lambda:us-east-1:000000000000:function:myFn:PROD/invocations"); + LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(extracted); + assertEquals("myFn", ref.name()); + assertEquals("PROD", ref.qualifier()); + } }