fix(apigateway): report rootResourceId and the API key defaults (#3269)

* fix(apigateway): report rootResourceId and the API key defaults

GetRestApi, CreateRestApi and GetRestApis returned only id, name, description,
createdDate, apiStatus, tags and endpointConfiguration. Three documented response
members were missing. None of them is ever supplied by the caller, so a client has
no way to obtain them other than from the response.

rootResourceId is the most load bearing. The root resource is created with the API
and is already reachable through GetResources, it was just not reported on the API
itself -- which is where a client reads it in order to parent its first resource:

    resource "aws_api_gateway_resource" "hello" {
      rest_api_id = aws_api_gateway_rest_api.api.id
      parent_id   = aws_api_gateway_rest_api.api.root_resource_id   # was empty
      path_part   = "hello"
    }

apiKeySource and disableExecuteApiEndpoint are reported with the AWS defaults,
HEADER and false. Neither is settable on a REST API here: createRestApi ignores
both and updateRestApi patches only /name and /description, so the emulated value
is always the default. Reporting it beats omitting it, because a client that reads
an absent member back as "" or null sees a difference from the configuration it
just sent and never converges.

Reference: the GetRestApi response syntax and elements, including the sample
response carrying "rootResourceId" --
https://docs.aws.amazon.com/apigateway/latest/api/API_GetRestApi.html
apiKeySource is documented there with valid values HEADER | AUTHORIZER.

Tests assert that the reported rootResourceId is the same id GetResources gives the
"/" resource, and that a resource can actually be created against it.

* fix(apigateway): refuse to delete the root resource of a REST API

Reporting rootResourceId on the API only holds up if the resource at "/" is
still there. deleteResource had no guard, so a caller could delete the root and
leave the API with nothing to report and nothing to parent a new resource on,
a state with no way back short of recreating the API.

The root is created with the API and has no pathPart to address it by; it goes
away when the API does, via deleteRestApi, which cascades through the store and
is unaffected by this. putRestApi already skipped "/" when clearing resources.

The botocore model shipped with awscli 2.36.30 (apigateway/2015-07-09) lists
BadRequestException, httpStatusCode 400, among the errors of DeleteResource,
which settles the error type for a delete the service refuses to carry out. It
does not document the root-resource case either way, so the refusal itself is a
deliberate choice for the reason above rather than verified AWS parity, and the
message is descriptive rather than copied from AWS.

* fix(apigateway): let a vanished API cost only its rootResourceId

ListRestApis renders a snapshot of the APIs and resolves each one's root
afterwards, and that lookup read the API's resources, whose first act is to load
the API itself. An API deleted between the snapshot and the render was therefore
already gone by the time its root was looked up, and the NotFoundException it
raised turned the whole listing into a 404 rather than costing the caller one
member of one item.

The lookup moves into ApiGatewayService.findRootResourceId, which returns an
empty Optional for an API that is no longer there. The tolerance is narrow: only
NotFoundException is caught, every other AwsException still propagates, and
GetRestApi on a missing API is still a 404 because it loads the API directly.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-08 23:51:05 -05:00
1 parent 922eb0b9e5
commit c57b8ff5f6
4 files changed
+294 -8

No files matched your search

@@ -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<String, Object> 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<RestApi> 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<Map<String, String>> 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;
}
@@ -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.
* <p>
* 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<String> findRootResourceId(String region, String apiId) {
List<ApiGatewayResource> 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));
}
@@ -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"));
}
}
@@ -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 <a href="https://docs.aws.amazon.com/apigateway/latest/api/API_GetRestApi.html">GetRestApi</a>
*/
@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()));
}
}