Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(apigateway): honour the remaining REST integration settings (#3434)

Abhigyaf7565dff3e2b
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index e46888039d..39bfb084cc 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -238,7 +238,6 @@ These management-plane operations have no handler in v1. Calls will return `404`
- Authorizer testing: `TestInvokeAuthorizer`
- Model templates: `GetModelTemplate`
- Documentation parts and versions (the entire family, 10 operations)
-- VPC Links (5 operations)
- Client Certificates (5 operations)
- `GetExport` / `ImportDocumentationParts`
@@ -263,6 +262,35 @@ Passthrough keeps repeated values repeated, in both directions: `?tag=a&tag=b` r
- **Request** — the body is the rendered `requestTemplates` entry selected by the incoming `Content-Type` (falling back to the type without its charset), subject to `passthroughBehavior` (`NEVER` and `WHEN_NO_TEMPLATES` return `415`). Only headers and query parameters named by `integration.request.*` mappings are forwarded; unmapped inbound headers are **not** passed through — that passthrough is `HTTP_PROXY`'s job.
- **Response** — the backend's reply runs through the method's integration responses. As in AWS, `selectionPattern` is matched against the backend's **HTTP status code** (for `AWS`/Lambda integrations it is matched against the error message instead), so `"5\\d{2}"` on a `502` integration response remaps any backend `5xx` to `502`. The matched response's `responseTemplates` render the body, `responseParameters` map `integration.response.header.*` (case-insensitively) or `integration.response.body.<jsonpath>` onto `method.response.header.*`, and `$context.responseOverride` assignments take precedence. With no integration responses configured, the backend's status and body are relayed as-is.
+### Integration Settings
+
+`PutIntegration` persists and `GetIntegration` returns the full configuration, including the mapping templates and integration responses that IaC tools diff against:
+
+| Field | Behaviour |
+| --- | --- |
+| `requestParameters` / `requestTemplates` | Applied at invoke time and returned on read-back |
+| `passthroughBehavior` | `NEVER` and `WHEN_NO_TEMPLATES` reject an unmatched Content-Type with `415` |
+| `timeoutInMillis` | Honoured; defaults to AWS's 29,000 ms. Values below 50 are rejected. The 29s ceiling is an edge-optimized limit, so Regional APIs may exceed it |
+| `tlsConfig.insecureSkipVerification` | Honoured, with AWS's semantics: it stops requiring the backend certificate to be issued by a trusted CA, so a private-CA or self-signed backend is reachable, but expiration, hostname and the presence of a root certificate authority are still checked |
+| `contentHandling` | `CONVERT_TO_TEXT` base64-encodes a binary request for mapping templates; `CONVERT_TO_BINARY` base64-decodes a text request before sending it |
+| `connectionType` / `connectionId` | `VPC_LINK` requires `connectionId` to name an existing, available VPC link; an unknown link yields `502` |
+| `cacheNamespace` / `cacheKeyParameters` | Form the response cache key (see below) |
+| `credentials` | Persisted and returned. Floci does not enforce IAM, so the role is not actually assumed |
+
+Integration responses additionally accept `contentHandling`, applied as an output conversion after response templates.
+
+### Binary Payloads
+
+Set `binaryMediaTypes` on the RestApi to mark content types as binary. Entries are matched exactly, ignoring any charset parameter; `*/*` is the one wildcard entry, and it covers every content type. A subtype wildcard such as `image/*` is not expanded, matching AWS, which documents only `*/*` and otherwise names one exact media type at a time. A binary request body reaches an `AWS_PROXY` (Lambda) integration base64-encoded with `isBase64Encoded: true`; previously it was read as a UTF-8 string, which corrupted it. For non-proxy integrations, pair `binaryMediaTypes` with `contentHandling` as above.
+
+### Caching
+
+Response caching needs both switches AWS requires: `cacheClusterEnabled` on the stage and `caching/enabled` on the method (or the `*/*` wildcard) via `UpdateStage` patch operations. Entries are keyed by the integration's `cacheNamespace` and the values of its `cacheKeyParameters`, and by nothing else: AWS lets separate resources share a `cacheNamespace` precisely so they can return the same cached data, so the method and request path are deliberately not part of the key. The namespace defaults to the resource id, which keeps resources that did not opt into sharing separate. Entries expire after `caching/ttlInSeconds` (default 300s), and only successful (`< 400`) responses are stored. There is no real cache cluster — `cacheClusterSize` is recorded and reported but has no effect on capacity.
+
+### VPC Links
+
+The five REST VPC Link operations (`CreateVpcLink`, `GetVpcLink`, `GetVpcLinks`, `UpdateVpcLink`, `DeleteVpcLink`) are emulated at `/vpclinks`. `CreateVpcLink` requires a name and at least one target ARN, answers `202`, and provisions the link as `AVAILABLE` immediately rather than transitioning through `PENDING`. Since Floci has no real VPC, a valid link routes straight to the integration URI; what is enforced is that the link exists and is available. `UpdateVpcLink` follows AWS's patch-operation table: only `replace` on `/name` and `/description` is accepted, and any other operation or path returns `BadRequestException` rather than being applied or silently ignored.
+
### Examples
```bash
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
index d39b2161d5..f357858b24 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
@@ -1431,6 +1431,80 @@ public class ApiGatewayController {
}
}
+ // ──────────────────────────── VPC Links (v1) ────────────────────────────
+
+ @POST
+ @Path("/vpclinks")
+ public Response createV1VpcLink(@Context HttpHeaders headers, 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.VpcLink link =
+ service.createVpcLink(region, request);
+ // AWS provisions asynchronously and answers 202 Accepted.
+ return Response.status(202).entity(toV1VpcLinkNode(link).toString())
+ .type(MediaType.APPLICATION_JSON).build();
+ } catch (IOException e) {
+ throw new AwsException("BadRequestException", e.getMessage(), 400);
+ }
+ }
+
+ @GET
+ @Path("/vpclinks")
+ public Response getV1VpcLinks(@Context HttpHeaders headers) {
+ String region = regionResolver.resolveRegion(headers);
+ ObjectNode result = objectMapper.createObjectNode();
+ ArrayNode items = result.putArray("item");
+ service.getVpcLinks(region).forEach(l -> items.add(toV1VpcLinkNode(l)));
+ return Response.ok(result.toString()).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ @GET
+ @Path("/vpclinks/{vpcLinkId}")
+ public Response getV1VpcLink(@Context HttpHeaders headers,
+ @PathParam("vpcLinkId") String vpcLinkId) {
+ String region = regionResolver.resolveRegion(headers);
+ return Response.ok(toV1VpcLinkNode(service.getVpcLink(region, vpcLinkId)).toString())
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+
+ @PATCH
+ @Path("/vpclinks/{vpcLinkId}")
+ public Response updateV1VpcLink(@Context HttpHeaders headers,
+ @PathParam("vpcLinkId") String vpcLinkId,
+ String body) {
+ String region = regionResolver.resolveRegion(headers);
+ io.github.hectorvent.floci.services.apigateway.model.VpcLink link =
+ service.updateVpcLink(region, vpcLinkId, parsePatchOperations(body));
+ return Response.ok(toV1VpcLinkNode(link).toString()).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ @DELETE
+ @Path("/vpclinks/{vpcLinkId}")
+ public Response deleteV1VpcLink(@Context HttpHeaders headers,
+ @PathParam("vpcLinkId") String vpcLinkId) {
+ String region = regionResolver.resolveRegion(headers);
+ service.deleteVpcLink(region, vpcLinkId);
+ return Response.accepted().build();
+ }
+
+ private ObjectNode toV1VpcLinkNode(io.github.hectorvent.floci.services.apigateway.model.VpcLink link) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("id", link.getId());
+ node.put("name", link.getName());
+ if (link.getDescription() != null) node.put("description", link.getDescription());
+ ArrayNode arns = node.putArray("targetArns");
+ link.getTargetArns().forEach(arns::add);
+ node.put("status", link.getStatus());
+ if (link.getStatusMessage() != null) node.put("statusMessage", link.getStatusMessage());
+ if (!link.getTags().isEmpty()) {
+ ObjectNode tags = node.putObject("tags");
+ link.getTags().forEach(tags::put);
+ }
+ return node;
+ }
+
// ──────────────────────────── VPC Links (v2) ────────────────────────────
@POST
@@ -2032,6 +2106,11 @@ public class ApiGatewayController {
node.set("tags", tagsNode);
}
+ if (api.getBinaryMediaTypes() != null && !api.getBinaryMediaTypes().isEmpty()) {
+ ArrayNode binaryTypes = node.putArray("binaryMediaTypes");
+ api.getBinaryMediaTypes().forEach(binaryTypes::add);
+ }
+
EndpointConfiguration epConfig = api.getEndpointConfiguration();
if (epConfig == null) {
epConfig = new EndpointConfiguration();
@@ -2106,6 +2185,21 @@ public class ApiGatewayController {
node.put("httpMethod", i.getHttpMethod());
node.put("uri", i.getUri());
node.put("passthroughBehavior", i.getPassthroughBehavior());
+ if (i.getContentHandling() != null) node.put("contentHandling", i.getContentHandling());
+ if (i.getTimeoutInMillis() != null) node.put("timeoutInMillis", i.getTimeoutInMillis());
+ if (i.getConnectionType() != null) node.put("connectionType", i.getConnectionType());
+ if (i.getConnectionId() != null) node.put("connectionId", i.getConnectionId());
+ if (i.getCredentials() != null) node.put("credentials", i.getCredentials());
+ if (i.getCacheNamespace() != null) node.put("cacheNamespace", i.getCacheNamespace());
+ if (!i.getCacheKeyParameters().isEmpty()) {
+ ArrayNode keys = node.putArray("cacheKeyParameters");
+ i.getCacheKeyParameters().forEach(keys::add);
+ }
+ if (i.getTlsConfig() != null) {
+ node.putObject("tlsConfig")
+ .put("insecureSkipVerification", i.getTlsConfig().isInsecureSkipVerification());
+ }
+ // Mapping configuration is what IaC tools diff against — omitting it read as drift.
if (!i.getRequestParameters().isEmpty()) {
ObjectNode params = node.putObject("requestParameters");
i.getRequestParameters().forEach(params::put);
@@ -2126,6 +2220,7 @@ public class ApiGatewayController {
ObjectNode node = objectMapper.createObjectNode();
node.put("statusCode", r.statusCode());
node.put("selectionPattern", r.selectionPattern());
+ if (r.contentHandling() != null) node.put("contentHandling", r.contentHandling());
if (r.responseParameters() != null && !r.responseParameters().isEmpty()) {
ObjectNode params = node.putObject("responseParameters");
r.responseParameters().forEach(params::put);
@@ -2152,6 +2247,9 @@ public class ApiGatewayController {
if (s.getDescription() != null) node.put("description", s.getDescription());
node.put("createdDate", s.getCreatedDate());
node.put("lastUpdatedDate", s.getLastUpdatedDate());
+ node.put("cacheClusterEnabled", s.isCacheClusterEnabled());
+ node.put("cacheClusterStatus", s.getCacheClusterStatus());
+ if (s.getCacheClusterSize() != null) node.put("cacheClusterSize", s.getCacheClusterSize());
if (!s.getVariables().isEmpty()) {
ObjectNode vars = node.putObject("variables");
s.getVariables().forEach(vars::put);
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
index 600d14e6b5..7906e717da 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.apigateway.model.GatewayResponseType;
import io.github.hectorvent.floci.services.apigateway.model.Integration;
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
+import io.github.hectorvent.floci.services.apigateway.model.MethodSetting;
import io.github.hectorvent.floci.services.apigateway.model.Stage;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
@@ -433,7 +434,20 @@ public class ApiGatewayExecuteController {
"No integration type configured");
}
- return switch (integrationType.toUpperCase(Locale.ROOT)) {
+ Response vpcLinkError = validateVpcLink(scope, region, integration);
+ if (vpcLinkError != null) return vpcLinkError;
+
+ String cacheKey = cacheKeyFor(stage, matched, httpMethod, path, integration, headers, uriInfo);
+ if (cacheKey != null) {
+ CachedResponse cached = responseCache.get(cacheKey);
+ if (cached != null && cached.expiresAt() > System.currentTimeMillis()) {
+ LOG.debugv("execute-api: cache hit for {0} {1}/{2}{3}", httpMethod, apiId, stageName, path);
+ return fromCache(cached);
+ }
+ responseCache.remove(cacheKey);
+ }
+
+ Response response = switch (integrationType.toUpperCase(Locale.ROOT)) {
case "AWS_PROXY" -> invokeProxy(scope, region, apiId, httpMethod, path, proxy, stageName,
matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey,
iamIdentity);
@@ -441,13 +455,20 @@ public class ApiGatewayExecuteController {
matched, integration, headers, uriInfo, body, authorizerResult);
case "HTTP_PROXY" -> invokeHttpProxy(scope, apiId, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body);
- case "HTTP" -> invokeHttpIntegration(scope, apiId, httpMethod, path, proxy, stageName,
+ case "HTTP" -> invokeHttpIntegration(scope, region, apiId, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body, authorizerResult);
case "MOCK" -> invokeMock(scope, region, httpMethod, path, stageName,
matched, integration, headers, uriInfo, body, authorizerResult);
default -> gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
"Unsupported integration type: " + integration.getType());
};
+
+ // Only successful responses are cached — AWS does not serve an error from the cache.
+ if (cacheKey != null && response.getStatus() < 400) {
+ responseCache.put(cacheKey,
+ snapshotForCache(response, cacheTtlSeconds(methodSettingFor(stage, matched.getPath(), httpMethod))));
+ }
+ return response;
}
private void applyApiOwnerContext(ApiGatewayV2Service.ApiOwner owner) {
@@ -585,7 +606,7 @@ public class ApiGatewayExecuteController {
httpMethod, apiId, stageName, path, uri);
io.github.hectorvent.floci.services.apigatewayv2.proxy.ProxyResult result =
- httpProxyInvoker.invoke(target, ctx);
+ httpProxyInvoker.invoke(target, ctx, proxyOptions(integration));
Response.ResponseBuilder rb = Response.status(result.statusCode());
if (result.body() != null) rb.entity(result.body());
@@ -601,6 +622,192 @@ public class ApiGatewayExecuteController {
return rb.build();
}
+ // ──────────────────────────── Response caching ────────────────────────────
+
+ /** AWS's default integration cache TTL when a method enables caching without naming one. */
+ private static final int DEFAULT_CACHE_TTL_SECONDS = 300;
+
+ private record CachedResponse(int status, Object entity, Map<String, String> headers, long expiresAt) {}
+
+ private final Map<String, CachedResponse> responseCache = new ConcurrentHashMap<>();
+
+ /**
+ * The cache key for this request, or {@code null} when caching does not apply. AWS caches only
+ * when the stage has a cache cluster <em>and</em> the method — or the wildcard entry — enables
+ * caching. The key is the integration's {@code cacheNamespace} plus the values of its
+ * {@code cacheKeyParameters}, so two requests differing only in an uncached parameter share an
+ * entry, which is exactly the behaviour that surprises people in production.
+ *
+ * <p>Nothing identifying the resource goes into the key beyond the namespace itself. AWS
+ * documents {@code cacheNamespace} as shareable across resources precisely so those resources
+ * can return the same cached data; mixing the method and request path back in would mean two
+ * resources could never share an entry, which is the setting's whole purpose. The namespace
+ * defaults to the resource id, so resources that did not opt into sharing stay separate.
+ */
+ private String cacheKeyFor(Stage stage, ApiGatewayResource resource, String httpMethod,
+ String path, Integration integration, HttpHeaders headers, UriInfo uriInfo) {
+ if (stage == null || !stage.isCacheClusterEnabled()) return null;
+ MethodSetting setting = methodSettingFor(stage, resource.getPath(), httpMethod);
+ if (setting == null || !setting.isCachingEnabled()) return null;
+
+ StringBuilder key = new StringBuilder();
+ key.append(integration.getCacheNamespace() != null
+ ? integration.getCacheNamespace() : resource.getId());
+ for (String param : integration.getCacheKeyParameters()) {
+ key.append('|').append(param).append('=')
+ .append(cacheKeyParameterValue(param, headers, uriInfo, resource.getPath(), path));
+ }
+ return key.toString();
+ }
+
+ /**
+ * The method's own settings, falling back to the stage-wide wildcard entry. Settings are keyed
+ * by the resource path without its leading slash ({@code pets/GET}), matching what AWS reports.
+ */
+ private static MethodSetting methodSettingFor(Stage stage, String resourcePath, String httpMethod) {
+ String normalized = resourcePath != null && resourcePath.startsWith("/")
+ ? resourcePath.substring(1) : resourcePath;
+ MethodSetting exact = stage.getMethodSettings().get(normalized + "/" + httpMethod);
+ return exact != null ? exact : stage.getMethodSettings().get("*/*");
+ }
+
+ private String cacheKeyParameterValue(String param, HttpHeaders headers, UriInfo uriInfo,
+ String resourcePath, String path) {
+ if (param.startsWith("method.request.querystring.")) {
+ return uriInfo.getQueryParameters()
+ .getFirst(param.substring("method.request.querystring.".length()));
+ }
+ if (param.startsWith("method.request.header.")) {
+ return headers.getHeaderString(param.substring("method.request.header.".length()));
+ }
+ if (param.startsWith("method.request.path.")) {
+ return extractPathParams(resourcePath, path)
+ .get(param.substring("method.request.path.".length()));
+ }
+ return null;
+ }
+
+ private static int cacheTtlSeconds(MethodSetting setting) {
+ int ttl = setting != null ? setting.getCacheTtlInSeconds() : 0;
+ return ttl > 0 ? ttl : DEFAULT_CACHE_TTL_SECONDS;
+ }
+
+ private static CachedResponse snapshotForCache(Response response, int ttlSeconds) {
+ Map<String, String> headers = new LinkedHashMap<>();
+ response.getStringHeaders().forEach((name, values) -> {
+ if (!values.isEmpty()) headers.put(name, values.get(0));
+ });
+ return new CachedResponse(response.getStatus(), response.getEntity(), headers,
+ System.currentTimeMillis() + ttlSeconds * 1000L);
+ }
+
+ private static Response fromCache(CachedResponse cached) {
+ Response.ResponseBuilder rb = Response.status(cached.status()).entity(cached.entity());
+ cached.headers().forEach(rb::header);
+ return rb.build();
+ }
+
+ // ──────────────────────────── VPC Link ────────────────────────────
+
+ /**
+ * Checks that a {@code VPC_LINK} integration names a VPC link that exists and is available,
+ * returning an error response when it does not and {@code null} when the request may proceed.
+ *
+ * <p>Floci has no real VPC, so a valid link routes straight to the integration URI. What this
+ * catches is the misconfiguration AWS also rejects: pointing at a link that was deleted or
+ * never created, which would otherwise silently behave like a plain internet integration.
+ */
+ private Response validateVpcLink(GatewayResponseScope scope, String region, Integration integration) {
+ if (!"VPC_LINK".equalsIgnoreCase(integration.getConnectionType())) {
+ return null;
+ }
+ String connectionId = integration.getConnectionId();
+ if (connectionId == null || connectionId.isBlank()) {
+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,
+ "VPC_LINK integration is missing a connectionId");
+ }
+ try {
+ io.github.hectorvent.floci.services.apigateway.model.VpcLink link =
+ apiGatewayService.getVpcLink(region, connectionId);
+ if (!"AVAILABLE".equalsIgnoreCase(link.getStatus())) {
+ return Response.status(502)
+ .entity(jsonMessage("VPC link is not available: " + link.getStatus()))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+ return null;
+ } catch (AwsException e) {
+ LOG.warnv("VPC_LINK integration references unknown link {0} in {1}", connectionId, region);
+ return Response.status(502)
+ .entity(jsonMessage("Invalid VPC link identifier specified: " + connectionId))
+ .type(MediaType.APPLICATION_JSON).build();
+ }
+ }
+
+ // ──────────────────────────── Binary payloads ────────────────────────────
+
+ /**
+ * True when {@code contentType} matches one of the API's configured {@code binaryMediaTypes}.
+ * The charset parameter is ignored when comparing.
+ *
+ * <p>Entries are compared literally apart from the catch-all <code>*&#47;*</code>, which is the
+ * only wildcard AWS documents concretely: "To support all binary media types, specify
+ * <code>*&#47;*</code>." A subtype wildcard such as {@code image/*} is not expanded, because
+ * nothing in the AWS documentation says API Gateway treats it as a pattern: every example there
+ * names one exact media type at a time, and the browser walkthrough tells you to register the
+ * concrete {@code image/webp} even though the request's {@code Accept} header carries
+ * {@code image/*}.
+ *
+ * @see <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html">Enabling binary support using the console</a>
+ */
+ private boolean isBinaryMediaType(String region, String apiId, String contentType) {
+ if (contentType == null || contentType.isBlank()) return false;
+ List<String> binaryTypes;
+ try {
+ binaryTypes = apiGatewayService.getRestApi(region, apiId).getBinaryMediaTypes();
+ } catch (AwsException e) {
+ return false;
+ }
+ if (binaryTypes == null || binaryTypes.isEmpty()) return false;
+
+ String base = contentType.contains(";")
+ ? contentType.substring(0, contentType.indexOf(';')).trim() : contentType.trim();
+ return binaryTypes.stream().anyMatch(configured -> mediaTypeMatches(configured, base));
+ }
+
+ private static boolean mediaTypeMatches(String configured, String contentType) {
+ if (configured == null) return false;
+ String candidate = configured.trim();
+ return "*/*".equals(candidate) || candidate.equalsIgnoreCase(contentType);
+ }
+
+ /**
+ * The request body as mapping templates should see it. {@code CONVERT_TO_TEXT} base64-encodes a
+ * binary payload so it survives being handled as a string; otherwise the bytes are read as UTF-8.
+ */
+ private static String templateBody(Integration integration, byte[] body, boolean binaryRequest) {
+ if (body == null || body.length == 0) return null;
+ if (binaryRequest && "CONVERT_TO_TEXT".equalsIgnoreCase(integration.getContentHandling())) {
+ return Base64.getEncoder().encodeToString(body);
+ }
+ return new String(body, StandardCharsets.UTF_8);
+ }
+
+ /**
+ * The payload actually sent to the backend. {@code CONVERT_TO_BINARY} treats the rendered body
+ * as base64 and decodes it; anything else is sent as UTF-8 bytes.
+ */
+ private static byte[] outgoingPayload(Integration integration, String renderedBody) {
+ if (renderedBody == null) return new byte[0];
+ if ("CONVERT_TO_BINARY".equalsIgnoreCase(integration.getContentHandling())) {
+ try {
+ return Base64.getDecoder().decode(renderedBody.trim());
+ } catch (IllegalArgumentException e) {
+ LOG.debugv("CONVERT_TO_BINARY: body is not valid base64, sending it unchanged");
+ }
+ }
+ return renderedBody.getBytes(StandardCharsets.UTF_8);
+ }
+
// ──────────────────────────── HTTP (non-proxy) ────────────────────────────
/**
@@ -613,7 +820,8 @@ public class ApiGatewayExecuteController {
* {@code selectionPattern} is matched against the backend's HTTP status code (for
* {@code AWS}/Lambda integrations it is matched against the error message instead).
*/
- private Response invokeHttpIntegration(GatewayResponseScope scope, String apiId, String httpMethod, String path,
+ private Response invokeHttpIntegration(GatewayResponseScope scope, String region, String apiId,
+ String httpMethod, String path,
String proxy, String stageName, ApiGatewayResource resource,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body,
@@ -625,7 +833,9 @@ public class ApiGatewayExecuteController {
}
String requestId = UUID.randomUUID().toString();
- String bodyStr = body != null && body.length > 0 ? new String(body, StandardCharsets.UTF_8) : null;
+ boolean binaryRequest = isBinaryMediaType(region, apiId,
+ headers.getHeaderString(HttpHeaders.CONTENT_TYPE));
+ String bodyStr = templateBody(integration, body, binaryRequest);
Map<String, String> headerMap = new HashMap<>();
for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {
@@ -691,8 +901,7 @@ public class ApiGatewayExecuteController {
target.setIntegrationUri(uri);
target.setIntegrationMethod(integration.getHttpMethod());
- byte[] payload = transformedBody != null
- ? transformedBody.getBytes(StandardCharsets.UTF_8) : new byte[0];
+ byte[] payload = outgoingPayload(integration, transformedBody);
io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx =
new io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext(
@@ -705,7 +914,7 @@ public class ApiGatewayExecuteController {
LOG.debugv("execute-api: {0} {1}/{2}{3} → HTTP {4}", httpMethod, apiId, stageName, path, uri);
io.github.hectorvent.floci.services.apigatewayv2.proxy.ProxyResult result =
- httpProxyInvoker.invoke(target, ctx);
+ httpProxyInvoker.invoke(target, ctx, proxyOptions(integration));
String responseBodyStr = result.body() != null
? new String(result.body(), StandardCharsets.UTF_8) : "";
@@ -730,8 +939,8 @@ public class ApiGatewayExecuteController {
// For HTTP integrations selectionPattern is matched against the backend's status code.
return mapIntegrationResponse(integration, String.valueOf(result.statusCode()),
- responseBodyStr, result.statusCode(), responseHeaders, responseMappingCtx,
- defaultContentType);
+ responseBodyStr, result.body(), result.statusCode(), responseHeaders,
+ responseMappingCtx, defaultContentType);
}
private boolean isGatewayGeneratedProxyFailure(InvokeResult result) {
@@ -1130,8 +1339,13 @@ public class ApiGatewayExecuteController {
}
if (body != null && body.length > 0) {
- event.put("body", new String(body));
- event.put("isBase64Encoded", false);
+ // A payload whose content type is in the API's binaryMediaTypes must reach the function
+ // base64-encoded; reading it as a UTF-8 string corrupts it.
+ boolean binary = isBinaryMediaType(region, apiId, headers.getHeaderString(HttpHeaders.CONTENT_TYPE));
+ event.put("body", binary
+ ? Base64.getEncoder().encodeToString(body)
+ : new String(body, StandardCharsets.UTF_8));
+ event.put("isBase64Encoded", binary);
} else {
event.putNull("body");
event.put("isBase64Encoded", false);
@@ -1316,11 +1530,11 @@ public class ApiGatewayExecuteController {
// 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));
+ if (!e.getValue().isEmpty()) headerMap.put(e.getKey(), e.getValue().getFirst());
}
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));
+ if (!e.getValue().isEmpty()) queryMap.put(e.getKey(), e.getValue().getFirst());
}
Map<String, String> pathMap = new HashMap<>();
pathMap.putAll(extractPathParams(resource.getPath(), path));
@@ -1513,12 +1727,13 @@ public class ApiGatewayExecuteController {
"Unsupported Media Type");
Map<String, String> requestTemplates = integration.getRequestTemplates();
+ RequestTemplateResult requestTemplateResult = new RequestTemplateResult(bodyStr != null ? bodyStr : "", incomingContentType, null);
if (requestTemplates == null || requestTemplates.isEmpty()) {
// No templates defined at all
if ("NEVER".equalsIgnoreCase(integration.getPassthroughBehavior())) {
return new RequestTemplateResult(null, null, unsupportedMediaType);
}
- return new RequestTemplateResult(bodyStr != null ? bodyStr : "", incomingContentType, null);
+ return requestTemplateResult;
}
// Try exact match first, then without charset: "application/json; charset=utf-8" → "application/json"
@@ -1544,7 +1759,7 @@ public class ApiGatewayExecuteController {
return new RequestTemplateResult(null, null, unsupportedMediaType);
}
// WHEN_NO_MATCH (default) — passthrough
- return new RequestTemplateResult(bodyStr != null ? bodyStr : "", incomingContentType, null);
+ return requestTemplateResult;
}
/**
@@ -1562,6 +1777,16 @@ public class ApiGatewayExecuteController {
Map<String, String> integrationResponseHeaders,
VtlTemplateEngine.VtlContext responseMappingCtx,
String defaultContentType) {
+ return mapIntegrationResponse(integration, selectionMatchString, responseBodyStr, null,
+ fallbackStatus, integrationResponseHeaders, responseMappingCtx, defaultContentType);
+ }
+
+ private Response mapIntegrationResponse(Integration integration, String selectionMatchString,
+ String responseBodyStr, byte[] rawResponseBody,
+ int fallbackStatus,
+ Map<String, String> integrationResponseHeaders,
+ VtlTemplateEngine.VtlContext responseMappingCtx,
+ String defaultContentType) {
Map<String, IntegrationResponse> integrationResponses = integration.getIntegrationResponses();
IntegrationResponse matchedResponse = null;
IntegrationResponse defaultResponse = null;
@@ -1617,8 +1842,25 @@ public class ApiGatewayExecuteController {
finalStatus = templateResult.statusOverride();
}
+ // Integration-response contentHandling is an output conversion, applied after templates:
+ // CONVERT_TO_TEXT base64-encodes a binary payload for the caller, CONVERT_TO_BINARY decodes
+ // a base64 text payload back to bytes.
+ Object entity = finalBody;
+ String responseContentHandling = matchedResponse != null ? matchedResponse.contentHandling() : null;
+ if ("CONVERT_TO_TEXT".equalsIgnoreCase(responseContentHandling)) {
+ byte[] source = templateResult == null && rawResponseBody != null
+ ? rawResponseBody : finalBody.getBytes(StandardCharsets.UTF_8);
+ entity = Base64.getEncoder().encodeToString(source);
+ } else if ("CONVERT_TO_BINARY".equalsIgnoreCase(responseContentHandling)) {
+ try {
+ entity = Base64.getDecoder().decode(finalBody.trim());
+ } catch (IllegalArgumentException e) {
+ LOG.debugv("CONVERT_TO_BINARY: response body is not valid base64, returning it unchanged");
+ }
+ }
+
Response.ResponseBuilder rb = Response.status(finalStatus)
- .entity(finalBody);
+ .entity(entity);
String contentType = null;
@@ -2083,6 +2325,17 @@ public class ApiGatewayExecuteController {
private final io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker httpProxyInvoker =
new io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker();
+ /** REST integrations default to AWS's 29s and may opt out of backend TLS verification. */
+ private static io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker.ProxyOptions
+ proxyOptions(Integration integration) {
+ long timeoutMillis = integration.getTimeoutInMillis() != null
+ ? integration.getTimeoutInMillis() : 29_000L;
+ boolean insecure = integration.getTlsConfig() != null
+ && integration.getTlsConfig().isInsecureSkipVerification();
+ return new io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpProxyInvoker.ProxyOptions(
+ java.time.Duration.ofMillis(timeoutMillis), insecure);
+ }
+
private Response dispatchHttpProxyV2(io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration,
Route route, String httpMethod, String path,
HttpHeaders headers, UriInfo uriInfo, byte[] body,
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index 528eca9c52..ce4678cfbf 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -34,6 +34,7 @@ import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.MethodSetting;
+import io.github.hectorvent.floci.services.apigateway.model.VpcLink;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
@@ -82,6 +83,7 @@ public class ApiGatewayService {
private final StorageBackend<String, RequestValidator> requestValidatorStore;
private final StorageBackend<String, GatewayResponse> gatewayResponseStore;
private final StorageBackend<String, Model> modelStore;
+ private final StorageBackend<String, VpcLink> vpcLinkStore;
private final StorageBackend<String, Account> accountStore;
private final StorageBackend<String, CustomDomain> domainStore;
private final StorageBackend<String, BasePathMapping> basePathMappingStore;
@@ -136,6 +138,9 @@ public class ApiGatewayService {
this.modelStore = storageFactory.create("apigateway", "apigateway-models.json",
new TypeReference<>() {
});
+ this.vpcLinkStore = storageFactory.create("apigateway", "apigateway-vpclinks.json",
+ new TypeReference<>() {
+ });
this.accountStore = storageFactory.create("apigateway", "apigateway-account.json",
new TypeReference<>() {
});
@@ -178,22 +183,19 @@ public class ApiGatewayService {
"Unsupported patch operation: " + opType, 400);
}
- switch (path) {
- case "/cloudwatchRoleArn" -> {
- if ("remove".equals(opType)) {
- copy.setCloudwatchRoleArn(null);
- } else {
- copy.setCloudwatchRoleArn(value);
- }
+ if (path.equals("/cloudwatchRoleArn")) {
+ if ("remove".equals(opType)) {
+ copy.setCloudwatchRoleArn(null);
+ } else {
+ copy.setCloudwatchRoleArn(value);
}
- default -> {
- if (path.startsWith("/throttleSettings")) {
- throw new AwsException("BadRequestException",
- "/throttleSettings value cannot be changed this way", 400);
- }
+ } else {
+ if (path.startsWith("/throttleSettings")) {
throw new AwsException("BadRequestException",
- "Unsupported patch path: " + path, 400);
+ "/throttleSettings value cannot be changed this way", 400);
}
+ throw new AwsException("BadRequestException",
+ "Unsupported patch path: " + path, 400);
}
}
}
@@ -226,6 +228,11 @@ public class ApiGatewayService {
api.setCreatedDate(System.currentTimeMillis() / 1000L);
api.setTags(ReservedTags.stripApiGatewayReservedTags(tags));
+ if (request.get("binaryMediaTypes") instanceof List<?> binaryTypes) {
+ api.setBinaryMediaTypes(binaryTypes.stream()
+ .filter(String.class::isInstance).map(String.class::cast).toList());
+ }
+
EndpointConfiguration endpointConfiguration = new EndpointConfiguration();
if (request.get(EPC_KEY) instanceof Map<?, ?> epMap) {
epMap.forEach((k, v) -> {
@@ -529,6 +536,34 @@ public class ApiGatewayService {
integration.setPassthroughBehavior((String) request.get("passthroughBehavior"));
}
+ integration.setContentHandling((String) request.get("contentHandling"));
+ integration.setCredentials((String) request.get("credentials"));
+ integration.setCacheNamespace((String) request.get("cacheNamespace"));
+ if (request.get("connectionType") != null) {
+ integration.setConnectionType((String) request.get("connectionType"));
+ }
+ integration.setConnectionId((String) request.get("connectionId"));
+
+ if (request.get("timeoutInMillis") instanceof Number timeout) {
+ // AWS accepts 50ms upward; the 29s ceiling applies only to edge-optimized APIs, and
+ // Regional/private APIs (Floci's default) may exceed it, so only the floor is enforced.
+ if (timeout.intValue() < 50) {
+ throw new AwsException("BadRequestException",
+ "Invalid timeout value: " + timeout.intValue(), 400);
+ }
+ integration.setTimeoutInMillis(timeout.intValue());
+ }
+
+ if (request.get("cacheKeyParameters") instanceof List<?> cacheKeys) {
+ integration.setCacheKeyParameters(cacheKeys.stream()
+ .filter(String.class::isInstance).map(String.class::cast).toList());
+ }
+
+ if (request.get("tlsConfig") instanceof Map<?, ?> tls) {
+ integration.setTlsConfig(new Integration.TlsConfig(
+ Boolean.TRUE.equals(tls.get("insecureSkipVerification"))));
+ }
+
@SuppressWarnings("unchecked")
Map<String, String> reqParams = (Map<String, String>) request.get("requestParameters");
if (reqParams != null) integration.setRequestParameters(reqParams);
@@ -574,7 +609,8 @@ public class ApiGatewayService {
IntegrationResponse ir = new IntegrationResponse(statusCode, selectionPattern,
respParams != null ? respParams : new HashMap<>(),
- respTemplates != null ? respTemplates : new HashMap<>());
+ respTemplates != null ? respTemplates : new HashMap<>(),
+ (String) request.get("contentHandling"));
integration.getIntegrationResponses().put(statusCode, ir);
resourceStore.put(resourceKey(region, apiId, resourceId),
@@ -734,6 +770,11 @@ public class ApiGatewayService {
Map<String, String> variables = (Map<String, String>) request.get("variables");
if (variables != null) stage.setVariables(variables);
+ if (Boolean.TRUE.equals(request.get("cacheClusterEnabled"))) {
+ stage.setCacheClusterEnabled(true);
+ stage.setCacheClusterSize((String) request.getOrDefault("cacheClusterSize", "0.5"));
+ }
+
stageStore.put(stageKey(region, apiId, stageName), stage);
LOG.infov("Created stage {0} for API {1}", stageName, apiId);
return stage;
@@ -3036,6 +3077,12 @@ public class ApiGatewayService {
integrationRequest.put("httpMethod", integrationExt.get("httpMethod"));
integrationRequest.put("uri", integrationExt.get("uri"));
integrationRequest.put("passthroughBehavior", integrationExt.get("passthroughBehavior"));
+ for (String field : List.of("contentHandling", "timeoutInMillis", "connectionType",
+ "connectionId", "credentials", "cacheNamespace", "cacheKeyParameters", "tlsConfig")) {
+ if (integrationExt.get(field) != null) {
+ integrationRequest.put(field, integrationExt.get(field));
+ }
+ }
Map<String, String> reqParams = (Map<String, String>) integrationExt.get("requestParameters");
if (reqParams != null) integrationRequest.put("requestParameters", reqParams);
@@ -3126,6 +3173,95 @@ public class ApiGatewayService {
return region + "::" + domainName + "::" + basePath;
}
+ // ──────────────────────────── VPC Links (v1) ────────────────────────────
+
+ public VpcLink createVpcLink(String region, Map<String, Object> request) {
+ String name = (String) request.get("name");
+ if (name == null || name.isBlank()) {
+ throw new AwsException("BadRequestException", "Vpc link name must be specified", 400);
+ }
+
+ @SuppressWarnings("unchecked")
+ List<String> targetArns = request.get("targetArns") instanceof List<?> arns
+ ? (List<String>) arns : List.of();
+ if (targetArns.isEmpty()) {
+ throw new AwsException("BadRequestException",
+ "At least one target ARN must be specified", 400);
+ }
+
+ VpcLink link = new VpcLink();
+ link.setId(shortId(10));
+ link.setName(name);
+ link.setDescription((String) request.get("description"));
+ link.setTargetArns(targetArns);
+ // Floci has no real VPC to provision against, so the link is immediately usable rather
+ // than transitioning PENDING → AVAILABLE as it does in AWS.
+ link.setStatus("AVAILABLE");
+
+ if (request.get("tags") instanceof Map<?, ?> tags) {
+ Map<String, String> stringTags = new HashMap<>();
+ tags.forEach((k, v) -> {
+ if (k != null && v != null) stringTags.put(k.toString(), v.toString());
+ });
+ link.setTags(stringTags);
+ }
+
+ vpcLinkStore.put(vpcLinkKey(region, link.getId()), link);
+ LOG.infov("Created VPC Link: {0} ({1}) in {2}", link.getName(), link.getId(), region);
+ return link;
+ }
+
+ public VpcLink getVpcLink(String region, String vpcLinkId) {
+ return vpcLinkStore.get(vpcLinkKey(region, vpcLinkId))
+ .orElseThrow(() -> new AwsException("NotFoundException", "Invalid VPC link identifier specified", 404));
+ }
+
+ public List<VpcLink> getVpcLinks(String region) {
+ return vpcLinkStore.scan(k -> k.startsWith(region + "::"));
+ }
+
+ /**
+ * AWS's patch-operation table for a VPC link supports only {@code replace}, and only on
+ * {@code /name} and {@code /description}. Applying anything else is an error rather than a
+ * no-op: silently accepting {@code op=remove,path=/name} would have set the name to the
+ * supplied value, and silently ignoring an unknown path would report success for a change that
+ * never happened.
+ */
+ public VpcLink updateVpcLink(String region, String vpcLinkId, List<Map<String, String>> patchOperations) {
+ VpcLink link = getVpcLink(region, vpcLinkId);
+ if (patchOperations != null) {
+ for (Map<String, String> op : patchOperations) {
+ String operation = op.get("op");
+ String path = op.get("path");
+ String value = op.get("value");
+ if (!"replace".equals(operation)) {
+ throw new AwsException("BadRequestException", "Unsupported operation", 400);
+ }
+ if (path == null) {
+ throw new AwsException("BadRequestException", "Missing path", 400);
+ }
+ switch (path) {
+ case "/name" -> link.setName(value);
+ case "/description" -> link.setDescription(value);
+ default -> throw new AwsException("BadRequestException",
+ "Invalid patch path '" + path + "' specified for op 'replace'. "
+ + "Must be one of: [/name, /description]", 400);
+ }
+ }
+ }
+ vpcLinkStore.put(vpcLinkKey(region, vpcLinkId), link);
+ return link;
+ }
+
+ public void deleteVpcLink(String region, String vpcLinkId) {
+ getVpcLink(region, vpcLinkId);
+ vpcLinkStore.delete(vpcLinkKey(region, vpcLinkId));
+ }
+
+ private String vpcLinkKey(String region, String vpcLinkId) {
+ return region + "::" + vpcLinkId;
+ }
+
private static String shortId(int length) {
return UUID.randomUUID().toString().replace("-", "").substring(0, length);
}
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 077a9234d4..4742b7c8f3 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
@@ -4,7 +4,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -15,10 +17,103 @@ public class Integration {
private String uri;
private String httpMethod;
private String passthroughBehavior = "WHEN_NO_MATCH"; // WHEN_NO_MATCH, WHEN_NO_TEMPLATES, NEVER
+ private String contentHandling; // CONVERT_TO_BINARY, CONVERT_TO_TEXT, or null to pass through
+ private Integer timeoutInMillis; // 50–29000; AWS caps REST integrations at 29s
+ private String connectionType = "INTERNET"; // INTERNET or VPC_LINK
+ private String connectionId; // VpcLink id when connectionType is VPC_LINK
+ private String credentials; // IAM role ARN assumed for AWS integrations
+ private String cacheNamespace;
+ private List<String> cacheKeyParameters = new ArrayList<>();
+ private TlsConfig tlsConfig;
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<>();
+ /** Integration TLS settings. {@code insecureSkipVerification} skips backend cert validation. */
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ @RegisterForReflection
+ public static class TlsConfig {
+ private boolean insecureSkipVerification;
+
+ public TlsConfig() {}
+
+ public TlsConfig(boolean insecureSkipVerification) {
+ this.insecureSkipVerification = insecureSkipVerification;
+ }
+
+ public boolean isInsecureSkipVerification() {
+ return insecureSkipVerification;
+ }
+
+ public void setInsecureSkipVerification(boolean insecureSkipVerification) {
+ this.insecureSkipVerification = insecureSkipVerification;
+ }
+ }
+
+ public String getContentHandling() {
+ return contentHandling;
+ }
+
+ public void setContentHandling(String contentHandling) {
+ this.contentHandling = contentHandling;
+ }
+
+ public Integer getTimeoutInMillis() {
+ return timeoutInMillis;
+ }
+
+ public void setTimeoutInMillis(Integer timeoutInMillis) {
+ this.timeoutInMillis = timeoutInMillis;
+ }
+
+ public String getConnectionType() {
+ return connectionType;
+ }
+
+ public void setConnectionType(String connectionType) {
+ this.connectionType = connectionType != null ? connectionType : "INTERNET";
+ }
+
+ public String getConnectionId() {
+ return connectionId;
+ }
+
+ public void setConnectionId(String connectionId) {
+ this.connectionId = connectionId;
+ }
+
+ public String getCredentials() {
+ return credentials;
+ }
+
+ public void setCredentials(String credentials) {
+ this.credentials = credentials;
+ }
+
+ public String getCacheNamespace() {
+ return cacheNamespace;
+ }
+
+ public void setCacheNamespace(String cacheNamespace) {
+ this.cacheNamespace = cacheNamespace;
+ }
+
+ public List<String> getCacheKeyParameters() {
+ return cacheKeyParameters;
+ }
+
+ public void setCacheKeyParameters(List<String> cacheKeyParameters) {
+ this.cacheKeyParameters = cacheKeyParameters != null ? cacheKeyParameters : new ArrayList<>();
+ }
+
+ public TlsConfig getTlsConfig() {
+ return tlsConfig;
+ }
+
+ public void setTlsConfig(TlsConfig tlsConfig) {
+ this.tlsConfig = tlsConfig;
+ }
+
public String getType() {
return type;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/IntegrationResponse.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/IntegrationResponse.java
index b0d2ab2e1c..d3266318c4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/IntegrationResponse.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/IntegrationResponse.java
@@ -12,5 +12,14 @@ public record IntegrationResponse(
String statusCode,
String selectionPattern,
Map<String, String> responseParameters,
- Map<String, String> responseTemplates
-) {}
+ Map<String, String> responseTemplates,
+ /** CONVERT_TO_BINARY, CONVERT_TO_TEXT, or null to pass the payload through unchanged. */
+ String contentHandling
+) {
+ /** Backwards-compatible factory for responses that specify no content handling. */
+ public IntegrationResponse(String statusCode, String selectionPattern,
+ Map<String, String> responseParameters,
+ Map<String, String> responseTemplates) {
+ this(statusCode, selectionPattern, responseParameters, responseTemplates, null);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java
index 3d19571be9..b22c250395 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/RestApi.java
@@ -4,7 +4,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -18,6 +20,16 @@ public class RestApi {
private String rootResourceId;
private Map<String, String> tags = new HashMap<>();
private EndpointConfiguration endpointConfiguration;
+ /** Content types treated as binary when applying integration contentHandling. */
+ private List<String> binaryMediaTypes = new ArrayList<>();
+
+ public List<String> getBinaryMediaTypes() {
+ return binaryMediaTypes;
+ }
+
+ public void setBinaryMediaTypes(List<String> binaryMediaTypes) {
+ this.binaryMediaTypes = binaryMediaTypes != null ? binaryMediaTypes : new ArrayList<>();
+ }
public String getId() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Stage.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Stage.java
index 0bb560ce84..550432f84e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Stage.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/Stage.java
@@ -16,6 +16,35 @@ public class Stage {
private String description;
private Map<String, String> variables = new HashMap<>();
private Map<String, MethodSetting> methodSettings = new HashMap<>();
+ /** Stage-level cache switch; a method's own cachingEnabled only applies when this is on. */
+ private boolean cacheClusterEnabled;
+ private String cacheClusterSize;
+ private String cacheClusterStatus = "NOT_AVAILABLE";
+
+ public boolean isCacheClusterEnabled() {
+ return cacheClusterEnabled;
+ }
+
+ public void setCacheClusterEnabled(boolean cacheClusterEnabled) {
+ this.cacheClusterEnabled = cacheClusterEnabled;
+ this.cacheClusterStatus = cacheClusterEnabled ? "AVAILABLE" : "NOT_AVAILABLE";
+ }
+
+ public String getCacheClusterSize() {
+ return cacheClusterSize;
+ }
+
+ public void setCacheClusterSize(String cacheClusterSize) {
+ this.cacheClusterSize = cacheClusterSize;
+ }
+
+ public String getCacheClusterStatus() {
+ return cacheClusterStatus;
+ }
+
+ public void setCacheClusterStatus(String cacheClusterStatus) {
+ this.cacheClusterStatus = cacheClusterStatus;
+ }
private long createdDate;
private long lastUpdatedDate;
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/VpcLink.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/VpcLink.java
new file mode 100644
index 0000000000..b948e3832a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/VpcLink.java
@@ -0,0 +1,87 @@
+package io.github.hectorvent.floci.services.apigateway.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A REST (v1) VPC Link: the private connection between an API and a Network Load Balancer, named
+ * by an integration's {@code connectionId} when its {@code connectionType} is {@code VPC_LINK}.
+ *
+ * <p>Distinct from the v2 {@code VpcLink}, which is described by subnets and security groups rather
+ * than by target ARNs.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@RegisterForReflection
+public class VpcLink {
+
+ private String id;
+ private String name;
+ private String description;
+ private List<String> targetArns = new ArrayList<>();
+ /** PENDING, AVAILABLE, DELETING or FAILED. */
+ private String status = "AVAILABLE";
+ private String statusMessage;
+ private Map<String, String> tags = new HashMap<>();
+
+ 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 List<String> getTargetArns() {
+ return targetArns;
+ }
+
+ public void setTargetArns(List<String> targetArns) {
+ this.targetArns = targetArns != null ? targetArns : new ArrayList<>();
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getStatusMessage() {
+ return statusMessage;
+ }
+
+ public void setStatusMessage(String statusMessage) {
+ this.statusMessage = statusMessage;
+ }
+
+ public Map<String, String> getTags() {
+ return tags;
+ }
+
+ public void setTags(Map<String, String> tags) {
+ this.tags = tags != null ? tags : new HashMap<>();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java
index b8ead7aace..ff1b5774fb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java
@@ -3,6 +3,11 @@ package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
import org.jboss.logging.Logger;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -15,6 +20,15 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.SecureRandom;
+import java.security.cert.CertPath;
+import java.security.cert.CertPathValidator;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.PKIXParameters;
+import java.security.cert.TrustAnchor;
+import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
@@ -48,6 +62,20 @@ public class HttpProxyInvoker {
private static final Set<String> RESTRICTED = Set.of(
"connection", "content-length", "expect", "host", "upgrade");
+ /**
+ * Per-integration transport settings.
+ *
+ * @param timeout how long to wait for the backend response
+ * @param insecureTls stop requiring the backend certificate to be issued by a trusted
+ * certificate authority, for an integration configured with
+ * {@code tlsConfig.insecureSkipVerification}. Expiration, hostname and the
+ * presence of a root certificate authority are still checked, as in AWS.
+ */
+ public record ProxyOptions(Duration timeout, boolean insecureTls) {
+ /** HTTP API (v2) defaults: 30s, certificates verified. */
+ public static final ProxyOptions DEFAULTS = new ProxyOptions(Duration.ofSeconds(30), false);
+ }
+
// Pin to HTTP/1.1: the default HTTP_2 setting attempts cleartext-HTTP/2 negotiation
// against http:// backends, which hangs against plain HTTP/1.1 servers (notably the
// in-JVM Vertx HttpServer used by ELBv2 listeners for HttpAlbIntegration).
@@ -57,9 +85,197 @@ public class HttpProxyInvoker {
.followRedirects(HttpClient.Redirect.NEVER)
.build();
+ /** Built on first use: an integration opting out of TLS verification is the exception. */
+ private volatile HttpClient insecureClient;
+
+ private HttpClient clientFor(ProxyOptions options) {
+ if (!options.insecureTls()) return client;
+ HttpClient existing = insecureClient;
+ if (existing != null) return existing;
+ synchronized (this) {
+ if (insecureClient == null) {
+ insecureClient = buildInsecureClient();
+ }
+ return insecureClient;
+ }
+ }
+
+ private HttpClient buildInsecureClient() {
+ try {
+ TrustManager[] trustManagers = {new CaIssuanceSkippingTrustManager()};
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(null, trustManagers, new SecureRandom());
+ // Hostname verification stays on. insecureSkipVerification waives only the "issued by a
+ // supported CA" check; AWS documents that it still verifies the hostname, so a
+ // certificate for the wrong host must fail here exactly as it would in AWS. Setting this
+ // explicitly matters: SSLParameters defaults the algorithm to null, so handing
+ // HttpClient a fresh instance without it would silently disable the check.
+ SSLParameters sslParameters = new SSLParameters();
+ sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
+ return HttpClient.newBuilder()
+ .version(HttpClient.Version.HTTP_1_1)
+ .connectTimeout(Duration.ofSeconds(10))
+ .followRedirects(HttpClient.Redirect.NEVER)
+ .sslContext(sslContext)
+ .sslParameters(sslParameters)
+ .build();
+ } catch (GeneralSecurityException e) {
+ LOG.warnv("Could not build insecure TLS client, falling back to verified: {0}", e.getMessage());
+ return client;
+ }
+ }
+
+ /**
+ * The trust behaviour {@code tlsConfig.insecureSkipVerification} actually buys in AWS: API
+ * Gateway stops checking that the endpoint's certificate was issued by a supported certificate
+ * authority, so private-CA and self-signed certificates are accepted, but it still performs
+ * basic certificate validation covering the expiration date, the hostname and the presence of a
+ * root certificate authority. A trust-all manager is looser than that, and looser in the
+ * direction that hides bugs: a backend whose certificate has expired, or whose chain is broken,
+ * would work locally and fail in AWS.
+ *
+ * <p>For anything beyond a lone self-signed certificate the chain goes through the platform's
+ * PKIX validator, anchored on the chain's own root, so the rules AWS keeps for a private
+ * certificate authority (cA=true together with keyUsage keyCertSign, pathLenConstraint, and
+ * name constraints on the intermediates) are enforced by the code that already implements them
+ * correctly. The root's own constraints are checked here instead, because PKIX treats a trust
+ * anchor as given and never reads its extensions.
+ *
+ * <p>Hostname verification is not done here, it is the SSL engine's endpoint identification.
+ */
+ private static final class CaIssuanceSkippingTrustManager implements X509TrustManager {
+
+ /** X509v3 Name Constraints, RFC 5280 §4.2.1.10. */
+ private static final String NAME_CONSTRAINTS_OID = "2.5.29.30";
+
+
+ /** Position of {@code keyCertSign} in the KeyUsage bit string, RFC 5280 §4.2.1.3. */
+ private static final int KEY_CERT_SIGN_BIT = 5;
+
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ // This manager only ever verifies a backend as a client would; it never authenticates
+ // an inbound peer. Accepting one silently would be a genuine trust-all.
+ throw new CertificateException("client certificates are not accepted by this proxy");
+ }
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ if (chain == null || chain.length == 0) {
+ throw new CertificateException("backend presented no certificate");
+ }
+
+ // Expiration (and not-yet-valid), for every certificate in the chain. PKIX exempts a
+ // trust anchor from this, and AWS does not, so it is checked here rather than left to
+ // the validator below.
+ for (X509Certificate certificate : chain) {
+ certificate.checkValidity();
+ }
+
+ // The chain has to terminate in a self-signed certificate: that trailing certificate is
+ // the "root certificate authority" whose presence AWS still requires. What is skipped is
+ // only whether that root is one we trust.
+ X509Certificate root = chain[chain.length - 1];
+ if (!root.getIssuerX500Principal().equals(root.getSubjectX500Principal())) {
+ throw new CertificateException(
+ "certificate chain does not terminate in a root certificate authority: "
+ + root.getSubjectX500Principal());
+ }
+
+ if (chain.length == 1) {
+ // A lone self-signed certificate is its own root, and is the plain
+ // self-signed-server case the setting exists to enable, so CA extensions are not
+ // demanded of it: requiring them would reject what AWS documents as supported.
+ // The signature still has to verify, so the certificate cannot have been tampered
+ // with in flight.
+ verifySignedBy(root, root);
+ return;
+ }
+
+ // A longer chain means a real certificate authority issued the leaf, and AWS states two
+ // constraints such a root "must satisfy": the x509 extension keyUsage must have
+ // keyCertSign, and the x509 extension basicConstraints must have CA:TRUE. These are
+ // checked here rather than left to the validator below, which treats the trust anchor
+ // as given and never looks at its extensions.
+ //
+ // A root carrying no keyUsage extension at all fails the first of those. Generic PKIX
+ // would read the missing extension as leaving the key unrestricted (RFC 5280 §4.2.1.3),
+ // but API Gateway states the extension as a requirement on the root rather than a bit
+ // to inspect when present, so the looser reading would accept a certificate authority
+ // that real API Gateway turns away.
+ if (root.getBasicConstraints() < 0) {
+ throw new CertificateException(
+ "root certificate is not a certificate authority (BasicConstraints cA=false): "
+ + root.getSubjectX500Principal());
+ }
+ boolean[] keyUsage = root.getKeyUsage();
+ if (keyUsage == null) {
+ throw new CertificateException(
+ "root certificate carries no keyUsage extension, which API Gateway requires "
+ + "on a private certificate authority: " + root.getSubjectX500Principal());
+ }
+ if (keyUsage.length <= KEY_CERT_SIGN_BIT || !keyUsage[KEY_CERT_SIGN_BIT]) {
+ throw new CertificateException(
+ "root certificate is not permitted to sign certificates "
+ + "(keyUsage without keyCertSign): " + root.getSubjectX500Principal());
+ }
+
+ // Name constraints on the root itself cannot be honoured: the platform validator refuses
+ // to process constraints handed to it with a trust anchor, as opposed to ones it reads
+ // from a certificate inside the path, so a root carrying them can be rejected but never
+ // evaluated. Rejecting is both the safe direction and the documented one: AWS tells
+ // operators hitting validation errors under insecureSkipVerification to check that their
+ // CA certificates carry no Name Constraints extension and to reissue them without it.
+ // Constraints on an intermediate sit in the path proper and are enforced normally.
+ if (root.getExtensionValue(NAME_CONSTRAINTS_OID) != null) {
+ throw new CertificateException(
+ "root certificate carries X509v3 Name Constraints, which cannot be enforced "
+ + "for a privately trusted root: " + root.getSubjectX500Principal());
+ }
+
+ // The rest of the rules AWS keeps are the ordinary PKIX ones. Handing them to the
+ // platform validator, with this chain's own root as the trust anchor, is precisely the
+ // "stop checking that the root is one we trust, keep checking everything else"
+ // semantic: chain signatures, basicConstraints and keyCertSign on any intermediates,
+ // pathLenConstraint, and the X509v3 name constraints AWS documents it enforces.
+ try {
+ CertPath path = CertificateFactory.getInstance("X.509")
+ .generateCertPath(List.of(chain).subList(0, chain.length - 1));
+ PKIXParameters parameters = new PKIXParameters(
+ Set.of(new TrustAnchor(root, null)));
+ // Revocation would mean CRL or OCSP fetches for an issuer we are deliberately not
+ // trusting: AWS lists expiration, hostname and the presence of a root as what
+ // survives insecureSkipVerification, not revocation.
+ parameters.setRevocationEnabled(false);
+ CertPathValidator.getInstance("PKIX").validate(path, parameters);
+ } catch (GeneralSecurityException e) {
+ throw new CertificateException("certificate chain is not valid: " + e.getMessage(), e);
+ }
+ }
+
+ private static void verifySignedBy(X509Certificate certificate, X509Certificate issuer)
+ throws CertificateException {
+ try {
+ certificate.verify(issuer.getPublicKey());
+ } catch (GeneralSecurityException e) {
+ throw new CertificateException("certificate chain signature does not verify: "
+ + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[0];
+ }
+ }
+
private final RequestParameterMapper mapper = new RequestParameterMapper(new ContextValueResolver());
public ProxyResult invoke(Integration integration, RequestContext ctx) {
+ return invoke(integration, ctx, ProxyOptions.DEFAULTS);
+ }
+
+ public ProxyResult invoke(Integration integration, RequestContext ctx, ProxyOptions options) {
// 1. Resolve target URL from IntegrationUri template + captured path params
String resolvedUrl = PathTemplateResolver.resolve(integration.getIntegrationUri(), ctx.pathParams());
@@ -94,7 +310,7 @@ public class HttpProxyInvoker {
String finalUrl = buildFinalUrl(builder);
if (hasHeader(builder, "Host") && finalUrl.startsWith("http://")) {
try {
- return invokeHttpWithHostOverride(finalUrl, method, builder);
+ return invokeHttpWithHostOverride(finalUrl, method, builder, options.timeout());
} catch (Exception e) {
LOG.warnv("HTTP_PROXY backend call failed: {0}", e.getMessage());
return errorResult("Bad Gateway: " + e.getMessage());
@@ -105,7 +321,7 @@ public class HttpProxyInvoker {
try {
hrb = HttpRequest.newBuilder()
.uri(URI.create(finalUrl))
- .timeout(Duration.ofSeconds(30));
+ .timeout(options.timeout());
} catch (IllegalArgumentException e) {
LOG.warnv("HTTP_PROXY: invalid target URL: {0}", e.getMessage());
return errorResult("Bad Gateway: invalid target URL: " + e.getMessage());
@@ -130,7 +346,8 @@ public class HttpProxyInvoker {
}
try {
- HttpResponse<byte[]> resp = client.send(hrb.build(), HttpResponse.BodyHandlers.ofByteArray());
+ HttpResponse<byte[]> resp =
+ clientFor(options).send(hrb.build(), HttpResponse.BodyHandlers.ofByteArray());
Map<String, List<String>> respHeaders = new LinkedHashMap<>();
for (Map.Entry<String, List<String>> e : resp.headers().map().entrySet()) {
if (HOP_BY_HOP.contains(e.getKey().toLowerCase())) continue;
@@ -156,7 +373,8 @@ public class HttpProxyInvoker {
return null;
}
- private static ProxyResult invokeHttpWithHostOverride(String finalUrl, String method, ProxyRequestBuilder builder)
+ private static ProxyResult invokeHttpWithHostOverride(String finalUrl, String method,
+ ProxyRequestBuilder builder, Duration timeout)
throws IOException {
URI uri = URI.create(finalUrl);
int port = uri.getPort() == -1 ? 80 : uri.getPort();
@@ -170,7 +388,7 @@ public class HttpProxyInvoker {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(uri.getHost(), port), 10_000);
- socket.setSoTimeout(30_000);
+ socket.setSoTimeout((int) Math.min(timeout.toMillis(), Integer.MAX_VALUE));
OutputStream out = socket.getOutputStream();
byte[] body = builder.body() == null ? new byte[0] : builder.body();
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayBinaryContentHandlingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayBinaryContentHandlingTest.java
new file mode 100644
index 0000000000..fa20a3a5a8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayBinaryContentHandlingTest.java
@@ -0,0 +1,284 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+/**
+ * Covers {@code binaryMediaTypes} on the RestApi together with {@code contentHandling} on the
+ * integration and its integration responses, AWS's mechanism for moving binary payloads through a
+ * REST API.
+ *
+ * <p>{@code CONVERT_TO_TEXT} base64-encodes a binary payload so it can be handled as a string;
+ * {@code CONVERT_TO_BINARY} decodes a base64 text payload back into bytes. Both are applied on the
+ * way out of the stage they belong to: request-side for the integration, response-side for the
+ * integration response.
+ */
+@QuarkusTest
+class ApiGatewayBinaryContentHandlingTest {
+
+ /** Deliberately not valid UTF-8, so any string round-trip corrupts it detectably. */
+ private static final byte[] BINARY_PAYLOAD = {
+ (byte) 0x89, 0x50, 0x4E, 0x47, (byte) 0xFF, (byte) 0xD8, 0x00, 0x01, (byte) 0xFE, 0x7F
+ };
+
+ private static HttpServer backend;
+ private static int backendPort;
+
+ private static final AtomicReference<byte[]> receivedBody = new AtomicReference<>();
+
+ private final List<String> createdApis = new ArrayList<>();
+
+ @BeforeAll
+ static void startBackend() throws IOException {
+ backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ backend.createContext("/", ApiGatewayBinaryContentHandlingTest::handle);
+ backend.start();
+ backendPort = backend.getAddress().getPort();
+ }
+
+ @AfterAll
+ static void stopBackend() {
+ if (backend != null) backend.stop(0);
+ }
+
+ private static void handle(HttpExchange exchange) throws IOException {
+ receivedBody.set(exchange.getRequestBody().readAllBytes());
+
+ // ?echo=binary returns the raw binary payload; ?echo=base64 returns it base64-encoded.
+ String query = exchange.getRequestURI().getQuery();
+ byte[] response;
+ String contentType;
+ if (query != null && query.contains("echo=binary")) {
+ response = BINARY_PAYLOAD;
+ contentType = "image/jpeg";
+ } else if (query != null && query.contains("echo=base64")) {
+ response = Base64.getEncoder().encodeToString(BINARY_PAYLOAD)
+ .getBytes(StandardCharsets.UTF_8);
+ contentType = "text/plain";
+ } else {
+ response = "{\"ok\":true}".getBytes(StandardCharsets.UTF_8);
+ contentType = "application/json";
+ }
+ exchange.getResponseHeaders().add("Content-Type", contentType);
+ exchange.sendResponseHeaders(200, response.length);
+ exchange.getResponseBody().write(response);
+ exchange.close();
+ }
+
+ /**
+ * Builds a deployed REST API with {@code image/jpeg} as a binary media type and a POST
+ * /widget method backed by an HTTP (non-proxy) integration.
+ */
+ private String createApi(String name, String integrationExtras, String integrationResponseBody) {
+ return createApi(name, "\"image/jpeg\"", integrationExtras, integrationResponseBody);
+ }
+
+ /** As above, but with an explicit {@code binaryMediaTypes} array body (JSON, without brackets). */
+ private String createApi(String name, String binaryMediaTypes, String integrationExtras,
+ String integrationResponseBody) {
+ String apiId = given().contentType(ContentType.JSON)
+ .body("{\"name\":\"" + name + "\",\"binaryMediaTypes\":[" + binaryMediaTypes + "]}")
+ .when().post("/restapis")
+ .then().statusCode(201).body("id", notNullValue())
+ .extract().path("id");
+ createdApis.add(apiId);
+
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+ String resourceId = given().contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"widget\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201).extract().path("id");
+
+ given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
+ .then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("{\"type\":\"HTTP\",\"httpMethod\":\"POST\","
+ + "\"uri\":\"http://127.0.0.1:" + backendPort + "/widget\"" + integrationExtras + "}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
+ .then().statusCode(201);
+
+ if (integrationResponseBody != null) {
+ given().contentType(ContentType.JSON).body(integrationResponseBody)
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId
+ + "/methods/POST/integration/responses/200")
+ .then().statusCode(201);
+ }
+
+ String deploymentId = given().contentType(ContentType.JSON).body("{}")
+ .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);
+
+ return apiId;
+ }
+
+ @AfterEach
+ void cleanup() {
+ for (String apiId : createdApis) {
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+ createdApis.clear();
+ }
+
+ @Test
+ void convertToTextBase64EncodesABinaryRequestForMappingTemplates() {
+ receivedBody.set(null);
+ // $input.body is the base64 text, so the backend receives it verbatim inside the template.
+ String apiId = createApi("binary-convert-to-text",
+ ",\"contentHandling\":\"CONVERT_TO_TEXT\","
+ + "\"requestTemplates\":{\"image/jpeg\":\"$input.body\"}", null);
+
+ given().contentType("image/jpeg").body(BINARY_PAYLOAD)
+ .when().post("/execute-api/" + apiId + "/test/widget")
+ .then().statusCode(200);
+
+ assertEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
+ new String(receivedBody.get(), StandardCharsets.UTF_8));
+ }
+
+ @Test
+ void convertToBinaryDecodesABase64RequestBeforeSendingIt() {
+ receivedBody.set(null);
+ String apiId = createApi("binary-convert-to-binary",
+ ",\"contentHandling\":\"CONVERT_TO_BINARY\","
+ + "\"requestTemplates\":{\"text/plain\":\"$input.body\"}", null);
+
+ given().contentType("text/plain")
+ .body(Base64.getEncoder().encodeToString(BINARY_PAYLOAD))
+ .when().post("/execute-api/" + apiId + "/test/widget")
+ .then().statusCode(200);
+
+ assertArrayEquals(BINARY_PAYLOAD, receivedBody.get());
+ }
+
+ @Test
+ void withoutContentHandlingABinaryRequestIsNotBase64Encoded() {
+ receivedBody.set(null);
+ String apiId = createApi("binary-passthrough",
+ ",\"requestTemplates\":{\"image/jpeg\":\"$input.body\"}", null);
+
+ given().contentType("image/jpeg").body(BINARY_PAYLOAD)
+ .when().post("/execute-api/" + apiId + "/test/widget")
+ .then().statusCode(200);
+
+ // No conversion requested, so the payload is handled as text, decidedly not base64.
+ assertEquals(false,
+ Base64.getEncoder().encodeToString(BINARY_PAYLOAD)
+ .equals(new String(receivedBody.get(), StandardCharsets.UTF_8)));
+ }
+
+ /**
+ * The catch-all entry AWS documents: "To support all binary media types, specify
+ * <code>*&#47;*</code>." It covers {@code image/png}, which is never named explicitly.
+ */
+ @Test
+ void theCatchAllBinaryMediaTypeCoversAnyContentType() {
+ receivedBody.set(null);
+ String apiId = createApi("binary-catch-all", "\"*/*\"",
+ ",\"contentHandling\":\"CONVERT_TO_TEXT\","
+ + "\"requestTemplates\":{\"image/png\":\"$input.body\"}", null);
+
+ given().contentType("image/png").body(BINARY_PAYLOAD)
+ .when().post("/execute-api/" + apiId + "/test/widget")
+ .then().statusCode(200);
+
+ // Treated as binary purely via the catch-all, so CONVERT_TO_TEXT base64-encoded it.
+ assertEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
+ new String(receivedBody.get(), StandardCharsets.UTF_8));
+ }
+
+ /**
+ * A subtype wildcard is not a pattern. AWS documents only <code>*&#47;*</code> as a wildcard
+ * entry and names one exact media type at a time everywhere else, so {@code image/}<code>*</code>
+ * matches nothing but a request that literally declares that content type.
+ */
+ @Test
+ void aSubtypeWildcardIsNotExpanded() {
+ receivedBody.set(null);
+ String apiId = createApi("binary-subtype-wildcard", "\"image/*\"",
+ ",\"contentHandling\":\"CONVERT_TO_TEXT\","
+ + "\"requestTemplates\":{\"image/png\":\"$input.body\"}", null);
+
+ given().contentType("image/png").body(BINARY_PAYLOAD)
+ .when().post("/execute-api/" + apiId + "/test/widget")
+ .then().statusCode(200);
+
+ // Not binary, so no base64 conversion happened.
+ assertNotEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
+ new String(receivedBody.get(), StandardCharsets.UTF_8));
+ }
+
+ /** The charset parameter must not defeat the match: {@code image/jpeg; charset=x} is still binary. */
+ @Test
+ void aCharsetParameterDoesNotDefeatTheBinaryMediaTypeMatch() {
+ receivedBody.set(null);
+ String apiId = createApi("binary-charset-param",
+ ",\"contentHandling\":\"CONVERT_TO_TEXT\","
+ + "\"requestTemplates\":{\"image/jpeg\":\"$input.body\"}", null);
+
+ given().contentType("image/jpeg; charset=utf-8").body(BINARY_PAYLOAD)
+ .when().post("/execute-api/" + apiId + "/test/widget")
+ .then().statusCode(200);
+
+ assertEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
+ new String(receivedBody.get(), StandardCharsets.UTF_8));
+ }
+
+ /** A non-proxy HTTP integration forwards only mapped query params, so ?echo must be mapped. */
+ private static final String ECHO_QUERY_MAPPING =
+ ",\"requestParameters\":{\"integration.request.querystring.echo\":"
+ + "\"method.request.querystring.echo\"}";
+
+ @Test
+ void integrationResponseConvertToTextBase64EncodesABinaryBackendBody() {
+ String apiId = createApi("binary-resp-to-text", ECHO_QUERY_MAPPING,
+ "{\"selectionPattern\":\"\",\"contentHandling\":\"CONVERT_TO_TEXT\"}");
+
+ byte[] received = given().contentType(ContentType.JSON).body("{}")
+ .when().post("/execute-api/" + apiId + "/test/widget?echo=binary")
+ .then().statusCode(200)
+ .extract().asByteArray();
+
+ assertEquals(Base64.getEncoder().encodeToString(BINARY_PAYLOAD),
+ new String(received, StandardCharsets.UTF_8));
+ }
+
+ @Test
+ void integrationResponseConvertToBinaryDecodesABase64BackendBody() {
+ String apiId = createApi("binary-resp-to-binary", ECHO_QUERY_MAPPING,
+ "{\"selectionPattern\":\"\",\"contentHandling\":\"CONVERT_TO_BINARY\"}");
+
+ byte[] received = given().contentType(ContentType.JSON).body("{}")
+ .when().post("/execute-api/" + apiId + "/test/widget?echo=base64")
+ .then().statusCode(200)
+ .extract().asByteArray();
+
+ assertArrayEquals(BINARY_PAYLOAD, received);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationFieldsRoundTripTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationFieldsRoundTripTest.java
new file mode 100644
index 0000000000..d4812ee2aa
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationFieldsRoundTripTest.java
@@ -0,0 +1,137 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
+
+/**
+ * Round-trips the {@code PutIntegration} fields AWS documents that Floci previously accepted and
+ * silently dropped: {@code contentHandling}, {@code timeoutInMillis}, {@code connectionType},
+ * {@code connectionId}, {@code credentials}, {@code cacheNamespace}, {@code cacheKeyParameters} and
+ * {@code tlsConfig}, plus {@code contentHandling} on an integration response and
+ * {@code binaryMediaTypes} on the RestApi.
+ *
+ * <p>The mapping configuration these sit alongside ({@code requestParameters},
+ * {@code requestTemplates}, {@code integrationResponses}) is covered by
+ * {@link ApiGatewayIntegrationReadBackTest}.
+ */
+@QuarkusTest
+class ApiGatewayIntegrationFieldsRoundTripTest {
+
+ private String apiId;
+ private String resourceId;
+
+ @BeforeEach
+ void setup() {
+ apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"integration-fields-roundtrip\",\"binaryMediaTypes\":[\"image/jpeg\",\"application/octet-stream\"]}")
+ .when().post("/restapis")
+ .then().statusCode(201).body("id", notNullValue())
+ .extract().path("id");
+
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+
+ resourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"widget\"}")
+ .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);
+ }
+
+ @AfterEach
+ void cleanup() {
+ if (apiId != null) {
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+ }
+
+ private String integrationPath() {
+ return "/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration";
+ }
+
+ private void putFullIntegration() {
+ given().contentType(ContentType.JSON)
+ .body("""
+ {"type":"HTTP","httpMethod":"POST","uri":"http://backend.internal/widget",
+ "contentHandling":"CONVERT_TO_BINARY",
+ "timeoutInMillis":12000,
+ "connectionType":"VPC_LINK",
+ "connectionId":"abc123",
+ "credentials":"arn:aws:iam::000000000000:role/ApiGatewayRole",
+ "cacheNamespace":"widget-ns",
+ "cacheKeyParameters":["method.request.querystring.tenant"],
+ "tlsConfig":{"insecureSkipVerification":true}}
+ """)
+ .when().put(integrationPath())
+ .then().statusCode(201);
+ }
+
+ @Test
+ void putIntegrationEchoesEveryConfiguredField() {
+ given().contentType(ContentType.JSON)
+ .body("""
+ {"type":"HTTP","httpMethod":"POST","uri":"http://backend.internal/widget",
+ "contentHandling":"CONVERT_TO_TEXT","timeoutInMillis":9000,
+ "connectionType":"VPC_LINK","connectionId":"abc123",
+ "tlsConfig":{"insecureSkipVerification":true}}
+ """)
+ .when().put(integrationPath())
+ .then().statusCode(201)
+ .body("type", equalTo("HTTP"))
+ .body("contentHandling", equalTo("CONVERT_TO_TEXT"))
+ .body("timeoutInMillis", equalTo(9000))
+ .body("connectionType", equalTo("VPC_LINK"))
+ .body("connectionId", equalTo("abc123"))
+ .body("tlsConfig.insecureSkipVerification", equalTo(true));
+ }
+
+ @Test
+ void getIntegrationReturnsTheSettingsItStores() {
+ putFullIntegration();
+
+ given().when().get(integrationPath())
+ .then().statusCode(200)
+ .body("cacheNamespace", equalTo("widget-ns"))
+ .body("cacheKeyParameters", contains("method.request.querystring.tenant"))
+ .body("credentials", equalTo("arn:aws:iam::000000000000:role/ApiGatewayRole"))
+ .body("contentHandling", equalTo("CONVERT_TO_BINARY"))
+ .body("timeoutInMillis", equalTo(12000));
+ }
+
+ @Test
+ void getIntegrationResponseReturnsItsContentHandling() {
+ putFullIntegration();
+
+ given().contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"5\\\\d{2}\",\"contentHandling\":\"CONVERT_TO_TEXT\"}")
+ .when().put(integrationPath() + "/responses/502")
+ .then().statusCode(201);
+
+ given().when().get(integrationPath() + "/responses/502")
+ .then().statusCode(200)
+ .body("statusCode", equalTo("502"))
+ .body("contentHandling", equalTo("CONVERT_TO_TEXT"));
+ }
+
+ @Test
+ void restApiRoundTripsBinaryMediaTypes() {
+ given().when().get("/restapis/" + apiId)
+ .then().statusCode(200)
+ .body("binaryMediaTypes", containsInAnyOrder("image/jpeg", "application/octet-stream"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationTransportOptionsTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationTransportOptionsTest.java
new file mode 100644
index 0000000000..7bac658c7b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayIntegrationTransportOptionsTest.java
@@ -0,0 +1,567 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import com.sun.net.httpserver.HttpsConfigurator;
+import com.sun.net.httpserver.HttpsServer;
+import io.github.hectorvent.floci.services.acm.CertificateGenerator;
+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.BasicConstraints;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralSubtree;
+import org.bouncycastle.asn1.x509.KeyUsage;
+import org.bouncycastle.asn1.x509.NameConstraints;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.SecureRandom;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.notNullValue;
+
+/**
+ * Covers the two REST integration transport settings AWS documents that Floci previously accepted
+ * and ignored: {@code timeoutInMillis} and {@code tlsConfig.insecureSkipVerification}.
+ *
+ * <p>The TLS case matters because {@code HttpProxyInvoker} uses a default {@code HttpClient}: an
+ * HTTPS backend presenting a self-signed certificate was unreachable with no way to opt out, which
+ * is the common shape for an internal service behind a private CA.
+ */
+@QuarkusTest
+class ApiGatewayIntegrationTransportOptionsTest {
+
+ private static HttpServer slowServer;
+ private static HttpsServer tlsServer;
+ private static HttpsServer wrongHostTlsServer;
+ private static HttpsServer expiredTlsServer;
+ private static HttpsServer privateCaTlsServer;
+ private static HttpsServer nonSigningRootTlsServer;
+ private static HttpsServer keyUsagelessRootTlsServer;
+ private static HttpsServer nameConstrainedRootTlsServer;
+ private static HttpsServer nameConstrainedIntermediateTlsServer;
+ private static HttpsServer permissiveIntermediateTlsServer;
+ private static int slowPort;
+ private static int tlsPort;
+ private static int wrongHostTlsPort;
+ private static int expiredTlsPort;
+ private static int privateCaTlsPort;
+ private static int nonSigningRootTlsPort;
+ private static int keyUsagelessRootTlsPort;
+ private static int nameConstrainedRootTlsPort;
+ private static int nameConstrainedIntermediateTlsPort;
+ private static int permissiveIntermediateTlsPort;
+
+ private final List<String> createdApis = new ArrayList<>();
+
+ @BeforeAll
+ static void startBackends() throws Exception {
+ slowServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ slowServer.createContext("/", ApiGatewayIntegrationTransportOptionsTest::slowHandler);
+ slowServer.start();
+ slowPort = slowServer.getAddress().getPort();
+
+ tlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ tlsServer.setHttpsConfigurator(new HttpsConfigurator(selfSignedContext()));
+ tlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ tlsServer.start();
+ tlsPort = tlsServer.getAddress().getPort();
+
+ // Same self-signed shape, but the certificate names a host this server is not reachable at,
+ // so only hostname verification can reject it.
+ wrongHostTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ wrongHostTlsServer.setHttpsConfigurator(new HttpsConfigurator(
+ selfSignedContextFor("wrong.example", List.of("wrong.example"))));
+ wrongHostTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ wrongHostTlsServer.start();
+ wrongHostTlsPort = wrongHostTlsServer.getAddress().getPort();
+
+ // Correct hostname, self-signed, but expired two days ago.
+ expiredTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ expiredTlsServer.setHttpsConfigurator(new HttpsConfigurator(expiredSelfSignedContext()));
+ expiredTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ expiredTlsServer.start();
+ expiredTlsPort = expiredTlsServer.getAddress().getPort();
+
+ // A leaf issued by a private root, the shape insecureSkipVerification exists for beyond the
+ // single self-signed certificate. Serves the root alongside the leaf, as a real backend does.
+ privateCaTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ privateCaTlsServer.setHttpsConfigurator(new HttpsConfigurator(
+ privateCaContext(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign, null)));
+ privateCaTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ privateCaTlsServer.start();
+ privateCaTlsPort = privateCaTlsServer.getAddress().getPort();
+
+ // Same chain, except the root declares cA=true without keyCertSign. AWS requires both
+ // together, so this root cannot issue the leaf it just issued.
+ nonSigningRootTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ nonSigningRootTlsServer.setHttpsConfigurator(new HttpsConfigurator(
+ privateCaContext(KeyUsage.digitalSignature | KeyUsage.cRLSign, null)));
+ nonSigningRootTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ nonSigningRootTlsServer.start();
+ nonSigningRootTlsPort = nonSigningRootTlsServer.getAddress().getPort();
+
+ // Same chain again, except the root carries no keyUsage extension at all. AWS states the
+ // extension itself as a requirement on a private root, not just the bit inside it.
+ keyUsagelessRootTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ keyUsagelessRootTlsServer.setHttpsConfigurator(new HttpsConfigurator(privateCaContext(null, null)));
+ keyUsagelessRootTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ keyUsagelessRootTlsServer.start();
+ keyUsagelessRootTlsPort = keyUsagelessRootTlsServer.getAddress().getPort();
+
+ // A fully-formed root that additionally carries Name Constraints of its own.
+ NameConstraints internalOnly = permittedDnsSubtree("internal.example");
+ nameConstrainedRootTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ nameConstrainedRootTlsServer.setHttpsConfigurator(new HttpsConfigurator(privateCaContext(
+ KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign, internalOnly)));
+ nameConstrainedRootTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ nameConstrainedRootTlsServer.start();
+ nameConstrainedRootTlsPort = nameConstrainedRootTlsServer.getAddress().getPort();
+
+ // Three certificates, with the constraints on the intermediate where the validator actually
+ // reads them: the intermediate permits itself internal.example and issued for localhost.
+ nameConstrainedIntermediateTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ nameConstrainedIntermediateTlsServer.setHttpsConfigurator(new HttpsConfigurator(
+ intermediateCaContext(permittedDnsSubtree("internal.example"))));
+ nameConstrainedIntermediateTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ nameConstrainedIntermediateTlsServer.start();
+ nameConstrainedIntermediateTlsPort = nameConstrainedIntermediateTlsServer.getAddress().getPort();
+
+ // The same three-certificate shape whose intermediate permits localhost. Without this, the
+ // test above would pass for any three-certificate chain rather than because of the
+ // constraint it names.
+ permissiveIntermediateTlsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ permissiveIntermediateTlsServer.setHttpsConfigurator(new HttpsConfigurator(
+ intermediateCaContext(permittedDnsSubtree("localhost"))));
+ permissiveIntermediateTlsServer.createContext("/", exchange -> respond(exchange, 200, "{\"tls\":\"ok\"}"));
+ permissiveIntermediateTlsServer.start();
+ permissiveIntermediateTlsPort = permissiveIntermediateTlsServer.getAddress().getPort();
+ }
+
+ @AfterAll
+ static void stopBackends() {
+ if (slowServer != null) slowServer.stop(0);
+ if (tlsServer != null) tlsServer.stop(0);
+ if (wrongHostTlsServer != null) wrongHostTlsServer.stop(0);
+ if (expiredTlsServer != null) expiredTlsServer.stop(0);
+ if (privateCaTlsServer != null) privateCaTlsServer.stop(0);
+ if (nonSigningRootTlsServer != null) nonSigningRootTlsServer.stop(0);
+ if (keyUsagelessRootTlsServer != null) keyUsagelessRootTlsServer.stop(0);
+ if (nameConstrainedRootTlsServer != null) nameConstrainedRootTlsServer.stop(0);
+ if (nameConstrainedIntermediateTlsServer != null) nameConstrainedIntermediateTlsServer.stop(0);
+ if (permissiveIntermediateTlsServer != null) permissiveIntermediateTlsServer.stop(0);
+ }
+
+ /** Sleeps when asked to, so a configured timeout can be observed firing. */
+ private static void slowHandler(HttpExchange exchange) throws IOException {
+ String query = exchange.getRequestURI().getQuery();
+ if (query != null && query.contains("slow=true")) {
+ try {
+ Thread.sleep(2000);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ respond(exchange, 200, "{\"from\":\"backend\"}");
+ }
+
+ private static void respond(HttpExchange exchange, int status, String body) throws IOException {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/json");
+ exchange.sendResponseHeaders(status, bytes.length);
+ exchange.getResponseBody().write(bytes);
+ exchange.close();
+ }
+
+ /** An SSLContext serving a genuinely self-signed cert no default trust store will accept. */
+ private static SSLContext selfSignedContext() throws Exception {
+ return selfSignedContextFor("localhost", List.of("localhost", "127.0.0.1"));
+ }
+
+ /**
+ * A self-signed certificate for localhost whose validity window closed two days ago. Trusting
+ * everything accepts it; AWS does not, because expiration is part of the basic validation that
+ * survives insecureSkipVerification.
+ */
+ private static SSLContext expiredSelfSignedContext() throws Exception {
+ CertificateGenerator generator = new CertificateGenerator();
+ KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
+ X500Name dn = new X500Name("CN=localhost");
+ Instant now = Instant.now();
+ X509Certificate certificate = generator.signCertificate(
+ dn, keyPair.getPublic(), dn, keyPair.getPrivate(),
+ List.of("localhost", "127.0.0.1"), false, CertificateGenerator.LeafUsage.SERVER,
+ now.minus(10, ChronoUnit.DAYS), now.minus(2, ChronoUnit.DAYS));
+ return contextFor(certificate, keyPair.getPrivate());
+ }
+
+ private static SSLContext selfSignedContextFor(String commonName, List<String> sans) throws Exception {
+ CertificateGenerator generator = new CertificateGenerator();
+ CertificateGenerator.GeneratedCertificate generated = generator.generateSelfSignedCertificate(
+ commonName, sans, KeyAlgorithm.RSA_2048);
+
+ X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
+ .generateCertificate(new ByteArrayInputStream(
+ generated.certificatePem().getBytes(StandardCharsets.UTF_8)));
+
+ // RSA keys are emitted as PKCS#1 ("RSA PRIVATE KEY"), not PKCS#8, so use the generator's
+ // own parser rather than PKCS8EncodedKeySpec.
+ PrivateKey privateKey = generator.parsePrivateKey(generated.privateKeyPem());
+
+ return contextFor(certificate, privateKey);
+ }
+
+ /**
+ * A two-certificate chain: a {@code localhost} leaf issued by a self-signed root built with
+ * exactly {@code rootKeyUsageBits} and, optionally, {@code nameConstraints}. Both are what a
+ * private certificate authority looks like on the wire, and both are the knobs AWS documents as
+ * still mattering under {@code insecureSkipVerification}.
+ */
+ /** Permitted subtrees naming a single DNS name, the usual private-CA scoping shape. */
+ private static NameConstraints permittedDnsSubtree(String dnsName) {
+ return new NameConstraints(
+ new GeneralSubtree[]{new GeneralSubtree(new GeneralName(GeneralName.dNSName, dnsName))},
+ null);
+ }
+
+ /**
+ * A three-certificate chain, root to intermediate to {@code localhost} leaf, where the
+ * intermediate carries {@code nameConstraints}. Constraints belong on the intermediate to be
+ * enforced: it sits inside the certification path, where the validator reads extensions, rather
+ * than being the trust anchor, whose extensions are never looked at.
+ */
+ private static SSLContext intermediateCaContext(NameConstraints nameConstraints) throws Exception {
+ KeyPairGenerator keys = KeyPairGenerator.getInstance("RSA");
+ keys.initialize(2048);
+ KeyPair rootKeyPair = keys.generateKeyPair();
+ KeyPair intermediateKeyPair = keys.generateKeyPair();
+ KeyPair leafKeyPair = keys.generateKeyPair();
+
+ Instant now = Instant.now();
+ int caKeyUsage = KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign;
+
+ X500Name rootDn = new X500Name("CN=Floci Test Root");
+ X509Certificate root = buildCa(rootDn, rootKeyPair.getPublic(), rootDn, rootKeyPair.getPrivate(),
+ caKeyUsage, null, now);
+
+ X500Name intermediateDn = new X500Name("CN=Floci Test Intermediate");
+ X509Certificate intermediate = buildCa(intermediateDn, intermediateKeyPair.getPublic(),
+ rootDn, rootKeyPair.getPrivate(), caKeyUsage, nameConstraints, now);
+
+ X509Certificate leaf = new CertificateGenerator().signCertificate(
+ new X500Name("CN=localhost"), leafKeyPair.getPublic(), intermediateDn,
+ intermediateKeyPair.getPrivate(), List.of("localhost", "127.0.0.1"), false,
+ CertificateGenerator.LeafUsage.SERVER, now.minus(1, ChronoUnit.DAYS),
+ now.plus(30, ChronoUnit.DAYS));
+
+ return contextFor(leafKeyPair.getPrivate(), leaf, intermediate, root);
+ }
+
+ /** A CA certificate, self-signed when {@code issuerDn} is its own subject. */
+ private static X509Certificate buildCa(X500Name subjectDn, java.security.PublicKey subjectKey,
+ X500Name issuerDn, PrivateKey issuerKey, Integer keyUsageBits,
+ NameConstraints nameConstraints, Instant now) throws Exception {
+ JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
+ issuerDn, new BigInteger(128, new SecureRandom()),
+ Date.from(now.minus(1, ChronoUnit.DAYS)), Date.from(now.plus(365, ChronoUnit.DAYS)),
+ subjectDn, subjectKey);
+ builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
+ // A null bit set means the extension is left off entirely, which is its own case: AWS
+ // requires the extension to be there, not merely to have the right bit when present.
+ if (keyUsageBits != null) {
+ builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageBits));
+ }
+ if (nameConstraints != null) {
+ builder.addExtension(Extension.nameConstraints, true, nameConstraints);
+ }
+ ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(issuerKey);
+ return new JcaX509CertificateConverter().getCertificate(builder.build(signer));
+ }
+
+ private static SSLContext privateCaContext(Integer rootKeyUsageBits, NameConstraints nameConstraints)
+ throws Exception {
+ KeyPairGenerator keys = KeyPairGenerator.getInstance("RSA");
+ keys.initialize(2048);
+ KeyPair rootKeyPair = keys.generateKeyPair();
+ KeyPair leafKeyPair = keys.generateKeyPair();
+
+ Instant now = Instant.now();
+ X500Name rootDn = new X500Name("CN=Floci Test Root");
+ X509Certificate root = buildCa(rootDn, rootKeyPair.getPublic(), rootDn,
+ rootKeyPair.getPrivate(), rootKeyUsageBits, nameConstraints, now);
+
+ X509Certificate leaf = new CertificateGenerator().signCertificate(
+ new X500Name("CN=localhost"), leafKeyPair.getPublic(), rootDn, rootKeyPair.getPrivate(),
+ List.of("localhost", "127.0.0.1"), false, CertificateGenerator.LeafUsage.SERVER,
+ now.minus(1, ChronoUnit.DAYS), now.plus(30, ChronoUnit.DAYS));
+
+ return contextFor(leafKeyPair.getPrivate(), leaf, root);
+ }
+
+ private static SSLContext contextFor(X509Certificate certificate, PrivateKey privateKey) throws Exception {
+ return contextFor(privateKey, certificate);
+ }
+
+ private static SSLContext contextFor(PrivateKey privateKey, X509Certificate... chain) throws Exception {
+ char[] password = "floci-test".toCharArray();
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+ keyStore.load(null, null);
+ keyStore.setKeyEntry("backend", privateKey, password, (Certificate[]) chain);
+
+ KeyManagerFactory keyManagers = KeyManagerFactory.getInstance(
+ KeyManagerFactory.getDefaultAlgorithm());
+ keyManagers.init(keyStore, password);
+
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers.getKeyManagers(), null, null);
+ return sslContext;
+ }
+
+ /** Builds a deployed REST API whose /{proxy+} ANY method is an HTTP_PROXY to {@code targetUri}. */
+ private String createApi(String name, String targetUri, String integrationExtras) {
+ String apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"" + name + "\"}")
+ .when().post("/restapis")
+ .then().statusCode(201).body("id", notNullValue())
+ .extract().path("id");
+ createdApis.add(apiId);
+
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+ String resourceId = given().contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"{proxy+}\"}")
+ .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/ANY")
+ .then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"ANY\",\"uri\":\"" + targetUri + "\""
+ + integrationExtras + "}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/ANY/integration")
+ .then().statusCode(201);
+
+ String deploymentId = given().contentType(ContentType.JSON).body("{}")
+ .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);
+
+ return apiId;
+ }
+
+ @AfterEach
+ void cleanup() {
+ for (String apiId : createdApis) {
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+ createdApis.clear();
+ }
+
+ @Test
+ void configuredTimeoutCutsOffASlowBackend() {
+ String apiId = createApi("timeout-short", "http://127.0.0.1:" + slowPort + "/{proxy}",
+ ",\"timeoutInMillis\":300");
+
+ // Backend sleeps 2s; the 300ms integration timeout must fire and surface as 502.
+ given().when().get("/execute-api/" + apiId + "/test/thing?slow=true")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void aGenerousTimeoutLetsTheSameSlowBackendThrough() {
+ String apiId = createApi("timeout-long", "http://127.0.0.1:" + slowPort + "/{proxy}",
+ ",\"timeoutInMillis\":10000");
+
+ given().when().get("/execute-api/" + apiId + "/test/thing?slow=true")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void rejectsATimeoutBelowTheAwsMinimum() {
+ String apiId = given().contentType(ContentType.JSON)
+ .body("{\"name\":\"timeout-invalid\"}")
+ .when().post("/restapis").then().statusCode(201).extract().path("id");
+ createdApis.add(apiId);
+
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+ given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + rootId + "/methods/GET")
+ .then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"GET\","
+ + "\"uri\":\"http://example.internal\",\"timeoutInMillis\":10}")
+ .when().put("/restapis/" + apiId + "/resources/" + rootId + "/methods/GET/integration")
+ .then().statusCode(400);
+ }
+
+ @Test
+ void selfSignedHttpsBackendIsRejectedWithoutTlsConfig() {
+ String apiId = createApi("tls-verified", "https://localhost:" + tlsPort + "/{proxy}", "");
+
+ // Default trust store cannot verify the backend's self-signed cert → 502 Bad Gateway.
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void insecureSkipVerificationReachesTheSelfSignedHttpsBackend() {
+ String apiId = createApi("tls-insecure", "https://localhost:" + tlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(200)
+ .body("tls", org.hamcrest.Matchers.equalTo("ok"));
+ }
+
+ @Test
+ void insecureSkipVerificationStillVerifiesTheHostname() {
+ String apiId = createApi("tls-insecure-wrong-host",
+ "https://localhost:" + wrongHostTlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ // AWS documents insecureSkipVerification as skipping only the check that the certificate
+ // was issued by a supported CA: expiration, hostname and the presence of a root CA are
+ // still verified. A certificate issued for wrong.example must therefore fail against a
+ // backend addressed as localhost.
+ // See https://docs.aws.amazon.com/apigateway/latest/api/API_TlsConfig.html
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void insecureSkipVerificationStillRejectsAnExpiredCertificate() {
+ String apiId = createApi("tls-insecure-expired",
+ "https://localhost:" + expiredTlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ // Expiration is the other half of the basic validation AWS keeps. A backend whose
+ // certificate has lapsed has to fail here too, or it works locally and breaks in AWS.
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void insecureSkipVerificationReachesABackendBehindAPrivateCa() {
+ String apiId = createApi("tls-insecure-private-ca",
+ "https://localhost:" + privateCaTlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ // The case the setting exists for beyond a lone self-signed certificate: a well-formed
+ // private root that no public trust store knows. Everything else about the chain is
+ // correct, so it has to be accepted.
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(200)
+ .body("tls", org.hamcrest.Matchers.equalTo("ok"));
+ }
+
+ @Test
+ void insecureSkipVerificationStillRequiresKeyCertSignOnAPrivateRoot() {
+ String apiId = createApi("tls-insecure-root-without-key-cert-sign",
+ "https://localhost:" + nonSigningRootTlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ // AWS states the two requirements on a private root together: the keyUsage extension has
+ // to include keyCertSign and basicConstraints has to say CA:TRUE. Checking only the second
+ // accepts a root that real API Gateway rejects, which is the direction that hides a broken
+ // certificate authority until deployment.
+ // See https://docs.aws.amazon.com/apigateway/latest/api/API_TlsConfig.html
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void insecureSkipVerificationRejectsAPrivateRootWithNoKeyUsageExtension() {
+ String apiId = createApi("tls-insecure-root-without-key-usage",
+ "https://localhost:" + keyUsagelessRootTlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ // AWS states the constraint as "x509 extension keyUsage must have keyCertSign", which a
+ // root carrying no keyUsage extension does not satisfy. Generic PKIX would read the absent
+ // extension as leaving the key unrestricted, and that looser reading accepts a certificate
+ // authority real API Gateway turns away.
+ // See https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-extensions-integration-tls-config.html
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void insecureSkipVerificationEnforcesNameConstraintsOnAnIntermediate() {
+ String apiId = createApi("tls-insecure-name-constrained-intermediate",
+ "https://localhost:" + nameConstrainedIntermediateTlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ // The intermediate permits itself only internal.example and issued for localhost anyway.
+ // AWS documents certificate chain validation as including X509v3 Name Constraints
+ // enforcement, so an issuer overreaching its own declared scope must not be honoured here.
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void insecureSkipVerificationReachesABackendWhoseIntermediatePermitsIt() {
+ String apiId = createApi("tls-insecure-permissive-intermediate",
+ "https://localhost:" + permissiveIntermediateTlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ // Same three-certificate shape, same code path, with the constraint satisfied. Without this
+ // the test above would be satisfied by any rejection of a three-certificate chain rather
+ // than by the constraint it names.
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(200)
+ .body("tls", org.hamcrest.Matchers.equalTo("ok"));
+ }
+
+ @Test
+ void insecureSkipVerificationRejectsARootCarryingNameConstraints() {
+ String apiId = createApi("tls-insecure-name-constrained-root",
+ "https://localhost:" + nameConstrainedRootTlsPort + "/{proxy}",
+ ",\"tlsConfig\":{\"insecureSkipVerification\":true}");
+
+ // Constraints on the trust anchor itself are a separate case from the one above, and they
+ // cannot be evaluated: the platform validator refuses to process constraints supplied with
+ // an anchor rather than read from a certificate in the path. Rejecting is the safe
+ // direction and the documented one. AWS tells operators hitting validation errors under
+ // insecureSkipVerification to check that their CA certificates carry no Name Constraints
+ // extension and to reissue them without it, so such a certificate does not work in AWS
+ // either.
+ given().when().get("/execute-api/" + apiId + "/test/thing")
+ .then().statusCode(502);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayVpcLinkAndCachingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayVpcLinkAndCachingTest.java
new file mode 100644
index 0000000000..c837868dba
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayVpcLinkAndCachingTest.java
@@ -0,0 +1,346 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Covers the REST (v1) VPC Link operations and stage-level response caching, both previously absent.
+ *
+ * <p>Floci has no real VPC, so a VPC_LINK integration routes straight to its URI. What is enforced
+ * is the misconfiguration AWS also rejects: naming a link that does not exist.
+ *
+ * <p>Caching follows AWS's two-level switch: the stage needs a cache cluster and the method needs
+ * caching enabled, and the entry is keyed by the integration's {@code cacheKeyParameters}.
+ */
+@QuarkusTest
+class ApiGatewayVpcLinkAndCachingTest {
+
+ private static HttpServer backend;
+ private static int backendPort;
+ /** Counts backend hits, so a cache hit is observable as the absence of one. */
+ private static final AtomicInteger backendHits = new AtomicInteger();
+
+ private final List<String> createdApis = new ArrayList<>();
+ private final List<String> createdLinks = new ArrayList<>();
+
+ @BeforeAll
+ static void startBackend() throws IOException {
+ backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ backend.createContext("/", ApiGatewayVpcLinkAndCachingTest::handle);
+ backend.start();
+ backendPort = backend.getAddress().getPort();
+ }
+
+ @AfterAll
+ static void stopBackend() {
+ if (backend != null) backend.stop(0);
+ }
+
+ private static void handle(HttpExchange exchange) throws IOException {
+ int hit = backendHits.incrementAndGet();
+ byte[] response = ("{\"hit\":" + hit + "}").getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/json");
+ exchange.sendResponseHeaders(200, response.length);
+ exchange.getResponseBody().write(response);
+ exchange.close();
+ }
+
+ @AfterEach
+ void cleanup() {
+ for (String apiId : createdApis) {
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+ createdApis.clear();
+ for (String linkId : createdLinks) {
+ given().when().delete("/vpclinks/" + linkId);
+ }
+ createdLinks.clear();
+ }
+
+ private String createVpcLink(String name) {
+ String id = given().contentType(ContentType.JSON)
+ .body("{\"name\":\"" + name + "\",\"targetArns\":"
+ + "[\"arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/net/nlb/abc\"]}")
+ .when().post("/vpclinks")
+ .then().statusCode(202).body("id", notNullValue())
+ .extract().path("id");
+ createdLinks.add(id);
+ return id;
+ }
+
+ /** A deployed API with a GET /widget method; caller supplies integration and stage extras. */
+ private String createApi(String name, String integrationExtras, String stageExtras) {
+ String apiId = given().contentType(ContentType.JSON)
+ .body("{\"name\":\"" + name + "\"}")
+ .when().post("/restapis").then().statusCode(201).extract().path("id");
+ createdApis.add(apiId);
+
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+ String resourceId = given().contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"widget\"}")
+ .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/GET")
+ .then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"GET\","
+ + "\"uri\":\"http://127.0.0.1:" + backendPort + "/widget\"" + integrationExtras + "}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
+ .then().statusCode(201);
+
+ String deploymentId = given().contentType(ContentType.JSON).body("{}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201).extract().path("id");
+ given().contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"" + stageExtras + "}")
+ .when().post("/restapis/" + apiId + "/stages")
+ .then().statusCode(201);
+
+ return apiId;
+ }
+
+ /**
+ * A deployed API with GET /alpha and GET /beta, both proxying to the same backend with caching
+ * on. When {@code cacheNamespace} is non-null both integrations declare it, which is how AWS
+ * lets separate resources return the same cached data.
+ */
+ private String createTwoResourceApi(String name, String cacheNamespace) {
+ String apiId = given().contentType(ContentType.JSON)
+ .body("{\"name\":\"" + name + "\"}")
+ .when().post("/restapis").then().statusCode(201).extract().path("id");
+ createdApis.add(apiId);
+
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+
+ String namespaceField = cacheNamespace == null
+ ? "" : ",\"cacheNamespace\":\"" + cacheNamespace + "\"";
+ for (String pathPart : List.of("alpha", "beta")) {
+ 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/GET")
+ .then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"GET\","
+ + "\"uri\":\"http://127.0.0.1:" + backendPort + "/widget\""
+ + namespaceField + "}")
+ .when().put("/restapis/" + apiId + "/resources/" + resourceId
+ + "/methods/GET/integration")
+ .then().statusCode(201);
+ }
+
+ String deploymentId = given().contentType(ContentType.JSON).body("{}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201).extract().path("id");
+ given().contentType(ContentType.JSON)
+ .body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\","
+ + "\"cacheClusterEnabled\":true}")
+ .when().post("/restapis/" + apiId + "/stages")
+ .then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("{\"patchOperations\":["
+ + "{\"op\":\"replace\",\"path\":\"/~1alpha/GET/caching/enabled\",\"value\":\"true\"},"
+ + "{\"op\":\"replace\",\"path\":\"/~1beta/GET/caching/enabled\",\"value\":\"true\"}]}")
+ .when().patch("/restapis/" + apiId + "/stages/test")
+ .then().statusCode(200);
+
+ return apiId;
+ }
+
+ /** Turns on caching for GET /widget on the stage. */
+ private void enableMethodCaching(String apiId, int ttlSeconds) {
+ given().contentType(ContentType.JSON)
+ .body("{\"patchOperations\":["
+ + "{\"op\":\"replace\",\"path\":\"/~1widget/GET/caching/enabled\",\"value\":\"true\"},"
+ + "{\"op\":\"replace\",\"path\":\"/~1widget/GET/caching/ttlInSeconds\",\"value\":\""
+ + ttlSeconds + "\"}]}")
+ .when().patch("/restapis/" + apiId + "/stages/test")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void vpcLinkCrudRoundTrips() {
+ String linkId = createVpcLink("crud-link");
+
+ given().when().get("/vpclinks/" + linkId)
+ .then().statusCode(200)
+ .body("name", equalTo("crud-link"))
+ .body("status", equalTo("AVAILABLE"))
+ .body("targetArns", contains(
+ "arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/net/nlb/abc"));
+
+ given().when().get("/vpclinks").then().statusCode(200).body("item.id", contains(linkId));
+
+ given().contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"renamed\"}]}")
+ .when().patch("/vpclinks/" + linkId)
+ .then().statusCode(200).body("name", equalTo("renamed"));
+
+ given().when().delete("/vpclinks/" + linkId).then().statusCode(202);
+ given().when().get("/vpclinks/" + linkId).then().statusCode(404);
+ createdLinks.remove(linkId);
+ }
+
+ @Test
+ void createVpcLinkRequiresATargetArn() {
+ given().contentType(ContentType.JSON).body("{\"name\":\"no-targets\"}")
+ .when().post("/vpclinks").then().statusCode(400);
+ }
+
+ @Test
+ void vpcLinkIntegrationRoutesWhenTheLinkExists() {
+ String linkId = createVpcLink("routing-link");
+ String apiId = createApi("vpclink-ok",
+ ",\"connectionType\":\"VPC_LINK\",\"connectionId\":\"" + linkId + "\"", "");
+
+ given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
+ }
+
+ @Test
+ void vpcLinkIntegrationIsRejectedWhenTheLinkIsUnknown() {
+ String apiId = createApi("vpclink-missing",
+ ",\"connectionType\":\"VPC_LINK\",\"connectionId\":\"does-not-exist\"", "");
+
+ given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(502);
+ }
+
+ @Test
+ void cachingServesTheSecondRequestWithoutHittingTheBackend() {
+ backendHits.set(0);
+ String apiId = createApi("cache-on", "", ",\"cacheClusterEnabled\":true");
+ enableMethodCaching(apiId, 300);
+
+ given().when().get("/execute-api/" + apiId + "/test/widget")
+ .then().statusCode(200).body("hit", equalTo(1));
+ given().when().get("/execute-api/" + apiId + "/test/widget")
+ .then().statusCode(200).body("hit", equalTo(1));
+
+ assertEquals(1, backendHits.get(), "second request should have been served from the cache");
+ }
+
+ @Test
+ void cachingIsOffWhenTheStageHasNoCacheCluster() {
+ backendHits.set(0);
+ // Method-level caching alone is not enough: AWS needs the stage's cache cluster too.
+ String apiId = createApi("cache-no-cluster", "", "");
+ enableMethodCaching(apiId, 300);
+
+ given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
+ given().when().get("/execute-api/" + apiId + "/test/widget").then().statusCode(200);
+
+ assertEquals(2, backendHits.get(), "without a cache cluster every request reaches the backend");
+ }
+
+ @Test
+ void cacheKeyParametersSeparateEntries() {
+ backendHits.set(0);
+ String apiId = createApi("cache-keys",
+ ",\"cacheKeyParameters\":[\"method.request.querystring.tenant\"]",
+ ",\"cacheClusterEnabled\":true");
+ enableMethodCaching(apiId, 300);
+
+ given().when().get("/execute-api/" + apiId + "/test/widget?tenant=a").then().statusCode(200);
+ given().when().get("/execute-api/" + apiId + "/test/widget?tenant=a").then().statusCode(200);
+ // A different value for a declared cache key parameter is a different entry.
+ given().when().get("/execute-api/" + apiId + "/test/widget?tenant=b").then().statusCode(200);
+
+ assertEquals(2, backendHits.get(), "tenant=a should be cached, tenant=b should miss");
+ }
+
+ @Test
+ void aSharedCacheNamespaceLetsTwoResourcesReturnTheSameCachedData() {
+ backendHits.set(0);
+ String apiId = createTwoResourceApi("cache-shared-ns", "reports");
+
+ given().when().get("/execute-api/" + apiId + "/test/alpha")
+ .then().statusCode(200).body("hit", equalTo(1));
+ // AWS documents cacheNamespace as shareable across resources so that those resources can
+ // return the same cached data. Folding the method and request path into the key would make
+ // that impossible, since two resources never share a path.
+ given().when().get("/execute-api/" + apiId + "/test/beta")
+ .then().statusCode(200).body("hit", equalTo(1));
+
+ assertEquals(1, backendHits.get(),
+ "the second resource shares the namespace, so it should read the first one's entry");
+ }
+
+ @Test
+ void resourcesKeepSeparateEntriesWithoutASharedNamespace() {
+ backendHits.set(0);
+ // cacheNamespace defaults to the resource id, so resources that did not opt into sharing
+ // still get an entry each.
+ String apiId = createTwoResourceApi("cache-default-ns", null);
+
+ given().when().get("/execute-api/" + apiId + "/test/alpha").then().statusCode(200);
+ given().when().get("/execute-api/" + apiId + "/test/beta").then().statusCode(200);
+
+ assertEquals(2, backendHits.get(), "distinct default namespaces should not share an entry");
+ }
+
+ @Test
+ void updateVpcLinkRejectsAnUnsupportedOperation() {
+ String linkId = createVpcLink("patch-op-link");
+
+ // AWS's patch-operation table supports only replace on a VPC link, and applying an
+ // unsupported operation returns an error. Accepting remove here would have set the name to
+ // the supplied value instead.
+ given().contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/name\",\"value\":\"gone\"}]}")
+ .when().patch("/vpclinks/" + linkId)
+ .then().statusCode(400);
+
+ given().when().get("/vpclinks/" + linkId)
+ .then().statusCode(200).body("name", equalTo("patch-op-link"));
+ }
+
+ @Test
+ void updateVpcLinkRejectsAnUnsupportedPath() {
+ String linkId = createVpcLink("patch-path-link");
+
+ // Only /name and /description are patchable. Silently ignoring /targetArns would report
+ // success for a change that never happened.
+ given().contentType(ContentType.JSON)
+ .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/targetArns\",\"value\":\"x\"}]}")
+ .when().patch("/vpclinks/" + linkId)
+ .then().statusCode(400);
+ }
+
+ @Test
+ void stageReportsItsCacheClusterState() {
+ String apiId = createApi("cache-reported", "", ",\"cacheClusterEnabled\":true");
+
+ given().when().get("/restapis/" + apiId + "/stages/test")
+ .then().statusCode(200)
+ .body("cacheClusterEnabled", equalTo(true))
+ .body("cacheClusterStatus", equalTo("AVAILABLE"));
+ }
+}