diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index cf587960c5..f7ab4318f1 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -230,6 +230,8 @@ this default hostname with `404 Not Found`, matching AWS HTTP API behavior. | **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage | | **Deployments** | CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment | | **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel | +| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName | +| **API Mappings** | CreateApiMapping, GetApiMapping, GetApiMappings, DeleteApiMapping | | **Tags** | TagResource, UntagResource, GetTags | ### WebSocket Data-Plane {#websocket-data-plane} @@ -291,8 +293,7 @@ DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Disconn ### Not Implemented -- `ReimportApi`, `ExportApi`, `GetApiMapping`, `CreateApiMapping`, `DeleteApiMapping` -- `GetDomainName`, `CreateDomainName`, `DeleteDomainName` +- `ReimportApi`, `ExportApi`, `UpdateDomainName`, `UpdateApiMapping` - `CreateVpcLink`, `GetVpcLink`, `GetVpcLinks`, `UpdateVpcLink`, `DeleteVpcLink` ### Examples diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java index 931f3c2573..16b437940b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java @@ -1,8 +1,11 @@ package io.github.hectorvent.floci.services.apigateway; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HexFormat; import java.time.Instant; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -955,6 +958,7 @@ public class ApiGatewayController { @Path("/v2/apis/{apiId}") public Response deleteApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) { String region = regionResolver.resolveRegion(headers); + service.requireNoApiMappings(apiId); v2Service.deleteApi(region, apiId); return Response.noContent().build(); } @@ -1131,6 +1135,128 @@ public class ApiGatewayController { return Response.accepted().build(); } + // ──────────────────────────── Custom Domains (v2) ──────────────────────────── + // + // A custom domain is one resource in AWS, reachable through both APIs, so these read and write + // the same records the v1 endpoints do. That also means a domain created here resolves through + // the Host-header routing that already exists for v1. + + @POST + @Path("/v2/domainnames") + public Response createV2DomainName(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + Map request = readJsonBody(body); + // HTTP APIs require exactly one configuration, where the REST API takes none at all. It has + // to be an object: a scalar or a list there is still a body AWS would not have accepted. + if (!(request.get("domainNameConfigurations") instanceof List configurations) + || configurations.size() != 1 + || !(configurations.getFirst() instanceof Map configuration)) { + throw new AwsException("BadRequestException", + "Invalid input. Expected one domain name configuration", 400); + } + rejectUnemulatedDomainInputs(request, configuration); + CustomDomain domain = service.createDomainName(region, toV1DomainRequest(request)); + return Response.status(201).entity(toV2DomainNode(region, domain).toString()) + .type(MediaType.APPLICATION_JSON).build(); + } + + @GET + @Path("/v2/domainnames") + public Response getV2DomainNames(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + service.getDomainNames(region).forEach(d -> items.add(toV2DomainNode(region, d))); + return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build(); + } + + @GET + @Path("/v2/domainnames/{domainName}") + public Response getV2DomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) { + String region = regionResolver.resolveRegion(headers); + CustomDomain domain = service.getDomainName(region, domainName); + return Response.ok(toV2DomainNode(region, domain).toString()).type(MediaType.APPLICATION_JSON).build(); + } + + @DELETE + @Path("/v2/domainnames/{domainName}") + public Response deleteV2DomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) { + String region = regionResolver.resolveRegion(headers); + service.deleteDomainName(region, domainName); + return Response.noContent().build(); + } + + // ──────────────────────────── API Mappings (v2) ──────────────────────────── + + @POST + @Path("/v2/domainnames/{domainName}/apimappings") + public Response createApiMapping(@Context HttpHeaders headers, + @PathParam("domainName") String domainName, + String body) { + String region = regionResolver.resolveRegion(headers); + Map request = readJsonBody(body); + if (request.get("apiId") == null || request.get("stage") == null) { + throw new AwsException("BadRequestException", "apiId and stage are required", 400); + } + String apiId = String.valueOf(request.get("apiId")); + String stage = String.valueOf(request.get("stage")); + // A mapping to an API or stage that does not exist would route nowhere, so AWS refuses it + // rather than answering 201 with something unusable. + requireApiAndStageExist(region, apiId, stage); + + String basePath = ApiGatewayService.canonicalBasePath( + request.get("apiMappingKey") == null ? null : String.valueOf(request.get("apiMappingKey"))); + boolean keyTaken = service.basePathMappingsByStoredPath(region, domainName).keySet().stream() + .anyMatch(existing -> ApiGatewayService.canonicalBasePath(existing).equals(basePath)); + if (keyTaken) { + throw new AwsException("ConflictException", + "ApiMapping key already exists for this domain name", 409); + } + + Map v1Request = new HashMap<>(); + v1Request.put("restApiId", apiId); + v1Request.put("stage", stage); + v1Request.put("basePath", basePath); + BasePathMapping mapping = service.createBasePathMapping(region, domainName, v1Request); + return Response.status(201).entity(toApiMappingNode(basePath, mapping).toString()) + .type(MediaType.APPLICATION_JSON).build(); + } + + @GET + @Path("/v2/domainnames/{domainName}/apimappings") + public Response getApiMappings(@Context HttpHeaders headers, @PathParam("domainName") String domainName) { + String region = regionResolver.resolveRegion(headers); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + service.basePathMappingsByStoredPath(region, domainName) + .forEach((storedPath, mapping) -> items.add(toApiMappingNode(storedPath, mapping))); + return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build(); + } + + @GET + @Path("/v2/domainnames/{domainName}/apimappings/{apiMappingId}") + public Response getApiMapping(@Context HttpHeaders headers, + @PathParam("domainName") String domainName, + @PathParam("apiMappingId") String apiMappingId) { + String region = regionResolver.resolveRegion(headers); + StoredMapping found = findApiMapping(region, domainName, apiMappingId); + return Response.ok(toApiMappingNode(found.storedPath(), found.mapping()).toString()) + .type(MediaType.APPLICATION_JSON).build(); + } + + @DELETE + @Path("/v2/domainnames/{domainName}/apimappings/{apiMappingId}") + public Response deleteApiMapping(@Context HttpHeaders headers, + @PathParam("domainName") String domainName, + @PathParam("apiMappingId") String apiMappingId) { + String region = regionResolver.resolveRegion(headers); + // Deleted by the path the selected record is stored under, so the record that answered the + // lookup is the record that goes. + StoredMapping found = findApiMapping(region, domainName, apiMappingId); + service.deleteBasePathMappingRecord(region, domainName, found.storedPath()); + return Response.noContent().build(); + } + // ──────────────────────────── Route Responses (v2) ──────────────────────────── @POST @@ -1722,6 +1848,150 @@ public class ApiGatewayController { return node; } + private Map readJsonBody(String body) { + try { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + return request; + } catch (IOException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + /** + * Refuses the parts of a domain that floci does not emulate, rather than accepting them and + * answering with a domain that behaves differently from the one that was asked for. + */ + private static void rejectUnemulatedDomainInputs(Map request, Map configuration) { + Object routingMode = request.get("routingMode"); + if (routingMode != null && !"API_MAPPING_ONLY".equals(routingMode)) { + throw new AwsException("BadRequestException", + "Only API_MAPPING_ONLY routing is supported", 400); + } + if (request.get("mutualTlsAuthentication") != null) { + throw new AwsException("BadRequestException", + "Mutual TLS authentication is not supported", 400); + } + Object ipAddressType = configuration.get("ipAddressType"); + if (ipAddressType != null && !"ipv4".equals(ipAddressType)) { + throw new AwsException("BadRequestException", + "Only the ipv4 address type is supported", 400); + } + if (configuration.get("ownershipVerificationCertificateArn") != null) { + throw new AwsException("BadRequestException", + "Ownership verification certificates are not supported", 400); + } + } + + /** Flattens the v2 request onto the keys the shared custom-domain store is written with. */ + private Map toV1DomainRequest(Map request) { + Map v1Request = new HashMap<>(); + v1Request.put("domainName", request.get("domainName")); + copyIfPresent(request, v1Request, "tags", "tags"); + if (request.get("domainNameConfigurations") instanceof List configurations + && !configurations.isEmpty() + && configurations.getFirst() instanceof Map configuration) { + copyIfPresent(configuration, v1Request, "certificateArn", "certificateArn"); + copyIfPresent(configuration, v1Request, "certificateName", "certificateName"); + copyIfPresent(configuration, v1Request, "endpointType", "endpointType"); + copyIfPresent(configuration, v1Request, "securityPolicy", "securityPolicy"); + } + return v1Request; + } + + private static void copyIfPresent(Map source, Map target, String from, String to) { + Object value = source.get(from); + if (value != null) { + target.put(to, value); + } + } + + private ObjectNode toV2DomainNode(String region, CustomDomain d) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("domainName", d.getDomainName()); + node.put("domainNameArn", "arn:aws:apigateway:" + region + "::/domainnames/" + d.getDomainName()); + node.put("apiMappingSelectionExpression", "$request.basepath"); + // AWS reports both of these on every domain. + node.put("routingMode", "API_MAPPING_ONLY"); + + ObjectNode configuration = objectMapper.createObjectNode(); + configuration.put("apiGatewayDomainName", d.getRegionalDomainName()); + configuration.put("hostedZoneId", d.getRegionalHostedZoneId()); + configuration.put("endpointType", d.getEndpointConfigurationType()); + configuration.put("domainNameStatus", d.getDomainNameStatus()); + configuration.put("ipAddressType", "ipv4"); + if (d.getCertificateArn() != null) { + configuration.put("certificateArn", d.getCertificateArn()); + } + if (d.getCertificateName() != null) { + configuration.put("certificateName", d.getCertificateName()); + } + if (d.getSecurityPolicy() != null) { + configuration.put("securityPolicy", d.getSecurityPolicy()); + } + node.putArray("domainNameConfigurations").add(configuration); + if (d.getTags() != null && !d.getTags().isEmpty()) { + ObjectNode tags = node.putObject("tags"); + d.getTags().forEach(tags::put); + } + return node; + } + + private ObjectNode toApiMappingNode(String storedPath, BasePathMapping mapping) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("apiMappingId", apiMappingId(storedPath)); + node.put("apiId", mapping.getRestApiId()); + node.put("stage", mapping.getStage()); + // v1 stores the root mapping as "(none)"; v2 expresses it as an empty key. + // The key reported is the one the record is stored under, so it matches its id. + String canonical = ApiGatewayService.canonicalBasePath(storedPath); + node.put("apiMappingKey", "(none)".equals(canonical) ? "" : canonical); + return node; + } + + /** Rejects a mapping whose API or stage does not exist, with the errors AWS gives for each. */ + private void requireApiAndStageExist(String region, String apiId, String stage) { + try { + v2Service.getApi(region, apiId); + } catch (AwsException e) { + throw new AwsException("BadRequestException", "Invalid API identifier specified: " + apiId, 400); + } + try { + v2Service.getStage(region, apiId, stage); + } catch (AwsException e) { + throw new AwsException("BadRequestException", "Invalid stage identifier specified", 400); + } + } + + /** + * Derives the mapping id from what identifies the mapping, so it survives a restart and is the + * same id whichever API created it. The base path is encoded rather than hashed: two base paths + * sharing a hash would share an id, and a read or delete by that id would pick between them. + */ + // Package-private so the identity property can be tested against records that only persisted + // state can hold: no API path creates a non-canonical base path any more. + static String apiMappingId(String storedPath) { + // Encoded from the key the record is stored under — not its canonical form, and not the + // record's own field, which BasePathMapping normalises on construction. State written + // before writes were canonicalised can sit under "" or "/" beside "(none)", and reading + // identity from anywhere but the key hands several records one id for a read or a delete + // to choose between. The prefix keeps an empty stored path from producing an empty id. + return "m" + HexFormat.of().formatHex( + (storedPath == null ? "" : storedPath).getBytes(StandardCharsets.UTF_8)); + } + + /** A mapping together with the base path it is stored under, which is what identifies it. */ + private record StoredMapping(String storedPath, BasePathMapping mapping) {} + + private StoredMapping findApiMapping(String region, String domainName, String apiMappingId) { + return service.basePathMappingsByStoredPath(region, domainName).entrySet().stream() + .filter(entry -> apiMappingId(entry.getKey()).equals(apiMappingId)) + .map(entry -> new StoredMapping(entry.getKey(), entry.getValue())) + .findFirst() + .orElseThrow(() -> new AwsException("NotFoundException", + "Unable to find ApiMapping with ID " + apiMappingId, 404)); + } + private ObjectNode toDomainNode(CustomDomain d) { ObjectNode node = objectMapper.createObjectNode(); node.put("domainName", d.getDomainName()); 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.java index 5d44c64119..8d52067699 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 @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigateway; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -940,8 +941,8 @@ public class ApiGatewayService { // 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); + throw new AwsException("BadRequestException", + "The domain name you provided already exists.", 400); } CustomDomain domain = new CustomDomain(); @@ -950,15 +951,43 @@ public class ApiGatewayService { domain.setCertificateArn((String) request.get("certificateArn")); domain.setRegionalDomainName(domainName + ".regional.local"); domain.setRegionalHostedZoneId("Z2FDTNDATAQYL2"); + domain.setEndpointConfigurationType(endpointTypeOf(request)); + domain.setSecurityPolicy((String) request.getOrDefault("securityPolicy", "TLS_1_2")); + // Nothing is provisioned behind the domain, so it is usable as soon as it exists. + domain.setDomainNameStatus("AVAILABLE"); + if (request.get("tags") instanceof Map tags && !tags.isEmpty()) { + Map copied = new java.util.LinkedHashMap<>(); + tags.forEach((key, value) -> copied.put(String.valueOf(key), String.valueOf(value))); + domain.setTags(copied); + } domainStore.put(domainKey(region, domainName), domain); LOG.infov("Created custom domain {0} in {1}", domainName, region); return domain; } + /** + * Reads the endpoint type from either spelling: REST passes {@code endpointConfiguration.types}, + * HTTP APIs pass a single {@code endpointType}. REGIONAL is the default an emulated domain gets, + * since nothing here fronts it with an edge distribution. + */ + private static String endpointTypeOf(Map request) { + Object endpointType = request.get("endpointType"); + if (endpointType instanceof String type && !type.isBlank()) { + return type; + } + if (request.get("endpointConfiguration") instanceof Map configuration + && configuration.get("types") instanceof List types && !types.isEmpty() + && types.getFirst() instanceof String type && !type.isBlank()) { + return type; + } + return "REGIONAL"; + } + public CustomDomain getDomainName(String region, String domainName) { return domainStore.get(domainKey(region, domainName)) - .orElseThrow(() -> new AwsException("NotFoundException", "Domain name not found", 404)); + .orElseThrow(() -> new AwsException("NotFoundException", + "Invalid domain name identifier specified", 404)); } public List getDomainNames(String region) { @@ -976,9 +1005,19 @@ public class ApiGatewayService { // ──────────────────────────── Base Path Mappings ──────────────────────────── + /** + * The canonical spelling of a base path. Reads have always normalised the root this way, so + * writes have to as well: otherwise the store holds several records that all mean the root, a + * mapping created as "" cannot be read back as "", and anything deriving an identity from the + * base path sees one path under several names. + */ + public static String canonicalBasePath(String basePath) { + return basePath == null || basePath.isBlank() || "/".equals(basePath) ? "(none)" : basePath; + } + public BasePathMapping createBasePathMapping(String region, String domainName, Map request) { getDomainName(region, domainName); - String basePath = (String) request.getOrDefault("basePath", "(none)"); + String basePath = canonicalBasePath((String) request.get("basePath")); String apiId = (String) request.get("restApiId"); String stage = (String) request.get("stage"); @@ -988,6 +1027,21 @@ public class ApiGatewayService { return mapping; } + /** + * Refuses to let an API go while a custom domain still maps to it, which is what AWS answers: + * the mapping would otherwise be left pointing at an API that no longer exists. + */ + public void requireNoApiMappings(String apiId) { + // Every region is scanned, not just the caller's: a mapping is keyed under the region of + // the domain it belongs to, which need not be the region the API is being deleted in. + boolean mapped = basePathMappingStore.scan(key -> true).stream() + .anyMatch(mapping -> apiId.equals(mapping.getRestApiId())); + if (mapped) { + throw new AwsException("BadRequestException", "Deleting API " + apiId + + " failed. Please remove all API mappings for the API from your custom domain names.", 400); + } + } + public BasePathMapping getBasePathMapping(String region, String domainName, String basePath) { String path = (basePath == null || basePath.isEmpty() || "/" .equals(basePath)) ? "(none)" : basePath; return basePathMappingStore.get(mappingKey(region, domainName, path)) @@ -1006,6 +1060,42 @@ public class ApiGatewayService { basePathMappingStore.delete(mappingKey(region, domainName, path)); } + /** + * The mappings on a domain, keyed by the base path each record is stored under. + * + *

That path is the record's identity, and it is not always what the record reports: + * {@link BasePathMapping} normalises an empty base path to {@code (none)} in its constructor, + * so a record written before writes were canonicalised can sit under the key {@code ""} while + * its own field reads {@code (none)}. Anything identifying a record — an id derived from it, a + * delete aimed at it — has to use the key rather than the field. + */ + public Map basePathMappingsByStoredPath(String region, String domainName) { + getDomainName(region, domainName); + String prefix = region + "::" + domainName + "::"; + Map byStoredPath = new LinkedHashMap<>(); + for (String key : basePathMappingStore.keys()) { + if (key.startsWith(prefix)) { + basePathMappingStore.get(key) + .ifPresent(mapping -> byStoredPath.put(key.substring(prefix.length()), mapping)); + } + } + return byStoredPath; + } + + /** + * Deletes the record stored under exactly this base path, for a caller that already holds the + * record rather than a key to look one up by. Normalising here would delete the canonical root + * instead — state written before writes were canonicalised can hold a record under "/" or "", + * and that is the record such a caller selected. + */ + public void deleteBasePathMappingRecord(String region, String domainName, String storedBasePath) { + String key = mappingKey(region, domainName, storedBasePath == null ? "" : storedBasePath); + if (basePathMappingStore.get(key).isEmpty()) { + throw new AwsException("NotFoundException", "Base path mapping not found", 404); + } + basePathMappingStore.delete(key); + } + // ──────────────────────────── Custom Domain Resolution ──────────────────────────── /** diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/CustomDomain.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/CustomDomain.java index 51a541a4ea..3b2ee4f83e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/CustomDomain.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/CustomDomain.java @@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.apigateway.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.Map; + @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) public class CustomDomain { @@ -19,6 +21,7 @@ public class CustomDomain { private String endpointConfigurationType; // REGIONAL or EDGE private String domainNameStatus; // AVAILABLE, UPDATING, PENDING private String securityPolicy; + private Map tags; public CustomDomain() { this.domainNameStatus = "AVAILABLE"; @@ -64,4 +67,7 @@ public class CustomDomain { public String getSecurityPolicy() { return securityPolicy; } public void setSecurityPolicy(String securityPolicy) { this.securityPolicy = securityPolicy; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } } 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.java index 677afd0e1b..54aafae5fa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainIntegrationTest.java @@ -210,13 +210,14 @@ class ApiGatewayCustomDomainIntegrationTest { @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 + // domain name again (even implicitly in the same region) must fail. + // Verified against AWS: both the REST and HTTP APIs answer BadRequestException, not a conflict 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); + .statusCode(400); } @Test @Order(15) diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayV2DomainNameIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayV2DomainNameIntegrationTest.java new file mode 100644 index 0000000000..d0392b54d9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayV2DomainNameIntegrationTest.java @@ -0,0 +1,439 @@ +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.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; + +/** + * Custom domain names and API mappings over the HTTP API (v2) endpoints. + * + *

Before these routes existed, {@code POST /v2/domainnames} matched the S3 controller's + * catch-all instead and came back as an S3 XML error about multipart uploads, which an SDK + * expecting JSON cannot even deserialize. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayV2DomainNameIntegrationTest { + + private static final String DOMAIN = "v2-domain-test.example.com"; + private static String apiId; + private static String apiMappingId; + + @Test + @Order(1) + void createDomainNameIsRoutedToApiGateway() { + given() + .contentType(ContentType.JSON) + .body(""" + {"domainName":"%s","domainNameConfigurations":[ + {"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc", + "endpointType":"REGIONAL","securityPolicy":"TLS_1_2"}]} + """.formatted(DOMAIN)) + .when() + .post("/v2/domainnames") + .then() + .statusCode(201) + .contentType(ContentType.JSON) + .body("domainName", is(DOMAIN)) + .body("domainNameArn", containsString("/domainnames/" + DOMAIN)) + .body("apiMappingSelectionExpression", is("$request.basepath")) + .body("domainNameConfigurations[0].endpointType", is("REGIONAL")) + .body("domainNameConfigurations[0].securityPolicy", is("TLS_1_2")) + .body("domainNameConfigurations[0].domainNameStatus", is("AVAILABLE")) + .body("domainNameConfigurations[0].apiGatewayDomainName", notNullValue()) + .body("domainNameConfigurations[0].hostedZoneId", notNullValue()) + .body("domainNameConfigurations[0].certificateArn", containsString("certificate/abc")) + .body("domainNameConfigurations[0].ipAddressType", is("ipv4")) + .body("routingMode", is("API_MAPPING_ONLY")) + // The symptom this replaces: an S3 error for a call S3 was never asked to serve. + .body(not(containsString("uploads"))); + } + + @Test + @Order(2) + void duplicateDomainNameIsABadRequest() { + // Verified against AWS, which answers BadRequestException here rather than a conflict. + given() + .contentType(ContentType.JSON) + .body(""" + {"domainName":"%s","domainNameConfigurations":[{"endpointType":"REGIONAL"}]} + """.formatted(DOMAIN)) + .when() + .post("/v2/domainnames") + .then() + .statusCode(400) + .body(containsString("already exists")); + } + + @Test + @Order(3) + void aDomainNameConfigurationIsRequired() { + // AWS: "Invalid input. Expected one domain name configuration" — the REST API takes none, + // so the two endpoints do not share this rule. + given() + .contentType(ContentType.JSON) + .body("{\"domainName\":\"no-configuration.example.com\"}") + .when() + .post("/v2/domainnames") + .then() + .statusCode(400) + .body(containsString("Expected one domain name configuration")); + } + + @Test + @Order(3) + void tagsAreKeptRatherThanDropped() { + // Dropping them would leave terraform with a diff it can never settle. + given() + .contentType(ContentType.JSON) + .body(""" + {"domainName":"tagged.example.com", + "domainNameConfigurations":[{"endpointType":"REGIONAL"}], + "tags":{"env":"prod"}} + """) + .when() + .post("/v2/domainnames") + .then() + .statusCode(201) + .body("tags.env", is("prod")); + + given() + .when() + .get("/v2/domainnames/tagged.example.com") + .then() + .statusCode(200) + .body("tags.env", is("prod")); + } + + @Test + @Order(3) + void anUnsupportedRoutingModeIsRefused() { + // floci does not emulate routing rules, so it says so rather than quietly creating a + // domain that routes by API mapping regardless. + given() + .contentType(ContentType.JSON) + .body(""" + {"domainName":"routing.example.com", + "domainNameConfigurations":[{"endpointType":"REGIONAL"}], + "routingMode":"ROUTING_RULE_ONLY"} + """) + .when() + .post("/v2/domainnames") + .then() + .statusCode(400) + .body(containsString("API_MAPPING_ONLY")); + } + + @Test + @Order(4) + void getAndListDomainNames() { + given() + .when() + .get("/v2/domainnames/" + DOMAIN) + .then() + .statusCode(200) + .body("domainName", is(DOMAIN)); + + given() + .when() + .get("/v2/domainnames") + .then() + .statusCode(200) + .body("items.domainName", hasItemEqualTo(DOMAIN)); + } + + @Test + @Order(5) + void domainIsTheSameResourceThroughBothApis() { + // AWS exposes one custom domain through both APIs, so what v2 created v1 must also see. + given() + .when() + .get("/domainnames/" + DOMAIN) + .then() + .statusCode(200) + .body("domainName", is(DOMAIN)); + } + + @Test + @Order(6) + void createApiMapping() { + apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"v2-domain-api\",\"protocolType\":\"HTTP\"}") + .when() + .post("/v2/apis") + .then() + .statusCode(201) + .extract().path("apiId"); + + // A mapping needs a stage that exists, so the API gets one before it is mapped. + given() + .contentType(ContentType.JSON) + .body("{\"stageName\":\"$default\"}") + .when() + .post("/v2/apis/" + apiId + "/stages") + .then() + .statusCode(201); + + apiMappingId = given() + .contentType(ContentType.JSON) + .body("{\"apiId\":\"%s\",\"stage\":\"$default\",\"apiMappingKey\":\"orders\"}".formatted(apiId)) + .when() + .post("/v2/domainnames/" + DOMAIN + "/apimappings") + .then() + .statusCode(201) + .body("apiId", is(apiId)) + .body("stage", is("$default")) + .body("apiMappingKey", is("orders")) + .body("apiMappingId", notNullValue()) + .extract().path("apiMappingId"); + } + + @Test + @Order(7) + void aMappingNeedsAnApiAndStageThatExist() { + // Verified against AWS: both are BadRequestException rather than a 201 for a mapping that + // routes nowhere. + given() + .contentType(ContentType.JSON) + .body("{\"apiId\":\"zzzzzzzzzz\",\"stage\":\"$default\"}") + .when() + .post("/v2/domainnames/" + DOMAIN + "/apimappings") + .then() + .statusCode(400) + .body(containsString("Invalid API identifier specified")); + + given() + .contentType(ContentType.JSON) + .body("{\"apiId\":\"%s\",\"stage\":\"nosuchstage\"}".formatted(apiId)) + .when() + .post("/v2/domainnames/" + DOMAIN + "/apimappings") + .then() + .statusCode(400) + .body(containsString("Invalid stage identifier specified")); + } + + @Test + @Order(7) + void anOmittedAndAnEmptyMappingKeyAreTheSameMapping() { + // AWS answers the second with ConflictException, so the two spellings must land on one + // record rather than creating two apparent root mappings. + String rootMapping = "{\"apiId\":\"%s\",\"stage\":\"$default\"}".formatted(apiId); + given() + .contentType(ContentType.JSON) + .body(rootMapping) + .when() + .post("/v2/domainnames/" + DOMAIN + "/apimappings") + .then() + .statusCode(201) + .body("apiMappingKey", is("")); + + given() + .contentType(ContentType.JSON) + .body("{\"apiId\":\"%s\",\"stage\":\"$default\",\"apiMappingKey\":\"\"}".formatted(apiId)) + .when() + .post("/v2/domainnames/" + DOMAIN + "/apimappings") + .then() + .statusCode(409) + .body(containsString("already exists")); + + // And the root mapping is reachable through the v1 endpoint, which spells it "(none)". + given() + .when() + .get("/domainnames/" + DOMAIN + "/basepathmappings/(none)") + .then() + .statusCode(200); + } + + @Test + @Order(7) + void rootSpellingsCollapseToOneRecordOnWrite() { + // The read path has always normalised the root to "(none)"; the write path now does too, so + // "/" cannot end up stored beside it as a second record that means the same thing — and a + // mapping created as "" can be read back as "", which it could not before. + String otherDomain = "root-spelling.example.com"; + given() + .contentType(ContentType.JSON) + .body(""" + {"domainName":"%s","domainNameConfigurations":[{"endpointType":"REGIONAL"}]} + """.formatted(otherDomain)) + .when() + .post("/v2/domainnames") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"restApiId\":\"%s\",\"stage\":\"$default\",\"basePath\":\"\"}".formatted(apiId)) + .when() + .post("/domainnames/" + otherDomain + "/basepathmappings") + .then() + .statusCode(201); + + given() + .when() + .get("/domainnames/" + otherDomain + "/basepathmappings/(none)") + .then() + .statusCode(200); + + // One record, whichever spelling created it. + given() + .when() + .get("/v2/domainnames/" + otherDomain + "/apimappings") + .then() + .statusCode(200) + .body("items.size()", is(1)) + .body("items[0].apiMappingKey", is("")); + } + + @Test + @Order(7) + void mappingIdsDoNotCollide() { + // Ids derived by hashing would collide: "Aa" and "BB" share a Java String hashCode, so a + // read or delete by that id would pick between the two mappings arbitrarily. + String first = createMapping("Aa"); + String second = createMapping("BB"); + org.junit.jupiter.api.Assertions.assertNotEquals(first, second); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/" + first) + .then() + .statusCode(200) + .body("apiMappingKey", is("Aa")); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/" + second) + .then() + .statusCode(200) + .body("apiMappingKey", is("BB")); + } + + private String createMapping(String key) { + return given() + .contentType(ContentType.JSON) + .body("{\"apiId\":\"%s\",\"stage\":\"$default\",\"apiMappingKey\":\"%s\"}".formatted(apiId, key)) + .when() + .post("/v2/domainnames/" + DOMAIN + "/apimappings") + .then() + .statusCode(201) + .extract().path("apiMappingId"); + } + + @Test + @Order(8) + void anApiStillMappedToADomainCannotBeDeleted() { + // Verified against AWS, which refuses rather than leaving the mapping pointing at an API + // that no longer exists. + given() + .when() + .delete("/v2/apis/" + apiId) + .then() + .statusCode(400) + .body(containsString("remove all API mappings")); + + given() + .when() + .get("/v2/apis/" + apiId) + .then() + .statusCode(200); + } + + @Test + @Order(6) + void inputsFlociCannotHonourAreRefused() { + // Accepting these would answer with a domain that behaves differently from the request. + String[] bodies = { + """ + {"domainName":"mtls.example.com","domainNameConfigurations":[{"endpointType":"REGIONAL"}], + "mutualTlsAuthentication":{"truststoreUri":"s3://bucket/truststore.pem"}}""", + """ + {"domainName":"dualstack.example.com", + "domainNameConfigurations":[{"endpointType":"REGIONAL","ipAddressType":"dualstack"}]}""", + """ + {"domainName":"ownership.example.com","domainNameConfigurations":[ + {"endpointType":"REGIONAL","ownershipVerificationCertificateArn":"arn:aws:acm:us-east-1:0:certificate/o"}]}""" + }; + for (String body : bodies) { + given() + .contentType(ContentType.JSON) + .body(body) + .when() + .post("/v2/domainnames") + .then() + .statusCode(400); + } + } + + @Test + @Order(8) + void getApiMappingByItsId() { + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/" + apiMappingId) + .then() + .statusCode(200) + .body("apiMappingId", is(apiMappingId)) + .body("apiId", is(apiId)); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings") + .then() + .statusCode(200) + .body("items.apiMappingId", hasItemEqualTo(apiMappingId)); + } + + @Test + @Order(9) + void unknownApiMappingIsNotFound() { + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/does-not-exist") + .then() + .statusCode(404); + } + + @Test + @Order(10) + void deleteApiMappingThenDomainName() { + given() + .when() + .delete("/v2/domainnames/" + DOMAIN + "/apimappings/" + apiMappingId) + .then() + .statusCode(204); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/" + apiMappingId) + .then() + .statusCode(404); + + given() + .when() + .delete("/v2/domainnames/" + DOMAIN) + .then() + .statusCode(204); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN) + .then() + .statusCode(404); + } + + private static org.hamcrest.Matcher> hasItemEqualTo(String value) { + return org.hamcrest.Matchers.hasItem(equalTo(value)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiMappingIdTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiMappingIdTest.java new file mode 100644 index 0000000000..11257e84cd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiMappingIdTest.java @@ -0,0 +1,48 @@ +package io.github.hectorvent.floci.services.apigateway; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * The v2 mapping id has to name exactly one stored record. + * + *

It is derived from the base path a record is stored under, which is the only thing that + * identifies it. Not its canonical form, and not the record's own field: writes canonicalise now, + * so no endpoint creates a record under "/" or "", but state written before that can hold one — and + * `BasePathMapping` normalises an empty base path to "(none)" in its constructor, so such a record + * reports "(none)" while living under the key "". Deriving identity from either would give several + * records one id, and a read or a delete would pick between them. + */ +class ApiMappingIdTest { + + @Test + void rootLikeKeysThatWerePersistedSeparatelyKeepSeparateIds() { + String canonical = ApiGatewayController.apiMappingId("(none)"); + String slash = ApiGatewayController.apiMappingId("/"); + String empty = ApiGatewayController.apiMappingId(""); + + assertNotEquals(canonical, slash); + assertNotEquals(canonical, empty); + assertNotEquals(slash, empty); + } + + @Test + void everyIdIsNonEmptyAndStable() { + // A record stored under an empty key must still produce an id a caller can put in a URL. + assertFalse(ApiGatewayController.apiMappingId("").isEmpty()); + assertFalse(ApiGatewayController.apiMappingId(null).isEmpty()); + + assertEquals(ApiGatewayController.apiMappingId("orders"), + ApiGatewayController.apiMappingId("orders")); + } + + @Test + void distinctKeysSharingAJavaHashKeepDistinctIds() { + assertEquals("Aa".hashCode(), "BB".hashCode()); + assertNotEquals(ApiGatewayController.apiMappingId("Aa"), + ApiGatewayController.apiMappingId("BB")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BasePathMappingRecordDeletionTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BasePathMappingRecordDeletionTest.java new file mode 100644 index 0000000000..6f9e67e8b5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BasePathMappingRecordDeletionTest.java @@ -0,0 +1,59 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Deleting a mapping by the record a caller already holds must remove that record and no other. + * + *

The v2 endpoints select a mapping by an id derived from the path it is stored under, then + * delete it. Going back through the normalising lookup would turn a record stored as "/" or "" — + * which state written before writes were canonicalised can still hold — into the canonical root, + * deleting the wrong record and leaving the selected one behind. + */ +@QuarkusTest +class BasePathMappingRecordDeletionTest { + + private static final String REGION = "us-east-1"; + + @Inject + ApiGatewayService service; + + private String domainWithRootMapping(String domainName) { + service.createDomainName(REGION, Map.of("domainName", domainName)); + service.createBasePathMapping(REGION, domainName, + Map.of("restApiId", "api123", "stage", "prod")); + return domainName; + } + + @Test + void deletingByARootLikePathDoesNotRemoveTheCanonicalRecord() { + String domain = domainWithRootMapping("record-deletion.example.com"); + + // No record is stored under "/", so this must find nothing rather than normalise its way + // onto the canonical root. + AwsException e = assertThrows(AwsException.class, + () -> service.deleteBasePathMappingRecord(REGION, domain, "/")); + assertEquals("NotFoundException", e.getErrorCode()); + + assertNotNull(service.getBasePathMapping(REGION, domain, "(none)"), + "the canonical root mapping was deleted by a request for another record"); + } + + @Test + void deletingByTheStoredPathRemovesThatRecord() { + String domain = domainWithRootMapping("record-deletion-2.example.com"); + + service.deleteBasePathMappingRecord(REGION, domain, "(none)"); + + assertThrows(AwsException.class, () -> service.getBasePathMapping(REGION, domain, "(none)")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/LegacyBasePathMappingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/LegacyBasePathMappingIntegrationTest.java new file mode 100644 index 0000000000..a22d397e17 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/LegacyBasePathMappingIntegrationTest.java @@ -0,0 +1,102 @@ +package io.github.hectorvent.floci.services.apigateway; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Mappings written before base paths were canonicalised on write. + * + *

Such a record sits under the key {@code ""} while reporting {@code (none)} from its own field, + * because {@link BasePathMapping} normalises in its constructor. No endpoint can create one now, so + * the state is seeded through the same storage backend the service uses — the factory hands out one + * backend per file. + */ +@QuarkusTest +class LegacyBasePathMappingIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String DOMAIN = "legacy-mapping.example.com"; + + @Inject + StorageFactory storageFactory; + + @Inject + ApiGatewayService service; + + private StorageBackend mappings() { + return storageFactory.create("apigateway", "apigateway-mappings.json", + new TypeReference>() {}); + } + + private void seedLegacyState() { + service.createDomainName(REGION, Map.of("domainName", DOMAIN)); + // The canonical root, as writes produce it today. + service.createBasePathMapping(REGION, DOMAIN, Map.of("restApiId", "api-canonical", "stage", "prod")); + // And one the old write path left under the empty key; its field still reads "(none)". + mappings().put(REGION + "::" + DOMAIN + "::", new BasePathMapping("", "api-legacy", "prod")); + } + + @Test + void eachRecordKeepsItsOwnIdAndDeletesItself() { + seedLegacyState(); + + String canonicalId = ApiGatewayController.apiMappingId("(none)"); + String legacyId = ApiGatewayController.apiMappingId(""); + assertNotEquals(canonicalId, legacyId); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings") + .then() + .statusCode(200) + .body("items.apiMappingId", hasItem(canonicalId)) + .body("items.apiMappingId", hasItem(legacyId)); + + // Each id resolves to its own record rather than to whichever matched first. + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/" + legacyId) + .then() + .statusCode(200) + .body("apiId", is("api-legacy")); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/" + canonicalId) + .then() + .statusCode(200) + .body("apiId", is("api-canonical")); + + // Deleting the legacy record removes that record, not the canonical root beside it. + given() + .when() + .delete("/v2/domainnames/" + DOMAIN + "/apimappings/" + legacyId) + .then() + .statusCode(204); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/" + legacyId) + .then() + .statusCode(404); + + given() + .when() + .get("/v2/domainnames/" + DOMAIN + "/apimappings/" + canonicalId) + .then() + .statusCode(200) + .body("apiId", is("api-canonical")); + } +}