mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(cloudformation): provision AWS::ApiGatewayV2::DomainName and ApiMapping (#5038)
* refactor(apigateway): move the v2 domain and API mapping rules into the service CreateDomainName and CreateApiMapping on /v2/domainnames kept their rules in ApiGatewayController: the one-configuration check, the refusal of inputs Floci does not emulate, the flattening onto the shared custom-domain store, the API and stage existence check, the mapping key conflict check, the API type the mapping is routed as, and the mapping id. A CloudFormation provisioner cannot reach a controller, so it would have had to copy them. They now live in ApiGatewayService. createV2DomainName validates the body and creates the domain; createApiMapping checks the API and stage, refuses a key that is taken and routes the mapping as the API's protocol type; getApiMapping, deleteApiMapping and apiMappingId follow. ApiGatewayService takes ApiGatewayV2Service for the API and stage lookup, so the whole rule sits in one place and a caller needs one service. Nothing on the v2 side depends on the v1 service, so this adds no cycle. Leaving the lookup in ApiGatewayV2Service was tried first, but then every caller had to resolve the API before calling into ApiGatewayService, and the rule was split across two classes again. The code is moved, not rewritten: messages, error codes, the order of the checks and the id scheme are unchanged, and the controller delegates. * feat(cloudformation): provision AWS::ApiGatewayV2::DomainName and ApiMapping Both types were left to the stub arm. A stack reported CREATE_COMPLETE, but no domain or mapping existed, Fn::GetAtt on the domain resolved to literals such as DomainResource.RegionalDomainName (so a Route 53 alias built from it pointed nowhere), and with allow-stub-unsupported-resource-types off the stack rolled back. ApiGatewayV2DomainCfnProvisioner creates them through the v2 rules in ApiGatewayService and injects only that service. Ref on a domain is its name and Fn::GetAtt returns DomainNameArn, RegionalDomainName and RegionalHostedZoneId as GetDomainName reports them. Ref on a mapping is its ApiMappingId, which is also its only attribute. Updates follow AWS. DomainName is the only createOnly property of either type, and everything else changes in place: the domain's configuration is replaced as a whole, as DomainNameConfigurations is on AWS, and a mapping's ApiId, Stage and ApiMappingKey change without a new id. To keep the id across a key change, a mapping now stores the apiMappingId it was given instead of deriving it from its key on every read. A record persisted before is still read under the derived id, and a new mapping gets the id it always had unless another mapping holds it. Deriving the id and documenting the difference was the first version; it was dropped because Ref changed where AWS keeps it, and the change set already reported the key change as an update. A replacement creates the new entity and leaves the displaced one to ReplacementCleanup, so it is deleted in UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, kept under UpdateReplacePolicy: Retain, and put back when a later resource fails the update. The first version deleted the old domain inside provision, as the v1 provisioner does, and a failed rename then ended in UPDATE_ROLLBACK_FAILED with the original domain and its mappings already gone. A mapping moved to another domain gets an id the displaced mapping does not hold, since two mappings under one physical id cannot be told apart, and the domain of each displaced id is recorded beside the cleanup. An in-place update snapshots what it changes, so a failed stack update restores it instead of ending in UPDATE_ROLLBACK_FAILED. CDK templates needed the v2 rules to match AWS in two more places. apigateway.DomainName with a multi-level basePath maps a REST API through AWS::ApiGatewayV2::ApiMapping, so a mapping now accepts a REST API stage. And the restrictions AWS documents for API mappings are enforced, in the API and in templates alike: no v2 call on an edge-optimized domain, with AWS's message; TLS_1_2 for an HTTP API or a multi-level key, which also keeps such a domain on TLS_1_2; no WebSocket API beside an HTTP or REST API; and AWS's key characters and length. The id-only delete accepts <ApiMappingId>|<DomainName>, the type's primary identifier, which is how Cloud Control names a mapping; a bare id still answers NotFoundException, so Cloud Control cannot report a delete that did not happen. The integration test deploys two templates aws-cdk-lib 2.272.0 synthesized, checked in with the app that produced them, and compat-cdk deploys the same shapes. * fix(apigateway): answer v2 domain and API mapping calls as API Gateway does The review of this PR found four places where Floci answered differently from API Gateway. Each was measured against API Gateway in eu-west-1 on 2026-10-04, with an imported certificate on a throwaway domain. An HTTP API custom domain is regional. CreateDomainName and UpdateDomainName with an endpoint type of PRIVATE, or one API Gateway does not know, give a REGIONAL domain, where Floci refused the first and stored the type on an update. EDGE is refused with "EDGE endpoint type is not supported for APIGatewayV2 domainName", not the message for v2 calls on an existing edge-optimized domain. API mapping keys are checked as API Gateway checks them, with its messages: a key does not end with '/', does not start with '/' or hold '//', holds letters, digits and $-_.+!*'(), between its levels, and is at most 300 characters. No key, an empty one, or on a create one of whitespace only, is the root; an update refuses whitespace only. Floci took "/" for the root and had its own message for the characters, without the comma. UpdateApiMapping and UpdateDomainName answer over the v2 HTTP API, not only from CloudFormation. What an UpdateApiMapping leaves out keeps its value. Cloud Control identifies an AWS::ApiGatewayV2::ApiMapping by the type's primary identifier, <ApiMappingId>|<DomainName>, while CloudFormation's Ref stays the bare id: CloudControlService derives the identifier from the desired state, as it already names primary identifier fields by type, and the provisioner deletes by it with the create-time attributes too. * fix(apigateway): refuse a v2 update of an edge domain, and recover a compound identifier whole The second review pass found three gaps in the previous commit. UpdateDomainName through the v2 API converted a v1-created edge-optimized domain to REGIONAL. The v2 API does not manage an edge-optimized domain, so the update is refused with the message every other v2 call on one gets, and the CloudFormation in-place update goes through the same check. A v2 UpdateDomainName without a configuration returned the domain unchanged without looking at the rest of the body, so a mutual TLS request was silently dropped. ApiGatewayService.updateV2DomainName now refuses what Floci does not emulate, and the edge-optimized domain, either way. Cloud Control's recovery of a create that finished just before a restart took the identifier after the last '|' of its key, which for an API mapping's <ApiMappingId>|<DomainName> left only the domain. It now takes everything after the key's third separator. A later review pass found four more points. UpdateApiMapping fills in what its body leaves out under the lock the update takes, so two partial updates of one mapping cannot write back each other's old values. A v2 domain's certificate is stored as the v1 API's regional certificate, which is what a regional domain reports through both APIs; a domain the v2 API wrote before still reports the one it holds until its configuration is replaced. The domain ARN both APIs and both CloudFormation provisioners build comes from ApiGatewayService.domainNameArn, the Cloud Control test waits with the awaitSuccess helper main has since gained, and requireMappingAllowed's javadoc is back on it.
This commit is contained in:
1 parent
b1bb016b6e
commit
85e0061a6f
27 files changed
+3729
-169
No files matched your search
+54
-141
@@ -5,9 +5,9 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
|
||||
@@ -50,11 +50,9 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -1613,16 +1611,7 @@ public class ApiGatewayController {
|
||||
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));
|
||||
CustomDomain domain = service.createV2DomainName(region, request);
|
||||
return Response.status(201).entity(toV2DomainNode(region, domain).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
@@ -1645,6 +1634,20 @@ public class ApiGatewayController {
|
||||
return Response.ok(toV2DomainNode(region, domain).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code UpdateDomainName}: the body's configuration replaces the domain's as a whole, and a body
|
||||
* without one changes nothing.
|
||||
*/
|
||||
@PATCH
|
||||
@Path("/v2/domainnames/{domainName}")
|
||||
public Response updateV2DomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
Map<String, Object> request = readJsonBody(body);
|
||||
CustomDomain domain = service.updateV2DomainName(region, domainName, request);
|
||||
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) {
|
||||
@@ -1667,26 +1670,11 @@ public class ApiGatewayController {
|
||||
}
|
||||
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,
|
||||
v2Service.getApi(region, apiId).getProtocolType());
|
||||
return Response.status(201).entity(toApiMappingNode(basePath, mapping).toString())
|
||||
String apiMappingKey = request.get("apiMappingKey") == null
|
||||
? null
|
||||
: String.valueOf(request.get("apiMappingKey"));
|
||||
StoredMapping created = service.createApiMapping(region, domainName, apiMappingKey, apiId, stage);
|
||||
return Response.status(201).entity(toApiMappingNode(created).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@@ -1696,8 +1684,7 @@ public class ApiGatewayController {
|
||||
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)));
|
||||
service.getApiMappings(region, domainName).forEach(mapping -> items.add(toApiMappingNode(mapping)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@@ -1707,21 +1694,34 @@ public class ApiGatewayController {
|
||||
@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())
|
||||
StoredMapping found = service.getApiMapping(region, domainName, apiMappingId);
|
||||
return Response.ok(toApiMappingNode(found).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code UpdateApiMapping}: what the body leaves out keeps its value, as on AWS, and the mapping
|
||||
* keeps its id through a change of key.
|
||||
*/
|
||||
@PATCH
|
||||
@Path("/v2/domainnames/{domainName}/apimappings/{apiMappingId}")
|
||||
public Response updateApiMapping(@Context HttpHeaders headers,
|
||||
@PathParam("domainName") String domainName,
|
||||
@PathParam("apiMappingId") String apiMappingId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
Map<String, Object> request = readJsonBody(body);
|
||||
StoredMapping updated = service.updateApiMapping(region, domainName, apiMappingId, request);
|
||||
return Response.ok(toApiMappingNode(updated).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());
|
||||
service.deleteApiMapping(region, domainName, apiMappingId);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
@@ -2458,58 +2458,10 @@ public class ApiGatewayController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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", AwsArnUtils.Arn.of("apigateway", region, "", "/domainnames/" + d.getDomainName()).toString());
|
||||
node.put("domainNameArn", ApiGatewayService.domainNameArn(region, d.getDomainName()));
|
||||
node.put("apiMappingSelectionExpression", "$request.basepath");
|
||||
// AWS reports both of these on every domain.
|
||||
node.put("routingMode", "API_MAPPING_ONLY");
|
||||
@@ -2520,11 +2472,13 @@ public class ApiGatewayController {
|
||||
configuration.put("endpointType", d.getEndpointConfigurationType());
|
||||
configuration.put("domainNameStatus", d.getDomainNameStatus());
|
||||
configuration.put("ipAddressType", "ipv4");
|
||||
if (d.getCertificateArn() != null) {
|
||||
configuration.put("certificateArn", d.getCertificateArn());
|
||||
String certificateArn = ApiGatewayService.v2CertificateArn(d);
|
||||
if (certificateArn != null) {
|
||||
configuration.put("certificateArn", certificateArn);
|
||||
}
|
||||
if (d.getCertificateName() != null) {
|
||||
configuration.put("certificateName", d.getCertificateName());
|
||||
String certificateName = ApiGatewayService.v2CertificateName(d);
|
||||
if (certificateName != null) {
|
||||
configuration.put("certificateName", certificateName);
|
||||
}
|
||||
if (d.getSecurityPolicy() != null) {
|
||||
configuration.put("securityPolicy", d.getSecurityPolicy());
|
||||
@@ -2537,65 +2491,24 @@ public class ApiGatewayController {
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toApiMappingNode(String storedPath, BasePathMapping mapping) {
|
||||
private ObjectNode toApiMappingNode(StoredMapping stored) {
|
||||
String storedPath = stored.storedPath();
|
||||
BasePathMapping mapping = stored.mapping();
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("apiMappingId", apiMappingId(storedPath));
|
||||
node.put("apiMappingId", stored.apiMappingId());
|
||||
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.
|
||||
// The key reported is the one the record is stored under, which is the path it routes on.
|
||||
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(String region, CustomDomain d) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("domainName", d.getDomainName());
|
||||
node.put("domainNameArn", AwsArnUtils.Arn.of("apigateway", region, "", "/domainnames/" + d.getDomainName()).toString());
|
||||
node.put("domainNameArn", ApiGatewayService.domainNameArn(region, d.getDomainName()));
|
||||
node.put("domainNameStatus", d.getDomainNameStatus());
|
||||
node.put("endpointConfigurationType", d.getEndpointConfigurationType());
|
||||
node.putObject("endpointConfiguration").putArray("types").add(d.getEndpointConfigurationType());
|
||||
|
||||
+499
-4
@@ -41,6 +41,7 @@ import io.github.hectorvent.floci.services.apigateway.model.Stage;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.VpcLink;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.swagger.parser.OpenAPIParser;
|
||||
import io.swagger.v3.core.util.Json;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
@@ -55,6 +56,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
@@ -63,6 +65,7 @@ import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -117,6 +120,8 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
private final TlsCertificateManager certificateManager;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
/** The v2 APIs an API mapping can point at; a custom domain is shared by both APIs. */
|
||||
private final ApiGatewayV2Service apiGatewayV2Service;
|
||||
|
||||
// Constants
|
||||
private static final String EPC_KEY = "endpointConfiguration";
|
||||
@@ -124,6 +129,21 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
private static final String EPC_VPC_IDS_KEY = "vpcEndpointIds";
|
||||
private static final String EPC_TYPES_PATH = "/endpointConfiguration/types/";
|
||||
private static final String EPC_VPC_IDS_PATH = "/endpointConfiguration/vpcEndpointIds";
|
||||
private static final String TLS_1_2 = "TLS_1_2";
|
||||
/** The API type a mapping to a REST API is stored with, beside a v2 API's protocol type. */
|
||||
private static final String REST_API_TYPE = "REST";
|
||||
/** What AWS answers for a v2 API mapping call on an edge-optimized domain. */
|
||||
private static final String V2_EDGE_DOMAIN_MESSAGE = "Only REGIONAL domain names can be managed through the "
|
||||
+ "API Gateway V2 API. For EDGE domain names, please use the API Gateway V1 API. Also note that only REST "
|
||||
+ "APIs can be attached to EDGE domain names.";
|
||||
/** What AWS answers for a v2 domain created or updated with the EDGE endpoint type. */
|
||||
private static final String V2_EDGE_ENDPOINT_TYPE_MESSAGE =
|
||||
"EDGE endpoint type is not supported for APIGatewayV2 domainName";
|
||||
/** The characters AWS allows in an API mapping key, its level separator included, and the most it takes. */
|
||||
private static final Pattern API_MAPPING_KEY = Pattern.compile("[A-Za-z0-9$\\-_.+!*'(),/]+");
|
||||
private static final int MAX_API_MAPPING_KEY_LENGTH = 300;
|
||||
private static final String MAPPING_KEY_SLASHES_MESSAGE =
|
||||
"API mapping key should not start with a '/' or have consecutive '/'s.";
|
||||
|
||||
ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,
|
||||
TlsCertificateManager certificateManager) {
|
||||
@@ -131,12 +151,20 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
new RegionResolver(config.defaultRegion(), config.defaultAccountId()));
|
||||
}
|
||||
|
||||
ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,
|
||||
TlsCertificateManager certificateManager, RegionResolver regionResolver) {
|
||||
this(storageFactory, config, certificateManager, regionResolver,
|
||||
new ApiGatewayV2Service(storageFactory, config, regionResolver));
|
||||
}
|
||||
|
||||
@Inject
|
||||
public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,
|
||||
TlsCertificateManager certificateManager, RegionResolver regionResolver) {
|
||||
TlsCertificateManager certificateManager, RegionResolver regionResolver,
|
||||
ApiGatewayV2Service apiGatewayV2Service) {
|
||||
this.certificateManager = certificateManager;
|
||||
this.config = config;
|
||||
this.regionResolver = regionResolver;
|
||||
this.apiGatewayV2Service = apiGatewayV2Service;
|
||||
this.apiStore = storageFactory.create("apigateway", "apigateway-apis.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
@@ -2013,6 +2041,14 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
|
||||
// ──────────────────────────── Custom Domains ────────────────────────────
|
||||
|
||||
/**
|
||||
* A public custom domain's ARN, {@code arn:<partition>:apigateway:<region>::/domainnames/<name>},
|
||||
* which both APIs report and CloudFormation's {@code DomainNameArn} returns.
|
||||
*/
|
||||
public static String domainNameArn(String region, String domainName) {
|
||||
return AwsArnUtils.Arn.of("apigateway", region, "", "/domainnames/" + domainName).toString();
|
||||
}
|
||||
|
||||
public CustomDomain createDomainName(String region, Map<String, Object> request) {
|
||||
String domainName = (String) request.get("domainName");
|
||||
if (domainName == null) throw new AwsException("BadRequestException", "domainName is required", 400);
|
||||
@@ -2200,6 +2236,9 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
throw new AwsException("BadRequestException", "Unsupported path: " + path, 400);
|
||||
}
|
||||
}
|
||||
if (!Objects.equals(newSecurityPolicy, domain.getSecurityPolicy())) {
|
||||
requireMappingsAllowSecurityPolicy(region, domainName, newSecurityPolicy);
|
||||
}
|
||||
// Only a change of type is held to the partition: an EDGE domain stored before the rule
|
||||
// existed must still take certificate or security-policy updates.
|
||||
if (!Objects.equals(newEndpointConfigurationType, domain.getEndpointConfigurationType())) {
|
||||
@@ -2228,11 +2267,11 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public BasePathMapping createBasePathMapping(String region, String domainName, Map<String, Object> request) {
|
||||
return createBasePathMapping(region, domainName, request, "REST");
|
||||
return createBasePathMapping(region, domainName, request, REST_API_TYPE, Set.of());
|
||||
}
|
||||
|
||||
BasePathMapping createBasePathMapping(String region, String domainName,
|
||||
Map<String, Object> request, String apiType) {
|
||||
private BasePathMapping createBasePathMapping(String region, String domainName, Map<String, Object> request,
|
||||
String apiType, Set<String> excludedIds) {
|
||||
String basePath = canonicalBasePath((String) request.get("basePath"));
|
||||
String apiId = (String) request.get("restApiId");
|
||||
String stage = (String) request.get("stage");
|
||||
@@ -2245,6 +2284,8 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
if (basePathMappingStore.get(key).isPresent()) {
|
||||
throw new AwsException("ConflictException", "Base path already exists for this domain name", 409);
|
||||
}
|
||||
requireProtocolTypesCompatible(region, domainName, apiType, null);
|
||||
mapping.setApiMappingId(unusedApiMappingId(region, domainName, basePath, excludedIds));
|
||||
basePathMappingStore.put(key, mapping);
|
||||
}
|
||||
LOG.infov("Created mapping for {0} path={1} -> API {2}", domainName, basePath, apiId);
|
||||
@@ -2372,6 +2413,460 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
return mapping;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Custom Domains and API Mappings (v2) ────────────────────────────
|
||||
//
|
||||
// A custom domain is one resource in AWS, reachable through both APIs, so the v2 operations read
|
||||
// and write the same records the v1 ones do. The rules live here rather than in the controller
|
||||
// because CloudFormation's AWS::ApiGatewayV2 types go through them too.
|
||||
|
||||
/** {@code CreateDomainName} through the v2 API, from its request body. */
|
||||
public CustomDomain createV2DomainName(String region, Map<String, Object> request) {
|
||||
return createDomainName(region, toV1DomainRequest(request));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code UpdateDomainName} through the v2 API: a body with a configuration replaces the domain's
|
||||
* as {@link #replaceV2DomainConfiguration} does. One without changes nothing, after the same
|
||||
* refusals: of what Floci does not emulate, and of an edge-optimized domain, which the v2 API
|
||||
* does not manage.
|
||||
*/
|
||||
public CustomDomain updateV2DomainName(String region, String domainName, Map<String, Object> request) {
|
||||
if (request.get("domainNameConfigurations") != null) {
|
||||
return replaceV2DomainConfiguration(region, domainName, request);
|
||||
}
|
||||
rejectUnemulatedDomainInputs(request, Map.of());
|
||||
CustomDomain domain = getDomainName(region, domainName);
|
||||
requireRegionalDomain(domain);
|
||||
return domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drives a domain's configuration to the one in a v2 {@code CreateDomainName} body, validated the
|
||||
* same way. This is what an update of {@code DomainNameConfigurations} does on AWS: the list is
|
||||
* replaced as a whole, so a certificate the body leaves out is cleared and a security policy it
|
||||
* leaves out takes the {@code TLS_1_2} default. The domain is regional, so its certificate goes to
|
||||
* the regional fields, and one left in the edge-optimized fields by an earlier v2 write is
|
||||
* cleared with the rest. Tags are not touched.
|
||||
*/
|
||||
public CustomDomain replaceV2DomainConfiguration(String region, String domainName,
|
||||
Map<String, Object> request) {
|
||||
Map<String, Object> v1Request = toV1DomainRequest(request);
|
||||
String securityPolicy = (String) v1Request.getOrDefault("securityPolicy", TLS_1_2);
|
||||
synchronized (domainNameLock) {
|
||||
CustomDomain domain = getDomainName(region, domainName);
|
||||
requireRegionalDomain(domain);
|
||||
if (!Objects.equals(securityPolicy, domain.getSecurityPolicy())) {
|
||||
requireMappingsAllowSecurityPolicy(region, domainName, securityPolicy);
|
||||
}
|
||||
domain.setCertificateArn(null);
|
||||
domain.setCertificateName(null);
|
||||
domain.setRegionalCertificateArn((String) v1Request.get("regionalCertificateArn"));
|
||||
domain.setRegionalCertificateName((String) v1Request.get("regionalCertificateName"));
|
||||
domain.setSecurityPolicy(securityPolicy);
|
||||
applyEndpointType(domain, endpointTypeOf(v1Request), region);
|
||||
domainStore.put(domainKey(region, domainName), domain);
|
||||
return domain;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens a v2 {@code CreateDomainName} body onto the keys the shared custom-domain store is
|
||||
* written with, after refusing what floci does not emulate.
|
||||
*/
|
||||
private static Map<String, Object> toV1DomainRequest(Map<String, Object> request) {
|
||||
// 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);
|
||||
}
|
||||
if ("EDGE".equals(configuration.get("endpointType"))) {
|
||||
throw new AwsException("BadRequestException", V2_EDGE_ENDPOINT_TYPE_MESSAGE, 400);
|
||||
}
|
||||
rejectUnemulatedDomainInputs(request, configuration);
|
||||
Map<String, Object> v1Request = new HashMap<>();
|
||||
v1Request.put("domainName", request.get("domainName"));
|
||||
copyIfPresent(request, v1Request, "tags", "tags");
|
||||
// An HTTP API domain is regional: API Gateway creates or keeps any other endpoint type it is
|
||||
// given, PRIVATE or one it does not know, as REGIONAL (measured, eu-west-1, 2026-10-04). Its
|
||||
// certificate is the regional one, which the v1 API reports as regionalCertificateArn.
|
||||
copyIfPresent(configuration, v1Request, "certificateArn", "regionalCertificateArn");
|
||||
copyIfPresent(configuration, v1Request, "certificateName", "regionalCertificateName");
|
||||
v1Request.put("endpointType", "REGIONAL");
|
||||
copyIfPresent(configuration, v1Request, "securityPolicy", "securityPolicy");
|
||||
return v1Request;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/** A v2 API mapping: the base path mapping record, with the base path it is stored under. */
|
||||
public record StoredMapping(String storedPath, BasePathMapping mapping) {
|
||||
|
||||
/** The id stored on the record, or for a record persisted before ids were stored, the derived one. */
|
||||
public String apiMappingId() {
|
||||
return mapping.getApiMappingId() != null
|
||||
? mapping.getApiMappingId()
|
||||
: ApiGatewayService.apiMappingId(storedPath);
|
||||
}
|
||||
}
|
||||
|
||||
/** What a mapping routes to: an API, one of its stages, and the type of API it is routed as. */
|
||||
private record MappingTarget(String apiId, String stage, String apiType) {}
|
||||
|
||||
/** The mappings of a domain, refused for an edge-optimized one as AWS refuses every v2 call on it. */
|
||||
public List<StoredMapping> getApiMappings(String region, String domainName) {
|
||||
requireRegionalDomain(getDomainName(region, domainName));
|
||||
List<StoredMapping> mappings = new ArrayList<>();
|
||||
basePathMappingsByStoredPath(region, domainName)
|
||||
.forEach((storedPath, mapping) -> mappings.add(new StoredMapping(storedPath, mapping)));
|
||||
return mappings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a v2 API mapping, stored as a base path mapping that remembers the type of API it
|
||||
* routes to.
|
||||
*/
|
||||
public StoredMapping createApiMapping(String region, String domainName, String apiMappingKey,
|
||||
String apiId, String stage) {
|
||||
return createApiMapping(region, domainName, apiMappingKey, apiId, stage, Set.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* As above, with ids the new mapping must not be given. A caller that still tracks a mapping on
|
||||
* another domain under one of them would otherwise hold two mappings it cannot tell apart; on
|
||||
* AWS a new mapping never takes the id of another.
|
||||
*/
|
||||
public StoredMapping createApiMapping(String region, String domainName, String apiMappingKey,
|
||||
String apiId, String stage, Set<String> excludedIds) {
|
||||
// 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.
|
||||
requireValidApiMappingKey(apiMappingKey, false);
|
||||
MappingTarget target = requireMappingTarget(region, apiId, stage);
|
||||
String basePath = canonicalBasePath(apiMappingKey);
|
||||
synchronized (domainNameLock) {
|
||||
requireMappingAllowed(getDomainName(region, domainName), basePath, target.apiType());
|
||||
requireApiMappingKeyFree(region, domainName, basePath);
|
||||
|
||||
Map<String, Object> v1Request = new HashMap<>();
|
||||
v1Request.put("restApiId", target.apiId());
|
||||
v1Request.put("stage", target.stage());
|
||||
v1Request.put("basePath", basePath);
|
||||
return new StoredMapping(basePath,
|
||||
createBasePathMapping(region, domainName, v1Request, target.apiType(), excludedIds));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The v2 {@code UpdateApiMapping} from its request body: what the body leaves out keeps its value,
|
||||
* as on AWS. The values it keeps are read under the lock the update takes, so two updates naming
|
||||
* different fields of one mapping cannot write back each other's old values.
|
||||
*/
|
||||
public StoredMapping updateApiMapping(String region, String domainName, String apiMappingId,
|
||||
Map<String, Object> request) {
|
||||
synchronized (domainNameLock) {
|
||||
StoredMapping current = getApiMapping(region, domainName, apiMappingId);
|
||||
String currentKey = canonicalBasePath(current.storedPath());
|
||||
String apiMappingKey = request.containsKey("apiMappingKey")
|
||||
? Objects.toString(request.get("apiMappingKey"), null)
|
||||
: ("(none)".equals(currentKey) ? null : currentKey);
|
||||
String apiId = Objects.toString(request.get("apiId"), current.mapping().getRestApiId());
|
||||
String stage = Objects.toString(request.get("stage"), current.mapping().getStage());
|
||||
return updateApiMapping(region, domainName, apiMappingId, apiMappingKey, apiId, stage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Points a v2 API mapping at a new key, API and stage, the v2 {@code UpdateApiMapping}. The id
|
||||
* names the mapping rather than its key, so it stays with the record when the key changes, as on
|
||||
* AWS.
|
||||
*/
|
||||
public StoredMapping updateApiMapping(String region, String domainName, String apiMappingId,
|
||||
String apiMappingKey, String apiId, String stage) {
|
||||
requireValidApiMappingKey(apiMappingKey, true);
|
||||
MappingTarget target = requireMappingTarget(region, apiId, stage);
|
||||
String basePath = canonicalBasePath(apiMappingKey);
|
||||
synchronized (domainNameLock) {
|
||||
CustomDomain domain = getDomainName(region, domainName);
|
||||
StoredMapping found = getApiMapping(region, domainName, apiMappingId);
|
||||
requireMappingAllowed(domain, basePath, target.apiType());
|
||||
requireProtocolTypesCompatible(region, domainName, target.apiType(), found.storedPath());
|
||||
BasePathMapping mapping = found.mapping();
|
||||
String storedPath = found.storedPath();
|
||||
if (!basePath.equals(canonicalBasePath(storedPath))) {
|
||||
requireApiMappingKeyFree(region, domainName, basePath);
|
||||
// Pinned before the record leaves the path a legacy id was derived from.
|
||||
mapping.setApiMappingId(found.apiMappingId());
|
||||
basePathMappingStore.delete(mappingKey(region, domainName, storedPath));
|
||||
mapping.setBasePath(basePath);
|
||||
storedPath = basePath;
|
||||
}
|
||||
mapping.setRestApiId(target.apiId());
|
||||
mapping.setStage(target.stage());
|
||||
mapping.setApiType(target.apiType());
|
||||
basePathMappingStore.put(mappingKey(region, domainName, storedPath), mapping);
|
||||
return new StoredMapping(storedPath, mapping);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The API and stage a v2 API mapping points at. AWS takes a REST API here as well as an HTTP or
|
||||
* WebSocket API, which is how a REST API gets a mapping with more than one level, and refuses an
|
||||
* API or stage that does not exist rather than creating a mapping that routes nowhere. A v2 API
|
||||
* answers first, as it did before REST APIs were accepted.
|
||||
*/
|
||||
private MappingTarget requireMappingTarget(String region, String apiId, String stageName) {
|
||||
String apiType = v2ApiType(region, apiId);
|
||||
boolean restApi = apiType == null && restApiExists(region, apiId);
|
||||
if (apiType == null && !restApi) {
|
||||
throw new AwsException("BadRequestException", "Invalid API identifier specified: " + apiId, 400);
|
||||
}
|
||||
try {
|
||||
if (restApi) {
|
||||
getStage(region, apiId, stageName);
|
||||
} else {
|
||||
apiGatewayV2Service.getStage(region, apiId, stageName);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
throw new AwsException("BadRequestException", "Invalid stage identifier specified", 400);
|
||||
}
|
||||
return new MappingTarget(apiId, stageName, restApi ? REST_API_TYPE : apiType);
|
||||
}
|
||||
|
||||
private String v2ApiType(String region, String apiId) {
|
||||
try {
|
||||
return apiGatewayV2Service.getApi(region, apiId).getProtocolType();
|
||||
} catch (AwsException notAV2Api) {
|
||||
LOG.debugv("{0} is not an HTTP or WebSocket API in {1}: {2}", apiId, region, notAV2Api.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean restApiExists(String region, String apiId) {
|
||||
try {
|
||||
getRestApi(region, apiId);
|
||||
return true;
|
||||
} catch (AwsException notARestApi) {
|
||||
LOG.debugv("{0} is not a REST API in {1}: {2}", apiId, region, notARestApi.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses an API mapping key that API Gateway refuses, with its messages (measured, eu-west-1,
|
||||
* 2026-10-04). No key or an empty one is the root mapping, and so is a key of whitespace only
|
||||
* on a create; an update refuses that one.
|
||||
*/
|
||||
private static void requireValidApiMappingKey(String apiMappingKey, boolean update) {
|
||||
if (apiMappingKey == null || apiMappingKey.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (apiMappingKey.isBlank()) {
|
||||
if (update) {
|
||||
throw new AwsException("BadRequestException", MAPPING_KEY_SLASHES_MESSAGE, 400);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (apiMappingKey.length() > MAX_API_MAPPING_KEY_LENGTH) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"ApiMapping key length must be under " + MAX_API_MAPPING_KEY_LENGTH + " characters.", 400);
|
||||
}
|
||||
if (apiMappingKey.endsWith("/")) {
|
||||
throw new AwsException("BadRequestException", "API mapping key should not end with a '/'.", 400);
|
||||
}
|
||||
if (apiMappingKey.startsWith("/") || apiMappingKey.contains("//")) {
|
||||
throw new AwsException("BadRequestException", MAPPING_KEY_SLASHES_MESSAGE, 400);
|
||||
}
|
||||
if (!API_MAPPING_KEY.matcher(apiMappingKey).matches()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"An API mapping key may contain only letters, numbers and one of $-_.+!*'(), characters.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The restrictions AWS puts on an API mapping's domain: only a regional domain is reachable
|
||||
* through the v2 API, and an HTTP API or a key with more than one level needs a domain on the
|
||||
* TLS 1.2 security policy.
|
||||
*/
|
||||
private static void requireMappingAllowed(CustomDomain domain, String basePath, String apiType) {
|
||||
requireRegionalDomain(domain);
|
||||
boolean root = "(none)".equals(basePath);
|
||||
if (!TLS_1_2.equals(securityPolicyOf(domain))) {
|
||||
if ("HTTP".equals(apiType)) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"HTTP APIs can only be mapped to a regional custom domain name with the TLS 1.2 security policy",
|
||||
400);
|
||||
}
|
||||
if (!root && basePath.contains("/")) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"API mappings with multiple levels require a regional custom domain name with the TLS 1.2 "
|
||||
+ "security policy", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireRegionalDomain(CustomDomain domain) {
|
||||
if ("EDGE".equals(domain.getEndpointConfigurationType())) {
|
||||
throw new AwsException("BadRequestException", V2_EDGE_DOMAIN_MESSAGE, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A domain whose mappings need TLS 1.2, an HTTP API or a key with more than one level, cannot be
|
||||
* moved to another security policy: the mappings AWS accepted would no longer be allowed on it.
|
||||
*/
|
||||
private void requireMappingsAllowSecurityPolicy(String region, String domainName, String securityPolicy) {
|
||||
if (TLS_1_2.equals(securityPolicy == null ? TLS_1_2 : securityPolicy)) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<String, BasePathMapping> entry : basePathMappingsByStoredPath(region, domainName).entrySet()) {
|
||||
String basePath = canonicalBasePath(entry.getKey());
|
||||
if ("HTTP".equals(entry.getValue().getApiType())
|
||||
|| (!"(none)".equals(basePath) && basePath.contains("/"))) {
|
||||
throw new AwsException("BadRequestException", "Custom domain name " + domainName
|
||||
+ " has HTTP API mappings or API mappings with multiple levels, which require the TLS 1.2 "
|
||||
+ "security policy", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS keeps WebSocket APIs off a custom domain name that an HTTP or REST API is mapped to, and the
|
||||
* other way round. {@code ignoredStoredPath} is the mapping being changed, if any. A record
|
||||
* persisted before mappings remembered their API type is not held against either.
|
||||
*/
|
||||
private void requireProtocolTypesCompatible(String region, String domainName, String apiType,
|
||||
String ignoredStoredPath) {
|
||||
boolean webSocket = "WEBSOCKET".equals(apiType);
|
||||
for (Map.Entry<String, BasePathMapping> entry : basePathMappingsByStoredPath(region, domainName).entrySet()) {
|
||||
String otherType = entry.getValue().getApiType();
|
||||
if (otherType == null || entry.getKey().equals(ignoredStoredPath)) {
|
||||
continue;
|
||||
}
|
||||
if (webSocket != "WEBSOCKET".equals(otherType)) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"WebSocket APIs can't be mapped to the same custom domain name as an HTTP API or REST API",
|
||||
400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String securityPolicyOf(CustomDomain domain) {
|
||||
return domain.getSecurityPolicy() == null ? TLS_1_2 : domain.getSecurityPolicy();
|
||||
}
|
||||
|
||||
/** Whichever spelling an earlier record was written under, "" and an omitted key are one key. */
|
||||
private void requireApiMappingKeyFree(String region, String domainName, String basePath) {
|
||||
boolean keyTaken = basePathMappingsByStoredPath(region, domainName).keySet().stream()
|
||||
.anyMatch(existing -> canonicalBasePath(existing).equals(basePath));
|
||||
if (keyTaken) {
|
||||
throw new AwsException("ConflictException",
|
||||
"ApiMapping key already exists for this domain name", 409);
|
||||
}
|
||||
}
|
||||
|
||||
public StoredMapping getApiMapping(String region, String domainName, String apiMappingId) {
|
||||
requireRegionalDomain(getDomainName(region, domainName));
|
||||
return basePathMappingsByStoredPath(region, domainName).entrySet().stream()
|
||||
.map(entry -> new StoredMapping(entry.getKey(), entry.getValue()))
|
||||
.filter(stored -> stored.apiMappingId().equals(apiMappingId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"Unable to find ApiMapping with ID " + apiMappingId, 404));
|
||||
}
|
||||
|
||||
/**
|
||||
* The id a new mapping on {@code basePath} is given: the one derived from the path, so a mapping
|
||||
* gets the id it always had, unless a mapping whose key changed since it was created still holds
|
||||
* it, or the caller excludes it. Then a numbered variant, so no two mappings on a domain share one.
|
||||
*/
|
||||
private String unusedApiMappingId(String region, String domainName, String basePath, Set<String> excludedIds) {
|
||||
Set<String> taken = new HashSet<>(excludedIds);
|
||||
basePathMappingsByStoredPath(region, domainName)
|
||||
.forEach((storedPath, mapping) -> taken.add(new StoredMapping(storedPath, mapping).apiMappingId()));
|
||||
String derived = apiMappingId(basePath);
|
||||
String id = derived;
|
||||
for (int n = 2; taken.contains(id); n++) {
|
||||
id = derived + "-" + n;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
public void deleteApiMapping(String region, String domainName, String apiMappingId) {
|
||||
// Deleted by the path the selected record is stored under, so the record that answered the
|
||||
// lookup is the record that goes.
|
||||
StoredMapping found = getApiMapping(region, domainName, apiMappingId);
|
||||
deleteBasePathMappingRecord(region, domainName, found.storedPath());
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives a mapping id from the path the mapping is stored under. A new mapping is given this id
|
||||
* and stores it, so the id outlives a later change of key; a record persisted before ids were
|
||||
* stored is still read under 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.
|
||||
*/
|
||||
public 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));
|
||||
}
|
||||
|
||||
/** The certificate a v2 domain configuration reports, see {@link #v2CertificateIsRegional}. */
|
||||
public static String v2CertificateArn(CustomDomain domain) {
|
||||
return v2CertificateIsRegional(domain) ? domain.getRegionalCertificateArn() : domain.getCertificateArn();
|
||||
}
|
||||
|
||||
/** The certificate name a v2 domain configuration reports, see {@link #v2CertificateIsRegional}. */
|
||||
public static String v2CertificateName(CustomDomain domain) {
|
||||
return v2CertificateIsRegional(domain) ? domain.getRegionalCertificateName() : domain.getCertificateName();
|
||||
}
|
||||
|
||||
/**
|
||||
* The v1 model keeps an edge-optimized domain's certificate apart from a regional one's, and the
|
||||
* v2 API reports whichever the domain uses. A regional domain the v2 API wrote before its
|
||||
* certificate went to the regional fields still holds it in the edge-optimized ones, so those
|
||||
* answer while the regional ones are empty.
|
||||
*/
|
||||
private static boolean v2CertificateIsRegional(CustomDomain domain) {
|
||||
return !"EDGE".equals(domain.getEndpointConfigurationType())
|
||||
&& (domain.getRegionalCertificateArn() != null || domain.getRegionalCertificateName() != null);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Custom Domain Resolution ────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
+8
@@ -10,6 +10,11 @@ public class BasePathMapping {
|
||||
private String restApiId;
|
||||
private String stage;
|
||||
private String apiType;
|
||||
/**
|
||||
* The v2 {@code apiMappingId}, given when the mapping is created and kept when its key changes.
|
||||
* Null on a record persisted before ids were stored, whose id is derived from its stored path.
|
||||
*/
|
||||
private String apiMappingId;
|
||||
|
||||
public BasePathMapping() {
|
||||
this.basePath = "(none)";
|
||||
@@ -32,4 +37,7 @@ public class BasePathMapping {
|
||||
|
||||
public String getApiType() { return apiType; }
|
||||
public void setApiType(String apiType) { this.apiType = apiType; }
|
||||
|
||||
public String getApiMappingId() { return apiMappingId; }
|
||||
public void setApiMappingId(String apiMappingId) { this.apiMappingId = apiMappingId; }
|
||||
}
|
||||
+22
-5
@@ -149,8 +149,9 @@ public class CloudControlService {
|
||||
String identifier = created.entrySet().stream()
|
||||
.filter(resource -> resource.getValue() == recovered)
|
||||
.map(Map.Entry::getKey)
|
||||
.map(key -> key.substring((accountId + "|").length()))
|
||||
.map(key -> key.substring(key.lastIndexOf('|') + 1))
|
||||
// account|region|type|identifier: the identifier is everything after the
|
||||
// third separator, since a compound one holds separators of its own.
|
||||
.map(key -> key.split("\\|", 4)[3])
|
||||
.findFirst().orElse(normalized.identifier());
|
||||
normalized = new ProgressEvent(normalized.typeName(), identifier, normalized.requestToken(),
|
||||
normalized.operation(), "SUCCESS", null, recovered.model(), accountId);
|
||||
@@ -321,12 +322,13 @@ public class CloudControlService {
|
||||
if (resource == null || resource.getPhysicalId() == null) {
|
||||
recordCreateFailure(pending, "CreateResource is not supported for " + typeName + ".");
|
||||
} else {
|
||||
String identifier = identifierOf(typeName, resource.getPhysicalId(), props);
|
||||
String model = resourceModel(region, typeName, resource.getPhysicalId(), props);
|
||||
CreatedResource createdResource = new CreatedResource(token, accountId,
|
||||
resource.getAttributes() == null ? Map.of() : Map.copyOf(resource.getAttributes()), model);
|
||||
created.put(createdKey(accountId, region, typeName, resource.getPhysicalId()), createdResource);
|
||||
persistCreated(accountId, region, typeName, resource.getPhysicalId(), createdResource);
|
||||
record(new ProgressEvent(typeName, resource.getPhysicalId(),
|
||||
created.put(createdKey(accountId, region, typeName, identifier), createdResource);
|
||||
persistCreated(accountId, region, typeName, identifier, createdResource);
|
||||
record(new ProgressEvent(typeName, identifier,
|
||||
token, "CREATE", "SUCCESS", null, model, accountId));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -454,6 +456,20 @@ public class CloudControlService {
|
||||
return propertiesString(model);
|
||||
}
|
||||
|
||||
/**
|
||||
* The identifier Cloud Control hands out for a created resource: the type's primary identifier,
|
||||
* which for most types is the physical id. A compound one joins its parts with {@code |}, as
|
||||
* Cloud Control does; an {@code AWS::ApiGatewayV2::ApiMapping} is {@code <ApiMappingId>|<DomainName>},
|
||||
* where CloudFormation's {@code Ref} is the bare id.
|
||||
*/
|
||||
private static String identifierOf(String typeName, String physicalId, JsonNode desiredState) {
|
||||
if ("AWS::ApiGatewayV2::ApiMapping".equals(typeName) && desiredState != null
|
||||
&& desiredState.path("DomainName").isTextual()) {
|
||||
return physicalId + "|" + desiredState.path("DomainName").asText();
|
||||
}
|
||||
return physicalId;
|
||||
}
|
||||
|
||||
/** The read-only primary identifier property name for the common EC2/IAM types. */
|
||||
private static String primaryIdentifierField(String typeName) {
|
||||
return switch (typeName) {
|
||||
@@ -464,6 +480,7 @@ public class CloudControlService {
|
||||
case "AWS::EC2::InternetGateway" -> "InternetGatewayId";
|
||||
case "AWS::EC2::RouteTable" -> "RouteTableId";
|
||||
case "AWS::EC2::LaunchTemplate" -> "LaunchTemplateId";
|
||||
case "AWS::ApiGatewayV2::ApiMapping" -> "ApiMappingId";
|
||||
default -> "Id";
|
||||
};
|
||||
}
|
||||
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
|
||||
@@ -103,7 +102,7 @@ public class ApiGatewayDomainCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
r.setPhysicalId(domainName);
|
||||
r.getAttributes().put("DomainNameArn",
|
||||
AwsArnUtils.Arn.of("apigateway", ctx.region(), "", "/domainnames/" + domainName).toString());
|
||||
ApiGatewayService.domainNameArn(ctx.region(), domainName));
|
||||
r.getAttributes().put("RegionalDomainName", orEmpty(provisioned.getRegionalDomainName()));
|
||||
r.getAttributes().put("RegionalHostedZoneId", orEmpty(provisioned.getRegionalHostedZoneId()));
|
||||
r.getAttributes().put("DistributionDomainName", orEmpty(provisioned.getDistributionDomainName()));
|
||||
|
||||
+506
@@ -0,0 +1,506 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::ApiGatewayV2::DomainName} and {@code AWS::ApiGatewayV2::ApiMapping}.
|
||||
*
|
||||
* <p>A custom domain is one resource in AWS, reachable through both APIs, so these write the same
|
||||
* domain and base path mapping records as {@link ApiGatewayDomainCfnProvisioner}, through the rules
|
||||
* the v2 API applies. A domain's physical id is its name and a mapping's is its {@code ApiMappingId},
|
||||
* as in AWS. {@code DomainName} is the only createOnly property of either type: a new one replaces
|
||||
* the resource, everything else is updated in place, and a mapping keeps its id when its key changes.
|
||||
*
|
||||
* <p>A replacement creates the new entity and leaves the displaced one to {@link ReplacementCleanup},
|
||||
* which deletes it once the stack update commits, keeps it under {@code UpdateReplacePolicy: Retain},
|
||||
* and puts it back when a later resource fails the update. An in-place update snapshots what it
|
||||
* changes first, so a failed update can restore it.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ApiGatewayV2DomainCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ApiGatewayV2DomainCfnProvisioner.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String DOMAIN_NAME_TYPE = "AWS::ApiGatewayV2::DomainName";
|
||||
private static final String API_MAPPING_TYPE = "AWS::ApiGatewayV2::ApiMapping";
|
||||
private static final String NOT_FOUND = "NotFoundException";
|
||||
/** The domain a mapping belongs to: its delete needs it, and its physical id does not carry it. */
|
||||
private static final String MAPPING_DOMAIN_NAME_ATTR = "__FlociApiMappingDomainName";
|
||||
/**
|
||||
* The domain of each mapping this resource displaced and may still owe a delete, by id. A mapping
|
||||
* id is unique only within its domain, so the cleanup and the rollback need both.
|
||||
*/
|
||||
private static final String MAPPING_DISPLACED_DOMAINS_ATTR = "__FlociApiMappingDisplacedDomains";
|
||||
/** {@code <ApiMappingId>|<DomainName>}, the type's primary identifier, which Cloud Control names a mapping by. */
|
||||
private static final String IDENTIFIER_SEPARATOR = "|";
|
||||
|
||||
private final ApiGatewayService apiGatewayService;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayV2DomainCfnProvisioner(ApiGatewayService apiGatewayService) {
|
||||
this.apiGatewayService = apiGatewayService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(DOMAIN_NAME_TYPE, API_MAPPING_TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
switch (r.getResourceType()) {
|
||||
case DOMAIN_NAME_TYPE -> provisionDomainName(r, props, ctx);
|
||||
case API_MAPPING_TYPE -> provisionApiMapping(r, props, ctx);
|
||||
default -> throw new IllegalStateException(
|
||||
"ApiGatewayV2DomainCfnProvisioner cannot handle " + r.getResourceType());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
switch (resourceType) {
|
||||
case DOMAIN_NAME_TYPE -> deleteDomain(physicalId, region);
|
||||
case API_MAPPING_TYPE -> deleteMappingByIdentifier(physicalId, region);
|
||||
default -> throw new IllegalStateException(
|
||||
"ApiGatewayV2DomainCfnProvisioner cannot handle " + resourceType);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
String physicalId = resource.getPhysicalId();
|
||||
if (API_MAPPING_TYPE.equals(resource.getResourceType()) && physicalId != null
|
||||
&& physicalId.contains(IDENTIFIER_SEPARATOR)) {
|
||||
// What Cloud Control created, keyed by the primary identifier, <ApiMappingId>|<DomainName>.
|
||||
deleteMappingByIdentifier(physicalId, region);
|
||||
return;
|
||||
}
|
||||
if (API_MAPPING_TYPE.equals(resource.getResourceType()) && resource.getAttributes() != null) {
|
||||
String domainName = resource.getAttributes().get(MAPPING_DOMAIN_NAME_ATTR);
|
||||
if (!isBlank(domainName)) {
|
||||
deleteMapping(domainName, resource.getPhysicalId(), region);
|
||||
return;
|
||||
}
|
||||
}
|
||||
delete(resource.getResourceType(), resource.getPhysicalId(), region);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
// The update committed, so what an in-place change snapshotted for a rollback is spent.
|
||||
resource.getAttributes().remove(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR);
|
||||
resource.getAttributes().remove(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR);
|
||||
if (DOMAIN_NAME_TYPE.equals(resource.getResourceType())) {
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
UpdateCleanupResult result = ReplacementCleanup.complete(resource, mappingDeleter(resource));
|
||||
forgetDisplacedDomainsOnceNothingIsOwed(resource);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR);
|
||||
resource.getAttributes().remove(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
forgetDisplacedDomainsOnceNothingIsOwed(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
return switch (resource.getResourceType()) {
|
||||
case DOMAIN_NAME_TYPE -> rollbackDomainUpdate(resource);
|
||||
case API_MAPPING_TYPE -> rollbackMappingUpdate(resource);
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
// ──────────────────────────── DomainName ────────────────────────────
|
||||
|
||||
private void provisionDomainName(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
String domainName = ctx.resolveOptional(props, "DomainName");
|
||||
if (isBlank(domainName)) {
|
||||
throw new IllegalArgumentException("AWS::ApiGatewayV2::DomainName requires DomainName");
|
||||
}
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
Map<String, Object> request = domainRequest(domainName, props, tags, ctx);
|
||||
|
||||
CustomDomain existing = ctx.isUpdate() ? findDomain(ctx.priorPhysicalId(), ctx.region()) : null;
|
||||
CustomDomain provisioned;
|
||||
if (existing != null && ctx.reusesPriorEntity(domainName)) {
|
||||
// Snapshotted before the first change, so a later resource failing the update can put the
|
||||
// domain back. The service validates before it writes, so a template the API would refuse
|
||||
// changes nothing.
|
||||
r.getAttributes().put(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR,
|
||||
domainSnapshot(existing, ctx.region()));
|
||||
provisioned = apiGatewayService.replaceV2DomainConfiguration(ctx.region(), domainName, request);
|
||||
reconcileTags(provisioned, tags, ctx.region());
|
||||
} else {
|
||||
r.getAttributes().remove(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR);
|
||||
provisioned = apiGatewayService.createV2DomainName(ctx.region(), request);
|
||||
}
|
||||
r.setPhysicalId(domainName);
|
||||
r.getAttributes().put("DomainNameArn",
|
||||
ApiGatewayService.domainNameArn(ctx.region(), domainName));
|
||||
r.getAttributes().put("RegionalDomainName", orEmpty(provisioned.getRegionalDomainName()));
|
||||
r.getAttributes().put("RegionalHostedZoneId", orEmpty(provisioned.getRegionalHostedZoneId()));
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
/** The template's domain in the shape of a v2 {@code CreateDomainName} body. */
|
||||
private static Map<String, Object> domainRequest(String domainName, JsonNode props, Map<String, String> tags,
|
||||
ProvisionContext ctx) {
|
||||
Map<String, Object> request = new LinkedHashMap<>();
|
||||
request.put("domainName", domainName);
|
||||
JsonNode configurations = props.hasNonNull("DomainNameConfigurations")
|
||||
? ctx.engine().resolveNode(props.get("DomainNameConfigurations"))
|
||||
: null;
|
||||
if (configurations != null && configurations.isArray()) {
|
||||
List<Map<String, Object>> resolved = new ArrayList<>();
|
||||
for (JsonNode configuration : configurations) {
|
||||
Map<String, Object> entry = new LinkedHashMap<>();
|
||||
putIfPresent(entry, "certificateArn", ctx.resolveOptional(configuration, "CertificateArn"));
|
||||
putIfPresent(entry, "certificateName", ctx.resolveOptional(configuration, "CertificateName"));
|
||||
putIfPresent(entry, "endpointType", ctx.resolveOptional(configuration, "EndpointType"));
|
||||
putIfPresent(entry, "securityPolicy", ctx.resolveOptional(configuration, "SecurityPolicy"));
|
||||
putIfPresent(entry, "ipAddressType", ctx.resolveOptional(configuration, "IpAddressType"));
|
||||
putIfPresent(entry, "ownershipVerificationCertificateArn",
|
||||
ctx.resolveOptional(configuration, "OwnershipVerificationCertificateArn"));
|
||||
resolved.add(entry);
|
||||
}
|
||||
request.put("domainNameConfigurations", resolved);
|
||||
}
|
||||
JsonNode mutualTls = props.hasNonNull("MutualTlsAuthentication")
|
||||
? ctx.engine().resolveNode(props.get("MutualTlsAuthentication"))
|
||||
: null;
|
||||
if (mutualTls != null && mutualTls.isObject()) {
|
||||
Map<String, Object> truststore = new LinkedHashMap<>();
|
||||
putIfPresent(truststore, "truststoreUri", ctx.resolveOptional(mutualTls, "TruststoreUri"));
|
||||
putIfPresent(truststore, "truststoreVersion", ctx.resolveOptional(mutualTls, "TruststoreVersion"));
|
||||
if (!truststore.isEmpty()) {
|
||||
request.put("mutualTlsAuthentication", truststore);
|
||||
}
|
||||
}
|
||||
putIfPresent(request, "routingMode", ctx.resolveOptional(props, "RoutingMode"));
|
||||
if (!tags.isEmpty()) {
|
||||
request.put("tags", tags);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private static String domainSnapshot(CustomDomain domain, String region) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode();
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("domainName", domain.getDomainName());
|
||||
snapshot.put("certificateArn", ApiGatewayService.v2CertificateArn(domain));
|
||||
snapshot.put("certificateName", ApiGatewayService.v2CertificateName(domain));
|
||||
snapshot.put("endpointType", domain.getEndpointConfigurationType());
|
||||
snapshot.put("securityPolicy", domain.getSecurityPolicy());
|
||||
ObjectNode tags = snapshot.putObject("tags");
|
||||
if (domain.getTags() != null) {
|
||||
domain.getTags().forEach(tags::put);
|
||||
}
|
||||
return snapshot.toString();
|
||||
}
|
||||
|
||||
private boolean rollbackDomainUpdate(StackResource resource) {
|
||||
if (ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
return true;
|
||||
}
|
||||
String rawSnapshot = resource.getAttributes().remove(CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR);
|
||||
JsonNode snapshot = rawSnapshot == null ? null : readSnapshot(resource, rawSnapshot);
|
||||
if (snapshot == null) {
|
||||
return false;
|
||||
}
|
||||
String region = snapshot.path("region").asText();
|
||||
String domainName = snapshot.path("domainName").asText();
|
||||
Map<String, Object> configuration = new LinkedHashMap<>();
|
||||
putIfPresent(configuration, "certificateArn", snapshot.path("certificateArn").asText(null));
|
||||
putIfPresent(configuration, "certificateName", snapshot.path("certificateName").asText(null));
|
||||
putIfPresent(configuration, "endpointType", snapshot.path("endpointType").asText(null));
|
||||
putIfPresent(configuration, "securityPolicy", snapshot.path("securityPolicy").asText(null));
|
||||
Map<String, Object> request = new LinkedHashMap<>();
|
||||
request.put("domainName", domainName);
|
||||
request.put("domainNameConfigurations", List.of(configuration));
|
||||
CustomDomain restored = apiGatewayService.replaceV2DomainConfiguration(region, domainName, request);
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
snapshot.path("tags").fields().forEachRemaining(tag -> tags.put(tag.getKey(), tag.getValue().asText()));
|
||||
reconcileTags(restored, tags, region);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Drives the domain's tags to the template's: a dropped key is untagged, an unchanged set is left alone. */
|
||||
private void reconcileTags(CustomDomain existing, Map<String, String> desired, String region) {
|
||||
Map<String, String> current = existing.getTags() == null ? Map.of() : existing.getTags();
|
||||
if (desired.equals(current)) {
|
||||
return;
|
||||
}
|
||||
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
|
||||
if (!stale.isEmpty()) {
|
||||
apiGatewayService.untagDomainName(region, existing.getDomainName(), stale);
|
||||
}
|
||||
if (!desired.isEmpty()) {
|
||||
apiGatewayService.tagDomainName(region, existing.getDomainName(), desired);
|
||||
}
|
||||
}
|
||||
|
||||
private CustomDomain findDomain(String domainName, String region) {
|
||||
try {
|
||||
return apiGatewayService.getDomainName(region, domainName);
|
||||
} catch (AwsException e) {
|
||||
if (!NOT_FOUND.equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("Custom domain {0} from the previous execution is gone, creating it again", domainName);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteDomain(String domainName, String region) {
|
||||
CfnDeletes.safeDelete("custom domain", domainName,
|
||||
() -> apiGatewayService.deleteDomainName(region, domainName), NOT_FOUND);
|
||||
}
|
||||
|
||||
// ──────────────────────────── ApiMapping ────────────────────────────
|
||||
|
||||
private void provisionApiMapping(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
String domainName = ctx.resolveOptional(props, "DomainName");
|
||||
String apiId = ctx.resolveOptional(props, "ApiId");
|
||||
String stage = ctx.resolveOptional(props, "Stage");
|
||||
if (isBlank(domainName) || isBlank(apiId) || isBlank(stage)) {
|
||||
throw new IllegalArgumentException(
|
||||
"AWS::ApiGatewayV2::ApiMapping requires DomainName, ApiId and Stage");
|
||||
}
|
||||
String apiMappingKey = ctx.resolveOptional(props, "ApiMappingKey");
|
||||
|
||||
String priorDomainName = r.getAttributes().get(MAPPING_DOMAIN_NAME_ATTR);
|
||||
StoredMapping existing = ctx.isUpdate() && domainName.equals(priorDomainName)
|
||||
? findMapping(priorDomainName, ctx.priorPhysicalId(), ctx.region())
|
||||
: null;
|
||||
StoredMapping provisioned;
|
||||
if (existing != null) {
|
||||
// ApiId, Stage and ApiMappingKey update in place, and the mapping keeps its id. The
|
||||
// snapshot comes first, so a later resource failing the update can put the mapping back.
|
||||
r.getAttributes().put(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR,
|
||||
mappingSnapshot(existing, domainName, ctx.region()));
|
||||
provisioned = apiGatewayService.updateApiMapping(ctx.region(), domainName, existing.apiMappingId(),
|
||||
apiMappingKey, apiId, stage);
|
||||
} else {
|
||||
r.getAttributes().remove(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR);
|
||||
Set<String> excludedIds = Set.of();
|
||||
if (ctx.isUpdate() && isBlank(priorDomainName)) {
|
||||
// The stub arm's record from before this provisioner existed: nothing was created for
|
||||
// it, so the cleanup and the rollback have no domain to delete it from.
|
||||
rememberDisplacedDomain(r, ctx.priorPhysicalId(), "");
|
||||
} else if (ctx.isUpdate() && !domainName.equals(priorDomainName)) {
|
||||
// A new DomainName replaces the mapping. On AWS the replacement gets an id of its own;
|
||||
// here it would derive the displaced mapping's id when the key is the same, and two
|
||||
// mappings under one physical id cannot be told apart by the cleanup or the rollback.
|
||||
excludedIds = Set.of(ctx.priorPhysicalId());
|
||||
rememberDisplacedDomain(r, ctx.priorPhysicalId(), priorDomainName);
|
||||
}
|
||||
provisioned = apiGatewayService.createApiMapping(ctx.region(), domainName, apiMappingKey, apiId, stage,
|
||||
excludedIds);
|
||||
}
|
||||
String apiMappingId = provisioned.apiMappingId();
|
||||
r.setPhysicalId(apiMappingId);
|
||||
r.getAttributes().put("ApiMappingId", apiMappingId);
|
||||
r.getAttributes().put(MAPPING_DOMAIN_NAME_ATTR, domainName);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
forgetDisplacedDomainsOnceNothingIsOwed(r);
|
||||
}
|
||||
|
||||
private static String mappingSnapshot(StoredMapping existing, String domainName, String region) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode();
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("domainName", domainName);
|
||||
snapshot.put("apiMappingId", existing.apiMappingId());
|
||||
String key = ApiGatewayService.canonicalBasePath(existing.storedPath());
|
||||
snapshot.put("apiMappingKey", "(none)".equals(key) ? null : key);
|
||||
snapshot.put("apiId", existing.mapping().getRestApiId());
|
||||
snapshot.put("stage", existing.mapping().getStage());
|
||||
return snapshot.toString();
|
||||
}
|
||||
|
||||
private boolean rollbackMappingUpdate(StackResource resource) {
|
||||
// Rolling back a replacement deletes it through the domain it was created on, and one whose
|
||||
// delete fails stays owed, so its domain is recorded before the attempt.
|
||||
String replacement = resource.getPhysicalId();
|
||||
String replacementDomain = resource.getAttributes().get(MAPPING_DOMAIN_NAME_ATTR);
|
||||
boolean replacementAlreadyKnown = displacedDomains(resource).containsKey(replacement);
|
||||
if (!replacementAlreadyKnown && !isBlank(replacementDomain)) {
|
||||
rememberDisplacedDomain(resource, replacement, replacementDomain);
|
||||
}
|
||||
boolean rolledBack;
|
||||
try {
|
||||
rolledBack = ReplacementCleanup.rollback(resource, mappingDeleter(resource));
|
||||
} finally {
|
||||
// The prior mapping stands again even when deleting the replacement failed, so the
|
||||
// resource names the prior mapping's domain from here on.
|
||||
Map<String, String> domains = displacedDomains(resource);
|
||||
if (!replacement.equals(resource.getPhysicalId()) && domains.containsKey(resource.getPhysicalId())) {
|
||||
String priorDomain = domains.remove(resource.getPhysicalId());
|
||||
if (isBlank(priorDomain)) {
|
||||
resource.getAttributes().remove(MAPPING_DOMAIN_NAME_ATTR);
|
||||
} else {
|
||||
resource.getAttributes().put(MAPPING_DOMAIN_NAME_ATTR, priorDomain);
|
||||
}
|
||||
writeDisplacedDomains(resource, domains);
|
||||
}
|
||||
}
|
||||
if (rolledBack) {
|
||||
forgetDisplacedDomainsOnceNothingIsOwed(resource);
|
||||
return true;
|
||||
}
|
||||
if (!replacementAlreadyKnown) {
|
||||
Map<String, String> domains = displacedDomains(resource);
|
||||
domains.remove(replacement);
|
||||
writeDisplacedDomains(resource, domains);
|
||||
}
|
||||
String rawSnapshot = resource.getAttributes().remove(CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR);
|
||||
JsonNode snapshot = rawSnapshot == null ? null : readSnapshot(resource, rawSnapshot);
|
||||
if (snapshot == null) {
|
||||
return false;
|
||||
}
|
||||
apiGatewayService.updateApiMapping(snapshot.path("region").asText(), snapshot.path("domainName").asText(),
|
||||
snapshot.path("apiMappingId").asText(), snapshot.path("apiMappingKey").asText(null),
|
||||
snapshot.path("apiId").asText(), snapshot.path("stage").asText());
|
||||
return true;
|
||||
}
|
||||
|
||||
private StoredMapping findMapping(String domainName, String apiMappingId, String region) {
|
||||
try {
|
||||
return apiGatewayService.getApiMapping(region, domainName, apiMappingId);
|
||||
} catch (AwsException e) {
|
||||
if (!NOT_FOUND.equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("API mapping {0} on {1} from the previous execution is gone, creating it again",
|
||||
apiMappingId, domainName);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes a displaced or rolled-back mapping through the domain it was created on. */
|
||||
private ReplacementCleanup.Deleter mappingDeleter(StackResource resource) {
|
||||
return (type, apiMappingId, region) -> {
|
||||
String domainName = displacedDomains(resource).getOrDefault(apiMappingId,
|
||||
resource.getAttributes().get(MAPPING_DOMAIN_NAME_ATTR));
|
||||
if (isBlank(domainName)) {
|
||||
LOG.debugv("API mapping {0} has no domain, so nothing was created for it", apiMappingId);
|
||||
return;
|
||||
}
|
||||
deleteMapping(domainName, apiMappingId, region);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The id-only delete, which Cloud Control reaches with the type's primary identifier,
|
||||
* {@code <ApiMappingId>|<DomainName>}. A bare id names no domain to look in.
|
||||
*/
|
||||
private void deleteMappingByIdentifier(String identifier, String region) {
|
||||
int separator = identifier == null ? -1 : identifier.indexOf(IDENTIFIER_SEPARATOR);
|
||||
if (separator <= 0 || separator == identifier.length() - 1) {
|
||||
throw new AwsException(NOT_FOUND, "Unable to find ApiMapping with ID " + identifier, 404);
|
||||
}
|
||||
deleteMapping(identifier.substring(separator + 1), identifier.substring(0, separator), region);
|
||||
}
|
||||
|
||||
/** Tolerates a mapping already gone, including one removed together with its domain. */
|
||||
private void deleteMapping(String domainName, String apiMappingId, String region) {
|
||||
CfnDeletes.safeDelete("API mapping", apiMappingId,
|
||||
() -> apiGatewayService.deleteApiMapping(region, domainName, apiMappingId), NOT_FOUND);
|
||||
}
|
||||
|
||||
private static void rememberDisplacedDomain(StackResource resource, String apiMappingId, String domainName) {
|
||||
Map<String, String> domains = displacedDomains(resource);
|
||||
domains.put(apiMappingId, domainName);
|
||||
writeDisplacedDomains(resource, domains);
|
||||
}
|
||||
|
||||
private static void forgetDisplacedDomainsOnceNothingIsOwed(StackResource resource) {
|
||||
if (!ReplacementCleanup.hasReplacement(resource)) {
|
||||
resource.getAttributes().remove(MAPPING_DISPLACED_DOMAINS_ATTR);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> displacedDomains(StackResource resource) {
|
||||
Map<String, String> domains = new LinkedHashMap<>();
|
||||
String raw = resource.getAttributes().get(MAPPING_DISPLACED_DOMAINS_ATTR);
|
||||
if (isBlank(raw)) {
|
||||
return domains;
|
||||
}
|
||||
try {
|
||||
MAPPER.readTree(raw).fields().forEachRemaining(e -> domains.put(e.getKey(), e.getValue().asText()));
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.warnv("Unreadable displaced API mapping domains on {0}, dropping them: {1}",
|
||||
resource.getLogicalId(), e.getMessage());
|
||||
}
|
||||
return domains;
|
||||
}
|
||||
|
||||
private static void writeDisplacedDomains(StackResource resource, Map<String, String> domains) {
|
||||
if (domains.isEmpty()) {
|
||||
resource.getAttributes().remove(MAPPING_DISPLACED_DOMAINS_ATTR);
|
||||
return;
|
||||
}
|
||||
ObjectNode node = MAPPER.createObjectNode();
|
||||
domains.forEach(node::put);
|
||||
resource.getAttributes().put(MAPPING_DISPLACED_DOMAINS_ATTR, node.toString());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Shared ────────────────────────────
|
||||
|
||||
private static JsonNode readSnapshot(StackResource resource, String rawSnapshot) {
|
||||
try {
|
||||
return MAPPER.readTree(rawSnapshot);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.errorv("Could not parse the update snapshot of {0}: {1}", resource.getLogicalId(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void putIfPresent(Map<String, Object> request, String key, String value) {
|
||||
if (value != null) {
|
||||
request.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
|
||||
private static String orEmpty(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
}
|
||||
+16
@@ -134,6 +134,22 @@ public final class CfnRollback {
|
||||
*/
|
||||
public static final String INTEGRATION_CONNECTION_SNAPSHOT_ATTR = "__FlociIntegrationConnectionSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the certificate, security policy, endpoint type and tags an API Gateway v2 custom domain
|
||||
* carried before an in-place update changed them, so a failed stack update can put them back.
|
||||
* Written by {@code ApiGatewayV2DomainCfnProvisioner} before its first mutating call and spent
|
||||
* by its {@code rollbackUpdate}.
|
||||
*/
|
||||
public static final String API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR = "__FlociApiGatewayV2DomainUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the key, API and stage an API Gateway v2 API mapping carried before an in-place update
|
||||
* changed them, with the domain that addresses it, so a failed stack update can put them back.
|
||||
* Written by {@code ApiGatewayV2DomainCfnProvisioner} before its update call and spent by its
|
||||
* {@code rollbackUpdate}.
|
||||
*/
|
||||
public static final String API_MAPPING_UPDATE_SNAPSHOT_ATTR = "__FlociApiMappingUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the complete prior metric filter, identity, name mode and per-address mutation outcomes
|
||||
* and ownership states.
|
||||
|
||||
Reference in new issue
Block a user