mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
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:
1 parent
48880aa79a
commit
74da157681
9 files changed
+1024
-8
No files matched your search
@@ -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
|
||||
|
||||
+270
@@ -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());
|
||||
|
||||
+94
-4
@@ -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; }
|
||||
}
|
||||
+3
-2
@@ -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)
|
||||
|
||||
+439
@@ -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.
|
||||
*
|
||||
* <p>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<Iterable<? super String>> hasItemEqualTo(String value) {
|
||||
return org.hamcrest.Matchers.hasItem(equalTo(value));
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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"));
|
||||
}
|
||||
}
|
||||
+59
@@ -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.
|
||||
*
|
||||
* <p>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)"));
|
||||
}
|
||||
}
|
||||
+102
@@ -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.
|
||||
*
|
||||
* <p>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<String, BasePathMapping> mappings() {
|
||||
return storageFactory.create("apigateway", "apigateway-mappings.json",
|
||||
new TypeReference<Map<String, BasePathMapping>>() {});
|
||||
}
|
||||
|
||||
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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user