diff --git a/docs/configuration/tls.md b/docs/configuration/tls.md index 0a84155382..65b964ba18 100644 --- a/docs/configuration/tls.md +++ b/docs/configuration/tls.md @@ -36,7 +36,9 @@ client = boto3.client('sts', endpoint_url='https://localhost:4566', verify=False When `FLOCI_TLS_ENABLED=true` and no custom certificate is provided, Floci auto-generates a self-signed certificate at startup. The certificate: - Is persisted to `{persistent-path}/tls/` and reused across restarts -- Includes `localhost`, `127.0.0.1`, `0.0.0.0`, `*.localhost`, `localhost.floci.io`, and `*.localhost.floci.io` as Subject Alternative Names (SANs) +- Includes `localhost`, `127.0.0.1`, `0.0.0.0`, `*.localhost`, `localhost.floci.io`, + `*.localhost.floci.io`, `*.execute-api.localhost.floci.io`, and + `*.execute-api.localhost.localstack.cloud` as Subject Alternative Names (SANs) - Automatically includes custom hostnames from `FLOCI_HOSTNAME` and `FLOCI_BASE_URL` in the SANs - Is regenerated when hostname configuration changes between restarts diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 0721725155..8df935de2e 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -200,6 +200,23 @@ setups, and `floci:override-id` wins when both are present. Every other tag is p Both HTTP and WebSocket protocol types are fully supported, including the WebSocket data-plane (real connection handling, message routing, and the `@connections` management API). +### HTTP API data-plane + +API Gateway v2 advertises HTTP APIs through Floci's local execute-api domain: + +```bash +curl http://{apiId}.execute-api.localhost.floci.io:4566/{stageName}/{path} +``` + +When an API has a `$default` stage, callers may omit the stage segment: + +```bash +curl http://{apiId}.execute-api.localhost.floci.io:4566/{path} +``` + +APIs created or updated with `disableExecuteApiEndpoint` reject requests to +this default hostname with `404 Not Found`, matching AWS HTTP API behavior. + ### Supported Operations | Category | Operations | diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java index 9c986eed52..69de131696 100644 --- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java +++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java @@ -52,7 +52,9 @@ public class TlsConfigSource implements ConfigSource { // host.docker.internal: how Lambda containers reach Floci when it runs on the host (not in a container). private static final List DEFAULT_SAN_HOSTNAMES = List.of( "localhost", "127.0.0.1", "0.0.0.0", "*.localhost", - "localhost.floci.io", "*.localhost.floci.io", "host.docker.internal"); + "localhost.floci.io", "*.localhost.floci.io", + "*.execute-api.localhost.floci.io", + "*.execute-api.localhost.localstack.cloud", "host.docker.internal"); private final Map properties = new HashMap<>(); 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 206711bad6..931f3c2573 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 @@ -1792,6 +1792,7 @@ public class ApiGatewayController { node.put("protocolType", api.getProtocolType()); node.put("apiEndpoint", api.getApiEndpoint()); node.put("createdDate", java.time.Instant.ofEpochMilli(api.getCreatedDate()).toString()); + node.put("disableExecuteApiEndpoint", api.isDisableExecuteApiEndpoint()); if (api.getRouteSelectionExpression() != null) node.put("routeSelectionExpression", api.getRouteSelectionExpression()); if (api.getDescription() != null) node.put("description", api.getDescription()); if (api.getApiKeySelectionExpression() != null) node.put("apiKeySelectionExpression", api.getApiKeySelectionExpression()); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java new file mode 100644 index 0000000000..b19c3a9740 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java @@ -0,0 +1,188 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; +import jakarta.annotation.Priority; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.PreMatching; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriBuilder; +import jakarta.ws.rs.ext.Provider; +import org.jboss.logging.Logger; + +import java.net.URI; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Provider +@PreMatching +@Priority(9) +public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter { + + private static final Logger LOG = Logger.getLogger(ApiGatewayExecuteApiHostFilter.class); + private static final Pattern EXECUTE_API_HOST = Pattern.compile( + "^([a-z0-9-]+)\\.execute-api\\.localhost\\.(?:floci\\.io|localstack\\.cloud)$", + Pattern.CASE_INSENSITIVE); + + private final ApiGatewayLookup apiGatewayLookup; + private final RegionResolver regionResolver; + private final ApiGatewayExecuteRouteContext routeContext; + + @Inject + public ApiGatewayExecuteApiHostFilter(ApiGatewayV2Service apiGatewayV2Service, + RegionResolver regionResolver, + ApiGatewayExecuteRouteContext routeContext) { + this(new ApiGatewayLookup() { + @Override + public String resolveApiRegion(String preferredRegion, String apiId) { + return apiGatewayV2Service.resolveApiRegion(preferredRegion, apiId); + } + + @Override + public String protocolType(String region, String apiId) { + return apiGatewayV2Service.getApi(region, apiId).getProtocolType(); + } + + @Override + public boolean executeApiEndpointDisabled(String region, String apiId) { + return apiGatewayV2Service.getApi(region, apiId).isDisableExecuteApiEndpoint(); + } + + @Override + public void requireStage(String region, String apiId, String stageName) { + apiGatewayV2Service.getStage(region, apiId, stageName); + } + }, regionResolver, routeContext); + } + + ApiGatewayExecuteApiHostFilter(ApiGatewayLookup apiGatewayLookup, RegionResolver regionResolver) { + this(apiGatewayLookup, regionResolver, new ApiGatewayExecuteRouteContext()); + } + + ApiGatewayExecuteApiHostFilter(ApiGatewayLookup apiGatewayLookup, RegionResolver regionResolver, + ApiGatewayExecuteRouteContext routeContext) { + this.apiGatewayLookup = apiGatewayLookup; + this.regionResolver = regionResolver; + this.routeContext = routeContext; + } + + @Override + public void filter(ContainerRequestContext requestContext) { + String host = requestContext.getHeaderString("Host"); + if (host == null) { + return; + } + + Matcher matcher = EXECUTE_API_HOST.matcher(stripPort(host)); + if (!matcher.matches()) { + return; + } + + String apiId = matcher.group(1).toLowerCase(Locale.ROOT); + String preferredRegion = regionResolver.resolveRegionFromAuth( + requestContext.getHeaderString("Authorization")); + String region = apiGatewayLookup.resolveApiRegion(preferredRegion, apiId); + try { + if (!"HTTP".equals(apiGatewayLookup.protocolType(region, apiId))) { + return; + } + if (apiGatewayLookup.executeApiEndpointDisabled(region, apiId)) { + requestContext.abortWith(Response.status(Response.Status.NOT_FOUND) + .entity("{\"message\":\"Not Found\"}") + .type(MediaType.APPLICATION_JSON) + .build()); + return; + } + } catch (AwsException e) { + LOG.debugv(e, "Execute API host did not resolve to an HTTP API: apiId={0}, region={1}", + apiId, region); + return; + } + + URI originalUri = requestContext.getUriInfo().getRequestUri(); + String originalPath = originalUri.getRawPath(); + + // Host matching alone cannot tell whether this request was already rewritten: the Host + // header still names the execute-api subdomain afterwards. Rewriting twice would produce + // /execute-api/{apiId}/execute-api/{apiId}/... and a 404, so bail out if another + // execute-api filter got here first. + if (originalPath != null && originalPath.startsWith("/execute-api/")) { + return; + } + + String path = originalPath == null ? "" : stripLeadingSlash(originalPath); + String firstSegment = firstSegment(path); + + String stageName = "$default"; + String remainingPath = path; + if (!firstSegment.isEmpty() && stageExists(region, apiId, firstSegment)) { + stageName = firstSegment; + remainingPath = stripFirstSegment(path); + } else if (!stageExists(region, apiId, stageName)) { + return; + } + + String newPath = "/execute-api/" + apiId + "/" + stageName + "/"; + if (!remainingPath.isEmpty()) { + newPath += remainingPath; + } + + URI newUri = UriBuilder.fromUri(originalUri) + .replacePath(newPath) + .buildFromEncoded(); + LOG.debugv("Execute API host routing: {0}{1} -> {2}", host, originalPath, newUri.getRawPath()); + routeContext.routeToHttpApi(region); + requestContext.setRequestUri(newUri); + } + + private boolean stageExists(String region, String apiId, String stageName) { + try { + apiGatewayLookup.requireStage(region, apiId, stageName); + return true; + } catch (AwsException e) { + LOG.debugv(e, "Execute API stage lookup did not resolve: apiId={0}, region={1}, stage={2}", + apiId, region, stageName); + return false; + } + } + + interface ApiGatewayLookup { + String resolveApiRegion(String preferredRegion, String apiId); + + String protocolType(String region, String apiId); + + boolean executeApiEndpointDisabled(String region, String apiId); + + void requireStage(String region, String apiId, String stageName); + } + + private static String stripPort(String host) { + int colonIndex = host.lastIndexOf(':'); + if (colonIndex > 0) { + String port = host.substring(colonIndex + 1); + if (!port.isEmpty() && port.chars().allMatch(Character::isDigit)) { + return host.substring(0, colonIndex); + } + } + return host; + } + + private static String stripLeadingSlash(String path) { + return path.startsWith("/") ? path.substring(1) : path; + } + + private static String firstSegment(String path) { + int slash = path.indexOf('/'); + return slash >= 0 ? path.substring(0, slash) : path; + } + + private static String stripFirstSegment(String path) { + int slash = path.indexOf('/'); + return slash >= 0 ? path.substring(slash + 1) : ""; + } +} 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 38bd40e8c7..6e065f6b00 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 @@ -89,6 +89,7 @@ public class ApiGatewayExecuteController { private final WebSocketConnectionManager webSocketConnectionManager; private final ElbV2Service elbV2Service; private final SqsQueryHandler sqsQueryHandler; + private final ApiGatewayExecuteRouteContext routeContext; @Inject public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service, @@ -97,7 +98,8 @@ public class ApiGatewayExecuteController { AwsServiceRouter serviceRouter, WebSocketConnectionManager webSocketConnectionManager, ElbV2Service elbV2Service, - SqsQueryHandler sqsQueryHandler) { + SqsQueryHandler sqsQueryHandler, + ApiGatewayExecuteRouteContext routeContext) { this.apiGatewayService = apiGatewayService; this.apiGatewayV2Service = apiGatewayV2Service; this.lambdaService = lambdaService; @@ -108,6 +110,7 @@ public class ApiGatewayExecuteController { this.webSocketConnectionManager = webSocketConnectionManager; this.elbV2Service = elbV2Service; this.sqsQueryHandler = sqsQueryHandler; + this.routeContext = routeContext; } /** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */ @@ -245,30 +248,33 @@ public class ApiGatewayExecuteController { Response dispatch(String httpMethod, String apiId, String stageName, String proxy, HttpHeaders headers, UriInfo uriInfo, byte[] body) { String region = regionResolver.resolveRegion(headers); - - // Check if this is a v2 (HTTP API) or v1 (REST API) - boolean isV2 = false; - try { - apiGatewayV2Service.getApi(region, apiId); - isV2 = true; - } catch (AwsException ignored) { - // Not a v2 API — fall through to v1 handling + String httpApiRegion = routeContext.httpApiRegion(); + if (httpApiRegion != null) { + return dispatchV2(httpMethod, apiId, stageName, proxy, headers, uriInfo, body, httpApiRegion); } - if (isV2) { - return dispatchV2(httpMethod, apiId, stageName, proxy, headers, uriInfo, body, region); - } - - // Resolve region for unsigned data-plane requests + String preferredRegion = region; String auth = headers.getHeaderString("Authorization"); if (auth == null || auth.isBlank()) { region = apiGatewayService.resolveRestApiRegion(region, apiId); } - // Verify API and stage exist - Stage stage; try { apiGatewayService.getRestApi(region, apiId); + } catch (AwsException restApiError) { + String v2Region = apiGatewayV2Service.resolveApiRegion(preferredRegion, apiId); + try { + apiGatewayV2Service.getApi(v2Region, apiId); + return dispatchV2(httpMethod, apiId, stageName, proxy, headers, uriInfo, body, v2Region); + } catch (AwsException ignored) { + return Response.status(restApiError.getHttpStatus()) + .entity(jsonMessage(restApiError.getMessage())) + .type(MediaType.APPLICATION_JSON).build(); + } + } + + Stage stage; + try { stage = apiGatewayService.getStage(region, apiId, stageName); } catch (AwsException e) { return Response.status(e.getHttpStatus()) @@ -1262,6 +1268,22 @@ public class ApiGatewayExecuteController { private Response dispatchV2(String httpMethod, String apiId, String stageName, String proxy, HttpHeaders headers, UriInfo uriInfo, byte[] body, String region) { + // disableExecuteApiEndpoint is enforced here rather than in the caller because both the + // host-based route (*.execute-api.localhost.*, already rejected by ApiGatewayExecuteApiHostFilter) + // and the direct /execute-api/{apiId}/{stage}/... route land here. Checking at the single + // choke point keeps the two entry points from disagreeing about whether an API is invokable. + // A missing API is not this method's error to report — findMatchingRoute below 404s. + try { + if (apiGatewayV2Service.getApi(region, apiId).isDisableExecuteApiEndpoint()) { + return Response.status(Response.Status.NOT_FOUND) + .entity(jsonMessage("Not Found")) + .type(MediaType.APPLICATION_JSON).build(); + } + } catch (AwsException e) { + LOG.debugv(e, "HTTP API lookup failed before execute-api dispatch: apiId={0}, region={1}", + apiId, region); + } + String path = "/" + (proxy == null ? "" : proxy); Route route = apiGatewayV2Service.findMatchingRoute(region, apiId, httpMethod, path); @@ -1316,7 +1338,7 @@ public class ApiGatewayExecuteController { String requestId = UUID.randomUUID().toString(); String eventJson = buildV2ProxyEvent(httpMethod, path, route.getRouteKey(), - apiId, stageName, headers, uriInfo, body, requestId); + apiId, region, stageName, headers, uriInfo, body, requestId); LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName); @@ -1882,7 +1904,7 @@ public class ApiGatewayExecuteController { } String buildV2ProxyEvent(String httpMethod, String path, String routeKey, - String apiId, String stageName, + String apiId, String region, String stageName, HttpHeaders headers, UriInfo uriInfo, byte[] body, String requestId) { ObjectNode event = objectMapper.createObjectNode(); @@ -1915,7 +1937,7 @@ public class ApiGatewayExecuteController { ObjectNode ctx = event.putObject("requestContext"); ctx.put("accountId", regionResolver.getAccountId()); ctx.put("apiId", apiId); - ctx.put("domainName", apiId + ".execute-api.us-east-1.amazonaws.com"); + ctx.put("domainName", apiId + ".execute-api." + region + ".amazonaws.com"); ctx.put("domainPrefix", apiId); ctx.put("requestId", requestId); ctx.put("routeKey", routeKey != null ? routeKey : "$default"); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java new file mode 100644 index 0000000000..f54ea2c93a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java @@ -0,0 +1,21 @@ +package io.github.hectorvent.floci.services.apigateway; + +import jakarta.enterprise.context.RequestScoped; + +/** + * Carries routing information established by pre-matching execute-api filters to the + * execute controller without changing the AWS-compatible request. + */ +@RequestScoped +public class ApiGatewayExecuteRouteContext { + + private String httpApiRegion; + + void routeToHttpApi(String region) { + this.httpApiRegion = region; + } + + String httpApiRegion() { + return httpApiRegion; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java index 221c00d669..66b3704b8c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java @@ -495,6 +495,7 @@ public class ApiGatewayV2JsonHandler { node.put("ProtocolType", api.getProtocolType()); node.put("ApiEndpoint", api.getApiEndpoint()); node.put("CreatedDate", api.getCreatedDate() / 1000.0); + node.put("DisableExecuteApiEndpoint", api.isDisableExecuteApiEndpoint()); if (api.getRouteSelectionExpression() != null) { node.put("RouteSelectionExpression", api.getRouteSelectionExpression()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java index fcc2bdb0dd..5df8e5cf69 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java @@ -99,6 +99,7 @@ public class ApiGatewayV2Service { api.setRouteSelectionExpression(routeSelectionExpression); api.setDescription(description); api.setApiKeySelectionExpression(apiKeySelectionExpression); + api.setDisableExecuteApiEndpoint(booleanValue(request.get("disableExecuteApiEndpoint"))); if ("WEBSOCKET".equals(protocolType)) { api.setApiEndpoint(String.format("wss://%s.execute-api.%s.amazonaws.com", api.getApiId(), region)); @@ -126,6 +127,18 @@ public class ApiGatewayV2Service { .orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404)); } + public String resolveApiRegion(String preferredRegion, String apiId) { + if (apiStore.get(apiKey(preferredRegion, apiId)).isPresent()) { + return preferredRegion; + } + + return apiStore.keys().stream() + .filter(k -> k.endsWith("::" + apiId)) + .map(k -> k.substring(0, k.indexOf("::"))) + .findFirst() + .orElse(preferredRegion); + } + public List getApis(String region) { String prefix = region + "::"; return apiStore.scan(k -> k.startsWith(prefix)); @@ -167,6 +180,10 @@ public class ApiGatewayV2Service { if (request.containsKey("apiKeySelectionExpression") && request.get("apiKeySelectionExpression") != null) { api.setApiKeySelectionExpression((String) request.get("apiKeySelectionExpression")); } + if (request.containsKey("disableExecuteApiEndpoint") + && request.get("disableExecuteApiEndpoint") != null) { + api.setDisableExecuteApiEndpoint(booleanValue(request.get("disableExecuteApiEndpoint"))); + } if (request.containsKey("tags")) { @SuppressWarnings("unchecked") Map tags = (Map) request.get("tags"); @@ -183,6 +200,10 @@ public class ApiGatewayV2Service { return api; } + private static boolean booleanValue(Object value) { + return value != null && Boolean.parseBoolean(String.valueOf(value)); + } + private static Api.Cors toCors(Map m) { @SuppressWarnings("unchecked") List allowOrigins = (List) m.get("allowOrigins"); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Api.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Api.java index 4ae92416a9..35ade0c40c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Api.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Api.java @@ -19,6 +19,7 @@ public class Api { private String routeSelectionExpression; private String description; private String apiKeySelectionExpression; + private boolean disableExecuteApiEndpoint; private Cors corsConfiguration; public Api() {} @@ -50,6 +51,11 @@ public class Api { public String getApiKeySelectionExpression() { return apiKeySelectionExpression; } public void setApiKeySelectionExpression(String apiKeySelectionExpression) { this.apiKeySelectionExpression = apiKeySelectionExpression; } + public boolean isDisableExecuteApiEndpoint() { return disableExecuteApiEndpoint; } + public void setDisableExecuteApiEndpoint(boolean disableExecuteApiEndpoint) { + this.disableExecuteApiEndpoint = disableExecuteApiEndpoint; + } + public Cors getCorsConfiguration() { return corsConfiguration; } public void setCorsConfiguration(Cors corsConfiguration) { this.corsConfiguration = corsConfiguration; } diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java index 51bdb4955c..582992d0b0 100644 --- a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java @@ -229,7 +229,9 @@ class TlsCertificateHostnameTest { List sans = extractSansFromCertificate(cert); Set expectedSans = Set.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", - "localhost.floci.io", "*.localhost.floci.io", "host.docker.internal"); + "localhost.floci.io", "*.localhost.floci.io", + "*.execute-api.localhost.floci.io", + "*.execute-api.localhost.localstack.cloud", "host.docker.internal"); Set actualSans = new HashSet<>(sans); assertEquals(expectedSans, actualSans, @@ -252,7 +254,9 @@ class TlsCertificateHostnameTest { List sans = extractSansFromCertificate(cert); Set expectedSans = Set.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", - "localhost.floci.io", "*.localhost.floci.io", "host.docker.internal"); + "localhost.floci.io", "*.localhost.floci.io", + "*.execute-api.localhost.floci.io", + "*.execute-api.localhost.localstack.cloud", "host.docker.internal"); Set actualSans = new HashSet<>(sans); assertEquals(expectedSans, actualSans, diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java index 0cd44ad27c..2be14011fa 100644 --- a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java @@ -160,10 +160,14 @@ class TlsConfigSourceCertificateGenerationTest { assertTrue(sans.contains("host.docker.internal"), "Certificate SANs should include default 'host.docker.internal'"); + assertTrue(sans.contains("*.execute-api.localhost.floci.io"), + "Certificate SANs should include API Gateway execution hosts"); + assertTrue(sans.contains("*.execute-api.localhost.localstack.cloud"), + "Certificate SANs should include LocalStack-compatible API Gateway execution hosts"); // Should not contain any custom hostnames - assertEquals(7, sans.size(), - "Certificate SANs should contain exactly 7 default entries (localhost, 127.0.0.1, 0.0.0.0, *.localhost, localhost.floci.io, *.localhost.floci.io, host.docker.internal)"); + assertEquals(9, sans.size(), + "Certificate SANs should contain exactly 9 default entries, including API Gateway execution hosts"); } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java new file mode 100644 index 0000000000..d26ac51be2 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java @@ -0,0 +1,298 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ApiGatewayExecuteApiHostFilterTest { + + private static final String API_ID = "abc123"; + private static final String REGION = "us-east-1"; + + @Test + void routesStageLessRequestToDefaultStageAndPreservesQuery() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(API_ID); + lookup.addStage(API_ID, "$default"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.floci.io:4566", + URI.create("http://abc123.execute-api.localhost.floci.io:4566/accounts?tenant=alpha")); + ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext(); + + new ApiGatewayExecuteApiHostFilter( + lookup, new RegionResolver(REGION, "000000000000"), routeContext) + .filter(request.context()); + + assertEquals("/execute-api/abc123/$default/accounts", request.routedUri().getRawPath()); + assertEquals("tenant=alpha", request.routedUri().getQuery()); + assertEquals(REGION, routeContext.httpApiRegion()); + } + + @Test + void routesExplicitStageAndRemovesItFromRemainingPath() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(API_ID); + lookup.addStage(API_ID, "dev"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.localstack.cloud", + URI.create("http://abc123.execute-api.localhost.localstack.cloud/dev/accounts")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertEquals("/execute-api/abc123/dev/accounts", request.routedUri().getRawPath()); + } + + @Test + void preservesEncodedPathAndQueryComponents() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(API_ID); + lookup.addStage(API_ID, "$default"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.floci.io", + URI.create("http://abc123.execute-api.localhost.floci.io/files/a%2Fb?value=a%2Fb")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertEquals("/execute-api/abc123/$default/files/a%2Fb", request.routedUri().getRawPath()); + assertEquals("value=a%2Fb", request.routedUri().getRawQuery()); + } + + @Test + void routesStageRootWithTrailingSlash() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(API_ID); + lookup.addStage(API_ID, "dev"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.floci.io", + URI.create("http://abc123.execute-api.localhost.floci.io/dev")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertEquals("/execute-api/abc123/dev/", request.routedUri().getRawPath()); + } + + @Test + void resolvesUnsignedApiOutsideDefaultRegion() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi("us-west-2", API_ID, "HTTP"); + lookup.addStage("us-west-2", API_ID, "$default"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.floci.io", + URI.create("http://abc123.execute-api.localhost.floci.io/accounts")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertEquals("/execute-api/abc123/$default/accounts", request.routedUri().getRawPath()); + } + + @Test + void normalizesMixedCaseHostApiId() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(API_ID); + lookup.addStage(API_ID, "$default"); + RecordingRequest request = new RecordingRequest( + "AbC123.execute-api.localhost.floci.io", + URI.create("http://abc123.execute-api.localhost.floci.io/accounts")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertEquals("/execute-api/abc123/$default/accounts", request.routedUri().getRawPath()); + } + + @Test + void rejectsDisabledExecuteApiEndpoint() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(API_ID); + lookup.addStage(API_ID, "$default"); + lookup.disableExecuteApiEndpoint(API_ID); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.floci.io", + URI.create("http://abc123.execute-api.localhost.floci.io/accounts")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertNull(request.routedUri()); + assertEquals(404, request.abortedResponse().getStatus()); + assertEquals("{\"message\":\"Not Found\"}", request.abortedResponse().getEntity()); + } + + @Test + void ignoresWebSocketApi() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(REGION, API_ID, "WEBSOCKET"); + lookup.addStage(API_ID, "$default"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.floci.io", + URI.create("http://abc123.execute-api.localhost.floci.io/accounts")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertNull(request.routedUri()); + } + + @Test + void doesNotMarkHttpRouteWhenNoStageMatches() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(API_ID); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.floci.io", + URI.create("http://abc123.execute-api.localhost.floci.io/accounts")); + ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext(); + + new ApiGatewayExecuteApiHostFilter( + lookup, new RegionResolver(REGION, "000000000000"), routeContext) + .filter(request.context()); + + assertNull(request.routedUri()); + assertNull(routeContext.httpApiRegion()); + } + + @Test + void ignoresNonExecuteApiHost() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + RecordingRequest request = new RecordingRequest( + "localhost:4566", + URI.create("http://localhost:4566/accounts")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertNull(request.routedUri()); + assertEquals(0, lookup.apiLookups); + } + + private static final class FakeApiGatewayLookup implements ApiGatewayExecuteApiHostFilter.ApiGatewayLookup { + private final Map protocols = new HashMap<>(); + private final Map stages = new HashMap<>(); + private final Map disabledExecuteApiEndpoints = new HashMap<>(); + private int apiLookups; + + void addApi(String apiId) { + addApi(REGION, apiId, "HTTP"); + } + + void addApi(String region, String apiId, String protocolType) { + protocols.put(region + "/" + apiId, protocolType); + } + + void addStage(String apiId, String stageName) { + addStage(REGION, apiId, stageName); + } + + void addStage(String region, String apiId, String stageName) { + stages.put(region + "/" + apiId + "/" + stageName, true); + } + + void disableExecuteApiEndpoint(String apiId) { + disabledExecuteApiEndpoints.put(REGION + "/" + apiId, true); + } + + @Override + public String resolveApiRegion(String preferredRegion, String apiId) { + if (protocols.containsKey(preferredRegion + "/" + apiId)) { + return preferredRegion; + } + String suffix = "/" + apiId; + return protocols.keySet().stream() + .filter(key -> key.endsWith(suffix)) + .map(key -> key.substring(0, key.indexOf('/'))) + .findFirst() + .orElse(preferredRegion); + } + + @Override + public String protocolType(String region, String apiId) { + apiLookups++; + String protocolType = protocols.get(region + "/" + apiId); + if (protocolType == null) { + throw new AwsException("NotFoundException", "Invalid API id specified", 404); + } + return protocolType; + } + + @Override + public boolean executeApiEndpointDisabled(String region, String apiId) { + return disabledExecuteApiEndpoints.getOrDefault(region + "/" + apiId, false); + } + + @Override + public void requireStage(String region, String apiId, String stageName) { + if (!stages.containsKey(region + "/" + apiId + "/" + stageName)) { + throw new AwsException("NotFoundException", "Stage not found", 404); + } + } + } + + private static final class RecordingRequest { + private final String host; + private final URI requestUri; + private URI routedUri; + private Response abortedResponse; + + private RecordingRequest(String host, URI requestUri) { + this.host = host; + this.requestUri = requestUri; + } + + private ContainerRequestContext context() { + return (ContainerRequestContext) Proxy.newProxyInstance( + ContainerRequestContext.class.getClassLoader(), + new Class[] { ContainerRequestContext.class }, + (proxy, method, args) -> switch (method.getName()) { + case "getHeaderString" -> header((String) args[0]); + case "getUriInfo" -> uriInfo(); + case "setRequestUri" -> { + routedUri = (URI) args[0]; + yield null; + } + case "abortWith" -> { + abortedResponse = (Response) args[0]; + yield null; + } + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private URI routedUri() { + return routedUri; + } + + private Response abortedResponse() { + return abortedResponse; + } + + private String header(String name) { + return "Host".equals(name) ? host : null; + } + + private UriInfo uriInfo() { + return (UriInfo) Proxy.newProxyInstance( + UriInfo.class.getClassLoader(), + new Class[] { UriInfo.class }, + (proxy, method, args) -> { + if ("getRequestUri".equals(method.getName())) { + return requestUri; + } + throw new UnsupportedOperationException(method.getName()); + }); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostIntegrationTest.java new file mode 100644 index 0000000000..d47106120e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostIntegrationTest.java @@ -0,0 +1,317 @@ +package io.github.hectorvent.floci.services.apigateway; + +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.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayExecuteApiHostIntegrationTest { + + private static final String REGION = "us-west-2"; + private static final String AUTHORIZATION = + "AWS4-HMAC-SHA256 Credential=test/20260730/" + REGION + "/apigateway/aws4_request"; + + private static HttpServer backend; + private static int backendPort; + private static String apiId; + private static String integrationId; + + @BeforeAll + static void startBackend() throws IOException { + backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + backend.createContext("/", exchange -> { + String query = exchange.getRequestURI().getRawQuery(); + byte[] response = """ + {"path":"%s","query":"%s"} + """.formatted(exchange.getRequestURI().getRawPath(), query == null ? "" : query) + .strip() + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, response.length); + exchange.getResponseBody().write(response); + exchange.close(); + }); + backend.start(); + backendPort = backend.getAddress().getPort(); + } + + @AfterAll + static void stopBackend() { + if (backend != null) { + backend.stop(0); + } + } + + @Test + @Order(1) + void createsHttpApiOutsideDefaultRegion() { + apiId = given() + .header("Authorization", AUTHORIZATION) + .contentType(ContentType.JSON) + .body(""" + {"name":"execute-api-host-test","protocolType":"HTTP"} + """) + .when().post("/v2/apis") + .then() + .statusCode(201) + .body("apiId", notNullValue()) + .body("disableExecuteApiEndpoint", equalTo(false)) + .extract().path("apiId"); + } + + @Test + @Order(2) + void configuresDefaultAndExplicitStages() { + createStage("$default"); + createStage("dev"); + } + + @Test + @Order(3) + void configuresHttpProxyRoute() { + integrationId = given() + .header("Authorization", AUTHORIZATION) + .contentType(ContentType.JSON) + .body(""" + { + "integrationType":"HTTP_PROXY", + "integrationUri":"http://127.0.0.1:%d/backend", + "integrationMethod":"GET", + "payloadFormatVersion":"1.0" + } + """.formatted(backendPort)) + .when().post("/v2/apis/" + apiId + "/integrations") + .then() + .statusCode(201) + .body("integrationId", notNullValue()) + .extract().path("integrationId"); + + given() + .header("Authorization", AUTHORIZATION) + .contentType(ContentType.JSON) + .body(""" + {"routeKey":"GET /accounts","target":"integrations/%s"} + """.formatted(integrationId)) + .when().post("/v2/apis/" + apiId + "/routes") + .then() + .statusCode(201); + } + + @Test + @Order(4) + void invokesDefaultStageByHostWithoutAuthorizationAndPreservesQuery() { + given() + .header("Host", apiId + ".execute-api.localhost.floci.io:4566") + .queryParam("tenant", "alpha") + .when().get("/accounts") + .then() + .statusCode(200) + .body("path", equalTo("/backend")) + .body("query", equalTo("tenant=alpha")); + } + + @Test + @Order(5) + void invokesExplicitStageByCompatibleHost() { + given() + .header("Host", apiId + ".execute-api.localhost.localstack.cloud") + .when().get("/dev/accounts") + .then() + .statusCode(200) + .body("path", equalTo("/backend")); + } + + @Test + @Order(6) + void createsRestApiWithSameIdentifier() { + given() + .contentType(ContentType.JSON) + .body(""" + {"name":"rest-routing-collision","tags":{"floci:override-id":"%s"}} + """.formatted(apiId)) + .when().post("/restapis") + .then() + .statusCode(201) + .body("id", equalTo(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\":\"accounts\"}") + .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("{\"responseParameters\":{}}") + .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/responses/200") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body(""" + {"type":"MOCK","requestTemplates":{"application/json":"{\\"statusCode\\":200}"}} + """) + .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body(""" + { + "selectionPattern":"", + "responseTemplates":{"application/json":"{\\"source\\":\\"rest\\"}"} + } + """) + .when().put("/restapis/" + apiId + "/resources/" + resourceId + + "/methods/GET/integration/responses/200") + .then() + .statusCode(201); + + String deploymentId = given() + .contentType(ContentType.JSON) + .body("{\"description\":\"routing collision regression\"}") + .when().post("/restapis/" + apiId + "/deployments") + .then() + .statusCode(201) + .extract().path("id"); + + given() + .contentType(ContentType.JSON) + .body(""" + {"stageName":"dev","deploymentId":"%s"} + """.formatted(deploymentId)) + .when().post("/restapis/" + apiId + "/stages") + .then() + .statusCode(201); + } + + @Test + @Order(7) + void directPathPrefersRestApiWhenIdentifiersCollide() { + given() + .when().get("/execute-api/" + apiId + "/dev/accounts") + .then() + .statusCode(200) + .body("source", equalTo("rest")); + } + + @Test + @Order(8) + void hostPathRetainsHttpApiRoutingWhenIdentifiersCollide() { + given() + .header("Host", apiId + ".execute-api.localhost.floci.io") + .when().get("/dev/accounts") + .then() + .statusCode(200) + .body("path", equalTo("/backend")); + } + + @Test + @Order(9) + void disabledExecuteApiEndpointReturnsNotFoundAndCanBeReenabled() { + given() + .header("Authorization", AUTHORIZATION) + .contentType(ContentType.JSON) + .body(""" + {"disableExecuteApiEndpoint":true} + """) + .when().patch("/v2/apis/" + apiId) + .then() + .statusCode(200) + .body("disableExecuteApiEndpoint", equalTo(true)); + + given() + .header("Host", apiId + ".execute-api.localhost.floci.io") + .when().get("/accounts") + .then() + .statusCode(404) + .body("message", equalTo("Not Found")); + + given() + .header("Authorization", AUTHORIZATION) + .contentType(ContentType.JSON) + .body(""" + {"disableExecuteApiEndpoint":false} + """) + .when().patch("/v2/apis/" + apiId) + .then() + .statusCode(200) + .body("disableExecuteApiEndpoint", equalTo(false)); + } + + /** + * The direct {@code /execute-api/{apiId}/{stage}/...} form is the same execute-api endpoint as + * the {@code *.execute-api.localhost.*} host, so {@code disableExecuteApiEndpoint} has to reject + * there too — otherwise the two entry points disagree about whether the API is invokable. + * + *

Uses its own HTTP API rather than the shared {@code apiId}: by this point the shared one has + * a REST API with a colliding identifier (see {@link #directPathPrefersRestApiWhenIdentifiersCollide}), + * so its direct path resolves to REST and never reaches the v2 dispatch this guards. + */ + @Test + @Order(10) + void disabledExecuteApiEndpointAlsoRejectsTheDirectPath() { + String isolatedApiId = given() + .header("Authorization", AUTHORIZATION) + .contentType(ContentType.JSON) + .body(""" + {"name":"execute-api-direct-disable-test","protocolType":"HTTP", + "disableExecuteApiEndpoint":true} + """) + .when().post("/v2/apis") + .then() + .statusCode(201) + .body("disableExecuteApiEndpoint", equalTo(true)) + .extract().path("apiId"); + + given() + .when().get("/execute-api/" + isolatedApiId + "/dev/accounts") + .then() + .statusCode(404) + .body("message", equalTo("Not Found")); + } + + private static void createStage(String stageName) { + given() + .header("Authorization", AUTHORIZATION) + .contentType(ContentType.JSON) + .body(""" + {"stageName":"%s","autoDeploy":true} + """.formatted(stageName)) + .when().post("/v2/apis/" + apiId + "/stages") + .then() + .statusCode(201); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java index 5d2ef61158..641446053f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java @@ -28,7 +28,7 @@ class ApiGatewayExecuteControllerTest { return new ApiGatewayExecuteController( null, null, null, regionResolver, objectMapper, null, - null, null, null, null); + null, null, null, null, new ApiGatewayExecuteRouteContext()); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java index f9e620654e..bc7e1e86bc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java @@ -35,7 +35,8 @@ class ApiGatewayProxyMatchTest { void setUp() { ctrl = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, lambdaService, new RegionResolver("us-east-1", "000000000000"), - new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null); + new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null, + new ApiGatewayExecuteRouteContext()); } private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) { diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java index fb568a3842..d7db4161c7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java @@ -50,7 +50,7 @@ class BuildV2ProxyEventBodyEncodingTest { controller = new ApiGatewayExecuteController( null, null, null, regionResolver, objectMapper, null, - null, null, null, null + null, null, null, null, new ApiGatewayExecuteRouteContext() ); } @@ -66,7 +66,7 @@ class BuildV2ProxyEventBodyEncodingTest { String json = controller.buildV2ProxyEvent( "POST", "/echo", "POST /echo", - "abc123", "$default", headers, uriInfo, requestBody, "req-1"); + "abc123", "us-east-1", "$default", headers, uriInfo, requestBody, "req-1"); JsonNode event = objectMapper.readTree(json); if (expectedBody == null) { diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java index dcc0b36a1b..6b1519f19a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java @@ -41,7 +41,7 @@ class BuildV2ProxyEventPathParametersTest { controller = new ApiGatewayExecuteController( null, null, null, regionResolver, new ObjectMapper(), null, - null, null, null, null + null, null, null, null, new ApiGatewayExecuteRouteContext() ); } @@ -49,10 +49,12 @@ class BuildV2ProxyEventPathParametersTest { void greedyProxyRoutePopulatesPathParameters() throws Exception { String json = controller.buildV2ProxyEvent( "POST", "/trpc/health", "ANY /{proxy+}", - "abc123", "$default", headers, uriInfo, null, "req-1"); + "abc123", "us-west-2", "$default", headers, uriInfo, null, "req-1"); JsonNode event = new ObjectMapper().readTree(json); assertTrue(event.has("pathParameters"), "pathParameters must be present"); assertEquals("trpc/health", event.get("pathParameters").get("proxy").asText()); + assertEquals("abc123.execute-api.us-west-2.amazonaws.com", + event.get("requestContext").get("domainName").asText()); } @Test @@ -60,7 +62,7 @@ class BuildV2ProxyEventPathParametersTest { when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/api/stage/users/42")); String json = controller.buildV2ProxyEvent( "GET", "/users/42", "GET /users/{id}", - "abc123", "$default", headers, uriInfo, null, "req-2"); + "abc123", "us-east-2", "$default", headers, uriInfo, null, "req-2"); JsonNode event = new ObjectMapper().readTree(json); assertTrue(event.has("pathParameters"), "pathParameters must be present"); assertEquals("42", event.get("pathParameters").get("id").asText()); @@ -71,7 +73,7 @@ class BuildV2ProxyEventPathParametersTest { when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/api/stage/anything")); String json = controller.buildV2ProxyEvent( "GET", "/anything", "$default", - "abc123", "$default", headers, uriInfo, null, "req-3"); + "abc123", "us-east-1", "$default", headers, uriInfo, null, "req-3"); JsonNode event = new ObjectMapper().readTree(json); assertFalse(event.has("pathParameters"), "pathParameters must be absent for $default route"); } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandlerTest.java index c5e918f350..7fb51b7498 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandlerTest.java @@ -48,7 +48,11 @@ class ApiGatewayV2JsonHandlerTest { .header("X-Amz-Target", TARGET_PREFIX + "CreateApi") .header("Authorization", AUTH_HEADER) .body(""" - {"Name":"json11-test","ProtocolType":"HTTP"} + { + "Name":"json11-test", + "ProtocolType":"HTTP", + "DisableExecuteApiEndpoint":true + } """) .when().post("/") .then() @@ -59,7 +63,20 @@ class ApiGatewayV2JsonHandlerTest { // AWS defaults must be populated .body("RouteSelectionExpression", equalTo("${request.method} ${request.path}")) .body("ApiKeySelectionExpression", equalTo("$request.header.x-api-key")) + .body("DisableExecuteApiEndpoint", equalTo(true)) .extract().path("ApiId"); + + given() + .contentType(AMZ_JSON) + .header("X-Amz-Target", TARGET_PREFIX + "UpdateApi") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ApiId":"%s","DisableExecuteApiEndpoint":false} + """.formatted(apiId)) + .when().post("/") + .then() + .statusCode(200) + .body("DisableExecuteApiEndpoint", equalTo(false)); } @Test