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.
+ *
+ * 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.
+ *
+ *
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 buildContextMap(VtlContext ctx) {
+ Map 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 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 headers,
+ Map queryParams,
+ Map pathParams,
+ String stage,
+ String httpMethod,
+ String resourcePath,
+ String requestId,
+ String accountId,
+ Map 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> params() {
+ Map> 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 requestParameters = new HashMap<>(); // integration.request.* → method.request.*
private Map requestTemplates = new HashMap<>();
private Map 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 getRequestParameters() {
+ return requestParameters;
+ }
+
+ public void setRequestParameters(Map requestParameters) {
+ this.requestParameters = requestParameters != null ? requestParameters : new HashMap<>();
+ }
+
public Map 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 requestParameters = new HashMap<>();
+ private Map requestModels = new HashMap<>();
private Map 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 getRequestModels() { return requestModels; }
+ public void setRequestModels(Map requestModels) {
+ this.requestModels = requestModels != null ? requestModels : new HashMap<>();
+ }
+
public Map getRequestParameters() { return requestParameters; }
public void setRequestParameters(Map 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 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 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 responses,
+ Map> 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 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 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 anyOf(int... values) {
+ org.hamcrest.Matcher[] 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);
+ }
+}