Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cloudfront): serve execute-api custom origins of this Floci in-process (#6754)

Liron Cohen548788840c3a
diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md
index d11ff33552..1fbe55c221 100644
--- a/docs/services/cloudfront.md
+++ b/docs/services/cloudfront.md
@@ -265,6 +265,14 @@ PUT, PATCH and DELETE).
keeps a connection to the origin after the last packet of a response. An origin that does not
answer in time is answered 504, "The origin didn't respond before the request expired", as on AWS.
- Custom origins that resolve to loopback, private, link-local, carrier-grade NAT, or other non-routable addresses are rejected by default. Development-only private origins must be explicitly allowlisted by exact hostname.
+- A custom origin whose domain is an execute-api endpoint (`{apiId}.execute-api.{region}.amazonaws.com`) of an
+ HTTP or REST API that exists in this Floci is served by Floci itself, at the address the viewer reached,
+ through the same host routing as a direct call. The origin path names the stage, as on AWS. Neither DNS nor
+ the private address check applies. A forwarded viewer `Host` is a 502, so use an origin request policy
+ such as `Managed-AllViewerExceptHostHeader`. An execute-api domain of an API that does not exist in this
+ Floci is fetched like any other custom origin. A request that the host routing would not send to the API
+ (a WebSocket API, a disabled endpoint, a missing stage, or a region other than the API's) is answered 404
+ `{"message":"Not Found"}` and never reaches Floci's other endpoints.
- A custom origin whose domain is a [Lambda Web Function](lambda-web-functions.md) endpoint of this Floci is
served by Floci itself, at the address the viewer reached. The origin names the endpoint's
`domainName` with or without its port, and its protocol and ports do not matter, so neither DNS nor
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
index d5ac248a13..6c548e8a2a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java
@@ -47,6 +47,7 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
@Inject
public ApiGatewayExecuteApiHostFilter(ApiGatewayV2Service apiGatewayV2Service,
+ ApiGatewayService apiGatewayService,
RegionResolver regionResolver,
ApiGatewayExecuteRouteContext routeContext,
EmulatorConfig config,
@@ -57,6 +58,11 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
return apiGatewayV2Service.findApiOwner(apiId);
}
+ @Override
+ public Optional<String> findRestApiRegion(String apiId) {
+ return apiGatewayService.findRestApiOwner(apiId).map(ApiGatewayService.ApiOwner::region);
+ }
+
@Override
public String resolveApiRegion(String preferredRegion, String apiId) {
return apiGatewayV2Service.resolveApiRegion(preferredRegion, apiId);
@@ -125,6 +131,28 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
}
}
+ /**
+ * Whether a request for this execute-api host and raw path would be rewritten onto an API by
+ * {@link #filter}. False when the host names no API, the region label is not the API's region,
+ * the API is not invokable on this path (WebSocket, disabled endpoint, no stage), or the path is
+ * already an internal {@code /execute-api/} path.
+ */
+ public boolean routes(String host, String originalPath) {
+ try {
+ RouteDecision decision = decide(host, originalPath, null);
+ Optional<String> apiRegion = switch (decision.kind()) {
+ case HTTP_API -> Optional.of(decision.region());
+ case REST_API -> apiGatewayLookup.findRestApiRegion(decision.apiId());
+ case NONE, DISABLED -> Optional.empty();
+ };
+ String hostRegion = regionResolver.resolveRegionFromHost(host);
+ return apiRegion.isPresent() && (hostRegion == null || hostRegion.equals(apiRegion.get()));
+ } catch (AwsException e) {
+ LOG.debugv(e, "Execute API host did not resolve to one API: apiId={0}", extractApiId(host, baseHostname));
+ return false;
+ }
+ }
+
private static Response notFoundResponse() {
return Response.status(Response.Status.NOT_FOUND)
.entity(NOT_FOUND_BODY)
@@ -291,6 +319,10 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
return Optional.empty();
}
+ default Optional<String> findRestApiRegion(String apiId) {
+ return Optional.empty();
+ }
+
String resolveApiRegion(String preferredRegion, String apiId);
String protocolType(String region, String apiId);
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java
index 9bb430bee7..e3ccffc651 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java
@@ -3,6 +3,9 @@ package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestHost;
+import io.github.hectorvent.floci.services.apigateway.ApiGatewayExecuteApiHostFilter;
+import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
@@ -111,6 +114,10 @@ public class CloudFrontServingController {
private final CloudFrontService service;
private final S3Service s3Service;
private final LambdaWebService lambdaWebService;
+ private final ApiGatewayService apiGatewayService;
+ private final ApiGatewayV2Service apiGatewayV2Service;
+ private final ApiGatewayExecuteApiHostFilter executeApiHostFilter;
+ private final String flociHostname;
private final LambdaWebIamAuth lambdaWebIamAuth;
private final CurrentVertxRequest currentVertxRequest;
private final HttpServer httpServer;
@@ -120,11 +127,17 @@ public class CloudFrontServingController {
@Inject
public CloudFrontServingController(CloudFrontService service, S3Service s3Service,
LambdaWebService lambdaWebService, LambdaWebIamAuth lambdaWebIamAuth,
+ ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
+ ApiGatewayExecuteApiHostFilter executeApiHostFilter,
EmulatorConfig emulatorConfig, CurrentVertxRequest currentVertxRequest,
HttpServer httpServer) {
this.service = service;
this.s3Service = s3Service;
this.lambdaWebService = lambdaWebService;
+ this.apiGatewayService = apiGatewayService;
+ this.apiGatewayV2Service = apiGatewayV2Service;
+ this.executeApiHostFilter = executeApiHostFilter;
+ this.flociHostname = emulatorConfig.hostname().orElse("localhost");
this.lambdaWebIamAuth = lambdaWebIamAuth;
this.currentVertxRequest = currentVertxRequest;
this.httpServer = httpServer;
@@ -771,16 +784,25 @@ public class CloudFrontServingController {
String viewerScheme, String method, ViewerBody viewerBody) {
boolean includeBody = !"HEAD".equals(method);
try {
- // Floci serves its own Web Function endpoints, whatever port and protocol the origin names.
+ // Floci serves its own Web Function and execute-api endpoints, whatever port and protocol the origin names.
String webEndpoint = webFunctionEndpoint(origin);
- if (webEndpoint != null && originRequest.headers().stream()
+ String executeApiHost = webEndpoint == null ? executeApiHost(origin) : null;
+ boolean inProcess = webEndpoint != null || executeApiHost != null;
+ if (inProcess && originRequest.headers().stream()
.anyMatch(header -> "Host".equalsIgnoreCase(header.name()))) {
// CloudFront checks the endpoint's certificate against the forwarded viewer Host, which it never names.
- LOG.debugv("CloudFront forwards the viewer Host to Web Function origin {0}", origin.getId());
+ LOG.debugv("CloudFront forwards the viewer Host to in-process origin {0}", origin.getId());
return OriginResponse.error(502, "Bad Gateway.");
}
- URI target = webEndpoint != null
- ? flociListenerUri(forwardUri, originRequest.rawQuery())
+ // Dot segments would be resolved after the host filter's check and escape the API's stage.
+ String originPath = executeApiHost != null
+ ? CloudFrontRequestRouter.normalizePath(rawPath(forwardUri)) : forwardUri;
+ if (executeApiHost != null && !executeApiHostFilter.routes(executeApiHost, originPath)) {
+ byte[] notFound = ApiGatewayExecuteApiHostFilter.NOT_FOUND_BODY.getBytes(StandardCharsets.UTF_8);
+ return new OriginResponse(404, MediaType.APPLICATION_JSON, notFound, notFound.length, Map.of());
+ }
+ URI target = inProcess
+ ? flociListenerUri(originPath, originRequest.rawQuery())
: buildCustomOriginUri(origin, viewerScheme, forwardUri, originRequest.rawQuery());
HttpRequest.Builder rb = HttpRequest.newBuilder()
.uri(target);
@@ -798,6 +820,9 @@ public class CloudFrontServingController {
}
}
}
+ if (executeApiHost != null) {
+ originHeaders.put("Host", executeApiHost);
+ }
if (webEndpoint != null) {
originHeaders.put("Host", webEndpoint);
if (alwaysAmzAuth(origin)) {
@@ -808,7 +833,7 @@ public class CloudFrontServingController {
// Both bodies are streamed, so neither has to fit in memory: the viewer's goes out with its
// own Content-Length, or chunked as it came, and the origin's comes back as it arrives.
ViewerBody requestBody = originRequestBody(method, viewerBody);
- CloudFrontOriginHttpClient.OpenResponse resp = (webEndpoint != null ? flociClient : httpClient).open(
+ CloudFrontOriginHttpClient.OpenResponse resp = (inProcess ? flociClient : httpClient).open(
rb.build(), originRequest.headers(),
originHeaders, requestBody != null ? requestBody.stream() : null,
requestBody != null ? requestBody.length() : -1, originTimeouts(origin));
@@ -850,6 +875,37 @@ public class CloudFrontServingController {
}
}
+ /**
+ * The origin's host when it is an execute-api endpoint of an HTTP or REST API that exists in this
+ * Floci, which the execute-api host filter then routes, and null otherwise.
+ */
+ private String executeApiHost(Origin origin) {
+ String host;
+ try {
+ host = normalizeOriginHost(origin.getDomainName());
+ } catch (IllegalArgumentException ignored) {
+ // An invalid domain cannot name a local API; the normal origin fetch rejects it.
+ return null;
+ }
+ String apiId = ApiGatewayExecuteApiHostFilter.extractApiId(host, flociHostname);
+ if (apiId == null) {
+ return null;
+ }
+ try {
+ boolean exists = apiGatewayV2Service.findApiOwner(apiId).isPresent()
+ || apiGatewayService.findRestApiOwner(apiId).isPresent();
+ return exists ? host : null;
+ } catch (AwsException e) {
+ LOG.debugv("CloudFront execute-api origin id is ambiguous: {0}", apiId);
+ return null;
+ }
+ }
+
+ private static String rawPath(String forwardUri) {
+ int query = forwardUri.indexOf('?');
+ return query < 0 ? forwardUri : forwardUri.substring(0, query);
+ }
+
/**
* The plain HTTP port at the address the viewer reached Floci at, which also serves the Web
* Function endpoints. A viewer over TLS reached the HTTPS port instead.
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterDecisionTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterDecisionTest.java
index 6e9af433c5..36fc4e16df 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterDecisionTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterDecisionTest.java
@@ -11,6 +11,7 @@ import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -23,6 +24,7 @@ class ApiGatewayExecuteApiHostFilterDecisionTest {
private static final String VIEWER_ACCOUNT = "000000000000";
private static final String OWNER_ACCOUNT = "111122223333";
private static final String HOST = API_ID + ".execute-api." + REGION + ".amazonaws.com";
+ private static final String WRONG_REGION_HOST = API_ID + ".execute-api.eu-west-1.amazonaws.com";
private final RequestContext viewer = viewerContext();
private final StubLookup lookup = new StubLookup(viewer);
@@ -142,6 +144,55 @@ class ApiGatewayExecuteApiHostFilterDecisionTest {
assertEquals(REGION, viewer.getRegion());
}
+ @Test
+ void httpApiOfAnotherAccountRoutes() {
+ lookup.owner = new ApiGatewayV2Service.ApiOwner(OWNER_ACCOUNT, REGION);
+ lookup.httpApi = true;
+
+ assertTrue(filter.routes(HOST, "/dev/accounts"));
+ }
+
+ @Test
+ void httpApiWithAnotherRegionLabelDoesNotRoute() {
+ lookup.owner = new ApiGatewayV2Service.ApiOwner(OWNER_ACCOUNT, REGION);
+ lookup.httpApi = true;
+
+ assertFalse(filter.routes(WRONG_REGION_HOST, "/dev/accounts"));
+ }
+
+ @Test
+ void restApiInTheHostRegionRoutes() {
+ lookup.restRegion = REGION;
+
+ assertTrue(filter.routes(HOST, "/dev/"));
+ }
+
+ @Test
+ void restApiWithAnotherRegionLabelDoesNotRoute() {
+ lookup.restRegion = REGION;
+
+ assertFalse(filter.routes(WRONG_REGION_HOST, "/dev/"));
+ }
+
+ @Test
+ void restApiThatDoesNotExistDoesNotRoute() {
+ assertFalse(filter.routes(HOST, "/dev/"));
+ }
+
+ @Test
+ void ambiguousApiIdDoesNotRoute() {
+ lookup.ambiguous = true;
+
+ assertFalse(filter.routes(HOST, "/dev/accounts"));
+ }
+
+ @Test
+ void internalExecuteApiPathDoesNotRoute() {
+ lookup.restRegion = REGION;
+
+ assertFalse(filter.routes(HOST, "/execute-api/" + API_ID + "/dev/"));
+ }
+
private static RequestContext viewerContext() {
RequestContext context = new RequestContext();
context.setAccountId(VIEWER_ACCOUNT);
@@ -153,6 +204,7 @@ class ApiGatewayExecuteApiHostFilterDecisionTest {
private final RequestContext viewer;
private final List<String> accountsSeen = new ArrayList<>();
private ApiGatewayV2Service.ApiOwner owner;
+ private String restRegion;
private String stage = "dev";
private boolean disabled;
private boolean crash;
@@ -171,6 +223,11 @@ class ApiGatewayExecuteApiHostFilterDecisionTest {
return Optional.ofNullable(owner);
}
+ @Override
+ public Optional<String> findRestApiRegion(String apiId) {
+ return Optional.ofNullable(restRegion);
+ }
+
@Override
public String resolveApiRegion(String preferredRegion, String apiId) {
return preferredRegion;
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontExecuteApiOriginServingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontExecuteApiOriginServingTest.java
new file mode 100644
index 0000000000..8b019521d3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontExecuteApiOriginServingTest.java
@@ -0,0 +1,349 @@
+package io.github.hectorvent.floci.services.cloudfront;
+
+import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
+import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
+import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
+import io.github.hectorvent.floci.services.cloudfront.model.Origin;
+import io.github.hectorvent.floci.testing.PartitionCleanup;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.RestAssured;
+import io.restassured.http.ContentType;
+import io.restassured.specification.RequestSpecification;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * Distributions whose origin is an execute-api endpoint of an API that exists in this Floci, answered
+ * by Floci itself. The only backend is a stub on 127.0.0.1, and no private origin host is allowed here.
+ */
+@QuarkusTest
+class CloudFrontExecuteApiOriginServingTest {
+
+ private static final String CACHING_DISABLED = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad";
+ private static final String REGION = "us-east-1";
+ private static final String STAGE = "dev";
+ private static final String OTHER_ACCOUNT_AUTHORIZATION =
+ "AWS4-HMAC-SHA256 Credential=111122223333/20261027/" + REGION + "/apigateway/aws4_request";
+
+ @Inject
+ CloudFrontService cloudFrontService;
+
+ @RegisterExtension
+ final PartitionCleanup cleanup = new PartitionCleanup();
+
+ private HttpServer backend;
+
+ @AfterEach
+ void stopBackend() {
+ if (backend != null) {
+ backend.stop(0);
+ }
+ }
+
+ @Test
+ void anHttpApiOriginIsServedWithItsStatusBodyAndHeadersAtTheStageOfTheOriginPath() throws IOException {
+ String apiId = createHttpApi();
+ Distribution created = createDistribution(executeApiDomain(apiId), "/" + STAGE,
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/accounts?tenant=alpha")
+ .then().statusCode(200)
+ .header("X-Backend", "stub")
+ .body("path", equalTo("/backend"))
+ .body("query", equalTo("tenant=alpha"));
+ }
+
+ @Test
+ void aRestApiOriginIsServedAtTheStageOfTheOriginPath() {
+ String apiId = createRestApi();
+ Distribution created = createDistribution(executeApiDomain(apiId), "/" + STAGE,
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/")
+ .then().statusCode(200)
+ .body("from", equalTo("rest"));
+ }
+
+ @Test
+ void anExecuteApiOriginOfAnApiThatDoesNotExistIsNotServedInProcess() {
+ Distribution created = createDistribution("nosuchapi01.execute-api." + REGION + ".localhost", "",
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/accounts")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void aPrivateOriginThatIsNotAnExecuteApiEndpointIsStillRefused() throws IOException {
+ startBackend();
+ Distribution created = createDistribution("127.0.0.1", "",
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID,
+ backend.getAddress().getPort());
+
+ given().header("Host", created.getDomainName())
+ .when().get("/accounts")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void forwardingTheViewerHostToAnExecuteApiOriginIsABadGateway() throws IOException {
+ String apiId = createHttpApi();
+ Distribution created = createDistribution(executeApiDomain(apiId), "/" + STAGE,
+ CloudFrontService.MANAGED_ALL_VIEWER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/accounts")
+ .then().statusCode(502);
+ }
+
+ @Test
+ void aPostReachesTheApiIntegrationWithItsMethodAndBody() throws IOException {
+ String apiId = createHttpApi();
+ Distribution created = createDistribution(executeApiDomain(apiId), "/" + STAGE,
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName()).contentType(ContentType.TEXT).body("ping")
+ .when().post("/accounts")
+ .then().statusCode(200)
+ .body("method", equalTo("POST"))
+ .body("body", equalTo("ping"));
+ }
+
+ @Test
+ void theStageIsTakenFromTheViewerPathWhenTheOriginPathIsEmpty() throws IOException {
+ String apiId = createHttpApi();
+ Distribution created = createDistribution(executeApiDomain(apiId), "",
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/" + STAGE + "/accounts")
+ .then().statusCode(200)
+ .body("path", equalTo("/backend"));
+ }
+
+ @Test
+ void aWebSocketApiOriginNeverExposesFlociManagementOutput() {
+ String apiId = given().contentType(ContentType.JSON)
+ .body(Map.of("name", "cf-ws", "protocolType", "WEBSOCKET",
+ "routeSelectionExpression", "$request.body.action"))
+ .when().post("/v2/apis").then().statusCode(201).extract().path("apiId");
+ cleanup.register(() -> given().when().delete("/v2/apis/" + apiId));
+ Distribution created = createDistribution(executeApiDomain(apiId), "",
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/v2/apis")
+ .then().statusCode(404)
+ .body("message", equalTo("Not Found"));
+ }
+
+ @Test
+ void anHttpApiOriginWithoutTheRequestedStageNeverExposesFlociManagementOutput() throws IOException {
+ String apiId = createHttpApi();
+ Distribution created = createDistribution(executeApiDomain(apiId), "/nostage",
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/v2/apis")
+ .then().statusCode(404)
+ .body("message", equalTo("Not Found"));
+ }
+
+ @Test
+ void aViewerPathIntoTheInternalExecuteApiRouteIsNotServed() throws IOException {
+ String apiId = createHttpApi();
+ Distribution created = createDistribution(executeApiDomain(apiId), "",
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/execute-api/" + apiId + "/" + STAGE + "/accounts")
+ .then().statusCode(404);
+ }
+
+ @Test
+ void anExecuteApiDomainWithAnotherRegionThanTheApiIsNotServed() throws IOException {
+ String apiId = createHttpApi();
+ Distribution created = createDistribution(apiId + ".execute-api.eu-west-1.amazonaws.com", "/" + STAGE,
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/accounts")
+ .then().statusCode(404);
+ }
+
+ @Test
+ void anHttpApiOfAnotherAccountThanTheViewerIsServed() throws IOException {
+ String apiId = createHttpApi(OTHER_ACCOUNT_AUTHORIZATION);
+ Distribution created = createDistribution(executeApiDomain(apiId), "/" + STAGE,
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/accounts")
+ .then().statusCode(200)
+ .body("path", equalTo("/backend"));
+ }
+
+ @Test
+ void aRestApiWithAnotherRegionLabelThanTheApiIsNotServed() {
+ String apiId = createRestApi();
+ Distribution created = createDistribution(apiId + ".execute-api.eu-west-1.amazonaws.com", "/" + STAGE,
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ given().header("Host", created.getDomainName())
+ .when().get("/")
+ .then().statusCode(404)
+ .body("message", equalTo("Not Found"));
+ }
+
+ @Test
+ void dotSegmentsInTheViewerPathCannotLeaveTheApiStage() throws IOException {
+ String apiId = createHttpApi();
+ Distribution created = createDistribution(executeApiDomain(apiId), "",
+ CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
+
+ // A raw socket, because the test HTTP client would resolve the dot segments itself.
+ try (Socket socket = new Socket("127.0.0.1", RestAssured.port)) {
+ socket.getOutputStream().write(("GET /" + STAGE + "/../../../v2/apis HTTP/1.1\r\nHost: "
+ + created.getDomainName() + "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.UTF_8));
+ String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
+
+ assertThat(response.lines().findFirst().orElse(""), equalTo("HTTP/1.1 404 Not Found"));
+ assertThat(response, not(containsString("\"items\"")));
+ }
+ }
+
+ private static String executeApiDomain(String apiId) {
+ return apiId + ".execute-api." + REGION + ".amazonaws.com";
+ }
+
+ private void startBackend() throws IOException {
+ backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ backend.createContext("/", exchange -> {
+ String query = exchange.getRequestURI().getRawQuery();
+ String sentBody = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
+ byte[] response = "{\"path\":\"%s\",\"query\":\"%s\",\"method\":\"%s\",\"body\":\"%s\"}"
+ .formatted(exchange.getRequestURI().getRawPath(), query == null ? "" : query,
+ exchange.getRequestMethod(), sentBody)
+ .getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/json");
+ exchange.getResponseHeaders().add("X-Backend", "stub");
+ exchange.sendResponseHeaders(200, response.length);
+ exchange.getResponseBody().write(response);
+ exchange.close();
+ });
+ backend.start();
+ }
+
+ private String createHttpApi() throws IOException {
+ return createHttpApi(null);
+ }
+
+ private String createHttpApi(String authorization) throws IOException {
+ startBackend();
+ String apiId = asOwner(authorization).contentType(ContentType.JSON)
+ .body(Map.of("name", "cf-execute-api", "protocolType", "HTTP"))
+ .when().post("/v2/apis")
+ .then().statusCode(201).extract().path("apiId");
+ cleanup.register(() -> asOwner(authorization).when().delete("/v2/apis/" + apiId));
+ asOwner(authorization).contentType(ContentType.JSON).body(Map.of("stageName", STAGE))
+ .when().post("/v2/apis/" + apiId + "/stages").then().statusCode(201);
+ String integrationId = asOwner(authorization).contentType(ContentType.JSON)
+ .body(Map.of("integrationType", "HTTP_PROXY", "integrationMethod", "GET",
+ "integrationUri", "http://127.0.0.1:" + backend.getAddress().getPort() + "/backend",
+ "payloadFormatVersion", "1.0"))
+ .when().post("/v2/apis/" + apiId + "/integrations")
+ .then().statusCode(201).extract().path("integrationId");
+ asOwner(authorization).contentType(ContentType.JSON)
+ .body(Map.of("routeKey", "GET /accounts", "target", "integrations/" + integrationId))
+ .when().post("/v2/apis/" + apiId + "/routes").then().statusCode(201);
+ String postIntegrationId = asOwner(authorization).contentType(ContentType.JSON)
+ .body(Map.of("integrationType", "HTTP_PROXY", "integrationMethod", "POST",
+ "integrationUri", "http://127.0.0.1:" + backend.getAddress().getPort() + "/backend",
+ "payloadFormatVersion", "1.0"))
+ .when().post("/v2/apis/" + apiId + "/integrations")
+ .then().statusCode(201).extract().path("integrationId");
+ asOwner(authorization).contentType(ContentType.JSON)
+ .body(Map.of("routeKey", "POST /accounts", "target", "integrations/" + postIntegrationId))
+ .when().post("/v2/apis/" + apiId + "/routes").then().statusCode(201);
+ return apiId;
+ }
+
+ private static RequestSpecification asOwner(String authorization) {
+ return authorization == null ? given() : given().header("Authorization", authorization);
+ }
+
+ private String createRestApi() {
+ String apiId = given().contentType(ContentType.JSON).body(Map.of("name", "cf-execute-api-rest"))
+ .when().post("/restapis").then().statusCode(201).extract().path("id");
+ cleanup.register(() -> given().when().delete("/restapis/" + apiId));
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+ String method = "/restapis/" + apiId + "/resources/" + rootId + "/methods/GET";
+ given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE"))
+ .when().put(method).then().statusCode(201);
+ given().contentType(ContentType.JSON).body(Map.of())
+ .when().put(method + "/responses/200").then().statusCode(201);
+ given().contentType(ContentType.JSON)
+ .body(Map.of("type", "MOCK", "requestTemplates", Map.of("application/json", "{\"statusCode\": 200}")))
+ .when().put(method + "/integration").then().statusCode(201);
+ given().contentType(ContentType.JSON)
+ .body(Map.of("selectionPattern", "", "responseTemplates",
+ Map.of("application/json", "{\"from\":\"rest\"}")))
+ .when().put(method + "/integration/responses/200").then().statusCode(201);
+ given().contentType(ContentType.JSON).body(Map.of("stageName", STAGE))
+ .when().post("/restapis/" + apiId + "/deployments").then().statusCode(201);
+ return apiId;
+ }
+
+ private Distribution createDistribution(String domain, String originPath, String originRequestPolicyId) {
+ return createDistribution(domain, originPath, originRequestPolicyId, 443);
+ }
+
+ private Distribution createDistribution(String domain, String originPath, String originRequestPolicyId,
+ int originPort) {
+ Origin origin = new Origin();
+ origin.setId("api");
+ origin.setDomainName(domain);
+ origin.setOriginPath(originPath);
+ Map<String, Object> customOriginConfig = new LinkedHashMap<>();
+ customOriginConfig.put("HTTPPort", String.valueOf(originPort));
+ customOriginConfig.put("HTTPSPort", String.valueOf(originPort));
+ customOriginConfig.put("OriginProtocolPolicy", originPort == 443 ? "https-only" : "http-only");
+ origin.setCustomOriginConfig(customOriginConfig);
+ DefaultCacheBehavior behavior = new DefaultCacheBehavior();
+ behavior.setTargetOriginId("api");
+ behavior.setViewerProtocolPolicy("allow-all");
+ behavior.setAllowedMethods(List.of("GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"));
+ behavior.setCachePolicyId(CACHING_DISABLED);
+ behavior.setOriginRequestPolicyId(originRequestPolicyId);
+ DistributionConfig config = new DistributionConfig();
+ config.setEnabled(true);
+ config.setOrigins(List.of(origin));
+ config.setDefaultCacheBehavior(behavior);
+ Distribution distribution = new Distribution();
+ distribution.setConfig(config);
+ Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
+ cleanup.register(() -> cloudFrontService.removeDistribution(created.getId()));
+ return created;
+ }
+}