fix(apigateway): validate imported models in their deployment context (#5645)

* fix(apigateway): resolve imported request model references

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): snapshot request model schemas for deployments

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): match the default body validation error

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(apigateway): expect the AWS default validation message

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): address model snapshot review findings

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): resolve model URLs from deployment snapshots

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(apigateway): make model reference cases collectable

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(apigateway): accept canonical model URLs in every partition

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-15 06:50:46 -04:00
1 parent 6f78083080
commit 5a72b4f561
6 files changed
+508 -17

No files matched your search

@@ -0,0 +1,110 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
import io.github.hectorvent.floci.services.apigateway.model.Model;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class ApiGatewayDeploymentModelTest {
private static final String REGION = "us-east-1";
private static final String ORIGINAL = "{\"type\":\"string\",\"enum\":[\"READY\"]}";
private static final String UPDATED = "{\"type\":\"string\",\"enum\":[\"DONE\"]}";
private static final String SNAPSHOTS = "apigateway-deployment-models.json";
@Test
void deploymentValidationUsesTheSchemaCapturedForExport(@TempDir Path directory) throws Exception {
ApiGatewayService service = spy(service(directory));
String apiId = service.createRestApi(REGION, Map.of("name", "concurrent-model-update")).getId();
Model original = new Model();
original.setName("Status");
original.setSchema(ORIGINAL);
Model updated = new Model();
updated.setName("Status");
updated.setSchema(UPDATED);
doReturn(List.of(original), List.of(updated)).when(service).getModels(REGION, apiId);
Deployment deployment = service.createDeployment(REGION, apiId, Map.of());
assertEquals(ORIGINAL, new ObjectMapper().readTree(deployment.exportSnapshot())
.path("models").get(0).path("schema").asText());
assertEquals(Map.of("Status", ORIGINAL),
service.getDeploymentModelSchemas(REGION, apiId, deployment.id()));
}
@Test
void deploymentModelsSurviveUpdatesDeletionAndRestart(@TempDir Path directory) {
ApiGatewayService service = service(directory);
String apiId = service.createRestApi(REGION, Map.of("name", "snapshot")).getId();
service.createModel(REGION, apiId, Map.of("name", "Status", "schema", ORIGINAL));
String original = service.createDeployment(REGION, apiId, Map.of()).id();
service.updateModel(REGION, apiId, "Status",
List.of(Map.of("op", "replace", "path", "/schema", "value", UPDATED)));
ApiGatewayService restarted = service(directory);
assertEquals(UPDATED, restarted.getModel(REGION, apiId, "Status").getSchema());
assertEquals(Map.of("Status", ORIGINAL), restarted.getDeploymentModelSchemas(REGION, apiId, original));
String updated = restarted.createDeployment(REGION, apiId, Map.of()).id();
restarted.deleteModel(REGION, apiId, "Status");
assertEquals(Map.of("Status", ORIGINAL), restarted.getDeploymentModelSchemas(REGION, apiId, original));
assertEquals(Map.of("Status", UPDATED), restarted.getDeploymentModelSchemas(REGION, apiId, updated));
}
@Test
void emptySnapshotsDifferFromLegacyDeploymentsWithoutSnapshots(@TempDir Path directory) throws Exception {
ApiGatewayService service = service(directory);
String apiId = service.createRestApi(REGION, Map.of("name", "empty")).getId();
String deploymentId = service.createDeployment(REGION, apiId, Map.of()).id();
service.createModel(REGION, apiId, Map.of("name", "Status", "schema", ORIGINAL));
assertTrue(service.getDeploymentModelSchemas(REGION, apiId, deploymentId).isEmpty());
Files.delete(directory.resolve(SNAPSHOTS));
ApiGatewayService legacy = service(directory);
assertEquals(deploymentId, legacy.getDeployment(REGION, apiId, deploymentId).id());
assertEquals(Map.of("Status", ORIGINAL), legacy.getDeploymentModelSchemas(REGION, apiId, deploymentId));
}
@Test
void deletingDeploymentsAndApisRemovesTheirSnapshots(@TempDir Path directory) throws Exception {
ApiGatewayService service = service(directory);
String firstApi = service.createRestApi(REGION, Map.of("name", "first")).getId();
String secondApi = service.createRestApi(REGION, Map.of("name", "second")).getId();
String firstDeployment = service.createDeployment(REGION, firstApi, Map.of()).id();
service.createDeployment(REGION, secondApi, Map.of());
service.deleteDeployment(REGION, firstApi, firstDeployment);
assertEquals(1, new ObjectMapper().readTree(directory.resolve(SNAPSHOTS).toFile()).size());
service.deleteRestApi(REGION, secondApi);
assertTrue(new ObjectMapper().readTree(directory.resolve(SNAPSHOTS).toFile()).isEmpty());
}
private ApiGatewayService service(Path directory) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(directory.toString());
when(config.defaultAccountId()).thenReturn("000000000000");
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode(anyString())).thenReturn("persistent");
return new ApiGatewayService(new StorageFactory(config, access), config,
mock(TlsCertificateManager.class), new RegionResolver(REGION, "000000000000"));
}
}
@@ -2,13 +2,21 @@ package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
@@ -1083,6 +1091,191 @@ class ApiGatewayOpenApiImportTest {
// ──────────────────────────── Request Body Validation ────────────────────────────
@ParameterizedTest
@ValueSource(strings = {"us-east-1", "cn-north-1", "us-gov-west-1"})
@Order(100)
void importedModelReferencesValidateDeployedSiblingModelsAndRecursiveBodies(String region) throws Exception {
RequestSpecification request = new RequestSpecBuilder().addHeader("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20261015/" + region
+ "/apigateway/aws4_request, SignedHeaders=host, Signature=test").build();
String spec = """
{
"openapi":"3.0.1", "info":{"title":"ReferencedWorkflowModels","version":"1"},
"x-amazon-apigateway-request-validators":{
"full":{"validateRequestBody":true,"validateRequestParameters":true}},
"x-amazon-apigateway-request-validator":"full",
"paths":{"/list-workflows":{"post":{
"requestBody":{"content":{"application/json":{
"schema":{"$ref":"#/components/schemas/Request"}}}},
"x-amazon-apigateway-integration":{"type":"MOCK",
"requestTemplates":{"application/json":"{\\"statusCode\\":200}"},
"responses":{"default":{"statusCode":"200",
"responseTemplates":{"application/json":"{\\"accepted\\":true}"}}}}}}},
"components":{"schemas":{
"Category":{"type":"string","enum":["DMS"]},
"Status":{"type":"string","enum":["RUNNING"]},
"Request":{"type":"object","required":["workflowCategory","status"],
"properties":{
"workflowCategory":{"$ref":"#/components/schemas/Category"},
"status":{"$ref":"#/components/schemas/Status"},
"child":{"$ref":"#/components/schemas/Request"}}}}}
}
""";
String apiId = given().spec(request).contentType(ContentType.JSON).queryParam("mode", "import")
.body(spec).post("/restapis").then().statusCode(201).extract().path("id");
AtomicInteger integrationCalls = new AtomicInteger();
HttpServer integration = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
try {
integration.createContext("/accepted", exchange -> {
integrationCalls.incrementAndGet();
byte[] bytes = "{\"accepted\":true}".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
});
integration.start();
String resourceId = given().spec(request).get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item.find { it.path == '/list-workflows' }.id");
given().spec(request).contentType(ContentType.JSON)
.body("{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"POST\",\"uri\":\"http://127.0.0.1:"
+ integration.getAddress().getPort() + "/accepted\"}")
.put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
.then().statusCode(201);
String deployment = given().spec(request).contentType(ContentType.JSON).body("{}")
.post("/restapis/" + apiId + "/deployments")
.then().statusCode(201).extract().path("id");
given().spec(request).contentType(ContentType.JSON)
.body("{\"stageName\":\"test\",\"deploymentId\":\"" + deployment + "\"}")
.post("/restapis/" + apiId + "/stages").then().statusCode(201);
String endpoint = "/execute-api/" + apiId + "/test/list-workflows";
String valid = "{\"workflowCategory\":\"DMS\",\"status\":\"RUNNING\"}";
given().spec(request).contentType(ContentType.JSON).body(valid).post(endpoint)
.then().statusCode(200).body(containsString("accepted"));
given().spec(request).contentType(ContentType.JSON)
.body("{\"workflowCategory\":\"DMS\",\"status\":\"RUNNING\",\"child\":" + valid + "}")
.post(endpoint).then().statusCode(200);
assertEquals(2, integrationCalls.get(), "Valid requests must reach the integration");
assertRejectedWithoutIntegration(request, endpoint, "{\"status\":\"RUNNING\"}", integrationCalls);
assertRejectedWithoutIntegration(request, endpoint, valid.replace("RUNNING", "INVALID"), integrationCalls);
assertRejectedWithoutIntegration(request, endpoint,
"{\"workflowCategory\":\"DMS\",\"status\":\"RUNNING\",\"child\":"
+ valid.replace("RUNNING", "INVALID") + "}", integrationCalls);
String schema = "{\"type\":\"string\",\"enum\":[\"DONE\"]}";
String patch = "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/schema\",\"value\":"
+ mapper.writeValueAsString(schema) + "}]}";
given().spec(request).contentType(ContentType.JSON).body(patch)
.patch("/restapis/" + apiId + "/models/Status").then().statusCode(200);
given().spec(request).contentType(ContentType.JSON).body(valid).post(endpoint).then().statusCode(200);
assertRejectedWithoutIntegration(request, endpoint, valid.replace("RUNNING", "DONE"), integrationCalls);
given().spec(request).contentType(ContentType.JSON).body("{\"stageName\":\"test\"}")
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
assertRejectedWithoutIntegration(request, endpoint, valid, integrationCalls);
given().spec(request).contentType(ContentType.JSON).body(valid.replace("RUNNING", "DONE"))
.post(endpoint).then().statusCode(200);
String storedSchema = given().spec(request).get("/restapis/" + apiId + "/models/Request")
.then().statusCode(200).extract().path("schema");
assertFalse(mapper.readTree(storedSchema).has("components"), "Validation must not rewrite stored models");
String urlSchema = storedSchema.replace("#/components/schemas/",
"https://apigateway.amazonaws.com/restapis/" + apiId + "/models/");
given().spec(request).contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/schema\",\"value\":"
+ mapper.writeValueAsString(urlSchema) + "}]}")
.patch("/restapis/" + apiId + "/models/Request").then().statusCode(200);
given().spec(request).contentType(ContentType.JSON).body("{\"stageName\":\"test\"}")
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
given().spec(request).contentType(ContentType.JSON).body(valid.replace("RUNNING", "DONE"))
.post(endpoint).then().statusCode(200);
given().spec(request).contentType(ContentType.JSON)
.body("{\"workflowCategory\":\"DMS\",\"status\":\"DONE\",\"child\":"
+ valid.replace("RUNNING", "DONE") + "}")
.post(endpoint).then().statusCode(200);
assertRejectedWithoutIntegration(request, endpoint, valid, integrationCalls);
assertRejectedWithoutIntegration(request, endpoint,
"{\"workflowCategory\":\"DMS\",\"status\":\"DONE\",\"child\":" + valid + "}", integrationCalls);
given().spec(request).contentType(ContentType.JSON).body(patch.replace("DONE", "RUNNING"))
.patch("/restapis/" + apiId + "/models/Status").then().statusCode(200);
given().spec(request).delete("/restapis/" + apiId + "/models/Category").then().statusCode(202);
given().spec(request).contentType(ContentType.JSON).body(valid.replace("RUNNING", "DONE"))
.post(endpoint).then().statusCode(200);
assertRejectedWithoutIntegration(request, endpoint, valid, integrationCalls);
given().spec(request).contentType(ContentType.JSON).body(patch)
.patch("/restapis/" + apiId + "/models/Status").then().statusCode(200);
given().spec(request).contentType(ContentType.JSON)
.body("{\"name\":\"Category\",\"schema\":\"{\\\"type\\\":\\\"string\\\",\\\"enum\\\":[\\\"DMS\\\"]}\"}")
.post("/restapis/" + apiId + "/models").then().statusCode(201);
given().spec(request).contentType(ContentType.JSON)
.body("{\"name\":\"UnrelatedInvalid\",\"schema\":\"{invalid\"}")
.post("/restapis/" + apiId + "/models").then().statusCode(201);
ObjectNode annotated = (ObjectNode) mapper.readTree(storedSchema);
annotated.putObject("default").put("$ref", "#/components/schemas/NotAModel");
given().spec(request).contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/schema\",\"value\":"
+ mapper.writeValueAsString(annotated.toString()) + "}]}")
.patch("/restapis/" + apiId + "/models/Request").then().statusCode(200);
given().spec(request).contentType(ContentType.JSON).body("{\"stageName\":\"test\"}")
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
given().spec(request).contentType(ContentType.JSON).body(valid.replace("RUNNING", "DONE"))
.post(endpoint).then().statusCode(200);
String otherApi = given().spec(request).contentType(ContentType.JSON).body("{\"name\":\"OtherModelOwner\"}")
.post("/restapis").then().statusCode(201).extract().path("id");
try {
given().spec(request).contentType(ContentType.JSON)
.body("{\"name\":\"OtherOnly\",\"contentType\":\"application/json\",\"schema\":"
+ mapper.writeValueAsString("{\"type\":\"object\"}") + "}")
.post("/restapis/" + otherApi + "/models").then().statusCode(201);
String missing = "{\"$ref\":\"https://apigateway.amazonaws.com/restapis/"
+ otherApi + "/models/OtherOnly\"}";
given().spec(request).contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/schema\",\"value\":"
+ mapper.writeValueAsString(missing) + "}]}")
.patch("/restapis/" + apiId + "/models/Request").then().statusCode(200);
given().spec(request).contentType(ContentType.JSON).body("{\"stageName\":\"test\"}")
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
assertRejectedWithoutIntegration(request, endpoint, valid, integrationCalls);
} finally {
given().spec(request).delete("/restapis/" + otherApi).then().statusCode(202);
}
AtomicInteger externalReads = new AtomicInteger();
HttpServer external = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
external.createContext("/schema", exchange -> {
externalReads.incrementAndGet();
byte[] bytes = "{}".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
});
external.start();
try {
String externalSchema = "{\"$ref\":\"http://127.0.0.1:" + external.getAddress().getPort() + "/schema\"}";
given().spec(request).contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/schema\",\"value\":"
+ mapper.writeValueAsString(externalSchema) + "}]}")
.patch("/restapis/" + apiId + "/models/Request").then().statusCode(200);
given().spec(request).contentType(ContentType.JSON).body("{\"stageName\":\"test\"}")
.post("/restapis/" + apiId + "/deployments").then().statusCode(201);
assertRejectedWithoutIntegration(request, endpoint, valid, integrationCalls);
assertEquals(0, externalReads.get(), "Request validation must not fetch external schemas");
} finally {
external.stop(0);
}
} finally {
integration.stop(0);
given().spec(request).delete("/restapis/" + apiId).then().statusCode(202);
}
}
private void assertRejectedWithoutIntegration(RequestSpecification request, String endpoint, String body,
AtomicInteger integrationCalls) {
int calls = integrationCalls.get();
given().spec(request).contentType(ContentType.JSON).body(body).post(endpoint)
.then().statusCode(400).body("message", equalTo("Invalid request body"));
assertEquals(calls, integrationCalls.get(), "Rejected requests must not reach the integration");
}
@Test
@Order(96)
void validation_rejectsInvalidBody() throws Exception {
@@ -1171,7 +1364,7 @@ class ApiGatewayOpenApiImportTest {
.post("/execute-api/" + apiId + "/test/items")
.then()
.statusCode(400)
.body(containsString("price"));
.body("message", equalTo("Invalid request body"));
// Wrong type for "price" — should fail
given()
@@ -1295,7 +1488,7 @@ class ApiGatewayOpenApiImportTest {
// ──────────────────────────── Content-Type Tolerance ────────────────────────────
@Test
@Order(70)
@Order(73)
void importRestApi_octetStreamContentType() throws Exception {
String spec = """
{"openapi": "3.0.1", "info": {"title": "OctetImport", "version": "1.0"}, "paths": {}}
@@ -1369,7 +1562,7 @@ class ApiGatewayOpenApiImportTest {
// ──────────────────────────── Security scheme / authorizer import ────────────────────────────
@Test
@Order(90)
@Order(89)
void importRestApi_lambdaAuthorizerFromSecurityScheme() throws Exception {
String spec = """
{
@@ -1645,7 +1838,7 @@ class ApiGatewayOpenApiImportTest {
}
@Test
@Order(95)
@Order(101)
void importRestApi_requestAuthorizerWithoutIdentitySourceRejectsDefaultCaching() {
String title = "InvalidCachedRequestAuthorizer";
String spec = requestAuthorizerSpec(title, "", "/invalid");
@@ -1667,7 +1860,7 @@ class ApiGatewayOpenApiImportTest {
}
@Test
@Order(96)
@Order(102)
void importRestApi_requestAuthorizerWithoutIdentitySourceAllowsZeroTtl() throws Exception {
String spec = requestAuthorizerSpec(
"UncachedRequestAuthorizer", ", \"authorizerResultTtlInSeconds\": 0", "/uncached");
@@ -1691,7 +1884,7 @@ class ApiGatewayOpenApiImportTest {
}
@Test
@Order(97)
@Order(103)
void putRestApi_invalidCachedRequestAuthorizerDoesNotReplaceExistingApi() throws Exception {
String originalSpec = """
{