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

* feat(APIGW): add AWS integration type for API Gateway REST v1

Add support for the API Gateway REST v1 AWS (non-proxy) integration type,
enabling direct service calls via VTL request/response mapping templates.

New components:
- VtlTemplateEngine: Apache Velocity engine with $input (body, json, path,
  params shorthand), $util (escapeJavaScript, urlEncode, base64, parseJson),
  $context, and $stageVariables
- AwsServiceRouter: parses action-based integration URIs and dispatches to
  13 internal service handlers (states, dynamodb, sqs, sns, events, etc.)

Integration features:
- Content-Type negotiation for request template selection
- passthroughBehavior (WHEN_NO_MATCH, WHEN_NO_TEMPLATES, NEVER)
- Request parameter mapping (method.request.* -> integration.request.*)
- Response parameter mapping with full JSONPath body extraction
- Integration response selection via selectionPattern regex matching
- VTL directives: #set, #foreach, #if/#else

Also fixes SFN timestamps to use epoch float (e.g. 1743263483.047) matching
real AWS format.

* feat(APIGW): add OpenAPI/Swagger import, models, and request validation

Add ImportRestApi (POST /restapis?mode=import) and PutRestApi
(PUT /restapis/{apiId}?mode=overwrite) supporting OpenAPI 3.0 and
Swagger 2.0 specs with x-amazon-apigateway-integration extensions.

- Parse OpenAPI specs via swagger-parser, create resources/methods/integrations
- Import components.schemas as API Gateway Models with JSON Schema
- Import x-amazon-apigateway-request-validators as RequestValidators
- Validator precedence: operation > path > API-level default
- Model CRUD endpoints (create, get, list, delete)
- Request body validation against JSON Schema (Draft 4) at execute-api layer
- Required parameter presence validation (query string, header)
- mode=merge returns 400 with clear error message
- 22 integration tests, 792 total passing

* fix(APIGW): match real AWS behavior for validators and mode=merge

- Remove path-level x-amazon-apigateway-request-validator (AWS only
  supports operation-level > API-level default, verified against real AWS)
- Accept mode=merge in PutRestApi (treated as overwrite for now, since
  real AWS accepts it — returning 400 was incorrect)

Verified: 31/31 compat tests against real AWS, 39/39 against Floci.
This commit is contained in:
thegagne authored and GitHub committed 2026-03-30 20:12:21 -05:00
1 parent 6ff819083d
commit d1d7ec3bd3
18 files changed
+4277 -28

No files matched your search

@@ -152,8 +152,14 @@ public class ApiGatewayController {
@POST
@Path("/restapis")
public Response createRestApi(@Context HttpHeaders headers, String body) {
public Response createRestApi(@Context HttpHeaders headers,
@QueryParam("mode") String mode,
String body) {
String region = regionResolver.resolveRegion(headers);
if ("import".equals(mode)) {
RestApi api = service.importRestApi(region, body);
return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
}
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
@@ -164,6 +170,17 @@ public class ApiGatewayController {
}
}
@PUT
@Path("/restapis/{apiId}")
public Response putRestApi(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@QueryParam("mode") String mode,
String body) {
String region = regionResolver.resolveRegion(headers);
RestApi api = service.putRestApi(region, apiId, mode, body);
return Response.ok(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis")
public Response getRestApis(@Context HttpHeaders headers) {
@@ -628,6 +645,52 @@ public class ApiGatewayController {
return Response.accepted().build();
}
// ──────────────────────────── Models (v1) ────────────────────────────
@POST
@Path("/restapis/{apiId}/models")
public Response createModel(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
String region = regionResolver.resolveRegion(headers);
try {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
io.github.hectorvent.floci.services.apigateway.model.Model model = service.createModel(region, apiId, request);
return Response.status(201).entity(toModelNode(model).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/restapis/{apiId}/models")
public Response getModels(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
String region = regionResolver.resolveRegion(headers);
List<io.github.hectorvent.floci.services.apigateway.model.Model> models = service.getModels(region, apiId);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
models.forEach(m -> items.add(toModelNode(m)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/restapis/{apiId}/models/{modelName}")
public Response getModel(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("modelName") String modelName) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(toModelNode(service.getModel(region, apiId, modelName)).toString()).type(MediaType.APPLICATION_JSON).build();
}
@DELETE
@Path("/restapis/{apiId}/models/{modelName}")
public Response deleteModel(@Context HttpHeaders headers,
@PathParam("apiId") String apiId,
@PathParam("modelName") String modelName) {
String region = regionResolver.resolveRegion(headers);
service.deleteModel(region, apiId, modelName);
return Response.accepted().build();
}
// ──────────────────────────── Custom Domains (v1) ────────────────────────────
@POST
@@ -843,6 +906,12 @@ public class ApiGatewayController {
node.put("httpMethod", m.getHttpMethod());
node.put("authorizationType", m.getAuthorizationType());
if (m.getAuthorizerId() != null) node.put("authorizerId", m.getAuthorizerId());
if (m.getRequestValidatorId() != null) node.put("requestValidatorId", m.getRequestValidatorId());
if (m.getRequestModels() != null && !m.getRequestModels().isEmpty()) {
ObjectNode models = objectMapper.createObjectNode();
m.getRequestModels().forEach(models::put);
node.set("requestModels", models);
}
if (m.getMethodIntegration() != null) {
node.set("methodIntegration", toIntegrationNode(m.getMethodIntegration()));
}
@@ -860,6 +929,7 @@ public class ApiGatewayController {
node.put("type", i.getType());
node.put("httpMethod", i.getHttpMethod());
node.put("uri", i.getUri());
node.put("passthroughBehavior", i.getPassthroughBehavior());
return node;
}
@@ -948,6 +1018,16 @@ public class ApiGatewayController {
return node;
}
private ObjectNode toModelNode(io.github.hectorvent.floci.services.apigateway.model.Model m) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", m.getId());
node.put("name", m.getName());
if (m.getDescription() != null) node.put("description", m.getDescription());
node.put("contentType", m.getContentType());
if (m.getSchema() != null) node.put("schema", m.getSchema());
return node;
}
private ObjectNode toRequestValidatorNode(RequestValidator v) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", v.getId());
@@ -22,9 +22,11 @@ import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
/**
* Executes API Gateway stage requests, routing them through the configured
@@ -46,16 +48,21 @@ public class ApiGatewayExecuteController {
private final LambdaService lambdaService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final VtlTemplateEngine vtlEngine;
private final AwsServiceRouter serviceRouter;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
LambdaService lambdaService, RegionResolver regionResolver,
ObjectMapper objectMapper) {
ObjectMapper objectMapper, VtlTemplateEngine vtlEngine,
AwsServiceRouter serviceRouter) {
this.apiGatewayService = apiGatewayService;
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaService = lambdaService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.vtlEngine = vtlEngine;
this.serviceRouter = serviceRouter;
}
@GET
@@ -157,6 +164,10 @@ public class ApiGatewayExecuteController {
Response authResponse = invokeAuthorizer(region, apiId, method, headers, uriInfo);
if (authResponse != null) return authResponse;
// 2. Request validation
Response validationResponse = validateRequest(region, apiId, method, headers, uriInfo, body);
if (validationResponse != null) return validationResponse;
Integration integration = method.getMethodIntegration();
if (integration == null) {
return Response.status(500)
@@ -170,6 +181,8 @@ public class ApiGatewayExecuteController {
return switch (integration.getType().toUpperCase()) {
case "AWS_PROXY" -> invokeProxy(region, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body);
case "AWS" -> invokeAwsIntegration(region, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body);
case "MOCK" -> invokeMock(integration);
default -> Response.status(500)
.entity(jsonMessage("Unsupported integration type: " + integration.getType()))
@@ -242,6 +255,97 @@ public class ApiGatewayExecuteController {
return null;
}
private Response validateRequest(String region, String apiId, MethodConfig method,
HttpHeaders headers, UriInfo uriInfo, byte[] body) {
String validatorId = method.getRequestValidatorId();
if (validatorId == null) return null;
io.github.hectorvent.floci.services.apigateway.model.RequestValidator validator;
try {
validator = apiGatewayService.getRequestValidator(region, apiId, validatorId);
} catch (AwsException e) {
return null; // Validator not found — skip validation
}
// Validate request parameters
if (validator.isValidateRequestParameters()) {
Map<String, Boolean> requiredParams = method.getRequestParameters();
if (requiredParams != null) {
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
for (Map.Entry<String, Boolean> entry : requiredParams.entrySet()) {
if (!Boolean.TRUE.equals(entry.getValue())) continue;
String paramKey = entry.getKey();
// Format: method.request.querystring.name or method.request.header.name
if (paramKey.startsWith("method.request.querystring.")) {
String name = paramKey.substring("method.request.querystring.".length());
if (!queryParams.containsKey(name) || queryParams.getFirst(name) == null) {
return Response.status(400)
.entity(jsonMessage("Missing required request parameter in QUERY_STRING: '" + name + "'"))
.type(MediaType.APPLICATION_JSON).build();
}
} else if (paramKey.startsWith("method.request.header.")) {
String name = paramKey.substring("method.request.header.".length());
if (headers.getHeaderString(name) == null) {
return Response.status(400)
.entity(jsonMessage("Missing required request parameter in HEADER: '" + name + "'"))
.type(MediaType.APPLICATION_JSON).build();
}
}
}
}
}
// Validate request body against model schema
if (validator.isValidateRequestBody()) {
Map<String, String> requestModels = method.getRequestModels();
if (requestModels != null && !requestModels.isEmpty()) {
String contentType = headers.getMediaType() != null
? headers.getMediaType().getType() + "/" + headers.getMediaType().getSubtype()
: "application/json";
String modelName = requestModels.get(contentType);
if (modelName == null) modelName = requestModels.get("application/json");
if (modelName != null) {
try {
io.github.hectorvent.floci.services.apigateway.model.Model model =
apiGatewayService.getModel(region, apiId, modelName);
String schemaStr = model.getSchema();
if (schemaStr != null && !schemaStr.isBlank()) {
String bodyStr = body != null ? new String(body, StandardCharsets.UTF_8) : "";
if (bodyStr.isBlank()) {
return Response.status(400)
.entity(jsonMessage("Invalid request body"))
.type(MediaType.APPLICATION_JSON).build();
}
JsonNode schemaNode = objectMapper.readTree(schemaStr);
JsonNode bodyNode = objectMapper.readTree(bodyStr);
com.networknt.schema.JsonSchemaFactory factory =
com.networknt.schema.JsonSchemaFactory.getInstance(
com.networknt.schema.SpecVersion.VersionFlag.V4);
com.networknt.schema.JsonSchema schema = factory.getSchema(schemaNode);
var errors = schema.validate(bodyNode);
if (!errors.isEmpty()) {
String errorMsg = errors.iterator().next().getMessage();
return Response.status(400)
.entity(jsonMessage("Invalid request body: " + errorMsg))
.type(MediaType.APPLICATION_JSON).build();
}
}
} catch (AwsException e) {
// Model not found — skip body validation
} catch (Exception e) {
return Response.status(400)
.entity(jsonMessage("Invalid request body"))
.type(MediaType.APPLICATION_JSON).build();
}
}
}
}
return null;
}
private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth, HttpHeaders headers) {
ObjectNode node = objectMapper.createObjectNode();
node.put("type", auth.getType());
@@ -374,6 +478,290 @@ public class ApiGatewayExecuteController {
}
}
// ──────────────────────────── AWS (non-proxy) ────────────────────────────
private Response invokeAwsIntegration(String region, String httpMethod, String path, String proxy,
String stageName, ApiGatewayResource resource,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body) {
AwsServiceRouter.IntegrationTarget target = serviceRouter.parseIntegrationUri(integration.getUri());
if (target == null) {
return Response.status(500)
.entity(jsonMessage("Cannot parse AWS integration URI: " + integration.getUri()))
.type(MediaType.APPLICATION_JSON).build();
}
String requestId = UUID.randomUUID().toString();
String bodyStr = body != null && body.length > 0 ? new String(body) : null;
// Build VTL context
Map<String, String> headerMap = new HashMap<>();
for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {
if (!e.getValue().isEmpty()) headerMap.put(e.getKey(), e.getValue().get(0));
}
Map<String, String> queryMap = new HashMap<>();
for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
if (!e.getValue().isEmpty()) queryMap.put(e.getKey(), e.getValue().get(0));
}
Map<String, String> pathMap = new HashMap<>();
if (proxy != null && !proxy.isEmpty()) pathMap.put("proxy", proxy);
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
resource.getPath(), requestId, "000000000000", null);
// Apply request parameter mapping (method.request.* → integration.request.*)
Map<String, String> integrationReqParams = integration.getRequestParameters();
if (integrationReqParams != null && !integrationReqParams.isEmpty()) {
for (Map.Entry<String, String> param : integrationReqParams.entrySet()) {
String dest = param.getKey(); // integration.request.header.X-Foo or integration.request.querystring.bar
String source = param.getValue(); // method.request.querystring.q or method.request.header.Auth or method.request.path.id
String resolvedValue = resolveRequestParameter(source, queryMap, pathMap, headerMap);
if (resolvedValue != null) {
if (dest.startsWith("integration.request.header.")) {
headerMap.put(dest.substring("integration.request.header.".length()), resolvedValue);
} else if (dest.startsWith("integration.request.querystring.")) {
queryMap.put(dest.substring("integration.request.querystring.".length()), resolvedValue);
} else if (dest.startsWith("integration.request.path.")) {
pathMap.put(dest.substring("integration.request.path.".length()), resolvedValue);
}
}
}
}
// Content-Type negotiation and passthrough behavior
String transformedBody;
Map<String, String> requestTemplates = integration.getRequestTemplates();
String incomingContentType = headerMap.getOrDefault("Content-Type",
headerMap.getOrDefault("content-type", "application/json"));
if (requestTemplates != null && !requestTemplates.isEmpty()) {
// Try exact match first, then wildcard fallback
String template = requestTemplates.get(incomingContentType);
if (template == null) {
// Try without charset: "application/json; charset=utf-8" → "application/json"
String baseType = incomingContentType.contains(";")
? incomingContentType.substring(0, incomingContentType.indexOf(';')).trim()
: incomingContentType;
template = requestTemplates.get(baseType);
}
if (template != null) {
transformedBody = vtlEngine.evaluate(template, vtlCtx);
} else {
// No matching template for this Content-Type
String behavior = integration.getPassthroughBehavior();
if ("NEVER".equalsIgnoreCase(behavior)) {
return Response.status(415)
.entity(jsonMessage("Unsupported Media Type"))
.type(MediaType.APPLICATION_JSON).build();
} else if ("WHEN_NO_TEMPLATES".equalsIgnoreCase(behavior)) {
// Templates exist but none match → reject
return Response.status(415)
.entity(jsonMessage("Unsupported Media Type"))
.type(MediaType.APPLICATION_JSON).build();
} else {
// WHEN_NO_MATCH (default) — passthrough
transformedBody = bodyStr != null ? bodyStr : "";
}
}
} else {
// No templates defined at all
String behavior = integration.getPassthroughBehavior();
if ("NEVER".equalsIgnoreCase(behavior)) {
return Response.status(415)
.entity(jsonMessage("Unsupported Media Type"))
.type(MediaType.APPLICATION_JSON).build();
}
transformedBody = bodyStr != null ? bodyStr : "";
}
// Dispatch to service
Response serviceResponse;
String errorType = null;
String errorMessage = null;
try {
JsonNode requestJson = objectMapper.readTree(transformedBody);
serviceResponse = serviceRouter.invoke(target.service(), target.action(), requestJson, region);
} catch (AwsException e) {
errorType = e.getErrorCode();
errorMessage = e.getMessage();
serviceResponse = null;
} catch (Exception e) {
errorType = "InternalError";
errorMessage = e.getMessage() != null ? e.getMessage() : "Service invocation failed";
serviceResponse = null;
}
// Build response body string
String responseBodyStr;
int serviceStatus;
if (serviceResponse != null) {
serviceStatus = serviceResponse.getStatus();
Object entity = serviceResponse.getEntity();
if (entity instanceof JsonNode jsonNode) {
try {
responseBodyStr = objectMapper.writeValueAsString(jsonNode);
} catch (Exception e) {
responseBodyStr = entity.toString();
}
} else if (entity != null) {
responseBodyStr = entity.toString();
} else {
responseBodyStr = "{}";
}
// Check if service returned an error status
if (serviceStatus >= 400) {
try {
JsonNode errorNode = objectMapper.readTree(responseBodyStr);
errorType = errorNode.path("__type").asText(
errorNode.path("errorType").asText(null));
errorMessage = errorNode.path("message").asText(
errorNode.path("Message").asText(
errorNode.path("errorMessage").asText("Service error")));
} catch (Exception ignored) {
errorType = "ServiceError";
errorMessage = responseBodyStr;
}
}
} else {
serviceStatus = 500;
responseBodyStr = String.format("{\"errorMessage\":\"%s\",\"errorType\":\"%s\"}",
errorMessage != null ? errorMessage.replace("\"", "\\\"") : "Unknown error",
errorType != null ? errorType : "UnknownError");
}
// Select integration response
Map<String, IntegrationResponse> integrationResponses = integration.getIntegrationResponses();
IntegrationResponse matchedResponse = null;
IntegrationResponse defaultResponse = null;
// Build the error string to match selectionPattern against.
// AWS matches against the error response body/message. We match against
// both errorType and errorMessage to catch patterns like ".*ResourceNotFoundException.*".
String errorMatchString = errorType != null
? errorType + (errorMessage != null ? ": " + errorMessage : "")
: errorMessage;
if (integrationResponses != null && !integrationResponses.isEmpty()) {
for (IntegrationResponse ir : integrationResponses.values()) {
if (ir.selectionPattern() == null || ir.selectionPattern().isEmpty()) {
defaultResponse = ir;
} else if (errorMatchString != null) {
try {
if (Pattern.matches(ir.selectionPattern(), errorMatchString)) {
matchedResponse = ir;
break;
}
} catch (Exception ignored) {
// Invalid regex — skip
}
}
}
if (matchedResponse == null) {
matchedResponse = defaultResponse;
}
}
// Determine final status code and body
int finalStatus;
String finalBody;
if (matchedResponse != null) {
finalStatus = Integer.parseInt(matchedResponse.statusCode());
Map<String, String> responseTemplates = matchedResponse.responseTemplates();
if (responseTemplates != null && !responseTemplates.isEmpty()) {
String responseTemplate = responseTemplates.getOrDefault("application/json",
responseTemplates.values().iterator().next());
if (responseTemplate != null && !responseTemplate.isEmpty()) {
VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
resource.getPath(), requestId, "000000000000", null);
finalBody = vtlEngine.evaluate(responseTemplate, responseMappingCtx);
} else {
finalBody = responseBodyStr;
}
} else {
finalBody = responseBodyStr;
}
} else {
finalStatus = errorType != null ? 500 : (serviceStatus >= 400 ? serviceStatus : 200);
finalBody = responseBodyStr;
}
Response.ResponseBuilder rb = Response.status(finalStatus)
.entity(finalBody)
.type(MediaType.APPLICATION_JSON);
// Apply response parameter mapping (header mapping)
if (matchedResponse != null && matchedResponse.responseParameters() != null) {
Map<String, String> serviceResponseHeaders = new HashMap<>();
if (serviceResponse != null) {
for (Map.Entry<String, List<String>> e : serviceResponse.getStringHeaders().entrySet()) {
if (!e.getValue().isEmpty()) serviceResponseHeaders.put(e.getKey(), e.getValue().get(0));
}
}
for (Map.Entry<String, String> param : matchedResponse.responseParameters().entrySet()) {
String dest = param.getKey(); // method.response.header.X-Foo
String source = param.getValue(); // integration.response.header.X-Bar or 'static' or integration.response.body.jsonpath
if (!dest.startsWith("method.response.header.")) continue;
String headerName = dest.substring("method.response.header.".length());
String headerValue = resolveResponseParameter(source, serviceResponseHeaders, responseBodyStr);
if (headerValue != null) {
rb.header(headerName, headerValue);
}
}
}
return rb.build();
}
private String resolveResponseParameter(String source, Map<String, String> serviceHeaders, String responseBody) {
if (source == null) return null;
// Static value: 'some value'
if (source.startsWith("'") && source.endsWith("'")) {
return source.substring(1, source.length() - 1);
}
// Integration response header
if (source.startsWith("integration.response.header.")) {
String headerName = source.substring("integration.response.header.".length());
return serviceHeaders.get(headerName);
}
// Integration response body (JSONPath)
if (source.startsWith("integration.response.body.")) {
String jsonPath = "$." + source.substring("integration.response.body.".length());
try {
JsonNode root = objectMapper.readTree(responseBody);
JsonNode node = VtlTemplateEngine.InputVariable.resolvePath(root, jsonPath);
return node.isMissingNode() ? null : node.asText();
} catch (Exception e) {
return null;
}
}
return null;
}
private String resolveRequestParameter(String source, Map<String, String> queryParams,
Map<String, String> pathParams, Map<String, String> headers) {
if (source == null) return null;
if (source.startsWith("method.request.querystring.")) {
return queryParams.get(source.substring("method.request.querystring.".length()));
}
if (source.startsWith("method.request.path.")) {
return pathParams.get(source.substring("method.request.path.".length()));
}
if (source.startsWith("method.request.header.")) {
return headers.get(source.substring("method.request.header.".length()));
}
// Static value
if (source.startsWith("'") && source.endsWith("'")) {
return source.substring(1, source.length() - 1);
}
return null;
}
// ──────────────────────────── MOCK ────────────────────────────
private Response invokeMock(Integration integration) {
@@ -7,14 +7,14 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.*;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;
@ApplicationScoped
public class ApiGatewayService {
@@ -30,6 +30,7 @@ public class ApiGatewayService {
private final StorageBackend<String, UsagePlan> usagePlanStore;
private final StorageBackend<String, UsagePlanKey> usagePlanKeyStore;
private final StorageBackend<String, RequestValidator> requestValidatorStore;
private final StorageBackend<String, Model> modelStore;
private final StorageBackend<String, CustomDomain> domainStore;
private final StorageBackend<String, BasePathMapping> basePathMappingStore;
private final RegionResolver regionResolver;
@@ -63,6 +64,9 @@ public class ApiGatewayService {
this.requestValidatorStore = storageFactory.create("apigateway", "apigateway-validators.json",
new TypeReference<>() {
});
this.modelStore = storageFactory.create("apigateway", "apigateway-models.json",
new TypeReference<>() {
});
this.domainStore = storageFactory.create("apigateway", "apigateway-domains.json",
new TypeReference<>() {
});
@@ -114,6 +118,8 @@ public class ApiGatewayService {
resourceStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(resourceStore::delete);
deploymentStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(deploymentStore::delete);
stageStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(stageStore::delete);
modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);
requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);
LOG.infov("Deleted REST API: {0} in {1}", apiId, region);
}
@@ -160,11 +166,16 @@ public class ApiGatewayService {
method.setHttpMethod(httpMethod.toUpperCase());
method.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
method.setAuthorizerId((String) request.get("authorizerId"));
method.setRequestValidatorId((String) request.get("requestValidatorId"));
@SuppressWarnings("unchecked")
Map<String, Boolean> reqParams = (Map<String, Boolean>) request.get("requestParameters");
if (reqParams != null) method.setRequestParameters(reqParams);
@SuppressWarnings("unchecked")
Map<String, String> reqModels = (Map<String, String>) request.get("requestModels");
if (reqModels != null) method.setRequestModels(reqModels);
resource.getResourceMethods().put(httpMethod.toUpperCase(), method);
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
return method;
@@ -216,6 +227,14 @@ public class ApiGatewayService {
integration.setHttpMethod((String) request.get("httpMethod"));
integration.setUri((String) request.get("uri"));
if (request.get("passthroughBehavior") != null) {
integration.setPassthroughBehavior((String) request.get("passthroughBehavior"));
}
@SuppressWarnings("unchecked")
Map<String, String> reqParams = (Map<String, String>) request.get("requestParameters");
if (reqParams != null) integration.setRequestParameters(reqParams);
@SuppressWarnings("unchecked")
Map<String, String> reqTemplates = (Map<String, String>) request.get("requestTemplates");
if (reqTemplates != null) integration.setRequestTemplates(reqTemplates);
@@ -544,6 +563,38 @@ public class ApiGatewayService {
requestValidatorStore.delete(requestValidatorKey(region, apiId, validatorId));
}
// ──────────────────────────── Models ────────────────────────────
public Model createModel(String region, String apiId, Map<String, Object> request) {
getRestApi(region, apiId);
Model model = new Model();
model.setId(shortId(6));
model.setName((String) request.get("name"));
model.setDescription((String) request.get("description"));
model.setContentType((String) request.getOrDefault("contentType", "application/json"));
model.setSchema((String) request.get("schema"));
modelStore.put(modelKey(region, apiId, model.getName()), model);
LOG.infov("Created model {0} for API {1}", model.getName(), apiId);
return model;
}
public Model getModel(String region, String apiId, String modelName) {
return modelStore.get(modelKey(region, apiId, modelName))
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid model name specified", 404));
}
public List<Model> getModels(String region, String apiId) {
getRestApi(region, apiId);
String prefix = region + "::" + apiId + "::";
return modelStore.scan(k -> k.startsWith(prefix));
}
public void deleteModel(String region, String apiId, String modelName) {
getModel(region, apiId, modelName);
modelStore.delete(modelKey(region, apiId, modelName));
}
// ──────────────────────────── Custom Domains ────────────────────────────
public CustomDomain createDomainName(String region, Map<String, Object> request) {
@@ -685,6 +736,283 @@ public class ApiGatewayService {
apiStore.put(apiKey(region, apiId), api);
}
// ──────────────────────────── OpenAPI Import ────────────────────────────
public RestApi importRestApi(String region, String specBody) {
OpenAPI openAPI = parseOpenApiSpec(specBody);
String name = openAPI.getInfo() != null ? openAPI.getInfo().getTitle() : "Imported API";
String description = openAPI.getInfo() != null ? openAPI.getInfo().getDescription() : null;
Map<String, Object> request = new HashMap<>();
request.put("name", name);
request.put("description", description);
RestApi api = createRestApi(region, request);
applyOpenApiSpec(region, api.getId(), openAPI);
LOG.infov("Imported REST API from OpenAPI spec: {0} ({1})", name, api.getId());
return api;
}
public RestApi putRestApi(String region, String apiId, String mode, String specBody) {
// Note: mode=merge is accepted but treated as overwrite (merge semantics not yet implemented)
RestApi api = getRestApi(region, apiId);
OpenAPI openAPI = parseOpenApiSpec(specBody);
// Delete all non-root resources
List<ApiGatewayResource> existing = getResources(region, apiId);
for (ApiGatewayResource r : existing) {
if (!"/".equals(r.getPath())) {
deleteResource(region, apiId, r.getId());
}
}
// Clear methods on root resource
ApiGatewayResource root = existing.stream()
.filter(r -> "/".equals(r.getPath())).findFirst().orElse(null);
if (root != null) {
root.setResourceMethods(new HashMap<>());
resourceStore.put(resourceKey(region, apiId, root.getId()), root);
}
// Clear existing models and validators
String prefix = region + "::" + apiId + "::";
modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);
requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);
// Update API metadata from spec
if (openAPI.getInfo() != null) {
if (openAPI.getInfo().getTitle() != null) api.setName(openAPI.getInfo().getTitle());
if (openAPI.getInfo().getDescription() != null) api.setDescription(openAPI.getInfo().getDescription());
apiStore.put(apiKey(region, apiId), api);
}
applyOpenApiSpec(region, apiId, openAPI);
LOG.infov("Updated REST API from OpenAPI spec: {0} ({1})", api.getName(), apiId);
return api;
}
private OpenAPI parseOpenApiSpec(String specBody) {
SwaggerParseResult result = new io.swagger.parser.OpenAPIParser().readContents(specBody, null, null);
if (result.getOpenAPI() == null) {
String errors = result.getMessages() != null ? String.join(", ", result.getMessages()) : "unknown error";
throw new AwsException("BadRequestException", "Failed to parse OpenAPI spec: " + errors, 400);
}
return result.getOpenAPI();
}
@SuppressWarnings("unchecked")
private void applyOpenApiSpec(String region, String apiId, OpenAPI openAPI) {
// Import schemas as Models
if (openAPI.getComponents() != null && openAPI.getComponents().getSchemas() != null) {
for (var schemaEntry : openAPI.getComponents().getSchemas().entrySet()) {
String schemaName = schemaEntry.getKey();
var schema = schemaEntry.getValue();
Map<String, Object> modelReq = new HashMap<>();
modelReq.put("name", schemaName);
modelReq.put("contentType", "application/json");
try {
// Use swagger's own JSON serializer to produce clean JSON Schema
modelReq.put("schema", io.swagger.v3.core.util.Json.mapper().writeValueAsString(schema));
} catch (Exception e) {
modelReq.put("schema", "{}");
}
createModel(region, apiId, modelReq);
}
}
// Import x-amazon-apigateway-request-validators as RequestValidators
Map<String, String> validatorNameToId = new HashMap<>();
Map<String, Object> topExtensions = openAPI.getExtensions();
if (topExtensions != null) {
Map<String, Object> validators = (Map<String, Object>) topExtensions
.get("x-amazon-apigateway-request-validators");
if (validators != null) {
for (var entry : validators.entrySet()) {
String validatorName = entry.getKey();
Map<String, Object> validatorDef = (Map<String, Object>) entry.getValue();
Map<String, Object> valReq = new HashMap<>();
valReq.put("name", validatorName);
valReq.put("validateRequestBody",
Boolean.TRUE.equals(validatorDef.get("validateRequestBody")));
valReq.put("validateRequestParameters",
Boolean.TRUE.equals(validatorDef.get("validateRequestParameters")));
RequestValidator rv = createRequestValidator(region, apiId, valReq);
validatorNameToId.put(validatorName, rv.getId());
}
}
// API-level default validator
String defaultValidator = (String) topExtensions.get("x-amazon-apigateway-request-validator");
if (defaultValidator != null && validatorNameToId.containsKey(defaultValidator)) {
validatorNameToId.put("__default__", validatorNameToId.get(defaultValidator));
}
}
if (openAPI.getPaths() == null) return;
// Find the root resource
List<ApiGatewayResource> resources = getResources(region, apiId);
ApiGatewayResource rootResource = resources.stream()
.filter(r -> "/".equals(r.getPath())).findFirst().orElse(null);
if (rootResource == null) return;
// Map of full path → resource ID for creating nested resources
Map<String, String> pathToResourceId = new HashMap<>();
pathToResourceId.put("/", rootResource.getId());
for (Map.Entry<String, PathItem> pathEntry : openAPI.getPaths().entrySet()) {
String path = pathEntry.getKey();
PathItem pathItem = pathEntry.getValue();
// Ensure all intermediate path segments exist
String resourceId = ensureResourcePath(region, apiId, path, pathToResourceId);
// Create methods for each operation on this path
var operations = pathItem.readOperationsMap();
if (operations == null) continue;
for (var opEntry : operations.entrySet()) {
String httpMethod = opEntry.getKey().name().toUpperCase();
var operation = opEntry.getValue();
// Create the method
Map<String, Object> methodRequest = new HashMap<>();
methodRequest.put("authorizationType", "NONE");
// Link request models from operation requestBody
if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {
Map<String, String> requestModels = new HashMap<>();
for (var contentEntry : operation.getRequestBody().getContent().entrySet()) {
String contentType = contentEntry.getKey();
var mediaType = contentEntry.getValue();
if (mediaType.getSchema() != null && mediaType.getSchema().get$ref() != null) {
String ref = mediaType.getSchema().get$ref();
// Extract model name from #/components/schemas/ModelName
String modelName = ref.substring(ref.lastIndexOf('/') + 1);
requestModels.put(contentType, modelName);
}
}
if (!requestModels.isEmpty()) {
methodRequest.put("requestModels", requestModels);
}
}
// Map OpenAPI parameters to requestParameters
if (operation.getParameters() != null && !operation.getParameters().isEmpty()) {
Map<String, Boolean> requestParameters = new HashMap<>();
for (var param : operation.getParameters()) {
String location = switch (param.getIn()) {
case "query" -> "method.request.querystring." + param.getName();
case "header" -> "method.request.header." + param.getName();
case "path" -> "method.request.path." + param.getName();
default -> null;
};
if (location != null) {
requestParameters.put(location, param.getRequired() != null && param.getRequired());
}
}
if (!requestParameters.isEmpty()) {
methodRequest.put("requestParameters", requestParameters);
}
}
// Link request validator (operation-level overrides API-level default)
String opValidator = null;
if (operation.getExtensions() != null) {
opValidator = (String) operation.getExtensions()
.get("x-amazon-apigateway-request-validator");
}
if (opValidator != null && validatorNameToId.containsKey(opValidator)) {
methodRequest.put("requestValidatorId", validatorNameToId.get(opValidator));
} else if (validatorNameToId.containsKey("__default__")) {
methodRequest.put("requestValidatorId", validatorNameToId.get("__default__"));
}
putMethod(region, apiId, resourceId, httpMethod, methodRequest);
// Extract x-amazon-apigateway-integration extension
Map<String, Object> integrationExt = null;
if (operation.getExtensions() != null) {
integrationExt = (Map<String, Object>) operation.getExtensions()
.get("x-amazon-apigateway-integration");
}
if (integrationExt != null) {
applyIntegration(region, apiId, resourceId, httpMethod, integrationExt);
}
}
}
}
private String ensureResourcePath(String region, String apiId, String path,
Map<String, String> pathToResourceId) {
if (pathToResourceId.containsKey(path)) {
return pathToResourceId.get(path);
}
// Split path into segments and create each one
String[] segments = path.split("/");
StringBuilder currentPath = new StringBuilder();
String parentId = pathToResourceId.get("/");
for (int i = 1; i < segments.length; i++) {
String segment = segments[i];
if (segment.isEmpty()) continue;
currentPath.append("/").append(segment);
String fullPath = currentPath.toString();
if (!pathToResourceId.containsKey(fullPath)) {
Map<String, Object> request = new HashMap<>();
request.put("pathPart", segment);
ApiGatewayResource resource = createResource(region, apiId, parentId, request);
pathToResourceId.put(fullPath, resource.getId());
}
parentId = pathToResourceId.get(fullPath);
}
return parentId;
}
@SuppressWarnings("unchecked")
private void applyIntegration(String region, String apiId, String resourceId,
String httpMethod, Map<String, Object> integrationExt) {
Map<String, Object> integrationRequest = new HashMap<>();
integrationRequest.put("type", integrationExt.get("type"));
integrationRequest.put("httpMethod", integrationExt.get("httpMethod"));
integrationRequest.put("uri", integrationExt.get("uri"));
integrationRequest.put("passthroughBehavior", integrationExt.get("passthroughBehavior"));
Map<String, String> reqParams = (Map<String, String>) integrationExt.get("requestParameters");
if (reqParams != null) integrationRequest.put("requestParameters", reqParams);
Map<String, String> reqTemplates = (Map<String, String>) integrationExt.get("requestTemplates");
if (reqTemplates != null) integrationRequest.put("requestTemplates", reqTemplates);
putIntegration(region, apiId, resourceId, httpMethod, integrationRequest);
// Process integration responses
Map<String, Object> responses = (Map<String, Object>) integrationExt.get("responses");
if (responses != null) {
for (Map.Entry<String, Object> respEntry : responses.entrySet()) {
String selectionPattern = respEntry.getKey();
Map<String, Object> respDef = (Map<String, Object>) respEntry.getValue();
String statusCode = String.valueOf(respDef.getOrDefault("statusCode", "200"));
String pattern = "default".equals(selectionPattern) ? "" : selectionPattern;
Map<String, Object> irRequest = new HashMap<>();
irRequest.put("selectionPattern", pattern);
irRequest.put("responseParameters", respDef.get("responseParameters"));
irRequest.put("responseTemplates", respDef.get("responseTemplates"));
putIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode, irRequest);
// Ensure method response exists for this status code
putMethodResponse(region, apiId, resourceId, httpMethod, statusCode, new HashMap<>());
}
}
}
// ──────────────────────────── Key helpers ────────────────────────────
private String apiKey(String region, String apiId) {
@@ -711,6 +1039,10 @@ public class ApiGatewayService {
return region + "::" + apiId + "::" + validatorId;
}
private String modelKey(String region, String apiId, String modelName) {
return region + "::" + apiId + "::" + modelName;
}
private String apiKeyGlobalKey(String region, String apiKeyId) {
return region + "::" + apiKeyId;
}
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
/**
* Routes API Gateway AWS integration requests to the correct internal service handler.
*
* <p>Parses integration URIs of the form
* {@code arn:aws:apigateway:{region}:{service}:action/{ActionName}}
* and dispatches to the matching JSON handler.
*/
@ApplicationScoped
public class AwsServiceRouter {
private static final Logger LOG = Logger.getLogger(AwsServiceRouter.class);
private final StepFunctionsJsonHandler stepFunctionsHandler;
private final DynamoDbJsonHandler dynamoDbHandler;
private final SqsJsonHandler sqsHandler;
private final SnsJsonHandler snsHandler;
private final EventBridgeHandler eventBridgeHandler;
private final SsmJsonHandler ssmHandler;
private final KinesisJsonHandler kinesisHandler;
private final CloudWatchLogsHandler logsHandler;
private final CloudWatchMetricsJsonHandler metricsHandler;
private final SecretsManagerJsonHandler secretsManagerHandler;
private final KmsJsonHandler kmsHandler;
private final CognitoJsonHandler cognitoHandler;
private final AcmJsonHandler acmHandler;
@Inject
public AwsServiceRouter(StepFunctionsJsonHandler stepFunctionsHandler,
DynamoDbJsonHandler dynamoDbHandler,
SqsJsonHandler sqsHandler,
SnsJsonHandler snsHandler,
EventBridgeHandler eventBridgeHandler,
SsmJsonHandler ssmHandler,
KinesisJsonHandler kinesisHandler,
CloudWatchLogsHandler logsHandler,
CloudWatchMetricsJsonHandler metricsHandler,
SecretsManagerJsonHandler secretsManagerHandler,
KmsJsonHandler kmsHandler,
CognitoJsonHandler cognitoHandler,
AcmJsonHandler acmHandler) {
this.stepFunctionsHandler = stepFunctionsHandler;
this.dynamoDbHandler = dynamoDbHandler;
this.sqsHandler = sqsHandler;
this.snsHandler = snsHandler;
this.eventBridgeHandler = eventBridgeHandler;
this.ssmHandler = ssmHandler;
this.kinesisHandler = kinesisHandler;
this.logsHandler = logsHandler;
this.metricsHandler = metricsHandler;
this.secretsManagerHandler = secretsManagerHandler;
this.kmsHandler = kmsHandler;
this.cognitoHandler = cognitoHandler;
this.acmHandler = acmHandler;
}
/**
* Parsed components of an API Gateway AWS integration URI.
*/
public record IntegrationTarget(String region, String service, String action) {}
/**
* Parses an integration URI like
* {@code arn:aws:apigateway:us-east-1:states:action/StartExecution}.
*
* @return parsed target, or null if the URI format is not recognized
*/
public IntegrationTarget parseIntegrationUri(String uri) {
if (uri == null || !uri.startsWith("arn:aws:apigateway:")) {
return null;
}
// arn:aws:apigateway:{region}:{service}:action/{Action}
String[] parts = uri.split(":");
if (parts.length < 6) {
return null;
}
String region = parts[3];
String service = parts[4];
// parts[5] should be "action/{ActionName}"
String actionPart = parts[5];
if (!actionPart.startsWith("action/")) {
return null;
}
String action = actionPart.substring("action/".length());
return new IntegrationTarget(region, service, action);
}
/**
* Dispatches to the appropriate service handler.
*
* @param service the AWS service name from the URI (e.g., "states", "dynamodb")
* @param action the action name (e.g., "StartExecution", "PutItem")
* @param requestBody the JSON request body
* @param region the AWS region
* @return the service response
*/
public Response invoke(String service, String action, JsonNode requestBody, String region) {
LOG.debugv("AWS integration dispatch: {0}:{1} in {2}", service, action, region);
try {
return switch (service) {
case "states" -> stepFunctionsHandler.handle(action, requestBody, region);
case "dynamodb" -> dynamoDbHandler.handle(action, requestBody, region);
case "sqs" -> sqsHandler.handle(action, requestBody, region);
case "sns" -> snsHandler.handle(action, requestBody, region);
case "events" -> eventBridgeHandler.handle(action, requestBody, region);
case "ssm" -> ssmHandler.handle(action, requestBody, region);
case "kinesis" -> kinesisHandler.handle(action, requestBody, region);
case "logs" -> logsHandler.handle(action, requestBody, region);
case "monitoring" -> metricsHandler.handle(action, requestBody, region);
case "secretsmanager" -> secretsManagerHandler.handle(action, requestBody, region);
case "kms" -> kmsHandler.handle(action, requestBody, region);
case "cognito-idp" -> cognitoHandler.handle(action, requestBody, region);
case "acm" -> acmHandler.handle(action, requestBody, region);
default -> throw new AwsException("UnknownService",
"Unsupported AWS service integration: " + service, 400);
};
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("InternalError",
e.getMessage() != null ? e.getMessage() : "Service invocation failed", 500);
}
}
}
@@ -0,0 +1,283 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* Evaluates AWS API Gateway VTL (Velocity Template Language) mapping templates.
*
* <p>Provides the standard API Gateway context variables:
* {@code $input}, {@code $util}, {@code $context}, {@code $stageVariables}.
*/
@ApplicationScoped
public class VtlTemplateEngine {
private final VelocityEngine engine;
private final ObjectMapper objectMapper;
@Inject
public VtlTemplateEngine(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.engine = new VelocityEngine();
engine.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
engine.setProperty(RuntimeConstants.RUNTIME_LOG_NAME, "io.github.hectorvent.floci.vtl");
engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "string");
engine.setProperty("resource.loader.string.class",
"org.apache.velocity.runtime.resource.loader.StringResourceLoader");
engine.init();
}
/**
* Evaluates a VTL template with the given request context.
*
* @param template the VTL template string
* @param ctx the request context
* @return the evaluated template output
*/
public String evaluate(String template, VtlContext ctx) {
if (template == null || template.isEmpty()) {
return ctx.body() != null ? ctx.body() : "";
}
VelocityContext vc = new VelocityContext();
vc.put("input", new InputVariable(ctx, objectMapper));
vc.put("util", new UtilVariable(objectMapper));
vc.put("context", buildContextMap(ctx));
vc.put("stageVariables", ctx.stageVariables() != null ? ctx.stageVariables() : Map.of());
StringWriter writer = new StringWriter();
engine.evaluate(vc, writer, "apigw-template", template);
return writer.toString();
}
private Map<String, Object> buildContextMap(VtlContext ctx) {
Map<String, Object> map = new HashMap<>();
map.put("requestId", ctx.requestId());
map.put("stage", ctx.stage());
map.put("httpMethod", ctx.httpMethod());
map.put("resourcePath", ctx.resourcePath());
map.put("accountId", ctx.accountId());
Map<String, String> identity = new HashMap<>();
identity.put("sourceIp", "127.0.0.1");
map.put("identity", identity);
return map;
}
// ────────── Context variable classes ──────────
/**
* Request context for VTL evaluation.
*/
public record VtlContext(
String body,
Map<String, String> headers,
Map<String, String> queryParams,
Map<String, String> pathParams,
String stage,
String httpMethod,
String resourcePath,
String requestId,
String accountId,
Map<String, String> stageVariables
) {}
/**
* The {@code $input} variable available in API Gateway VTL templates.
*/
public static class InputVariable {
private final VtlContext ctx;
private final ObjectMapper objectMapper;
public InputVariable(VtlContext ctx, ObjectMapper objectMapper) {
this.ctx = ctx;
this.objectMapper = objectMapper;
}
/** Returns the raw request body. */
public String body() {
return ctx.body() != null ? ctx.body() : "";
}
/**
* Evaluates a simple JSON path against the request body and returns the result as a JSON string.
* Supports {@code '$'} (whole body) and dot-notation paths like {@code '$.foo.bar'}.
*/
public String json(String path) {
if (ctx.body() == null || ctx.body().isEmpty()) {
return "{}";
}
try {
JsonNode root = objectMapper.readTree(ctx.body());
JsonNode target = resolvePath(root, path);
return objectMapper.writeValueAsString(target);
} catch (Exception e) {
return ctx.body();
}
}
/**
* Evaluates a simple JSON path and returns the result as an object navigable in VTL.
*/
public Object path(String path) {
if (ctx.body() == null || ctx.body().isEmpty()) {
return Map.of();
}
try {
JsonNode root = objectMapper.readTree(ctx.body());
JsonNode target = resolvePath(root, path);
return objectMapper.convertValue(target, Object.class);
} catch (Exception e) {
return Map.of();
}
}
/** Searches all parameter types for the given name (querystring, path, header). */
public String params(String paramName) {
if (ctx.queryParams() != null && ctx.queryParams().containsKey(paramName)) {
return ctx.queryParams().get(paramName);
}
if (ctx.pathParams() != null && ctx.pathParams().containsKey(paramName)) {
return ctx.pathParams().get(paramName);
}
if (ctx.headers() != null && ctx.headers().containsKey(paramName)) {
return ctx.headers().get(paramName);
}
return "";
}
/** Returns request parameters organized by type. */
public Map<String, Map<String, String>> params() {
Map<String, Map<String, String>> params = new HashMap<>();
params.put("querystring", ctx.queryParams() != null ? ctx.queryParams() : Map.of());
params.put("path", ctx.pathParams() != null ? ctx.pathParams() : Map.of());
params.put("header", ctx.headers() != null ? ctx.headers() : Map.of());
return params;
}
static JsonNode resolvePath(JsonNode root, String path) {
if (path == null || "$".equals(path)) {
return root;
}
String normalized = path.startsWith("$.") ? path.substring(2) : path;
JsonNode current = root;
for (String segment : normalized.split("\\.")) {
if (current == null || current.isMissingNode()) break;
// Handle array indexing: "items[0]" or "[0]"
int bracketIdx = segment.indexOf('[');
if (bracketIdx >= 0) {
if (bracketIdx > 0) {
current = current.path(segment.substring(0, bracketIdx));
}
// Extract all indices: [0][1] etc.
String rest = segment.substring(bracketIdx);
while (rest.startsWith("[")) {
int close = rest.indexOf(']');
if (close < 0) break;
int index = Integer.parseInt(rest.substring(1, close));
current = current.path(index);
rest = rest.substring(close + 1);
}
} else {
current = current.path(segment);
}
}
return current;
}
}
/**
* The {@code $util} variable available in API Gateway VTL templates.
*/
public static class UtilVariable {
private final ObjectMapper objectMapper;
public UtilVariable(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
/**
* Escapes a string using EcmaScript/JavaScript string rules.
* Matches AWS API Gateway behavior (Apache Commons Lang escapeEcmaScript).
* Escapes: backslash, double/single quotes, forward slash, control chars,
* and non-ASCII characters (outside 0x20-0x7E) as unicode escape sequences.
*/
public String escapeJavaScript(String s) {
if (s == null) return "";
StringBuilder sb = new StringBuilder(s.length() + 16);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\\' -> sb.append("\\\\");
case '"' -> sb.append("\\\"");
case '\'' -> sb.append("\\'");
case '/' -> sb.append("\\/");
case '\b' -> sb.append("\\b");
case '\t' -> sb.append("\\t");
case '\n' -> sb.append("\\n");
case '\f' -> sb.append("\\f");
case '\r' -> sb.append("\\r");
default -> {
if (c < 0x20 || c > 0x7E) {
sb.append("\\u").append(String.format("%04x", (int) c));
} else {
sb.append(c);
}
}
}
}
return sb.toString();
}
/** URL-encodes a string. */
public String urlEncode(String s) {
if (s == null) return "";
return URLEncoder.encode(s, StandardCharsets.UTF_8);
}
/** URL-decodes a string. */
public String urlDecode(String s) {
if (s == null) return "";
return URLDecoder.decode(s, StandardCharsets.UTF_8);
}
/** Base64-encodes a string. */
public String base64Encode(String s) {
if (s == null) return "";
return Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8));
}
/** Base64-decodes a string. */
public String base64Decode(String s) {
if (s == null) return "";
return new String(Base64.getDecoder().decode(s), StandardCharsets.UTF_8);
}
/** Parses a JSON string into a Map/List structure navigable in VTL. */
public Object parseJson(String s) {
if (s == null || s.isEmpty()) return Map.of();
try {
return objectMapper.readValue(s, Object.class);
} catch (JsonProcessingException e) {
return Map.of();
}
}
}
}
@@ -11,6 +11,8 @@ public class Integration {
private String type; // MOCK, HTTP, AWS, HTTP_PROXY, AWS_PROXY
private String uri;
private String httpMethod;
private String passthroughBehavior = "WHEN_NO_MATCH"; // WHEN_NO_MATCH, WHEN_NO_TEMPLATES, NEVER
private Map<String, String> requestParameters = new HashMap<>(); // integration.request.* → method.request.*
private Map<String, String> requestTemplates = new HashMap<>();
private Map<String, IntegrationResponse> integrationResponses = new HashMap<>();
@@ -38,6 +40,22 @@ public class Integration {
this.httpMethod = httpMethod;
}
public String getPassthroughBehavior() {
return passthroughBehavior;
}
public void setPassthroughBehavior(String passthroughBehavior) {
this.passthroughBehavior = passthroughBehavior != null ? passthroughBehavior : "WHEN_NO_MATCH";
}
public Map<String, String> getRequestParameters() {
return requestParameters;
}
public void setRequestParameters(Map<String, String> requestParameters) {
this.requestParameters = requestParameters != null ? requestParameters : new HashMap<>();
}
public Map<String, String> getRequestTemplates() {
return requestTemplates;
}
@@ -11,7 +11,9 @@ public class MethodConfig {
private String httpMethod;
private String authorizationType;
private String authorizerId;
private String requestValidatorId;
private Map<String, Boolean> requestParameters = new HashMap<>();
private Map<String, String> requestModels = new HashMap<>();
private Map<String, MethodResponse> methodResponses = new HashMap<>();
private Integration methodIntegration;
@@ -24,6 +26,14 @@ public class MethodConfig {
public String getAuthorizerId() { return authorizerId; }
public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; }
public String getRequestValidatorId() { return requestValidatorId; }
public void setRequestValidatorId(String requestValidatorId) { this.requestValidatorId = requestValidatorId; }
public Map<String, String> getRequestModels() { return requestModels; }
public void setRequestModels(Map<String, String> requestModels) {
this.requestModels = requestModels != null ? requestModels : new HashMap<>();
}
public Map<String, Boolean> getRequestParameters() { return requestParameters; }
public void setRequestParameters(Map<String, Boolean> requestParameters) {
this.requestParameters = requestParameters != null ? requestParameters : new HashMap<>();
@@ -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; }
}
@@ -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()));
}
@@ -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();
}
@@ -138,7 +138,7 @@ public class StepFunctionsService {
return;
}
exec.setStatus("ABORTED");
exec.setStopDate(System.currentTimeMillis() / 1000L);
exec.setStopDate(System.currentTimeMillis() / 1000.0);
executionStore.put(arn, exec);
List<HistoryEvent> history = historyCache.getOrDefault(arn, new ArrayList<>());
@@ -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; }
@@ -9,20 +9,20 @@ import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class HistoryEvent {
private long id;
private long timestamp;
private double timestamp;
private String type;
private Long previousEventId;
private Map<String, Object> details;
public HistoryEvent() {
this.timestamp = System.currentTimeMillis() / 1000L;
this.timestamp = System.currentTimeMillis() / 1000.0;
}
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public long getTimestamp() { return timestamp; }
public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
public double getTimestamp() { return timestamp; }
public void setTimestamp(double timestamp) { this.timestamp = timestamp; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
@@ -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; }
}