From 41717057c5f2e48da643307d2526976151d45c09 Mon Sep 17 00:00:00 2001 From: Liron Cohen Date: Wed, 28 Oct 2026 01:04:45 +0200 Subject: [PATCH] refactor(apigateway): decide execute-api host routing before applying it (#6763) * refactor(apigateway): decide execute-api host routing before applying it ApiGatewayExecuteApiHostFilter.decide() returns a RouteDecision for a host and path without touching the request. filter() applies it: account and region of the API owner, the REST or HTTP API rewrite, or the 404 for a disabled endpoint. The lookups for an API with an owner run under the owner's account, and the caller's account and region are restored afterwards. No change in behavior for execute-api requests. * test(apigateway): give the API owner its own region in the restore tests The owner and the caller used the same region, so the tests passed even if underAccountOf() did not restore the caller's region. The owner now uses eu-west-1, and each restore test asserts the caller's region. --------- Co-authored-by: liRONCO11 <7966063+liRONCO11@users.noreply.github.com> --- .../ApiGatewayExecuteApiHostFilter.java | 157 ++++++++++---- ...tewayExecuteApiHostFilterDecisionTest.java | 204 ++++++++++++++++++ 2 files changed, 314 insertions(+), 47 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterDecisionTest.java 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 7d1fe41423..d5ac248a13 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 @@ -23,6 +23,7 @@ import org.jboss.logging.Logger; import java.net.URI; import java.util.Locale; import java.util.Optional; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -33,6 +34,8 @@ import java.util.regex.Pattern; public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter { private static final Logger LOG = Logger.getLogger(ApiGatewayExecuteApiHostFilter.class); + public static final String NOT_FOUND_BODY = "{\"message\":\"Not Found\"}"; + private static final String DEFAULT_STAGE = "$default"; private static final Pattern EXECUTE_API_PREFIX = Pattern.compile("^([a-z0-9-]+)\\.execute-api\\.(.+)$", Pattern.CASE_INSENSITIVE); @@ -103,24 +106,51 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) { String host = RequestHost.of(requestContext); - if (host == null) { - return; + URI originalUri = requestContext.getUriInfo().getRequestUri(); + String originalPath = originalUri.getRawPath(); + + RouteDecision decision = decide(host, originalPath, requestContext.getHeaderString("Authorization")); + if (this.requestContext != null) { + if (decision.owner() != null) { + this.requestContext.setAccountId(decision.owner().accountId()); + this.requestContext.setRegion(decision.owner().region()); + } } + switch (decision.kind()) { + case NONE -> { } + case DISABLED -> requestContext.abortWith(notFoundResponse()); + case REST_API -> routeToRestApi(requestContext, originalUri, originalPath, decision.apiId()); + case HTTP_API -> routeToHttpApi(requestContext, host, originalUri, originalPath, decision); + } + } + + private static Response notFoundResponse() { + return Response.status(Response.Status.NOT_FOUND) + .entity(NOT_FOUND_BODY) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + /** + * Decides what {@link #filter} does for a host and raw path, without touching the request. The + * lookups run under the account of the API's owner, and the caller's account and region are + * restored afterwards. + */ + RouteDecision decide(String host, String originalPath, String authorization) { String apiId = extractApiId(host, baseHostname); if (apiId == null) { - return; + return RouteDecision.none(null); } - Optional owner = apiGatewayLookup.findApiOwner(apiId); - String region; - if (owner.isPresent()) { - ApiGatewayV2Service.ApiOwner apiOwner = owner.get(); - if (this.requestContext != null) { - this.requestContext.setAccountId(apiOwner.accountId()); - this.requestContext.setRegion(apiOwner.region()); - } - region = apiOwner.region(); - } else { + ApiGatewayV2Service.ApiOwner owner = apiGatewayLookup.findApiOwner(apiId).orElse(null); + // 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 RouteDecision.none(owner); + } + if (owner == null) { // Region: the host label when it is a real AWS region (…execute-api.{region}.…), else // the SigV4 credential scope. The cross-region apiId scan (resolveApiRegion) is the // final fallback so an API created outside the default region still resolves — @@ -128,21 +158,15 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter { String hostRegion = regionResolver.resolveRegionFromHost(host); String preferredRegion = hostRegion != null ? hostRegion - : regionResolver.resolveRegionFromAuth(requestContext.getHeaderString("Authorization")); - region = apiGatewayLookup.resolveApiRegion(preferredRegion, apiId); - } - - 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; + : regionResolver.resolveRegionFromAuth(authorization); + return decideInRegion(apiId, apiGatewayLookup.resolveApiRegion(preferredRegion, apiId), + originalPath, owner); } + return underAccountOf(owner, () -> decideInRegion(apiId, owner.region(), originalPath, owner)); + } + private RouteDecision decideInRegion(String apiId, String region, String originalPath, + ApiGatewayV2Service.ApiOwner owner) { try { String protocolType = apiGatewayLookup.protocolType(region, apiId); // HTTP APIs route all their invoke traffic through this filter. WEBSOCKET APIs route @@ -151,49 +175,61 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter { boolean routable = "HTTP".equals(protocolType) || ("WEBSOCKET".equals(protocolType) && isConnectionsManagementPath(originalPath)); if (!routable) { - return; + return RouteDecision.none(owner); } if (apiGatewayLookup.executeApiEndpointDisabled(region, apiId)) { - requestContext.abortWith(Response.status(Response.Status.NOT_FOUND) - .entity("{\"message\":\"Not Found\"}") - .type(MediaType.APPLICATION_JSON) - .build()); - return; + return RouteDecision.disabled(owner); } } catch (AwsException e) { // The v2 owner lookup is account-independent. When it found no owner, let the // REST execute controller resolve the API after account context is established. - if (owner.isEmpty()) { - routeToRestApi(requestContext, originalUri, originalPath, apiId); - return; + if (owner == null) { + return RouteDecision.restApi(apiId); } LOG.debugv(e, "Execute API host did not resolve to a routable API: apiId={0}, region={1}", apiId, region); - return; + return RouteDecision.none(owner); } 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; + return RouteDecision.httpApi(apiId, region, owner, firstSegment, stripFirstSegment(path)); } + if (!stageExists(region, apiId, DEFAULT_STAGE)) { + return RouteDecision.none(owner); + } + return RouteDecision.httpApi(apiId, region, owner, DEFAULT_STAGE, path); + } - String newPath = "/execute-api/" + apiId + "/" + stageName + "/"; - if (!remainingPath.isEmpty()) { - newPath += remainingPath; + private T underAccountOf(ApiGatewayV2Service.ApiOwner owner, Supplier action) { + if (requestContext == null) { + return action.get(); + } + String callerAccount = requestContext.getAccountId(); + String callerRegion = requestContext.getRegion(); + requestContext.setAccountId(owner.accountId()); + requestContext.setRegion(owner.region()); + try { + return action.get(); + } finally { + requestContext.setAccountId(callerAccount); + requestContext.setRegion(callerRegion); + } + } + + private void routeToHttpApi(ContainerRequestContext requestContext, String host, URI originalUri, + String originalPath, RouteDecision decision) { + String newPath = "/execute-api/" + decision.apiId() + "/" + decision.stage() + "/"; + if (!decision.remainingPath().isEmpty()) { + newPath += decision.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); + routeContext.routeToHttpApi(decision.region()); // AWS_IAM dispatch rebuilds the caller's canonical request, which covers the path they // signed: the virtual-host path, not the /execute-api/... form this rewrite produces. routeContext.recordSignedRequestPath(originalPath); @@ -223,6 +259,33 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter { } } + enum RouteKind { NONE, DISABLED, REST_API, HTTP_API } + + /** + * The outcome of the routing decision. {@code owner} is the HTTP or WebSocket API owner found for + * the host, whatever the outcome, so that {@link #filter} can switch to its account, or null. + */ + record RouteDecision(RouteKind kind, String apiId, ApiGatewayV2Service.ApiOwner owner, + String region, String stage, String remainingPath) { + + static RouteDecision none(ApiGatewayV2Service.ApiOwner owner) { + return new RouteDecision(RouteKind.NONE, null, owner, null, null, null); + } + + static RouteDecision disabled(ApiGatewayV2Service.ApiOwner owner) { + return new RouteDecision(RouteKind.DISABLED, null, owner, null, null, null); + } + + static RouteDecision restApi(String apiId) { + return new RouteDecision(RouteKind.REST_API, apiId, null, null, null, null); + } + + static RouteDecision httpApi(String apiId, String region, ApiGatewayV2Service.ApiOwner owner, + String stage, String remainingPath) { + return new RouteDecision(RouteKind.HTTP_API, apiId, owner, region, stage, remainingPath); + } + } + interface ApiGatewayLookup { default Optional findApiOwner(String apiId) { return Optional.empty(); 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 new file mode 100644 index 0000000000..6e9af433c5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterDecisionTest.java @@ -0,0 +1,204 @@ +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.core.common.RequestContext; +import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ApiGatewayExecuteApiHostFilterDecisionTest { + + private static final String API_ID = "abc123"; + private static final String REGION = "us-east-1"; + private static final String OWNER_REGION = "eu-west-1"; + 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 final RequestContext viewer = viewerContext(); + private final StubLookup lookup = new StubLookup(viewer); + private final ApiGatewayExecuteApiHostFilter filter = new ApiGatewayExecuteApiHostFilter( + lookup, new RegionResolver(REGION, VIEWER_ACCOUNT), new ApiGatewayExecuteRouteContext(), + "localhost", viewer); + + @Test + void httpApiOfAnotherAccountIsLookedUpUnderTheOwnerAndTheViewerContextIsRestored() { + lookup.owner = new ApiGatewayV2Service.ApiOwner(OWNER_ACCOUNT, OWNER_REGION); + lookup.httpApi = true; + + ApiGatewayExecuteApiHostFilter.RouteDecision decision = filter.decide(HOST, "/dev/accounts", null); + + assertEquals(ApiGatewayExecuteApiHostFilter.RouteKind.HTTP_API, decision.kind()); + assertEquals("dev", decision.stage()); + assertEquals("accounts", decision.remainingPath()); + assertEquals(List.of(OWNER_ACCOUNT, OWNER_ACCOUNT), lookup.accountsSeen); + assertEquals(VIEWER_ACCOUNT, viewer.getAccountId()); + assertEquals(REGION, viewer.getRegion()); + } + + @Test + void viewerContextIsRestoredWhenALookupFails() { + lookup.owner = new ApiGatewayV2Service.ApiOwner(OWNER_ACCOUNT, OWNER_REGION); + + ApiGatewayExecuteApiHostFilter.RouteDecision decision = filter.decide(HOST, "/dev/accounts", null); + + assertEquals(ApiGatewayExecuteApiHostFilter.RouteKind.NONE, decision.kind()); + assertEquals(VIEWER_ACCOUNT, viewer.getAccountId()); + assertEquals(REGION, viewer.getRegion()); + } + + @Test + void restApiIsDecidedWithoutAnOwner() { + ApiGatewayExecuteApiHostFilter.RouteDecision decision = filter.decide(HOST, "/dev/", null); + + assertEquals(ApiGatewayExecuteApiHostFilter.RouteKind.REST_API, decision.kind()); + assertEquals(API_ID, decision.apiId()); + assertNull(decision.owner()); + } + + @Test + void httpApiWithoutOwnerIsDecidedInTheResolvedRegion() { + lookup.httpApi = true; + + ApiGatewayExecuteApiHostFilter.RouteDecision decision = filter.decide(HOST, "/dev/accounts", null); + + assertEquals(ApiGatewayExecuteApiHostFilter.RouteKind.HTTP_API, decision.kind()); + assertEquals(REGION, decision.region()); + assertNull(decision.owner()); + assertEquals(List.of(VIEWER_ACCOUNT, VIEWER_ACCOUNT), lookup.accountsSeen); + } + + @Test + void stagelessPathFallsBackToTheDefaultStage() { + lookup.owner = new ApiGatewayV2Service.ApiOwner(OWNER_ACCOUNT, REGION); + lookup.httpApi = true; + lookup.stage = "$default"; + + ApiGatewayExecuteApiHostFilter.RouteDecision decision = filter.decide(HOST, "/accounts", null); + + assertEquals(ApiGatewayExecuteApiHostFilter.RouteKind.HTTP_API, decision.kind()); + assertEquals("$default", decision.stage()); + assertEquals("accounts", decision.remainingPath()); + } + + @Test + void disabledEndpointIsDecidedAsDisabledWithTheOwner() { + ApiGatewayV2Service.ApiOwner owner = new ApiGatewayV2Service.ApiOwner(OWNER_ACCOUNT, REGION); + lookup.owner = owner; + lookup.httpApi = true; + lookup.disabled = true; + + ApiGatewayExecuteApiHostFilter.RouteDecision decision = filter.decide(HOST, "/dev/accounts", null); + + assertEquals(ApiGatewayExecuteApiHostFilter.RouteKind.DISABLED, decision.kind()); + assertEquals(owner, decision.owner()); + } + + @Test + void internalExecuteApiPathIsDecidedAsNoneWithoutLookingUpTheApi() { + lookup.owner = new ApiGatewayV2Service.ApiOwner(OWNER_ACCOUNT, REGION); + lookup.httpApi = true; + + ApiGatewayExecuteApiHostFilter.RouteDecision decision = + filter.decide(HOST, "/execute-api/" + API_ID + "/dev/", null); + + assertEquals(ApiGatewayExecuteApiHostFilter.RouteKind.NONE, decision.kind()); + assertTrue(lookup.accountsSeen.isEmpty()); + } + + @Test + void nonExecuteApiHostIsDecidedAsNone() { + ApiGatewayExecuteApiHostFilter.RouteDecision decision = filter.decide("example.com", "/dev/", null); + + assertEquals(ApiGatewayExecuteApiHostFilter.RouteKind.NONE, decision.kind()); + assertNull(decision.apiId()); + } + + @Test + void ambiguousApiIdFailsAndLeavesTheViewerContextUntouched() { + lookup.ambiguous = true; + + assertThrows(AwsException.class, () -> filter.decide(HOST, "/dev/accounts", null)); + assertEquals(VIEWER_ACCOUNT, viewer.getAccountId()); + assertEquals(REGION, viewer.getRegion()); + } + + @Test + void viewerContextIsRestoredWhenALookupThrowsUnexpectedly() { + lookup.owner = new ApiGatewayV2Service.ApiOwner(OWNER_ACCOUNT, OWNER_REGION); + lookup.crash = true; + + assertThrows(IllegalStateException.class, () -> filter.decide(HOST, "/dev/accounts", null)); + assertEquals(VIEWER_ACCOUNT, viewer.getAccountId()); + assertEquals(REGION, viewer.getRegion()); + } + + private static RequestContext viewerContext() { + RequestContext context = new RequestContext(); + context.setAccountId(VIEWER_ACCOUNT); + context.setRegion(REGION); + return context; + } + + private static final class StubLookup implements ApiGatewayExecuteApiHostFilter.ApiGatewayLookup { + private final RequestContext viewer; + private final List accountsSeen = new ArrayList<>(); + private ApiGatewayV2Service.ApiOwner owner; + private String stage = "dev"; + private boolean disabled; + private boolean crash; + private boolean httpApi; + private boolean ambiguous; + + private StubLookup(RequestContext viewer) { + this.viewer = viewer; + } + + @Override + public Optional findApiOwner(String apiId) { + if (ambiguous) { + throw new AwsException("ConflictException", "ambiguous", 409); + } + return Optional.ofNullable(owner); + } + + @Override + public String resolveApiRegion(String preferredRegion, String apiId) { + return preferredRegion; + } + + @Override + public String protocolType(String region, String apiId) { + accountsSeen.add(viewer.getAccountId()); + if (crash) { + throw new IllegalStateException("storage failure"); + } + if (!httpApi) { + throw new AwsException("NotFoundException", "Invalid API id specified", 404); + } + return "HTTP"; + } + + @Override + public boolean executeApiEndpointDisabled(String region, String apiId) { + return disabled; + } + + @Override + public void requireStage(String region, String apiId, String stageName) { + accountsSeen.add(viewer.getAccountId()); + if (!stage.equals(stageName)) { + throw new AwsException("NotFoundException", "Stage not found", 404); + } + } + } +}