mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(cloudfront): serve execute-api custom origins of this Floci in-process (#6754)
* feat(cloudfront): serve execute-api custom origins of this Floci in-process A custom origin whose domain is an execute-api endpoint of an HTTP or REST API in this Floci is now served through Floci's own listener, as Lambda Web Function endpoints are, with the execute-api domain as Host. Before, the origin went through DNS and the viewer got 502. ApiGatewayExecuteApiHostFilter.routes() says whether the host filter rewrites a host and path onto an API. A request that it does not route (a WebSocket API, a disabled endpoint, a missing stage, another region) answers 404 and never reaches Floci's other endpoints. Dot segments in the forwarded path are resolved before that check. A forwarded viewer Host answers 502. Every other origin is unchanged. * refactor(cloudfront): share the execute-api routing decision with the host filter ApiGatewayExecuteApiHostFilter.decide() returns the routing decision without touching the request, with its lookups under the API owner's account. filter() applies the decision and routes() reuses it, so the two cannot drift. This fixes two cases where routes() differed from filter(): an HTTP API owned by another account than the viewer is now served through CloudFront, and a REST API origin whose region label is not the API's region now answers 404. The 404 body is one constant. * refactor(apigateway): keep Optional out of the route decision record RouteDecision stores the API owner as a nullable value, and the decision helpers take it as a plain parameter. Optional stays the return type of the owner lookup only, as AGENTS.md asks. * refactor(cloudfront): name the ignored host parse failure and drop the Optional test field --------- Co-authored-by: liRONCO11 <7966063+liRONCO11@users.noreply.github.com>
This commit is contained in:
1 parent
a636de20dc
commit
548788840c
5 files changed
+508
-6
No files matched your search
+32
@@ -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);
|
||||
|
||||
+62
-6
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user