perf(apigateway): skip execute-api work on requests for other services (#7691)

The execute-api host filter parsed the request URI and ran a regular
expression on every request. The response filter created the
request-scoped route context on every response, and that object calls
UUID.randomUUID() when it is created.

The host filter now refuses a host without the regular expression and
returns before it reads anything else. The response filter checks the
path first, so the route context is created only for API Gateway paths.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-06 20:00:27 -04:00
1 parent 949eb894e9
commit ae196fb9ac
4 files changed
+125 -2

No files matched your search

@@ -37,6 +37,7 @@ 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 String EXECUTE_API_LABEL = ".execute-api.";
private static final Pattern EXECUTE_API_PREFIX = Pattern.compile("^([a-z0-9-]+)\\.execute-api\\.(.+)$",
Pattern.CASE_INSENSITIVE);
@@ -113,10 +114,14 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
String host = RequestHost.of(requestContext);
String apiId = extractApiId(host, baseHostname);
if (apiId == null) {
return;
}
URI originalUri = requestContext.getUriInfo().getRequestUri();
String originalPath = originalUri.getRawPath();
RouteDecision decision = decide(host, originalPath, requestContext.getHeaderString("Authorization"));
RouteDecision decision = decide(apiId, host, originalPath, requestContext.getHeaderString("Authorization"));
if (this.requestContext != null) {
if (decision.owner() != null) {
this.requestContext.setAccountId(decision.owner().accountId());
@@ -167,7 +172,10 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
* restored afterwards.
*/
RouteDecision decide(String host, String originalPath, String authorization) {
String apiId = extractApiId(host, baseHostname);
return decide(extractApiId(host, baseHostname), host, originalPath, authorization);
}
private RouteDecision decide(String apiId, String host, String originalPath, String authorization) {
if (apiId == null) {
return RouteDecision.none(null);
}
@@ -347,6 +355,11 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
return null;
}
int dot = host.indexOf('.');
if (dot <= 0 || !host.regionMatches(true, dot, EXECUTE_API_LABEL, 0, EXECUTE_API_LABEL.length())) {
return null;
}
Matcher matcher = EXECUTE_API_PREFIX.matcher(stripPort(host));
if (!matcher.matches()) {
return null;
@@ -22,6 +22,11 @@ public class ApiGatewayExecuteResponseFilter implements ContainerResponseFilter
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
String path = request.getUriInfo().getPath();
if (!path.contains("/execute-api/") && !path.startsWith("/restapis/")) {
return;
}
// Reading routeContext creates the request-scoped bean, so other services must not reach it.
if (!routeContext.isRestApiRoute()) {
return;
}
@@ -277,6 +277,39 @@ class ApiGatewayExecuteApiHostFilterTest {
"abc123.execute-api.eu-south-9.localhost.floci.io", null));
}
@Test
void extractApiIdRejectsHostsThatCannotBeExecuteApiHosts() {
assertNull(ApiGatewayExecuteApiHostFilter.extractApiId("localhost:4566", null));
assertNull(ApiGatewayExecuteApiHostFilter.extractApiId(
".execute-api.us-east-1.localhost", null));
assertNull(ApiGatewayExecuteApiHostFilter.extractApiId(
"a.b.execute-api.us-east-1.localhost", null));
assertNull(ApiGatewayExecuteApiHostFilter.extractApiId("sqs.us-east-1.localhost:4566", null));
}
@Test
void extractApiIdAcceptsMixedCaseLabel() {
assertEquals("abc123", ApiGatewayExecuteApiHostFilter.extractApiId(
"AbC123.EXECUTE-API.us-east-1.localhost:4566", null));
}
@Test
void filterLeavesNonExecuteApiHostWithoutReadingUriOrAuthorization() {
ContainerRequestContext context = (ContainerRequestContext) Proxy.newProxyInstance(
ContainerRequestContext.class.getClassLoader(),
new Class<?>[] { ContainerRequestContext.class },
(proxy, method, args) -> {
if ("getHeaderString".equals(method.getName()) && "Host".equals(args[0])) {
return "sqs.us-east-1.localhost:4566";
}
throw new AssertionError("unexpected call " + method.getName());
});
new ApiGatewayExecuteApiHostFilter(
new FakeApiGatewayLookup(), new RegionResolver(REGION, "000000000000"))
.filter(context);
}
@Test
void ignoresRegionShapedLabelThatIsNotAKnownRegion() {
assertNull(ApiGatewayExecuteApiHostFilter.extractApiId(
@@ -0,0 +1,72 @@
package io.floci.aws.services.apigateway;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class ApiGatewayExecuteResponseFilterTest {
private final MultivaluedMap<String, Object> responseHeaders = new MultivaluedHashMap<>();
@ParameterizedTest
@ValueSource(strings = {"/", "/bench/k/1"})
void leavesResponsesForOtherServicesAloneWithoutTouchingTheRouteContext(String path) {
ApiGatewayExecuteRouteContext routeContext = mock(ApiGatewayExecuteRouteContext.class);
new ApiGatewayExecuteResponseFilter(routeContext).filter(request(path), response());
assertThat(responseHeaders, is(anEmptyMap()));
verifyNoInteractions(routeContext);
}
@ParameterizedTest
@ValueSource(strings = {
"/execute-api/abc/prod/x",
"/_aws/execute-api/abc/prod/x",
"/restapis/abc/prod/_user_request_/x"
})
void setsRequestIdentifiersOnRestApiExecution(String path) {
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
routeContext.routeToRestApi();
new ApiGatewayExecuteResponseFilter(routeContext).filter(request(path), response());
assertThat(responseHeaders.getFirst("x-amzn-RequestId"), is(notNullValue()));
assertThat(responseHeaders.getFirst("x-amz-apigw-id"), is(notNullValue()));
}
@Test
void leavesResponsesAloneForApiGatewayPathsThatAreNotRestRoutes() {
new ApiGatewayExecuteResponseFilter(new ApiGatewayExecuteRouteContext())
.filter(request("/restapis/abc"), response());
assertThat(responseHeaders, is(anEmptyMap()));
}
private static ContainerRequestContext request(String path) {
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getPath()).thenReturn(path);
ContainerRequestContext request = mock(ContainerRequestContext.class);
when(request.getUriInfo()).thenReturn(uriInfo);
return request;
}
private ContainerResponseContext response() {
ContainerResponseContext response = mock(ContainerResponseContext.class);
when(response.getHeaders()).thenReturn(responseHeaders);
return response;
}
}