mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+333
@@ -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<Future<?>> 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<String, String> 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<Future<?>> 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);
|
||||
}
|
||||
}
|
||||
+367
@@ -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<String, String> parameters(String apiId, String stage, String domain,
|
||||
String securityPolicy, String tagValue) {
|
||||
return parameters(apiId, stage, domain, securityPolicy, tagValue, "REGIONAL");
|
||||
}
|
||||
|
||||
private static Map<String, String> 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<String, String> 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<String, String> 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("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.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("<StackStatus>DELETE_FAILED</StackStatus>")) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
@@ -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));
|
||||
|
||||
+535
@@ -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<String, String> 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<Map<String, Object>> 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<Map<String, Object>> 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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user