diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java index da170d925b..b5c23b60ce 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java @@ -322,13 +322,13 @@ public class ApiGatewayController { String region = regionResolver.resolveRegion(headers); if ("import".equals(mode)) { RestApi api = service.importRestApi(region, body); - return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build(); + return Response.status(201).entity(toApiNode(region, api).toString()).type(MediaType.APPLICATION_JSON).build(); } try { @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); RestApi api = service.createRestApi(region, request); - return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build(); + return Response.status(201).entity(toApiNode(region, api).toString()).type(MediaType.APPLICATION_JSON).build(); } catch (IOException e) { throw new AwsException("BadRequestException", e.getMessage(), 400); } @@ -343,7 +343,7 @@ public class ApiGatewayController { String body) { String region = regionResolver.resolveRegion(headers); RestApi api = service.putRestApi(region, apiId, mode, body); - return Response.ok(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build(); + return Response.ok(toApiNode(region, api).toString()).type(MediaType.APPLICATION_JSON).build(); } @GET @@ -353,7 +353,7 @@ public class ApiGatewayController { List apis = service.getRestApis(region); ObjectNode root = objectMapper.createObjectNode(); ArrayNode items = root.putArray("item"); - apis.forEach(a -> items.add(toApiNode(a))); + apis.forEach(a -> items.add(toApiNode(region, a))); return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build(); } @@ -361,7 +361,7 @@ public class ApiGatewayController { @Path("/restapis/{apiId}") public Response getRestApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) { String region = regionResolver.resolveRegion(headers); - return Response.ok(toApiNode(service.getRestApi(region, apiId)).toString()).type(MediaType.APPLICATION_JSON).build(); + return Response.ok(toApiNode(region, service.getRestApi(region, apiId)).toString()).type(MediaType.APPLICATION_JSON).build(); } @PATCH @@ -370,7 +370,7 @@ public class ApiGatewayController { String region = regionResolver.resolveRegion(headers); List> patchOperations = parsePatchOperations(body); RestApi api = service.updateRestApi(region, apiId, patchOperations); - return Response.ok(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build(); + return Response.ok(toApiNode(region, api).toString()).type(MediaType.APPLICATION_JSON).build(); } @DELETE @@ -1902,7 +1902,7 @@ public class ApiGatewayController { // ──────────────────────────── Helpers ──────────────────────────── - private ObjectNode toApiNode(RestApi api) { + private ObjectNode toApiNode(String region, RestApi api) { ObjectNode node = objectMapper.createObjectNode(); node.put("id", api.getId()); node.put("name", api.getName()); @@ -1928,6 +1928,21 @@ public class ApiGatewayController { epConfig.getVpcEndpointIds().forEach(vpcIds::add); node.set("endpointConfiguration", epNode); + // The root resource is created with the API and is already reachable through + // GetResources, but AWS also reports its id on the API itself. Terraform reads it + // as aws_api_gateway_rest_api.root_resource_id, which is how the first resource + // under "/" gets its parent, so leaving it out breaks the conventional way of + // building a REST API. + service.findRootResourceId(region, api.getId()).ifPresent(id -> node.put("rootResourceId", id)); + + // Neither member is settable on a REST API here: createRestApi ignores both and + // updateRestApi patches only /name and /description, so the emulated value is always + // the AWS default. Report the defaults rather than omitting them, because a client + // that reads an absent member back as "" or null sees it as a difference from the + // configuration it just sent and never converges. + node.put("apiKeySource", "HEADER"); + node.put("disableExecuteApiEndpoint", false); + return node; } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java index 58e9b78de3..9e91e662b4 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 @@ -315,6 +315,30 @@ public class ApiGatewayService { return resourceStore.scan(k -> k.startsWith(prefix)); } + /** + * The id of the resource at "/", or empty if there is no API to read it from. + *

+ * ListRestApis renders a snapshot of the APIs and resolves this per API afterwards, so an + * API deleted in between is already gone by the time its root is looked up. That must cost + * the caller the one member rather than failing the whole listing, which is why a missing + * API is empty here instead of a not-found. Every other failure still propagates. + */ + public Optional findRootResourceId(String region, String apiId) { + List resources; + try { + resources = getResources(region, apiId); + } catch (AwsException e) { + if ("NotFoundException".equals(e.getErrorCode())) { + return Optional.empty(); + } + throw e; + } + return resources.stream() + .filter(r -> "/".equals(r.getPath())) + .map(ApiGatewayResource::getId) + .findFirst(); + } + public ApiGatewayResource getResource(String region, String apiId, String resourceId) { return resourceStore.get(resourceKey(region, apiId, resourceId)) .orElseThrow(() -> new AwsException("NotFoundException", "Invalid resource id specified", 404)); @@ -339,7 +363,15 @@ public class ApiGatewayService { } public void deleteResource(String region, String apiId, String resourceId) { - getResource(region, apiId, resourceId); + ApiGatewayResource resource = getResource(region, apiId, resourceId); + // The root resource is created with the API and cannot be removed on its own; it + // goes away only when the API does. Allowing it to be deleted would leave the API + // with no resource at "/", and so with no rootResourceId to report or to parent a + // new resource on, a state that has no way back short of recreating the API. + if ("/".equals(resource.getPath())) { + throw new AwsException("BadRequestException", + "Invalid resource identifier specified: the root resource cannot be deleted", 400); + } resourceStore.delete(resourceKey(region, apiId, resourceId)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayListRestApisConcurrentDeleteTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayListRestApisConcurrentDeleteTest.java new file mode 100644 index 0000000000..8520c2238d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayListRestApisConcurrentDeleteTest.java @@ -0,0 +1,68 @@ +package io.github.hectorvent.floci.services.apigateway; + +import java.util.Optional; + +import jakarta.inject.Inject; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * ListRestApis renders a snapshot of the APIs and then resolves each one's rootResourceId, + * which reads that API's resources. An API deleted in between is already gone by the time the + * second read happens, and the not-found it raises must cost the caller that one member rather + * than turning the whole listing into a 404. + */ +@QuarkusTest +class ApiGatewayListRestApisConcurrentDeleteTest { + + private static final String REGION = "us-east-1"; + + @Inject + ApiGatewayService service; + + @Test + void theRootLookupOfAVanishedApiIsEmptyRatherThanNotFound() { + // Same read the listing performs for each API in its snapshot. The id belongs to no + // API, which is exactly the state a concurrent DeleteRestApi leaves behind. + assertEquals(Optional.empty(), service.findRootResourceId(REGION, "nosuchapi")); + } + + @Test + void thatToleranceIsNarrowerThanTheReadItGuards() { + // Only the vanished API is tolerated: reading the resources of a missing API on its + // own still raises, so nothing else is being swallowed on the way past. + AwsException e = assertThrows(AwsException.class, () -> service.getResources(REGION, "nosuchapi")); + assertEquals("NotFoundException", e.getErrorCode()); + } + + @Test + void anApiThatIsStillThereStillReportsItsRoot() { + String apiId = given() + .contentType("application/json") + .body("{\"name\":\"listing-survivor\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract().path("id"); + + assertTrue(service.findRootResourceId(REGION, apiId).isPresent()); + + given() + .when() + .get("/restapis") + .then() + .statusCode(200) + .body("item.findAll { it.id == '" + apiId + "' }[0].rootResourceId", notNullValue()) + .body("item.findAll { it.id == '" + apiId + "' }[0].name", equalTo("listing-survivor")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRestApiResponseFieldsTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRestApiResponseFieldsTest.java new file mode 100644 index 0000000000..462927600e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRestApiResponseFieldsTest.java @@ -0,0 +1,171 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; + +/** + * RestApi response members that clients read but that a caller never supplies: + * rootResourceId, apiKeySource and disableExecuteApiEndpoint. + * + * @see GetRestApi + */ +@QuarkusTest +class ApiGatewayRestApiResponseFieldsTest { + + private String createApi(String name) { + return given() + .contentType("application/json") + .body("{\"name\":\"" + name + "\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .extract().path("id"); + } + + @Test + void createRestApiReportsTheRootResourceId() { + given() + .contentType("application/json") + .body("{\"name\":\"root-id-on-create\"}") + .when() + .post("/restapis") + .then() + .statusCode(201) + .body("rootResourceId", notNullValue()); + } + + @Test + void getRestApiReportsTheIdOfTheResourceAtRoot() { + String apiId = createApi("root-id-on-get"); + + // Whatever GetResources calls the "/" resource is what the API must report, + // otherwise a resource parented on rootResourceId would be orphaned. + String rootFromResources = given() + .when() + .get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + // A freshly created API has exactly one resource: "/". + .body("item.size()", equalTo(1)) + .body("item[0].path", equalTo("/")) + .extract().path("item[0].id"); + + given() + .when() + .get("/restapis/" + apiId) + .then() + .statusCode(200) + .body("rootResourceId", equalTo(rootFromResources)); + } + + @Test + void theReportedRootResourceIdCanParentANewResource() { + String apiId = createApi("root-id-usable"); + String rootId = given() + .when() + .get("/restapis/" + apiId) + .then() + .statusCode(200) + .extract().path("rootResourceId"); + + given() + .contentType("application/json") + .body("{\"pathPart\":\"hello\"}") + .when() + .post("/restapis/" + apiId + "/resources/" + rootId) + .then() + .statusCode(201) + .body("path", equalTo("/hello")) + .body("parentId", equalTo(rootId)); + } + + @Test + void getRestApiReportsApiKeySourceAndExecuteApiEndpointDefaults() { + String apiId = createApi("api-defaults"); + + given() + .when() + .get("/restapis/" + apiId) + .then() + .statusCode(200) + .body("apiKeySource", equalTo("HEADER")) + .body("disableExecuteApiEndpoint", is(false)); + } + + /** + * rootResourceId is reported only when a resource at "/" exists, so the root has to be + * undeletable for the member to be dependable. AWS keeps the root for the life of the + * API: it is created with the API, has no pathPart to address it by, and DeleteResource + * is documented as raising BadRequestException for a request it will not carry out. + */ + @Test + void theRootResourceCannotBeDeleted() { + String apiId = createApi("root-undeletable"); + String rootId = given() + .when() + .get("/restapis/" + apiId) + .then() + .statusCode(200) + .extract().path("rootResourceId"); + + given() + .when() + .delete("/restapis/" + apiId + "/resources/" + rootId) + .then() + .statusCode(400) + .body("message", containsString("root resource")); + + // And the API still reports it, rather than silently losing the member. + given() + .when() + .get("/restapis/" + apiId) + .then() + .statusCode(200) + .body("rootResourceId", equalTo(rootId)); + } + + @Test + void deletingANonRootResourceStillSucceeds() { + String apiId = createApi("child-deletable"); + String rootId = given() + .when() + .get("/restapis/" + apiId) + .then() + .extract().path("rootResourceId"); + + String childId = given() + .contentType("application/json") + .body("{\"pathPart\":\"child\"}") + .when() + .post("/restapis/" + apiId + "/resources/" + rootId) + .then() + .statusCode(201) + .extract().path("id"); + + given() + .when() + .delete("/restapis/" + apiId + "/resources/" + childId) + .then() + .statusCode(202); + } + + @Test + void listRestApisReportsTheSameMembersAsGetRestApi() { + String apiId = createApi("api-in-list"); + + given() + .when() + .get("/restapis") + .then() + .statusCode(200) + .body("item.findAll { it.id == '" + apiId + "' }.rootResourceId", everyItem(notNullValue())); + } +}