Light, fluffy, and always free - The AWS Local Emulator alternative
feat(apigatway): handle requests to custom domains (#922)
Steve Sandersa51e43438604
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.javanew file mode 100644index 0000000000..c5a7077dd7--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java@@ -0,0 +1,115 @@+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.annotation.Priority;+import jakarta.inject.Inject;+import jakarta.ws.rs.container.ContainerRequestContext;+import jakarta.ws.rs.container.ContainerRequestFilter;+import jakarta.ws.rs.container.PreMatching;+import jakarta.ws.rs.core.UriBuilder;+import jakarta.ws.rs.ext.Provider;+import org.jboss.logging.Logger;++import java.net.URI;++/**+ * Routes requests based on the Host header for API Gateway custom domains.+ *+ * <p>When a request arrives with a Host header matching a registered custom domain's+ * {@code regionalDomainName} (e.g., {@code my-domain.regional.local:4566}), this filter+ * resolves the corresponding base path mapping and rewrites the request URI to the+ * standard execute-api path format: {@code /execute-api/{apiId}/{stageName}/{path}}.+ *+ * <p>This enables users to invoke API Gateway APIs using custom domain names, matching+ * real AWS behavior where custom domains route to REST APIs via base path mappings.+ */+@Provider+@PreMatching+@Priority(10) // Run after Lambda URL filter (5) but before general processing+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;++ @Inject+ public ApiGatewayCustomDomainFilter(ApiGatewayService apiGatewayService) {+ this.apiGatewayService = apiGatewayService;+ }++ @Override+ public void filter(ContainerRequestContext requestContext) {+ String host = requestContext.getHeaderString("Host");+ if (host == null) {+ return;+ }++ String hostname = stripPort(host);++ // Try matching by regionalDomainName first, then by bare domain name+ CustomDomain domain = null;+ if (hostname.endsWith(REGIONAL_SUFFIX)) {+ domain = apiGatewayService.findDomainByRegionalHostname(hostname);+ }+ if (domain == null) {+ domain = apiGatewayService.findDomainByName(hostname);+ }+ if (domain == null) {+ return;+ }++ URI originalUri = requestContext.getUriInfo().getRequestUri();+ String path = originalUri.getRawPath();+ if (path == null) {+ path = "/";+ }++ // Resolve the base path mapping for this domain + path+ BasePathMapping mapping = apiGatewayService.resolveBasePathMapping(domain.getDomainName(), path);+ if (mapping == null) {+ LOG.debugv("No base path mapping found for domain {0} path {1}", domain.getDomainName(), path);+ return;+ }++ String restApiId = mapping.getRestApiId();++ if (restApiId == null) {+ return;+ }++ // Strip the base path from the request path to get the remaining path+ String remainingPath = apiGatewayService.stripBasePath(path, mapping);++ String effectiveStage = mapping.getStage();+ if (effectiveStage == null || effectiveStage.isEmpty()) {+ return;+ }++ if (remainingPath.startsWith("/")) {+ remainingPath = remainingPath.substring(1);+ }++ // Rewrite to the standard execute-api path+ String newPath = "/execute-api/" + restApiId + "/" + effectiveStage + "/" + remainingPath;++ URI newUri = UriBuilder.fromUri(originalUri)+ .replacePath(newPath)+ .build();++ LOG.debugv("Custom domain routing: {0}{1} -> {2}", host, path, newUri.getPath());+ requestContext.setRequestUri(newUri);+ }++ private static String stripPort(String host) {+ int colonIndex = host.lastIndexOf(':');+ if (colonIndex > 0) {+ String maybePart = host.substring(colonIndex + 1);+ if (!maybePart.isEmpty() && maybePart.chars().allMatch(Character::isDigit)) {+ return host.substring(0, colonIndex);+ }+ }+ return host;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.javaindex 078fef83f6..23fe8602c4 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java@@ -686,6 +686,13 @@ public class ApiGatewayService {String domainName = (String) request.get("domainName");if (domainName == null) throw new AwsException("BadRequestException", "domainName is required", 400);+ // AWS enforces global uniqueness of custom domain names across all regions+ boolean exists = !domainStore.scan(k -> k.endsWith("::" + domainName)).isEmpty();+ if (exists) {+ throw new AwsException("ConflictException",+ "The domain name you provided already exists.", 409);+ }+CustomDomain domain = new CustomDomain();domain.setDomainName(domainName);domain.setCertificateName((String) request.get("certificateName"));@@ -748,6 +755,91 @@ public class ApiGatewayService {basePathMappingStore.delete(mappingKey(region, domainName, path));}+ // ──────────────────────────── Custom Domain Resolution ────────────────────────────++ /**+ * Resolves a custom domain by its regionalDomainName (e.g., "my-domain.regional.local").+ * Derives the domain name from the regionalDomainName and performs a key-based lookup.+ *+ * @return the CustomDomain if found, or null if no domain matches+ */+ public CustomDomain findDomainByRegionalHostname(String regionalDomainName) {+ if (!regionalDomainName.endsWith(".regional.local")) {+ return null;+ }+ String domainName = regionalDomainName.substring(0,+ regionalDomainName.length() - ".regional.local".length());+ return findDomainByName(domainName);+ }++ /**+ * Resolves a custom domain by its actual domain name (e.g., "api.example.com").+ * Domain names are globally unique across regions.+ *+ * @return the CustomDomain if found, or null if no domain matches+ */+ public CustomDomain findDomainByName(String domainName) {+ List<CustomDomain> results = domainStore.scan(k -> k.endsWith("::" + domainName));+ return results.isEmpty() ? null : results.get(0);+ }++ /**+ * Resolves the base path mapping for a given domain and request path.+ * Uses longest-prefix matching on the base path.+ *+ * @param domainName the custom domain name+ * @param requestPath the incoming request path (e.g., "/v1/items/123")+ * @return the matching BasePathMapping, or null if none matches+ */+ public BasePathMapping resolveBasePathMapping(String domainName, String requestPath) {+ // Get all mappings across all regions for this domain+ List<BasePathMapping> allMappings = basePathMappingStore.scan(k -> k.contains("::" + domainName + "::"));++ if (allMappings.isEmpty()) {+ return null;+ }++ // Find the best match using longest-prefix matching+ BasePathMapping bestMatch = null;+ int bestLength = -1;++ for (BasePathMapping mapping : allMappings) {+ String basePath = mapping.getBasePath();+ if ("(none)".equals(basePath)) {+ // Catch-all mapping — matches if no better mapping exists+ if (bestLength < 0) {+ bestMatch = mapping;+ bestLength = 0;+ }+ } else {+ String prefix = "/" + basePath;+ if (requestPath.equals(prefix) || requestPath.startsWith(prefix + "/")) {+ if (basePath.length() > bestLength) {+ bestMatch = mapping;+ bestLength = basePath.length();+ }+ }+ }+ }++ return bestMatch;+ }++ /**+ * Returns the remaining path after stripping the matched base path prefix.+ */+ public String stripBasePath(String requestPath, BasePathMapping mapping) {+ String basePath = mapping.getBasePath();+ if ("(none)".equals(basePath)) {+ return requestPath;+ }+ String prefix = "/" + basePath;+ if (requestPath.equals(prefix)) {+ return "/";+ }+ return requestPath.substring(prefix.length());+ }+// ──────────────────────────── Update Methods ────────────────────────────public RestApi updateRestApi(String region, String apiId, List<Map<String, String>> patchOperations) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainIntegrationTest.javanew file mode 100644index 0000000000..677afd0e1b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainIntegrationTest.java@@ -0,0 +1,256 @@+package io.github.hectorvent.floci.services.apigateway;++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 static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.*;++/**+ * Verifies that API Gateway custom domain routing via Host header works correctly.+ *+ * <p>When a request arrives with a Host header matching a registered custom domain's+ * {@code regionalDomainName}, the filter resolves the base path mapping and routes+ * the request to the appropriate REST API and stage.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class ApiGatewayCustomDomainIntegrationTest {++ private static String apiId;+ private static String rootId;+ private static String resourceId;+ private static String deploymentId;++ @Test @Order(1)+ void createRestApi() {+ apiId = given()+ .contentType(ContentType.JSON)+ .body("{\"name\":\"custom-domain-test-api\"}")+ .when().post("/restapis")+ .then()+ .statusCode(201)+ .body("id", notNullValue())+ .extract().path("id");+ }++ @Test @Order(2)+ void setupMockIntegration() {+ rootId = given()+ .when().get("/restapis/" + apiId + "/resources")+ .then()+ .statusCode(200)+ .extract().path("item[0].id");++ resourceId = given()+ .contentType(ContentType.JSON)+ .body("{\"pathPart\":\"items\"}")+ .when().post("/restapis/" + apiId + "/resources/" + rootId)+ .then()+ .statusCode(201)+ .extract().path("id");++ given()+ .contentType(ContentType.JSON)+ .body("{\"authorizationType\":\"NONE\"}")+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("{\"responseParameters\":{}}")+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/responses/200")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"message\\\":\\\"custom-domain-works\\\"}\"}}")+ .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200")+ .then()+ .statusCode(201);+ }++ @Test @Order(3)+ void createDeploymentAndStage() {+ 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\":\"prod\",\"deploymentId\":\"" + deploymentId + "\"}")+ .when().post("/restapis/" + apiId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test @Order(4)+ void createCustomDomain() {+ given()+ .contentType(ContentType.JSON)+ .body("{\"domainName\":\"api.example.com\",\"certificateArn\":\"arn:aws:acm:us-east-1:123456789012:certificate/abc\"}")+ .when().post("/domainnames")+ .then()+ .statusCode(201)+ .body("domainName", equalTo("api.example.com"))+ .body("regionalDomainName", equalTo("api.example.com.regional.local"));+ }++ @Test @Order(5)+ void createBasePathMapping_withBasePath() {+ given()+ .contentType(ContentType.JSON)+ .body("{\"basePath\":\"v1\",\"restApiId\":\"" + apiId + "\",\"stage\":\"prod\"}")+ .when().post("/domainnames/api.example.com/basepathmappings")+ .then()+ .statusCode(201)+ .body("basePath", equalTo("v1"))+ .body("restApiId", equalTo(apiId));+ }++ @Test @Order(6)+ void invokeViaCustomDomain_withBasePath() {+ given()+ .header("Host", "api.example.com.regional.local:4566")+ .when().get("/v1/items")+ .then()+ .statusCode(200)+ .body("message", equalTo("custom-domain-works"));+ }++ @Test @Order(7)+ void invokeViaCustomDomain_withoutPort() {+ given()+ .header("Host", "api.example.com.regional.local")+ .when().get("/v1/items")+ .then()+ .statusCode(200)+ .body("message", equalTo("custom-domain-works"));+ }++ @Test @Order(8)+ void invokeViaBareDomainName() {+ given()+ .header("Host", "api.example.com")+ .when().get("/v1/items")+ .then()+ .statusCode(200)+ .body("message", equalTo("custom-domain-works"));+ }++ @Test @Order(9)+ void invokeViaBareDomainName_withPort() {+ given()+ .header("Host", "api.example.com:4566")+ .when().get("/v1/items")+ .then()+ .statusCode(200)+ .body("message", equalTo("custom-domain-works"));+ }++ @Test @Order(10)+ void createBasePathMapping_catchAll() {+ given()+ .contentType(ContentType.JSON)+ .body("{\"basePath\":\"(none)\",\"restApiId\":\"" + apiId + "\",\"stage\":\"prod\"}")+ .when().post("/domainnames/api.example.com/basepathmappings")+ .then()+ .statusCode(201);+ }++ @Test @Order(11)+ void invokeViaCustomDomain_catchAllMapping() {+ // With catch-all, /items should route directly (no base path prefix needed)+ given()+ .header("Host", "api.example.com.regional.local")+ .when().get("/items")+ .then()+ .statusCode(200)+ .body("message", equalTo("custom-domain-works"));+ }++ @Test @Order(12)+ void invokeViaCustomDomain_specificPathTakesPrecedence() {+ // /v1/items should still match the /v1 mapping (longer prefix wins)+ given()+ .header("Host", "api.example.com.regional.local")+ .when().get("/v1/items")+ .then()+ .statusCode(200)+ .body("message", equalTo("custom-domain-works"));+ }++ @Test @Order(13)+ void invokeViaCustomDomain_unknownDomain_passesThrough() {+ // Unknown domain should not be intercepted by the filter+ given()+ .header("Host", "unknown.regional.local")+ .when().get("/v1/items")+ .then()+ .statusCode(anyOf(is(403), is(404)));+ }++ @Test @Order(14)+ void createDuplicateDomainName_rejected() {+ // Domain names are globally unique across regions — creating the same+ // domain name again (even implicitly in the same region) must fail+ given()+ .contentType(ContentType.JSON)+ .body("{\"domainName\":\"api.example.com\",\"certificateArn\":\"arn:aws:acm:us-east-1:123456789012:certificate/dup\"}")+ .when().post("/domainnames")+ .then()+ .statusCode(409);+ }++ @Test @Order(15)+ void mappingWithoutStage_isNotRouted() {+ // Create a domain with a mapping that has no stage configured+ given()+ .contentType(ContentType.JSON)+ .body("{\"domainName\":\"nostage.example.com\",\"certificateArn\":\"arn:aws:acm:us-east-1:123456789012:certificate/xyz\"}")+ .when().post("/domainnames")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("{\"basePath\":\"(none)\",\"restApiId\":\"" + apiId + "\"}")+ .when().post("/domainnames/nostage.example.com/basepathmappings")+ .then()+ .statusCode(201);++ // Filter should not route this — no stage means early return+ given()+ .header("Host", "nostage.example.com")+ .when().get("/prod/items")+ .then()+ .statusCode(anyOf(is(403), is(404)));+ }++ @Test @Order(16)+ void cleanup() {+ given().when().delete("/domainnames/api.example.com/basepathmappings/v1").then().statusCode(anyOf(is(200), is(202), is(204)));+ given().when().delete("/domainnames/api.example.com/basepathmappings/(none)").then().statusCode(anyOf(is(200), is(202), is(204)));+ given().when().delete("/domainnames/api.example.com").then().statusCode(anyOf(is(200), is(202), is(204)));+ given().when().delete("/domainnames/nostage.example.com/basepathmappings/(none)").then().statusCode(anyOf(is(200), is(202), is(204)));+ given().when().delete("/domainnames/nostage.example.com").then().statusCode(anyOf(is(200), is(202), is(204)));+ given().when().delete("/restapis/" + apiId).then().statusCode(202);+ }+}