mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): provision AWS::ApiGatewayV2::DomainName and ApiMapping (#5038)
* refactor(apigateway): move the v2 domain and API mapping rules into the service CreateDomainName and CreateApiMapping on /v2/domainnames kept their rules in ApiGatewayController: the one-configuration check, the refusal of inputs Floci does not emulate, the flattening onto the shared custom-domain store, the API and stage existence check, the mapping key conflict check, the API type the mapping is routed as, and the mapping id. A CloudFormation provisioner cannot reach a controller, so it would have had to copy them. They now live in ApiGatewayService. createV2DomainName validates the body and creates the domain; createApiMapping checks the API and stage, refuses a key that is taken and routes the mapping as the API's protocol type; getApiMapping, deleteApiMapping and apiMappingId follow. ApiGatewayService takes ApiGatewayV2Service for the API and stage lookup, so the whole rule sits in one place and a caller needs one service. Nothing on the v2 side depends on the v1 service, so this adds no cycle. Leaving the lookup in ApiGatewayV2Service was tried first, but then every caller had to resolve the API before calling into ApiGatewayService, and the rule was split across two classes again. The code is moved, not rewritten: messages, error codes, the order of the checks and the id scheme are unchanged, and the controller delegates. * feat(cloudformation): provision AWS::ApiGatewayV2::DomainName and ApiMapping Both types were left to the stub arm. A stack reported CREATE_COMPLETE, but no domain or mapping existed, Fn::GetAtt on the domain resolved to literals such as DomainResource.RegionalDomainName (so a Route 53 alias built from it pointed nowhere), and with allow-stub-unsupported-resource-types off the stack rolled back. ApiGatewayV2DomainCfnProvisioner creates them through the v2 rules in ApiGatewayService and injects only that service. Ref on a domain is its name and Fn::GetAtt returns DomainNameArn, RegionalDomainName and RegionalHostedZoneId as GetDomainName reports them. Ref on a mapping is its ApiMappingId, which is also its only attribute. Updates follow AWS. DomainName is the only createOnly property of either type, and everything else changes in place: the domain's configuration is replaced as a whole, as DomainNameConfigurations is on AWS, and a mapping's ApiId, Stage and ApiMappingKey change without a new id. To keep the id across a key change, a mapping now stores the apiMappingId it was given instead of deriving it from its key on every read. A record persisted before is still read under the derived id, and a new mapping gets the id it always had unless another mapping holds it. Deriving the id and documenting the difference was the first version; it was dropped because Ref changed where AWS keeps it, and the change set already reported the key change as an update. A replacement creates the new entity and leaves the displaced one to ReplacementCleanup, so it is deleted in UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, kept under UpdateReplacePolicy: Retain, and put back when a later resource fails the update. The first version deleted the old domain inside provision, as the v1 provisioner does, and a failed rename then ended in UPDATE_ROLLBACK_FAILED with the original domain and its mappings already gone. A mapping moved to another domain gets an id the displaced mapping does not hold, since two mappings under one physical id cannot be told apart, and the domain of each displaced id is recorded beside the cleanup. An in-place update snapshots what it changes, so a failed stack update restores it instead of ending in UPDATE_ROLLBACK_FAILED. CDK templates needed the v2 rules to match AWS in two more places. apigateway.DomainName with a multi-level basePath maps a REST API through AWS::ApiGatewayV2::ApiMapping, so a mapping now accepts a REST API stage. And the restrictions AWS documents for API mappings are enforced, in the API and in templates alike: no v2 call on an edge-optimized domain, with AWS's message; TLS_1_2 for an HTTP API or a multi-level key, which also keeps such a domain on TLS_1_2; no WebSocket API beside an HTTP or REST API; and AWS's key characters and length. The id-only delete accepts <ApiMappingId>|<DomainName>, the type's primary identifier, which is how Cloud Control names a mapping; a bare id still answers NotFoundException, so Cloud Control cannot report a delete that did not happen. The integration test deploys two templates aws-cdk-lib 2.272.0 synthesized, checked in with the app that produced them, and compat-cdk deploys the same shapes. * fix(apigateway): answer v2 domain and API mapping calls as API Gateway does The review of this PR found four places where Floci answered differently from API Gateway. Each was measured against API Gateway in eu-west-1 on 2026-10-04, with an imported certificate on a throwaway domain. An HTTP API custom domain is regional. CreateDomainName and UpdateDomainName with an endpoint type of PRIVATE, or one API Gateway does not know, give a REGIONAL domain, where Floci refused the first and stored the type on an update. EDGE is refused with "EDGE endpoint type is not supported for APIGatewayV2 domainName", not the message for v2 calls on an existing edge-optimized domain. API mapping keys are checked as API Gateway checks them, with its messages: a key does not end with '/', does not start with '/' or hold '//', holds letters, digits and $-_.+!*'(), between its levels, and is at most 300 characters. No key, an empty one, or on a create one of whitespace only, is the root; an update refuses whitespace only. Floci took "/" for the root and had its own message for the characters, without the comma. UpdateApiMapping and UpdateDomainName answer over the v2 HTTP API, not only from CloudFormation. What an UpdateApiMapping leaves out keeps its value. Cloud Control identifies an AWS::ApiGatewayV2::ApiMapping by the type's primary identifier, <ApiMappingId>|<DomainName>, while CloudFormation's Ref stays the bare id: CloudControlService derives the identifier from the desired state, as it already names primary identifier fields by type, and the provisioner deletes by it with the create-time attributes too. * fix(apigateway): refuse a v2 update of an edge domain, and recover a compound identifier whole The second review pass found three gaps in the previous commit. UpdateDomainName through the v2 API converted a v1-created edge-optimized domain to REGIONAL. The v2 API does not manage an edge-optimized domain, so the update is refused with the message every other v2 call on one gets, and the CloudFormation in-place update goes through the same check. A v2 UpdateDomainName without a configuration returned the domain unchanged without looking at the rest of the body, so a mutual TLS request was silently dropped. ApiGatewayService.updateV2DomainName now refuses what Floci does not emulate, and the edge-optimized domain, either way. Cloud Control's recovery of a create that finished just before a restart took the identifier after the last '|' of its key, which for an API mapping's <ApiMappingId>|<DomainName> left only the domain. It now takes everything after the key's third separator. A later review pass found four more points. UpdateApiMapping fills in what its body leaves out under the lock the update takes, so two partial updates of one mapping cannot write back each other's old values. A v2 domain's certificate is stored as the v1 API's regional certificate, which is what a regional domain reports through both APIs; a domain the v2 API wrote before still reports the one it holds until its configuration is replaced. The domain ARN both APIs and both CloudFormation provisioners build comes from ApiGatewayService.domainNameArn, the Cloud Control test waits with the awaitSuccess helper main has since gained, and requireMappingAllowed's javadoc is back on it.
This commit is contained in:
1 parent
b1bb016b6e
commit
85e0061a6f
27 files changed
+3729
-169
No files matched your search
+424
@@ -0,0 +1,424 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.TlsCertificateManager;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The v2 custom domain and API mapping rules, over real services and in-memory stores: the id a
|
||||
* mapping is given and keeps, the APIs it can point at, and the restrictions AWS documents for API
|
||||
* mappings (a regional domain, the TLS 1.2 security policy for an HTTP API or a key with more than
|
||||
* one level, no WebSocket API beside an HTTP or REST API, the characters and length of a key).
|
||||
*/
|
||||
class ApiGatewayV2ApiMappingServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String DOMAIN = "api.example.com";
|
||||
private static final String OTHER_DOMAIN = "other.example.com";
|
||||
private static final String CERTIFICATE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/abc";
|
||||
private static final String EDGE_MESSAGE = "Only REGIONAL domain names can be managed through the API Gateway V2 "
|
||||
+ "API. For EDGE domain names, please use the API Gateway V1 API. Also note that only REST APIs can be "
|
||||
+ "attached to EDGE domain names.";
|
||||
|
||||
private static final String V2_EDGE_ENDPOINT_MESSAGE = "EDGE endpoint type is not supported for APIGatewayV2 "
|
||||
+ "domainName";
|
||||
|
||||
private ApiGatewayService service;
|
||||
private ApiGatewayV2Service v2Service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
when(storageFactory.create(anyString(), anyString(), any()))
|
||||
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().cloudfront().domainSuffix()).thenReturn("cloudfront.net");
|
||||
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
v2Service = new ApiGatewayV2Service(storageFactory, config, regionResolver);
|
||||
service = new ApiGatewayService(storageFactory, config, mock(TlsCertificateManager.class), regionResolver,
|
||||
v2Service);
|
||||
}
|
||||
|
||||
private void v2Domain(String name) {
|
||||
service.createV2DomainName(REGION, Map.of("domainName", name,
|
||||
"domainNameConfigurations", List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "REGIONAL"))));
|
||||
}
|
||||
|
||||
/** A domain as the v1 API creates it, which can carry what the v2 API cannot. */
|
||||
private void v1Domain(String name, String endpointType, String securityPolicy) {
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("domainName", name);
|
||||
request.put("regionalCertificateArn", CERTIFICATE_ARN);
|
||||
request.put("certificateArn", CERTIFICATE_ARN);
|
||||
request.put("endpointConfiguration", Map.of("types", List.of(endpointType)));
|
||||
request.put("securityPolicy", securityPolicy);
|
||||
service.createDomainName(REGION, request);
|
||||
}
|
||||
|
||||
private String api(String protocolType, String stage) {
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("name", protocolType.toLowerCase() + "-api");
|
||||
request.put("protocolType", protocolType);
|
||||
if ("WEBSOCKET".equals(protocolType)) {
|
||||
request.put("routeSelectionExpression", "$request.body.action");
|
||||
}
|
||||
String apiId = v2Service.createApi(REGION, request).getApiId();
|
||||
v2Service.createStage(REGION, apiId, Map.of("stageName", stage));
|
||||
return apiId;
|
||||
}
|
||||
|
||||
private String restApi(String stage) {
|
||||
String apiId = service.createRestApi(REGION, Map.of("name", "rest-api")).getId();
|
||||
service.createDeployment(REGION, apiId, Map.of("stageName", stage));
|
||||
return apiId;
|
||||
}
|
||||
|
||||
private static void assertBadRequest(String message, Runnable call) {
|
||||
AwsException failure = assertThrows(AwsException.class, call::run);
|
||||
assertEquals("BadRequestException", failure.getErrorCode());
|
||||
assertEquals(400, failure.getHttpStatus());
|
||||
if (message != null) {
|
||||
assertEquals(message, failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMappingKeepsItsIdWhenItsKeyChanges() {
|
||||
v2Domain(DOMAIN);
|
||||
String apiId = api("HTTP", "$default");
|
||||
StoredMapping created = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default");
|
||||
|
||||
StoredMapping updated = service.updateApiMapping(REGION, DOMAIN, created.apiMappingId(), "v2", apiId, "$default");
|
||||
|
||||
assertEquals(created.apiMappingId(), updated.apiMappingId());
|
||||
assertEquals("v2", updated.storedPath());
|
||||
assertEquals("v2", service.getApiMapping(REGION, DOMAIN, created.apiMappingId()).storedPath());
|
||||
assertEquals(1, service.getApiMappings(REGION, DOMAIN).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyAnotherMappingMovedOffGetsAnIdOfItsOwn() {
|
||||
v2Domain(DOMAIN);
|
||||
String apiId = api("HTTP", "$default");
|
||||
String first = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default").apiMappingId();
|
||||
service.updateApiMapping(REGION, DOMAIN, first, "v2", apiId, "$default");
|
||||
|
||||
String second = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default").apiMappingId();
|
||||
|
||||
assertNotEquals(first, second);
|
||||
assertEquals("v2", service.getApiMapping(REGION, DOMAIN, first).storedPath());
|
||||
assertEquals("v1", service.getApiMapping(REGION, DOMAIN, second).storedPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExcludedIdIsNotHandedOut() {
|
||||
v2Domain(DOMAIN);
|
||||
String apiId = api("HTTP", "$default");
|
||||
String derived = ApiGatewayService.apiMappingId("v1");
|
||||
|
||||
String id = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default", Set.of(derived)).apiMappingId();
|
||||
|
||||
assertNotEquals(derived, id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyChangeOntoATakenKeyConflicts() {
|
||||
v2Domain(DOMAIN);
|
||||
String apiId = api("HTTP", "$default");
|
||||
String first = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default").apiMappingId();
|
||||
service.createApiMapping(REGION, DOMAIN, "v2", apiId, "$default");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> service.updateApiMapping(REGION, DOMAIN, first, "v2", apiId, "$default"));
|
||||
|
||||
assertEquals("ConflictException", failure.getErrorCode());
|
||||
assertEquals("v1", service.getApiMapping(REGION, DOMAIN, first).storedPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestApiCanBeMappedUnderAKeyWithSeveralLevels() {
|
||||
v2Domain(DOMAIN);
|
||||
String apiId = restApi("prod");
|
||||
|
||||
StoredMapping created = service.createApiMapping(REGION, DOMAIN, "orders/v1/items", apiId, "prod");
|
||||
|
||||
assertEquals("REST", created.mapping().getApiType());
|
||||
assertEquals(apiId, service.resolveBasePathMapping(DOMAIN, "/orders/v1/items/123").getRestApiId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anApiOrStageThatDoesNotExistIsRefused() {
|
||||
v2Domain(DOMAIN);
|
||||
String httpApi = api("HTTP", "$default");
|
||||
String restApi = restApi("prod");
|
||||
|
||||
assertBadRequest("Invalid API identifier specified: nope",
|
||||
() -> service.createApiMapping(REGION, DOMAIN, "a", "nope", "$default"));
|
||||
assertBadRequest("Invalid stage identifier specified",
|
||||
() -> service.createApiMapping(REGION, DOMAIN, "b", httpApi, "missing"));
|
||||
assertBadRequest("Invalid stage identifier specified",
|
||||
() -> service.createApiMapping(REGION, DOMAIN, "c", restApi, "missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEdgeDomainCannotBeManagedThroughTheV2Api() {
|
||||
v1Domain(DOMAIN, "EDGE", "TLS_1_2");
|
||||
String restApi = restApi("prod");
|
||||
|
||||
assertBadRequest(EDGE_MESSAGE, () -> service.createApiMapping(REGION, DOMAIN, "v1", restApi, "prod"));
|
||||
assertBadRequest(EDGE_MESSAGE, () -> service.getApiMappings(REGION, DOMAIN));
|
||||
assertBadRequest(V2_EDGE_ENDPOINT_MESSAGE, () -> service.createV2DomainName(REGION, Map.of("domainName",
|
||||
OTHER_DOMAIN, "domainNameConfigurations", List.of(Map.of("endpointType", "EDGE")))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Measured against API Gateway (eu-west-1, 2026-10-04): an HTTP API custom domain is regional.
|
||||
* A create or update with an endpoint type of PRIVATE or one API Gateway does not know gives a
|
||||
* REGIONAL domain; EDGE is refused.
|
||||
*/
|
||||
@Test
|
||||
void aV2DomainIsRegionalWhateverOtherEndpointTypeItIsGiven() {
|
||||
service.createV2DomainName(REGION, Map.of("domainName", DOMAIN, "domainNameConfigurations",
|
||||
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "PRIVATE"))));
|
||||
assertEquals("REGIONAL", service.getDomainName(REGION, DOMAIN).getEndpointConfigurationType());
|
||||
|
||||
service.replaceV2DomainConfiguration(REGION, DOMAIN, Map.of("domainNameConfigurations",
|
||||
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "FOO"))));
|
||||
assertEquals("REGIONAL", service.getDomainName(REGION, DOMAIN).getEndpointConfigurationType());
|
||||
|
||||
assertBadRequest(V2_EDGE_ENDPOINT_MESSAGE, () -> service.replaceV2DomainConfiguration(REGION, DOMAIN,
|
||||
Map.of("domainNameConfigurations",
|
||||
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "EDGE")))));
|
||||
assertEquals("REGIONAL", service.getDomainName(REGION, DOMAIN).getEndpointConfigurationType());
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateDomainName through the v2 API is a v2 call like the others: refused on an
|
||||
* edge-optimized domain, and refused for what Floci does not emulate even without a
|
||||
* configuration to replace.
|
||||
*/
|
||||
@Test
|
||||
void aV2UpdateRefusesAnEdgeDomainAndWhatIsNotEmulated() {
|
||||
v1Domain(DOMAIN, "EDGE", "TLS_1_2");
|
||||
assertBadRequest(EDGE_MESSAGE, () -> service.updateV2DomainName(REGION, DOMAIN, Map.of(
|
||||
"domainNameConfigurations",
|
||||
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "endpointType", "REGIONAL")))));
|
||||
assertEquals("EDGE", service.getDomainName(REGION, DOMAIN).getEndpointConfigurationType());
|
||||
|
||||
v2Domain(OTHER_DOMAIN);
|
||||
assertBadRequest("Mutual TLS authentication is not supported", () -> service.updateV2DomainName(REGION,
|
||||
OTHER_DOMAIN, Map.of("mutualTlsAuthentication", Map.of("truststoreUri", "s3://bucket/key"))));
|
||||
assertEquals(OTHER_DOMAIN, service.updateV2DomainName(REGION, OTHER_DOMAIN, Map.of()).getDomainName());
|
||||
}
|
||||
|
||||
/** Measured against API Gateway (eu-west-1, 2026-10-04), its messages included. */
|
||||
@Test
|
||||
void anApiMappingKeyIsCheckedAsApiGatewayChecksIt() {
|
||||
v2Domain(DOMAIN);
|
||||
String httpApi = api("HTTP", "prod");
|
||||
String endSlash = "API mapping key should not end with a '/'.";
|
||||
String slashes = "API mapping key should not start with a '/' or have consecutive '/'s.";
|
||||
String characters = "An API mapping key may contain only letters, numbers and one of $-_.+!*'(), characters.";
|
||||
|
||||
assertBadRequest(endSlash, () -> service.createApiMapping(REGION, DOMAIN, "/", httpApi, "prod"));
|
||||
assertBadRequest(endSlash, () -> service.createApiMapping(REGION, DOMAIN, "a/", httpApi, "prod"));
|
||||
assertBadRequest(slashes, () -> service.createApiMapping(REGION, DOMAIN, "/a", httpApi, "prod"));
|
||||
assertBadRequest(slashes, () -> service.createApiMapping(REGION, DOMAIN, "a//b", httpApi, "prod"));
|
||||
assertBadRequest(characters, () -> service.createApiMapping(REGION, DOMAIN, " a", httpApi, "prod"));
|
||||
assertBadRequest(characters, () -> service.createApiMapping(REGION, DOMAIN, "a~b", httpApi, "prod"));
|
||||
assertBadRequest("ApiMapping key length must be under 300 characters.",
|
||||
() -> service.createApiMapping(REGION, DOMAIN, "a".repeat(301), httpApi, "prod"));
|
||||
|
||||
assertEquals("a,b$", service.createApiMapping(REGION, DOMAIN, "a,b$", httpApi, "prod").storedPath());
|
||||
assertEquals("a".repeat(300),
|
||||
service.createApiMapping(REGION, DOMAIN, "a".repeat(300), httpApi, "prod").storedPath());
|
||||
// A key of whitespace only is the root on a create, and refused on an update.
|
||||
assertEquals("(none)", ApiGatewayService.canonicalBasePath(
|
||||
service.createApiMapping(REGION, DOMAIN, " ", httpApi, "prod").storedPath()));
|
||||
String id = service.createApiMapping(REGION, DOMAIN, "v1", httpApi, "prod").apiMappingId();
|
||||
assertBadRequest(slashes, () -> service.updateApiMapping(REGION, DOMAIN, id, " ", httpApi, "prod"));
|
||||
assertBadRequest(endSlash, () -> service.updateApiMapping(REGION, DOMAIN, id, "/", httpApi, "prod"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anHttpApiNeedsTheTls12SecurityPolicy() {
|
||||
v1Domain(DOMAIN, "REGIONAL", "TLS_1_0");
|
||||
String httpApi = api("HTTP", "$default");
|
||||
String restApi = restApi("prod");
|
||||
|
||||
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "http", httpApi, "$default"));
|
||||
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "orders/v1", restApi, "prod"));
|
||||
assertEquals("REST", service.createApiMapping(REGION, DOMAIN, "orders", restApi, "prod").mapping().getApiType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDomainWithAnHttpApiMappingStaysOnTls12() {
|
||||
v2Domain(DOMAIN);
|
||||
String httpApi = api("HTTP", "$default");
|
||||
service.createApiMapping(REGION, DOMAIN, null, httpApi, "$default");
|
||||
|
||||
assertBadRequest(null, () -> service.replaceV2DomainConfiguration(REGION, DOMAIN, Map.of("domainName", DOMAIN,
|
||||
"domainNameConfigurations", List.of(Map.of("certificateArn", CERTIFICATE_ARN,
|
||||
"endpointType", "REGIONAL", "securityPolicy", "TLS_1_0")))));
|
||||
assertBadRequest(null, () -> service.updateDomainName(REGION, DOMAIN,
|
||||
List.of(Map.of("op", "replace", "path", "/securityPolicy", "value", "TLS_1_0"))));
|
||||
assertEquals("TLS_1_2", service.getDomainName(REGION, DOMAIN).getSecurityPolicy());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWebSocketApiDoesNotShareADomainWithAnHttpOrRestApi() {
|
||||
v2Domain(DOMAIN);
|
||||
v2Domain(OTHER_DOMAIN);
|
||||
String webSocketApi = api("WEBSOCKET", "prod");
|
||||
String httpApi = api("HTTP", "$default");
|
||||
String restApi = restApi("prod");
|
||||
service.createApiMapping(REGION, DOMAIN, "ws", webSocketApi, "prod");
|
||||
service.createApiMapping(REGION, OTHER_DOMAIN, "http", httpApi, "$default");
|
||||
|
||||
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "http", httpApi, "$default"));
|
||||
assertBadRequest(null, () -> service.createBasePathMapping(REGION, DOMAIN,
|
||||
Map.of("basePath", "rest", "restApiId", restApi, "stage", "prod")));
|
||||
assertBadRequest(null, () -> service.createApiMapping(REGION, OTHER_DOMAIN, "ws", webSocketApi, "prod"));
|
||||
service.createApiMapping(REGION, DOMAIN, "ws2", webSocketApi, "prod");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyHoldsOnlyTheCharactersAwsAllowsUpTo300OfThem() {
|
||||
v2Domain(DOMAIN);
|
||||
String apiId = api("HTTP", "$default");
|
||||
|
||||
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "v1?x", apiId, "$default"));
|
||||
assertBadRequest(null, () -> service.createApiMapping(REGION, DOMAIN, "a".repeat(301), apiId, "$default"));
|
||||
service.createApiMapping(REGION, DOMAIN, "a".repeat(300), apiId, "$default");
|
||||
service.createApiMapping(REGION, DOMAIN, "$-_.+!*'()/x", apiId, "$default");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatingAMappingOntoAnotherKindOfApiRoutesItAsThatKind() {
|
||||
v2Domain(DOMAIN);
|
||||
String httpApi = api("HTTP", "$default");
|
||||
String restApi = restApi("prod");
|
||||
String id = service.createApiMapping(REGION, DOMAIN, "v1", httpApi, "$default").apiMappingId();
|
||||
|
||||
StoredMapping updated = service.updateApiMapping(REGION, DOMAIN, id, "v1", restApi, "prod");
|
||||
|
||||
assertEquals("REST", updated.mapping().getApiType());
|
||||
assertEquals(restApi, service.getApiMapping(REGION, DOMAIN, id).mapping().getRestApiId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacingADomainConfigurationReplacesItAsAWhole() {
|
||||
service.createV2DomainName(REGION, Map.of("domainName", DOMAIN, "domainNameConfigurations",
|
||||
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "certificateName", "named",
|
||||
"endpointType", "REGIONAL", "securityPolicy", "TLS_1_0"))));
|
||||
|
||||
CustomDomain replaced = service.replaceV2DomainConfiguration(REGION, DOMAIN, Map.of("domainName", DOMAIN,
|
||||
"domainNameConfigurations", List.of(Map.of("certificateArn", CERTIFICATE_ARN))));
|
||||
|
||||
assertEquals(CERTIFICATE_ARN, replaced.getRegionalCertificateArn());
|
||||
assertNull(replaced.getRegionalCertificateName(), "a field the configuration leaves out is cleared");
|
||||
assertEquals("TLS_1_2", replaced.getSecurityPolicy(), "an omitted security policy takes the default");
|
||||
assertEquals("REGIONAL", replaced.getEndpointConfigurationType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aV2DomainKeepsItsCertificateAsTheRegionalOne() {
|
||||
service.createV2DomainName(REGION, Map.of("domainName", DOMAIN, "domainNameConfigurations",
|
||||
List.of(Map.of("certificateArn", CERTIFICATE_ARN, "certificateName", "named"))));
|
||||
|
||||
CustomDomain domain = service.getDomainName(REGION, DOMAIN);
|
||||
|
||||
assertEquals(CERTIFICATE_ARN, domain.getRegionalCertificateArn());
|
||||
assertEquals("named", domain.getRegionalCertificateName());
|
||||
assertNull(domain.getCertificateArn(), "the edge-optimized certificate is not the regional domain's");
|
||||
assertNull(domain.getCertificateName());
|
||||
assertEquals(CERTIFICATE_ARN, ApiGatewayService.v2CertificateArn(domain));
|
||||
assertEquals("named", ApiGatewayService.v2CertificateName(domain));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theV2ApiReportsTheCertificateOfTheDomainsEndpointType() {
|
||||
Map<String, Object> regional = new HashMap<>();
|
||||
regional.put("domainName", DOMAIN);
|
||||
regional.put("regionalCertificateArn", CERTIFICATE_ARN);
|
||||
regional.put("endpointConfiguration", Map.of("types", List.of("REGIONAL")));
|
||||
service.createDomainName(REGION, regional);
|
||||
Map<String, Object> edge = new HashMap<>();
|
||||
edge.put("domainName", OTHER_DOMAIN);
|
||||
edge.put("certificateArn", "arn:aws:acm:us-east-1:000000000000:certificate/edge");
|
||||
edge.put("regionalCertificateArn", CERTIFICATE_ARN);
|
||||
edge.put("endpointConfiguration", Map.of("types", List.of("EDGE")));
|
||||
service.createDomainName(REGION, edge);
|
||||
|
||||
assertEquals(CERTIFICATE_ARN, ApiGatewayService.v2CertificateArn(service.getDomainName(REGION, DOMAIN)));
|
||||
assertEquals("arn:aws:acm:us-east-1:000000000000:certificate/edge",
|
||||
ApiGatewayService.v2CertificateArn(service.getDomainName(REGION, OTHER_DOMAIN)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDomainTheV2ApiWroteToTheEdgeFieldsKeepsItsCertificateUntilItIsReplaced() {
|
||||
// How a v2 create stored a regional domain's certificate before it went to the regional fields.
|
||||
Map<String, Object> earlier = new HashMap<>();
|
||||
earlier.put("domainName", DOMAIN);
|
||||
earlier.put("certificateArn", CERTIFICATE_ARN);
|
||||
earlier.put("certificateName", "earlier");
|
||||
earlier.put("endpointConfiguration", Map.of("types", List.of("REGIONAL")));
|
||||
service.createDomainName(REGION, earlier);
|
||||
assertEquals(CERTIFICATE_ARN, ApiGatewayService.v2CertificateArn(service.getDomainName(REGION, DOMAIN)));
|
||||
assertEquals("earlier", ApiGatewayService.v2CertificateName(service.getDomainName(REGION, DOMAIN)));
|
||||
|
||||
CustomDomain replaced = service.replaceV2DomainConfiguration(REGION, DOMAIN, Map.of("domainName", DOMAIN,
|
||||
"domainNameConfigurations", List.of(Map.of("securityPolicy", "TLS_1_2"))));
|
||||
|
||||
assertNull(replaced.getCertificateArn(), "the configuration is replaced as a whole");
|
||||
assertNull(replaced.getCertificateName());
|
||||
assertNull(ApiGatewayService.v2CertificateArn(replaced));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateBodyKeepsWhatItLeavesOut() {
|
||||
v2Domain(DOMAIN);
|
||||
String apiId = api("HTTP", "$default");
|
||||
v2Service.createStage(REGION, apiId, Map.of("stageName", "beta"));
|
||||
String id = service.createApiMapping(REGION, DOMAIN, "v1", apiId, "$default").apiMappingId();
|
||||
|
||||
StoredMapping rekeyed = service.updateApiMapping(REGION, DOMAIN, id,
|
||||
Map.of("apiId", apiId, "apiMappingKey", "v2"));
|
||||
assertEquals("v2", rekeyed.storedPath());
|
||||
assertEquals("$default", rekeyed.mapping().getStage(), "a stage the body leaves out is kept");
|
||||
|
||||
StoredMapping restaged = service.updateApiMapping(REGION, DOMAIN, id, Map.of("apiId", apiId, "stage", "beta"));
|
||||
assertEquals("v2", restaged.storedPath(), "a key the body leaves out is kept");
|
||||
assertEquals("beta", restaged.mapping().getStage());
|
||||
|
||||
Map<String, Object> toRoot = new HashMap<>();
|
||||
toRoot.put("apiId", apiId);
|
||||
toRoot.put("apiMappingKey", null);
|
||||
assertEquals("(none)", service.updateApiMapping(REGION, DOMAIN, id, toRoot).storedPath(),
|
||||
"a key the body names as null is the root");
|
||||
assertEquals(id, service.getApiMapping(REGION, DOMAIN, id).apiMappingId());
|
||||
}
|
||||
}
|
||||
+238
@@ -13,6 +13,7 @@ import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
/**
|
||||
* Custom domain names and API mappings over the HTTP API (v2) endpoints.
|
||||
@@ -433,6 +434,243 @@ class ApiGatewayV2DomainNameIntegrationTest {
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void aRestApiCanBeMappedUnderAKeyWithSeveralLevels() {
|
||||
// AWS takes a REST API here too: the v2 API is how a REST API gets a multi-level mapping.
|
||||
String restApiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"v2-mapped-rest-api\"}")
|
||||
.when()
|
||||
.post("/restapis")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().path("id");
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"stageName\":\"prod\"}")
|
||||
.when()
|
||||
.post("/restapis/" + restApiId + "/deployments")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"domainName":"rest-multi-level.example.com","domainNameConfigurations":[
|
||||
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc","endpointType":"REGIONAL"}]}
|
||||
""")
|
||||
.when()
|
||||
.post("/v2/domainnames")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"apiId\":\"%s\",\"stage\":\"prod\",\"apiMappingKey\":\"orders/v1/items\"}".formatted(restApiId))
|
||||
.when()
|
||||
.post("/v2/domainnames/rest-multi-level.example.com/apimappings")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiId", is(restApiId))
|
||||
.body("apiMappingKey", is("orders/v1/items"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void anEdgeDomainCannotBeManagedThroughTheV2Api() {
|
||||
String message = "Only REGIONAL domain names can be managed through the API Gateway V2 API. For EDGE "
|
||||
+ "domain names, please use the API Gateway V1 API. Also note that only REST APIs can be attached "
|
||||
+ "to EDGE domain names.";
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"domainName":"edge-only.example.com",
|
||||
"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc",
|
||||
"endpointConfiguration":{"types":["EDGE"]}}
|
||||
""")
|
||||
.when()
|
||||
.post("/domainnames")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/v2/domainnames/edge-only.example.com/apimappings")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("message", is(message));
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"domainName":"edge-v2.example.com","domainNameConfigurations":[{"endpointType":"EDGE"}]}
|
||||
""")
|
||||
.when()
|
||||
.post("/v2/domainnames")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
// Measured against API Gateway (eu-west-1, 2026-10-04): a v2 create names the endpoint type.
|
||||
.body("message", is("EDGE endpoint type is not supported for APIGatewayV2 domainName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(13)
|
||||
void anHttpApiIsMappedOnlyOntoADomainOnTls12() {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"domainName":"tls10.example.com",
|
||||
"regionalCertificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc",
|
||||
"endpointConfiguration":{"types":["REGIONAL"]},"securityPolicy":"TLS_1_0"}
|
||||
""")
|
||||
.when()
|
||||
.post("/domainnames")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"apiId\":\"%s\",\"stage\":\"$default\"}".formatted(apiId))
|
||||
.when()
|
||||
.post("/v2/domainnames/tls10.example.com/apimappings")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("TLS 1.2"));
|
||||
}
|
||||
|
||||
/** Measured against API Gateway (eu-west-1, 2026-10-04): what an update leaves out keeps its value. */
|
||||
@Test
|
||||
@Order(14)
|
||||
void updateApiMappingChangesOnlyWhatItNames() {
|
||||
String domain = "patch-mapping.example.com";
|
||||
createRegionalDomain(domain);
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"stageName\":\"s2\"}")
|
||||
.when()
|
||||
.post("/v2/apis/" + apiId + "/stages")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
String id = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"apiId\":\"%s\",\"stage\":\"$default\",\"apiMappingKey\":\"patched\"}".formatted(apiId))
|
||||
.when()
|
||||
.post("/v2/domainnames/" + domain + "/apimappings")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().path("apiMappingId");
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"apiId\":\"%s\",\"stage\":\"s2\"}".formatted(apiId))
|
||||
.when()
|
||||
.patch("/v2/domainnames/" + domain + "/apimappings/" + id)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiMappingId", is(id))
|
||||
.body("apiMappingKey", is("patched"))
|
||||
.body("stage", is("s2"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"apiId\":\"%s\",\"apiMappingKey\":\"patched-again\"}".formatted(apiId))
|
||||
.when()
|
||||
.patch("/v2/domainnames/" + domain + "/apimappings/" + id)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiMappingId", is(id))
|
||||
.body("apiMappingKey", is("patched-again"))
|
||||
.body("stage", is("s2"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"apiId\":\"%s\"}".formatted(apiId))
|
||||
.when()
|
||||
.patch("/v2/domainnames/" + domain + "/apimappings/zzzzzz")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
/** Measured against API Gateway (eu-west-1, 2026-10-04): an HTTP API domain stays regional. */
|
||||
@Test
|
||||
@Order(14)
|
||||
void updateDomainNameKeepsTheDomainRegional() {
|
||||
String domain = "patch-domain.example.com";
|
||||
createRegionalDomain(domain);
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"domainNameConfigurations":[
|
||||
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/def","endpointType":"PRIVATE"}]}
|
||||
""")
|
||||
.when()
|
||||
.patch("/v2/domainnames/" + domain)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainNameConfigurations[0].endpointType", is("REGIONAL"))
|
||||
.body("domainNameConfigurations[0].certificateArn", containsString("certificate/def"));
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"domainNameConfigurations":[
|
||||
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/def","endpointType":"EDGE"}]}
|
||||
""")
|
||||
.when()
|
||||
.patch("/v2/domainnames/" + domain)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("message", is("EDGE endpoint type is not supported for APIGatewayV2 domainName"));
|
||||
}
|
||||
|
||||
/** A domain is one resource: a regional one's certificate is the v1 API's regional certificate. */
|
||||
@Test
|
||||
@Order(15)
|
||||
void aRegionalDomainsCertificateIsTheSameThroughBothApis() {
|
||||
String v2Created = "cert-v2.example.com";
|
||||
createRegionalDomain(v2Created);
|
||||
given()
|
||||
.when()
|
||||
.get("/domainnames/" + v2Created)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("regionalCertificateArn", containsString("certificate/abc"))
|
||||
.body("certificateArn", nullValue());
|
||||
|
||||
String v1Created = "cert-v1.example.com";
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"domainName":"%s",
|
||||
"regionalCertificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/regional",
|
||||
"regionalCertificateName":"regional-name",
|
||||
"endpointConfiguration":{"types":["REGIONAL"]}}
|
||||
""".formatted(v1Created))
|
||||
.when()
|
||||
.post("/domainnames")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
given()
|
||||
.when()
|
||||
.get("/v2/domainnames/" + v1Created)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainNameConfigurations[0].certificateArn", containsString("certificate/regional"))
|
||||
.body("domainNameConfigurations[0].certificateName", is("regional-name"));
|
||||
}
|
||||
|
||||
private static void createRegionalDomain(String domain) {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"domainName":"%s","domainNameConfigurations":[
|
||||
{"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc","endpointType":"REGIONAL"}]}
|
||||
""".formatted(domain))
|
||||
.when()
|
||||
.post("/v2/domainnames")
|
||||
.then()
|
||||
.statusCode(201);
|
||||
}
|
||||
|
||||
private static org.hamcrest.Matcher<Iterable<? super String>> hasItemEqualTo(String value) {
|
||||
return org.hamcrest.Matchers.hasItem(equalTo(value));
|
||||
}
|
||||
|
||||
@@ -20,9 +20,9 @@ class ApiMappingIdTest {
|
||||
|
||||
@Test
|
||||
void rootLikeKeysThatWerePersistedSeparatelyKeepSeparateIds() {
|
||||
String canonical = ApiGatewayController.apiMappingId("(none)");
|
||||
String slash = ApiGatewayController.apiMappingId("/");
|
||||
String empty = ApiGatewayController.apiMappingId("");
|
||||
String canonical = ApiGatewayService.apiMappingId("(none)");
|
||||
String slash = ApiGatewayService.apiMappingId("/");
|
||||
String empty = ApiGatewayService.apiMappingId("");
|
||||
|
||||
assertNotEquals(canonical, slash);
|
||||
assertNotEquals(canonical, empty);
|
||||
@@ -32,17 +32,17 @@ class ApiMappingIdTest {
|
||||
@Test
|
||||
void everyIdIsNonEmptyAndStable() {
|
||||
// A record stored under an empty key must still produce an id a caller can put in a URL.
|
||||
assertFalse(ApiGatewayController.apiMappingId("").isEmpty());
|
||||
assertFalse(ApiGatewayController.apiMappingId(null).isEmpty());
|
||||
assertFalse(ApiGatewayService.apiMappingId("").isEmpty());
|
||||
assertFalse(ApiGatewayService.apiMappingId(null).isEmpty());
|
||||
|
||||
assertEquals(ApiGatewayController.apiMappingId("orders"),
|
||||
ApiGatewayController.apiMappingId("orders"));
|
||||
assertEquals(ApiGatewayService.apiMappingId("orders"),
|
||||
ApiGatewayService.apiMappingId("orders"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void distinctKeysSharingAJavaHashKeepDistinctIds() {
|
||||
assertEquals("Aa".hashCode(), "BB".hashCode());
|
||||
assertNotEquals(ApiGatewayController.apiMappingId("Aa"),
|
||||
ApiGatewayController.apiMappingId("BB"));
|
||||
assertNotEquals(ApiGatewayService.apiMappingId("Aa"),
|
||||
ApiGatewayService.apiMappingId("BB"));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -52,8 +52,8 @@ class LegacyBasePathMappingIntegrationTest {
|
||||
void eachRecordKeepsItsOwnIdAndDeletesItself() {
|
||||
seedLegacyState();
|
||||
|
||||
String canonicalId = ApiGatewayController.apiMappingId("(none)");
|
||||
String legacyId = ApiGatewayController.apiMappingId("");
|
||||
String canonicalId = ApiGatewayService.apiMappingId("(none)");
|
||||
String legacyId = ApiGatewayService.apiMappingId("");
|
||||
assertNotEquals(canonicalId, legacyId);
|
||||
|
||||
given()
|
||||
|
||||
+63
@@ -86,6 +86,69 @@ class CloudControlServiceTest {
|
||||
Map.of("VpcId", "vpc-account-a"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloud Control names an AWS::ApiGatewayV2::ApiMapping by the type's primary identifier,
|
||||
* {@code <ApiMappingId>|<DomainName>}, where CloudFormation's Ref is the bare ApiMappingId.
|
||||
*/
|
||||
@Test
|
||||
void anApiMappingIsIdentifiedByItsIdAndItsDomain() throws Exception {
|
||||
CfnResourceDispatcher provisioner = mock(CfnResourceDispatcher.class);
|
||||
StackResource resource = new StackResource();
|
||||
resource.setPhysicalId("abc123");
|
||||
resource.setAttributes(Map.of("ApiMappingId", "abc123"));
|
||||
when(provisioner.provisionStandalone(eq("AWS::ApiGatewayV2::ApiMapping"),
|
||||
any(), eq("us-east-1"), eq("111111111111"))).thenReturn(resource);
|
||||
CloudControlService service = new CloudControlService(
|
||||
mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class), provisioner,
|
||||
new ObjectMapper());
|
||||
String identifier = "abc123|api.example.com";
|
||||
|
||||
CloudControlService.ProgressEvent pending = service.createResource("us-east-1", "111111111111",
|
||||
"AWS::ApiGatewayV2::ApiMapping",
|
||||
"{\"DomainName\":\"api.example.com\",\"ApiId\":\"a1b2c3\",\"Stage\":\"$default\"}");
|
||||
awaitSuccess(service, "111111111111", pending.requestToken());
|
||||
assertEquals(identifier, service.requestStatus("111111111111", pending.requestToken()).identifier());
|
||||
String model = service.getResource("us-east-1", "111111111111",
|
||||
"AWS::ApiGatewayV2::ApiMapping", identifier).properties();
|
||||
assertEquals("abc123", new ObjectMapper().readTree(model).path("ApiMappingId").asText());
|
||||
|
||||
assertEquals("SUCCESS", service.deleteResource("us-east-1", "111111111111",
|
||||
"AWS::ApiGatewayV2::ApiMapping", identifier).operationStatus());
|
||||
verify(provisioner).deleteStandalone("AWS::ApiGatewayV2::ApiMapping", identifier, "us-east-1",
|
||||
Map.of("ApiMappingId", "abc123"));
|
||||
assertThrows(AwsException.class, () -> service.getResource("us-east-1", "111111111111",
|
||||
"AWS::ApiGatewayV2::ApiMapping", identifier));
|
||||
}
|
||||
|
||||
/**
|
||||
* A create that finished just before a restart is recorded while its request still reads
|
||||
* IN_PROGRESS; recovery reports it done under the whole identifier, a compound one included.
|
||||
*/
|
||||
@Test
|
||||
void aRecoveredCreateKeepsItsCompoundIdentifier() {
|
||||
AccountAwareStorageBackend<CloudControlService.PersistedRequest> requests =
|
||||
AccountAwareStorageBackend.inMemory("000000000000");
|
||||
AccountAwareStorageBackend<CloudControlService.PersistedCreatedResource> created =
|
||||
AccountAwareStorageBackend.inMemory("000000000000");
|
||||
String type = "AWS::ApiGatewayV2::ApiMapping";
|
||||
String identifier = "abc123|api.example.com";
|
||||
requests.putForAccount("111111111111", "token-1", new CloudControlService.PersistedRequest(
|
||||
new CloudControlService.ProgressEvent(type, null, "token-1", "CREATE", "IN_PROGRESS",
|
||||
null, null, "111111111111"),
|
||||
"us-east-1", "{\"DomainName\":\"api.example.com\"}", 1L));
|
||||
created.putForAccount("111111111111", "us-east-1|" + type + "|" + identifier,
|
||||
new CloudControlService.PersistedCreatedResource("token-1", "111111111111", "us-east-1", type,
|
||||
identifier, Map.of("ApiMappingId", "abc123"), "{\"ApiMappingId\":\"abc123\"}"));
|
||||
|
||||
CloudControlService restarted = new CloudControlService(
|
||||
mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class),
|
||||
mock(CfnResourceDispatcher.class), new ObjectMapper(), requests, created);
|
||||
|
||||
CloudControlService.ProgressEvent recovered = restarted.requestStatus("111111111111", "token-1");
|
||||
assertEquals("SUCCESS", recovered.operationStatus());
|
||||
assertEquals(identifier, recovered.identifier());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoresAccountOwnersAndRequestStateFromMetadataStores() throws Exception {
|
||||
CfnResourceDispatcher provisioner = mock(CfnResourceDispatcher.class);
|
||||
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
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.hasItem;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::ApiGatewayV2::DomainName} and {@code AWS::ApiGatewayV2::ApiMapping} through
|
||||
* CloudFormation, with stubbing of unsupported types turned off so a type nothing provisions fails
|
||||
* the stack instead of reporting CREATE_COMPLETE. Asserts that {@code Ref} and every
|
||||
* {@code Fn::GetAtt} attribute are what the v2 API reports, that a request sent to the custom
|
||||
* domain reaches the integration, and that updates behave as on AWS: the domain's configuration and
|
||||
* the mapping's key, API and stage change in place with the mapping keeping its id, a new domain
|
||||
* name replaces what it names with the displaced domain deleted in the cleanup phase, kept under
|
||||
* {@code UpdateReplacePolicy: Retain} and put back when a later resource fails the update.
|
||||
*
|
||||
* <p>Two more stacks are what {@code aws-cdk-lib} 2.272.0 synthesizes, checked in verbatim with the
|
||||
* app that produced them under {@code cloudformation/apigatewayv2-domain/}: an {@code HttpApi} with a
|
||||
* {@code defaultDomainMapping}, a keyed mapping and a Route 53 alias, and a REST API on a custom
|
||||
* domain under a key with several levels, which CDK maps with {@code AWS::ApiGatewayV2::ApiMapping}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(CloudFormationUnsupportedResourceTypeStrictIntegrationTest.StrictProfile.class)
|
||||
class ApiGatewayV2DomainCfnIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261002/us-east-1/cloudformation/aws4_request";
|
||||
private static final String ROUTE53_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261002/us-east-1/route53/aws4_request";
|
||||
private static final String ZONE = "apigwv2-domain-cfn-it.example.com";
|
||||
private static final String CDK_DOMAIN = "cdk." + ZONE;
|
||||
private static final String CDK_REST_DOMAIN = "rest.apigwv2-rest-cfn-it.example.com";
|
||||
private static final String BACKEND_BODY = "reached the integration";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* The domain, mapping key, mapped stage, certificate name and tag value are parameters, so one
|
||||
* template drives the create, the in-place update and the replacement. {@code Break} adds a
|
||||
* mapping onto a stage that does not exist after everything else, which fails the stack there.
|
||||
*/
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Domain": {"Type": "String"},
|
||||
"MappingKey": {"Type": "String"},
|
||||
"MappingStage": {"Type": "String"},
|
||||
"CertificateName": {"Type": "String"},
|
||||
"TagValue": {"Type": "String"},
|
||||
"BackendUrl": {"Type": "String"},
|
||||
"Break": {"Type": "String", "Default": "no"}
|
||||
},
|
||||
"Conditions": {"Breaks": {"Fn::Equals": [{"Ref": "Break"}, "yes"]}},
|
||||
"Resources": {
|
||||
"Cert": {
|
||||
"Type": "AWS::CertificateManager::Certificate",
|
||||
"Properties": {"DomainName": "*.apigwv2-domain-cfn-it.example.com", "ValidationMethod": "DNS"}
|
||||
},
|
||||
"Api": {
|
||||
"Type": "AWS::ApiGatewayV2::Api",
|
||||
"Properties": {"Name": "apigwv2-domain-cfn-it", "ProtocolType": "HTTP"}
|
||||
},
|
||||
"Backend": {
|
||||
"Type": "AWS::ApiGatewayV2::Integration",
|
||||
"Properties": {
|
||||
"ApiId": {"Ref": "Api"},
|
||||
"IntegrationType": "HTTP_PROXY",
|
||||
"IntegrationUri": {"Ref": "BackendUrl"},
|
||||
"PayloadFormatVersion": "1.0"
|
||||
}
|
||||
},
|
||||
"HelloRoute": {
|
||||
"Type": "AWS::ApiGatewayV2::Route",
|
||||
"Properties": {
|
||||
"ApiId": {"Ref": "Api"},
|
||||
"RouteKey": "GET /hello",
|
||||
"Target": {"Fn::Join": ["/", ["integrations", {"Ref": "Backend"}]]}
|
||||
}
|
||||
},
|
||||
"DefaultStage": {
|
||||
"Type": "AWS::ApiGatewayV2::Stage",
|
||||
"Properties": {"ApiId": {"Ref": "Api"}, "StageName": "$default", "AutoDeploy": true}
|
||||
},
|
||||
"ProdStage": {
|
||||
"Type": "AWS::ApiGatewayV2::Stage",
|
||||
"Properties": {"ApiId": {"Ref": "Api"}, "StageName": "prod", "AutoDeploy": true}
|
||||
},
|
||||
"ApiDomain": {
|
||||
"Type": "AWS::ApiGatewayV2::DomainName",
|
||||
"Properties": {
|
||||
"DomainName": {"Ref": "Domain"},
|
||||
"DomainNameConfigurations": [{
|
||||
"CertificateArn": {"Ref": "Cert"},
|
||||
"CertificateName": {"Ref": "CertificateName"},
|
||||
"EndpointType": "REGIONAL",
|
||||
"SecurityPolicy": "TLS_1_2"
|
||||
}],
|
||||
"Tags": {"stack": {"Ref": "TagValue"}}
|
||||
}
|
||||
},
|
||||
"Mapping": {
|
||||
"Type": "AWS::ApiGatewayV2::ApiMapping",
|
||||
"DependsOn": ["DefaultStage", "ProdStage"],
|
||||
"Properties": {
|
||||
"DomainName": {"Ref": "ApiDomain"},
|
||||
"ApiId": {"Ref": "Api"},
|
||||
"Stage": {"Ref": "MappingStage"},
|
||||
"ApiMappingKey": {"Ref": "MappingKey"}
|
||||
}
|
||||
},
|
||||
"Breaker": {
|
||||
"Type": "AWS::ApiGatewayV2::ApiMapping",
|
||||
"Condition": "Breaks",
|
||||
"DependsOn": ["Mapping"],
|
||||
"Properties": {
|
||||
"DomainName": {"Ref": "ApiDomain"},
|
||||
"ApiId": {"Ref": "Api"},
|
||||
"Stage": "no-such-stage",
|
||||
"ApiMappingKey": "broken"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"CertArn": {"Value": {"Ref": "Cert"}},
|
||||
"ApiId": {"Value": {"Ref": "Api"}},
|
||||
"DomainRef": {"Value": {"Ref": "ApiDomain"}},
|
||||
"DomainNameArn": {"Value": {"Fn::GetAtt": ["ApiDomain", "DomainNameArn"]}},
|
||||
"RegionalDomainName": {"Value": {"Fn::GetAtt": ["ApiDomain", "RegionalDomainName"]}},
|
||||
"RegionalHostedZoneId": {"Value": {"Fn::GetAtt": ["ApiDomain", "RegionalHostedZoneId"]}},
|
||||
"MappingRef": {"Value": {"Ref": "Mapping"}},
|
||||
"MappingId": {"Value": {"Fn::GetAtt": ["Mapping", "ApiMappingId"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
private static HttpServer backend;
|
||||
private static final AtomicInteger backendHits = new AtomicInteger();
|
||||
private static String backendUrl;
|
||||
|
||||
@BeforeAll
|
||||
static void startBackend() throws Exception {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
backend.createContext("/", exchange -> {
|
||||
backendHits.incrementAndGet();
|
||||
byte[] body = BACKEND_BODY.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
});
|
||||
backend.start();
|
||||
backendUrl = "http://127.0.0.1:" + backend.getAddress().getPort();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopBackend() {
|
||||
if (backend != null) {
|
||||
backend.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainAndMappingExposeRealValuesRouteRequestsUpdateInPlaceReplaceAndDelete() {
|
||||
String stack = "apigwv2-domain-lifecycle";
|
||||
String domain = "api.lifecycle." + ZONE;
|
||||
String renamed = "gateway.lifecycle." + ZONE;
|
||||
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
|
||||
|
||||
String stacks = describeStacks(stack, "CREATE_COMPLETE");
|
||||
String apiId = outputValue(stacks, "ApiId");
|
||||
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"));
|
||||
|
||||
ValidatableResponse created = getDomain(domain).statusCode(200)
|
||||
.body("domainNameArn", equalTo(outputValue(stacks, "DomainNameArn")))
|
||||
.body("domainNameConfigurations[0].certificateArn", equalTo(certificateArn))
|
||||
.body("domainNameConfigurations[0].certificateName", equalTo("first"))
|
||||
.body("domainNameConfigurations[0].endpointType", equalTo("REGIONAL"))
|
||||
.body("domainNameConfigurations[0].securityPolicy", equalTo("TLS_1_2"))
|
||||
.body("tags.stack", equalTo("created"));
|
||||
String regionalDomainName = created.extract().path("domainNameConfigurations[0].apiGatewayDomainName");
|
||||
assertEquals(regionalDomainName, outputValue(stacks, "RegionalDomainName"));
|
||||
assertEquals(created.extract().<String>path("domainNameConfigurations[0].hostedZoneId"),
|
||||
outputValue(stacks, "RegionalHostedZoneId"));
|
||||
|
||||
String mappingId = outputValue(stacks, "MappingRef");
|
||||
assertEquals(mappingId, outputValue(stacks, "MappingId"), "Ref and GetAtt ApiMappingId are the same id");
|
||||
getMappings(domain).statusCode(200).body("items.apiMappingId", hasItem(mappingId));
|
||||
getMapping(domain, mappingId).statusCode(200)
|
||||
.body("apiId", equalTo(apiId))
|
||||
.body("stage", equalTo("$default"))
|
||||
.body("apiMappingKey", equalTo("v1"));
|
||||
invokeThroughDomain(domain, "/v1/hello");
|
||||
invokeThroughDomain(regionalDomainName, "/v1/hello");
|
||||
|
||||
// The domain's configuration and tags and the mapping's key and stage all change in place,
|
||||
// as on AWS: the mapping keeps its id, and the domain the regional name a DNS alias points at.
|
||||
cloudFormation(stack, "UpdateStack", TEMPLATE, parameters(domain, "v2", "prod", "second", "updated"));
|
||||
|
||||
stacks = describeStacks(stack, "UPDATE_COMPLETE");
|
||||
assertEquals(domain, outputValue(stacks, "DomainRef"));
|
||||
assertEquals(regionalDomainName, outputValue(stacks, "RegionalDomainName"));
|
||||
assertEquals(mappingId, outputValue(stacks, "MappingRef"));
|
||||
assertEquals(mappingId, outputValue(stacks, "MappingId"));
|
||||
getDomain(domain).statusCode(200)
|
||||
.body("domainNameConfigurations[0].apiGatewayDomainName", equalTo(regionalDomainName))
|
||||
.body("domainNameConfigurations[0].certificateArn", equalTo(certificateArn))
|
||||
.body("domainNameConfigurations[0].certificateName", equalTo("second"))
|
||||
.body("tags.stack", equalTo("updated"));
|
||||
getMapping(domain, mappingId).statusCode(200)
|
||||
.body("apiMappingKey", equalTo("v2"))
|
||||
.body("stage", equalTo("prod"));
|
||||
getMappings(domain).statusCode(200).body("items.size()", equalTo(1));
|
||||
invokeThroughDomain(domain, "/v2/hello");
|
||||
assertNotRouted(domain, "/v1/hello");
|
||||
|
||||
// DomainName is createOnly on both types: the new domain and its mapping are created, and the
|
||||
// displaced ones are deleted once the update has committed.
|
||||
cloudFormation(stack, "UpdateStack", TEMPLATE, parameters(renamed, "v2", "prod", "second", "updated"));
|
||||
|
||||
stacks = describeStacks(stack, "UPDATE_COMPLETE");
|
||||
assertEquals(renamed, outputValue(stacks, "DomainRef"));
|
||||
assertEquals("arn:aws:apigateway:us-east-1::/domainnames/" + renamed, outputValue(stacks, "DomainNameArn"));
|
||||
assertEquals(certificateArn, outputValue(stacks, "CertArn"), "the wildcard certificate is kept");
|
||||
String renamedMappingId = outputValue(stacks, "MappingRef");
|
||||
assertNotEquals(mappingId, renamedMappingId, "a replaced mapping gets an id of its own");
|
||||
getDomain(domain).statusCode(404);
|
||||
getDomain(renamed).statusCode(200)
|
||||
.body("domainNameConfigurations[0].certificateArn", equalTo(certificateArn))
|
||||
.body("domainNameConfigurations[0].certificateName", equalTo("second"))
|
||||
.body("tags.stack", equalTo("updated"));
|
||||
getMapping(renamed, renamedMappingId).statusCode(200)
|
||||
.body("apiId", equalTo(apiId))
|
||||
.body("stage", equalTo("prod"))
|
||||
.body("apiMappingKey", equalTo("v2"));
|
||||
invokeThroughDomain(renamed, "/v2/hello");
|
||||
String events = stackEvents(stack);
|
||||
assertTrue(events.contains("<ResourceStatus>UPDATE_COMPLETE_CLEANUP_IN_PROGRESS</ResourceStatus>"), events);
|
||||
assertTrue(hasEvent(events, "ApiDomain", domain, "DELETE_COMPLETE"), "the displaced domain is deleted in the cleanup");
|
||||
assertTrue(hasEvent(events, "Mapping", mappingId, "DELETE_COMPLETE"), "the displaced mapping is deleted in the cleanup");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
|
||||
getDomain(renamed).statusCode(404);
|
||||
given().when().get("/v2/apis/" + apiId).then().statusCode(404);
|
||||
awsAction("CertificateManager", "DescribeCertificate", "{\"CertificateArn\": \"" + certificateArn + "\"}")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRenameALaterResourceFailsIsRolledBackToTheOriginalDomainAndMapping() {
|
||||
String stack = "apigwv2-domain-rename-rollback";
|
||||
String domain = "api.rename-rollback." + ZONE;
|
||||
String renamed = "gateway.rename-rollback." + ZONE;
|
||||
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
|
||||
String mappingId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "MappingRef");
|
||||
|
||||
Map<String, String> breaking = parameters(renamed, "v1", "$default", "first", "created");
|
||||
breaking.put("Break", "yes");
|
||||
cloudFormation(stack, "UpdateStack", TEMPLATE, breaking);
|
||||
|
||||
String stacks = describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
assertEquals(domain, outputValue(stacks, "DomainRef"));
|
||||
assertEquals(mappingId, outputValue(stacks, "MappingRef"));
|
||||
getDomain(renamed).statusCode(404);
|
||||
getDomain(domain).statusCode(200);
|
||||
getMapping(domain, mappingId).statusCode(200).body("apiMappingKey", equalTo("v1"));
|
||||
invokeThroughDomain(domain, "/v1/hello");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
getDomain(domain).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInPlaceUpdateALaterResourceFailsIsPutBack() {
|
||||
String stack = "apigwv2-domain-in-place-rollback";
|
||||
String domain = "api.in-place-rollback." + ZONE;
|
||||
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
|
||||
String mappingId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "MappingRef");
|
||||
|
||||
Map<String, String> breaking = parameters(domain, "v2", "prod", "second", "updated");
|
||||
breaking.put("Break", "yes");
|
||||
cloudFormation(stack, "UpdateStack", TEMPLATE, breaking);
|
||||
|
||||
describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
getDomain(domain).statusCode(200)
|
||||
.body("domainNameConfigurations[0].certificateName", equalTo("first"))
|
||||
.body("tags.stack", equalTo("created"));
|
||||
getMapping(domain, mappingId).statusCode(200)
|
||||
.body("apiMappingKey", equalTo("v1"))
|
||||
.body("stage", equalTo("$default"));
|
||||
getMappings(domain).statusCode(200).body("items.size()", equalTo(1));
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainKeepsTheDomainARenameDisplaced() {
|
||||
String stack = "apigwv2-domain-retain";
|
||||
String domain = "api.retain." + ZONE;
|
||||
String renamed = "gateway.retain." + ZONE;
|
||||
String template = TEMPLATE.replace("\"Type\": \"AWS::ApiGatewayV2::DomainName\",",
|
||||
"\"Type\": \"AWS::ApiGatewayV2::DomainName\", \"UpdateReplacePolicy\": \"Retain\",");
|
||||
cloudFormation(stack, "CreateStack", template, parameters(domain, "v1", "$default", "first", "created"));
|
||||
describeStacks(stack, "CREATE_COMPLETE");
|
||||
|
||||
cloudFormation(stack, "UpdateStack", template, parameters(renamed, "v1", "$default", "first", "created"));
|
||||
|
||||
describeStacks(stack, "UPDATE_COMPLETE");
|
||||
getDomain(domain).statusCode(200);
|
||||
getMappings(domain).statusCode(200).body("items.size()", equalTo(0));
|
||||
getDomain(renamed).statusCode(200);
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
getDomain(renamed).statusCode(404);
|
||||
getDomain(domain).statusCode(200);
|
||||
given().when().delete("/v2/domainnames/" + domain).then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCreateALaterResourceFailsRemovesTheDomainAndMapping() {
|
||||
String stack = "apigwv2-domain-create-rollback";
|
||||
String domain = "api.create-rollback." + ZONE;
|
||||
Map<String, String> breaking = parameters(domain, "v1", "$default", "first", "created");
|
||||
breaking.put("Break", "yes");
|
||||
|
||||
cloudFormation(stack, "CreateStack", TEMPLATE, breaking);
|
||||
|
||||
describeStacks(stack, "ROLLBACK_COMPLETE");
|
||||
getDomain(domain).statusCode(404);
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMappingDroppedFromTheTemplateIsDeleted() {
|
||||
String stack = "apigwv2-domain-drop-mapping";
|
||||
String domain = "api.drop-mapping." + ZONE;
|
||||
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
|
||||
describeStacks(stack, "CREATE_COMPLETE");
|
||||
|
||||
cloudFormation(stack, "UpdateStack", withoutMapping(), parameters(domain, "v1", "$default", "first", "created"));
|
||||
|
||||
describeStacks(stack, "UPDATE_COMPLETE");
|
||||
getDomain(domain).statusCode(200);
|
||||
getMappings(domain).statusCode(200).body("items.size()", equalTo(0));
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStackWhoseDomainWasDeletedOutsideItStillDeletes() {
|
||||
String stack = "apigwv2-domain-gone";
|
||||
String domain = "api.gone." + ZONE;
|
||||
cloudFormation(stack, "CreateStack", TEMPLATE, parameters(domain, "v1", "$default", "first", "created"));
|
||||
describeStacks(stack, "CREATE_COMPLETE");
|
||||
given().when().delete("/v2/domainnames/" + domain).then().statusCode(204);
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cdkHttpApiWithADefaultDomainMappingAKeyedMappingAndAnAliasRecord() {
|
||||
String stack = "apigwv2-domain-cdk-http";
|
||||
cloudFormation(stack, "CreateStack", template("http-api-domain.template.json"), Map.of("BackendUrl", backendUrl));
|
||||
|
||||
String stacks = describeStacks(stack, "CREATE_COMPLETE");
|
||||
String apiId = outputValue(stacks, "ApiId");
|
||||
String regionalDomainName = outputValue(stacks, "RegionalDomainName");
|
||||
getDomain(CDK_DOMAIN).statusCode(200)
|
||||
.body("domainNameConfigurations[0].apiGatewayDomainName", equalTo(regionalDomainName))
|
||||
.body("domainNameConfigurations[0].hostedZoneId", equalTo(outputValue(stacks, "RegionalHostedZoneId")));
|
||||
getMappings(CDK_DOMAIN).statusCode(200)
|
||||
.body("items.size()", equalTo(2))
|
||||
.body("items.find { it.apiMappingKey == '' }.stage", equalTo("$default"))
|
||||
.body("items.find { it.apiMappingKey == '' }.apiId", equalTo(apiId))
|
||||
.body("items.find { it.apiMappingKey == 'prod' }.stage", equalTo("prod"));
|
||||
|
||||
// The alias carries the domain's real regional name and zone, not the literal attribute
|
||||
// names an unset Fn::GetAtt would leave there.
|
||||
given().header("Authorization", ROUTE53_AUTH)
|
||||
.when().get("/2013-04-01/hostedzone/" + outputValue(stacks, "ZoneId") + "/rrset")
|
||||
.then().statusCode(200)
|
||||
.body(containsString("<DNSName>" + regionalDomainName))
|
||||
.body(containsString("<HostedZoneId>" + outputValue(stacks, "RegionalHostedZoneId") + "</HostedZoneId>"));
|
||||
|
||||
invokeThroughDomain(CDK_DOMAIN, "/anything");
|
||||
invokeThroughDomain(CDK_DOMAIN, "/prod/anything");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
getDomain(CDK_DOMAIN).statusCode(404);
|
||||
given().when().get("/v2/apis/" + apiId).then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cdkRestApiOnACustomDomainUnderAKeyWithSeveralLevels() {
|
||||
String stack = "apigwv2-domain-cdk-rest";
|
||||
cloudFormation(stack, "CreateStack", template("rest-api-multi-level-domain.template.json"),
|
||||
Map.of("BackendUrl", backendUrl));
|
||||
|
||||
String restApiId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "RestApiId");
|
||||
getMappings(CDK_REST_DOMAIN).statusCode(200)
|
||||
.body("items.size()", equalTo(1))
|
||||
.body("items[0].apiId", equalTo(restApiId))
|
||||
.body("items[0].stage", equalTo("prod"))
|
||||
.body("items[0].apiMappingKey", equalTo("orders/v1"));
|
||||
invokeThroughDomain(CDK_REST_DOMAIN, "/orders/v1/items");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null, Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
getDomain(CDK_REST_DOMAIN).statusCode(404);
|
||||
}
|
||||
|
||||
private static Map<String, String> parameters(String domain, String mappingKey, String mappingStage,
|
||||
String certificateName, String tagValue) {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("Domain", domain);
|
||||
parameters.put("MappingKey", mappingKey);
|
||||
parameters.put("MappingStage", mappingStage);
|
||||
parameters.put("CertificateName", certificateName);
|
||||
parameters.put("TagValue", tagValue);
|
||||
parameters.put("BackendUrl", backendUrl);
|
||||
return parameters;
|
||||
}
|
||||
|
||||
/** The lifecycle template with the mappings and every output naming them taken out. */
|
||||
private static String withoutMapping() {
|
||||
try {
|
||||
ObjectNode template = (ObjectNode) MAPPER.readTree(TEMPLATE);
|
||||
((ObjectNode) template.get("Resources")).remove("Mapping");
|
||||
((ObjectNode) template.get("Resources")).remove("Breaker");
|
||||
((ObjectNode) template.get("Outputs")).remove("MappingRef");
|
||||
((ObjectNode) template.get("Outputs")).remove("MappingId");
|
||||
return template.toString();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String template(String name) {
|
||||
try (InputStream in = ApiGatewayV2DomainCfnIntegrationTest.class.getResourceAsStream(
|
||||
"/cloudformation/apigatewayv2-domain/" + name)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("Missing test template " + name);
|
||||
}
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** Waits for the create or update to settle, then hands back the DescribeStacks body. */
|
||||
private static String describeStacks(String stack, String expectedStatus) {
|
||||
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, CFN_AUTH);
|
||||
assertEquals(expectedStatus, state.status(), state.reason());
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static String stackEvents(String stack) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStackEvents")
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
/** Whether one event names this resource, physical id and status together. */
|
||||
private static boolean hasEvent(String events, String logicalId, String physicalId, String status) {
|
||||
return Arrays.stream(events.split("<member>"))
|
||||
.anyMatch(event -> event.contains("<LogicalResourceId>" + logicalId + "</LogicalResourceId>")
|
||||
&& event.contains("<PhysicalResourceId>" + physicalId + "</PhysicalResourceId>")
|
||||
&& event.contains("<ResourceStatus>" + status + "</ResourceStatus>"));
|
||||
}
|
||||
|
||||
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("/v2/domainnames/" + domain).then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse getMappings(String domain) {
|
||||
return given().when().get("/v2/domainnames/" + domain + "/apimappings").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse getMapping(String domain, String apiMappingId) {
|
||||
return given().when().get("/v2/domainnames/" + domain + "/apimappings/" + apiMappingId).then();
|
||||
}
|
||||
|
||||
/** The custom domain filter routes on the Host header, the way a DNS alias would deliver the request. */
|
||||
private static void invokeThroughDomain(String host, String path) {
|
||||
int before = backendHits.get();
|
||||
given().header("Host", host).when().get(path).then()
|
||||
.statusCode(200)
|
||||
.body(equalTo(BACKEND_BODY));
|
||||
assertEquals(before + 1, backendHits.get(), "the request through " + host + path + " reached the integration");
|
||||
}
|
||||
|
||||
private static void assertNotRouted(String host, String path) {
|
||||
int before = backendHits.get();
|
||||
given().header("Host", host).when().get(path);
|
||||
assertEquals(before, backendHits.get(), "the request through " + host + path + " reached the integration");
|
||||
}
|
||||
}
|
||||
+2
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayRestApiCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2DomainCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApplicationAutoScalingCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingGroupCfnProvisioner;
|
||||
@@ -358,6 +359,7 @@ final class CfnProvisionerFixture {
|
||||
discovered.add(new ApiGatewayApiKeyCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayUsagePlanCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayDomainCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayV2DomainCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayGatewayResponseCfnProvisioner(apiGatewayService));
|
||||
discovered.add(new ApiGatewayRestApiCfnProvisioner(apiGatewayService, s3Service, objectMapper));
|
||||
}
|
||||
|
||||
+638
@@ -0,0 +1,638 @@
|
||||
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.ApiGatewayService.StoredMapping;
|
||||
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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
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 v2 custom domain provisioner in isolation, over a mocked service. The validation
|
||||
* is the service's and is tested there; here 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, and how a replacement and a rollback reach the service. The replacement
|
||||
* lifecycle is {@link ReplacementCleanup}'s own, not a stand-in.
|
||||
*/
|
||||
class ApiGatewayV2DomainCfnProvisionerTest {
|
||||
|
||||
private static final String DOMAIN_TYPE = "AWS::ApiGatewayV2::DomainName";
|
||||
private static final String MAPPING_TYPE = "AWS::ApiGatewayV2::ApiMapping";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String DOMAIN = "api.example.com";
|
||||
private static final String OLD_DOMAIN = "old.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 String OTHER_API_ID = "zyx987wvu6";
|
||||
private static final String DOMAIN_ATTR = "__FlociApiMappingDomainName";
|
||||
private static final String DOMAIN_SNAPSHOT_ATTR = CfnRollback.API_GATEWAY_V2_DOMAIN_UPDATE_SNAPSHOT_ATTR;
|
||||
private static final String MAPPING_SNAPSHOT_ATTR = CfnRollback.API_MAPPING_UPDATE_SNAPSHOT_ATTR;
|
||||
private static final String V1_MAPPING_ID = ApiGatewayService.apiMappingId("v1");
|
||||
private static final String MOVED_MAPPING_ID = V1_MAPPING_ID + "-2";
|
||||
private static final AwsException DOMAIN_NOT_FOUND =
|
||||
new AwsException("NotFoundException", "Invalid domain name identifier specified", 404);
|
||||
private static final AwsException MAPPING_NOT_FOUND =
|
||||
new AwsException("NotFoundException", "Unable to find ApiMapping with ID " + V1_MAPPING_ID, 404);
|
||||
|
||||
private final ApiGatewayService apiGateway = mock(ApiGatewayService.class);
|
||||
private final ApiGatewayV2DomainCfnProvisioner provisioner = new ApiGatewayV2DomainCfnProvisioner(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;
|
||||
}
|
||||
|
||||
/** A domain resource as an earlier provision left it. */
|
||||
private static StackResource provisionedDomain(String domainName) {
|
||||
StackResource r = resource(DOMAIN_TYPE, domainName);
|
||||
r.getAttributes().put("DomainNameArn", "arn:aws:apigateway:us-east-1::/domainnames/" + domainName);
|
||||
r.getAttributes().put("RegionalDomainName", domainName + ".regional.local");
|
||||
r.getAttributes().put("RegionalHostedZoneId", "Z2FDTNDATAQYL2");
|
||||
return r;
|
||||
}
|
||||
|
||||
/** A mapping resource as an earlier provision left it: its id and the domain it was created on. */
|
||||
private static StackResource provisionedMapping(String apiMappingId, String domainName) {
|
||||
StackResource r = resource(MAPPING_TYPE, apiMappingId);
|
||||
r.getAttributes().put("ApiMappingId", apiMappingId);
|
||||
r.getAttributes().put(DOMAIN_ATTR, domainName);
|
||||
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 StoredMapping storedMapping(String apiMappingId, String storedPath, String apiId, String stage) {
|
||||
BasePathMapping mapping = new BasePathMapping(storedPath, apiId, stage);
|
||||
mapping.setApiMappingId(apiMappingId);
|
||||
return new StoredMapping(storedPath, mapping);
|
||||
}
|
||||
|
||||
private ObjectNode domainProps(String certificateArn, String securityPolicy) {
|
||||
ObjectNode props = mapper.createObjectNode().put("DomainName", DOMAIN);
|
||||
props.putArray("DomainNameConfigurations").addObject()
|
||||
.put("CertificateArn", certificateArn)
|
||||
.put("EndpointType", "REGIONAL")
|
||||
.put("SecurityPolicy", securityPolicy);
|
||||
props.putObject("Tags").put("stack", "my-stack");
|
||||
return props;
|
||||
}
|
||||
|
||||
private static Map<String, Object> domainRequest(String certificateArn, String securityPolicy) {
|
||||
Map<String, Object> configuration = new LinkedHashMap<>();
|
||||
configuration.put("certificateArn", certificateArn);
|
||||
configuration.put("endpointType", "REGIONAL");
|
||||
configuration.put("securityPolicy", securityPolicy);
|
||||
return Map.of("domainName", DOMAIN, "domainNameConfigurations", List.of(configuration),
|
||||
"tags", Map.of("stack", "my-stack"));
|
||||
}
|
||||
|
||||
private ObjectNode mappingProps(String domainName, String apiMappingKey, String apiId, String stage) {
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("DomainName", domainName)
|
||||
.put("ApiId", apiId)
|
||||
.put("Stage", stage);
|
||||
if (apiMappingKey != null) {
|
||||
props.put("ApiMappingKey", apiMappingKey);
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesBothTypes() {
|
||||
assertEquals(Set.of(DOMAIN_TYPE, MAPPING_TYPE), provisioner.resourceTypes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainSetsItsNameAsPhysicalIdAndTheThreeSchemaAttributes() {
|
||||
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
|
||||
StackResource r = resource(DOMAIN_TYPE);
|
||||
|
||||
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx());
|
||||
|
||||
verify(apiGateway).createV2DomainName(REGION, domainRequest(CERTIFICATE_ARN, "TLS_1_2"));
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
assertEquals(Map.of(
|
||||
"DomainNameArn", DOMAIN_ARN,
|
||||
"RegionalDomainName", "api.example.com.regional.local",
|
||||
"RegionalHostedZoneId", "Z2FDTNDATAQYL2"), r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainHandsEveryInputToTheServiceToJudge() {
|
||||
// The service refuses what floci does not emulate, so the template's values must reach it.
|
||||
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
|
||||
ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2").put("RoutingMode", "API_MAPPING_ONLY");
|
||||
((ObjectNode) props.withArray("DomainNameConfigurations").get(0))
|
||||
.put("IpAddressType", "dualstack")
|
||||
.put("OwnershipVerificationCertificateArn", RENEWED_CERTIFICATE_ARN);
|
||||
props.putObject("MutualTlsAuthentication").put("TruststoreUri", "s3://bucket/truststore.pem");
|
||||
|
||||
provisioner.provision(resource(DOMAIN_TYPE), props, ctx());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
|
||||
verify(apiGateway).createV2DomainName(eq(REGION), request.capture());
|
||||
assertEquals("API_MAPPING_ONLY", request.getValue().get("routingMode"));
|
||||
assertEquals(Map.of("truststoreUri", "s3://bucket/truststore.pem"),
|
||||
request.getValue().get("mutualTlsAuthentication"));
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> configuration =
|
||||
((List<Map<String, Object>>) request.getValue().get("domainNameConfigurations")).getFirst();
|
||||
assertEquals("dualstack", configuration.get("ipAddressType"));
|
||||
assertEquals(RENEWED_CERTIFICATE_ARN, configuration.get("ownershipVerificationCertificateArn"));
|
||||
}
|
||||
|
||||
@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()).createV2DomainName(any(), anyMap());
|
||||
verify(apiGateway, never()).createApiMapping(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainUpdateWithUnchangedNameReplacesItsConfigurationInPlace() {
|
||||
when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(regionalDomain(DOMAIN));
|
||||
CustomDomain updated = regionalDomain(DOMAIN);
|
||||
updated.setRegionalCertificateArn(RENEWED_CERTIFICATE_ARN);
|
||||
when(apiGateway.replaceV2DomainConfiguration(eq(REGION), eq(DOMAIN), anyMap())).thenReturn(updated);
|
||||
StackResource r = provisionedDomain(DOMAIN);
|
||||
|
||||
provisioner.provision(r, domainProps(RENEWED_CERTIFICATE_ARN, "TLS_1_2"), ctx(DOMAIN));
|
||||
|
||||
verify(apiGateway).replaceV2DomainConfiguration(REGION, DOMAIN, domainRequest(RENEWED_CERTIFICATE_ARN, "TLS_1_2"));
|
||||
verify(apiGateway, never()).createV2DomainName(any(), anyMap());
|
||||
verify(apiGateway, never()).deleteDomainName(any(), any());
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
assertTrue(r.getAttributes().containsKey(DOMAIN_SNAPSHOT_ATTR), "the prior configuration is kept for a rollback");
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainUpdateDrivesTagsToTheTemplate() {
|
||||
CustomDomain existing = regionalDomain(DOMAIN);
|
||||
existing.setTags(new LinkedHashMap<>(Map.of("stack", "my-stack", "owner", "old")));
|
||||
when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(existing);
|
||||
when(apiGateway.replaceV2DomainConfiguration(eq(REGION), eq(DOMAIN), anyMap())).thenReturn(existing);
|
||||
ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2");
|
||||
((ObjectNode) props.get("Tags")).put("team", "api");
|
||||
|
||||
provisioner.provision(provisionedDomain(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 domainUpdateTheServiceRefusesLeavesTheTagsAlone() {
|
||||
when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(regionalDomain(DOMAIN));
|
||||
when(apiGateway.replaceV2DomainConfiguration(eq(REGION), eq(DOMAIN), anyMap()))
|
||||
.thenThrow(new AwsException("BadRequestException", "Mutual TLS authentication is not supported", 400));
|
||||
ObjectNode props = domainProps(CERTIFICATE_ARN, "TLS_1_2");
|
||||
((ObjectNode) props.get("Tags")).put("team", "api");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(provisionedDomain(DOMAIN), props, ctx(DOMAIN)));
|
||||
|
||||
verify(apiGateway, never()).tagDomainName(any(), any(), anyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainRenameCreatesTheNewDomainAndLeavesTheOldOneToTheCleanup() {
|
||||
when(apiGateway.getDomainName(REGION, OLD_DOMAIN)).thenReturn(regionalDomain(OLD_DOMAIN));
|
||||
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
|
||||
StackResource r = provisionedDomain(OLD_DOMAIN);
|
||||
|
||||
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(OLD_DOMAIN));
|
||||
|
||||
verify(apiGateway).createV2DomainName(eq(REGION), anyMap());
|
||||
verify(apiGateway, never()).deleteDomainName(any(), any());
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
assertEquals("api.example.com.regional.local", r.getAttributes().get("RegionalDomainName"));
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
assertEquals(OLD_DOMAIN, provisioner.updateCleanupPhysicalId(r));
|
||||
|
||||
UpdateCleanupResult cleanup = provisioner.completeUpdate(r);
|
||||
|
||||
assertTrue(cleanup.complete());
|
||||
verify(apiGateway).deleteDomainName(REGION, OLD_DOMAIN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainRenameUnderRetainKeepsTheOldDomain() {
|
||||
when(apiGateway.getDomainName(REGION, OLD_DOMAIN)).thenReturn(regionalDomain(OLD_DOMAIN));
|
||||
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
|
||||
StackResource r = provisionedDomain(OLD_DOMAIN);
|
||||
r.setUpdateReplacePolicy("Retain");
|
||||
|
||||
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(OLD_DOMAIN));
|
||||
provisioner.completeUpdate(r);
|
||||
|
||||
verify(apiGateway, never()).deleteDomainName(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainRenameRollbackPutsTheOldDomainBackAndDeletesTheNewOne() {
|
||||
when(apiGateway.getDomainName(REGION, OLD_DOMAIN)).thenReturn(regionalDomain(OLD_DOMAIN));
|
||||
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
|
||||
StackResource r = provisionedDomain(OLD_DOMAIN);
|
||||
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(OLD_DOMAIN));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(apiGateway).deleteDomainName(REGION, DOMAIN);
|
||||
verify(apiGateway, never()).deleteDomainName(REGION, OLD_DOMAIN);
|
||||
assertEquals(OLD_DOMAIN, r.getPhysicalId());
|
||||
assertEquals("old.example.com.regional.local", r.getAttributes().get("RegionalDomainName"));
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainInPlaceRollbackRestoresTheConfigurationAndTagsItHadBefore() {
|
||||
CustomDomain existing = regionalDomain(DOMAIN);
|
||||
existing.setRegionalCertificateName("before");
|
||||
when(apiGateway.getDomainName(REGION, DOMAIN)).thenReturn(existing);
|
||||
CustomDomain updated = regionalDomain(DOMAIN);
|
||||
updated.setTags(new LinkedHashMap<>(Map.of("stack", "my-stack", "team", "api")));
|
||||
when(apiGateway.replaceV2DomainConfiguration(eq(REGION), eq(DOMAIN), anyMap())).thenReturn(updated);
|
||||
ObjectNode props = domainProps(RENEWED_CERTIFICATE_ARN, "TLS_1_2");
|
||||
((ObjectNode) props.get("Tags")).put("team", "api");
|
||||
StackResource r = provisionedDomain(DOMAIN);
|
||||
provisioner.provision(r, props, ctx(DOMAIN));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
Map<String, Object> configuration = new LinkedHashMap<>();
|
||||
configuration.put("certificateArn", CERTIFICATE_ARN);
|
||||
configuration.put("certificateName", "before");
|
||||
configuration.put("endpointType", "REGIONAL");
|
||||
configuration.put("securityPolicy", "TLS_1_2");
|
||||
verify(apiGateway).replaceV2DomainConfiguration(REGION, DOMAIN,
|
||||
Map.of("domainName", DOMAIN, "domainNameConfigurations", List.of(configuration)));
|
||||
verify(apiGateway).untagDomainName(REGION, DOMAIN, List.of("team"));
|
||||
assertFalse(r.getAttributes().containsKey(DOMAIN_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainUpdateWhosePriorDomainIsGoneCreatesItAgain() {
|
||||
when(apiGateway.getDomainName(REGION, DOMAIN)).thenThrow(DOMAIN_NOT_FOUND);
|
||||
when(apiGateway.createV2DomainName(eq(REGION), anyMap())).thenReturn(regionalDomain(DOMAIN));
|
||||
StackResource r = provisionedDomain(DOMAIN);
|
||||
|
||||
provisioner.provision(r, domainProps(CERTIFICATE_ARN, "TLS_1_2"), ctx(DOMAIN));
|
||||
|
||||
verify(apiGateway).createV2DomainName(eq(REGION), anyMap());
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r), "the same name is the same domain, nothing to clean up");
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainDeleteToleratesAnAlreadyDeletedDomain() {
|
||||
doThrow(DOMAIN_NOT_FOUND).when(apiGateway).deleteDomainName(REGION, DOMAIN);
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(resource(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(resource(DOMAIN_TYPE, DOMAIN), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingPhysicalIdIsTheIdTheServiceGaveIt() {
|
||||
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of()))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
StackResource r = resource(MAPPING_TYPE);
|
||||
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx());
|
||||
|
||||
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
|
||||
assertEquals(Map.of("ApiMappingId", V1_MAPPING_ID, DOMAIN_ATTR, DOMAIN), r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingWithoutAKeyIsTheRootMapping() {
|
||||
String rootId = ApiGatewayService.apiMappingId("(none)");
|
||||
when(apiGateway.createApiMapping(REGION, DOMAIN, null, API_ID, "$default", Set.of()))
|
||||
.thenReturn(storedMapping(rootId, "(none)", API_ID, "$default"));
|
||||
StackResource r = resource(MAPPING_TYPE);
|
||||
|
||||
provisioner.provision(r, mappingProps(DOMAIN, null, API_ID, "$default"), ctx());
|
||||
|
||||
assertEquals(rootId, r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingRequiresDomainNameApiIdAndStage() {
|
||||
for (String missing : List.of("DomainName", "ApiId", "Stage")) {
|
||||
ObjectNode props = mappingProps(DOMAIN, "v1", API_ID, "$default");
|
||||
props.remove(missing);
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> provisioner.provision(resource(MAPPING_TYPE), props, ctx()), missing);
|
||||
}
|
||||
verify(apiGateway, never()).createApiMapping(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingUpdateOnTheSameDomainIsInPlaceAndKeepsTheIdThroughAKeyChange() {
|
||||
when(apiGateway.getApiMapping(REGION, DOMAIN, V1_MAPPING_ID))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
when(apiGateway.updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v2", OTHER_API_ID, "prod"))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v2", OTHER_API_ID, "prod"));
|
||||
StackResource r = provisionedMapping(V1_MAPPING_ID, DOMAIN);
|
||||
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v2", OTHER_API_ID, "prod"), ctx(V1_MAPPING_ID));
|
||||
|
||||
verify(apiGateway).updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v2", OTHER_API_ID, "prod");
|
||||
verify(apiGateway, never()).createApiMapping(any(), any(), any(), any(), any(), any());
|
||||
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
|
||||
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
|
||||
assertEquals(V1_MAPPING_ID, r.getAttributes().get("ApiMappingId"));
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
assertTrue(r.getAttributes().containsKey(MAPPING_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingUpdateTheServiceRefusesCreatesNothing() {
|
||||
when(apiGateway.getApiMapping(REGION, DOMAIN, V1_MAPPING_ID))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
when(apiGateway.updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v1", API_ID, "nosuchstage"))
|
||||
.thenThrow(new AwsException("BadRequestException", "Invalid stage identifier specified", 400));
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
provisionedMapping(V1_MAPPING_ID, DOMAIN), mappingProps(DOMAIN, "v1", API_ID, "nosuchstage"),
|
||||
ctx(V1_MAPPING_ID)));
|
||||
|
||||
assertEquals("BadRequestException", failure.getErrorCode());
|
||||
verify(apiGateway, never()).createApiMapping(any(), any(), any(), any(), any(), any());
|
||||
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingInPlaceRollbackPutsTheKeyApiAndStageBack() {
|
||||
when(apiGateway.getApiMapping(REGION, DOMAIN, V1_MAPPING_ID))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
when(apiGateway.updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v2", OTHER_API_ID, "prod"))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v2", OTHER_API_ID, "prod"));
|
||||
StackResource r = provisionedMapping(V1_MAPPING_ID, DOMAIN);
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v2", OTHER_API_ID, "prod"), ctx(V1_MAPPING_ID));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(apiGateway).updateApiMapping(REGION, DOMAIN, V1_MAPPING_ID, "v1", API_ID, "$default");
|
||||
assertFalse(r.getAttributes().containsKey(MAPPING_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingInPlaceRollbackOfTheRootMappingRestoresTheRoot() {
|
||||
String rootId = ApiGatewayService.apiMappingId("(none)");
|
||||
when(apiGateway.getApiMapping(REGION, DOMAIN, rootId))
|
||||
.thenReturn(storedMapping(rootId, "(none)", API_ID, "$default"));
|
||||
when(apiGateway.updateApiMapping(REGION, DOMAIN, rootId, "v1", API_ID, "$default"))
|
||||
.thenReturn(storedMapping(rootId, "v1", API_ID, "$default"));
|
||||
StackResource r = provisionedMapping(rootId, DOMAIN);
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(rootId));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(apiGateway).updateApiMapping(REGION, DOMAIN, rootId, null, API_ID, "$default");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingMovedToAnotherDomainGetsANewIdAndTheOldOneWaitsForTheCleanup() {
|
||||
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of(V1_MAPPING_ID)))
|
||||
.thenReturn(storedMapping(MOVED_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
StackResource r = provisionedMapping(V1_MAPPING_ID, OLD_DOMAIN);
|
||||
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(V1_MAPPING_ID));
|
||||
|
||||
verify(apiGateway, never()).getApiMapping(any(), any(), any());
|
||||
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
|
||||
assertEquals(MOVED_MAPPING_ID, r.getPhysicalId());
|
||||
assertEquals(DOMAIN, r.getAttributes().get(DOMAIN_ATTR));
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
assertEquals(V1_MAPPING_ID, provisioner.updateCleanupPhysicalId(r));
|
||||
|
||||
assertTrue(provisioner.completeUpdate(r).complete());
|
||||
|
||||
verify(apiGateway).deleteApiMapping(REGION, OLD_DOMAIN, V1_MAPPING_ID);
|
||||
verify(apiGateway, never()).deleteApiMapping(REGION, DOMAIN, MOVED_MAPPING_ID);
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingMoveRollbackPutsTheOldMappingBackAndDeletesTheNewOne() {
|
||||
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of(V1_MAPPING_ID)))
|
||||
.thenReturn(storedMapping(MOVED_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
StackResource r = provisionedMapping(V1_MAPPING_ID, OLD_DOMAIN);
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(V1_MAPPING_ID));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, MOVED_MAPPING_ID);
|
||||
verify(apiGateway, never()).deleteApiMapping(REGION, OLD_DOMAIN, V1_MAPPING_ID);
|
||||
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
|
||||
assertEquals(V1_MAPPING_ID, r.getAttributes().get("ApiMappingId"));
|
||||
assertEquals(OLD_DOMAIN, r.getAttributes().get(DOMAIN_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingMoveRollbackWhoseDeleteFailsStillNamesTheOldDomain() {
|
||||
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of(V1_MAPPING_ID)))
|
||||
.thenReturn(storedMapping(MOVED_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
doThrow(new AwsException("BadRequestException", "Invalid request", 400))
|
||||
.when(apiGateway).deleteApiMapping(REGION, DOMAIN, MOVED_MAPPING_ID);
|
||||
StackResource r = provisionedMapping(V1_MAPPING_ID, OLD_DOMAIN);
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(V1_MAPPING_ID));
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
|
||||
|
||||
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
|
||||
assertEquals(OLD_DOMAIN, r.getAttributes().get(DOMAIN_ATTR));
|
||||
// The replacement stays owed, and the next cleanup reaches it through the domain it is on.
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
doThrow(MAPPING_NOT_FOUND).when(apiGateway).deleteApiMapping(REGION, DOMAIN, MOVED_MAPPING_ID);
|
||||
assertTrue(provisioner.completeUpdate(r).complete());
|
||||
verify(apiGateway, never()).deleteApiMapping(REGION, OLD_DOMAIN, MOVED_MAPPING_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingUpdateWhosePriorMappingIsGoneCreatesItAgain() {
|
||||
when(apiGateway.getApiMapping(REGION, DOMAIN, V1_MAPPING_ID)).thenThrow(MAPPING_NOT_FOUND);
|
||||
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of()))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
StackResource r = provisionedMapping(V1_MAPPING_ID, DOMAIN);
|
||||
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx(V1_MAPPING_ID));
|
||||
|
||||
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
|
||||
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingUpdateFromAStubbedResourceCreatesTheMappingAndDeletesNothingForTheStub() {
|
||||
// A stack persisted before this provisioner existed carries the stub arm's id and no domain.
|
||||
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of()))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
StackResource r = resource(MAPPING_TYPE, "Mapping-1a2b3c4d");
|
||||
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx("Mapping-1a2b3c4d"));
|
||||
|
||||
verify(apiGateway, never()).getApiMapping(any(), any(), any());
|
||||
assertEquals(V1_MAPPING_ID, r.getPhysicalId());
|
||||
assertTrue(provisioner.completeUpdate(r).complete());
|
||||
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingRollbackFromAStubbedResourceLeavesNoDomainBehind() {
|
||||
when(apiGateway.createApiMapping(REGION, DOMAIN, "v1", API_ID, "$default", Set.of()))
|
||||
.thenReturn(storedMapping(V1_MAPPING_ID, "v1", API_ID, "$default"));
|
||||
StackResource r = resource(MAPPING_TYPE, "Mapping-1a2b3c4d");
|
||||
provisioner.provision(r, mappingProps(DOMAIN, "v1", API_ID, "$default"), ctx("Mapping-1a2b3c4d"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
|
||||
assertEquals("Mapping-1a2b3c4d", r.getPhysicalId());
|
||||
assertNull(r.getAttributes().get(DOMAIN_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingDeleteAddressesTheRecordedDomain() {
|
||||
provisioner.delete(provisionedMapping(V1_MAPPING_ID, DOMAIN), REGION);
|
||||
|
||||
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingDeleteToleratesAMappingAlreadyGone() {
|
||||
doThrow(MAPPING_NOT_FOUND).when(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(provisionedMapping(V1_MAPPING_ID, DOMAIN), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingDeleteToleratesAMappingRemovedWithItsDomain() {
|
||||
doThrow(DOMAIN_NOT_FOUND).when(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(provisionedMapping(V1_MAPPING_ID, DOMAIN), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingDeletePropagatesOtherFailures() {
|
||||
doThrow(new AwsException("BadRequestException", "Invalid request", 400))
|
||||
.when(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(provisionedMapping(V1_MAPPING_ID, DOMAIN), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingDeleteByThePrimaryIdentifierAddressesItsDomain() {
|
||||
// Cloud Control names a mapping by the schema's primary identifier, <ApiMappingId>|<DomainName>.
|
||||
provisioner.delete(MAPPING_TYPE, V1_MAPPING_ID + "|" + DOMAIN, REGION);
|
||||
|
||||
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingDeleteByThePrimaryIdentifierWithItsRecordedDomainAddressesTheMapping() {
|
||||
// Cloud Control keys what it created by the primary identifier, and deletes it with the
|
||||
// attributes the create recorded, the domain among them.
|
||||
provisioner.delete(provisionedMapping(V1_MAPPING_ID + "|" + DOMAIN, DOMAIN), REGION);
|
||||
|
||||
verify(apiGateway).deleteApiMapping(REGION, DOMAIN, V1_MAPPING_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mappingDeleteByABareIdAnswersNotFound() {
|
||||
// A bare id names no domain to look in; the stack path treats NotFoundException as already
|
||||
// deleted, and Cloud Control reports it instead of claiming a delete that did not happen.
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(resource(MAPPING_TYPE, "Mapping-1a2b3c4d"), REGION));
|
||||
|
||||
assertEquals("NotFoundException", failure.getErrorCode());
|
||||
verify(apiGateway, never()).deleteApiMapping(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearUpdateDropsTheSnapshots() {
|
||||
StackResource r = provisionedMapping(V1_MAPPING_ID, DOMAIN);
|
||||
r.getAttributes().put(MAPPING_SNAPSHOT_ATTR, "{}");
|
||||
r.getAttributes().put(DOMAIN_SNAPSHOT_ATTR, "{}");
|
||||
|
||||
provisioner.clearUpdate(r);
|
||||
|
||||
assertEquals(Map.of("ApiMappingId", V1_MAPPING_ID, DOMAIN_ATTR, DOMAIN), r.getAttributes());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user