Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(APIGW): OpenAPI/Swagger import, models, and request validation (#113)

thegagned1d7ec3bd312
diff --git a/pom.xml b/pom.xml
index 6f8c01aa3f..6ad681cfe3 100644
--- a/pom.xml
+++ b/pom.xml
@@ -102,6 +102,27 @@
<version>0.9.9</version>
</dependency>
+ <!-- Apache Velocity Template Engine (API Gateway VTL mapping templates) -->
+ <dependency>
+ <groupId>org.apache.velocity</groupId>
+ <artifactId>velocity-engine-core</artifactId>
+ <version>2.4.1</version>
+ </dependency>
+
+ <!-- JSON Schema validation (API Gateway request validation) -->
+ <dependency>
+ <groupId>com.networknt</groupId>
+ <artifactId>json-schema-validator</artifactId>
+ <version>1.5.8</version>
+ </dependency>
+
+ <!-- OpenAPI/Swagger parser (API Gateway ImportRestApi) -->
+ <dependency>
+ <groupId>io.swagger.parser.v3</groupId>
+ <artifactId>swagger-parser</artifactId>
+ <version>2.1.38</version>
+ </dependency>
+
<!-- Testing -->
<dependency>
<groupId>io.quarkus</groupId>
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
index 11d450c804..be27838d06 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
@@ -152,8 +152,14 @@ public class ApiGatewayController {
@POST
@Path("/restapis")
- public Response createRestApi(@Context HttpHeaders headers, String body) {
+ public Response createRestApi(@Context HttpHeaders headers,
+ @QueryParam("mode") String mode,
+ String body) {
String region = regionResolver.resolveRegion(headers);
+ if ("import".equals(mode)) {
+ RestApi api = service.importRestApi(region, body);
+ return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
+ }
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
@@ -164,6 +170,17 @@ public class ApiGatewayController {
}
}
+ @PUT
+ @Path("/restapis/{apiId}")
+ public Response putRestApi(@Context HttpHeaders headers,
+ @PathParam("apiId") String apiId,
+ @QueryParam("mode") String mode,
+ String body) {
+ String region = regionResolver.resolveRegion(headers);
+ RestApi api = service.putRestApi(region, apiId, mode, body);
+ return Response.ok(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
+ }
+
@GET
@Path("/restapis")
public Response getRestApis(@Context HttpHeaders headers) {
@@ -628,6 +645,52 @@ public class ApiGatewayController {
return Response.accepted().build();
}
+ // ──────────────────────────── Models (v1) ────────────────────────────
+
+ @POST
+ @Path("/restapis/{apiId}/models")
+ public Response createModel(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
+ String region = regionResolver.resolveRegion(headers);
+ try {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> request = objectMapper.readValue(body, Map.class);
+ io.github.hectorvent.floci.services.apigateway.model.Model model = service.createModel(region, apiId, request);
+ return Response.status(201).entity(toModelNode(model).toString()).type(MediaType.APPLICATION_JSON).build();
+ } catch (IOException e) {
+ throw new AwsException("BadRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @GET
+ @Path("/restapis/{apiId}/models")
+ public Response getModels(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
+ String region = regionResolver.resolveRegion(headers);
+ List<io.github.hectorvent.floci.services.apigateway.model.Model> models = service.getModels(region, apiId);
+ ObjectNode root = objectMapper.createObjectNode();
+ ArrayNode items = root.putArray("item");
+ models.forEach(m -> items.add(toModelNode(m)));
+ return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ @GET
+ @Path("/restapis/{apiId}/models/{modelName}")
+ public Response getModel(@Context HttpHeaders headers,
+ @PathParam("apiId") String apiId,
+ @PathParam("modelName") String modelName) {
+ String region = regionResolver.resolveRegion(headers);
+ return Response.ok(toModelNode(service.getModel(region, apiId, modelName)).toString()).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ @DELETE
+ @Path("/restapis/{apiId}/models/{modelName}")
+ public Response deleteModel(@Context HttpHeaders headers,
+ @PathParam("apiId") String apiId,
+ @PathParam("modelName") String modelName) {
+ String region = regionResolver.resolveRegion(headers);
+ service.deleteModel(region, apiId, modelName);
+ return Response.accepted().build();
+ }
+
// ──────────────────────────── Custom Domains (v1) ────────────────────────────
@POST
@@ -843,6 +906,12 @@ public class ApiGatewayController {
node.put("httpMethod", m.getHttpMethod());
node.put("authorizationType", m.getAuthorizationType());
if (m.getAuthorizerId() != null) node.put("authorizerId", m.getAuthorizerId());
+ if (m.getRequestValidatorId() != null) node.put("requestValidatorId", m.getRequestValidatorId());
+ if (m.getRequestModels() != null && !m.getRequestModels().isEmpty()) {
+ ObjectNode models = objectMapper.createObjectNode();
+ m.getRequestModels().forEach(models::put);
+ node.set("requestModels", models);
+ }
if (m.getMethodIntegration() != null) {
node.set("methodIntegration", toIntegrationNode(m.getMethodIntegration()));
}
@@ -860,6 +929,7 @@ public class ApiGatewayController {
node.put("type", i.getType());
node.put("httpMethod", i.getHttpMethod());
node.put("uri", i.getUri());
+ node.put("passthroughBehavior", i.getPassthroughBehavior());
return node;
}
@@ -948,6 +1018,16 @@ public class ApiGatewayController {
return node;
}
+ private ObjectNode toModelNode(io.github.hectorvent.floci.services.apigateway.model.Model m) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("id", m.getId());
+ node.put("name", m.getName());
+ if (m.getDescription() != null) node.put("description", m.getDescription());
+ node.put("contentType", m.getContentType());
+ if (m.getSchema() != null) node.put("schema", m.getSchema());
+ return node;
+ }
+
private ObjectNode toRequestValidatorNode(RequestValidator v) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", v.getId());
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 38d1bc64e8..d4f821cad3 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
@@ -22,9 +22,11 @@ import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.regex.Pattern;
/**
* Executes API Gateway stage requests, routing them through the configured
@@ -46,16 +48,21 @@ public class ApiGatewayExecuteController {
private final LambdaService lambdaService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
+ private final VtlTemplateEngine vtlEngine;
+ private final AwsServiceRouter serviceRouter;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
LambdaService lambdaService, RegionResolver regionResolver,
- ObjectMapper objectMapper) {
+ ObjectMapper objectMapper, VtlTemplateEngine vtlEngine,
+ AwsServiceRouter serviceRouter) {
this.apiGatewayService = apiGatewayService;
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaService = lambdaService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
+ this.vtlEngine = vtlEngine;
+ this.serviceRouter = serviceRouter;
}
@GET
@@ -157,6 +164,10 @@ public class ApiGatewayExecuteController {
Response authResponse = invokeAuthorizer(region, apiId, method, headers, uriInfo);
if (authResponse != null) return authResponse;
+ // 2. Request validation
+ Response validationResponse = validateRequest(region, apiId, method, headers, uriInfo, body);
+ if (validationResponse != null) return validationResponse;
+
Integration integration = method.getMethodIntegration();
if (integration == null) {
return Response.status(500)
@@ -170,6 +181,8 @@ public class ApiGatewayExecuteController {
return switch (integration.getType().toUpperCase()) {
case "AWS_PROXY" -> invokeProxy(region, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body);
+ case "AWS" -> invokeAwsIntegration(region, httpMethod, path, proxy, stageName,
+ matched, integration, headers, uriInfo, body);
case "MOCK" -> invokeMock(integration);
default -> Response.status(500)
.entity(jsonMessage("Unsupported integration type: " + integration.getType()))
@@ -242,6 +255,97 @@ public class ApiGatewayExecuteController {
return null;
}
+ private Response validateRequest(String region, String apiId, MethodConfig method,
+ HttpHeaders headers, UriInfo uriInfo, byte[] body) {
+ String validatorId = method.getRequestValidatorId();
+ if (validatorId == null) return null;
+
+ io.github.hectorvent.floci.services.apigateway.model.RequestValidator validator;
+ try {
+ validator = apiGatewayService.getRequestValidator(region, apiId, validatorId);
+ } catch (AwsException e) {
+ return null; // Validator not found — skip validation
+ }
+
+ // Validate request parameters
+ if (validator.isValidateRequestParameters()) {
+ Map<String, Boolean> requiredParams = method.getRequestParameters();
+ if (requiredParams != null) {
+ MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
+ for (Map.Entry<String, Boolean> entry : requiredParams.entrySet()) {
+ if (!Boolean.TRUE.equals(entry.getValue())) continue;
+ String paramKey = entry.getKey();
+ // Format: method.request.querystring.name or method.request.header.name
+ if (paramKey.startsWith("method.request.querystring.")) {
+ String name = paramKey.substring("method.request.querystring.".length());
+ if (!queryParams.containsKey(name) || queryParams.getFirst(name) == null) {
+ return Response.status(400)
+ .entity(jsonMessage("Missing required request parameter in QUERY_STRING: '" + name + "'"))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+ } else if (paramKey.startsWith("method.request.header.")) {
+ String name = paramKey.substring("method.request.header.".length());
+ if (headers.getHeaderString(name) == null) {
+ return Response.status(400)
+ .entity(jsonMessage("Missing required request parameter in HEADER: '" + name + "'"))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+ }
+ }
+ }
+ }
+
+ // Validate request body against model schema
+ if (validator.isValidateRequestBody()) {
+ Map<String, String> requestModels = method.getRequestModels();
+ if (requestModels != null && !requestModels.isEmpty()) {
+ String contentType = headers.getMediaType() != null
+ ? headers.getMediaType().getType() + "/" + headers.getMediaType().getSubtype()
+ : "application/json";
+ String modelName = requestModels.get(contentType);
+ if (modelName == null) modelName = requestModels.get("application/json");
+
+ if (modelName != null) {
+ try {
+ io.github.hectorvent.floci.services.apigateway.model.Model model =
+ apiGatewayService.getModel(region, apiId, modelName);
+ String schemaStr = model.getSchema();
+ if (schemaStr != null && !schemaStr.isBlank()) {
+ String bodyStr = body != null ? new String(body, StandardCharsets.UTF_8) : "";
+ if (bodyStr.isBlank()) {
+ return Response.status(400)
+ .entity(jsonMessage("Invalid request body"))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+ JsonNode schemaNode = objectMapper.readTree(schemaStr);
+ JsonNode bodyNode = objectMapper.readTree(bodyStr);
+
+ com.networknt.schema.JsonSchemaFactory factory =
+ com.networknt.schema.JsonSchemaFactory.getInstance(
+ com.networknt.schema.SpecVersion.VersionFlag.V4);
+ com.networknt.schema.JsonSchema schema = factory.getSchema(schemaNode);
+ var errors = schema.validate(bodyNode);
+ if (!errors.isEmpty()) {
+ String errorMsg = errors.iterator().next().getMessage();
+ return Response.status(400)
+ .entity(jsonMessage("Invalid request body: " + errorMsg))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+ }
+ } catch (AwsException e) {
+ // Model not found — skip body validation
+ } catch (Exception e) {
+ return Response.status(400)
+ .entity(jsonMessage("Invalid request body"))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+ }
+ }
+ }
+
+ return null;
+ }
+
private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth, HttpHeaders headers) {
ObjectNode node = objectMapper.createObjectNode();
node.put("type", auth.getType());
@@ -374,6 +478,290 @@ public class ApiGatewayExecuteController {
}
}
+ // ──────────────────────────── AWS (non-proxy) ────────────────────────────
+
+ private Response invokeAwsIntegration(String region, String httpMethod, String path, String proxy,
+ String stageName, ApiGatewayResource resource,
+ Integration integration, HttpHeaders headers,
+ UriInfo uriInfo, byte[] body) {
+ AwsServiceRouter.IntegrationTarget target = serviceRouter.parseIntegrationUri(integration.getUri());
+ if (target == null) {
+ return Response.status(500)
+ .entity(jsonMessage("Cannot parse AWS integration URI: " + integration.getUri()))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+
+ String requestId = UUID.randomUUID().toString();
+ String bodyStr = body != null && body.length > 0 ? new String(body) : null;
+
+ // Build VTL context
+ 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<>();
+ if (proxy != null && !proxy.isEmpty()) pathMap.put("proxy", proxy);
+
+ VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
+ bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
+ resource.getPath(), requestId, "000000000000", null);
+
+ // Apply request parameter mapping (method.request.* → integration.request.*)
+ Map<String, String> integrationReqParams = integration.getRequestParameters();
+ if (integrationReqParams != null && !integrationReqParams.isEmpty()) {
+ for (Map.Entry<String, String> param : integrationReqParams.entrySet()) {
+ String dest = param.getKey(); // integration.request.header.X-Foo or integration.request.querystring.bar
+ String source = param.getValue(); // method.request.querystring.q or method.request.header.Auth or method.request.path.id
+ String resolvedValue = resolveRequestParameter(source, queryMap, pathMap, headerMap);
+ if (resolvedValue != null) {
+ if (dest.startsWith("integration.request.header.")) {
+ headerMap.put(dest.substring("integration.request.header.".length()), resolvedValue);
+ } else if (dest.startsWith("integration.request.querystring.")) {
+ queryMap.put(dest.substring("integration.request.querystring.".length()), resolvedValue);
+ } else if (dest.startsWith("integration.request.path.")) {
+ pathMap.put(dest.substring("integration.request.path.".length()), resolvedValue);
+ }
+ }
+ }
+ }
+
+ // Content-Type negotiation and passthrough behavior
+ String transformedBody;
+ Map<String, String> 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
+ String template = requestTemplates.get(incomingContentType);
+ if (template == null) {
+ // Try without charset: "application/json; charset=utf-8" → "application/json"
+ String baseType = incomingContentType.contains(";")
+ ? incomingContentType.substring(0, incomingContentType.indexOf(';')).trim()
+ : incomingContentType;
+ template = requestTemplates.get(baseType);
+ }
+
+ if (template != null) {
+ transformedBody = vtlEngine.evaluate(template, vtlCtx);
+ } else {
+ // No matching template for this Content-Type
+ String behavior = integration.getPassthroughBehavior();
+ if ("NEVER".equalsIgnoreCase(behavior)) {
+ return Response.status(415)
+ .entity(jsonMessage("Unsupported Media Type"))
+ .type(MediaType.APPLICATION_JSON).build();
+ } else if ("WHEN_NO_TEMPLATES".equalsIgnoreCase(behavior)) {
+ // Templates exist but none match → reject
+ return Response.status(415)
+ .entity(jsonMessage("Unsupported Media Type"))
+ .type(MediaType.APPLICATION_JSON).build();
+ } else {
+ // WHEN_NO_MATCH (default) — passthrough
+ transformedBody = bodyStr != null ? bodyStr : "";
+ }
+ }
+ } else {
+ // No templates defined at all
+ String behavior = integration.getPassthroughBehavior();
+ if ("NEVER".equalsIgnoreCase(behavior)) {
+ return Response.status(415)
+ .entity(jsonMessage("Unsupported Media Type"))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+ transformedBody = bodyStr != null ? bodyStr : "";
+ }
+
+ // Dispatch to service
+ Response serviceResponse;
+ String errorType = null;
+ String errorMessage = null;
+ try {
+ JsonNode requestJson = objectMapper.readTree(transformedBody);
+ serviceResponse = serviceRouter.invoke(target.service(), target.action(), requestJson, region);
+ } catch (AwsException e) {
+ errorType = e.getErrorCode();
+ errorMessage = e.getMessage();
+ serviceResponse = null;
+ } catch (Exception e) {
+ errorType = "InternalError";
+ errorMessage = e.getMessage() != null ? e.getMessage() : "Service invocation failed";
+ serviceResponse = null;
+ }
+
+ // Build response body string
+ String responseBodyStr;
+ int serviceStatus;
+ if (serviceResponse != null) {
+ serviceStatus = serviceResponse.getStatus();
+ Object entity = serviceResponse.getEntity();
+ if (entity instanceof JsonNode jsonNode) {
+ try {
+ responseBodyStr = objectMapper.writeValueAsString(jsonNode);
+ } catch (Exception e) {
+ responseBodyStr = entity.toString();
+ }
+ } else if (entity != null) {
+ responseBodyStr = entity.toString();
+ } else {
+ responseBodyStr = "{}";
+ }
+
+ // Check if service returned an error status
+ if (serviceStatus >= 400) {
+ try {
+ JsonNode errorNode = objectMapper.readTree(responseBodyStr);
+ errorType = errorNode.path("__type").asText(
+ errorNode.path("errorType").asText(null));
+ errorMessage = errorNode.path("message").asText(
+ errorNode.path("Message").asText(
+ errorNode.path("errorMessage").asText("Service error")));
+ } catch (Exception ignored) {
+ errorType = "ServiceError";
+ errorMessage = responseBodyStr;
+ }
+ }
+ } else {
+ serviceStatus = 500;
+ responseBodyStr = String.format("{\"errorMessage\":\"%s\",\"errorType\":\"%s\"}",
+ errorMessage != null ? errorMessage.replace("\"", "\\\"") : "Unknown error",
+ errorType != null ? errorType : "UnknownError");
+ }
+
+ // Select integration response
+ Map<String, IntegrationResponse> integrationResponses = integration.getIntegrationResponses();
+ IntegrationResponse matchedResponse = null;
+ IntegrationResponse defaultResponse = null;
+
+ // Build the error string to match selectionPattern against.
+ // AWS matches against the error response body/message. We match against
+ // both errorType and errorMessage to catch patterns like ".*ResourceNotFoundException.*".
+ String errorMatchString = errorType != null
+ ? errorType + (errorMessage != null ? ": " + errorMessage : "")
+ : errorMessage;
+
+ if (integrationResponses != null && !integrationResponses.isEmpty()) {
+ for (IntegrationResponse ir : integrationResponses.values()) {
+ if (ir.selectionPattern() == null || ir.selectionPattern().isEmpty()) {
+ defaultResponse = ir;
+ } else if (errorMatchString != null) {
+ try {
+ if (Pattern.matches(ir.selectionPattern(), errorMatchString)) {
+ matchedResponse = ir;
+ break;
+ }
+ } catch (Exception ignored) {
+ // Invalid regex — skip
+ }
+ }
+ }
+ if (matchedResponse == null) {
+ matchedResponse = defaultResponse;
+ }
+ }
+
+ // Determine final status code and body
+ int finalStatus;
+ String finalBody;
+
+ if (matchedResponse != null) {
+ finalStatus = Integer.parseInt(matchedResponse.statusCode());
+
+ Map<String, String> responseTemplates = matchedResponse.responseTemplates();
+ if (responseTemplates != null && !responseTemplates.isEmpty()) {
+ String responseTemplate = responseTemplates.getOrDefault("application/json",
+ responseTemplates.values().iterator().next());
+ if (responseTemplate != null && !responseTemplate.isEmpty()) {
+ VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
+ responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
+ resource.getPath(), requestId, "000000000000", null);
+ finalBody = vtlEngine.evaluate(responseTemplate, responseMappingCtx);
+ } else {
+ finalBody = responseBodyStr;
+ }
+ } else {
+ finalBody = responseBodyStr;
+ }
+ } else {
+ finalStatus = errorType != null ? 500 : (serviceStatus >= 400 ? serviceStatus : 200);
+ finalBody = responseBodyStr;
+ }
+
+ Response.ResponseBuilder rb = Response.status(finalStatus)
+ .entity(finalBody)
+ .type(MediaType.APPLICATION_JSON);
+
+ // Apply response parameter mapping (header mapping)
+ if (matchedResponse != null && matchedResponse.responseParameters() != null) {
+ Map<String, String> serviceResponseHeaders = new HashMap<>();
+ if (serviceResponse != null) {
+ for (Map.Entry<String, List<String>> e : serviceResponse.getStringHeaders().entrySet()) {
+ if (!e.getValue().isEmpty()) serviceResponseHeaders.put(e.getKey(), e.getValue().get(0));
+ }
+ }
+ for (Map.Entry<String, String> param : matchedResponse.responseParameters().entrySet()) {
+ String dest = param.getKey(); // method.response.header.X-Foo
+ String source = param.getValue(); // integration.response.header.X-Bar or 'static' or integration.response.body.jsonpath
+ if (!dest.startsWith("method.response.header.")) continue;
+ String headerName = dest.substring("method.response.header.".length());
+ String headerValue = resolveResponseParameter(source, serviceResponseHeaders, responseBodyStr);
+ if (headerValue != null) {
+ rb.header(headerName, headerValue);
+ }
+ }
+ }
+
+ return rb.build();
+ }
+
+ private String resolveResponseParameter(String source, Map<String, String> serviceHeaders, String responseBody) {
+ if (source == null) return null;
+ // Static value: 'some value'
+ if (source.startsWith("'") && source.endsWith("'")) {
+ return source.substring(1, source.length() - 1);
+ }
+ // Integration response header
+ if (source.startsWith("integration.response.header.")) {
+ String headerName = source.substring("integration.response.header.".length());
+ return serviceHeaders.get(headerName);
+ }
+ // Integration response body (JSONPath)
+ if (source.startsWith("integration.response.body.")) {
+ String jsonPath = "$." + source.substring("integration.response.body.".length());
+ try {
+ JsonNode root = objectMapper.readTree(responseBody);
+ JsonNode node = VtlTemplateEngine.InputVariable.resolvePath(root, jsonPath);
+ return node.isMissingNode() ? null : node.asText();
+ } catch (Exception e) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ private String resolveRequestParameter(String source, Map<String, String> queryParams,
+ Map<String, String> pathParams, Map<String, String> headers) {
+ if (source == null) return null;
+ if (source.startsWith("method.request.querystring.")) {
+ return queryParams.get(source.substring("method.request.querystring.".length()));
+ }
+ if (source.startsWith("method.request.path.")) {
+ return pathParams.get(source.substring("method.request.path.".length()));
+ }
+ if (source.startsWith("method.request.header.")) {
+ return headers.get(source.substring("method.request.header.".length()));
+ }
+ // Static value
+ if (source.startsWith("'") && source.endsWith("'")) {
+ return source.substring(1, source.length() - 1);
+ }
+ return null;
+ }
+
// ──────────────────────────── MOCK ────────────────────────────
private Response invokeMock(Integration integration) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index 4b782f55f0..d2b34a6739 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -7,14 +7,14 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.*;
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.PathItem;
+import io.swagger.v3.parser.core.models.SwaggerParseResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
+import java.util.*;
@ApplicationScoped
public class ApiGatewayService {
@@ -30,6 +30,7 @@ public class ApiGatewayService {
private final StorageBackend<String, UsagePlan> usagePlanStore;
private final StorageBackend<String, UsagePlanKey> usagePlanKeyStore;
private final StorageBackend<String, RequestValidator> requestValidatorStore;
+ private final StorageBackend<String, Model> modelStore;
private final StorageBackend<String, CustomDomain> domainStore;
private final StorageBackend<String, BasePathMapping> basePathMappingStore;
private final RegionResolver regionResolver;
@@ -63,6 +64,9 @@ public class ApiGatewayService {
this.requestValidatorStore = storageFactory.create("apigateway", "apigateway-validators.json",
new TypeReference<>() {
});
+ this.modelStore = storageFactory.create("apigateway", "apigateway-models.json",
+ new TypeReference<>() {
+ });
this.domainStore = storageFactory.create("apigateway", "apigateway-domains.json",
new TypeReference<>() {
});
@@ -114,6 +118,8 @@ public class ApiGatewayService {
resourceStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(resourceStore::delete);
deploymentStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(deploymentStore::delete);
stageStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(stageStore::delete);
+ modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);
+ requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);
LOG.infov("Deleted REST API: {0} in {1}", apiId, region);
}
@@ -160,11 +166,16 @@ public class ApiGatewayService {
method.setHttpMethod(httpMethod.toUpperCase());
method.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
method.setAuthorizerId((String) request.get("authorizerId"));
+ method.setRequestValidatorId((String) request.get("requestValidatorId"));
@SuppressWarnings("unchecked")
Map<String, Boolean> reqParams = (Map<String, Boolean>) request.get("requestParameters");
if (reqParams != null) method.setRequestParameters(reqParams);
+ @SuppressWarnings("unchecked")
+ Map<String, String> reqModels = (Map<String, String>) request.get("requestModels");
+ if (reqModels != null) method.setRequestModels(reqModels);
+
resource.getResourceMethods().put(httpMethod.toUpperCase(), method);
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
return method;
@@ -216,6 +227,14 @@ public class ApiGatewayService {
integration.setHttpMethod((String) request.get("httpMethod"));
integration.setUri((String) request.get("uri"));
+ if (request.get("passthroughBehavior") != null) {
+ integration.setPassthroughBehavior((String) request.get("passthroughBehavior"));
+ }
+
+ @SuppressWarnings("unchecked")
+ Map<String, String> reqParams = (Map<String, String>) request.get("requestParameters");
+ if (reqParams != null) integration.setRequestParameters(reqParams);
+
@SuppressWarnings("unchecked")
Map<String, String> reqTemplates = (Map<String, String>) request.get("requestTemplates");
if (reqTemplates != null) integration.setRequestTemplates(reqTemplates);
@@ -544,6 +563,38 @@ public class ApiGatewayService {
requestValidatorStore.delete(requestValidatorKey(region, apiId, validatorId));
}
+ // ──────────────────────────── Models ────────────────────────────
+
+ public Model createModel(String region, String apiId, Map<String, Object> request) {
+ getRestApi(region, apiId);
+ Model model = new Model();
+ model.setId(shortId(6));
+ model.setName((String) request.get("name"));
+ model.setDescription((String) request.get("description"));
+ model.setContentType((String) request.getOrDefault("contentType", "application/json"));
+ model.setSchema((String) request.get("schema"));
+
+ modelStore.put(modelKey(region, apiId, model.getName()), model);
+ LOG.infov("Created model {0} for API {1}", model.getName(), apiId);
+ return model;
+ }
+
+ public Model getModel(String region, String apiId, String modelName) {
+ return modelStore.get(modelKey(region, apiId, modelName))
+ .orElseThrow(() -> new AwsException("NotFoundException", "Invalid model name specified", 404));
+ }
+
+ public List<Model> getModels(String region, String apiId) {
+ getRestApi(region, apiId);
+ String prefix = region + "::" + apiId + "::";
+ return modelStore.scan(k -> k.startsWith(prefix));
+ }
+
+ public void deleteModel(String region, String apiId, String modelName) {
+ getModel(region, apiId, modelName);
+ modelStore.delete(modelKey(region, apiId, modelName));
+ }
+
// ──────────────────────────── Custom Domains ────────────────────────────
public CustomDomain createDomainName(String region, Map<String, Object> request) {
@@ -685,6 +736,283 @@ public class ApiGatewayService {
apiStore.put(apiKey(region, apiId), api);
}
+ // ──────────────────────────── OpenAPI Import ────────────────────────────
+
+ public RestApi importRestApi(String region, String specBody) {
+ OpenAPI openAPI = parseOpenApiSpec(specBody);
+
+ String name = openAPI.getInfo() != null ? openAPI.getInfo().getTitle() : "Imported API";
+ String description = openAPI.getInfo() != null ? openAPI.getInfo().getDescription() : null;
+
+ Map<String, Object> request = new HashMap<>();
+ request.put("name", name);
+ request.put("description", description);
+ RestApi api = createRestApi(region, request);
+
+ applyOpenApiSpec(region, api.getId(), openAPI);
+ LOG.infov("Imported REST API from OpenAPI spec: {0} ({1})", name, api.getId());
+ return api;
+ }
+
+ public RestApi putRestApi(String region, String apiId, String mode, String specBody) {
+ // Note: mode=merge is accepted but treated as overwrite (merge semantics not yet implemented)
+ RestApi api = getRestApi(region, apiId);
+ OpenAPI openAPI = parseOpenApiSpec(specBody);
+
+ // Delete all non-root resources
+ List<ApiGatewayResource> existing = getResources(region, apiId);
+ for (ApiGatewayResource r : existing) {
+ if (!"/".equals(r.getPath())) {
+ deleteResource(region, apiId, r.getId());
+ }
+ }
+ // Clear methods on root resource
+ ApiGatewayResource root = existing.stream()
+ .filter(r -> "/".equals(r.getPath())).findFirst().orElse(null);
+ if (root != null) {
+ root.setResourceMethods(new HashMap<>());
+ resourceStore.put(resourceKey(region, apiId, root.getId()), root);
+ }
+
+ // Clear existing models and validators
+ String prefix = region + "::" + apiId + "::";
+ modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);
+ requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);
+
+ // Update API metadata from spec
+ if (openAPI.getInfo() != null) {
+ if (openAPI.getInfo().getTitle() != null) api.setName(openAPI.getInfo().getTitle());
+ if (openAPI.getInfo().getDescription() != null) api.setDescription(openAPI.getInfo().getDescription());
+ apiStore.put(apiKey(region, apiId), api);
+ }
+
+ applyOpenApiSpec(region, apiId, openAPI);
+ LOG.infov("Updated REST API from OpenAPI spec: {0} ({1})", api.getName(), apiId);
+ return api;
+ }
+
+ private OpenAPI parseOpenApiSpec(String specBody) {
+ SwaggerParseResult result = new io.swagger.parser.OpenAPIParser().readContents(specBody, null, null);
+ if (result.getOpenAPI() == null) {
+ String errors = result.getMessages() != null ? String.join(", ", result.getMessages()) : "unknown error";
+ throw new AwsException("BadRequestException", "Failed to parse OpenAPI spec: " + errors, 400);
+ }
+ return result.getOpenAPI();
+ }
+
+ @SuppressWarnings("unchecked")
+ private void applyOpenApiSpec(String region, String apiId, OpenAPI openAPI) {
+ // Import schemas as Models
+ if (openAPI.getComponents() != null && openAPI.getComponents().getSchemas() != null) {
+ for (var schemaEntry : openAPI.getComponents().getSchemas().entrySet()) {
+ String schemaName = schemaEntry.getKey();
+ var schema = schemaEntry.getValue();
+ Map<String, Object> modelReq = new HashMap<>();
+ modelReq.put("name", schemaName);
+ modelReq.put("contentType", "application/json");
+ try {
+ // Use swagger's own JSON serializer to produce clean JSON Schema
+ modelReq.put("schema", io.swagger.v3.core.util.Json.mapper().writeValueAsString(schema));
+ } catch (Exception e) {
+ modelReq.put("schema", "{}");
+ }
+ createModel(region, apiId, modelReq);
+ }
+ }
+
+ // Import x-amazon-apigateway-request-validators as RequestValidators
+ Map<String, String> validatorNameToId = new HashMap<>();
+ Map<String, Object> topExtensions = openAPI.getExtensions();
+ if (topExtensions != null) {
+ Map<String, Object> validators = (Map<String, Object>) topExtensions
+ .get("x-amazon-apigateway-request-validators");
+ if (validators != null) {
+ for (var entry : validators.entrySet()) {
+ String validatorName = entry.getKey();
+ Map<String, Object> validatorDef = (Map<String, Object>) entry.getValue();
+ Map<String, Object> valReq = new HashMap<>();
+ valReq.put("name", validatorName);
+ valReq.put("validateRequestBody",
+ Boolean.TRUE.equals(validatorDef.get("validateRequestBody")));
+ valReq.put("validateRequestParameters",
+ Boolean.TRUE.equals(validatorDef.get("validateRequestParameters")));
+ RequestValidator rv = createRequestValidator(region, apiId, valReq);
+ validatorNameToId.put(validatorName, rv.getId());
+ }
+ }
+
+ // API-level default validator
+ String defaultValidator = (String) topExtensions.get("x-amazon-apigateway-request-validator");
+ if (defaultValidator != null && validatorNameToId.containsKey(defaultValidator)) {
+ validatorNameToId.put("__default__", validatorNameToId.get(defaultValidator));
+ }
+ }
+
+ if (openAPI.getPaths() == null) return;
+
+ // Find the root resource
+ List<ApiGatewayResource> resources = getResources(region, apiId);
+ ApiGatewayResource rootResource = resources.stream()
+ .filter(r -> "/".equals(r.getPath())).findFirst().orElse(null);
+ if (rootResource == null) return;
+
+ // Map of full path → resource ID for creating nested resources
+ Map<String, String> pathToResourceId = new HashMap<>();
+ pathToResourceId.put("/", rootResource.getId());
+
+ for (Map.Entry<String, PathItem> pathEntry : openAPI.getPaths().entrySet()) {
+ String path = pathEntry.getKey();
+ PathItem pathItem = pathEntry.getValue();
+
+ // Ensure all intermediate path segments exist
+ String resourceId = ensureResourcePath(region, apiId, path, pathToResourceId);
+
+ // Create methods for each operation on this path
+ var operations = pathItem.readOperationsMap();
+ if (operations == null) continue;
+
+ for (var opEntry : operations.entrySet()) {
+ String httpMethod = opEntry.getKey().name().toUpperCase();
+ var operation = opEntry.getValue();
+
+ // Create the method
+ Map<String, Object> methodRequest = new HashMap<>();
+ methodRequest.put("authorizationType", "NONE");
+
+ // Link request models from operation requestBody
+ if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {
+ Map<String, String> requestModels = new HashMap<>();
+ for (var contentEntry : operation.getRequestBody().getContent().entrySet()) {
+ String contentType = contentEntry.getKey();
+ var mediaType = contentEntry.getValue();
+ if (mediaType.getSchema() != null && mediaType.getSchema().get$ref() != null) {
+ String ref = mediaType.getSchema().get$ref();
+ // Extract model name from #/components/schemas/ModelName
+ String modelName = ref.substring(ref.lastIndexOf('/') + 1);
+ requestModels.put(contentType, modelName);
+ }
+ }
+ if (!requestModels.isEmpty()) {
+ methodRequest.put("requestModels", requestModels);
+ }
+ }
+
+ // Map OpenAPI parameters to requestParameters
+ if (operation.getParameters() != null && !operation.getParameters().isEmpty()) {
+ Map<String, Boolean> requestParameters = new HashMap<>();
+ for (var param : operation.getParameters()) {
+ String location = switch (param.getIn()) {
+ case "query" -> "method.request.querystring." + param.getName();
+ case "header" -> "method.request.header." + param.getName();
+ case "path" -> "method.request.path." + param.getName();
+ default -> null;
+ };
+ if (location != null) {
+ requestParameters.put(location, param.getRequired() != null && param.getRequired());
+ }
+ }
+ if (!requestParameters.isEmpty()) {
+ methodRequest.put("requestParameters", requestParameters);
+ }
+ }
+
+ // Link request validator (operation-level overrides API-level default)
+ String opValidator = null;
+ if (operation.getExtensions() != null) {
+ opValidator = (String) operation.getExtensions()
+ .get("x-amazon-apigateway-request-validator");
+ }
+ if (opValidator != null && validatorNameToId.containsKey(opValidator)) {
+ methodRequest.put("requestValidatorId", validatorNameToId.get(opValidator));
+ } else if (validatorNameToId.containsKey("__default__")) {
+ methodRequest.put("requestValidatorId", validatorNameToId.get("__default__"));
+ }
+
+ putMethod(region, apiId, resourceId, httpMethod, methodRequest);
+
+ // Extract x-amazon-apigateway-integration extension
+ Map<String, Object> integrationExt = null;
+ if (operation.getExtensions() != null) {
+ integrationExt = (Map<String, Object>) operation.getExtensions()
+ .get("x-amazon-apigateway-integration");
+ }
+
+ if (integrationExt != null) {
+ applyIntegration(region, apiId, resourceId, httpMethod, integrationExt);
+ }
+ }
+ }
+ }
+
+ private String ensureResourcePath(String region, String apiId, String path,
+ Map<String, String> pathToResourceId) {
+ if (pathToResourceId.containsKey(path)) {
+ return pathToResourceId.get(path);
+ }
+
+ // Split path into segments and create each one
+ String[] segments = path.split("/");
+ StringBuilder currentPath = new StringBuilder();
+ String parentId = pathToResourceId.get("/");
+
+ for (int i = 1; i < segments.length; i++) {
+ String segment = segments[i];
+ if (segment.isEmpty()) continue;
+ currentPath.append("/").append(segment);
+ String fullPath = currentPath.toString();
+
+ if (!pathToResourceId.containsKey(fullPath)) {
+ Map<String, Object> request = new HashMap<>();
+ request.put("pathPart", segment);
+ ApiGatewayResource resource = createResource(region, apiId, parentId, request);
+ pathToResourceId.put(fullPath, resource.getId());
+ }
+ parentId = pathToResourceId.get(fullPath);
+ }
+
+ return parentId;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void applyIntegration(String region, String apiId, String resourceId,
+ String httpMethod, Map<String, Object> integrationExt) {
+ Map<String, Object> integrationRequest = new HashMap<>();
+ integrationRequest.put("type", integrationExt.get("type"));
+ integrationRequest.put("httpMethod", integrationExt.get("httpMethod"));
+ integrationRequest.put("uri", integrationExt.get("uri"));
+ integrationRequest.put("passthroughBehavior", integrationExt.get("passthroughBehavior"));
+
+ Map<String, String> reqParams = (Map<String, String>) integrationExt.get("requestParameters");
+ if (reqParams != null) integrationRequest.put("requestParameters", reqParams);
+
+ Map<String, String> reqTemplates = (Map<String, String>) integrationExt.get("requestTemplates");
+ if (reqTemplates != null) integrationRequest.put("requestTemplates", reqTemplates);
+
+ putIntegration(region, apiId, resourceId, httpMethod, integrationRequest);
+
+ // Process integration responses
+ Map<String, Object> responses = (Map<String, Object>) integrationExt.get("responses");
+ if (responses != null) {
+ for (Map.Entry<String, Object> respEntry : responses.entrySet()) {
+ String selectionPattern = respEntry.getKey();
+ Map<String, Object> respDef = (Map<String, Object>) respEntry.getValue();
+
+ String statusCode = String.valueOf(respDef.getOrDefault("statusCode", "200"));
+ String pattern = "default".equals(selectionPattern) ? "" : selectionPattern;
+
+ Map<String, Object> irRequest = new HashMap<>();
+ irRequest.put("selectionPattern", pattern);
+ irRequest.put("responseParameters", respDef.get("responseParameters"));
+ irRequest.put("responseTemplates", respDef.get("responseTemplates"));
+
+ putIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode, irRequest);
+
+ // Ensure method response exists for this status code
+ putMethodResponse(region, apiId, resourceId, httpMethod, statusCode, new HashMap<>());
+ }
+ }
+ }
+
// ──────────────────────────── Key helpers ────────────────────────────
private String apiKey(String region, String apiId) {
@@ -711,6 +1039,10 @@ public class ApiGatewayService {
return region + "::" + apiId + "::" + validatorId;
}
+ private String modelKey(String region, String apiId, String modelName) {
+ return region + "::" + apiId + "::" + modelName;
+ }
+
private String apiKeyGlobalKey(String region, String apiKeyId) {
return region + "::" + apiKeyId;
}
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
new file mode 100644
index 0000000000..4d940746e9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/AwsServiceRouter.java
@@ -0,0 +1,146 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
+import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;
+import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
+import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
+import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
+import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
+import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
+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.ssm.SsmJsonHandler;
+import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+/**
+ * Routes API Gateway AWS integration requests to the correct internal service handler.
+ *
+ * <p>Parses integration URIs of the form
+ * {@code arn:aws:apigateway:{region}:{service}:action/{ActionName}}
+ * and dispatches to the matching JSON handler.
+ */
+@ApplicationScoped
+public class AwsServiceRouter {
+
+ private static final Logger LOG = Logger.getLogger(AwsServiceRouter.class);
+
+ private final StepFunctionsJsonHandler stepFunctionsHandler;
+ private final DynamoDbJsonHandler dynamoDbHandler;
+ private final SqsJsonHandler sqsHandler;
+ private final SnsJsonHandler snsHandler;
+ private final EventBridgeHandler eventBridgeHandler;
+ private final SsmJsonHandler ssmHandler;
+ private final KinesisJsonHandler kinesisHandler;
+ private final CloudWatchLogsHandler logsHandler;
+ private final CloudWatchMetricsJsonHandler metricsHandler;
+ private final SecretsManagerJsonHandler secretsManagerHandler;
+ private final KmsJsonHandler kmsHandler;
+ private final CognitoJsonHandler cognitoHandler;
+ private final AcmJsonHandler acmHandler;
+
+ @Inject
+ public AwsServiceRouter(StepFunctionsJsonHandler stepFunctionsHandler,
+ DynamoDbJsonHandler dynamoDbHandler,
+ SqsJsonHandler sqsHandler,
+ SnsJsonHandler snsHandler,
+ EventBridgeHandler eventBridgeHandler,
+ SsmJsonHandler ssmHandler,
+ KinesisJsonHandler kinesisHandler,
+ CloudWatchLogsHandler logsHandler,
+ CloudWatchMetricsJsonHandler metricsHandler,
+ SecretsManagerJsonHandler secretsManagerHandler,
+ KmsJsonHandler kmsHandler,
+ CognitoJsonHandler cognitoHandler,
+ AcmJsonHandler acmHandler) {
+ this.stepFunctionsHandler = stepFunctionsHandler;
+ this.dynamoDbHandler = dynamoDbHandler;
+ this.sqsHandler = sqsHandler;
+ this.snsHandler = snsHandler;
+ this.eventBridgeHandler = eventBridgeHandler;
+ this.ssmHandler = ssmHandler;
+ this.kinesisHandler = kinesisHandler;
+ this.logsHandler = logsHandler;
+ this.metricsHandler = metricsHandler;
+ this.secretsManagerHandler = secretsManagerHandler;
+ this.kmsHandler = kmsHandler;
+ this.cognitoHandler = cognitoHandler;
+ this.acmHandler = acmHandler;
+ }
+
+ /**
+ * Parsed components of an API Gateway AWS integration URI.
+ */
+ public record IntegrationTarget(String region, String service, String action) {}
+
+ /**
+ * Parses an integration URI like
+ * {@code arn:aws:apigateway:us-east-1:states:action/StartExecution}.
+ *
+ * @return parsed target, or null if the URI format is not recognized
+ */
+ public IntegrationTarget parseIntegrationUri(String uri) {
+ if (uri == null || !uri.startsWith("arn:aws:apigateway:")) {
+ return null;
+ }
+ // arn:aws:apigateway:{region}:{service}:action/{Action}
+ 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;
+ }
+ String action = actionPart.substring("action/".length());
+ return new IntegrationTarget(region, service, action);
+ }
+
+ /**
+ * Dispatches to the appropriate service handler.
+ *
+ * @param service the AWS service name from the URI (e.g., "states", "dynamodb")
+ * @param action the action name (e.g., "StartExecution", "PutItem")
+ * @param requestBody the JSON request body
+ * @param region the AWS region
+ * @return the service response
+ */
+ public Response invoke(String service, String action, JsonNode requestBody, String region) {
+ LOG.debugv("AWS integration dispatch: {0}:{1} in {2}", service, action, region);
+
+ try {
+ return switch (service) {
+ case "states" -> stepFunctionsHandler.handle(action, requestBody, region);
+ case "dynamodb" -> dynamoDbHandler.handle(action, requestBody, region);
+ case "sqs" -> sqsHandler.handle(action, requestBody, region);
+ case "sns" -> snsHandler.handle(action, requestBody, region);
+ case "events" -> eventBridgeHandler.handle(action, requestBody, region);
+ case "ssm" -> ssmHandler.handle(action, requestBody, region);
+ case "kinesis" -> kinesisHandler.handle(action, requestBody, region);
+ case "logs" -> logsHandler.handle(action, requestBody, region);
+ case "monitoring" -> metricsHandler.handle(action, requestBody, region);
+ case "secretsmanager" -> secretsManagerHandler.handle(action, requestBody, region);
+ case "kms" -> kmsHandler.handle(action, requestBody, region);
+ case "cognito-idp" -> cognitoHandler.handle(action, requestBody, region);
+ case "acm" -> acmHandler.handle(action, requestBody, region);
+ default -> throw new AwsException("UnknownService",
+ "Unsupported AWS 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/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java
new file mode 100644
index 0000000000..8f83f4f4a1
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java
@@ -0,0 +1,283 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+import org.apache.velocity.runtime.RuntimeConstants;
+
+import java.io.StringWriter;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Evaluates AWS API Gateway VTL (Velocity Template Language) mapping templates.
+ *
+ * <p>Provides the standard API Gateway context variables:
+ * {@code $input}, {@code $util}, {@code $context}, {@code $stageVariables}.
+ */
+@ApplicationScoped
+public class VtlTemplateEngine {
+
+ private final VelocityEngine engine;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public VtlTemplateEngine(ObjectMapper objectMapper) {
+ this.objectMapper = objectMapper;
+ this.engine = new VelocityEngine();
+ engine.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
+ engine.setProperty(RuntimeConstants.RUNTIME_LOG_NAME, "io.github.hectorvent.floci.vtl");
+ engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "string");
+ engine.setProperty("resource.loader.string.class",
+ "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
+ engine.init();
+ }
+
+ /**
+ * Evaluates a VTL template with the given request context.
+ *
+ * @param template the VTL template string
+ * @param ctx the request context
+ * @return the evaluated template output
+ */
+ public String evaluate(String template, VtlContext ctx) {
+ if (template == null || template.isEmpty()) {
+ return ctx.body() != null ? ctx.body() : "";
+ }
+
+ VelocityContext vc = new VelocityContext();
+ vc.put("input", new InputVariable(ctx, objectMapper));
+ vc.put("util", new UtilVariable(objectMapper));
+ vc.put("context", buildContextMap(ctx));
+ vc.put("stageVariables", ctx.stageVariables() != null ? ctx.stageVariables() : Map.of());
+
+ StringWriter writer = new StringWriter();
+ engine.evaluate(vc, writer, "apigw-template", template);
+ return writer.toString();
+ }
+
+ private Map<String, Object> buildContextMap(VtlContext ctx) {
+ Map<String, Object> map = new HashMap<>();
+ map.put("requestId", ctx.requestId());
+ map.put("stage", ctx.stage());
+ map.put("httpMethod", ctx.httpMethod());
+ map.put("resourcePath", ctx.resourcePath());
+ map.put("accountId", ctx.accountId());
+
+ Map<String, String> identity = new HashMap<>();
+ identity.put("sourceIp", "127.0.0.1");
+ map.put("identity", identity);
+
+ return map;
+ }
+
+ // ────────── Context variable classes ──────────
+
+ /**
+ * Request context for VTL evaluation.
+ */
+ public record VtlContext(
+ String body,
+ Map<String, String> headers,
+ Map<String, String> queryParams,
+ Map<String, String> pathParams,
+ String stage,
+ String httpMethod,
+ String resourcePath,
+ String requestId,
+ String accountId,
+ Map<String, String> stageVariables
+ ) {}
+
+ /**
+ * The {@code $input} variable available in API Gateway VTL templates.
+ */
+ public static class InputVariable {
+
+ private final VtlContext ctx;
+ private final ObjectMapper objectMapper;
+
+ public InputVariable(VtlContext ctx, ObjectMapper objectMapper) {
+ this.ctx = ctx;
+ this.objectMapper = objectMapper;
+ }
+
+ /** Returns the raw request body. */
+ public String body() {
+ return ctx.body() != null ? ctx.body() : "";
+ }
+
+ /**
+ * Evaluates a simple JSON path against the request body and returns the result as a JSON string.
+ * Supports {@code '$'} (whole body) and dot-notation paths like {@code '$.foo.bar'}.
+ */
+ public String json(String path) {
+ if (ctx.body() == null || ctx.body().isEmpty()) {
+ return "{}";
+ }
+ try {
+ JsonNode root = objectMapper.readTree(ctx.body());
+ JsonNode target = resolvePath(root, path);
+ return objectMapper.writeValueAsString(target);
+ } catch (Exception e) {
+ return ctx.body();
+ }
+ }
+
+ /**
+ * Evaluates a simple JSON path and returns the result as an object navigable in VTL.
+ */
+ public Object path(String path) {
+ if (ctx.body() == null || ctx.body().isEmpty()) {
+ return Map.of();
+ }
+ try {
+ JsonNode root = objectMapper.readTree(ctx.body());
+ JsonNode target = resolvePath(root, path);
+ return objectMapper.convertValue(target, Object.class);
+ } catch (Exception e) {
+ return Map.of();
+ }
+ }
+
+ /** Searches all parameter types for the given name (querystring, path, header). */
+ public String params(String paramName) {
+ if (ctx.queryParams() != null && ctx.queryParams().containsKey(paramName)) {
+ return ctx.queryParams().get(paramName);
+ }
+ if (ctx.pathParams() != null && ctx.pathParams().containsKey(paramName)) {
+ return ctx.pathParams().get(paramName);
+ }
+ if (ctx.headers() != null && ctx.headers().containsKey(paramName)) {
+ return ctx.headers().get(paramName);
+ }
+ return "";
+ }
+
+ /** Returns request parameters organized by type. */
+ public Map<String, Map<String, String>> params() {
+ Map<String, Map<String, String>> params = new HashMap<>();
+ params.put("querystring", ctx.queryParams() != null ? ctx.queryParams() : Map.of());
+ params.put("path", ctx.pathParams() != null ? ctx.pathParams() : Map.of());
+ params.put("header", ctx.headers() != null ? ctx.headers() : Map.of());
+ return params;
+ }
+
+ static JsonNode resolvePath(JsonNode root, String path) {
+ if (path == null || "$".equals(path)) {
+ return root;
+ }
+ String normalized = path.startsWith("$.") ? path.substring(2) : path;
+ JsonNode current = root;
+ for (String segment : normalized.split("\\.")) {
+ if (current == null || current.isMissingNode()) break;
+ // Handle array indexing: "items[0]" or "[0]"
+ int bracketIdx = segment.indexOf('[');
+ if (bracketIdx >= 0) {
+ if (bracketIdx > 0) {
+ current = current.path(segment.substring(0, bracketIdx));
+ }
+ // Extract all indices: [0][1] etc.
+ String rest = segment.substring(bracketIdx);
+ while (rest.startsWith("[")) {
+ int close = rest.indexOf(']');
+ if (close < 0) break;
+ int index = Integer.parseInt(rest.substring(1, close));
+ current = current.path(index);
+ rest = rest.substring(close + 1);
+ }
+ } else {
+ current = current.path(segment);
+ }
+ }
+ return current;
+ }
+ }
+
+ /**
+ * The {@code $util} variable available in API Gateway VTL templates.
+ */
+ public static class UtilVariable {
+
+ private final ObjectMapper objectMapper;
+
+ public UtilVariable(ObjectMapper objectMapper) {
+ this.objectMapper = objectMapper;
+ }
+
+ /**
+ * Escapes a string using EcmaScript/JavaScript string rules.
+ * Matches AWS API Gateway behavior (Apache Commons Lang escapeEcmaScript).
+ * Escapes: backslash, double/single quotes, forward slash, control chars,
+ * and non-ASCII characters (outside 0x20-0x7E) as unicode escape sequences.
+ */
+ public String escapeJavaScript(String s) {
+ if (s == null) return "";
+ StringBuilder sb = new StringBuilder(s.length() + 16);
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ switch (c) {
+ case '\\' -> sb.append("\\\\");
+ case '"' -> sb.append("\\\"");
+ case '\'' -> sb.append("\\'");
+ case '/' -> sb.append("\\/");
+ case '\b' -> sb.append("\\b");
+ case '\t' -> sb.append("\\t");
+ case '\n' -> sb.append("\\n");
+ case '\f' -> sb.append("\\f");
+ case '\r' -> sb.append("\\r");
+ default -> {
+ if (c < 0x20 || c > 0x7E) {
+ sb.append("\\u").append(String.format("%04x", (int) c));
+ } else {
+ sb.append(c);
+ }
+ }
+ }
+ }
+ return sb.toString();
+ }
+
+ /** URL-encodes a string. */
+ public String urlEncode(String s) {
+ if (s == null) return "";
+ return URLEncoder.encode(s, StandardCharsets.UTF_8);
+ }
+
+ /** URL-decodes a string. */
+ public String urlDecode(String s) {
+ if (s == null) return "";
+ return URLDecoder.decode(s, StandardCharsets.UTF_8);
+ }
+
+ /** Base64-encodes a string. */
+ public String base64Encode(String s) {
+ if (s == null) return "";
+ return Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8));
+ }
+
+ /** Base64-decodes a string. */
+ public String base64Decode(String s) {
+ if (s == null) return "";
+ return new String(Base64.getDecoder().decode(s), StandardCharsets.UTF_8);
+ }
+
+ /** Parses a JSON string into a Map/List structure navigable in VTL. */
+ public Object parseJson(String s) {
+ if (s == null || s.isEmpty()) return Map.of();
+ try {
+ return objectMapper.readValue(s, Object.class);
+ } catch (JsonProcessingException e) {
+ return Map.of();
+ }
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Integration.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Integration.java
index 4e841907de..6a0618e04a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Integration.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Integration.java
@@ -11,6 +11,8 @@ public class Integration {
private String type; // MOCK, HTTP, AWS, HTTP_PROXY, AWS_PROXY
private String uri;
private String httpMethod;
+ private String passthroughBehavior = "WHEN_NO_MATCH"; // WHEN_NO_MATCH, WHEN_NO_TEMPLATES, NEVER
+ private Map<String, String> requestParameters = new HashMap<>(); // integration.request.* → method.request.*
private Map<String, String> requestTemplates = new HashMap<>();
private Map<String, IntegrationResponse> integrationResponses = new HashMap<>();
@@ -38,6 +40,22 @@ public class Integration {
this.httpMethod = httpMethod;
}
+ public String getPassthroughBehavior() {
+ return passthroughBehavior;
+ }
+
+ public void setPassthroughBehavior(String passthroughBehavior) {
+ this.passthroughBehavior = passthroughBehavior != null ? passthroughBehavior : "WHEN_NO_MATCH";
+ }
+
+ public Map<String, String> getRequestParameters() {
+ return requestParameters;
+ }
+
+ public void setRequestParameters(Map<String, String> requestParameters) {
+ this.requestParameters = requestParameters != null ? requestParameters : new HashMap<>();
+ }
+
public Map<String, String> getRequestTemplates() {
return requestTemplates;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java
index ca46e44e47..aecb91509c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java
@@ -11,7 +11,9 @@ public class MethodConfig {
private String httpMethod;
private String authorizationType;
private String authorizerId;
+ private String requestValidatorId;
private Map<String, Boolean> requestParameters = new HashMap<>();
+ private Map<String, String> requestModels = new HashMap<>();
private Map<String, MethodResponse> methodResponses = new HashMap<>();
private Integration methodIntegration;
@@ -24,6 +26,14 @@ public class MethodConfig {
public String getAuthorizerId() { return authorizerId; }
public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; }
+ public String getRequestValidatorId() { return requestValidatorId; }
+ public void setRequestValidatorId(String requestValidatorId) { this.requestValidatorId = requestValidatorId; }
+
+ public Map<String, String> getRequestModels() { return requestModels; }
+ public void setRequestModels(Map<String, String> requestModels) {
+ this.requestModels = requestModels != null ? requestModels : new HashMap<>();
+ }
+
public Map<String, Boolean> getRequestParameters() { return requestParameters; }
public void setRequestParameters(Map<String, Boolean> requestParameters) {
this.requestParameters = requestParameters != null ? requestParameters : new HashMap<>();
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Model.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Model.java
new file mode 100644
index 0000000000..de28a00557
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Model.java
@@ -0,0 +1,31 @@
+package io.github.hectorvent.floci.services.apigateway.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Model {
+ private String id;
+ private String name;
+ private String description;
+ private String contentType = "application/json";
+ private String schema;
+
+ public Model() {}
+
+ public String getId() { return id; }
+ public void setId(String id) { this.id = id; }
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public String getContentType() { return contentType; }
+ public void setContentType(String contentType) { this.contentType = contentType; }
+
+ public String getSchema() { return schema; }
+ public void setSchema(String schema) { this.schema = schema; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
index ef16805a10..b54581a236 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
@@ -108,7 +108,7 @@ public class AslExecutor {
}
} catch (FailStateException e) {
exec.setStatus("FAILED");
- exec.setStopDate(System.currentTimeMillis() / 1000L);
+ exec.setStopDate(System.currentTimeMillis() / 1000.0);
String failError = e.error != null ? e.error : "States.Runtime";
String failCause = e.cause != null ? e.cause : "";
exec.setError(failError);
@@ -119,7 +119,7 @@ public class AslExecutor {
return;
} catch (Exception e) {
exec.setStatus("FAILED");
- exec.setStopDate(System.currentTimeMillis() / 1000L);
+ exec.setStopDate(System.currentTimeMillis() / 1000.0);
String runtimeError = "States.Runtime";
String runtimeCause = e.getMessage() != null ? e.getMessage() : "Unknown error";
exec.setError(runtimeError);
@@ -133,7 +133,7 @@ public class AslExecutor {
exec.setStatus("SUCCEEDED");
exec.setOutput(currentInput.toString());
- exec.setStopDate(System.currentTimeMillis() / 1000L);
+ exec.setStopDate(System.currentTimeMillis() / 1000.0);
addEvent(history, eventId, "ExecutionSucceeded", null,
Map.of("output", currentInput.toString()));
onUpdate.accept(exec, history);
@@ -141,7 +141,7 @@ public class AslExecutor {
} catch (Exception e) {
LOG.warnv("ASL execution failed for {0}: {1}", exec.getExecutionArn(), e.getMessage());
exec.setStatus("FAILED");
- exec.setStopDate(System.currentTimeMillis() / 1000L);
+ exec.setStopDate(System.currentTimeMillis() / 1000.0);
onUpdate.accept(exec, history);
}
});
@@ -669,7 +669,7 @@ public class AslExecutor {
execution.put("Id", exec.getExecutionArn());
execution.put("Name", exec.getName());
execution.put("RoleArn", sm.getRoleArn());
- execution.put("StartTime", java.time.Instant.ofEpochSecond(exec.getStartDate()).toString());
+ execution.put("StartTime", java.time.Instant.ofEpochMilli((long) (exec.getStartDate() * 1000)).toString());
if (exec.getInput() != null) {
execution.set("Input", parseInput(exec.getInput()));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java
index f10201e4ae..a6aafbf830 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java
@@ -144,7 +144,7 @@ public class StepFunctionsJsonHandler {
request.path("error").asText(null)
);
ObjectNode response = objectMapper.createObjectNode();
- response.put("stopDate", System.currentTimeMillis() / 1000L);
+ response.put("stopDate", System.currentTimeMillis() / 1000.0);
return Response.ok(response).build();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
index be7dca1f42..0fdad0febc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
@@ -138,7 +138,7 @@ public class StepFunctionsService {
return;
}
exec.setStatus("ABORTED");
- exec.setStopDate(System.currentTimeMillis() / 1000L);
+ exec.setStopDate(System.currentTimeMillis() / 1000.0);
executionStore.put(arn, exec);
List<HistoryEvent> history = historyCache.getOrDefault(arn, new ArrayList<>());
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/Execution.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/Execution.java
index 067d40b0b2..5ae0b6c722 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/Execution.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/Execution.java
@@ -12,13 +12,13 @@ public class Execution {
private String status = "RUNNING"; // RUNNING, SUCCEEDED, FAILED, TIMED_OUT, ABORTED
private String input;
private String output;
- private long startDate;
- private Long stopDate;
+ private double startDate;
+ private Double stopDate;
private String error;
private String cause;
public Execution() {
- this.startDate = System.currentTimeMillis() / 1000L;
+ this.startDate = System.currentTimeMillis() / 1000.0;
}
public String getExecutionArn() { return executionArn; }
@@ -39,11 +39,11 @@ public class Execution {
public String getOutput() { return output; }
public void setOutput(String output) { this.output = output; }
- public long getStartDate() { return startDate; }
- public void setStartDate(long startDate) { this.startDate = startDate; }
+ public double getStartDate() { return startDate; }
+ public void setStartDate(double startDate) { this.startDate = startDate; }
- public Long getStopDate() { return stopDate; }
- public void setStopDate(Long stopDate) { this.stopDate = stopDate; }
+ public Double getStopDate() { return stopDate; }
+ public void setStopDate(Double stopDate) { this.stopDate = stopDate; }
public String getError() { return error; }
public void setError(String error) { this.error = error; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/HistoryEvent.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/HistoryEvent.java
index 4fc61b3d51..12a503d441 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/HistoryEvent.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/HistoryEvent.java
@@ -9,20 +9,20 @@ import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class HistoryEvent {
private long id;
- private long timestamp;
+ private double timestamp;
private String type;
private Long previousEventId;
private Map<String, Object> details;
public HistoryEvent() {
- this.timestamp = System.currentTimeMillis() / 1000L;
+ this.timestamp = System.currentTimeMillis() / 1000.0;
}
public long getId() { return id; }
public void setId(long id) { this.id = id; }
- public long getTimestamp() { return timestamp; }
- public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
+ public double getTimestamp() { return timestamp; }
+ public void setTimestamp(double timestamp) { this.timestamp = timestamp; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/StateMachine.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/StateMachine.java
index 179e9956b3..e3c85fe5f6 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/StateMachine.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/StateMachine.java
@@ -12,10 +12,10 @@ public class StateMachine {
private String roleArn;
private String type = "STANDARD";
private String status = "ACTIVE";
- private long creationDate;
+ private double creationDate;
public StateMachine() {
- this.creationDate = System.currentTimeMillis() / 1000L;
+ this.creationDate = System.currentTimeMillis() / 1000.0;
}
public String getStateMachineArn() { return stateMachineArn; }
@@ -36,6 +36,6 @@ public class StateMachine {
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
- public long getCreationDate() { return creationDate; }
- public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
+ public double getCreationDate() { return creationDate; }
+ public void setCreationDate(double creationDate) { this.creationDate = creationDate; }
}
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
new file mode 100644
index 0000000000..ecfebe8f5a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsIntegrationTest.java
@@ -0,0 +1,1258 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.RestAssured;
+import io.restassured.config.EncoderConfig;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.*;
+
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Integration tests for API Gateway AWS (non-proxy) integration type.
+ * Tests the full flow: API Gateway → Step Functions → DynamoDB,
+ * and API Gateway → DynamoDB directly.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewayAwsIntegrationTest {
+
+ private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
+ private static final String DDB_CONTENT_TYPE = "application/x-amz-json-1.0";
+ private static final ObjectMapper mapper = new ObjectMapper();
+
+ private static String apiId;
+ private static String rootId;
+ private static String startResourceId;
+ private static String ddbResourceId;
+ private static String deploymentId;
+ private static String stateMachineArn;
+
+ private static final String TABLE_NAME = "apigw-sfn-test";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssured.config = RestAssured.config().encoderConfig(
+ EncoderConfig.encoderConfig()
+ .encodeContentTypeAs(SFN_CONTENT_TYPE, ContentType.TEXT));
+ }
+
+ // ──────────────── Setup: DynamoDB table + SFN state machine ────────────────
+
+ @Test @Order(0)
+ void setup_createDynamoDbTable() {
+ given()
+ .header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
+ "BillingMode": "PAY_PER_REQUEST"
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ @Test @Order(1)
+ void setup_createStateMachine() throws Exception {
+ // Simple Pass state machine — just echoes input back as output.
+ // This tests the APIGW → SFN integration without depending on SFN DDB support.
+ String definition = mapper.writeValueAsString(mapper.readTree("""
+ {
+ "StartAt": "Echo",
+ "States": {
+ "Echo": {
+ "Type": "Pass",
+ "End": true
+ }
+ }
+ }
+ """));
+
+ String body = """
+ {
+ "name": "apigw-test-sm",
+ "definition": %s,
+ "roleArn": "arn:aws:iam::000000000000:role/test-role"
+ }
+ """.formatted(mapper.writeValueAsString(definition));
+
+ String response = given()
+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
+ .contentType(SFN_CONTENT_TYPE)
+ .body(body)
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().asString();
+
+ stateMachineArn = mapper.readTree(response).path("stateMachineArn").asText();
+ assertNotNull(stateMachineArn);
+ assertFalse(stateMachineArn.isEmpty());
+ }
+
+ // ──────────────── Setup: API Gateway REST API ────────────────
+
+ @Test @Order(2)
+ void setup_createRestApi() {
+ apiId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"name":"aws-integration-test","description":"Test AWS integration type"}
+ """)
+ .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);
+ }
+
+ @Test @Order(4)
+ void setup_createStartResource() {
+ startResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"start\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+ }
+
+ @Test @Order(5)
+ void setup_configureStartMethod() throws Exception {
+ // PUT method
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + startResourceId + "/methods/POST")
+ .then().statusCode(201);
+
+ // PUT integration — AWS type targeting SFN StartExecution
+ // Build the integration body programmatically to avoid escaping hell.
+ // The VTL template wraps the input with DynamoDB typed attributes.
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", "arn:aws:apigateway:us-east-1:states:action/StartExecution");
+ var reqTemplates = mapper.createObjectNode();
+ // VTL template that builds the SFN StartExecution request.
+ // Passes the incoming body as the SFN execution input.
+ String vtl = "{\"stateMachineArn\": \"" + stateMachineArn + "\", "
+ + "\"input\": \"$util.escapeJavaScript($input.json('$'))\"}";
+ reqTemplates.put("application/json", vtl);
+ integrationNode.set("requestTemplates", reqTemplates);
+ String integrationBody = mapper.writeValueAsString(integrationNode);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(integrationBody)
+ .when().put("/restapis/" + apiId + "/resources/" + startResourceId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ // PUT integration response (200 default)
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + startResourceId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+ }
+
+ @Test @Order(6)
+ void setup_createDdbResource() {
+ ddbResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"items\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+ }
+
+ @Test @Order(7)
+ void setup_configureDdbMethod() {
+ // PUT method
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + ddbResourceId + "/methods/POST")
+ .then().statusCode(201);
+
+ // PUT integration — AWS type targeting DynamoDB PutItem directly
+ String integrationBody = """
+ {
+ "type": "AWS",
+ "httpMethod": "POST",
+ "uri": "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem",
+ "requestTemplates": {
+ "application/json": "{\\"TableName\\": \\"%s\\", \\"Item\\": {\\"id\\": {\\"S\\": \\"$input.path('$.id')\\"},\\"message\\": {\\"S\\": \\"$input.path('$.message')\\"}}}"
+ }
+ }
+ """.formatted(TABLE_NAME);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(integrationBody)
+ .when().put("/restapis/" + apiId + "/resources/" + ddbResourceId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ // PUT integration response (200 default)
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + ddbResourceId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+ }
+
+ @Test @Order(8)
+ void setup_deployAndCreateStage() {
+ 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 → SFN → DynamoDB ────────────────
+
+ @Test @Order(10)
+ void awsIntegration_sfnStartExecution() throws Exception {
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("{\"id\": \"apigw-sfn-1\", \"message\": \"hello from api gateway\"}")
+ .when().post("/execute-api/" + apiId + "/test/start")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(response);
+ assertTrue(result.has("executionArn"), "Response should have executionArn");
+ assertTrue(result.has("startDate"), "Response should have startDate");
+ String executionArn = result.path("executionArn").asText();
+ assertTrue(executionArn.contains("apigw-test-sm"), "Execution ARN should reference state machine");
+ }
+
+ @Test @Order(11)
+ void awsIntegration_sfnExecution_canDescribe() throws Exception {
+ // Wait briefly for async execution to complete
+ Thread.sleep(500);
+
+ // Verify the execution completed successfully via DescribeExecution
+ // (We use the executionArn from the previous test's StartExecution response)
+ String listResponse = given()
+ .header("X-Amz-Target", "AWSStepFunctions.ListExecutions")
+ .contentType(SFN_CONTENT_TYPE)
+ .body("{\"stateMachineArn\": \"" + stateMachineArn + "\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode executions = mapper.readTree(listResponse).path("executions");
+ assertTrue(executions.isArray() && executions.size() > 0, "Should have at least one execution");
+ assertEquals("SUCCEEDED", executions.get(0).path("status").asText());
+ }
+
+ // ──────────────── Test: APIGW → DynamoDB directly ────────────────
+
+ @Test @Order(12)
+ void awsIntegration_dynamoDbPutItem() throws Exception {
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("{\"id\": \"apigw-ddb-1\", \"message\": \"direct dynamodb write\"}")
+ .when().post("/execute-api/" + apiId + "/test/items")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ // PutItem returns empty object
+ JsonNode result = mapper.readTree(response);
+ assertNotNull(result);
+ }
+
+ @Test @Order(13)
+ void awsIntegration_dynamoDbPutItem_verifyInDb() throws Exception {
+ String response = given()
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "Key": {"id": {"S": "apigw-ddb-1"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(response);
+ assertTrue(result.has("Item"));
+ assertEquals("apigw-ddb-1", result.path("Item").path("id").path("S").asText());
+ assertEquals("direct dynamodb write", result.path("Item").path("message").path("S").asText());
+ }
+
+ // ──────────────── Test: Passthrough (no request template) ────────────────
+
+ @Test @Order(14)
+ void awsIntegration_passthrough_noRequestTemplate() throws Exception {
+ // Create a new resource with AWS integration but no request template
+ String ptResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"passthrough\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + ptResourceId + "/methods/POST")
+ .then().statusCode(201);
+
+ // No requestTemplates — body passes through as-is
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "type": "AWS",
+ "httpMethod": "POST",
+ "uri": "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem"
+ }
+ """)
+ .when().put("/restapis/" + apiId + "/resources/" + ptResourceId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + ptResourceId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+
+ // Redeploy
+ String newDeploymentId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"description\":\"v2\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201)
+ .extract().path("id");
+
+ // Update stage to new deployment
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/deploymentId\",\"value\":\"" + newDeploymentId + "\"}]}")
+ .when().patch("/restapis/" + apiId + "/stages/test")
+ .then().statusCode(200);
+
+ // Call with DynamoDB PutItem payload directly (passthrough)
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "TableName": "%s",
+ "Item": {
+ "id": {"S": "passthrough-1"},
+ "message": {"S": "passthrough write"}
+ }
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/execute-api/" + apiId + "/test/passthrough")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ // Verify in DynamoDB
+ String getResponse = given()
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "Key": {"id": {"S": "passthrough-1"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(getResponse);
+ assertTrue(result.has("Item"));
+ assertEquals("passthrough-1", result.path("Item").path("id").path("S").asText());
+ }
+
+ // ──────────────── Test: VTL $context and $util ────────────────
+
+ @Test @Order(15)
+ void awsIntegration_vtlContextVariables() throws Exception {
+ // Create a resource that uses $context variables in the template
+ String ctxResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"context-test\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + ctxResourceId + "/methods/POST")
+ .then().statusCode(201);
+
+ // Template that uses $context.stage and $context.httpMethod
+ String integrationBody = """
+ {
+ "type": "AWS",
+ "httpMethod": "POST",
+ "uri": "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem",
+ "requestTemplates": {
+ "application/json": "{\\"TableName\\": \\"%s\\", \\"Item\\": {\\"id\\": {\\"S\\": \\"ctx-$context.stage\\"},\\"method\\": {\\"S\\": \\"$context.httpMethod\\"}}}"
+ }
+ }
+ """.formatted(TABLE_NAME);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(integrationBody)
+ .when().put("/restapis/" + apiId + "/resources/" + ctxResourceId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + ctxResourceId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+
+ // Redeploy
+ String dep = given()
+ .contentType(ContentType.JSON)
+ .body("{\"description\":\"v3\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/deploymentId\",\"value\":\"" + dep + "\"}]}")
+ .when().patch("/restapis/" + apiId + "/stages/test")
+ .then().statusCode(200);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .when().post("/execute-api/" + apiId + "/test/context-test")
+ .then()
+ .statusCode(200);
+
+ // Verify the item was written with context values
+ String getResponse = given()
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "Key": {"id": {"S": "ctx-test"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(getResponse);
+ assertTrue(result.has("Item"), "Item should exist with context-derived key");
+ assertEquals("ctx-test", result.path("Item").path("id").path("S").asText());
+ assertEquals("POST", result.path("Item").path("method").path("S").asText());
+ }
+
+ // ──────────────── Test: Error path with selectionPattern ────────────────
+
+ @Test @Order(20)
+ void awsIntegration_errorPath_tableNotFound() throws Exception {
+ // Call DynamoDB PutItem against a non-existent table.
+ // Configure integration with a 400 error response using selectionPattern.
+ String errResourceId = createResourceWithAwsIntegration("error-test",
+ "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem",
+ null, // no request template — passthrough
+ Map.of(
+ "200", new IntegrationResponseConfig("", ""),
+ "400", new IntegrationResponseConfig(".*ResourceNotFoundException.*", "")
+ ));
+
+ redeploy();
+
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "TableName": "nonexistent-table",
+ "Item": {"id": {"S": "x"}}
+ }
+ """)
+ .when().post("/execute-api/" + apiId + "/test/error-test")
+ .then()
+ .statusCode(400)
+ .extract().asString();
+
+ // Error response should contain the error info
+ JsonNode result = mapper.readTree(response);
+ assertTrue(response.contains("ResourceNotFoundException")
+ || response.contains("nonexistent-table"),
+ "Error response should mention the error: " + response);
+ }
+
+ @Test @Order(21)
+ void awsIntegration_errorPath_defaultResponse() throws Exception {
+ // Call DynamoDB with bad request — no selectionPattern match, falls back to default (200)
+ String defResourceId = createResourceWithAwsIntegration("error-default",
+ "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem",
+ null,
+ Map.of("200", new IntegrationResponseConfig("", "")));
+
+ redeploy();
+
+ // Missing required fields → service error, but default 200 response catches it
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "TableName": "nonexistent-table-2",
+ "Item": {"id": {"S": "x"}}
+ }
+ """)
+ .when().post("/execute-api/" + apiId + "/test/error-default")
+ .then()
+ .extract().asString();
+
+ // Default response should still return something (error info in body)
+ assertNotNull(response);
+ assertFalse(response.isEmpty());
+ }
+
+ // ──────────────── Test: Response mapping template ────────────────
+
+ @Test @Order(30)
+ void awsIntegration_responseMappingTemplate() throws Exception {
+ // Create a DynamoDB GetItem integration with a response template
+ // that transforms the DynamoDB response into a simpler format.
+
+ // First, put an item to read
+ given()
+ .header("X-Amz-Target", "DynamoDB_20120810.PutItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "Item": {"id": {"S": "resp-map-1"}, "message": {"S": "mapped response"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // Response template extracts from the DynamoDB JSON response
+ String responseTemplate = "#set($root = $util.parseJson($input.body()))\n"
+ + "{\"id\": \"$root.Item.id.S\", \"message\": \"$root.Item.message.S\"}";
+
+ String resId = createResourceWithAwsIntegration("response-map",
+ "arn:aws:apigateway:us-east-1:dynamodb:action/GetItem",
+ null, // passthrough request
+ Map.of("200", new IntegrationResponseConfig("", responseTemplate)));
+
+ redeploy();
+
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "TableName": "%s",
+ "Key": {"id": {"S": "resp-map-1"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/execute-api/" + apiId + "/test/response-map")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(response);
+ assertEquals("resp-map-1", result.path("id").asText());
+ assertEquals("mapped response", result.path("message").asText());
+ }
+
+ @Test @Order(31)
+ void awsIntegration_responseMappingTemplate_listTables() throws Exception {
+ // Use ListTables (returns {"TableNames": [...]}) and transform with response template
+ String responseTemplate = "#set($root = $util.parseJson($input.body()))\n"
+ + "{\"count\": $root.TableNames.size(), \"tables\": $input.body()}";
+
+ createResourceWithAwsIntegration("list-tables",
+ "arn:aws:apigateway:us-east-1:dynamodb:action/ListTables",
+ "{}", // static request template
+ Map.of("200", new IntegrationResponseConfig("", responseTemplate)));
+
+ redeploy();
+
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .when().post("/execute-api/" + apiId + "/test/list-tables")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(response);
+ assertTrue(result.has("count"), "Response should have count field: " + response);
+ assertTrue(result.path("count").asInt() > 0, "Should have at least one table");
+ }
+
+ // ──────────────── Test: Response $input.json() in response template ────────────────
+
+ @Test @Order(32)
+ void awsIntegration_responseMappingTemplate_inputJson() throws Exception {
+ // Verify $input.json('$.path') works in response mapping templates
+ // (where $input refers to the service response, not the original request)
+ given()
+ .header("X-Amz-Target", "DynamoDB_20120810.PutItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "Item": {"id": {"S": "resp-json-1"}, "message": {"S": "json path test"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // Response template uses $input.json() to extract from DynamoDB response
+ String responseTemplate = "{\"itemId\": $input.json('$.Item.id.S'), \"msg\": $input.json('$.Item.message.S')}";
+
+ createResourceWithAwsIntegration("resp-json",
+ "arn:aws:apigateway:us-east-1:dynamodb:action/GetItem",
+ null,
+ Map.of("200", new IntegrationResponseConfig("", responseTemplate)));
+
+ redeploy();
+
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "TableName": "%s",
+ "Key": {"id": {"S": "resp-json-1"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/execute-api/" + apiId + "/test/resp-json")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(response);
+ assertEquals("resp-json-1", result.path("itemId").asText());
+ assertEquals("json path test", result.path("msg").asText());
+ }
+
+ // ──────────────── Test: SFN startDate format ────────────────
+
+ @Test @Order(33)
+ void awsIntegration_sfnStartDate_isEpochFloat() throws Exception {
+ // Verify startDate is returned as a float (epoch seconds with millis), not an integer
+ String response = given()
+ .contentType(ContentType.JSON)
+ .body("{\"id\": \"date-test-1\", \"message\": \"date format test\"}")
+ .when().post("/execute-api/" + apiId + "/test/start")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(response);
+ assertTrue(result.has("startDate"), "Response should have startDate");
+
+ // startDate should be a number (not a string)
+ assertTrue(result.path("startDate").isNumber(), "startDate should be a number");
+
+ // Verify it's a float with decimal places (e.g., 1774722483.047), not an integer
+ double startDate = result.path("startDate").asDouble();
+ assertTrue(startDate > 1000000000.0, "startDate should be a reasonable epoch timestamp");
+
+ // The raw JSON should contain a decimal point
+ assertTrue(response.contains("."), "startDate should be serialized as a float with decimal: " + response);
+ }
+
+ // ──────────────── Test: Response parameter mapping (headers) ────────────────
+
+ @Test @Order(40)
+ void awsIntegration_responseParameterMapping_staticValue() throws Exception {
+ // responseParameters with static value: 'value'
+ String resId = createResourceWithAwsIntegrationAndResponseParams("header-static",
+ "arn:aws:apigateway:us-east-1:dynamodb:action/ListTables",
+ "{}",
+ Map.of("200", new IntegrationResponseConfig("", "")),
+ Map.of("200", Map.of(
+ "method.response.header.Access-Control-Allow-Origin", "'*'",
+ "method.response.header.X-Custom", "'hello-world'"
+ )));
+
+ redeploy();
+
+ var response = given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .when().post("/execute-api/" + apiId + "/test/header-static")
+ .then()
+ .statusCode(200)
+ .extract().response();
+
+ assertEquals("*", response.header("Access-Control-Allow-Origin"));
+ assertEquals("hello-world", response.header("X-Custom"));
+ }
+
+ @Test @Order(41)
+ void awsIntegration_responseParameterMapping_bodyField() throws Exception {
+ // Put an item to read back
+ given()
+ .header("X-Amz-Target", "DynamoDB_20120810.PutItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "Item": {"id": {"S": "header-body-1"}, "message": {"S": "for header test"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // Map a response body field to a header
+ createResourceWithAwsIntegrationAndResponseParams("header-body",
+ "arn:aws:apigateway:us-east-1:dynamodb:action/GetItem",
+ null,
+ Map.of("200", new IntegrationResponseConfig("", "")),
+ Map.of("200", Map.of(
+ "method.response.header.X-Item-Id", "integration.response.body.Item"
+ )));
+
+ redeploy();
+
+ var response = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "TableName": "%s",
+ "Key": {"id": {"S": "header-body-1"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/execute-api/" + apiId + "/test/header-body")
+ .then()
+ .statusCode(200)
+ .extract().response();
+
+ // The header should contain something from the Item field
+ assertNotNull(response.header("X-Item-Id"), "Should have X-Item-Id header");
+ }
+
+ // ──────────────── Test: Content-Type negotiation ────────────────
+
+ @Test @Order(50)
+ void awsIntegration_contentTypeNegotiation_matchesTemplate() throws Exception {
+ // Create integration with templates for both application/json and application/xml
+ String resId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"ct-negotiate\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST")
+ .then().statusCode(201);
+
+ // Two templates: application/json writes "json-item", application/xml writes "xml-item"
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem");
+ var rt = mapper.createObjectNode();
+ rt.put("application/json",
+ "{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"ct-json\"}, \"source\": {\"S\": \"json-template\"}}}");
+ rt.put("application/xml",
+ "{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"ct-xml\"}, \"source\": {\"S\": \"xml-template\"}}}");
+ integrationNode.set("requestTemplates", rt);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(integrationNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+
+ redeploy();
+
+ // Send with application/json → should use json template
+ given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .when().post("/execute-api/" + apiId + "/test/ct-negotiate")
+ .then().statusCode(200);
+
+ // Verify json template was used
+ String getResp = given()
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("{\"TableName\": \"" + TABLE_NAME + "\", \"Key\": {\"id\": {\"S\": \"ct-json\"}}}")
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(getResp);
+ assertTrue(result.has("Item"), "JSON template should have been selected");
+ assertEquals("json-template", result.path("Item").path("source").path("S").asText());
+ }
+
+ // ──────────────── Test: passthroughBehavior ────────────────
+
+ @Test @Order(51)
+ void awsIntegration_passthroughBehavior_never_rejects() throws Exception {
+ // passthroughBehavior=NEVER with no templates → 415
+ String resId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"pt-never\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST")
+ .then().statusCode(201);
+
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/ListTables");
+ integrationNode.put("passthroughBehavior", "NEVER");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(integrationNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+
+ redeploy();
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .when().post("/execute-api/" + apiId + "/test/pt-never")
+ .then().statusCode(415);
+ }
+
+ @Test @Order(52)
+ void awsIntegration_passthroughBehavior_whenNoTemplates_noMatchRejects() throws Exception {
+ // passthroughBehavior=WHEN_NO_TEMPLATES with templates for text/plain → application/json should be rejected
+ String resId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"pt-nomatch\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST")
+ .then().statusCode(201);
+
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/ListTables");
+ integrationNode.put("passthroughBehavior", "WHEN_NO_TEMPLATES");
+ var rt = mapper.createObjectNode();
+ rt.put("text/plain", "{}");
+ integrationNode.set("requestTemplates", rt);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(integrationNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+
+ redeploy();
+
+ // Send application/json but only text/plain template exists → 415
+ given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .when().post("/execute-api/" + apiId + "/test/pt-nomatch")
+ .then().statusCode(415);
+ }
+
+ @Test @Order(53)
+ void awsIntegration_passthroughBehavior_whenNoMatch_passesThrough() throws Exception {
+ // passthroughBehavior=WHEN_NO_MATCH (default) with template for text/plain only
+ // → application/json should passthrough
+ String resId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"pt-default\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST")
+ .then().statusCode(201);
+
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/ListTables");
+ integrationNode.put("passthroughBehavior", "WHEN_NO_MATCH");
+ var rt = mapper.createObjectNode();
+ rt.put("text/plain", "{\"bad\":true}");
+ integrationNode.set("requestTemplates", rt);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(integrationNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+
+ redeploy();
+
+ // Send application/json → no match, but WHEN_NO_MATCH means passthrough
+ // Body is empty JSON {} which is valid for ListTables
+ given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .when().post("/execute-api/" + apiId + "/test/pt-default")
+ .then().statusCode(200);
+ }
+
+ // ──────────────── Test: Request parameter mapping ────────────────
+
+ @Test @Order(60)
+ void awsIntegration_requestParameterMapping() throws Exception {
+ // Map a query string param to be used in the VTL template via $input.params()
+ String resId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"req-param\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST")
+ .then().statusCode(201);
+
+ // Map method.request.querystring.itemId → integration.request.querystring.itemId
+ // and use it in the template
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem");
+ var reqParams = mapper.createObjectNode();
+ reqParams.put("integration.request.querystring.itemId", "method.request.querystring.itemId");
+ integrationNode.set("requestParameters", reqParams);
+ var rt = mapper.createObjectNode();
+ rt.put("application/json",
+ "{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"$input.params('itemId')\"}, \"source\": {\"S\": \"req-param-mapped\"}}}");
+ integrationNode.set("requestTemplates", rt);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(integrationNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + resId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+
+ redeploy();
+
+ // Call with query param
+ given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .queryParam("itemId", "param-123")
+ .when().post("/execute-api/" + apiId + "/test/req-param")
+ .then().statusCode(200);
+
+ // Verify the item was written with the query param value
+ String getResp = given()
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("{\"TableName\": \"" + TABLE_NAME + "\", \"Key\": {\"id\": {\"S\": \"param-123\"}}}")
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().asString();
+
+ JsonNode result = mapper.readTree(getResp);
+ assertTrue(result.has("Item"), "Item should exist with param-mapped key");
+ assertEquals("param-123", result.path("Item").path("id").path("S").asText());
+ assertEquals("req-param-mapped", result.path("Item").path("source").path("S").asText());
+ }
+
+ // ──────────────── Test: Response body JSONPath (deep) ────────────────
+
+ @Test @Order(61)
+ void awsIntegration_responseBodyJsonPath_deep() throws Exception {
+ // Put a nested item to read back
+ given()
+ .header("X-Amz-Target", "DynamoDB_20120810.PutItem")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("""
+ {
+ "TableName": "%s",
+ "Item": {"id": {"S": "deep-path-1"}, "message": {"S": "deep value"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // Map a deep JSON path from response body to a header
+ createResourceWithAwsIntegrationAndResponseParams("deep-path",
+ "arn:aws:apigateway:us-east-1:dynamodb:action/GetItem",
+ null,
+ Map.of("200", new IntegrationResponseConfig("", "")),
+ Map.of("200", Map.of(
+ "method.response.header.X-Item-Message", "integration.response.body.Item.message.S"
+ )));
+
+ redeploy();
+
+ var response = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {
+ "TableName": "%s",
+ "Key": {"id": {"S": "deep-path-1"}}
+ }
+ """.formatted(TABLE_NAME))
+ .when().post("/execute-api/" + apiId + "/test/deep-path")
+ .then()
+ .statusCode(200)
+ .extract().response();
+
+ assertEquals("deep value", response.header("X-Item-Message"));
+ }
+
+ // ──────────────── Helpers ────────────────
+
+ private record IntegrationResponseConfig(String selectionPattern, String responseTemplate) {}
+
+ private String createResourceWithAwsIntegrationAndResponseParams(
+ String pathPart, String uri, String requestTemplate,
+ Map<String, IntegrationResponseConfig> responses,
+ Map<String, Map<String, String>> responseParams) throws Exception {
+ String resourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"" + pathPart + "\"}")
+ .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);
+
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", uri);
+ if (requestTemplate != null) {
+ var rt = mapper.createObjectNode();
+ rt.put("application/json", requestTemplate);
+ integrationNode.set("requestTemplates", rt);
+ }
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(integrationNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ for (var entry : responses.entrySet()) {
+ var irNode = mapper.createObjectNode();
+ irNode.put("selectionPattern", entry.getValue().selectionPattern());
+ var respTemplates = mapper.createObjectNode();
+ respTemplates.put("application/json", entry.getValue().responseTemplate());
+ irNode.set("responseTemplates", respTemplates);
+
+ // Add response parameters if provided
+ Map<String, String> params = responseParams != null ? responseParams.get(entry.getKey()) : null;
+ if (params != null && !params.isEmpty()) {
+ var paramsNode = mapper.createObjectNode();
+ params.forEach(paramsNode::put);
+ irNode.set("responseParameters", paramsNode);
+ }
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(irNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId
+ + "/methods/POST/integration/responses/" + entry.getKey())
+ .then().statusCode(201);
+ }
+
+ return resourceId;
+ }
+
+ private String createResourceWithAwsIntegration(String pathPart, String uri,
+ String requestTemplate,
+ Map<String, IntegrationResponseConfig> responses) throws Exception {
+ String resourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"" + pathPart + "\"}")
+ .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);
+
+ var integrationNode = mapper.createObjectNode();
+ integrationNode.put("type", "AWS");
+ integrationNode.put("httpMethod", "POST");
+ integrationNode.put("uri", uri);
+ if (requestTemplate != null) {
+ var rt = mapper.createObjectNode();
+ rt.put("application/json", requestTemplate);
+ integrationNode.set("requestTemplates", rt);
+ }
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(integrationNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ for (var entry : responses.entrySet()) {
+ var irNode = mapper.createObjectNode();
+ irNode.put("selectionPattern", entry.getValue().selectionPattern());
+ var respTemplates = mapper.createObjectNode();
+ respTemplates.put("application/json", entry.getValue().responseTemplate());
+ irNode.set("responseTemplates", respTemplates);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body(mapper.writeValueAsString(irNode))
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId
+ + "/methods/POST/integration/responses/" + entry.getKey())
+ .then().statusCode(201);
+ }
+
+ return resourceId;
+ }
+
+ private void redeploy() {
+ String dep = given()
+ .contentType(ContentType.JSON)
+ .body("{\"description\":\"redeploy\"}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201)
+ .extract().path("id");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/deploymentId\",\"value\":\"" + dep + "\"}]}")
+ .when().patch("/restapis/" + apiId + "/stages/test")
+ .then().statusCode(200);
+ }
+
+ // ──────────────── Cleanup ────────────────
+
+ @Test @Order(99)
+ void cleanup() {
+ // Delete stage
+ given().when().delete("/restapis/" + apiId + "/stages/test").then().statusCode(anyOf(200, 202, 204));
+
+ // Delete REST API
+ given().when().delete("/restapis/" + apiId).then().statusCode(anyOf(200, 202, 204));
+
+ // Delete table
+ given()
+ .header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")
+ .contentType(DDB_CONTENT_TYPE)
+ .body("{\"TableName\": \"" + TABLE_NAME + "\"}")
+ .when().post("/")
+ .then().statusCode(200);
+
+ // Delete state machine
+ if (stateMachineArn != null) {
+ given()
+ .header("X-Amz-Target", "AWSStepFunctions.DeleteStateMachine")
+ .contentType(SFN_CONTENT_TYPE)
+ .body("{\"stateMachineArn\": \"" + stateMachineArn + "\"}")
+ .when().post("/")
+ .then().statusCode(200);
+ }
+ }
+
+ private static org.hamcrest.Matcher<Integer> anyOf(int... values) {
+ org.hamcrest.Matcher<Integer>[] matchers = new org.hamcrest.Matcher[values.length];
+ for (int i = 0; i < values.length; i++) {
+ matchers[i] = org.hamcrest.Matchers.equalTo(values[i]);
+ }
+ return org.hamcrest.Matchers.anyOf(matchers);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiImportTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiImportTest.java
new file mode 100644
index 0000000000..02c356eea3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiImportTest.java
@@ -0,0 +1,1303 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.*;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Integration tests for API Gateway OpenAPI/Swagger import.
+ * Tests ImportRestApi (POST /restapis?mode=import) and PutRestApi (PUT /restapis/{apiId}?mode=overwrite).
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewayOpenApiImportTest {
+
+ private static final ObjectMapper mapper = new ObjectMapper();
+ private static String importedApiId;
+ private static String overwriteApiId;
+
+ // ──────────────────────────── Import Basic ────────────────────────────
+
+ @Test
+ @Order(1)
+ void importRestApi_basicMock() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": {
+ "title": "MockAPI",
+ "description": "A simple mock API",
+ "version": "1.0"
+ },
+ "paths": {
+ "/health": {
+ "get": {
+ "x-amazon-apigateway-integration": {
+ "type": "MOCK",
+ "requestTemplates": {
+ "application/json": "{\\"statusCode\\": 200}"
+ },
+ "responses": {
+ "default": {
+ "statusCode": "200",
+ "responseTemplates": {
+ "application/json": "{\\"status\\": \\"ok\\"}"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .body("name", equalTo("MockAPI"))
+ .body("description", equalTo("A simple mock API"))
+ .body("id", notNullValue())
+ .extract().body().asString();
+
+ JsonNode node = mapper.readTree(body);
+ importedApiId = node.get("id").asText();
+ }
+
+ @Test
+ @Order(2)
+ void importRestApi_resourcesCreated() {
+ // Should have root "/" and "/health"
+ String body = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + importedApiId + "/resources")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(2))
+ .extract().body().asString();
+ }
+
+ @Test
+ @Order(3)
+ void importRestApi_methodAndIntegrationCreated() throws Exception {
+ // Find the /health resource
+ String body = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + importedApiId + "/resources")
+ .then()
+ .statusCode(200)
+ .extract().body().asString();
+
+ JsonNode resources = mapper.readTree(body).get("item");
+ String healthResourceId = null;
+ for (JsonNode r : resources) {
+ if ("/health".equals(r.get("path").asText())) {
+ healthResourceId = r.get("id").asText();
+ }
+ }
+ assertNotNull(healthResourceId, "Should have /health resource");
+
+ // Verify the GET method has MOCK integration
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + importedApiId + "/resources/" + healthResourceId + "/methods/GET/integration")
+ .then()
+ .statusCode(200)
+ .body("type", equalTo("MOCK"));
+ }
+
+ // ──────────────────────────── Import Nested Paths ────────────────────────────
+
+ @Test
+ @Order(10)
+ void importRestApi_nestedPaths() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "NestedAPI", "version": "1.0" },
+ "paths": {
+ "/orders": {
+ "get": {
+ "x-amazon-apigateway-integration": { "type": "MOCK" }
+ }
+ },
+ "/orders/{orderId}": {
+ "get": {
+ "x-amazon-apigateway-integration": { "type": "MOCK" }
+ }
+ },
+ "/orders/{orderId}/items": {
+ "get": {
+ "x-amazon-apigateway-integration": { "type": "MOCK" }
+ },
+ "post": {
+ "x-amazon-apigateway-integration": { "type": "MOCK" }
+ }
+ }
+ }
+ }
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .body("name", equalTo("NestedAPI"))
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ // Should have: /, /orders, /orders/{orderId}, /orders/{orderId}/items
+ String resourcesBody = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(4))
+ .extract().body().asString();
+
+ JsonNode items = mapper.readTree(resourcesBody).get("item");
+ boolean hasRoot = false, hasOrders = false, hasOrderId = false, hasItems = false;
+ for (JsonNode r : items) {
+ String path = r.get("path").asText();
+ switch (path) {
+ case "/" -> hasRoot = true;
+ case "/orders" -> hasOrders = true;
+ case "/orders/{orderId}" -> hasOrderId = true;
+ case "/orders/{orderId}/items" -> hasItems = true;
+ }
+ }
+ assertTrue(hasRoot && hasOrders && hasOrderId && hasItems,
+ "Should have all nested resources");
+
+ // Cleanup
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Import with AWS Integration ────────────────────────────
+
+ @Test
+ @Order(20)
+ void importRestApi_awsIntegrationWithTemplates() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "SfnAPI", "version": "1.0" },
+ "paths": {
+ "/start": {
+ "post": {
+ "x-amazon-apigateway-integration": {
+ "type": "AWS",
+ "httpMethod": "POST",
+ "uri": "arn:aws:apigateway:us-east-1:states:action/StartExecution",
+ "passthroughBehavior": "NEVER",
+ "requestTemplates": {
+ "application/json": "#set($body = $input.json('$'))\\n{\\"input\\": \\"$util.escapeJavaScript($body)\\", \\"stateMachineArn\\": \\"arn:aws:states:us-east-1:000000000000:stateMachine:test\\"}"
+ },
+ "requestParameters": {
+ "integration.request.header.X-Custom": "'static-value'"
+ },
+ "responses": {
+ "default": {
+ "statusCode": "200",
+ "responseTemplates": {
+ "application/json": "$input.json('$')"
+ }
+ },
+ "4\\\\d{2}": {
+ "statusCode": "400"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ // Find /start resource
+ String resourcesBody = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources")
+ .then()
+ .statusCode(200)
+ .extract().body().asString();
+
+ String startResourceId = null;
+ for (JsonNode r : mapper.readTree(resourcesBody).get("item")) {
+ if ("/start".equals(r.get("path").asText())) {
+ startResourceId = r.get("id").asText();
+ }
+ }
+ assertNotNull(startResourceId);
+
+ // Verify integration
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources/" + startResourceId + "/methods/POST/integration")
+ .then()
+ .statusCode(200)
+ .body("type", equalTo("AWS"))
+ .body("uri", equalTo("arn:aws:apigateway:us-east-1:states:action/StartExecution"))
+ .body("passthroughBehavior", equalTo("NEVER"));
+
+ // Verify integration responses exist
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources/" + startResourceId + "/methods/POST/integration/responses/200")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources/" + startResourceId + "/methods/POST/integration/responses/400")
+ .then()
+ .statusCode(200);
+
+ // Verify method responses exist
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources/" + startResourceId + "/methods/POST/responses/200")
+ .then()
+ .statusCode(200);
+
+ // Cleanup
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── PutRestApi (overwrite) ────────────────────────────
+
+ @Test
+ @Order(30)
+ void putRestApi_createApiForOverwrite() throws Exception {
+ // Create API imperatively first
+ String body = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"OverwriteMe\", \"description\": \"Will be overwritten\"}")
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+
+ overwriteApiId = mapper.readTree(body).get("id").asText();
+ }
+
+ @Test
+ @Order(31)
+ void putRestApi_overwriteWithNewSpec() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "OverwrittenAPI", "description": "New description", "version": "2.0" },
+ "paths": {
+ "/users": {
+ "get": {
+ "x-amazon-apigateway-integration": { "type": "MOCK" }
+ }
+ },
+ "/users/{userId}": {
+ "get": {
+ "x-amazon-apigateway-integration": { "type": "MOCK" }
+ },
+ "delete": {
+ "x-amazon-apigateway-integration": { "type": "MOCK" }
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "overwrite")
+ .body(spec)
+ .when()
+ .put("/restapis/" + overwriteApiId)
+ .then()
+ .statusCode(200)
+ .body("name", equalTo("OverwrittenAPI"))
+ .body("description", equalTo("New description"));
+ }
+
+ @Test
+ @Order(32)
+ void putRestApi_verifyNewResources() throws Exception {
+ // Should have: /, /users, /users/{userId}
+ String body = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + overwriteApiId + "/resources")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(3))
+ .extract().body().asString();
+
+ JsonNode items = mapper.readTree(body).get("item");
+ boolean hasUsers = false, hasUserId = false;
+ for (JsonNode r : items) {
+ String path = r.get("path").asText();
+ if ("/users".equals(path)) hasUsers = true;
+ if ("/users/{userId}".equals(path)) hasUserId = true;
+ }
+ assertTrue(hasUsers && hasUserId, "Should have /users and /users/{userId}");
+ }
+
+ // ──────────────────────────── Swagger 2.0 ────────────────────────────
+
+ @Test
+ @Order(40)
+ void importRestApi_swagger20() throws Exception {
+ String spec = """
+ {
+ "swagger": "2.0",
+ "info": { "title": "Swagger2API", "version": "1.0" },
+ "paths": {
+ "/ping": {
+ "get": {
+ "responses": { "200": { "description": "OK" } },
+ "x-amazon-apigateway-integration": {
+ "type": "MOCK",
+ "requestTemplates": {
+ "application/json": "{\\"statusCode\\": 200}"
+ },
+ "responses": {
+ "default": {
+ "statusCode": "200",
+ "responseTemplates": {
+ "application/json": "{\\"message\\": \\"pong\\"}"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .body("name", equalTo("Swagger2API"))
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ // Verify resources
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(2));
+
+ // Cleanup
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Error Cases ────────────────────────────
+
+ @Test
+ @Order(50)
+ void importRestApi_invalidSpec() {
+ given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body("this is not valid json or yaml")
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(400);
+ }
+
+ @Test
+ @Order(51)
+ void putRestApi_nonExistentApi() {
+ String spec = """
+ {"openapi": "3.0.1", "info": {"title": "Test", "version": "1.0"}, "paths": {}}
+ """;
+ given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "overwrite")
+ .body(spec)
+ .when()
+ .put("/restapis/nonexistent123")
+ .then()
+ .statusCode(404);
+ }
+
+ @Test
+ @Order(52)
+ void putRestApi_modeMergeAccepted() throws Exception {
+ // mode=merge is accepted (treated as overwrite — merge semantics not yet implemented)
+ String apiBody = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"MergeTest\"}")
+ .post("/restapis")
+ .then().statusCode(201).extract().body().asString();
+ String apiId = mapper.readTree(apiBody).get("id").asText();
+
+ String spec = """
+ {"openapi": "3.0.1", "info": {"title": "Merged", "version": "1.0"}, "paths": {}}
+ """;
+ given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "merge")
+ .body(spec)
+ .when()
+ .put("/restapis/" + apiId)
+ .then()
+ .statusCode(200)
+ .body("name", equalTo("Merged"));
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── YAML Format ────────────────────────────
+
+ @Test
+ @Order(60)
+ void importRestApi_yamlFormat() throws Exception {
+ String spec = """
+ openapi: "3.0.1"
+ info:
+ title: YamlAPI
+ version: "1.0"
+ paths:
+ /status:
+ get:
+ x-amazon-apigateway-integration:
+ type: MOCK
+ requestTemplates:
+ application/json: '{"statusCode": 200}'
+ responses:
+ default:
+ statusCode: "200"
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .body("name", equalTo("YamlAPI"))
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(2));
+
+ // Cleanup
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Root Path Methods ────────────────────────────
+
+ @Test
+ @Order(70)
+ void importRestApi_methodOnRootPath() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "RootPathAPI", "version": "1.0" },
+ "paths": {
+ "/": {
+ "get": {
+ "x-amazon-apigateway-integration": {
+ "type": "MOCK",
+ "requestTemplates": { "application/json": "{\\"statusCode\\": 200}" },
+ "responses": { "default": { "statusCode": "200" } }
+ }
+ }
+ },
+ "/sub": {
+ "post": {
+ "x-amazon-apigateway-integration": { "type": "MOCK" }
+ }
+ }
+ }
+ }
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ // Should have root "/" and "/sub"
+ String resourcesBody = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(2))
+ .extract().body().asString();
+
+ // Find root resource and verify it has a GET method
+ JsonNode items = mapper.readTree(resourcesBody).get("item");
+ String rootId = null;
+ for (JsonNode r : items) {
+ if ("/".equals(r.get("path").asText())) {
+ rootId = r.get("id").asText();
+ }
+ }
+ assertNotNull(rootId);
+
+ // Root should have GET method with MOCK integration
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources/" + rootId + "/methods/GET/integration")
+ .then()
+ .statusCode(200)
+ .body("type", equalTo("MOCK"));
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── End-to-End Invoke ────────────────────────────
+
+ @Test
+ @Order(80)
+ void importRestApi_deployAndInvokeMock() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "InvokeTestAPI", "version": "1.0" },
+ "paths": {
+ "/echo": {
+ "get": {
+ "x-amazon-apigateway-integration": {
+ "type": "MOCK",
+ "requestTemplates": { "application/json": "{\\"statusCode\\": 200}" },
+ "responses": {
+ "default": {
+ "statusCode": "200",
+ "responseTemplates": {
+ "application/json": "{\\"message\\": \\"hello from imported api\\"}"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """;
+
+ // Import
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ // Deploy
+ String deployBody = given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .when()
+ .post("/restapis/" + apiId + "/deployments")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+
+ String deployId = mapper.readTree(deployBody).get("id").asText();
+
+ // Create stage
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\": \"test\", \"deploymentId\": \"" + deployId + "\"}")
+ .when()
+ .post("/restapis/" + apiId + "/stages")
+ .then()
+ .statusCode(201);
+
+ // Invoke
+ given()
+ .when()
+ .get("/execute-api/" + apiId + "/test/echo")
+ .then()
+ .statusCode(200)
+ .body(containsString("hello from imported api"));
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Schemas → Models ────────────────────────────
+
+ @Test
+ @Order(85)
+ void importRestApi_schemasCreateModels() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "ModelsAPI", "version": "1.0" },
+ "paths": {
+ "/orders": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/OrderInput" }
+ }
+ }
+ },
+ "x-amazon-apigateway-integration": { "type": "MOCK",
+ "requestTemplates": { "application/json": "{\\"statusCode\\": 200}" },
+ "responses": { "default": { "statusCode": "200" } } }
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "OrderInput": {
+ "type": "object",
+ "required": ["itemId", "quantity"],
+ "properties": {
+ "itemId": { "type": "string" },
+ "quantity": { "type": "integer" }
+ }
+ },
+ "OrderOutput": {
+ "type": "object",
+ "properties": {
+ "orderId": { "type": "string" },
+ "status": { "type": "string" }
+ }
+ }
+ }
+ }
+ }
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ // Verify models were created
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/models")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(2));
+
+ // Verify individual model
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/models/OrderInput")
+ .then()
+ .statusCode(200)
+ .body("name", equalTo("OrderInput"))
+ .body("contentType", equalTo("application/json"))
+ .body("schema", containsString("itemId"));
+
+ // Verify requestModels on method
+ String resourcesBody = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources")
+ .then()
+ .extract().body().asString();
+
+ String ordersResourceId = null;
+ for (JsonNode r : mapper.readTree(resourcesBody).get("item")) {
+ if ("/orders".equals(r.get("path").asText())) {
+ ordersResourceId = r.get("id").asText();
+ }
+ }
+ assertNotNull(ordersResourceId);
+
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources/" + ordersResourceId + "/methods/POST")
+ .then()
+ .statusCode(200)
+ .body("requestModels.'application/json'", equalTo("OrderInput"));
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Request Validators ────────────────────────────
+
+ @Test
+ @Order(90)
+ void importRestApi_requestValidators() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "ValidatorAPI", "version": "1.0" },
+ "x-amazon-apigateway-request-validators": {
+ "full": {
+ "validateRequestBody": true,
+ "validateRequestParameters": true
+ },
+ "params-only": {
+ "validateRequestBody": false,
+ "validateRequestParameters": true
+ }
+ },
+ "x-amazon-apigateway-request-validator": "full",
+ "paths": {
+ "/validated": {
+ "post": {
+ "x-amazon-apigateway-integration": { "type": "MOCK",
+ "requestTemplates": { "application/json": "{\\"statusCode\\": 200}" },
+ "responses": { "default": { "statusCode": "200" } } }
+ }
+ },
+ "/params-checked": {
+ "get": {
+ "x-amazon-apigateway-request-validator": "params-only",
+ "x-amazon-apigateway-integration": { "type": "MOCK",
+ "requestTemplates": { "application/json": "{\\"statusCode\\": 200}" },
+ "responses": { "default": { "statusCode": "200" } } }
+ }
+ }
+ }
+ }
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ // Verify validators were created
+ String validatorsBody = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/requestvalidators")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(2))
+ .extract().body().asString();
+
+ // Find the "full" validator
+ JsonNode validators = mapper.readTree(validatorsBody).get("item");
+ String fullValidatorId = null;
+ String paramsOnlyValidatorId = null;
+ for (JsonNode v : validators) {
+ if ("full".equals(v.get("name").asText())) {
+ fullValidatorId = v.get("id").asText();
+ assertTrue(v.get("validateRequestBody").asBoolean());
+ assertTrue(v.get("validateRequestParameters").asBoolean());
+ }
+ if ("params-only".equals(v.get("name").asText())) {
+ paramsOnlyValidatorId = v.get("id").asText();
+ assertFalse(v.get("validateRequestBody").asBoolean());
+ assertTrue(v.get("validateRequestParameters").asBoolean());
+ }
+ }
+ assertNotNull(fullValidatorId, "Should have 'full' validator");
+ assertNotNull(paramsOnlyValidatorId, "Should have 'params-only' validator");
+
+ // Verify /validated method uses the default "full" validator
+ String resourcesBody = given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources")
+ .then()
+ .extract().body().asString();
+
+ String validatedResourceId = null;
+ String paramsCheckedResourceId = null;
+ for (JsonNode r : mapper.readTree(resourcesBody).get("item")) {
+ if ("/validated".equals(r.get("path").asText())) {
+ validatedResourceId = r.get("id").asText();
+ }
+ if ("/params-checked".equals(r.get("path").asText())) {
+ paramsCheckedResourceId = r.get("id").asText();
+ }
+ }
+
+ // Default validator applied to /validated POST
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources/" + validatedResourceId + "/methods/POST")
+ .then()
+ .statusCode(200)
+ .body("requestValidatorId", equalTo(fullValidatorId));
+
+ // Operation-level override on /params-checked GET
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/resources/" + paramsCheckedResourceId + "/methods/GET")
+ .then()
+ .statusCode(200)
+ .body("requestValidatorId", equalTo(paramsOnlyValidatorId));
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ @Test
+ @Order(91)
+ void importRestApi_validatorPrecedence() throws Exception {
+ // AWS only supports operation-level > API-level default (no path-level)
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "ValidatorPrecedenceAPI", "version": "1.0" },
+ "x-amazon-apigateway-request-validators": {
+ "full": { "validateRequestBody": true, "validateRequestParameters": true },
+ "body-only": { "validateRequestBody": true, "validateRequestParameters": false }
+ },
+ "x-amazon-apigateway-request-validator": "full",
+ "paths": {
+ "/default-validated": {
+ "get": {
+ "x-amazon-apigateway-integration": { "type": "MOCK",
+ "requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
+ "responses": {"default": {"statusCode": "200"}} }
+ }
+ },
+ "/op-override": {
+ "get": {
+ "x-amazon-apigateway-integration": { "type": "MOCK",
+ "requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
+ "responses": {"default": {"statusCode": "200"}} }
+ },
+ "post": {
+ "x-amazon-apigateway-request-validator": "body-only",
+ "x-amazon-apigateway-integration": { "type": "MOCK",
+ "requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
+ "responses": {"default": {"statusCode": "200"}} }
+ }
+ }
+ }
+ }
+ """;
+
+ String body = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+
+ String apiId = mapper.readTree(body).get("id").asText();
+
+ // Find validators
+ String validatorsBody = given()
+ .contentType(ContentType.JSON)
+ .get("/restapis/" + apiId + "/requestvalidators")
+ .then().statusCode(200).extract().body().asString();
+
+ String fullId = null, bodyOnlyId = null;
+ for (JsonNode v : mapper.readTree(validatorsBody).get("item")) {
+ if ("full".equals(v.get("name").asText())) fullId = v.get("id").asText();
+ if ("body-only".equals(v.get("name").asText())) bodyOnlyId = v.get("id").asText();
+ }
+ assertNotNull(fullId);
+ assertNotNull(bodyOnlyId);
+
+ // Find resources
+ String resourcesBody = given().get("/restapis/" + apiId + "/resources")
+ .then().extract().body().asString();
+ String defaultResourceId = null, opOverrideResourceId = null;
+ for (JsonNode r : mapper.readTree(resourcesBody).get("item")) {
+ if ("/default-validated".equals(r.get("path").asText())) defaultResourceId = r.get("id").asText();
+ if ("/op-override".equals(r.get("path").asText())) opOverrideResourceId = r.get("id").asText();
+ }
+
+ // /default-validated GET should use API-level default "full"
+ given().contentType(ContentType.JSON)
+ .get("/restapis/" + apiId + "/resources/" + defaultResourceId + "/methods/GET")
+ .then().statusCode(200)
+ .body("requestValidatorId", equalTo(fullId));
+
+ // /op-override GET should also use API-level default "full"
+ given().contentType(ContentType.JSON)
+ .get("/restapis/" + apiId + "/resources/" + opOverrideResourceId + "/methods/GET")
+ .then().statusCode(200)
+ .body("requestValidatorId", equalTo(fullId));
+
+ // /op-override POST should use operation-level "body-only"
+ given().contentType(ContentType.JSON)
+ .get("/restapis/" + apiId + "/resources/" + opOverrideResourceId + "/methods/POST")
+ .then().statusCode(200)
+ .body("requestValidatorId", equalTo(bodyOnlyId));
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Model CRUD ────────────────────────────
+
+ @Test
+ @Order(95)
+ void modelCrud_createGetListDelete() throws Exception {
+ // Create an API
+ String apiBody = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"ModelCrudTest\"}")
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+ String apiId = mapper.readTree(apiBody).get("id").asText();
+
+ // Create a model
+ String schema = "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"}}}";
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"Pet\", \"description\": \"A pet\", \"contentType\": \"application/json\", \"schema\": " + mapper.writeValueAsString(schema) + "}")
+ .when()
+ .post("/restapis/" + apiId + "/models")
+ .then()
+ .statusCode(201)
+ .body("name", equalTo("Pet"))
+ .body("description", equalTo("A pet"))
+ .body("contentType", equalTo("application/json"));
+
+ // Get model
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/models/Pet")
+ .then()
+ .statusCode(200)
+ .body("name", equalTo("Pet"))
+ .body("schema", containsString("id"));
+
+ // List models
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/models")
+ .then()
+ .statusCode(200)
+ .body("item", hasSize(1));
+
+ // Delete model
+ given()
+ .when()
+ .delete("/restapis/" + apiId + "/models/Pet")
+ .then()
+ .statusCode(202);
+
+ // Verify deleted
+ given()
+ .contentType(ContentType.JSON)
+ .when()
+ .get("/restapis/" + apiId + "/models/Pet")
+ .then()
+ .statusCode(404);
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Request Body Validation ────────────────────────────
+
+ @Test
+ @Order(96)
+ void validation_rejectsInvalidBody() throws Exception {
+ String spec = """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "BodyValidationAPI", "version": "1.0" },
+ "x-amazon-apigateway-request-validators": {
+ "body-only": {
+ "validateRequestBody": true,
+ "validateRequestParameters": false
+ }
+ },
+ "x-amazon-apigateway-request-validator": "body-only",
+ "paths": {
+ "/items": {
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ItemInput" }
+ }
+ }
+ },
+ "x-amazon-apigateway-integration": {
+ "type": "MOCK",
+ "requestTemplates": { "application/json": "{\\"statusCode\\": 200}" },
+ "responses": { "default": { "statusCode": "200",
+ "responseTemplates": { "application/json": "{\\"ok\\": true}" } } }
+ }
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ItemInput": {
+ "type": "object",
+ "required": ["name", "price"],
+ "properties": {
+ "name": { "type": "string" },
+ "price": { "type": "number" }
+ }
+ }
+ }
+ }
+ }
+ """;
+
+ String apiBody = given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(spec)
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().body().asString();
+ String apiId = mapper.readTree(apiBody).get("id").asText();
+
+ // Deploy
+ String deployBody = given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201).extract().body().asString();
+ String deployId = mapper.readTree(deployBody).get("id").asText();
+ given().contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\",\"deploymentId\":\"" + deployId + "\"}")
+ .post("/restapis/" + apiId + "/stages").then().statusCode(201);
+
+ // Valid request — should pass
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"Widget\", \"price\": 9.99}")
+ .when()
+ .post("/execute-api/" + apiId + "/test/items")
+ .then()
+ .statusCode(200)
+ .body(containsString("ok"));
+
+ // Missing required field "price" — should fail
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"Widget\"}")
+ .when()
+ .post("/execute-api/" + apiId + "/test/items")
+ .then()
+ .statusCode(400)
+ .body(containsString("price"));
+
+ // Wrong type for "price" — should fail
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"Widget\", \"price\": \"not-a-number\"}")
+ .when()
+ .post("/execute-api/" + apiId + "/test/items")
+ .then()
+ .statusCode(400);
+
+ // Empty body — should fail
+ given()
+ .contentType(ContentType.JSON)
+ .body("")
+ .when()
+ .post("/execute-api/" + apiId + "/test/items")
+ .then()
+ .statusCode(400);
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Request Parameter Validation ────────────────────────────
+
+ @Test
+ @Order(97)
+ void validation_rejectsMissingRequiredParams() throws Exception {
+ // Create API imperatively to test param validation
+ String apiBody = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"ParamValidationAPI\"}")
+ .post("/restapis")
+ .then().statusCode(201).extract().body().asString();
+ String apiId = mapper.readTree(apiBody).get("id").asText();
+
+ // Get root resource
+ String resourcesBody = given().get("/restapis/" + apiId + "/resources")
+ .then().extract().body().asString();
+ String rootId = null;
+ for (JsonNode r : mapper.readTree(resourcesBody).get("item")) {
+ if ("/".equals(r.get("path").asText())) rootId = r.get("id").asText();
+ }
+
+ // Create /search resource
+ String searchBody = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\": \"search\"}")
+ .post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201).extract().body().asString();
+ String searchId = mapper.readTree(searchBody).get("id").asText();
+
+ // Create request validator (params-only)
+ String valBody = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\": \"params-only\", \"validateRequestBody\": false, \"validateRequestParameters\": true}")
+ .post("/restapis/" + apiId + "/requestvalidators")
+ .then().statusCode(201).extract().body().asString();
+ String validatorId = mapper.readTree(valBody).get("id").asText();
+
+ // Create GET method with required query param and linked validator
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\": \"NONE\", \"requestValidatorId\": \"" + validatorId + "\", \"requestParameters\": {\"method.request.querystring.q\": true, \"method.request.header.X-Api-Key\": true}}")
+ .put("/restapis/" + apiId + "/resources/" + searchId + "/methods/GET")
+ .then().statusCode(201);
+
+ // Add MOCK integration
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"type\": \"MOCK\", \"requestTemplates\": {\"application/json\": \"{\\\"statusCode\\\": 200}\"}, \"passthroughBehavior\": \"WHEN_NO_MATCH\"}")
+ .put("/restapis/" + apiId + "/resources/" + searchId + "/methods/GET/integration")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"statusCode\": \"200\", \"responseTemplates\": {\"application/json\": \"{\\\"results\\\": []}\"}, \"selectionPattern\": \"\"}")
+ .put("/restapis/" + apiId + "/resources/" + searchId + "/methods/GET/integration/responses/200")
+ .then().statusCode(201);
+
+ // Deploy
+ String deployBody = given()
+ .contentType(ContentType.JSON)
+ .body("{}")
+ .post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201).extract().body().asString();
+ String deployId = mapper.readTree(deployBody).get("id").asText();
+ given().contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\",\"deploymentId\":\"" + deployId + "\"}")
+ .post("/restapis/" + apiId + "/stages").then().statusCode(201);
+
+ // Missing query param "q" — should fail
+ given()
+ .header("X-Api-Key", "test-key")
+ .when()
+ .get("/execute-api/" + apiId + "/test/search")
+ .then()
+ .statusCode(400)
+ .body(containsString("q"));
+
+ // Missing header "X-Api-Key" — should fail
+ given()
+ .queryParam("q", "test")
+ .when()
+ .get("/execute-api/" + apiId + "/test/search")
+ .then()
+ .statusCode(400)
+ .body(containsString("X-Api-Key"));
+
+ // Both present — should pass
+ given()
+ .queryParam("q", "test")
+ .header("X-Api-Key", "test-key")
+ .when()
+ .get("/execute-api/" + apiId + "/test/search")
+ .then()
+ .statusCode(200)
+ .body(containsString("results"));
+
+ given().delete("/restapis/" + apiId);
+ }
+
+ // ──────────────────────────── Cleanup ────────────────────────────
+
+ @Test
+ @Order(99)
+ void cleanup() {
+ if (importedApiId != null) {
+ given().delete("/restapis/" + importedApiId);
+ }
+ if (overwriteApiId != null) {
+ given().delete("/restapis/" + overwriteApiId);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java
new file mode 100644
index 0000000000..ad3607e7b2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java
@@ -0,0 +1,379 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+@QuarkusTest
+class VtlTemplateEngineTest {
+
+ @Inject
+ VtlTemplateEngine engine;
+
+ private VtlTemplateEngine.VtlContext ctx(String body) {
+ return new VtlTemplateEngine.VtlContext(
+ body,
+ Map.of("Content-Type", "application/json", "Authorization", "Bearer xyz"),
+ Map.of("limit", "10"),
+ Map.of("proxy", "users/123"),
+ "prod",
+ "POST",
+ "/users",
+ "req-123",
+ "000000000000",
+ Map.of()
+ );
+ }
+
+ @Test
+ void passthrough_nullTemplate() {
+ String result = engine.evaluate(null, ctx("{\"key\":\"value\"}"));
+ assertEquals("{\"key\":\"value\"}", result);
+ }
+
+ @Test
+ void passthrough_emptyTemplate() {
+ String result = engine.evaluate("", ctx("{\"key\":\"value\"}"));
+ assertEquals("{\"key\":\"value\"}", result);
+ }
+
+ @Test
+ void inputBody() {
+ String result = engine.evaluate("$input.body()", ctx("{\"key\":\"value\"}"));
+ assertEquals("{\"key\":\"value\"}", result);
+ }
+
+ @Test
+ void inputJson_root() {
+ String result = engine.evaluate("$input.json('$')", ctx("{\"name\":\"Alice\",\"age\":30}"));
+ // Should return the full body as JSON
+ assertTrue(result.contains("Alice"));
+ assertTrue(result.contains("30"));
+ }
+
+ @Test
+ void inputJson_nested() {
+ String result = engine.evaluate("$input.json('$.name')", ctx("{\"name\":\"Bob\"}"));
+ assertEquals("\"Bob\"", result);
+ }
+
+ @Test
+ void inputPath() {
+ String result = engine.evaluate("$input.path('$.name')", ctx("{\"name\":\"Carol\"}"));
+ assertEquals("Carol", result);
+ }
+
+ @Test
+ void inputParams() {
+ String result = engine.evaluate("$input.params().querystring.limit", ctx("{}"));
+ assertEquals("10", result);
+ }
+
+ @Test
+ void utilEscapeJavaScript_singleQuotes() {
+ String body = "{\"msg\":\"hello 'world'\"}";
+ String result = engine.evaluate("$util.escapeJavaScript($input.body())", ctx(body));
+ assertTrue(result.contains("\\'world\\'"), "Single quotes should be escaped: " + result);
+ }
+
+ @Test
+ void utilEscapeJavaScript_doubleQuotes() {
+ String result = engine.evaluate("$util.escapeJavaScript('he said \"hi\"')", ctx("{}"));
+ assertEquals("he said \\\"hi\\\"", result);
+ }
+
+ @Test
+ void utilEscapeJavaScript_forwardSlash() {
+ String result = engine.evaluate("$util.escapeJavaScript('a/b/c')", ctx("{}"));
+ assertEquals("a\\/b\\/c", result);
+ }
+
+ @Test
+ void utilEscapeJavaScript_controlChars() {
+ // Test backspace, form feed
+ var util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
+ String result = util.escapeJavaScript("a\bb\fc");
+ assertEquals("a\\bb\\fc", result);
+ }
+
+ @Test
+ void utilEscapeJavaScript_unicode() {
+ var util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
+ String result = util.escapeJavaScript("café");
+ assertEquals("caf\\u00e9", result);
+ }
+
+ @Test
+ void utilEscapeJavaScript_backslash() {
+ var util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
+ String result = util.escapeJavaScript("a\\b");
+ assertEquals("a\\\\b", result);
+ }
+
+ @Test
+ void utilEscapeJavaScript_newlineTabCr() {
+ var util = new VtlTemplateEngine.UtilVariable(new ObjectMapper());
+ String result = util.escapeJavaScript("a\nb\tc\rd");
+ assertEquals("a\\nb\\tc\\rd", result);
+ }
+
+ @Test
+ void utilUrlEncodeDecode() {
+ String result = engine.evaluate("$util.urlEncode('hello world')", ctx("{}"));
+ assertEquals("hello+world", result);
+
+ String decoded = engine.evaluate("$util.urlDecode('hello+world')", ctx("{}"));
+ assertEquals("hello world", decoded);
+ }
+
+ @Test
+ void utilBase64EncodeDecode() {
+ String encoded = engine.evaluate("$util.base64Encode('test data')", ctx("{}"));
+ assertEquals("dGVzdCBkYXRh", encoded);
+
+ String decoded = engine.evaluate("$util.base64Decode('dGVzdCBkYXRh')", ctx("{}"));
+ assertEquals("test data", decoded);
+ }
+
+ @Test
+ void contextVariables() {
+ String result = engine.evaluate(
+ "$context.stage:$context.httpMethod:$context.resourcePath:$context.requestId",
+ ctx("{}"));
+ assertEquals("prod:POST:/users:req-123", result);
+ }
+
+ @Test
+ void contextIdentity() {
+ String result = engine.evaluate("$context.identity.sourceIp", ctx("{}"));
+ assertEquals("127.0.0.1", result);
+ }
+
+ @Test
+ void stageVariables() {
+ VtlTemplateEngine.VtlContext svCtx = new VtlTemplateEngine.VtlContext(
+ "{}", Map.of(), Map.of(), Map.of(), "prod", "GET", "/",
+ "req-1", "000000000000", Map.of("tableName", "my-table"));
+ String result = engine.evaluate("$stageVariables.tableName", svCtx);
+ assertEquals("my-table", result);
+ }
+
+ @Test
+ void sfnRequestTemplate() {
+ String template = """
+ {"stateMachineArn": "arn:aws:states:us-east-1:000:sm:test", "input": "$util.escapeJavaScript($input.json('$'))"}""";
+ String body = "{\"id\":\"123\",\"message\":\"hello\"}";
+ String result = engine.evaluate(template, ctx(body));
+
+ assertTrue(result.contains("arn:aws:states:us-east-1:000:sm:test"));
+ assertTrue(result.contains("\\\"id\\\""));
+ assertTrue(result.contains("\\\"123\\\""));
+
+ // Verify it's valid JSON when we unescape the input field
+ assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
+ }
+
+ @Test
+ void velocityDirectives_set() {
+ String template = """
+ #set($body = $input.path('$'))
+ {"value": "$body.name"}""";
+ String result = engine.evaluate(template, ctx("{\"name\":\"Dave\"}")).trim();
+ assertTrue(result.contains("Dave"));
+ }
+
+ @Test
+ void inputJson_arrayIndex() {
+ String body = "{\"items\":[{\"id\":\"first\"},{\"id\":\"second\"}]}";
+ String result = engine.evaluate("$input.json('$.items[0].id')", ctx(body));
+ assertEquals("\"first\"", result);
+ }
+
+ @Test
+ void inputJson_arrayIndexNested() {
+ String body = "{\"data\":[[[\"deep\"]]]}";
+ String result = engine.evaluate("$input.json('$.data[0][0][0]')", ctx(body));
+ assertEquals("\"deep\"", result);
+ }
+
+ @Test
+ void inputPath_arrayIndex() {
+ String body = "{\"users\":[{\"name\":\"Eve\"},{\"name\":\"Frank\"}]}";
+ String result = engine.evaluate("$input.path('$.users[1].name')", ctx(body));
+ assertEquals("Frank", result);
+ }
+
+ @Test
+ void nullBody() {
+ String result = engine.evaluate("$input.body()", ctx(null));
+ assertEquals("", result);
+ }
+
+ // ──────────── Velocity directives: #foreach ────────────
+
+ @Test
+ void foreach_iterateArray() {
+ String body = "{\"names\":[\"Alice\",\"Bob\",\"Carol\"]}";
+ String template = "#set($names = $input.path('$.names'))\n"
+ + "[#foreach($name in $names)\"$name\"#if($foreach.hasNext),#end#end]";
+ String result = engine.evaluate(template, ctx(body)).trim();
+ assertEquals("[\"Alice\",\"Bob\",\"Carol\"]", result);
+ }
+
+ @Test
+ void foreach_buildJsonArray() {
+ // Common APIGW pattern: transform a list of items
+ String body = "{\"items\":[{\"id\":\"1\",\"val\":\"a\"},{\"id\":\"2\",\"val\":\"b\"}]}";
+ String template = "#set($items = $input.path('$.items'))\n"
+ + "{\"results\": [#foreach($item in $items)"
+ + "{\"key\": \"$item.id\"}#if($foreach.hasNext),#end"
+ + "#end]}";
+ String result = engine.evaluate(template, ctx(body)).trim();
+ assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
+ var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
+ assertEquals(2, node.path("results").size());
+ assertEquals("1", node.path("results").get(0).path("key").asText());
+ }
+
+ // ──────────── Velocity directives: #if / #else ────────────
+
+ @Test
+ void if_conditionalOutput() {
+ String body = "{\"type\":\"premium\"}";
+ String template = "#set($type = $input.path('$.type'))\n"
+ + "#if($type == 'premium')PREMIUM#else STANDARD#end";
+ String result = engine.evaluate(template, ctx(body)).trim();
+ assertEquals("PREMIUM", result);
+ }
+
+ @Test
+ void if_elseBranch() {
+ String body = "{\"type\":\"basic\"}";
+ String template = "#set($type = $input.path('$.type'))\n"
+ + "#if($type == 'premium')PREMIUM#else STANDARD#end";
+ String result = engine.evaluate(template, ctx(body)).trim();
+ assertEquals("STANDARD", result);
+ }
+
+ @Test
+ void if_nullCheck() {
+ // Common pattern: check if a field exists
+ String body = "{\"name\":\"test\"}";
+ String template = "#set($desc = $input.path('$.description'))\n"
+ + "#if($desc && $desc != '')HAS_DESC#else NO_DESC#end";
+ String result = engine.evaluate(template, ctx(body)).trim();
+ assertEquals("NO_DESC", result);
+ }
+
+ // ──────────── Complex real-world template patterns ────────────
+
+ @Test
+ void realWorld_sqsSendMessage() {
+ // Common pattern: APIGW → SQS SendMessage with body as message
+ String body = "{\"orderId\":\"123\",\"amount\":99.95}";
+ String template = """
+ {"QueueUrl": "http://localhost:4566/000000000000/my-queue", "MessageBody": "$util.escapeJavaScript($input.json('$'))"}""";
+ String result = engine.evaluate(template, ctx(body));
+ assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
+ var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
+ assertEquals("http://localhost:4566/000000000000/my-queue", node.path("QueueUrl").asText());
+ // MessageBody should be the escaped JSON string
+ assertTrue(node.path("MessageBody").asText().contains("orderId"));
+ }
+
+ @Test
+ void realWorld_dynamoDbQueryWithParams() {
+ // Pattern: use query string params in a DynamoDB query
+ var queryCtx = new VtlTemplateEngine.VtlContext(
+ "{}", Map.of(), Map.of("userId", "user-42", "status", "active"),
+ Map.of(), "prod", "GET", "/items",
+ "req-456", "000000000000", Map.of("tableName", "orders"));
+ String template = """
+ {"TableName": "$stageVariables.tableName", "KeyConditionExpression": "pk = :pk", "ExpressionAttributeValues": {":pk": {"S": "$input.params().querystring.userId"}}}""";
+ String result = engine.evaluate(template, queryCtx);
+ var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
+ assertEquals("orders", node.path("TableName").asText());
+ assertEquals("user-42", node.path("ExpressionAttributeValues").path(":pk").path("S").asText());
+ }
+
+ // ──────────── Multi-value params and headers ────────────
+
+ @Test
+ void inputParams_headerAccess() {
+ String result = engine.evaluate("$input.params().header.Authorization", ctx("{}"));
+ assertEquals("Bearer xyz", result);
+ }
+
+ @Test
+ void inputParams_pathAccess() {
+ String result = engine.evaluate("$input.params().path.proxy", ctx("{}"));
+ assertEquals("users/123", result);
+ }
+
+ @Test
+ void inputParams_allTypes() {
+ // Access all three param types in one template
+ String template = "$input.params().querystring.limit|$input.params().path.proxy|$input.params().header.get('Content-Type')";
+ String result = engine.evaluate(template, ctx("{}"));
+ assertTrue(result.startsWith("10|users/123|"), "Should contain all param types: " + result);
+ }
+
+ // ──────────── $util.parseJson in templates ────────────
+
+ // ──────────── $input.params('name') shorthand ────────────
+
+ @Test
+ void inputParams_shorthand_querystring() {
+ String result = engine.evaluate("$input.params('limit')", ctx("{}"));
+ assertEquals("10", result);
+ }
+
+ @Test
+ void inputParams_shorthand_path() {
+ String result = engine.evaluate("$input.params('proxy')", ctx("{}"));
+ assertEquals("users/123", result);
+ }
+
+ @Test
+ void inputParams_shorthand_header() {
+ String result = engine.evaluate("$input.params('Authorization')", ctx("{}"));
+ assertEquals("Bearer xyz", result);
+ }
+
+ @Test
+ void inputParams_shorthand_notFound() {
+ String result = engine.evaluate("$input.params('nonexistent')", ctx("{}"));
+ assertEquals("", result);
+ }
+
+ @Test
+ void inputParams_shorthand_querystringPrecedence() {
+ // querystring should take precedence over path and header
+ VtlTemplateEngine.VtlContext overlapCtx = new VtlTemplateEngine.VtlContext(
+ "{}", Map.of("shared", "header-val"),
+ Map.of("shared", "query-val"),
+ Map.of("shared", "path-val"),
+ "prod", "GET", "/", "req-1", "000000000000", Map.of());
+ String result = engine.evaluate("$input.params('shared')", overlapCtx);
+ assertEquals("query-val", result);
+ }
+
+ @Test
+ void utilParseJson_navigateResult() {
+ String template = "#set($parsed = $util.parseJson('{\"a\":{\"b\":\"deep\"}}'))\n$parsed.a.b";
+ String result = engine.evaluate(template, ctx("{}")).trim();
+ assertEquals("deep", result);
+ }
+
+ @Test
+ void utilParseJson_withArray() {
+ String template = "#set($parsed = $util.parseJson('[1,2,3]'))\n$parsed.size()";
+ String result = engine.evaluate(template, ctx("{}")).trim();
+ assertEquals("3", result);
+ }
+}