diff --git a/docs/configuration/partitions.md b/docs/configuration/partitions.md index b84de1b8db..dd7aad05b6 100644 --- a/docs/configuration/partitions.md +++ b/docs/configuration/partitions.md @@ -112,8 +112,8 @@ back to `aws` for a label no partition publishes. distinct from the Application/Classic one. The CloudFront hosted zone is published for `aws` and `aws-cn`; the SAML sign-on URL for five partitions. The ISO and EUSC regions have no load balancer hosted zones, and only the two ISO-F regions have an S3 website zone; where a table has - no row the field is omitted rather than guessed. An `EDGE` API Gateway custom domain is refused - outside the commercial partition (`BadRequestException`): GovCloud and ISO have no CloudFront, + no row the field is omitted rather than guessed. An `EDGE` API Gateway REST API or custom domain is + refused outside the commercial partition (`BadRequestException`): GovCloud and ISO have no CloudFront, and China has no edge-optimized API Gateway ([China API Gateway](https://docs.amazonaws.cn/en_us/aws/latest/userguide/api-gateway.html)). - **VPC endpoint service names**: interface endpoints (as `DescribeVpcEndpointServices` lists them) diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 5809031a58..efb22a9fba 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -526,11 +526,10 @@ setups, and `floci:override-id` wins when both are present. Every other tag is p Edge-optimized APIs and custom domains (`EDGE`) exist only in the commercial partition: China has CloudFront but no edge-optimized API Gateway, and GovCloud, EUSC and the ISO partitions have -no CloudFront. Floci enforces this for custom domains only: creating a domain with `EDGE`, or -switching one to it, outside the commercial partition is a `BadRequestException`, and `REGIONAL` -domains work in every partition (private custom domains are not emulated). REST APIs are not -checked yet, so an `EDGE` REST API is still created in any partition. Invoke URLs use the -partition's DNS suffix +no CloudFront. Floci enforces this for REST APIs and custom domains: creating either with `EDGE`, +or switching one to it with `UpdateRestApi` or `UpdateDomainName`, outside the commercial partition +is a `BadRequestException`. `REGIONAL` APIs and domains work in every partition (private custom +domains are not emulated). Invoke URLs use the partition's DNS suffix (`.execute-api.cn-north-1.amazonaws.com.cn`). See [AWS Partitions](../configuration/partitions.md). ## Configuration diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java index 9c1789e356..7573de8919 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java @@ -300,6 +300,7 @@ public class ApiGatewayService implements ResourceProvider { throw new AwsException("BadRequestException", "Endpoint configuration types must contain exactly one value.", 400); } + requireEndpointTypeAvailable(endpointConfiguration.getTypes().getFirst().name(), region); api.setEndpointConfiguration(endpointConfigurationOf(endpointConfiguration.getTypes().getFirst(), endpointConfiguration.getVpcEndpointIds())); @@ -2463,7 +2464,7 @@ public class ApiGatewayService implements ResourceProvider { if (patchOperations != null) { // Worked out before anything is set: the store hands back the live API, and a rejected // endpoint change must leave it as it was. - EndpointConfiguration endpointConfiguration = patchEndpointConfiguration(api, patchOperations); + EndpointConfiguration endpointConfiguration = patchEndpointConfiguration(api, patchOperations, region); for (Map op : patchOperations) { if (!"replace" .equals(op.get("op"))) continue; String path = op.getOrDefault("path", ""); @@ -2490,11 +2491,13 @@ public class ApiGatewayService implements ResourceProvider { * and disassociate a VPC endpoint. */ private static EndpointConfiguration patchEndpointConfiguration(RestApi api, - List> patchOperations) { + List> patchOperations, + String region) { EndpointConfiguration current = api.getEndpointConfiguration(); // An API stored without one is REGIONAL, which is also what GetRestApi reports for it. - EndpointType type = current == null || current.getTypes().isEmpty() + EndpointType currentType = current == null || current.getTypes().isEmpty() ? EndpointType.REGIONAL : current.getTypes().getFirst(); + EndpointType type = currentType; List vpcEndpointIds = new ArrayList<>(current == null ? List.of() : current.getVpcEndpointIds()); boolean patched = false; for (Map op : patchOperations) { @@ -2523,6 +2526,9 @@ public class ApiGatewayService implements ResourceProvider { } } } + if (type != currentType) { + requireEndpointTypeAvailable(type.name(), region); + } return patched ? endpointConfigurationOf(type, vpcEndpointIds) : null; } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java index 83ecf90298..b1a0431a13 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionRegionGatesIntegrationTest.java @@ -103,6 +103,51 @@ class PartitionRegionGatesIntegrationTest { .when().delete("/domainnames/" + regional)); } + private Response createRestApi(String region, String type) { + Response created = given() + .header("Authorization", PartitionMatrix.sigV4Auth(region, "apigateway")) + .contentType("application/json") + .body("{\"name\":\"edge-gate-" + Long.toString(System.nanoTime(), 36) + "\"," + + "\"endpointConfiguration\":{\"types\":[\"" + type + "\"]}}") + .when().post("/restapis"); + String id = created.jsonPath().getString("id"); + if (created.statusCode() == 201 && id != null) { + cleanup.register(() -> given() + .header("Authorization", PartitionMatrix.sigV4Auth(region, "apigateway")) + .when().delete("/restapis/" + id)); + } + return created; + } + + private static Response switchRestApiToEdge(String region, String id) { + return given() + .header("Authorization", PartitionMatrix.sigV4Auth(region, "apigateway")) + .contentType("application/json") + .body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/endpointConfiguration/types/REGIONAL\"," + + "\"value\":\"EDGE\"}]}") + .when().patch("/restapis/" + id); + } + + /** The domain rule applies to the REST APIs themselves: on create and on an endpoint-type switch. */ + @Test + void edgeRestApisAreRejectedOutsideTheCommercialPartition() { + for (String region : List.of("us-gov-west-1", "cn-north-1")) { + String partition = AwsRegions.partitionFor(region); + createRestApi(region, "EDGE").then().statusCode(400) + .body(containsString("not available in partition " + partition)); + + String regionalId = createRestApi(region, "REGIONAL").then().statusCode(201) + .extract().jsonPath().getString("id"); + switchRestApiToEdge(region, regionalId).then().statusCode(400) + .body(containsString("not available in partition " + partition)); + } + + createRestApi("us-east-1", "EDGE").then().statusCode(201); + String commercialId = createRestApi("us-east-1", "REGIONAL").then().statusCode(201) + .extract().jsonPath().getString("id"); + switchRestApiToEdge("us-east-1", commercialId).then().statusCode(200); + } + @Test void cloudFrontScopeLivesInThePartitionsImplicitGlobalRegion() { String name = "cn-" + Long.toString(System.nanoTime(), 36); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayEdgeRestApiPartitionTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayEdgeRestApiPartitionTest.java new file mode 100644 index 0000000000..bb292d2506 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayEdgeRestApiPartitionTest.java @@ -0,0 +1,119 @@ +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.model.EndpointType; +import io.github.hectorvent.floci.services.apigateway.model.RestApi; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * An edge-optimized REST API exists only in the commercial partition, so it cannot be created or + * switched to elsewhere, while a regional one works in every partition. + */ +class ApiGatewayEdgeRestApiPartitionTest { + + private final Map> stores = new HashMap<>(); + private ApiGatewayService service; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(invocation -> + stores.computeIfAbsent(invocation.getArgument(1, String.class), + ignored -> AccountAwareStorageBackend.inMemory("000000000000"))); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().cloudfront().domainSuffix()).thenReturn("cloudfront.net"); + service = new ApiGatewayService(storageFactory, config, mock(TlsCertificateManager.class), + new RegionResolver("us-east-1", "000000000000")); + } + + private RestApi create(String region, String type) { + return service.createRestApi(region, Map.of("name", "edge-test", + "endpointConfiguration", Map.of("types", List.of(type)))); + } + + private static List> switchTo(String from, String to) { + return List.of(Map.of("op", "replace", "path", "/endpointConfiguration/types/" + from, "value", to)); + } + + @ParameterizedTest + @ValueSource(strings = {"cn-north-1", "us-gov-west-1", "us-iso-east-1", "eusc-de-east-1"}) + void anEdgeRestApiIsRefusedOutsideTheCommercialPartition(String region) { + AwsException error = assertThrows(AwsException.class, () -> create(region, "EDGE")); + + assertEquals("BadRequestException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertThat(error.getMessage(), containsString("EDGE")); + assertEquals(List.of(), service.getRestApis(region)); + } + + @ParameterizedTest + @ValueSource(strings = {"cn-north-1", "us-gov-west-1"}) + void switchingARestApiToEdgeIsRefusedOutsideTheCommercialPartition(String region) { + RestApi api = create(region, "REGIONAL"); + + for (String pathRef : List.of("REGIONAL", "0")) { + AwsException error = assertThrows(AwsException.class, + () -> service.updateRestApi(region, api.getId(), switchTo(pathRef, "EDGE"))); + assertEquals("BadRequestException", error.getErrorCode()); + } + assertEquals(List.of(EndpointType.REGIONAL), + service.getRestApi(region, api.getId()).getEndpointConfiguration().getTypes()); + } + + @ParameterizedTest + @ValueSource(strings = {"us-east-1", "cn-north-1", "us-gov-west-1", "us-iso-east-1", "eusc-de-east-1"}) + void aRegionalRestApiIsAcceptedInEveryPartition(String region) { + RestApi api = create(region, "REGIONAL"); + + assertEquals(List.of(EndpointType.REGIONAL), api.getEndpointConfiguration().getTypes()); + } + + @Test + void anEdgeRestApiIsAcceptedInTheCommercialPartition() { + RestApi created = create("us-east-1", "EDGE"); + assertEquals(List.of(EndpointType.EDGE), created.getEndpointConfiguration().getTypes()); + + RestApi regional = create("us-east-1", "REGIONAL"); + RestApi switched = service.updateRestApi("us-east-1", regional.getId(), switchTo("REGIONAL", "EDGE")); + assertEquals(List.of(EndpointType.EDGE), switched.getEndpointConfiguration().getTypes()); + } + + /** A move away from EDGE needs nothing the partition lacks, so a stored EDGE API can still leave it. */ + @Test + void aStoredEdgeRestApiCanMoveToRegionalOutsideTheCommercialPartition() { + RestApi api = create("us-east-1", "EDGE"); + @SuppressWarnings("unchecked") + AccountAwareStorageBackend apiStore = + (AccountAwareStorageBackend) stores.get("apigateway-apis.json"); + apiStore.put("cn-north-1::" + api.getId(), api); + + RestApi renamed = service.updateRestApi("cn-north-1", api.getId(), + List.of(Map.of("op", "replace", "path", "/name", "value", "renamed"))); + assertEquals("renamed", renamed.getName()); + + RestApi switched = service.updateRestApi("cn-north-1", api.getId(), switchTo("EDGE", "REGIONAL")); + assertEquals(List.of(EndpointType.REGIONAL), switched.getEndpointConfiguration().getTypes()); + } +}