feat(apigatewayv2): support custom domain names and API mappings (#2390)

* feat(apigatewayv2): support custom domain names and API mappings

POST /v2/domainnames was not routed, so it matched the S3 controller's catch-all
and answered with an S3 XML error about multipart uploads, which an SDK
expecting JSON cannot deserialize. The same was true of the API mappings a
domain is used through.

Adds the eight actions over the records the REST endpoints already keep, since a
custom domain is one resource in AWS reachable through both APIs. A domain
created here is therefore visible to the v1 endpoints and resolves through the
Host-header routing that already exists:

- CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName
- CreateApiMapping, GetApiMapping, GetApiMappings, DeleteApiMapping
- the mapping id is derived from what identifies the mapping, so it survives a
  restart and is the same id whichever API created it

Taken from a live AWS account rather than the service model alone, which the
model does not tell you:

- every domain reports RoutingMode API_MAPPING_ONLY and an ipv4 IpAddressType
- a create without exactly one configuration is "Invalid input. Expected one
  domain name configuration"
- a duplicate domain is BadRequestException, not a conflict — for the REST API
  too, so the shared code and the test that asserted 409 were both wrong
- deleting an API that a domain still maps to is refused: "Please remove all API
  mappings for the API from your custom domain names"
- an unknown domain is "Invalid domain name identifier specified"

Tags are stored and returned rather than dropped, which would have left
terraform with a diff it could never settle. Mutual TLS, ownership verification
certificates, routing rules and non-ipv4 address types are refused rather than
accepted and ignored, so nothing is answered with a domain that behaves
differently from the one that was asked for.

* fix(apigatewayv2): make api mapping ids unique and validate what a mapping points at

Five problems from review of the previous commit.

Mapping ids were derived by hashing the base path, so two keys sharing a Java
hash shared an id and a read or delete by that id picked between them. The base
path is encoded rather than hashed, which cannot collide.

An omitted mapping key and an explicit empty one produced two different records,
where the shared store keeps the root mapping under "(none)" and could no longer
find either from v1. Both spellings now canonicalise to the one record, and a
second attempt is the ConflictException AWS answers: "ApiMapping key already
exists for this domain name".

A mapping was accepted for an API or stage that does not exist, returning 201
for something that routes nowhere. Both are looked up first, and answer as AWS
does: "Invalid API identifier specified: <id>" and "Invalid stage identifier
specified".

The delete guard scanned only the caller's region, so an API could still be
deleted out from under a mapping made in another region. It scans every region,
since a mapping is keyed under the region of its domain rather than of its API.

A domainNameConfigurations entry that was not an object passed the size check and
then failed an unchecked cast, answering 500 instead of the AWS-shaped 400.

* fix(apigateway): canonicalise base paths on write, key mapping ids off what is stored

Canonicalising only where the v2 mapping id was derived left the collision it was
meant to remove: the store could hold "(none)", "/" and "" as separate records
that all mean the root, and folding them together at id time gave them one id for
a read or a delete to choose between.

Base paths are canonicalised where they are written instead, matching what reads
have always done. The store can no longer gain a second record meaning the root,
and a v1 mapping created as "" can now be read back as "", which it could not
before: the write kept the raw value while the read looked for the canonical one.

The id is derived from the path a record is stored under rather than its
canonical form, so state persisted before this change keeps one id per record
rather than several records sharing one. No endpoint can create such a record
now, so that property is asserted directly against the records deserialization
can restore.

* fix(apigateway): delete the mapping record that was selected, not its canonical twin

The v2 endpoints select a mapping by an id derived from the path its record is
stored under, then deleted it through the lookup that normalises the root. For a
record left under "/" or "" by state written before writes were canonicalised,
that deleted the canonical root instead and left the selected record in place.

Deletion by record now addresses the stored path exactly, so the record that
answered the lookup is the record that goes. The normalising delete stays for
callers that pass a key to look one up by, which is what the REST endpoint does.

* fix(apigatewayv2): identify a mapping by its stored key, not by the field it reports

BasePathMapping normalises an empty base path to "(none)" in its constructor, so
a record the old write path left under the key "" reports "(none)" from its own
field. Deriving the mapping id from that field gave it the canonical root's id,
and deleting by it removed the canonical root while leaving the record behind —
the collision the previous commit was meant to close, through the one door it
left open.

The service exposes mappings keyed by the base path each record is stored under,
and the v2 endpoints derive ids, resolve lookups and delete through that key. The
key is the only thing that identifies a record; the field can disagree with it.

Seeded through the storage backend the service uses, since no endpoint creates
such a record any more: the test asserts the two records keep separate ids, each
id resolves to its own record, and deleting one leaves the other.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-18 20:27:44 -04:00
1 parent 48880aa79a
commit 74da157681
9 files changed
+1024 -8

No files matched your search

@@ -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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> readJsonBody(String body) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> 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<String, Object> 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<String, Object> toV1DomainRequest(Map<String, Object> request) {
Map<String, Object> 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<String, Object> 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());
@@ -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<String, String> 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<String, Object> 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<CustomDomain> 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<String, Object> 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.
*
* <p>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<String, BasePathMapping> basePathMappingsByStoredPath(String region, String domainName) {
getDomainName(region, domainName);
String prefix = region + "::" + domainName + "::";
Map<String, BasePathMapping> 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 ────────────────────────────
/**
@@ -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<String, String> 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<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}