mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(apigateway): provision AWS::ApiGateway::DomainName and BasePathMapping (#3040)
* feat(apigateway): provision AWS::ApiGateway::DomainName and BasePathMapping Both types were stubs: the stack turned green while no domain or mapping existed, Fn::GetAtt on the domain resolved to the literal attribute name, and a request sent to the custom domain was not routed. The new provisioner calls the existing CreateDomainName and CreateBasePathMapping. Ref and every Fn::GetAtt attribute return what GetDomainName reports, a changed DomainName or BasePath replaces the resource (created before the prior one is deleted), and everything else is patched in place. The physical id of a mapping is the compound identifier CloudFormation uses for the type, <DomainName>|<BasePath>, with (none) for an empty base path. Service fixes needed so the provisioned values can be read back through the API: CreateDomainName keeps regionalCertificateArn and regionalCertificateName (both were dropped), an EDGE domain gets a distributionDomainName and the fixed CloudFront hosted zone, GetDomainName returns domainNameArn, endpointConfiguration.types and tags, UpdateDomainName accepts the /endpointConfiguration/types/EDGE patch path, domain tags are managed through the tag API on the domain ARN, and CreateDomainName checks the name and stores the domain under one lock so two concurrent creates cannot both succeed. * fix(apigateway): keep the distribution in step with a domain's endpoint type A move to EDGE through UpdateDomainName left the domain without a distributionDomainName, and a move back to REGIONAL kept the old one, so GetDomainName and Fn::GetAtt reported CloudFront fields that did not match the endpoint type. Both create and update now go through one helper that puts a distribution in front of an EDGE domain and drops it for a REGIONAL one. * fix(apigateway): serialize domain and mapping changes, refuse a taken base path, validate the endpoint patch path The stores hand out live objects, so a domain patch, a tag write and a mapping patch were read-modify-write steps that concurrent calls could lose or corrupt: eight concurrent tag writes on one domain kept four tags. Every change to a custom domain or a base path mapping now runs under one lock, and a tag write replaces the tag map instead of changing the one a reader may be iterating. CreateBasePathMapping on a base path that already has a mapping answers ConflictException as AWS does; before, the new mapping silently replaced the old one, so eight concurrent creates of one base path all succeeded. UpdateDomainName accepted any /endpointConfiguration/types/<x> path; the path must now name the type the domain has, as on AWS. The provisioner sends the PATCH before it reconciles the tags, so a rejected update leaves the tags as they were. Tests cover every case above, the remaining cells of the update matrix (a prior resource gone under a new name), and the REGIONAL to EDGE move end to end through a stack. * fix(apigateway): refuse an endpoint type other than REGIONAL or EDGE on CreateDomainName UpdateDomainName already rejected any other value, but CreateDomainName stored whatever string the request carried, so a PRIVATE or misspelled type produced a domain that was neither regional nor edge-optimized and that nothing could route or describe. Private custom domains are not emulated, so the create now answers BadRequestException with the same message as the update, and nothing is stored. Adds the two remaining provisioner matrix cells as tests: a taken domain name fails the resource without deleting anything, and a resource without Properties is rejected.
This commit is contained in:
1 parent
b0a8dff206
commit
c3d977a3e3
12 files changed
+1716
-36
No files matched your search
+11
-5
@@ -995,7 +995,7 @@ public class ApiGatewayController {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
CustomDomain domain = service.createDomainName(region, request);
|
||||
return Response.status(201).entity(toDomainNode(domain).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.status(201).entity(toDomainNode(region, domain).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
@@ -1008,7 +1008,7 @@ public class ApiGatewayController {
|
||||
List<CustomDomain> domains = service.getDomainNames(region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
domains.forEach(d -> items.add(toDomainNode(d)));
|
||||
domains.forEach(d -> items.add(toDomainNode(region, d)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@@ -1016,7 +1016,7 @@ public class ApiGatewayController {
|
||||
@Path("/domainnames/{domainName}")
|
||||
public Response getDomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toDomainNode(service.getDomainName(region, domainName)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(toDomainNode(region, service.getDomainName(region, domainName)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@@ -1025,7 +1025,7 @@ public class ApiGatewayController {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<Map<String, String>> patchOperations = parsePatchOperations(body);
|
||||
CustomDomain domain = service.updateDomainName(region, domainName, patchOperations);
|
||||
return Response.ok(toDomainNode(domain).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(toDomainNode(region, domain).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@@ -2218,11 +2218,13 @@ public class ApiGatewayController {
|
||||
"Unable to find ApiMapping with ID " + apiMappingId, 404));
|
||||
}
|
||||
|
||||
private ObjectNode toDomainNode(CustomDomain d) {
|
||||
private ObjectNode toDomainNode(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("domainNameStatus", d.getDomainNameStatus());
|
||||
node.put("endpointConfigurationType", d.getEndpointConfigurationType());
|
||||
node.putObject("endpointConfiguration").putArray("types").add(d.getEndpointConfigurationType());
|
||||
if (d.getCertificateName() != null) node.put("certificateName", d.getCertificateName());
|
||||
if (d.getCertificateArn() != null) node.put("certificateArn", d.getCertificateArn());
|
||||
node.put("regionalDomainName", d.getRegionalDomainName());
|
||||
@@ -2242,6 +2244,10 @@ public class ApiGatewayController {
|
||||
if (d.getSecurityPolicy() != null) {
|
||||
node.put("securityPolicy", d.getSecurityPolicy());
|
||||
}
|
||||
if (d.getTags() != null && !d.getTags().isEmpty()) {
|
||||
ObjectNode tags = node.putObject("tags");
|
||||
d.getTags().forEach(tags::put);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
+126
-24
@@ -66,6 +66,13 @@ public class ApiGatewayService {
|
||||
private final StorageBackend<String, Account> accountStore;
|
||||
private final StorageBackend<String, CustomDomain> domainStore;
|
||||
private final StorageBackend<String, BasePathMapping> basePathMappingStore;
|
||||
/**
|
||||
* Guards every change to a custom domain or a base path mapping. The stores hand out live
|
||||
* objects, so a patch or a tag write is a read-modify-write; two of them on one domain at the
|
||||
* same time would drop one another's changes or corrupt the tag map. One lock for both kinds
|
||||
* also keeps a mapping from being created under a domain that is being deleted at that moment.
|
||||
*/
|
||||
private final Object domainNameLock = new Object();
|
||||
|
||||
// Constants
|
||||
private static final String EPC_KEY = "endpointConfiguration";
|
||||
@@ -1285,21 +1292,22 @@ public class ApiGatewayService {
|
||||
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);
|
||||
|
||||
// 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("BadRequestException",
|
||||
"The domain name you provided already exists.", 400);
|
||||
String endpointType = endpointTypeOf(request);
|
||||
if (!"REGIONAL".equals(endpointType) && !"EDGE".equals(endpointType)) {
|
||||
// Private custom domains are not emulated; anything else would be a domain that is
|
||||
// neither regional nor edge-optimized, which nothing here could route or describe.
|
||||
throw new AwsException("BadRequestException", "Invalid value for endpoint type: " + endpointType, 400);
|
||||
}
|
||||
|
||||
CustomDomain domain = new CustomDomain();
|
||||
domain.setDomainName(domainName);
|
||||
domain.setCertificateName((String) request.get("certificateName"));
|
||||
domain.setCertificateArn((String) request.get("certificateArn"));
|
||||
domain.setRegionalCertificateName((String) request.get("regionalCertificateName"));
|
||||
domain.setRegionalCertificateArn((String) request.get("regionalCertificateArn"));
|
||||
domain.setRegionalDomainName(domainName + ".regional.local");
|
||||
domain.setRegionalHostedZoneId("Z2FDTNDATAQYL2");
|
||||
domain.setEndpointConfigurationType(endpointTypeOf(request));
|
||||
applyEndpointType(domain, endpointType);
|
||||
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");
|
||||
@@ -1309,11 +1317,38 @@ public class ApiGatewayService {
|
||||
domain.setTags(copied);
|
||||
}
|
||||
|
||||
domainStore.put(domainKey(region, domainName), domain);
|
||||
// AWS enforces global uniqueness of custom domain names across all regions. The check and
|
||||
// the store are one step, so two concurrent creates of one name cannot both succeed.
|
||||
synchronized (domainNameLock) {
|
||||
boolean exists = !domainStore.scan(k -> k.endsWith("::" + domainName)).isEmpty();
|
||||
if (exists) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"The domain name you provided already exists.", 400);
|
||||
}
|
||||
domainStore.put(domainKey(region, domainName), domain);
|
||||
}
|
||||
LOG.infov("Created custom domain {0} in {1}", domainName, region);
|
||||
return domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* An edge-optimized domain fronts a CloudFront distribution, and a DNS alias points at the
|
||||
* distribution's name in the fixed CloudFront hosted zone AWS documents for every region. A
|
||||
* regional domain has none, so a move to {@code REGIONAL} drops the distribution again while a
|
||||
* move to {@code EDGE} puts one in front of the domain, as the migration does on AWS.
|
||||
*/
|
||||
private static void applyEndpointType(CustomDomain domain, String endpointType) {
|
||||
domain.setEndpointConfigurationType(endpointType);
|
||||
if (!"EDGE".equals(endpointType)) {
|
||||
domain.setDistributionDomainName(null);
|
||||
domain.setDistributionHostedZoneId(null);
|
||||
} else if (domain.getDistributionDomainName() == null) {
|
||||
domain.setDistributionDomainName(
|
||||
"d" + UUID.randomUUID().toString().replace("-", "").substring(0, 13) + ".cloudfront.net");
|
||||
domain.setDistributionHostedZoneId("Z2FDTNDATAQYW2");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
@@ -1344,14 +1379,22 @@ public class ApiGatewayService {
|
||||
}
|
||||
|
||||
public void deleteDomainName(String region, String domainName) {
|
||||
getDomainName(region, domainName);
|
||||
domainStore.delete(domainKey(region, domainName));
|
||||
// Delete associated mappings
|
||||
String prefix = region + "::" + domainName + "::";
|
||||
basePathMappingStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(basePathMappingStore::delete);
|
||||
synchronized (domainNameLock) {
|
||||
getDomainName(region, domainName);
|
||||
domainStore.delete(domainKey(region, domainName));
|
||||
// Delete associated mappings
|
||||
String prefix = region + "::" + domainName + "::";
|
||||
basePathMappingStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(basePathMappingStore::delete);
|
||||
}
|
||||
}
|
||||
|
||||
public CustomDomain updateDomainName(String region, String domainName, List<Map<String, String>> patchOperations) {
|
||||
synchronized (domainNameLock) {
|
||||
return applyDomainNamePatch(region, domainName, patchOperations);
|
||||
}
|
||||
}
|
||||
|
||||
private CustomDomain applyDomainNamePatch(String region, String domainName, List<Map<String, String>> patchOperations) {
|
||||
String domainKey = domainKey(region, domainName);
|
||||
CustomDomain domain = getDomainName(region, domainName);
|
||||
if (domain == null) {
|
||||
@@ -1386,7 +1429,7 @@ public class ApiGatewayService {
|
||||
// Check if value is required for the specific path
|
||||
if ("/certificateName".equals(path) || "/certificateArn".equals(path)
|
||||
|| "/regionalCertificateName".equals(path) || "/regionalCertificateArn".equals(path)
|
||||
|| "/securityPolicy".equals(path) || "/endpointConfiguration/types/REGIONAL".equals(path)) {
|
||||
|| "/securityPolicy".equals(path) || path.startsWith("/endpointConfiguration/types/")) {
|
||||
throw new AwsException("BadRequestException", "Value is required for path: " + path, 400);
|
||||
}
|
||||
}
|
||||
@@ -1401,7 +1444,13 @@ public class ApiGatewayService {
|
||||
newRegionalCertificateArn = value;
|
||||
} else if ("/securityPolicy".equals(path)) {
|
||||
newSecurityPolicy = value;
|
||||
} else if ("/endpointConfiguration/types/REGIONAL".equals(path)) {
|
||||
} else if (path.startsWith("/endpointConfiguration/types/")) {
|
||||
// The path names the type the domain has now; the value names the one it should get.
|
||||
if (!path.equals("/endpointConfiguration/types/" + newEndpointConfigurationType)) {
|
||||
throw new AwsException("BadRequestException", "Invalid patch path " + path
|
||||
+ ": the path must name the domain's current endpoint type, "
|
||||
+ newEndpointConfigurationType, 400);
|
||||
}
|
||||
if (!"REGIONAL".equals(value) && !"EDGE".equals(value)) {
|
||||
throw new AwsException("BadRequestException", "Invalid value for endpoint type: " + value, 400);
|
||||
}
|
||||
@@ -1415,7 +1464,7 @@ public class ApiGatewayService {
|
||||
domain.setRegionalCertificateName(newRegionalCertificateName);
|
||||
domain.setRegionalCertificateArn(newRegionalCertificateArn);
|
||||
domain.setSecurityPolicy(newSecurityPolicy);
|
||||
domain.setEndpointConfigurationType(newEndpointConfigurationType);
|
||||
applyEndpointType(domain, newEndpointConfigurationType);
|
||||
domainStore.put(domainKey, domain);
|
||||
return domain;
|
||||
}
|
||||
@@ -1433,13 +1482,19 @@ public class ApiGatewayService {
|
||||
}
|
||||
|
||||
public BasePathMapping createBasePathMapping(String region, String domainName, Map<String, Object> request) {
|
||||
getDomainName(region, domainName);
|
||||
String basePath = canonicalBasePath((String) request.get("basePath"));
|
||||
String apiId = (String) request.get("restApiId");
|
||||
String stage = (String) request.get("stage");
|
||||
|
||||
BasePathMapping mapping = new BasePathMapping(basePath, apiId, stage);
|
||||
basePathMappingStore.put(mappingKey(region, domainName, basePath), mapping);
|
||||
synchronized (domainNameLock) {
|
||||
getDomainName(region, domainName);
|
||||
String key = mappingKey(region, domainName, basePath);
|
||||
if (basePathMappingStore.get(key).isPresent()) {
|
||||
throw new AwsException("ConflictException", "Base path already exists for this domain name", 409);
|
||||
}
|
||||
basePathMappingStore.put(key, mapping);
|
||||
}
|
||||
LOG.infov("Created mapping for {0} path={1} -> API {2}", domainName, basePath, apiId);
|
||||
return mapping;
|
||||
}
|
||||
@@ -1472,9 +1527,11 @@ public class ApiGatewayService {
|
||||
}
|
||||
|
||||
public void deleteBasePathMapping(String region, String domainName, String basePath) {
|
||||
getBasePathMapping(region, domainName, basePath);
|
||||
String path = (basePath == null || basePath.isEmpty() || "/" .equals(basePath)) ? "(none)" : basePath;
|
||||
basePathMappingStore.delete(mappingKey(region, domainName, path));
|
||||
synchronized (domainNameLock) {
|
||||
getBasePathMapping(region, domainName, basePath);
|
||||
String path = (basePath == null || basePath.isEmpty() || "/" .equals(basePath)) ? "(none)" : basePath;
|
||||
basePathMappingStore.delete(mappingKey(region, domainName, path));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1507,13 +1564,22 @@ public class ApiGatewayService {
|
||||
*/
|
||||
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);
|
||||
synchronized (domainNameLock) {
|
||||
if (basePathMappingStore.get(key).isEmpty()) {
|
||||
throw new AwsException("NotFoundException", "Base path mapping not found", 404);
|
||||
}
|
||||
basePathMappingStore.delete(key);
|
||||
}
|
||||
basePathMappingStore.delete(key);
|
||||
}
|
||||
|
||||
public BasePathMapping updateBasePathMapping(String region, String domainName, String basePath, List<Map<String, String>> patchOperations) {
|
||||
synchronized (domainNameLock) {
|
||||
return applyBasePathMappingPatch(region, domainName, basePath, patchOperations);
|
||||
}
|
||||
}
|
||||
|
||||
private BasePathMapping applyBasePathMappingPatch(String region, String domainName, String basePath,
|
||||
List<Map<String, String>> patchOperations) {
|
||||
String normalizedPath = (basePath == null || basePath.isEmpty() || "/".equals(basePath)) ? "(none)" : basePath;
|
||||
|
||||
BasePathMapping mapping = getBasePathMapping(region, domainName, basePath);
|
||||
@@ -1871,6 +1937,42 @@ public class ApiGatewayService {
|
||||
apiStore.put(apiKey(region, apiId), api);
|
||||
}
|
||||
|
||||
public Map<String, String> getDomainNameTags(String region, String domainName) {
|
||||
synchronized (domainNameLock) {
|
||||
Map<String, String> tags = getDomainName(region, domainName).getTags();
|
||||
return tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Both tag writes replace the domain's tag map instead of changing it in place: the store hands
|
||||
* out the live object, and a GetDomainName in flight on another thread may be iterating the map
|
||||
* it was handed. The lock orders the writers; the fresh map keeps the readers safe.
|
||||
*/
|
||||
public void tagDomainName(String region, String domainName, Map<String, String> tags) {
|
||||
ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);
|
||||
synchronized (domainNameLock) {
|
||||
CustomDomain domain = getDomainName(region, domainName);
|
||||
Map<String, String> merged = domain.getTags() == null
|
||||
? new LinkedHashMap<>() : new LinkedHashMap<>(domain.getTags());
|
||||
merged.putAll(tags);
|
||||
domain.setTags(merged);
|
||||
domainStore.put(domainKey(region, domainName), domain);
|
||||
}
|
||||
}
|
||||
|
||||
public void untagDomainName(String region, String domainName, List<String> tagKeys) {
|
||||
synchronized (domainNameLock) {
|
||||
CustomDomain domain = getDomainName(region, domainName);
|
||||
if (domain.getTags() != null) {
|
||||
Map<String, String> remaining = new LinkedHashMap<>(domain.getTags());
|
||||
tagKeys.forEach(remaining::remove);
|
||||
domain.setTags(remaining);
|
||||
domainStore.put(domainKey(region, domainName), domain);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── OpenAPI Import ────────────────────────────
|
||||
|
||||
public RestApi importRestApi(String region, String specBody) {
|
||||
|
||||
+35
-5
@@ -11,13 +11,16 @@ import java.util.Map;
|
||||
/**
|
||||
* {@link TagHandler} implementation for API Gateway.
|
||||
*
|
||||
* <p>ARN format: {@code arn:aws:apigateway:<region>::/restapis/<apiId>}.
|
||||
* The {@code apiId} is the canonical identifier the underlying {@link ApiGatewayService}
|
||||
* <p>ARN formats: {@code arn:aws:apigateway:<region>::/restapis/<apiId>} for a REST API and
|
||||
* {@code arn:aws:apigateway:<region>::/domainnames/<domainName>} for a custom domain. The
|
||||
* {@code apiId} or domain name is the canonical identifier the underlying {@link ApiGatewayService}
|
||||
* uses for its tag store.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ApiGatewayTagHandler implements TagHandler {
|
||||
|
||||
private static final String DOMAIN_NAMES = "/domainnames/";
|
||||
|
||||
private final ApiGatewayService service;
|
||||
|
||||
@Inject
|
||||
@@ -37,17 +40,30 @@ public class ApiGatewayTagHandler implements TagHandler {
|
||||
|
||||
@Override
|
||||
public Map<String, String> listTags(String region, String arn) {
|
||||
return service.getTags(region, apiIdFromArn(arn));
|
||||
String domainName = domainNameFromArn(arn);
|
||||
return domainName != null
|
||||
? service.getDomainNameTags(region, domainName)
|
||||
: service.getTags(region, apiIdFromArn(arn));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tagResource(String region, String arn, Map<String, String> tags) {
|
||||
service.tagResource(region, apiIdFromArn(arn), tags);
|
||||
String domainName = domainNameFromArn(arn);
|
||||
if (domainName != null) {
|
||||
service.tagDomainName(region, domainName, tags);
|
||||
} else {
|
||||
service.tagResource(region, apiIdFromArn(arn), tags);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void untagResource(String region, String arn, List<String> tagKeys) {
|
||||
service.untagResource(region, apiIdFromArn(arn), tagKeys);
|
||||
String domainName = domainNameFromArn(arn);
|
||||
if (domainName != null) {
|
||||
service.untagDomainName(region, domainName, tagKeys);
|
||||
} else {
|
||||
service.untagResource(region, apiIdFromArn(arn), tagKeys);
|
||||
}
|
||||
}
|
||||
|
||||
private static String apiIdFromArn(String arn) {
|
||||
@@ -57,4 +73,18 @@ public class ApiGatewayTagHandler implements TagHandler {
|
||||
}
|
||||
return parts[1].split("/")[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* The domain a {@code /domainnames/<name>} ARN names, or null for any other ARN. A base path
|
||||
* mapping ARN continues past the domain and is not taggable, so it falls through to the REST API
|
||||
* parse and its "invalid ARN" answer.
|
||||
*/
|
||||
private static String domainNameFromArn(String arn) {
|
||||
int at = arn.indexOf(DOMAIN_NAMES);
|
||||
if (at < 0) {
|
||||
return null;
|
||||
}
|
||||
String domainName = arn.substring(at + DOMAIN_NAMES.length());
|
||||
return domainName.isEmpty() || domainName.contains("/") ? null : domainName;
|
||||
}
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::ApiGateway::DomainName} and {@code AWS::ApiGateway::BasePathMapping}.
|
||||
*
|
||||
* <p>A domain's physical id is its name, as in AWS, and its five read-only attributes come from the
|
||||
* stored domain. A regional domain has no CloudFront distribution, so for one the two distribution
|
||||
* attributes are empty rather than the literal {@code LogicalId.DistributionDomainName} an unset
|
||||
* attribute would resolve to. A mapping's physical id is the compound identifier CloudFormation
|
||||
* reports for the type, {@code <DomainName>|<BasePath>}, with {@code (none)} as the API's spelling
|
||||
* of an empty base path.
|
||||
*
|
||||
* <p>{@code MutualTlsAuthentication}, {@code OwnershipVerificationCertificateArn},
|
||||
* {@code EndpointAccessMode}, {@code RoutingMode} and {@code EndpointConfiguration.IpAddressType}
|
||||
* are accepted and ignored: nothing in the emulator reads them. The other {@code AWS::ApiGateway::*}
|
||||
* types still live in the legacy switch.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ApiGatewayDomainCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ApiGatewayDomainCfnProvisioner.class);
|
||||
private static final String DOMAIN_NAME_TYPE = "AWS::ApiGateway::DomainName";
|
||||
private static final String BASE_PATH_MAPPING_TYPE = "AWS::ApiGateway::BasePathMapping";
|
||||
private static final String NOT_FOUND = "NotFoundException";
|
||||
private static final String MAPPING_ID_SEPARATOR = "|";
|
||||
|
||||
private final ApiGatewayService apiGatewayService;
|
||||
|
||||
public ApiGatewayDomainCfnProvisioner(ApiGatewayService apiGatewayService) {
|
||||
this.apiGatewayService = apiGatewayService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(DOMAIN_NAME_TYPE, BASE_PATH_MAPPING_TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
switch (r.getResourceType()) {
|
||||
case DOMAIN_NAME_TYPE -> provisionDomainName(r, props, ctx);
|
||||
case BASE_PATH_MAPPING_TYPE -> provisionBasePathMapping(r, props, ctx);
|
||||
default -> throw new IllegalStateException(
|
||||
"ApiGatewayDomainCfnProvisioner cannot handle " + r.getResourceType());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
switch (resourceType) {
|
||||
case DOMAIN_NAME_TYPE -> deleteDomain(physicalId, region);
|
||||
case BASE_PATH_MAPPING_TYPE -> deleteMapping(physicalId, region);
|
||||
default -> throw new IllegalStateException(
|
||||
"ApiGatewayDomainCfnProvisioner cannot handle " + resourceType);
|
||||
}
|
||||
}
|
||||
|
||||
/** The template's view of a domain: the name, and everything that can change without a replacement. */
|
||||
private record DomainSpec(String endpointType, String certificateArn, String regionalCertificateArn,
|
||||
String securityPolicy, Map<String, String> tags) {
|
||||
}
|
||||
|
||||
private void provisionDomainName(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String domainName = ctx.resolveOptional(props, "DomainName");
|
||||
if (isBlank(domainName)) {
|
||||
throw new IllegalArgumentException("AWS::ApiGateway::DomainName requires DomainName");
|
||||
}
|
||||
DomainSpec desired = new DomainSpec(endpointType(props, ctx),
|
||||
ctx.resolveOptional(props, "CertificateArn"),
|
||||
ctx.resolveOptional(props, "RegionalCertificateArn"),
|
||||
ctx.resolveOptional(props, "SecurityPolicy"),
|
||||
ctx.resolveTags(props, "Tags"));
|
||||
|
||||
// DomainName is the schema's only createOnly property: a new name replaces the domain, and
|
||||
// the replacement is created before the prior domain is removed, as CloudFormation does.
|
||||
// Everything else is patched in place, so the regional name a DNS record outside the stack
|
||||
// points at survives the update.
|
||||
CustomDomain existing = ctx.isUpdate() ? findDomain(ctx.priorPhysicalId(), ctx.region()) : null;
|
||||
CustomDomain provisioned;
|
||||
if (existing != null && ctx.reusesPriorEntity(domainName)) {
|
||||
provisioned = updateDomainInPlace(existing, desired, ctx.region());
|
||||
} else {
|
||||
provisioned = apiGatewayService.createDomainName(ctx.region(), createDomainRequest(domainName, desired));
|
||||
if (existing != null) {
|
||||
deleteDomain(ctx.priorPhysicalId(), ctx.region());
|
||||
}
|
||||
}
|
||||
r.setPhysicalId(domainName);
|
||||
r.getAttributes().put("DomainNameArn",
|
||||
"arn:aws:apigateway:" + ctx.region() + "::/domainnames/" + domainName);
|
||||
r.getAttributes().put("RegionalDomainName", orEmpty(provisioned.getRegionalDomainName()));
|
||||
r.getAttributes().put("RegionalHostedZoneId", orEmpty(provisioned.getRegionalHostedZoneId()));
|
||||
r.getAttributes().put("DistributionDomainName", orEmpty(provisioned.getDistributionDomainName()));
|
||||
r.getAttributes().put("DistributionHostedZoneId", orEmpty(provisioned.getDistributionHostedZoneId()));
|
||||
}
|
||||
|
||||
private static String endpointType(JsonNode props, ProvisionContext ctx) {
|
||||
if (props == null || !props.hasNonNull("EndpointConfiguration")) {
|
||||
return null;
|
||||
}
|
||||
JsonNode configuration = ctx.engine().resolveNode(props.get("EndpointConfiguration"));
|
||||
JsonNode types = configuration == null ? null : configuration.path("Types");
|
||||
if (types == null || !types.isArray() || types.size() == 0) {
|
||||
return null;
|
||||
}
|
||||
return ctx.engine().resolve(types.get(0));
|
||||
}
|
||||
|
||||
private static Map<String, Object> createDomainRequest(String domainName, DomainSpec spec) {
|
||||
Map<String, Object> request = new LinkedHashMap<>();
|
||||
request.put("domainName", domainName);
|
||||
if (spec.endpointType() != null) {
|
||||
request.put("endpointConfiguration", Map.of("types", List.of(spec.endpointType())));
|
||||
}
|
||||
putIfPresent(request, "certificateArn", spec.certificateArn());
|
||||
putIfPresent(request, "regionalCertificateArn", spec.regionalCertificateArn());
|
||||
putIfPresent(request, "securityPolicy", spec.securityPolicy());
|
||||
if (!spec.tags().isEmpty()) {
|
||||
request.put("tags", spec.tags());
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private CustomDomain updateDomainInPlace(CustomDomain existing, DomainSpec desired, String region) {
|
||||
List<Map<String, String>> operations = new ArrayList<>();
|
||||
addReplace(operations, "/certificateArn", existing.getCertificateArn(), desired.certificateArn());
|
||||
addReplace(operations, "/regionalCertificateArn",
|
||||
existing.getRegionalCertificateArn(), desired.regionalCertificateArn());
|
||||
addReplace(operations, "/securityPolicy", existing.getSecurityPolicy(), desired.securityPolicy());
|
||||
if (desired.endpointType() != null
|
||||
&& !desired.endpointType().equals(existing.getEndpointConfigurationType())) {
|
||||
// The patch path names the type the domain has now; the value names the one it should get.
|
||||
operations.add(replaceOperation(
|
||||
"/endpointConfiguration/types/" + existing.getEndpointConfigurationType(),
|
||||
desired.endpointType()));
|
||||
}
|
||||
// The patch carries the validation, so it goes first: a rejected update leaves the tags as
|
||||
// they were instead of half-applying the template.
|
||||
CustomDomain updated = operations.isEmpty()
|
||||
? existing
|
||||
: apiGatewayService.updateDomainName(region, existing.getDomainName(), operations);
|
||||
reconcileTags(updated, desired.tags(), region);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
private void provisionBasePathMapping(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String domainName = ctx.resolveOptional(props, "DomainName");
|
||||
String restApiId = ctx.resolveOptional(props, "RestApiId");
|
||||
if (isBlank(domainName) || isBlank(restApiId)) {
|
||||
throw new IllegalArgumentException(
|
||||
"AWS::ApiGateway::BasePathMapping requires DomainName and RestApiId");
|
||||
}
|
||||
String basePath = ApiGatewayService.canonicalBasePath(ctx.resolveOptional(props, "BasePath"));
|
||||
String stage = ctx.resolveOptional(props, "Stage");
|
||||
String physicalId = domainName + MAPPING_ID_SEPARATOR + basePath;
|
||||
|
||||
// DomainName and BasePath are createOnly: a change to either replaces the mapping, created
|
||||
// before the prior one is removed. RestApiId and Stage are patched in place.
|
||||
BasePathMapping existing = ctx.isUpdate() ? findMapping(ctx.priorPhysicalId(), ctx.region()) : null;
|
||||
if (existing != null && ctx.reusesPriorEntity(physicalId)) {
|
||||
List<Map<String, String>> operations = new ArrayList<>();
|
||||
addReplace(operations, "/restApiId", existing.getRestApiId(), restApiId);
|
||||
addReplace(operations, "/stage", existing.getStage(), stage);
|
||||
if (!operations.isEmpty()) {
|
||||
apiGatewayService.updateBasePathMapping(ctx.region(), domainName, basePath, operations);
|
||||
}
|
||||
} else {
|
||||
Map<String, Object> request = new LinkedHashMap<>();
|
||||
request.put("basePath", basePath);
|
||||
request.put("restApiId", restApiId);
|
||||
putIfPresent(request, "stage", stage);
|
||||
apiGatewayService.createBasePathMapping(ctx.region(), domainName, request);
|
||||
if (existing != null) {
|
||||
deleteMapping(ctx.priorPhysicalId(), ctx.region());
|
||||
}
|
||||
}
|
||||
r.setPhysicalId(physicalId);
|
||||
}
|
||||
|
||||
private BasePathMapping findMapping(String physicalId, String region) {
|
||||
try {
|
||||
MappingId id = MappingId.parse(physicalId);
|
||||
return apiGatewayService.getBasePathMapping(region, id.domainName(), id.basePath());
|
||||
} catch (AwsException e) {
|
||||
if (!NOT_FOUND.equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("Base path mapping {0} from the previous execution is gone, creating it again", physicalId);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteMapping(String physicalId, String region) {
|
||||
MappingId id = MappingId.parse(physicalId);
|
||||
CfnDeletes.safeDelete("base path mapping", physicalId,
|
||||
() -> apiGatewayService.deleteBasePathMapping(region, id.domainName(), id.basePath()), NOT_FOUND);
|
||||
}
|
||||
|
||||
/** The compound identifier of a mapping, {@code <DomainName>|<BasePath>}; neither part can contain the bar. */
|
||||
private record MappingId(String domainName, String basePath) {
|
||||
|
||||
static MappingId parse(String physicalId) {
|
||||
int separator = physicalId == null ? -1 : physicalId.indexOf(MAPPING_ID_SEPARATOR);
|
||||
if (separator <= 0 || separator == physicalId.length() - 1) {
|
||||
throw new AwsException(NOT_FOUND,
|
||||
"Invalid base path mapping identifier specified, expected <DomainName>|<BasePath>: "
|
||||
+ physicalId, 404);
|
||||
}
|
||||
return new MappingId(physicalId.substring(0, separator), physicalId.substring(separator + 1));
|
||||
}
|
||||
}
|
||||
|
||||
/** A property the template leaves out keeps its stored value: the PATCH API cannot unset these. */
|
||||
private static void addReplace(List<Map<String, String>> operations, String path,
|
||||
String current, String desired) {
|
||||
if (desired != null && !desired.equals(current)) {
|
||||
operations.add(replaceOperation(path, desired));
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> replaceOperation(String path, String value) {
|
||||
return Map.of("op", "replace", "path", path, "value", value);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user