diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 07a189e0be..c69a5a97ff 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -105,6 +105,24 @@ immediately. > disabled, or deleted key is still executed — it simply arrives with a null `identity.apiKey` rather > than being rejected with `403`. +### Custom Domain Names + +A domain created with `CreateDomainName` is `AVAILABLE` at once. Its `regionalDomainName` is +`.regional.local`, and a request whose `Host` header is either that name or the domain +itself is routed through the domain's base path mappings to the mapped REST API stage. An +`EDGE` domain also reports a `distributionDomainName` under `cloudfront.net` and the fixed +CloudFront hosted zone `Z2FDTNDATAQYW2`; a `REGIONAL` domain reports neither, as on AWS. Moving a +domain between the two types with `UpdateDomainName` creates or drops the distribution. +`GetDomainName` returns the `domainNameArn`, the `endpointConfiguration`, both certificate ARNs +and the `tags`. Tags are managed through `TagResource`, `UntagResource` and `GetTags` on +`arn:aws:apigateway:::/domainnames/`. A second mapping on a base path that +already has one is a `ConflictException`. A `PRIVATE` endpoint type is refused: private custom +domains are not emulated. Mutual TLS, ownership verification certificates, routing modes and +endpoint access modes are accepted and ignored. + +Templates can create domains and mappings with `AWS::ApiGateway::DomainName` and +`AWS::ApiGateway::BasePathMapping`; see [CloudFormation](cloudformation.md). + ### IAM Authorization (`AWS_IAM`) {#iam-authorization} A method (v1) or route (v2) whose `authorizationType` is `AWS_IAM` requires a SigV4-signed caller. diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index ecc809ce52..fd501d4632 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -73,7 +73,7 @@ cross-resource references. | Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` | | Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook` | | Route 53 | `HostedZone`, `RecordSet` | -| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account` | +| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping` | | API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` | | Step Functions | `StateMachine` | | CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` | diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java index 1102562127..da170d925b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java @@ -995,7 +995,7 @@ public class ApiGatewayController { @SuppressWarnings("unchecked") Map 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 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> 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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java index 20d90457b2..e855539b33 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java @@ -66,6 +66,13 @@ public class ApiGatewayService { private final StorageBackend accountStore; private final StorageBackend domainStore; private final StorageBackend 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 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> patchOperations) { + synchronized (domainNameLock) { + return applyDomainNamePatch(region, domainName, patchOperations); + } + } + + private CustomDomain applyDomainNamePatch(String region, String domainName, List> 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 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> patchOperations) { + synchronized (domainNameLock) { + return applyBasePathMappingPatch(region, domainName, basePath, patchOperations); + } + } + + private BasePathMapping applyBasePathMappingPatch(String region, String domainName, String basePath, + List> 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 getDomainNameTags(String region, String domainName) { + synchronized (domainNameLock) { + Map 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 tags) { + ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags); + synchronized (domainNameLock) { + CustomDomain domain = getDomainName(region, domainName); + Map 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 tagKeys) { + synchronized (domainNameLock) { + CustomDomain domain = getDomainName(region, domainName); + if (domain.getTags() != null) { + Map 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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java index 66ea0a0f62..452817d81d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java @@ -11,13 +11,16 @@ import java.util.Map; /** * {@link TagHandler} implementation for API Gateway. * - *

ARN format: {@code arn:aws:apigateway:::/restapis/}. - * The {@code apiId} is the canonical identifier the underlying {@link ApiGatewayService} + *

ARN formats: {@code arn:aws:apigateway:::/restapis/} for a REST API and + * {@code arn:aws:apigateway:::/domainnames/} 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 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 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 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/} 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; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisioner.java new file mode 100644 index 0000000000..19b996c63b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisioner.java @@ -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}. + * + *

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 |}, with {@code (none)} as the API's spelling + * of an empty base path. + * + *

{@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 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 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 createDomainRequest(String domainName, DomainSpec spec) { + Map 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> 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 desired, String region) { + Map current = existing.getTags() == null ? Map.of() : existing.getTags(); + if (desired.equals(current)) { + return; + } + List 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> 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 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 |}; 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 |: " + + 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> operations, String path, + String current, String desired) { + if (desired != null && !desired.equals(current)) { + operations.add(replaceOperation(path, desired)); + } + } + + private static Map replaceOperation(String path, String value) { + return Map.of("op", "replace", "path", path, "value", value); + } + + private static void putIfPresent(Map 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; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainNameIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainNameIntegrationTest.java new file mode 100644 index 0000000000..3a61ef16f9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainNameIntegrationTest.java @@ -0,0 +1,333 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicInteger; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * What {@code CreateDomainName} keeps and {@code GetDomainName} reports for a REST custom domain: + * the regional certificate, the endpoint configuration, the ARN, the tags, and for an + * edge-optimized domain the CloudFront distribution a DNS alias would point at. Tags are managed + * through the tag API on the domain's ARN, as on AWS. + */ +@QuarkusTest +class ApiGatewayDomainNameIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String CERTIFICATE_ARN = + "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555"; + + @Inject + ApiGatewayService service; + + @Test + void createKeepsTheRegionalCertificateAndReportsTheEndpointConfiguration() { + String domain = "regional.apigw-domain-it.example.com"; + createDomain(""" + {"domainName":"%s", + "regionalCertificateArn":"%s", + "regionalCertificateName":"regional-cert", + "endpointConfiguration":{"types":["REGIONAL"]}} + """.formatted(domain, CERTIFICATE_ARN)) + .body("regionalCertificateArn", equalTo(CERTIFICATE_ARN)) + .body("regionalCertificateName", equalTo("regional-cert")); + + given().when().get("/domainnames/" + domain).then() + .statusCode(200) + .body("domainNameArn", equalTo("arn:aws:apigateway:us-east-1::/domainnames/" + domain)) + .body("regionalCertificateArn", equalTo(CERTIFICATE_ARN)) + .body("regionalCertificateName", equalTo("regional-cert")) + .body("endpointConfiguration.types[0]", equalTo("REGIONAL")) + .body("regionalDomainName", equalTo(domain + ".regional.local")) + .body("distributionDomainName", nullValue()) + .body("distributionHostedZoneId", nullValue()); + + deleteDomain(domain); + } + + @Test + void edgeDomainReportsTheDistributionADnsAliasPointsAt() { + String domain = "edge.apigw-domain-it.example.com"; + createDomain(""" + {"domainName":"%s", + "certificateArn":"%s", + "endpointConfiguration":{"types":["EDGE"]}} + """.formatted(domain, CERTIFICATE_ARN)) + .body("endpointConfiguration.types[0]", equalTo("EDGE")) + .body("distributionDomainName", endsWith(".cloudfront.net")) + .body("distributionHostedZoneId", equalTo("Z2FDTNDATAQYW2")); + + deleteDomain(domain); + } + + @Test + void endpointTypeCanBeMovedFromEdgeToRegional() { + String domain = "endpoint-type.apigw-domain-it.example.com"; + createDomain(""" + {"domainName":"%s","certificateArn":"%s","endpointConfiguration":{"types":["EDGE"]}} + """.formatted(domain, CERTIFICATE_ARN)); + + // The patch path names the type the domain has now, the value the type it should get. A + // regional domain has no distribution, so the move drops the CloudFront fields. + given().contentType(ContentType.JSON) + .body(""" + {"patchOperations":[{"op":"replace","path":"/endpointConfiguration/types/EDGE","value":"REGIONAL"}]} + """) + .when().patch("/domainnames/" + domain).then() + .statusCode(200) + .body("endpointConfiguration.types[0]", equalTo("REGIONAL")) + .body("distributionDomainName", nullValue()) + .body("distributionHostedZoneId", nullValue()); + + deleteDomain(domain); + } + + @Test + void endpointTypeCanBeMovedFromRegionalToEdge() { + String domain = "edge-migration.apigw-domain-it.example.com"; + createDomain(""" + {"domainName":"%s","regionalCertificateArn":"%s","endpointConfiguration":{"types":["REGIONAL"]}} + """.formatted(domain, CERTIFICATE_ARN)) + .body("distributionDomainName", nullValue()); + + // Moving to EDGE puts a distribution in front of the domain, as on AWS. + given().contentType(ContentType.JSON) + .body(""" + {"patchOperations":[{"op":"replace","path":"/endpointConfiguration/types/REGIONAL","value":"EDGE"}]} + """) + .when().patch("/domainnames/" + domain).then() + .statusCode(200) + .body("endpointConfiguration.types[0]", equalTo("EDGE")) + .body("distributionDomainName", endsWith(".cloudfront.net")) + .body("distributionHostedZoneId", equalTo("Z2FDTNDATAQYW2")); + + given().when().get("/domainnames/" + domain).then() + .statusCode(200) + .body("distributionDomainName", endsWith(".cloudfront.net")); + + deleteDomain(domain); + } + + @Test + void createRejectsAnEndpointTypeOtherThanRegionalOrEdge() { + // Private custom domains are not emulated, and an unknown type would leave a domain that is + // neither regional nor edge, so both are refused up front and nothing is stored. + String domain = "private.apigw-domain-it.example.com"; + for (String type : List.of("PRIVATE", "FOOBAR")) { + given().contentType(ContentType.JSON) + .body(""" + {"domainName":"%s","regionalCertificateArn":"%s","endpointConfiguration":{"types":["%s"]}} + """.formatted(domain, CERTIFICATE_ARN, type)) + .when().post("/domainnames").then() + .statusCode(400) + .body("message", equalTo("Invalid value for endpoint type: " + type)); + } + given().when().get("/domainnames/" + domain).then().statusCode(404); + } + + @Test + void endpointTypePatchPathMustNameTheCurrentType() { + String domain = "endpoint-path.apigw-domain-it.example.com"; + createDomain(""" + {"domainName":"%s","regionalCertificateArn":"%s","endpointConfiguration":{"types":["REGIONAL"]}} + """.formatted(domain, CERTIFICATE_ARN)); + + // A path naming a type the domain does not have, or no type at all, is rejected as on AWS, + // and the domain is left as it was. + for (String path : List.of("/endpointConfiguration/types/EDGE", "/endpointConfiguration/types/FOO")) { + given().contentType(ContentType.JSON) + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"" + path + "\",\"value\":\"EDGE\"}]}") + .when().patch("/domainnames/" + domain).then() + .statusCode(400) + .body("message", equalTo("Invalid patch path " + path + + ": the path must name the domain's current endpoint type, REGIONAL")); + } + given().when().get("/domainnames/" + domain).then() + .statusCode(200) + .body("endpointConfiguration.types[0]", equalTo("REGIONAL")) + .body("distributionDomainName", nullValue()); + + deleteDomain(domain); + } + + @Test + void tagsAreReportedAndManagedThroughTheTagApi() { + String domain = "tags.apigw-domain-it.example.com"; + String arn = "arn:aws:apigateway:us-east-1::/domainnames/" + domain; + createDomain(""" + {"domainName":"%s","regionalCertificateArn":"%s","tags":{"env":"prod"}} + """.formatted(domain, CERTIFICATE_ARN)) + .body("tags.env", equalTo("prod")); + + given().pathParam("arn", arn).contentType(ContentType.JSON) + .body("{\"tags\":{\"team\":\"api\"}}") + .when().put("/tags/{arn}").then().statusCode(204); + + given().pathParam("arn", arn).when().get("/tags/{arn}").then() + .statusCode(200) + .body("tags.env", equalTo("prod")) + .body("tags.team", equalTo("api")); + + given().pathParam("arn", arn).queryParam("tagKeys", "env") + .when().delete("/tags/{arn}").then().statusCode(anyOf(is(200), is(204))); + + given().when().get("/domainnames/" + domain).then() + .statusCode(200) + .body("tags.env", nullValue()) + .body("tags.team", equalTo("api")); + + deleteDomain(domain); + } + + @Test + void concurrentCreatesOfOneDomainNameAdmitExactlyOne() throws Exception { + String domain = "race.apigw-domain-it.example.com"; + int callers = 8; + ExecutorService pool = Executors.newFixedThreadPool(callers); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger created = new AtomicInteger(); + AtomicInteger rejected = new AtomicInteger(); + try { + List> calls = new java.util.ArrayList<>(); + for (int i = 0; i < callers; i++) { + calls.add(pool.submit(() -> { + start.await(); + try { + service.createDomainName(REGION, Map.of("domainName", domain)); + created.incrementAndGet(); + } catch (AwsException e) { + assertEquals("BadRequestException", e.getErrorCode()); + rejected.incrementAndGet(); + } + return null; + })); + } + start.countDown(); + for (Future call : calls) { + call.get(); + } + } finally { + pool.shutdownNow(); + } + + assertEquals(1, created.get(), "domain names are unique, so exactly one caller may create it"); + assertEquals(callers - 1, rejected.get()); + service.deleteDomainName(REGION, domain); + } + + @Test + void creatingAMappingOnATakenBasePathIsAConflict() { + String domain = "conflict.apigw-domain-it.example.com"; + createDomain(""" + {"domainName":"%s","regionalCertificateArn":"%s"} + """.formatted(domain, CERTIFICATE_ARN)); + String mapping = "{\"basePath\":\"v1\",\"restApiId\":\"abc123def4\",\"stage\":\"prod\"}"; + given().contentType(ContentType.JSON).body(mapping) + .when().post("/domainnames/" + domain + "/basepathmappings").then().statusCode(201); + + // AWS refuses a second mapping on the same base path rather than replacing the first. + given().contentType(ContentType.JSON).body(mapping) + .when().post("/domainnames/" + domain + "/basepathmappings").then() + .statusCode(409) + .body("message", equalTo("Base path already exists for this domain name")); + + given().when().get("/domainnames/" + domain + "/basepathmappings/v1").then() + .statusCode(200) + .body("stage", equalTo("prod")); + + deleteDomain(domain); + } + + @Test + void concurrentMappingCreatesOnOneBasePathAdmitExactlyOne() throws Exception { + String domain = "mapping-race.apigw-domain-it.example.com"; + service.createDomainName(REGION, Map.of("domainName", domain)); + Outcome outcome = race(8, () -> service.createBasePathMapping(REGION, domain, + Map.of("basePath", "v1", "restApiId", "abc123def4", "stage", "prod")), "ConflictException"); + + assertEquals(1, outcome.succeeded(), "one base path holds one mapping, so exactly one caller may create it"); + assertEquals(7, outcome.rejected()); + service.deleteDomainName(REGION, domain); + } + + @Test + void concurrentTagWritesOnOneDomainKeepEveryKey() throws Exception { + String domain = "tag-race.apigw-domain-it.example.com"; + service.createDomainName(REGION, Map.of("domainName", domain)); + AtomicInteger next = new AtomicInteger(); + Outcome outcome = race(8, () -> { + String key = "key-" + next.getAndIncrement(); + service.tagDomainName(REGION, domain, Map.of(key, "value")); + }, null); + + assertEquals(8, outcome.succeeded()); + Map tags = service.getDomainNameTags(REGION, domain); + assertEquals(8, tags.size(), "a tag write must not lose a concurrent write: " + tags); + service.deleteDomainName(REGION, domain); + } + + private record Outcome(int succeeded, int rejected) { + } + + /** Runs the call from {@code callers} threads released together; a rejection must carry {@code rejectedCode}. */ + private static Outcome race(int callers, ThrowingRunnable call, String rejectedCode) throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(callers); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger succeeded = new AtomicInteger(); + AtomicInteger rejected = new AtomicInteger(); + try { + List> calls = new java.util.ArrayList<>(); + for (int i = 0; i < callers; i++) { + calls.add(pool.submit(() -> { + start.await(); + try { + call.run(); + succeeded.incrementAndGet(); + } catch (AwsException e) { + assertEquals(rejectedCode, e.getErrorCode()); + rejected.incrementAndGet(); + } + return null; + })); + } + start.countDown(); + for (Future future : calls) { + future.get(); + } + } finally { + pool.shutdownNow(); + } + return new Outcome(succeeded.get(), rejected.get()); + } + + private interface ThrowingRunnable { + void run() throws Exception; + } + + private static io.restassured.response.ValidatableResponse createDomain(String body) { + return given().contentType(ContentType.JSON).body(body) + .when().post("/domainnames").then().statusCode(201); + } + + private static void deleteDomain(String domain) { + given().when().delete("/domainnames/" + domain).then().statusCode(202); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayDomainCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayDomainCfnIntegrationTest.java new file mode 100644 index 0000000000..1037b46dcd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayDomainCfnIntegrationTest.java @@ -0,0 +1,367 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsAction; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Provisions an {@code AWS::ApiGateway::DomainName} and an {@code AWS::ApiGateway::BasePathMapping} + * through a CloudFormation stack, laid out the way CDK emits a regional custom domain: an ACM + * certificate, the domain referencing it, and a mapping onto a REST API stage. Asserts that every + * {@code Fn::GetAtt} attribute is the value {@code GetDomainName} reports rather than the literal + * {@code ApiDomain.RegionalDomainName} the stub arm would leave in the record, that a request sent + * to the custom domain reaches the mapped API, that mutable properties update in place while a + * renamed domain is replaced, and that deleting the stack removes the mapping before the REST API + * that refuses to go while a mapping points at it. + */ +@QuarkusTest +class ApiGatewayDomainCfnIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260904/us-east-1/cloudformation/aws4_request"; + private static final String STACK = "apigw-domain-cfn-it"; + private static final String INLINE_API_STACK = "apigw-domain-cfn-inline-it"; + private static final String DOMAIN = "api.apigw-domain-cfn-it.example.com"; + private static final String RENAMED_DOMAIN = "gateway.apigw-domain-cfn-it.example.com"; + private static final String INLINE_DOMAIN = "inline.apigw-domain-cfn-it.example.com"; + + /** + * The domain, stage, security policy and tag value are parameters so the same template drives + * the create, the in-place update and the replacement. A wildcard certificate keeps a domain + * rename from replacing the certificate as well. + */ + private static final String TEMPLATE = """ + { + "Parameters": { + "ApiId": {"Type": "String"}, + "StageName": {"Type": "String"}, + "Domain": {"Type": "String"}, + "SecurityPolicy": {"Type": "String"}, + "TagValue": {"Type": "String"}, + "EndpointType": {"Type": "String", "Default": "REGIONAL"} + }, + "Resources": { + "Cert": { + "Type": "AWS::CertificateManager::Certificate", + "Properties": {"DomainName": "*.apigw-domain-cfn-it.example.com", "ValidationMethod": "DNS"} + }, + "ApiDomain": { + "Type": "AWS::ApiGateway::DomainName", + "Properties": { + "DomainName": {"Ref": "Domain"}, + "EndpointConfiguration": {"Types": [{"Ref": "EndpointType"}]}, + "RegionalCertificateArn": {"Ref": "Cert"}, + "SecurityPolicy": {"Ref": "SecurityPolicy"}, + "Tags": [{"Key": "stack", "Value": {"Ref": "TagValue"}}] + } + }, + "Mapping": { + "Type": "AWS::ApiGateway::BasePathMapping", + "Properties": { + "DomainName": {"Ref": "ApiDomain"}, + "BasePath": "v1", + "RestApiId": {"Ref": "ApiId"}, + "Stage": {"Ref": "StageName"} + } + } + }, + "Outputs": { + "CertArn": {"Value": {"Ref": "Cert"}}, + "DomainRef": {"Value": {"Ref": "ApiDomain"}}, + "DomainNameArn": {"Value": {"Fn::GetAtt": ["ApiDomain", "DomainNameArn"]}}, + "RegionalDomainName": {"Value": {"Fn::GetAtt": ["ApiDomain", "RegionalDomainName"]}}, + "RegionalHostedZoneId": {"Value": {"Fn::GetAtt": ["ApiDomain", "RegionalHostedZoneId"]}}, + "DistributionDomainName": {"Value": {"Fn::GetAtt": ["ApiDomain", "DistributionDomainName"]}}, + "DistributionHostedZoneId": {"Value": {"Fn::GetAtt": ["ApiDomain", "DistributionHostedZoneId"]}}, + "MappingRef": {"Value": {"Ref": "Mapping"}} + } + } + """; + + /** The REST API lives in the stack, as it does when one template owns the whole API. */ + private static final String INLINE_API_TEMPLATE = """ + { + "Resources": { + "Api": { + "Type": "AWS::ApiGateway::RestApi", + "Properties": {"Name": "apigw-domain-cfn-inline-it"} + }, + "ApiDomain": { + "Type": "AWS::ApiGateway::DomainName", + "Properties": { + "DomainName": "%s", + "RegionalCertificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555" + } + }, + "Mapping": { + "Type": "AWS::ApiGateway::BasePathMapping", + "Properties": {"DomainName": {"Ref": "ApiDomain"}, "RestApiId": {"Ref": "Api"}} + } + }, + "Outputs": { + "ApiId": {"Value": {"Ref": "Api"}}, + "MappingRef": {"Value": {"Ref": "Mapping"}} + } + } + """.formatted(INLINE_DOMAIN); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void domainStackExposesRealAttributesRoutesRequestsUpdatesInPlaceReplacesOnRenameAndDeletes() throws Exception { + String apiId = createMockApi("apigw-domain-cfn-it-api"); + String deploymentId = createDeployment(apiId); + createStage(apiId, "prod", deploymentId); + createStage(apiId, "dev", deploymentId); + + cloudFormation(STACK, "CreateStack", TEMPLATE, parameters(apiId, "prod", DOMAIN, "TLS_1_2", "created")); + + String stacks = describeStacks(STACK, "CREATE_COMPLETE"); + String certificateArn = outputValue(stacks, "CertArn"); + assertTrue(certificateArn.startsWith("arn:aws:acm:us-east-1:"), certificateArn); + assertEquals(DOMAIN, outputValue(stacks, "DomainRef")); + assertEquals("arn:aws:apigateway:us-east-1::/domainnames/" + DOMAIN, outputValue(stacks, "DomainNameArn")); + assertEquals(DOMAIN + "|v1", outputValue(stacks, "MappingRef")); + assertEquals("", outputValue(stacks, "DistributionDomainName"), + "a regional domain has no distribution, and must not resolve to the literal attribute name"); + assertEquals("", outputValue(stacks, "DistributionHostedZoneId")); + + ValidatableResponse domain = getDomain(DOMAIN).statusCode(200); + String regionalDomainName = domain.extract().path("regionalDomainName"); + assertEquals(regionalDomainName, outputValue(stacks, "RegionalDomainName")); + assertEquals(domain.extract().path("regionalHostedZoneId"), outputValue(stacks, "RegionalHostedZoneId")); + domain.body("domainNameArn", equalTo(outputValue(stacks, "DomainNameArn"))) + .body("regionalCertificateArn", equalTo(certificateArn)) + .body("securityPolicy", equalTo("TLS_1_2")) + .body("endpointConfiguration.types[0]", equalTo("REGIONAL")) + .body("tags.stack", equalTo("created")); + getMapping(DOMAIN, "v1").statusCode(200) + .body("restApiId", equalTo(apiId)) + .body("stage", equalTo("prod")); + invokeThroughDomain(DOMAIN, "/v1/items"); + + // Everything but the name updates in place: the domain keeps its identity and its regional + // name, which is what a DNS record outside the stack points at. + cloudFormation(STACK, "UpdateStack", TEMPLATE, parameters(apiId, "dev", DOMAIN, "TLS_1_0", "updated")); + + stacks = describeStacks(STACK, "UPDATE_COMPLETE"); + assertEquals(DOMAIN, outputValue(stacks, "DomainRef")); + assertEquals(DOMAIN + "|v1", outputValue(stacks, "MappingRef")); + assertEquals(regionalDomainName, outputValue(stacks, "RegionalDomainName")); + getDomain(DOMAIN).statusCode(200) + .body("regionalDomainName", equalTo(regionalDomainName)) + .body("regionalCertificateArn", equalTo(certificateArn)) + .body("securityPolicy", equalTo("TLS_1_0")) + .body("tags.stack", equalTo("updated")); + getMapping(DOMAIN, "v1").statusCode(200).body("stage", equalTo("dev")); + invokeThroughDomain(DOMAIN, "/v1/items"); + + // Moving to EDGE is also in place: the domain keeps its identity and regional name, and the + // distribution attributes a DNS alias for an edge domain points at appear. + cloudFormation(STACK, "UpdateStack", TEMPLATE, + parameters(apiId, "dev", DOMAIN, "TLS_1_0", "updated", "EDGE")); + + stacks = describeStacks(STACK, "UPDATE_COMPLETE"); + assertEquals(DOMAIN, outputValue(stacks, "DomainRef")); + assertEquals(regionalDomainName, outputValue(stacks, "RegionalDomainName")); + String distribution = outputValue(stacks, "DistributionDomainName"); + assertTrue(distribution.endsWith(".cloudfront.net"), "an edge domain has a distribution: " + distribution); + assertEquals("Z2FDTNDATAQYW2", outputValue(stacks, "DistributionHostedZoneId")); + getDomain(DOMAIN).statusCode(200) + .body("endpointConfiguration.types[0]", equalTo("EDGE")) + .body("distributionDomainName", equalTo(distribution)); + invokeThroughDomain(DOMAIN, "/v1/items"); + + // And back: a regional domain has no distribution, so the attributes empty again. + cloudFormation(STACK, "UpdateStack", TEMPLATE, parameters(apiId, "dev", DOMAIN, "TLS_1_0", "updated")); + + stacks = describeStacks(STACK, "UPDATE_COMPLETE"); + assertEquals("", outputValue(stacks, "DistributionDomainName")); + assertEquals("", outputValue(stacks, "DistributionHostedZoneId")); + getDomain(DOMAIN).statusCode(200) + .body("endpointConfiguration.types[0]", equalTo("REGIONAL")) + .body("distributionDomainName", nullValue()); + + // DomainName is createOnly: a new name is a replacement, created before the old domain goes, + // and the mapping follows it because its DomainName is createOnly too. + cloudFormation(STACK, "UpdateStack", TEMPLATE, parameters(apiId, "dev", RENAMED_DOMAIN, "TLS_1_0", "updated")); + + stacks = describeStacks(STACK, "UPDATE_COMPLETE"); + assertEquals(RENAMED_DOMAIN, outputValue(stacks, "DomainRef")); + assertEquals(RENAMED_DOMAIN + "|v1", outputValue(stacks, "MappingRef")); + assertEquals(certificateArn, outputValue(stacks, "CertArn"), "the wildcard certificate is kept"); + getDomain(DOMAIN).statusCode(404); + getDomain(RENAMED_DOMAIN).statusCode(200) + .body("regionalCertificateArn", equalTo(certificateArn)) + .body("securityPolicy", equalTo("TLS_1_0")); + getMapping(RENAMED_DOMAIN, "v1").statusCode(200) + .body("restApiId", equalTo(apiId)) + .body("stage", equalTo("dev")); + invokeThroughDomain(RENAMED_DOMAIN, "/v1/items"); + + cloudFormation(STACK, "DeleteStack", null, Map.of()); + awaitStackDeleted(STACK); + + getDomain(RENAMED_DOMAIN).statusCode(404); + getMapping(RENAMED_DOMAIN, "v1").statusCode(404); + awsAction("CertificateManager", "DescribeCertificate", "{\"CertificateArn\": \"" + certificateArn + "\"}") + .then().statusCode(404); + deleteApi(apiId); + } + + @Test + void mappingWithoutABasePathOntoAnApiInTheSameStackIsCreatedAndDeletedWithIt() throws Exception { + cloudFormation(INLINE_API_STACK, "CreateStack", INLINE_API_TEMPLATE, Map.of()); + + String stacks = describeStacks(INLINE_API_STACK, "CREATE_COMPLETE"); + String apiId = outputValue(stacks, "ApiId"); + assertEquals(INLINE_DOMAIN + "|(none)", outputValue(stacks, "MappingRef"), + "an omitted BasePath is the API's (none)"); + getMapping(INLINE_DOMAIN, "(none)").statusCode(200) + .body("restApiId", equalTo(apiId)) + .body("stage", nullValue()); + + cloudFormation(INLINE_API_STACK, "DeleteStack", null, Map.of()); + awaitStackDeleted(INLINE_API_STACK); + + getDomain(INLINE_DOMAIN).statusCode(404); + given().when().get("/restapis/" + apiId).then().statusCode(404); + } + + private static Map parameters(String apiId, String stage, String domain, + String securityPolicy, String tagValue) { + return parameters(apiId, stage, domain, securityPolicy, tagValue, "REGIONAL"); + } + + private static Map parameters(String apiId, String stage, String domain, + String securityPolicy, String tagValue, String endpointType) { + return Map.of("ApiId", apiId, "StageName", stage, "Domain", domain, + "SecurityPolicy", securityPolicy, "TagValue", tagValue, "EndpointType", endpointType); + } + + private static void cloudFormation(String stack, String action, String templateBody, + Map parameters) { + RequestSpecification request = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", action) + .formParam("StackName", stack); + if (templateBody != null) { + request.formParam("TemplateBody", templateBody); + } + int index = 1; + for (Map.Entry parameter : parameters.entrySet()) { + request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey()); + request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue()); + index++; + } + request.when().post("/").then().statusCode(200); + } + + private static String describeStacks(String stack, String expectedStatus) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stack) + .when().post("/").then().statusCode(200) + .body(containsString("" + expectedStatus + "")) + .extract().asString(); + } + + /** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */ + private static void awaitStackDeleted(String stack) throws InterruptedException { + for (int i = 0; i < 100; i++) { + String body = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stack) + .when().post("/").then().extract().asString(); + if (body.contains("does not exist")) { + return; + } + if (body.contains("DELETE_FAILED")) { + fail("stack delete failed: " + body); + } + Thread.sleep(50); + } + fail("stack " + stack + " was not deleted within the timeout"); + } + + private static String outputValue(String xml, String key) { + return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key); + } + + private static ValidatableResponse getDomain(String domain) { + return given().when().get("/domainnames/" + domain).then(); + } + + private static ValidatableResponse getMapping(String domain, String basePath) { + return given().when().get("/domainnames/" + domain + "/basepathmappings/" + basePath).then(); + } + + /** The custom domain filter routes on the Host header, the way a DNS alias would deliver the request. */ + private static void invokeThroughDomain(String domain, String path) { + given().header("Host", domain).when().get(path).then() + .statusCode(200) + .body("message", equalTo("via-custom-domain")); + } + + /** A REST API whose GET /items is a MOCK integration answering a fixed JSON body. */ + private static String createMockApi(String name) { + String apiId = given().contentType(ContentType.JSON).body("{\"name\":\"" + name + "\"}") + .when().post("/restapis").then().statusCode(201).extract().path("id"); + String rootId = given().when().get("/restapis/" + apiId + "/resources") + .then().statusCode(200).extract().path("item[0].id"); + String resourceId = given().contentType(ContentType.JSON).body("{\"pathPart\":\"items\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId).then().statusCode(201).extract().path("id"); + String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET"; + given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}") + .when().put(method).then().statusCode(201); + given().contentType(ContentType.JSON).body("{\"responseParameters\":{}}") + .when().put(method + "/responses/200").then().statusCode(201); + given().contentType(ContentType.JSON) + .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}") + .when().put(method + "/integration").then().statusCode(201); + given().contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":" + + "\"{\\\"message\\\":\\\"via-custom-domain\\\"}\"}}") + .when().put(method + "/integration/responses/200").then().statusCode(201); + return apiId; + } + + private static String createDeployment(String apiId) { + return given().contentType(ContentType.JSON).body("{\"description\":\"v1\"}") + .when().post("/restapis/" + apiId + "/deployments").then().statusCode(201).extract().path("id"); + } + + private static void createStage(String apiId, String stage, String deploymentId) { + given().contentType(ContentType.JSON) + .body("{\"stageName\":\"" + stage + "\",\"deploymentId\":\"" + deploymentId + "\"}") + .when().post("/restapis/" + apiId + "/stages").then().statusCode(201); + } + + private static void deleteApi(String apiId) { + given().when().delete("/restapis/" + apiId).then().statusCode(202); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 388156e1e0..74dbeb07d8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.sqs.SqsService; import io.github.hectorvent.floci.services.wafv2.WafV2Service; import io.github.hectorvent.floci.services.cloudformation.provisioners.AcmCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayAccountCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayDomainCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner; @@ -233,6 +234,7 @@ final class CfnProvisionerFixture { } if (apiGatewayService != null) { discovered.add(new ApiGatewayAccountCfnProvisioner(apiGatewayService)); + discovered.add(new ApiGatewayDomainCfnProvisioner(apiGatewayService)); } if (autoScalingService != null) { discovered.add(new AutoScalingLifecycleHookCfnProvisioner(autoScalingService)); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisionerTest.java new file mode 100644 index 0000000000..981d0d28aa --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayDomainCfnProvisionerTest.java @@ -0,0 +1,535 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +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.model.BasePathMapping; +import io.github.hectorvent.floci.services.apigateway.model.CustomDomain; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The API Gateway custom domain provisioner in isolation: one mocked service. Every case asserts + * the exact physical id and the exact {@code Fn::GetAtt} attribute keys, since an unmapped type + * still reports CREATE_COMPLETE through the dispatcher's stub arm. + */ +class ApiGatewayDomainCfnProvisionerTest { + + private static final String DOMAIN_TYPE = "AWS::ApiGateway::DomainName"; + private static final String MAPPING_TYPE = "AWS::ApiGateway::BasePathMapping"; + private static final String REGION = "us-east-1"; + private static final String DOMAIN = "api.example.com"; + private static final String DOMAIN_ARN = "arn:aws:apigateway:us-east-1::/domainnames/api.example.com"; + private static final String CERTIFICATE_ARN = + "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555"; + private static final String RENEWED_CERTIFICATE_ARN = + "arn:aws:acm:us-east-1:000000000000:certificate/99999999-2222-3333-4444-555555555555"; + private static final String API_ID = "abc123def4"; + private static final AwsException NOT_FOUND = + new AwsException("NotFoundException", "Invalid domain name identifier specified", 404); + + private final ApiGatewayService apiGateway = mock(ApiGatewayService.class); + private final ApiGatewayDomainCfnProvisioner provisioner = new ApiGatewayDomainCfnProvisioner(apiGateway); + private final ObjectMapper mapper = new ObjectMapper(); + + private ProvisionContext ctx() { + return ctx(null); + } + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null || node.isMissingNode() || node.isNull() ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId); + } + + private static StackResource resource(String type) { + StackResource r = new StackResource(); + r.setLogicalId("Res"); + r.setResourceType(type); + r.setAttributes(new HashMap<>()); + return r; + } + + private static StackResource resource(String type, String physicalId) { + StackResource r = resource(type); + r.setPhysicalId(physicalId); + return r; + } + + private static CustomDomain regionalDomain(String name) { + CustomDomain d = new CustomDomain(); + d.setDomainName(name); + d.setEndpointConfigurationType("REGIONAL"); + d.setRegionalCertificateArn(CERTIFICATE_ARN); + d.setSecurityPolicy("TLS_1_2"); + d.setRegionalDomainName(name + ".regional.local"); + d.setRegionalHostedZoneId("Z2FDTNDATAQYL2"); + d.setTags(new LinkedHashMap<>(Map.of("stack", "my-stack"))); + return d; + } + + private static BasePathMapping mapping(String basePath, String apiId, String stage) { + return new BasePathMapping(basePath, apiId, stage); + } + + private ObjectNode domainProps(String certificateArn, String securityPolicy) { + ObjectNode props = mapper.createObjectNode() + .put("DomainName", DOMAIN) + .put("RegionalCertificateArn", certificateArn) + .put("SecurityPolicy", securityPolicy); + props.putObject("EndpointConfiguration").putArray("Types").add("REGIONAL"); + props.putArray("Tags").addObject().put("Key", "stack").put("Value", "my-stack"); + return props; + } + + private ObjectNode mappingProps(String basePath, String apiId, String stage) { + ObjectNode props = mapper.createObjectNode().put("DomainName", DOMAIN).put("RestApiId", apiId); + if (basePath != null) { + props.put("BasePath", basePath); + } + if (stage != null) { + props.put("Stage", stage); + } + return props; + } + + private static Map replace(String path, String value) { + return Map.of("op", "replace", "path", path, "value", value); + } + + @Test + void servesBothTypes() { + assertEquals(Set.of(DOMAIN_TYPE, MAPPING_TYPE), provisioner.resourceTypes()); + } + + @Test + void regionalDomainSetsDomainAsPhysicalIdAndAllFiveAttributes() { + when(apiGateway.createDomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN)); + StackResource r = resource(DOMAIN_TYPE); + + provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx()); + + @SuppressWarnings("unchecked") + ArgumentCaptor> request = ArgumentCaptor.forClass(Map.class); + verify(apiGateway).createDomainName(eq(REGION), request.capture()); + assertEquals(Map.of( + "domainName", DOMAIN, + "endpointConfiguration", Map.of("types", List.of("REGIONAL")), + "regionalCertificateArn", CERTIFICATE_ARN, + "securityPolicy", "TLS_1_2", + "tags", Map.of("stack", "my-stack")), request.getValue()); + assertEquals(DOMAIN, r.getPhysicalId()); + assertEquals(Map.of( + "DomainNameArn", DOMAIN_ARN, + "RegionalDomainName", "api.example.com.regional.local", + "RegionalHostedZoneId", "Z2FDTNDATAQYL2", + "DistributionDomainName", "", + "DistributionHostedZoneId", ""), r.getAttributes()); + } + + @Test + void edgeDomainExposesItsDistribution() { + CustomDomain edge = regionalDomain(DOMAIN); + edge.setEndpointConfigurationType("EDGE"); + edge.setDistributionDomainName("d1234567890abc.cloudfront.net"); + edge.setDistributionHostedZoneId("Z2FDTNDATAQYW2"); + when(apiGateway.createDomainName(eq(REGION), anyMap())).thenReturn(edge); + ObjectNode props = mapper.createObjectNode().put("DomainName", DOMAIN).put("CertificateArn", CERTIFICATE_ARN); + props.putObject("EndpointConfiguration").putArray("Types").add("EDGE"); + StackResource r = resource(DOMAIN_TYPE); + + provisioner.provision(r, props, ctx()); + + @SuppressWarnings("unchecked") + ArgumentCaptor> request = ArgumentCaptor.forClass(Map.class); + verify(apiGateway).createDomainName(eq(REGION), request.capture()); + assertEquals(Map.of( + "domainName", DOMAIN, + "endpointConfiguration", Map.of("types", List.of("EDGE")), + "certificateArn", CERTIFICATE_ARN), request.getValue()); + assertEquals("d1234567890abc.cloudfront.net", r.getAttributes().get("DistributionDomainName")); + assertEquals("Z2FDTNDATAQYW2", r.getAttributes().get("DistributionHostedZoneId")); + } + + @Test + void createWhenTheDomainNameIsAlreadyTakenFailsWithoutTouchingIt() { + // Domain names are unique across regions, so a template naming one that exists outside the + // stack fails the resource, as on AWS, and never deletes what it did not create. + when(apiGateway.createDomainName(eq(REGION), anyMap())) + .thenThrow(new AwsException("BadRequestException", "The domain name you provided already exists.", 400)); + StackResource r = resource(DOMAIN_TYPE); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx())); + + assertEquals("BadRequestException", failure.getErrorCode()); + verify(apiGateway, never()).deleteDomainName(any(), any()); + assertEquals(null, r.getPhysicalId()); + } + + @Test + void resourcesWithoutPropertiesAreRejected() { + assertThrows(IllegalArgumentException.class, () -> provisioner.provision(resource(DOMAIN_TYPE), null, ctx())); + assertThrows(IllegalArgumentException.class, () -> provisioner.provision(resource(MAPPING_TYPE), null, ctx())); + + verify(apiGateway, never()).createDomainName(any(), anyMap()); + verify(apiGateway, never()).createBasePathMapping(any(), any(), anyMap()); + } + + @Test + void domainRequiresDomainName() { + ObjectNode props = mapper.createObjectNode().put("RegionalCertificateArn", CERTIFICATE_ARN); + + assertThrows(IllegalArgumentException.class, () -> provisioner.provision(resource(DOMAIN_TYPE), props, ctx())); + + verify(apiGateway, never()).createDomainName(any(), anyMap()); + } + + @Test + void updateWithUnchangedDomainPatchesWhatChangedInPlace() { + CustomDomain existing = regionalDomain(DOMAIN); + when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(existing); + CustomDomain patched = regionalDomain(DOMAIN); + patched.setRegionalCertificateArn(RENEWED_CERTIFICATE_ARN); + patched.setSecurityPolicy("TLS_1_0"); + when(apiGateway.updateDomainName(eq(REGION), eq(DOMAIN), anyList())).thenReturn(patched); + StackResource r = resource(DOMAIN_TYPE, DOMAIN); + + provisioner.provision(r, domainProps(RENEWED_CERTIFICATE_ARN, "TLS_1_0"), ctx(DOMAIN)); + + verify(apiGateway).updateDomainName(REGION, DOMAIN, List.of( + replace("/regionalCertificateArn", RENEWED_CERTIFICATE_ARN), + replace("/securityPolicy", "TLS_1_0"))); + verify(apiGateway, never()).createDomainName(any(), anyMap()); + verify(apiGateway, never()).deleteDomainName(any(), any()); + assertEquals(DOMAIN, r.getPhysicalId()); + assertEquals("api.example.com.regional.local", r.getAttributes().get("RegionalDomainName")); + } + + @Test + void updateWithNothingChangedDoesNotPatch() { + when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(regionalDomain(DOMAIN)); + StackResource r = resource(DOMAIN_TYPE, DOMAIN); + + provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(DOMAIN)); + + verify(apiGateway, never()).updateDomainName(any(), any(), anyList()); + verify(apiGateway, never()).untagDomainName(any(), any(), anyList()); + verify(apiGateway, never()).tagDomainName(any(), any(), anyMap()); + assertEquals(Map.of( + "DomainNameArn", DOMAIN_ARN, + "RegionalDomainName", "api.example.com.regional.local", + "RegionalHostedZoneId", "Z2FDTNDATAQYL2", + "DistributionDomainName", "", + "DistributionHostedZoneId", ""), r.getAttributes()); + } + + @Test + void updateNamesTheCurrentEndpointTypeInThePatchPath() { + // AWS's patch path names the type the domain has now; the value is the type it should get. + when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(regionalDomain(DOMAIN)); + when(apiGateway.updateDomainName(eq(REGION), eq(DOMAIN), anyList())).thenReturn(regionalDomain(DOMAIN)); + ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2"); + props.putObject("EndpointConfiguration").putArray("Types").add("EDGE"); + + provisioner.provision(resource(DOMAIN_TYPE, DOMAIN), props, ctx(DOMAIN)); + + verify(apiGateway).updateDomainName(REGION, DOMAIN, + List.of(replace("/endpointConfiguration/types/REGIONAL", "EDGE"))); + } + + @Test + void updateDrivesTagsToTheTemplate() { + CustomDomain existing = regionalDomain(DOMAIN); + existing.setTags(new LinkedHashMap<>(Map.of("stack", "my-stack", "owner", "old"))); + when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(existing); + ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2"); + props.putArray("Tags").addObject().put("Key", "stack").put("Value", "my-stack"); + props.withArray("Tags").addObject().put("Key", "team").put("Value", "api"); + + provisioner.provision(resource(DOMAIN_TYPE, DOMAIN), props, ctx(DOMAIN)); + + verify(apiGateway).untagDomainName(REGION, DOMAIN, List.of("owner")); + verify(apiGateway).tagDomainName(REGION, DOMAIN, Map.of("stack", "my-stack", "team", "api")); + } + + @Test + void updateWithoutTagsRemovesTheStoredOnes() { + when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(regionalDomain(DOMAIN)); + ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2"); + props.remove("Tags"); + + provisioner.provision(resource(DOMAIN_TYPE, DOMAIN), props, ctx(DOMAIN)); + + verify(apiGateway).untagDomainName(REGION, DOMAIN, List.of("stack")); + verify(apiGateway, never()).tagDomainName(any(), any(), anyMap()); + } + + @Test + void updateWithChangedDomainReplacesIt() { + when(apiGateway.getDomainName(REGION, "old.example.com")).thenReturn(regionalDomain("old.example.com")); + when(apiGateway.createDomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN)); + StackResource r = resource(DOMAIN_TYPE, "old.example.com"); + + provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx("old.example.com")); + + verify(apiGateway).createDomainName(eq(REGION), anyMap()); + verify(apiGateway).deleteDomainName(REGION, "old.example.com"); + verify(apiGateway, never()).updateDomainName(any(), any(), anyList()); + assertEquals(DOMAIN, r.getPhysicalId()); + assertEquals("api.example.com.regional.local", r.getAttributes().get("RegionalDomainName")); + } + + @Test + void updateWhosePriorDomainIsGoneCreatesItAgain() { + when(apiGateway.getDomainName(REGION, DOMAIN)).thenThrow(NOT_FOUND); + when(apiGateway.createDomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN)); + StackResource r = resource(DOMAIN_TYPE, DOMAIN); + + provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(DOMAIN)); + + verify(apiGateway).createDomainName(eq(REGION), anyMap()); + verify(apiGateway, never()).updateDomainName(any(), any(), anyList()); + verify(apiGateway, never()).deleteDomainName(any(), any()); + assertEquals(DOMAIN, r.getPhysicalId()); + } + + @Test + void updateWhosePriorDomainIsGoneUnderANewNameCreatesWithoutDeleting() { + when(apiGateway.getDomainName(REGION, "old.example.com")).thenThrow(NOT_FOUND); + when(apiGateway.createDomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN)); + StackResource r = resource(DOMAIN_TYPE, "old.example.com"); + + provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx("old.example.com")); + + verify(apiGateway).createDomainName(eq(REGION), anyMap()); + verify(apiGateway, never()).deleteDomainName(any(), any()); + assertEquals(DOMAIN, r.getPhysicalId()); + } + + @Test + void updateThatFailsValidationLeavesTagsUntouched() { + // The patch carries the validation, so it runs first: a rejected update must not have + // already rewritten the domain's tags. + CustomDomain existing = regionalDomain(DOMAIN); + when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(existing); + when(apiGateway.updateDomainName(eq(REGION), eq(DOMAIN), anyList())) + .thenThrow(new AwsException("BadRequestException", "Invalid value for endpoint type: PRIVATE", 400)); + ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2"); + props.putObject("EndpointConfiguration").putArray("Types").add("PRIVATE"); + props.withArray("Tags").addObject().put("Key", "team").put("Value", "api"); + + assertThrows(AwsException.class, () -> provisioner.provision(resource(DOMAIN_TYPE, DOMAIN), props, ctx(DOMAIN))); + + verify(apiGateway, never()).tagDomainName(any(), any(), anyMap()); + verify(apiGateway, never()).untagDomainName(any(), any(), anyList()); + } + + @Test + void replacementToleratesAPriorDomainThatIsAlreadyGone() { + when(apiGateway.getDomainName(REGION, "old.example.com")).thenReturn(regionalDomain("old.example.com")); + when(apiGateway.createDomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN)); + doThrow(NOT_FOUND).when(apiGateway).deleteDomainName(REGION, "old.example.com"); + StackResource r = resource(DOMAIN_TYPE, "old.example.com"); + + assertDoesNotThrow(() -> provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx("old.example.com"))); + assertEquals(DOMAIN, r.getPhysicalId()); + } + + @Test + void domainDeleteToleratesAnAlreadyDeletedDomain() { + doThrow(NOT_FOUND).when(apiGateway).deleteDomainName(REGION, DOMAIN); + + assertDoesNotThrow(() -> provisioner.delete(DOMAIN_TYPE, DOMAIN, REGION)); + } + + @Test + void domainDeletePropagatesOtherFailures() { + doThrow(new AwsException("BadRequestException", "Domain is in use", 400)) + .when(apiGateway).deleteDomainName(REGION, DOMAIN); + + assertThrows(AwsException.class, () -> provisioner.delete(DOMAIN_TYPE, DOMAIN, REGION)); + } + + @Test + void mappingPhysicalIdJoinsDomainAndBasePathWithAPipe() { + StackResource r = resource(MAPPING_TYPE); + + provisioner.provision(r, mappingProps("v1", API_ID, "prod"), ctx()); + + verify(apiGateway).createBasePathMapping(REGION, DOMAIN, + Map.of("basePath", "v1", "restApiId", API_ID, "stage", "prod")); + assertEquals("api.example.com|v1", r.getPhysicalId()); + assertEquals(Map.of(), r.getAttributes()); + } + + @Test + void mappingWithoutBasePathUsesTheApiSpellingOfNone() { + StackResource r = resource(MAPPING_TYPE); + + provisioner.provision(r, mappingProps(null, API_ID, null), ctx()); + + verify(apiGateway).createBasePathMapping(REGION, DOMAIN, Map.of("basePath", "(none)", "restApiId", API_ID)); + assertEquals("api.example.com|(none)", r.getPhysicalId()); + } + + @Test + void mappingRequiresDomainNameAndRestApiId() { + assertThrows(IllegalArgumentException.class, () -> provisioner.provision( + resource(MAPPING_TYPE), mapper.createObjectNode().put("RestApiId", API_ID), ctx())); + assertThrows(IllegalArgumentException.class, () -> provisioner.provision( + resource(MAPPING_TYPE), mapper.createObjectNode().put("DomainName", DOMAIN), ctx())); + + verify(apiGateway, never()).createBasePathMapping(any(), any(), anyMap()); + } + + @Test + void mappingUpdateWithSameIdentityPatchesApiAndStageInPlace() { + when(apiGateway.getBasePathMapping(REGION, DOMAIN, "v1")).thenReturn(mapping("v1", API_ID, "prod")); + StackResource r = resource(MAPPING_TYPE, "api.example.com|v1"); + + provisioner.provision(r, mappingProps("v1", "newapi1234", "dev"), ctx("api.example.com|v1")); + + verify(apiGateway).updateBasePathMapping(REGION, DOMAIN, "v1", + List.of(replace("/restApiId", "newapi1234"), replace("/stage", "dev"))); + verify(apiGateway, never()).createBasePathMapping(any(), any(), anyMap()); + verify(apiGateway, never()).deleteBasePathMapping(any(), any(), any()); + assertEquals("api.example.com|v1", r.getPhysicalId()); + } + + @Test + void mappingUpdateThatDropsStagePatchesOnlyWhatTheTemplateNames() { + // The PATCH API cannot unset a stage, so an omitted Stage keeps the stored one rather than + // sending a replace with no value, which the service rejects. + when(apiGateway.getBasePathMapping(REGION, DOMAIN, "v1")).thenReturn(mapping("v1", API_ID, "prod")); + + provisioner.provision(resource(MAPPING_TYPE, "api.example.com|v1"), + mappingProps("v1", "newapi1234", null), ctx("api.example.com|v1")); + + verify(apiGateway).updateBasePathMapping(REGION, DOMAIN, "v1", List.of(replace("/restApiId", "newapi1234"))); + } + + @Test + void mappingUpdateWithNothingChangedDoesNotPatch() { + when(apiGateway.getBasePathMapping(REGION, DOMAIN, "v1")).thenReturn(mapping("v1", API_ID, "prod")); + + provisioner.provision(resource(MAPPING_TYPE, "api.example.com|v1"), + mappingProps("v1", API_ID, "prod"), ctx("api.example.com|v1")); + + verify(apiGateway, never()).updateBasePathMapping(any(), any(), any(), anyList()); + } + + @Test + void mappingUpdateWithChangedBasePathReplacesIt() { + when(apiGateway.getBasePathMapping(REGION, DOMAIN, "v1")).thenReturn(mapping("v1", API_ID, "prod")); + StackResource r = resource(MAPPING_TYPE, "api.example.com|v1"); + + provisioner.provision(r, mappingProps("v2", API_ID, "prod"), ctx("api.example.com|v1")); + + verify(apiGateway).createBasePathMapping(REGION, DOMAIN, + Map.of("basePath", "v2", "restApiId", API_ID, "stage", "prod")); + verify(apiGateway).deleteBasePathMapping(REGION, DOMAIN, "v1"); + verify(apiGateway, never()).updateBasePathMapping(any(), any(), any(), anyList()); + assertEquals("api.example.com|v2", r.getPhysicalId()); + } + + @Test + void mappingUpdateWhosePriorMappingIsGoneCreatesItAgain() { + when(apiGateway.getBasePathMapping(REGION, DOMAIN, "v1")).thenThrow(NOT_FOUND); + StackResource r = resource(MAPPING_TYPE, "api.example.com|v1"); + + provisioner.provision(r, mappingProps("v1", API_ID, "prod"), ctx("api.example.com|v1")); + + verify(apiGateway).createBasePathMapping(REGION, DOMAIN, + Map.of("basePath", "v1", "restApiId", API_ID, "stage", "prod")); + verify(apiGateway, never()).deleteBasePathMapping(any(), any(), any()); + assertEquals("api.example.com|v1", r.getPhysicalId()); + } + + @Test + void mappingUpdateWhosePriorIsGoneUnderANewIdCreatesWithoutDeleting() { + when(apiGateway.getBasePathMapping(REGION, DOMAIN, "v1")).thenThrow(NOT_FOUND); + StackResource r = resource(MAPPING_TYPE, "api.example.com|v1"); + + provisioner.provision(r, mappingProps("v2", API_ID, "prod"), ctx("api.example.com|v1")); + + verify(apiGateway).createBasePathMapping(REGION, DOMAIN, + Map.of("basePath", "v2", "restApiId", API_ID, "stage", "prod")); + verify(apiGateway, never()).deleteBasePathMapping(any(), any(), any()); + assertEquals("api.example.com|v2", r.getPhysicalId()); + } + + @Test + void mappingDeleteSplitsTheCompositeId() { + provisioner.delete(MAPPING_TYPE, "api.example.com|(none)", REGION); + + verify(apiGateway).deleteBasePathMapping(REGION, DOMAIN, "(none)"); + } + + @Test + void mappingDeleteToleratesAnAlreadyDeletedMapping() { + // The domain's delete removes its mappings first, so a mapping deleted after its domain is gone. + doThrow(NOT_FOUND).when(apiGateway).deleteBasePathMapping(REGION, DOMAIN, "v1"); + + assertDoesNotThrow(() -> provisioner.delete(MAPPING_TYPE, "api.example.com|v1", REGION)); + } + + @Test + void mappingDeletePropagatesOtherFailures() { + doThrow(new AwsException("BadRequestException", "Invalid patch", 400)) + .when(apiGateway).deleteBasePathMapping(REGION, DOMAIN, "v1"); + + assertThrows(AwsException.class, () -> provisioner.delete(MAPPING_TYPE, "api.example.com|v1", REGION)); + } + + @Test + void mappingDeleteAnswersNotFoundForAnIdWithoutTheSeparator() { + // Nothing this provisioner creates has such an id, so there is nothing to remove: the stack + // path treats NotFoundException as already deleted, and Cloud Control reports it as such. + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.delete(MAPPING_TYPE, DOMAIN, REGION)); + + assertEquals("NotFoundException", failure.getErrorCode()); + verify(apiGateway, never()).deleteBasePathMapping(any(), any(), any()); + } + + @Test + void mappingUpdateWhosePriorIdIsMalformedCreatesTheMapping() { + // A stack persisted before this provisioner existed carries the stub arm's generated id. + StackResource r = resource(MAPPING_TYPE, "Mapping-1a2b3c4d"); + + provisioner.provision(r, mappingProps("v1", API_ID, "prod"), ctx("Mapping-1a2b3c4d")); + + verify(apiGateway).createBasePathMapping(REGION, DOMAIN, + Map.of("basePath", "v1", "restApiId", API_ID, "stage", "prod")); + verify(apiGateway, never()).deleteBasePathMapping(any(), any(), any()); + assertEquals("api.example.com|v1", r.getPhysicalId()); + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 933d0003f1..4324b03ff2 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -1,6 +1,8 @@ AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner AWS::ApiGateway::Authorizer LEGACY_SWITCH +AWS::ApiGateway::BasePathMapping ApiGatewayDomainCfnProvisioner AWS::ApiGateway::Deployment LEGACY_SWITCH +AWS::ApiGateway::DomainName ApiGatewayDomainCfnProvisioner AWS::ApiGateway::Method LEGACY_SWITCH AWS::ApiGateway::Resource LEGACY_SWITCH AWS::ApiGateway::RestApi LEGACY_SWITCH diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 1f4d9b18ea..969d8662c8 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -85,7 +85,7 @@ type_order: AWS::ElasticLoadBalancingV2: [LoadBalancer, TargetGroup, Listener, ListenerRule] AWS::AutoScaling: [LaunchConfiguration, AutoScalingGroup, LifecycleHook] AWS::Route53: [HostedZone, RecordSet] - AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account] + AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account, DomainName, BasePathMapping] AWS::ApiGatewayV2: [Api, Authorizer, Route, Integration, Stage, Deployment] AWS::CodePipeline: [Pipeline, CustomActionType, Webhook] AWS::Batch: [ComputeEnvironment, JobQueue, JobDefinition]