fix(apigateway): verify AWS_IAM signatures against the custom-domain path (#4092)

* fix(apigateway): verify AWS_IAM signatures against the custom-domain path

The custom domain filter rewrites a request onto /execute-api/... before
dispatch but, unlike the execute-api host filter, never recorded the path
the caller actually signed. SigV4 verification then rebuilt the canonical
request from the rewritten path, so every AWS_IAM method invoked through a
custom domain was rejected with InvalidSignatureException.

Record the original raw path on ApiGatewayExecuteRouteContext, matching
ApiGatewayExecuteApiHostFilter, and give the filter an explicit
ApplicationScoped scope so the request-scoped context injects through a
client proxy. Covers both REST and HTTP API custom domains, since v2 API
mappings are stored as base path mappings and routed by the same filter.

* test(apigateway): cover AWS_IAM through an HTTP API custom domain

A v2 API mapping is stored as a base path mapping and routed by the same
custom domain filter as REST APIs, so the fix applies to HTTP APIs too. Prove
it rather than assert it: a signed request through the domain reaches the
integration, and unsigned, rewritten-path and other-path signatures are
rejected with v2's flat 403 Forbidden.
This commit is contained in:
stodan authored and GitHub committed 2026-09-21 16:11:06 -04:00
1 parent 7b29fdcf83
commit c083aad12b
5 files changed
+515 -2

No files matched your search

+4 -1
View File
@@ -139,7 +139,10 @@ Templates can create domains and mappings with `AWS::ApiGateway::DomainName` and
A method (v1) or route (v2) whose `authorizationType` is `AWS_IAM` requires a SigV4-signed caller.
Before the integration runs, the signature is verified against the request as it arrived (method,
path, query string, the headers named in `SignedHeaders`, and the SHA-256 of the body). Both
path, query string, the headers named in `SignedHeaders`, and the SHA-256 of the body). A request
that reaches the API through a [custom domain](#custom-domain-names) or an `execute-api` virtual
host is verified against the path the caller signed, not the `/execute-api/...` form Floci
rewrites it to internally. Both
placements AWS accepts are honoured: an `Authorization` header and a presigned query string
(`X-Amz-Algorithm=AWS4-HMAC-SHA256`). The credential must be scoped to the `execute-api` service.
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
@@ -28,16 +29,20 @@ import java.net.URI;
@Provider
@PreMatching
@Priority(10) // Run after Lambda URL filter (5) but before general processing
@ApplicationScoped
public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(ApiGatewayCustomDomainFilter.class);
private static final String REGIONAL_SUFFIX = ".regional.local";
private final ApiGatewayService apiGatewayService;
private final ApiGatewayExecuteRouteContext routeContext;
@Inject
public ApiGatewayCustomDomainFilter(ApiGatewayService apiGatewayService) {
public ApiGatewayCustomDomainFilter(ApiGatewayService apiGatewayService,
ApiGatewayExecuteRouteContext routeContext) {
this.apiGatewayService = apiGatewayService;
this.routeContext = routeContext;
}
@Override
@@ -100,6 +105,9 @@ public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter {
.build();
LOG.debugv("Custom domain routing: {0}{1} -> {2}", host, path, newUri.getPath());
// AWS_IAM dispatch rebuilds the caller's canonical request, which covers the path they
// signed: the custom-domain path, not the /execute-api/... form this rewrite produces.
routeContext.recordSignedRequestPath(path);
requestContext.setRequestUri(newUri);
}
@@ -0,0 +1,137 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.net.URI;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ApiGatewayCustomDomainFilterTest {
private static final String DOMAIN = "api.example.com";
private static final String API_ID = "abc123";
@Test
void recordsCustomDomainPathAsTheSignedPath() {
ApiGatewayService service = serviceWithMapping("v1", "prod");
RecordingRequest request = new RecordingRequest(
DOMAIN + ".regional.local:4566",
URI.create("http://" + DOMAIN + ".regional.local:4566/v1/iam?tenant=alpha"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
new ApiGatewayCustomDomainFilter(service, routeContext).filter(request.context());
assertEquals("/execute-api/" + API_ID + "/prod/iam", request.routedUri().getRawPath());
assertEquals("tenant=alpha", request.routedUri().getRawQuery());
assertEquals("/v1/iam", routeContext.signedRequestPath());
}
@Test
void recordsBareDomainPathAsTheSignedPath() {
ApiGatewayService service = serviceWithMapping("(none)", "prod");
RecordingRequest request = new RecordingRequest(
DOMAIN, URI.create("http://" + DOMAIN + "/orders/42"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
new ApiGatewayCustomDomainFilter(service, routeContext).filter(request.context());
assertEquals("/execute-api/" + API_ID + "/prod/orders/42", request.routedUri().getRawPath());
assertEquals("/orders/42", routeContext.signedRequestPath());
}
@Test
void leavesSignedPathUnsetWhenHostIsNotACustomDomain() {
ApiGatewayService service = mock(ApiGatewayService.class);
RecordingRequest request = new RecordingRequest(
"localhost:4566", URI.create("http://localhost:4566/v1/iam"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
new ApiGatewayCustomDomainFilter(service, routeContext).filter(request.context());
assertNull(request.routedUri());
assertNull(routeContext.signedRequestPath());
}
@Test
void leavesSignedPathUnsetWhenNoMappingMatches() {
ApiGatewayService service = mock(ApiGatewayService.class);
CustomDomain domain = new CustomDomain();
domain.setDomainName(DOMAIN);
when(service.findDomainByName(DOMAIN)).thenReturn(domain);
RecordingRequest request = new RecordingRequest(
DOMAIN, URI.create("http://" + DOMAIN + "/unmapped"));
ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext();
new ApiGatewayCustomDomainFilter(service, routeContext).filter(request.context());
assertNull(request.routedUri());
assertNull(routeContext.signedRequestPath());
}
private static ApiGatewayService serviceWithMapping(String basePath, String stage) {
ApiGatewayService service = mock(ApiGatewayService.class);
CustomDomain domain = new CustomDomain();
domain.setDomainName(DOMAIN);
BasePathMapping mapping = new BasePathMapping(basePath, API_ID, stage);
when(service.findDomainByRegionalHostname(DOMAIN + ".regional.local")).thenReturn(domain);
when(service.findDomainByName(DOMAIN)).thenReturn(domain);
when(service.resolveBasePathMapping(anyString(), anyString())).thenReturn(mapping);
when(service.stripBasePath(anyString(), eq(mapping)))
.thenAnswer(invocation -> {
String path = invocation.getArgument(0);
String prefix = "/" + basePath;
return path.startsWith(prefix) ? path.substring(prefix.length()) : path;
});
return service;
}
private static final class RecordingRequest {
private final String host;
private final URI requestUri;
private URI routedUri;
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" -> "Host".equalsIgnoreCase((String) args[0]) ? host : null;
case "getUriInfo" -> uriInfo();
case "setRequestUri" -> {
routedUri = (URI) args[0];
yield null;
}
default -> throw new UnsupportedOperationException(method.getName());
});
}
private URI routedUri() {
return routedUri;
}
private UriInfo uriInfo() {
return (UriInfo) Proxy.newProxyInstance(
UriInfo.class.getClassLoader(),
new Class<?>[] { UriInfo.class },
(proxy, method, args) -> switch (method.getName()) {
case "getRequestUri" -> requestUri;
default -> throw new UnsupportedOperationException(method.getName());
});
}
}
}
@@ -0,0 +1,170 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
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.time.Instant;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
/**
* An {@code AWS_IAM} method invoked through a custom domain. The caller signs the request it
* actually sends, {@code Host: <domain>} and the base-path-mapped path, while the custom domain
* filter rewrites the URI onto {@code /execute-api/...} before dispatch. Verification has to run
* against the signed form, so the rewritten path must not leak into the canonical request.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayCustomDomainIamAuthIntegrationTest {
private static final String REGION = "us-east-1";
private static final String ACCESS_KEY = "test";
private static final String SECRET_KEY = "test";
private static final String STAGE = "prod";
private static final String DOMAIN = "iam.example.com";
private static final String BASE_PATH = "v1";
private static String apiId;
@Test
@Order(0)
void setup() {
apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"custom-domain-iam-auth-test\"}")
.when().post("/restapis")
.then().statusCode(201)
.body("id", notNullValue())
.extract().path("id");
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200)
.extract().path("item[0].id");
createMockMethod(rootId, "iam", "AWS_IAM");
String deploymentId = given().contentType(ContentType.JSON)
.body("{\"description\":\"v1\"}")
.when().post("/restapis/" + apiId + "/deployments")
.then().statusCode(201)
.extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"stageName\":\"" + STAGE + "\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"domainName\":\"" + DOMAIN + "\","
+ "\"certificateArn\":\"arn:aws:acm:us-east-1:123456789012:certificate/abc\"}")
.when().post("/domainnames")
.then().statusCode(201)
.body("regionalDomainName", equalTo(DOMAIN + ".regional.local"));
given().contentType(ContentType.JSON)
.body("{\"basePath\":\"" + BASE_PATH + "\",\"restApiId\":\"" + apiId + "\","
+ "\"stage\":\"" + STAGE + "\"}")
.when().post("/domainnames/" + DOMAIN + "/basepathmappings")
.then().statusCode(201);
}
private static void createMockMethod(String rootId, String pathPart, String authorizationType) {
String resourceId = given().contentType(ContentType.JSON)
.body("{\"pathPart\":\"" + pathPart + "\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201)
.extract().path("id");
String methodPath = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
given().contentType(ContentType.JSON)
.body("{\"authorizationType\":\"" + authorizationType + "\"}")
.when().put(methodPath)
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"responseParameters\":{}}")
.when().put(methodPath + "/responses/200")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
.when().put(methodPath + "/integration")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"\",\"responseTemplates\":"
+ "{\"application/json\":\"{\\\"reached\\\":\\\"integration\\\"}\"}}")
.when().put(methodPath + "/integration/responses/200")
.then().statusCode(201);
}
@Test
@Order(10)
void unsignedRequestThroughCustomDomainIsRejected() {
given().header("Host", DOMAIN)
.when().get(customDomainPath())
.then().statusCode(403)
.header("x-amzn-ErrorType", "MissingAuthenticationTokenException")
.body("message", equalTo("Missing Authentication Token"));
}
@Test
@Order(11)
void requestSignedForTheBareDomainReachesTheIntegration() throws Exception {
given().header("Host", DOMAIN)
.headers(signedHeaders(customDomainPath(), DOMAIN))
.when().get(customDomainPath())
.then().statusCode(200)
.body("reached", equalTo("integration"));
}
@Test
@Order(12)
void requestSignedForTheRegionalDomainReachesTheIntegration() throws Exception {
String host = DOMAIN + ".regional.local:4566";
given().header("Host", host)
.headers(signedHeaders(customDomainPath(), host))
.when().get(customDomainPath())
.then().statusCode(200)
.body("reached", equalTo("integration"));
}
@Test
@Order(13)
void signatureOverTheRewrittenExecuteApiPathIsRejected() throws Exception {
String rewrittenPath = "/execute-api/" + apiId + "/" + STAGE + "/iam";
given().header("Host", DOMAIN)
.headers(signedHeaders(rewrittenPath, DOMAIN))
.when().get(customDomainPath())
.then().statusCode(403)
.header("x-amzn-ErrorType", "InvalidSignatureException");
}
@Test
@Order(14)
void signatureForAnotherCustomDomainPathIsRejected() throws Exception {
given().header("Host", DOMAIN)
.headers(signedHeaders("/" + BASE_PATH + "/other", DOMAIN))
.when().get(customDomainPath())
.then().statusCode(403)
.header("x-amzn-ErrorType", "InvalidSignatureException");
}
@Test
@Order(999)
void cleanup() {
given().when().delete("/domainnames/" + DOMAIN);
if (apiId != null) {
given().when().delete("/restapis/" + apiId);
}
}
private static String customDomainPath() {
return "/" + BASE_PATH + "/iam";
}
private static Map<String, String> signedHeaders(String path, String host) throws Exception {
return ExecuteApiRequestSigner.signedHeaders(
"GET", path, Map.of(), host, null, ACCESS_KEY, SECRET_KEY, REGION, Instant.now());
}
}
@@ -0,0 +1,195 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
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.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The HTTP API (v2) half of custom-domain IAM authorization. A v2 API mapping is stored as a
* base path mapping and routed by the same custom domain filter as REST APIs, so the caller
* signs {@code Host: <domain>} and the mapped path while the filter rewrites the URI onto
* {@code /execute-api/...}. Verification has to use the signed form here too, and a rejection
* takes v2's flat {@code 403 Forbidden} shape rather than v1's {@code x-amzn-ErrorType}.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class HttpApiCustomDomainIamAuthorizationTest {
private static final String REGION = "us-east-1";
private static final String ACCESS_KEY = "test";
private static final String SECRET_KEY = "test";
private static final String STAGE = "test";
private static final String DOMAIN = "iam-http.example.com";
private static final String MAPPING_KEY = "v1";
private static HttpServer backendServer;
private static final AtomicInteger backendHits = new AtomicInteger();
private static String httpApiId;
@BeforeAll
static void startBackend() throws Exception {
backendServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backendServer.createContext("/", exchange -> {
backendHits.incrementAndGet();
byte[] body = "reached the integration".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
backendServer.start();
}
@AfterAll
static void stopBackend() {
if (backendServer != null) {
backendServer.stop(0);
}
}
@Test
@Order(1)
void setup() {
httpApiId = given().contentType(ContentType.JSON)
.body("""
{"name":"http-api-custom-domain-iam-test","protocolType":"HTTP"}
""")
.when().post("/v2/apis")
.then().statusCode(201)
.extract().path("apiId");
given().contentType(ContentType.JSON)
.body("""
{"stageName":"%s"}
""".formatted(STAGE))
.when().post("/v2/apis/" + httpApiId + "/stages")
.then().statusCode(201);
String backendUrl = "http://127.0.0.1:" + backendServer.getAddress().getPort();
String integrationId = given().contentType(ContentType.JSON)
.body("""
{"integrationType":"HTTP_PROXY","integrationUri":"%s","payloadFormatVersion":"1.0"}
""".formatted(backendUrl))
.when().post("/v2/apis/" + httpApiId + "/integrations")
.then().statusCode(201)
.extract().path("integrationId");
given().contentType(ContentType.JSON)
.body("""
{"routeKey":"GET /iam","authorizationType":"AWS_IAM","target":"integrations/%s"}
""".formatted(integrationId))
.when().post("/v2/apis/" + httpApiId + "/routes")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("""
{"routeKey":"GET /open","target":"integrations/%s"}
""".formatted(integrationId))
.when().post("/v2/apis/" + httpApiId + "/routes")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("""
{"domainName":"%s","domainNameConfigurations":[
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc",
"endpointType":"REGIONAL"}]}
""".formatted(DOMAIN))
.when().post("/v2/domainnames")
.then().statusCode(201);
given().contentType(ContentType.JSON)
.body("""
{"apiId":"%s","stage":"%s","apiMappingKey":"%s"}
""".formatted(httpApiId, STAGE, MAPPING_KEY))
.when().post("/v2/domainnames/" + DOMAIN + "/apimappings")
.then().statusCode(201);
}
@Test
@Order(10)
void openRouteIsReachableThroughTheCustomDomain() {
backendHits.set(0);
given().header("Host", DOMAIN)
.when().get("/" + MAPPING_KEY + "/open")
.then().statusCode(200)
.body(equalTo("reached the integration"));
assertEquals(1, backendHits.get(), "the v2 API mapping must route through the custom domain");
}
@Test
@Order(11)
void unsignedRequestThroughTheCustomDomainIsRejected() {
backendHits.set(0);
given().header("Host", DOMAIN)
.when().get(customDomainPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get());
}
@Test
@Order(12)
void requestSignedForTheCustomDomainPathReachesTheIntegration() throws Exception {
backendHits.set(0);
given().header("Host", DOMAIN)
.headers(signedHeaders(customDomainPath()))
.when().get(customDomainPath())
.then().statusCode(200)
.body(equalTo("reached the integration"));
assertEquals(1, backendHits.get());
}
@Test
@Order(13)
void signatureOverTheRewrittenExecuteApiPathIsRejected() throws Exception {
backendHits.set(0);
given().header("Host", DOMAIN)
.headers(signedHeaders("/execute-api/" + httpApiId + "/" + STAGE + "/iam"))
.when().get(customDomainPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get());
}
@Test
@Order(14)
void signatureForAnotherMappedPathIsRejected() throws Exception {
backendHits.set(0);
given().header("Host", DOMAIN)
.headers(signedHeaders("/" + MAPPING_KEY + "/open"))
.when().get(customDomainPath())
.then().statusCode(403)
.body("message", equalTo("Forbidden"));
assertEquals(0, backendHits.get());
}
@Test
@Order(999)
void cleanup() {
given().when().delete("/v2/domainnames/" + DOMAIN);
if (httpApiId != null) {
given().when().delete("/v2/apis/" + httpApiId);
}
}
private static String customDomainPath() {
return "/" + MAPPING_KEY + "/iam";
}
private static Map<String, String> signedHeaders(String path) throws Exception {
return ExecuteApiRequestSigner.signedHeaders(
"GET", path, Map.of(), DOMAIN, null, ACCESS_KEY, SECRET_KEY, REGION, Instant.now());
}
}