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

@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigateway;
// REST and v2 both define Authorizer; the less-used REST type is qualified below.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -12,6 +13,9 @@ import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.ValidationMessage;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsEndpoints;
@@ -54,6 +58,7 @@ import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URLDecoder;
@@ -1163,31 +1168,43 @@ public class ApiGatewayExecuteController {
if (modelName != null) {
try {
io.github.hectorvent.floci.services.apigateway.model.Model model =
apiGatewayService.getModel(region, apiId, modelName);
String schemaStr = model.getSchema();
Map<String, String> models = apiGatewayService.getDeploymentModelSchemas(region, apiId,
scope.stage() != null ? scope.stage().getDeploymentId() : null);
String schemaStr = models.get(modelName);
if (schemaStr != null && !schemaStr.isBlank()) {
String bodyStr = body != null ? new String(body, StandardCharsets.UTF_8) : "";
if (bodyStr.isBlank()) {
return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_BODY, 400,
"Invalid request body");
}
JsonNode schemaNode = objectMapper.readTree(schemaStr);
JsonNode schemaNode = modelValidationSchema(models, schemaStr);
JsonNode bodyNode = objectMapper.readTree(bodyStr);
com.networknt.schema.JsonSchemaFactory factory =
com.networknt.schema.JsonSchemaFactory.getInstance(
com.networknt.schema.SpecVersion.VersionFlag.V4);
com.networknt.schema.JsonSchema schema = factory.getSchema(schemaNode);
JsonSchemaFactory factory =
JsonSchemaFactory.getInstance(
SpecVersion.VersionFlag.V4, builder -> builder.schemaLoaders(
loaders -> loaders.add(iri -> {
String prefix = "https://apigateway.amazonaws.com/restapis/" // partition-literal: documented model URI uses this host in every partition
+ apiId + "/models/";
String reference = iri.toString();
String referencedSchema = reference.startsWith(prefix)
? models.get(reference.substring(prefix.length())) : null;
if (referencedSchema == null) {
throw new IllegalArgumentException(
"Model reference is not in this deployment");
}
return () -> new ByteArrayInputStream(
modelValidationSchema(models, referencedSchema)
.toString().getBytes(StandardCharsets.UTF_8));
})));
JsonSchema schema = factory.getSchema(schemaNode);
Set<ValidationMessage> errors = schema.validate(bodyNode);
if (!errors.isEmpty()) {
String errorMsg = errors.iterator().next().getMessage();
return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_BODY, 400,
"Invalid request body: " + errorMsg, errorMsg);
"Invalid request body", errorMsg);
}
}
} catch (AwsException e) {
// Model not found — skip body validation
} catch (Exception e) {
return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_BODY, 400,
"Invalid request body");
@@ -1199,6 +1216,30 @@ public class ApiGatewayExecuteController {
return null;
}
private JsonNode modelValidationSchema(Map<String, String> models, String schema) throws JsonProcessingException {
JsonNode root = objectMapper.readTree(schema);
if (!(root instanceof ObjectNode document)) {
return root;
}
if ((document.has("components") && !document.get("components").isObject())
|| (document.path("components").has("schemas")
&& !document.path("components").get("schemas").isObject())) {
return root;
}
ObjectNode definitions = document.withObject("/components/schemas");
for (Map.Entry<String, String> model : models.entrySet()) {
if (!definitions.has(model.getKey())) {
try {
definitions.set(model.getKey(), objectMapper.readTree(model.getValue()));
} catch (JsonProcessingException ignored) {
// An unrelated malformed model must not invalidate this request. If referenced,
// its absent definition is rejected by the schema validator itself.
}
}
}
return root;
}
private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth,
HttpHeaders headers, String region, String apiId, String stageName,
String httpMethod, String requestPath,
@@ -109,6 +109,7 @@ public class ApiGatewayService implements ResourceProvider {
private final StorageBackend<String, RestApi> apiStore;
private final StorageBackend<String, ApiGatewayResource> resourceStore;
private final StorageBackend<String, Deployment> deploymentStore;
private final StorageBackend<String, Map<String, String>> deploymentModelStore;
private final StorageBackend<String, Stage> stageStore;
private final StorageBackend<String, Authorizer> authorizerStore;
private final StorageBackend<String, ApiKey> apiKeyStore;
@@ -185,6 +186,9 @@ public class ApiGatewayService implements ResourceProvider {
this.deploymentStore = storageFactory.create("apigateway", "apigateway-deployments.json",
new TypeReference<>() {
});
this.deploymentModelStore = storageFactory.create("apigateway", "apigateway-deployment-models.json",
new TypeReference<>() {
});
this.stageStore = storageFactory.create("apigateway", "apigateway-stages.json",
new TypeReference<>() {
});
@@ -415,6 +419,7 @@ public class ApiGatewayService implements ResourceProvider {
String prefix = region + "::" + apiId + "::";
resourceStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(resourceStore::delete);
deploymentStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(deploymentStore::delete);
deploymentModelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(deploymentModelStore::delete);
stageStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(stageStore::delete);
modelStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(modelStore::delete);
requestValidatorStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(requestValidatorStore::delete);
@@ -787,15 +792,18 @@ public class ApiGatewayService implements ResourceProvider {
getRestApi(region, apiId);
String description = (String) request.getOrDefault("description", "");
String snapshot;
Map<String, String> schemas;
try {
snapshot = JSON.writeValueAsString(new DeploymentExportSnapshot(getRestApi(region, apiId),
getResources(region, apiId), getModels(region, apiId), getAuthorizers(region, apiId),
getRequestValidators(region, apiId), getGatewayResponses(region, apiId).stream()
.filter(response -> !response.isDefaultResponse()).toList()));
schemas = modelSchemas(JSON.readValue(snapshot, DeploymentExportSnapshot.class).models());
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot capture REST API deployment", e);
}
Deployment deployment = new Deployment(shortId(10), description, System.currentTimeMillis() / 1000L, snapshot);
deploymentModelStore.put(deploymentKey(region, apiId, deployment.id()), schemas);
deploymentStore.put(deploymentKey(region, apiId, deployment.id()), deployment);
LOG.infov("Created deployment {0} for API {1}", deployment.id(), apiId);
@@ -850,6 +858,32 @@ public class ApiGatewayService implements ResourceProvider {
public void deleteDeployment(String region, String apiId, String deploymentId) {
getDeployment(region, apiId, deploymentId);
deploymentStore.delete(deploymentKey(region, apiId, deploymentId));
deploymentModelStore.delete(deploymentKey(region, apiId, deploymentId));
}
Map<String, String> getDeploymentModelSchemas(String region, String apiId, String deploymentId) {
if (deploymentId != null) {
Optional<Map<String, String>> schemas = deploymentModelStore.get(deploymentKey(region, apiId, deploymentId));
if (schemas.isPresent()) {
return schemas.get();
}
}
// Deployments persisted before model snapshots were introduced retain their existing behavior.
return currentModelSchemas(region, apiId);
}
private Map<String, String> currentModelSchemas(String region, String apiId) {
return modelSchemas(getModels(region, apiId));
}
private Map<String, String> modelSchemas(List<Model> models) {
Map<String, String> schemas = new HashMap<>();
for (Model model : models) {
if (model.getSchema() != null) {
schemas.put(model.getName(), model.getSchema());
}
}
return Map.copyOf(schemas);
}
public Deployment updateDeployment(String region, String apiId, String deploymentId, List<Map<String, String>> patchOperations) {