mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 22:37:55 -05:00
feat(apigateway): generate REST and WebSocket model templates (#9089)
GetModelTemplate now answers for REST and WebSocket models with sample VTL:
the $inputRoot line, two-space indented typed placeholders ("foo", 3.1415),
and an editable ##TODO / #foreach skeleton for arrays, generated from the
latest stored schema. A top-level scalar model is refused with 400
"Unsupported data type for mapping template", a missing WebSocket model with
404 "Invalid model identifier specified: <id>", and HTTP APIs refuse models
at CreateModel.
Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
Signed-off-by: Jackson Price <jxnprice@amazon.com>
This commit is contained in:
1 parent
bc6a2279d4
commit
33d873b705
16 files changed
+1007
-17
No files matched your search
@@ -92,6 +92,19 @@ describe('API Gateway v2', () => {
|
||||
expect(res.ApiKeySelectionExpression).toBe('$request.header.x-api-key');
|
||||
});
|
||||
|
||||
it('should reject models for HTTP APIs', async () => {
|
||||
await expect(gw.send(new CreateModelCommand({
|
||||
ApiId: apiId,
|
||||
Name: 'HttpModel',
|
||||
Schema: JSON.stringify({ type: 'object' }),
|
||||
ContentType: 'application/json',
|
||||
}))).rejects.toMatchObject({
|
||||
name: 'BadRequestException',
|
||||
message: 'Currently, Models are not permitted for APIs with a protocol type of HTTP',
|
||||
$metadata: { httpStatusCode: 400 },
|
||||
});
|
||||
});
|
||||
|
||||
it('should list APIs including the created one', async () => {
|
||||
const res = await gw.send(new GetApisCommand({}));
|
||||
expect(res.Items!.some(a => a.ApiId === apiId)).toBe(true);
|
||||
@@ -500,7 +513,8 @@ describe('API Gateway v2', () => {
|
||||
beforeAll(async () => {
|
||||
const res = await gw.send(new CreateApiCommand({
|
||||
Name: uniqueName('model-test'),
|
||||
ProtocolType: 'HTTP',
|
||||
ProtocolType: 'WEBSOCKET',
|
||||
RouteSelectionExpression: '$request.body.action',
|
||||
}));
|
||||
apiId = res.ApiId!;
|
||||
});
|
||||
|
||||
@@ -123,6 +123,42 @@ Unknown integration type strings produce warnings and leave the method without a
|
||||
integration. With `failOnWarnings=true`, the import or update is rejected before
|
||||
changing the API. Leading/trailing whitespace and non-ASCII lookalikes are not accepted.
|
||||
|
||||
### Model templates
|
||||
|
||||
`GetModelTemplate` returns the same sample VTL format for REST and WebSocket API models.
|
||||
Object properties use two-space indentation and sample values, including `"foo"` for
|
||||
strings and `3.1415` for numbers. Arrays contain a `##TODO:` comment and a
|
||||
`#foreach($elem in $inputRoot.TODO)` placeholder to customize for the source payload.
|
||||
This is a starting point for a mapping template, not a projection of the input JSON.
|
||||
Top-level array directives are unindented, with one space surrounding each sample element.
|
||||
|
||||
Nested objects, typed arrays and finite local JSON Pointer references
|
||||
(`#/definitions/...`) are supported. Updating a model changes its next template;
|
||||
no generated-template cache or additional persistent state is used. The existing
|
||||
`AmazonApiGatewayV2` JSON compatibility target also accepts `GetModelTemplate`, with
|
||||
`ApiId` and `ModelId` inputs and a `Value` response.
|
||||
|
||||
Template generation supports a bounded JSON-schema subset for `application/json` models.
|
||||
Composition (`allOf`, `anyOf`, `oneOf`, `not`), enums, const values, union types,
|
||||
tuple/untyped arrays, external or cyclic references, and property names containing
|
||||
VTL delimiters (`'`, `"`, `\`, `$`, `#`) or control characters return
|
||||
`UnsupportedOperation` (HTTP 501). Constraints such as ranges and formats do not
|
||||
choose the sample values. A schema must state a supported type or provide
|
||||
`properties`/`items` from which a type can be inferred.
|
||||
|
||||
Malformed JSON, including extra tokens after the schema, returns
|
||||
`BadRequestException` (HTTP 400). Top-level scalar models also return HTTP 400,
|
||||
with `Unsupported data type for mapping template: <type>`. Schema admission at
|
||||
model creation and update is unchanged; valid schemas outside the generator's
|
||||
subset remain storable. HTTP APIs reject model creation because models are only
|
||||
supported for WebSocket APIs in API Gateway v2.
|
||||
Template reads for a missing WebSocket model return `NotFoundException` (HTTP 404)
|
||||
with `Invalid model identifier specified: <id>`.
|
||||
|
||||
Local generation limits are 1,048,576 schema characters, 4,096 visited schema nodes,
|
||||
32 levels of nesting and 262,144 output characters. These are Floci limits, not
|
||||
AWS service quotas.
|
||||
|
||||
### Supported Operations
|
||||
|
||||
| Category | Operations |
|
||||
@@ -141,7 +177,7 @@ changing the API. Leading/trailing whitespace and non-ASCII lookalikes are not a
|
||||
| **Usage Plan Keys** | CreateUsagePlanKey, GetUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey |
|
||||
| **Request Validators** | CreateRequestValidator, GetRequestValidator, GetRequestValidators, UpdateRequestValidator, DeleteRequestValidator |
|
||||
| **Gateway Responses** | PutGatewayResponse, GetGatewayResponse, GetGatewayResponses, UpdateGatewayResponse, DeleteGatewayResponse |
|
||||
| **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
|
||||
| **Models** | CreateModel, GetModel, GetModels, GetModelTemplate, UpdateModel, DeleteModel |
|
||||
| **Documentation Parts** | CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart |
|
||||
| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName |
|
||||
| **Base Path Mappings** | CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, UpdateBasePathMapping, DeleteBasePathMapping |
|
||||
@@ -432,7 +468,6 @@ treated as a gateway response.
|
||||
These management-plane operations have no handler in v1. Calls will return `404` or an error:
|
||||
|
||||
- Authorizer testing: `TestInvokeAuthorizer`
|
||||
- Model templates: `GetModelTemplate`
|
||||
- Documentation versions (5 operations)
|
||||
- Client Certificates (5 operations)
|
||||
- `ImportDocumentationParts`
|
||||
@@ -1104,7 +1139,7 @@ listener relays the request unchanged and does not add a hop.
|
||||
| **Authorizers** | CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer |
|
||||
| **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage |
|
||||
| **Deployments** | CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment |
|
||||
| **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
|
||||
| **Models** | CreateModel, GetModel, GetModels, GetModelTemplate, UpdateModel, DeleteModel |
|
||||
| **Domain Names** | CreateDomainName, GetDomainName, GetDomainNames, UpdateDomainName, DeleteDomainName |
|
||||
| **API Mappings** | CreateApiMapping, GetApiMapping, GetApiMappings, UpdateApiMapping, DeleteApiMapping |
|
||||
| **VPC Links** | CreateVpcLink, GetVpcLink, GetVpcLinks, UpdateVpcLink, DeleteVpcLink |
|
||||
|
||||
@@ -36,8 +36,8 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 69 |
|
||||
| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 23 |
|
||||
| [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 |
|
||||
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 101 |
|
||||
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 66 (+ the data plane) |
|
||||
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 102 |
|
||||
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 67 (+ the data plane) |
|
||||
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 180 |
|
||||
| [STS](sts.md) | `POST /` with `Action=` param | Query | 11 |
|
||||
| [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/** Bounded JSON Schema traversal for API Gateway's sample mapping templates. */
|
||||
public final class ModelTemplateGenerator {
|
||||
private static final ObjectMapper JSON = new ObjectMapper()
|
||||
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
private static final int MAX_SCHEMA_CHARACTERS = 1_048_576;
|
||||
private static final int MAX_NODES = 4_096;
|
||||
private static final int MAX_DEPTH = 32;
|
||||
private static final int MAX_OUTPUT_CHARACTERS = 262_144;
|
||||
private static final Set<String> TYPES = Set.of("object", "array", "string", "integer", "number", "boolean", "null");
|
||||
|
||||
private ModelTemplateGenerator() {}
|
||||
|
||||
public static String generate(String schema, String contentType) {
|
||||
if (contentType != null && !contentType.split(";", 2)[0].trim().equalsIgnoreCase("application/json")) {
|
||||
throw unsupported("Only application/json model templates are supported.");
|
||||
}
|
||||
if (schema == null || schema.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "The model does not contain a JSON schema.", 400);
|
||||
}
|
||||
if (schema.length() > MAX_SCHEMA_CHARACTERS) {
|
||||
throw unsupported("The model schema exceeds the local template generation limit.");
|
||||
}
|
||||
JsonNode document;
|
||||
try {
|
||||
document = JSON.readTree(schema);
|
||||
} catch (JsonProcessingException error) {
|
||||
throw new AwsException("BadRequestException", "The model schema is not valid JSON.", 400);
|
||||
}
|
||||
Compiler compiler = new Compiler(document);
|
||||
Shape shape = compiler.read(document, 0, new HashSet<>());
|
||||
if (!"object".equals(shape.type()) && !"array".equals(shape.type())) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Unsupported data type for mapping template: " + shape.type(), 400);
|
||||
}
|
||||
Output output = new Output();
|
||||
output.append("#set($inputRoot = $input.path('$'))\n");
|
||||
render(shape, 0, output);
|
||||
return output.text.toString();
|
||||
}
|
||||
|
||||
private static void render(Shape shape, int depth, Output output) {
|
||||
String indent = " ".repeat(depth);
|
||||
String childIndent = indent + " ";
|
||||
switch (shape.type()) {
|
||||
case "object" -> {
|
||||
output.append("{");
|
||||
boolean first = true;
|
||||
for (Map.Entry<String, Shape> property : shape.properties().entrySet()) {
|
||||
if (!first) {
|
||||
output.append(",");
|
||||
}
|
||||
first = false;
|
||||
output.append("\n" + childIndent + TextNode.valueOf(property.getKey()) + " : ");
|
||||
render(property.getValue(), depth + 1, output);
|
||||
}
|
||||
if (!first) {
|
||||
output.append("\n" + indent);
|
||||
}
|
||||
output.append("}");
|
||||
}
|
||||
case "array" -> {
|
||||
output.append("[\n" + indent
|
||||
+ "##TODO: Update this foreach loop to reference array from input json\n"
|
||||
+ indent + "#foreach($elem in $inputRoot.TODO)\n" + indent + " ");
|
||||
render(shape.items(), depth + 1, output);
|
||||
output.append(" \n" + indent + "#if($foreach.hasNext),#end\n"
|
||||
+ indent + "#end\n" + indent + "]");
|
||||
}
|
||||
case "string" -> output.append("\"foo\"");
|
||||
case "integer" -> output.append("1");
|
||||
case "number" -> output.append("3.1415");
|
||||
case "boolean" -> output.append("true");
|
||||
case "null" -> output.append("null");
|
||||
default -> throw new IllegalStateException("Uncompiled schema type");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException unsupported(String message) {
|
||||
return new AwsException("UnsupportedOperation", message, 501);
|
||||
}
|
||||
|
||||
private record Shape(String type, Map<String, Shape> properties, Shape items) {}
|
||||
|
||||
private static final class Compiler {
|
||||
private final JsonNode root;
|
||||
private int nodes;
|
||||
|
||||
private Compiler(JsonNode root) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
private Shape read(JsonNode schema, int depth, Set<String> references) {
|
||||
nodes++;
|
||||
if (nodes > MAX_NODES || depth > MAX_DEPTH) {
|
||||
throw unsupported("The model schema exceeds the local template traversal limit.");
|
||||
}
|
||||
if (schema == null || !schema.isObject()) {
|
||||
throw unsupported("Model templates require JSON Schema objects.");
|
||||
}
|
||||
for (String keyword : Set.of("allOf", "anyOf", "oneOf", "not", "enum", "const")) {
|
||||
if (schema.has(keyword)) {
|
||||
throw unsupported("Model template generation does not support " + keyword + ".");
|
||||
}
|
||||
}
|
||||
if (schema.has("$ref")) {
|
||||
String reference = schema.path("$ref").asText();
|
||||
if (!reference.startsWith("#/")) {
|
||||
throw unsupported("Only finite local JSON Pointer references are supported.");
|
||||
}
|
||||
if (!references.add(reference)) {
|
||||
throw unsupported("Cyclic model references are not supported.");
|
||||
}
|
||||
try {
|
||||
JsonNode target = root.at(reference.substring(1));
|
||||
if (target.isMissingNode()) {
|
||||
throw unsupported("The local model reference could not be resolved.");
|
||||
}
|
||||
return read(target, depth + 1, references);
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw unsupported("The local model reference is not a valid JSON Pointer.");
|
||||
} finally {
|
||||
references.remove(reference);
|
||||
}
|
||||
}
|
||||
JsonNode declaredType = schema.get("type");
|
||||
if (declaredType != null && !declaredType.isTextual()) {
|
||||
throw unsupported("Model templates require a single supported JSON type at each value.");
|
||||
}
|
||||
String type = declaredType == null ? "" : declaredType.textValue();
|
||||
if (declaredType == null && schema.has("properties")) {
|
||||
type = "object";
|
||||
} else if (declaredType == null && schema.has("items")) {
|
||||
type = "array";
|
||||
}
|
||||
if (!TYPES.contains(type)) {
|
||||
throw unsupported("Model templates require a single supported JSON type at each value.");
|
||||
}
|
||||
Map<String, Shape> properties = new LinkedHashMap<>();
|
||||
Shape items = null;
|
||||
if ("object".equals(type) && schema.has("properties")) {
|
||||
JsonNode declared = schema.get("properties");
|
||||
if (!declared.isObject()) {
|
||||
throw unsupported("Model properties must be a JSON Schema object.");
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> property : declared.properties()) {
|
||||
String name = property.getKey();
|
||||
if (name.chars().anyMatch(character -> character < 32 || "'\"\\$#".indexOf(character) >= 0)) {
|
||||
throw unsupported("Property names containing VTL delimiters or control characters are not supported.");
|
||||
}
|
||||
properties.put(name, read(property.getValue(), depth + 1, references));
|
||||
}
|
||||
} else if ("array".equals(type)) {
|
||||
items = read(schema.get("items"), depth + 1, references);
|
||||
}
|
||||
return new Shape(type, properties, items);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Output {
|
||||
private final StringBuilder text = new StringBuilder();
|
||||
|
||||
private void append(String value) {
|
||||
if (text.length() + value.length() > MAX_OUTPUT_CHARACTERS) {
|
||||
throw unsupported("The generated template exceeds the local output limit.");
|
||||
}
|
||||
text.append(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1213,6 +1213,16 @@ public class ApiGatewayController {
|
||||
return Response.ok(toModelNode(service.getModel(region, apiId, modelName)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/models/{modelName}/default_template")
|
||||
public Response getModelTemplate(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
|
||||
@PathParam("modelName") String modelName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
String value = service.getModelTemplate(region, apiId, modelName);
|
||||
return Response.ok(objectMapper.createObjectNode().put("value", value).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/restapis/{apiId}/models/{modelName}")
|
||||
public Response updateModel(@Context HttpHeaders headers, @PathParam("apiId") String apiId, @PathParam("modelName") String modelName, String body) {
|
||||
@@ -2239,6 +2249,16 @@ public class ApiGatewayController {
|
||||
return Response.ok(toV2ModelNode(v2Service.getModel(region, apiId, modelId)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v2/apis/{apiId}/models/{modelId}/template")
|
||||
public Response getV2ModelTemplate(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
|
||||
@PathParam("modelId") String modelId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
String value = v2Service.getModelTemplate(region, apiId, modelId);
|
||||
return Response.ok(objectMapper.createObjectNode().put("value", value).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/v2/apis/{apiId}/models/{modelId}")
|
||||
public Response updateV2Model(@Context HttpHeaders headers,
|
||||
|
||||
@@ -15,6 +15,7 @@ import io.floci.aws.core.common.AwsPartitions;
|
||||
import io.floci.aws.core.common.AwsRegionFacts;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.CloudFrontEdgeDomain;
|
||||
import io.floci.aws.core.common.ModelTemplateGenerator;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.ReservedTags;
|
||||
@@ -2504,6 +2505,12 @@ public class ApiGatewayService implements ResourceProvider, Resettable {
|
||||
return model;
|
||||
}
|
||||
|
||||
public String getModelTemplate(String region, String apiId, String modelName) {
|
||||
getRestApi(region, apiId);
|
||||
Model model = getModel(region, apiId, modelName);
|
||||
return ModelTemplateGenerator.generate(model.getSchema(), model.getContentType());
|
||||
}
|
||||
|
||||
public List<Model> getModels(String region, String apiId) {
|
||||
getRestApi(region, apiId);
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
|
||||
@@ -83,6 +83,7 @@ public class ApiGatewayV2JsonHandler {
|
||||
case "DeleteIntegrationResponse" -> handleDeleteIntegrationResponse(request, region);
|
||||
case "CreateModel" -> handleCreateModel(request, region);
|
||||
case "GetModel" -> handleGetModel(request, region);
|
||||
case "GetModelTemplate" -> handleGetModelTemplate(request, region);
|
||||
case "GetModels" -> handleGetModels(request, region);
|
||||
case "UpdateModel" -> handleUpdateModel(request, region);
|
||||
case "DeleteModel" -> handleDeleteModel(request, region);
|
||||
@@ -492,6 +493,14 @@ public class ApiGatewayV2JsonHandler {
|
||||
return Response.ok(root.toString()).build();
|
||||
}
|
||||
|
||||
private Response handleGetModelTemplate(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String modelId = request.path("ModelId").asText();
|
||||
String template = service.getModelTemplate(region, apiId, modelId);
|
||||
ObjectNode response = objectMapper.createObjectNode().put("Value", template);
|
||||
return Response.ok(response.toString()).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateModel(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String modelId = request.path("ModelId").asText();
|
||||
|
||||
@@ -5,6 +5,7 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsEndpoints;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.ModelTemplateGenerator;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
@@ -1457,7 +1458,11 @@ public class ApiGatewayV2Service {
|
||||
// ──────────────────────────── Model CRUD ────────────────────────────
|
||||
|
||||
public Model createModel(String region, String apiId, Map<String, Object> request) {
|
||||
getApi(region, apiId);
|
||||
Api api = getApi(region, apiId);
|
||||
if (!"WEBSOCKET".equals(api.getProtocolType())) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Currently, Models are not permitted for APIs with a protocol type of HTTP", 400);
|
||||
}
|
||||
Model model = new Model();
|
||||
model.setModelId(shortId(10));
|
||||
model.setName((String) request.get("name"));
|
||||
@@ -1473,6 +1478,14 @@ public class ApiGatewayV2Service {
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Model not found", 404));
|
||||
}
|
||||
|
||||
public String getModelTemplate(String region, String apiId, String modelId) {
|
||||
getApi(region, apiId);
|
||||
Model model = modelStore.get(modelKey(region, apiId, modelId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException",
|
||||
"Invalid model identifier specified: " + modelId, 404));
|
||||
return ModelTemplateGenerator.generate(model.getSchema(), model.getContentType());
|
||||
}
|
||||
|
||||
public List<Model> getModels(String region, String apiId) {
|
||||
getApi(region, apiId);
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ModelTemplateGeneratorTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{}", "true", "null", "{\"type\":[\"string\",\"null\"]}",
|
||||
"{\"type\":[\"object\",\"null\"],\"properties\":{}}",
|
||||
"{\"type\":null,\"items\":{\"type\":\"string\"}}",
|
||||
"{\"type\":\"\",\"properties\":{}}",
|
||||
"{\"allOf\":[{\"type\":\"object\"}]}", "{\"type\":\"string\",\"enum\":[\"a\"]}",
|
||||
"{\"$ref\":\"https://example.invalid/schema\"}", "{\"$ref\":\"#/missing\"}",
|
||||
"{\"type\":\"array\"}", "{\"type\":\"array\",\"items\":[{\"type\":\"string\"}]}",
|
||||
"{\"type\":\"object\",\"properties\":[]}",
|
||||
"{\"type\":\"object\",\"properties\":{\"#set\":{\"type\":\"string\"}}}",
|
||||
"{\"definitions\":{\"Loop\":{\"$ref\":\"#/definitions/Loop\"}},\"$ref\":\"#/definitions/Loop\"}"
|
||||
})
|
||||
void explicitlyRefusesUnsupportedSchemas(String schema) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate(schema, "application/json"));
|
||||
assertEquals(501, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedSchemaHasAClientError() {
|
||||
assertEquals(400, assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate("{", "application/json")).getHttpStatus());
|
||||
assertEquals(400, assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate(null, "application/json")).getHttpStatus());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{\"type\":\"string\"} garbage", "{\"type\":\"string\"} {\"type\":\"number\"}"})
|
||||
void rejectsTrailingTokens(String schema) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate(schema, "application/json"));
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertEquals("The model schema is not valid JSON.", error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsWhitespaceAfterTheSchema() {
|
||||
assertTrue(ModelTemplateGenerator.generate("{\"type\":\"object\"} \n\t", "application/json")
|
||||
.startsWith("#set($inputRoot"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesNonJsonContent() {
|
||||
assertEquals(501, assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate("{\"type\":\"string\"}", "application/xml"))
|
||||
.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void boundsDeepAndLargeSchemasBeforeUnboundedExpansion() {
|
||||
String schema = "{\"type\":\"string\"}";
|
||||
for (int i = 0; i < 35; i++) {
|
||||
schema = "{\"type\":\"array\",\"items\":" + schema + "}";
|
||||
}
|
||||
String deep = schema;
|
||||
assertEquals(501, assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate(deep, "application/json")).getHttpStatus());
|
||||
assertEquals(501, assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate("x".repeat(1_048_577), "application/json"))
|
||||
.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void boundsGeneratedOutputIndependentlyOfSchemaTraversal() {
|
||||
ObjectNode schema = new ObjectMapper().createObjectNode().put("type", "object");
|
||||
ObjectNode properties = schema.putObject("properties");
|
||||
String name = "a".repeat(8_000);
|
||||
for (int i = 0; i < 40; i++) {
|
||||
properties.putObject(name + i).put("type", "string");
|
||||
}
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate(schema.toString(), "application/json"));
|
||||
assertEquals(501, error.getHttpStatus());
|
||||
assertTrue(error.getMessage().contains("output limit"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void referenceExpansionIsBoundedAndRepeatedFiniteReferencesWork() {
|
||||
String schema = """
|
||||
{"definitions":{"S":{"type":"string"}},"type":"object","properties":{
|
||||
"left":{"$ref":"#/definitions/S"},"right":{"$ref":"#/definitions/S"}}}
|
||||
""";
|
||||
assertTrue(ModelTemplateGenerator.generate(schema, "application/json; charset=utf-8")
|
||||
.contains("\"right\" : "));
|
||||
String many = "{\"type\":\"object\",\"properties\":{";
|
||||
StringBuilder properties = new StringBuilder(many);
|
||||
for (int i = 0; i < 4_100; i++) {
|
||||
if (i > 0) {
|
||||
properties.append(',');
|
||||
}
|
||||
properties.append('"').append(i).append("\":{\"type\":\"string\"}");
|
||||
}
|
||||
properties.append("}}");
|
||||
assertEquals(501, assertThrows(AwsException.class,
|
||||
() -> ModelTemplateGenerator.generate(properties.toString(), "application/json"))
|
||||
.getHttpStatus());
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package io.floci.aws.services.apigateway;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.awscore.exception.AwsServiceException;
|
||||
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
|
||||
import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.statement;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class ApiGatewayModelTemplateIamIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void scopedSdkReadAndExplicitDenyCoverTheActualTemplateRoute(boolean websocket) {
|
||||
String prefix = websocket ? "/v2/apis/" : "/restapis/";
|
||||
String api = given().header("Authorization", auth("test", "apigateway"))
|
||||
.contentType("application/json")
|
||||
.body(websocket ? Map.of("name", "template-iam", "protocolType", "WEBSOCKET",
|
||||
"routeSelectionExpression", "$request.body.action") : Map.of("name", "template-iam"))
|
||||
.post(prefix.substring(0, prefix.length() - 1)).then().statusCode(201)
|
||||
.extract().path(websocket ? "apiId" : "id");
|
||||
cleanup.register(() -> given().port(endpoint.getPort()).header("Authorization", auth("test", "apigateway"))
|
||||
.delete(prefix + api));
|
||||
String model = given().header("Authorization", auth("test", "apigateway"))
|
||||
.contentType("application/json")
|
||||
.body(Map.of("name", "IamModel", "contentType", "application/json", "schema", "{\"type\":\"object\"}"))
|
||||
.post(prefix + api + "/models").then().statusCode(201).extract().path(websocket ? "modelId" : "name");
|
||||
String path = prefix + api + "/models/" + model + (websocket ? "/template" : "/default_template");
|
||||
String resource = "arn:aws:apigateway:us-east-1::" + (websocket ? path.substring(3) : path);
|
||||
String user = "template-reader-" + UUID.randomUUID();
|
||||
String key = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), auth("test", "iam"), user).accessKeyId();
|
||||
policy(user, statement("Allow", "apigateway:GET", resource));
|
||||
assertFalse(read(websocket, key, api, model).isBlank());
|
||||
policy(user, statement("Allow", "apigateway:GET", resource + "-wrong"));
|
||||
assertEquals(403, assertThrows(AwsServiceException.class, () -> read(websocket, key, api, model)).statusCode());
|
||||
// Explicitly allow the spoofed action so this checks route attribution, not a blanket refusal.
|
||||
policy(user, statement("Allow", "apigateway:*", "*") + "," + statement("Deny", "apigateway:GET", resource));
|
||||
assertEquals(403, assertThrows(AwsServiceException.class, () -> read(websocket, key, api, model)).statusCode());
|
||||
given().header("Authorization", auth(key, "apigateway"))
|
||||
.header("X-Amz-Target", "AmazonApiGatewayV2.CreateApi")
|
||||
.get(path + "?Action=CreateApi").then().statusCode(403).body(containsString("apigateway:GET"));
|
||||
}
|
||||
|
||||
private String read(boolean websocket, String key, String api, String model) {
|
||||
if (websocket) {
|
||||
try (ApiGatewayV2Client client = AwsTestClients.create(ApiGatewayV2Client.builder(), key, "test",
|
||||
Region.US_EAST_1, Apache5HttpClient.builder(), endpoint)) {
|
||||
return client.getModelTemplate(request -> request.apiId(api).modelId(model)).value();
|
||||
}
|
||||
}
|
||||
try (ApiGatewayClient client = AwsTestClients.create(ApiGatewayClient.builder(), key, "test",
|
||||
Region.US_EAST_1, Apache5HttpClient.builder(), endpoint)) {
|
||||
return client.getModelTemplate(request -> request.restApiId(api).modelName(model)).value();
|
||||
}
|
||||
}
|
||||
|
||||
private void policy(String user, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("test", "iam"), user, "template-read",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package io.floci.aws.services.apigateway;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.config.TlsCertificateManager;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.ServiceConfigAccess;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
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;
|
||||
|
||||
class ApiGatewayModelTemplatePersistenceTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void restTemplateUsesTheLatestPersistedSchemaAfterRestart(@TempDir Path directory) {
|
||||
Services first = services(directory);
|
||||
String api = first.rest().createRestApi(REGION, Map.of("name", "rest-template")).getId();
|
||||
first.rest().createModel(REGION, api, Map.of("name", "Model", "schema", schema("string")));
|
||||
String original = first.rest().getModelTemplate(REGION, api, "Model");
|
||||
assertEquals(original, services(directory).rest().getModelTemplate(REGION, api, "Model"));
|
||||
first.rest().updateModel(REGION, api, "Model",
|
||||
List.of(Map.of("op", "replace", "path", "/schema", "value", schema("boolean"))));
|
||||
Services restarted = services(directory);
|
||||
assertNotEquals(original, restarted.rest().getModelTemplate(REGION, api, "Model"));
|
||||
restarted.rest().deleteModel(REGION, api, "Model");
|
||||
assertEquals(404, assertThrows(AwsException.class,
|
||||
() -> services(directory).rest().getModelTemplate(REGION, api, "Model")).getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void webSocketTemplateUsesTheLatestPersistedSchemaAfterRestart(@TempDir Path directory) {
|
||||
Services first = services(directory);
|
||||
String api = first.socket().createApi(REGION, Map.of("name", "socket-template", "protocolType", "WEBSOCKET",
|
||||
"routeSelectionExpression", "$request.body.action")).getApiId();
|
||||
String model = first.socket().createModel(REGION, api,
|
||||
Map.of("name", "Model", "schema", schema("string"))).getModelId();
|
||||
String original = first.socket().getModelTemplate(REGION, api, model);
|
||||
assertEquals(original, services(directory).socket().getModelTemplate(REGION, api, model));
|
||||
first.socket().updateModel(REGION, api, model, Map.of("schema", schema("boolean")));
|
||||
Services restarted = services(directory);
|
||||
assertNotEquals(original, restarted.socket().getModelTemplate(REGION, api, model));
|
||||
restarted.socket().deleteModel(REGION, api, model);
|
||||
assertEquals(404, assertThrows(AwsException.class,
|
||||
() -> services(directory).socket().getModelTemplate(REGION, api, model)).getHttpStatus());
|
||||
}
|
||||
|
||||
private static String schema(String type) {
|
||||
return "{\"type\":\"object\",\"properties\":{\"value\":{\"type\":\"" + type + "\"}}}";
|
||||
}
|
||||
|
||||
private Services services(Path directory) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.storage().persistentPath()).thenReturn(directory.toString());
|
||||
when(config.storage().wal().compactionIntervalMs()).thenReturn(3_600_000L);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode(anyString())).thenReturn("persistent");
|
||||
StorageFactory storage = new StorageFactory(config, access);
|
||||
RegionResolver regions = new RegionResolver(REGION, "000000000000");
|
||||
ApiGatewayV2Service socket = new ApiGatewayV2Service(storage, config, regions);
|
||||
ApiGatewayService rest = new ApiGatewayService(storage, config, mock(TlsCertificateManager.class),
|
||||
regions, socket, Clock.systemUTC());
|
||||
return new Services(rest, socket);
|
||||
}
|
||||
|
||||
private record Services(ApiGatewayService rest, ApiGatewayV2Service socket) {}
|
||||
}
|
||||
+414
@@ -0,0 +1,414 @@
|
||||
package io.floci.aws.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.awscore.exception.AwsServiceException;
|
||||
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
|
||||
import software.amazon.awssdk.services.apigateway.model.PatchOperation;
|
||||
import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class ApiGatewayModelTemplateSdkIntegrationTest {
|
||||
private static final String SCHEMA = """
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"ratio": {
|
||||
"type": "number"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"nothing": {
|
||||
"type": "null"
|
||||
},
|
||||
"nested": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"with space": {
|
||||
"type": "string"
|
||||
},
|
||||
"a.b": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"words": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"rows": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"label": {
|
||||
"type": "string"
|
||||
},
|
||||
"values": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
private static final String REFERENCE_SCHEMA = """
|
||||
{
|
||||
"definitions": {
|
||||
"a/b": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"hyphen-key": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"first": {
|
||||
"$ref": "#/definitions/a~1b"
|
||||
},
|
||||
"second": {
|
||||
"$ref": "#/definitions/a~1b"
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@Inject
|
||||
VtlTemplateEngine engine;
|
||||
@Inject
|
||||
ObjectMapper json;
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@BeforeAll
|
||||
static void configureJsonCompatibilityContentType() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void generatedSamplesRenderNestedValuesAndArrayPlaceholders(boolean websocket) throws Exception {
|
||||
try (Fixture fixture = new Fixture(websocket)) {
|
||||
String model = fixture.createModel("TypedModel", SCHEMA);
|
||||
String template = fixture.template(model);
|
||||
assertTrue(template.contains("\n \"name\" : \"foo\","));
|
||||
assertTrue(template.contains("##TODO: Update this foreach loop to reference array from input json"));
|
||||
assertTrue(template.contains("#foreach($elem in $inputRoot.TODO)"));
|
||||
JsonNode output = render(template, "{\"TODO\":[{},{}]}");
|
||||
assertEquals("foo", output.get("name").textValue());
|
||||
assertEquals(1, output.get("count").intValue());
|
||||
assertEquals(3.1415, output.get("ratio").doubleValue());
|
||||
assertTrue(output.get("enabled").booleanValue());
|
||||
assertTrue(output.get("nothing").isNull());
|
||||
assertEquals("foo", output.at("/nested/with space").textValue());
|
||||
assertTrue(output.at("/nested/a.b").booleanValue());
|
||||
assertEquals(2, output.get("words").size());
|
||||
assertEquals("foo", output.at("/words/0").textValue());
|
||||
assertEquals(1, output.at("/rows/0/values/0").intValue());
|
||||
String reference = fixture.createModel("ReferenceModel", REFERENCE_SCHEMA);
|
||||
JsonNode referenceInput = json.readTree("""
|
||||
{"first":{"hyphen-key":"left"},"second":{"hyphen-key":"right"}}
|
||||
""");
|
||||
JsonNode referenceOutput = render(fixture.template(reference), referenceInput.toString());
|
||||
assertEquals("foo", referenceOutput.at("/first/hyphen-key").textValue());
|
||||
assertEquals("foo", referenceOutput.at("/second/hyphen-key").textValue());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void bothSdkRoutesReturnTheDocumentedAwsSample(boolean websocket) {
|
||||
String schema = """
|
||||
{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"},
|
||||
"op":{"type":"string"},"c":{"type":"number"}}}
|
||||
""";
|
||||
String expected = """
|
||||
#set($inputRoot = $input.path('$'))
|
||||
{
|
||||
"a" : 3.1415,
|
||||
"b" : 3.1415,
|
||||
"op" : "foo",
|
||||
"c" : 3.1415
|
||||
}""";
|
||||
try (Fixture fixture = new Fixture(websocket)) {
|
||||
assertEquals(expected, fixture.template(fixture.createModel("DocumentedSample", schema)));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void bothSdkRoutesReturnTheAwsStringArraySkeleton(boolean websocket) throws Exception {
|
||||
String schema = """
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
""";
|
||||
String expected = """
|
||||
#set($inputRoot = $input.path('$'))
|
||||
[
|
||||
##TODO: Update this foreach loop to reference array from input json
|
||||
#foreach($elem in $inputRoot.TODO)
|
||||
"foo"\s
|
||||
#if($foreach.hasNext),#end
|
||||
#end
|
||||
]""";
|
||||
try (Fixture fixture = new Fixture(websocket)) {
|
||||
String template = fixture.template(fixture.createModel("StringArray", schema));
|
||||
assertEquals(expected, template);
|
||||
assertEquals(json.readTree("[]"), render(template, "{\"TODO\":[]}"));
|
||||
assertEquals(json.readTree("[\"foo\"]"), render(template, "{\"TODO\":[{}]}"));
|
||||
assertEquals(json.readTree("[\"foo\",\"foo\"]"), render(template, "{\"TODO\":[{},{}]}"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void websocketMissingModelUsesTemplateSpecificError() {
|
||||
try (Fixture fixture = new Fixture(true)) {
|
||||
String model = "missing-model";
|
||||
String message = "Invalid model identifier specified: " + model;
|
||||
AwsServiceException error = assertThrows(AwsServiceException.class, () -> fixture.template(model));
|
||||
assertEquals(404, error.statusCode());
|
||||
assertEquals("NotFoundException", error.awsErrorDetails().errorCode());
|
||||
assertEquals(message, error.awsErrorDetails().errorMessage());
|
||||
jsonTemplate(fixture.apiId, model).statusCode(404).body(containsString(message));
|
||||
|
||||
AwsServiceException modelError = assertThrows(AwsServiceException.class,
|
||||
() -> fixture.socket.getModel(request -> request.apiId(fixture.apiId).modelId(model)));
|
||||
assertEquals("Model not found", modelError.awsErrorDetails().errorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void topLevelStringModelsCannotGenerateTemplates(boolean websocket) {
|
||||
try (Fixture fixture = new Fixture(websocket)) {
|
||||
String model = fixture.createModel("Scalar", "{\"type\":\"string\"}");
|
||||
AwsServiceException error = assertThrows(AwsServiceException.class, () -> fixture.template(model));
|
||||
assertEquals(400, error.statusCode());
|
||||
assertEquals("Unsupported data type for mapping template: string", error.awsErrorDetails().errorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void modelUpdatesDeletionAndOwnedApiBoundariesAreObserved(boolean websocket) throws Exception {
|
||||
try (Fixture fixture = new Fixture(websocket)) {
|
||||
String model = fixture.createModel("LifecycleModel", valueSchema("string"));
|
||||
assertTrue(render(fixture.template(model), "{}").get("value").isTextual());
|
||||
fixture.update(model, valueSchema("integer"));
|
||||
assertTrue(render(fixture.template(model), "{}").get("value").isIntegralNumber());
|
||||
assertStatus(404, () -> fixture.templateAs(model, "test", Region.US_WEST_2));
|
||||
assertStatus(404, () -> fixture.templateAs(model, "987654321098", Region.US_EAST_1));
|
||||
assertStatus(404, () -> fixture.template("MissingModel"));
|
||||
String realApi = fixture.apiId;
|
||||
try {
|
||||
fixture.apiId = "missing-api";
|
||||
assertStatus(404, () -> fixture.template(model));
|
||||
} finally {
|
||||
fixture.apiId = realApi;
|
||||
}
|
||||
fixture.deleteModel(model);
|
||||
assertStatus(404, () -> fixture.template(model));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void unsupportedSchemasAreExplicitAndDoNotChangeStoredModels(boolean websocket) {
|
||||
try (Fixture fixture = new Fixture(websocket)) {
|
||||
String schema = "{\"allOf\":[{\"type\":\"object\"}]}";
|
||||
String model = fixture.createModel("CompositionModel", schema);
|
||||
assertStatus(501, () -> fixture.template(model));
|
||||
assertEquals(schema, fixture.schema(model));
|
||||
fixture.update(model, valueSchema("boolean"));
|
||||
assertFalse(fixture.template(model).isBlank());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void websocketJsonPathMatchesSdkTemplatesAndErrors() {
|
||||
try (Fixture fixture = new Fixture(true)) {
|
||||
String model = fixture.createModel("JsonPathModel", SCHEMA);
|
||||
assertEquals(fixture.template(model), jsonTemplate(fixture.apiId, model).statusCode(200)
|
||||
.extract().path("Value"));
|
||||
fixture.update(model, valueSchema("boolean"));
|
||||
assertEquals(fixture.template(model), jsonTemplate(fixture.apiId, model).statusCode(200)
|
||||
.extract().path("Value"));
|
||||
fixture.update(model, "{\"allOf\":[{\"type\":\"object\"}]}");
|
||||
jsonTemplate(fixture.apiId, model).statusCode(501).body(containsString("UnsupportedOperation"));
|
||||
fixture.deleteModel(model);
|
||||
jsonTemplate(fixture.apiId, model).statusCode(404).body(containsString("NotFoundException"));
|
||||
jsonTemplate("missing-api", model).statusCode(404).body(containsString("NotFoundException"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpApisRejectModelCreationBeforePersistingAnything() {
|
||||
try (ApiGatewayV2Client client = v2("test", Region.US_EAST_1)) {
|
||||
String api = client.createApi(request -> request.name("http-template-boundary").protocolType("HTTP")).apiId();
|
||||
try {
|
||||
String message = "Currently, Models are not permitted for APIs with a protocol type of HTTP";
|
||||
AwsServiceException error = assertThrows(AwsServiceException.class,
|
||||
() -> client.createModel(request -> request.apiId(api).name("HttpModel")
|
||||
.contentType("application/json").schema(valueSchema("string"))));
|
||||
assertEquals(400, error.statusCode());
|
||||
assertEquals(message, error.awsErrorDetails().errorMessage());
|
||||
given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonApiGatewayV2.CreateModel")
|
||||
.header("Authorization", auth("test", "apigatewayv2"))
|
||||
.body(Map.of("ApiId", api, "Name", "HttpModel", "ContentType", "application/json",
|
||||
"Schema", valueSchema("string")))
|
||||
.post("/").then().statusCode(400).body(containsString(message));
|
||||
assertTrue(client.getModels(request -> request.apiId(api)).items().isEmpty());
|
||||
assertStatus(404, () -> client.getModelTemplate(request -> request.apiId(api).modelId("missing")));
|
||||
jsonTemplate(api, "missing").statusCode(404).body(containsString("NotFoundException"));
|
||||
} finally {
|
||||
client.deleteApi(request -> request.apiId(api));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String valueSchema(String type) {
|
||||
return "{\"type\":\"object\",\"properties\":{\"value\":{\"type\":\"" + type + "\"}}}";
|
||||
}
|
||||
|
||||
private JsonNode render(String template, String body) throws Exception {
|
||||
VtlTemplateEngine.VtlContext context = new VtlTemplateEngine.VtlContext(body, Map.of(), Map.of(),
|
||||
Map.of(), "stage", "POST", "/", "request", "000000000000", Map.of(), Map.of());
|
||||
return json.readTree(engine.evaluate(template, context).body());
|
||||
}
|
||||
|
||||
private void assertStatus(int status, Runnable request) {
|
||||
assertEquals(status, assertThrows(AwsServiceException.class, request::run).statusCode());
|
||||
}
|
||||
|
||||
private ApiGatewayClient v1(String key, Region region) {
|
||||
return AwsTestClients.create(ApiGatewayClient.builder(), key, "test", region,
|
||||
Apache5HttpClient.builder(), endpoint);
|
||||
}
|
||||
|
||||
private ApiGatewayV2Client v2(String key, Region region) {
|
||||
return AwsTestClients.create(ApiGatewayV2Client.builder(), key, "test", region,
|
||||
Apache5HttpClient.builder(), endpoint);
|
||||
}
|
||||
|
||||
private ValidatableResponse jsonTemplate(String api, String model) {
|
||||
return given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonApiGatewayV2.GetModelTemplate")
|
||||
.header("Authorization", auth("test", "apigatewayv2"))
|
||||
.body(Map.of("ApiId", api, "ModelId", model)).post("/").then();
|
||||
}
|
||||
|
||||
private final class Fixture implements AutoCloseable {
|
||||
private final boolean websocket;
|
||||
private final ApiGatewayClient rest = v1("test", Region.US_EAST_1);
|
||||
private final ApiGatewayV2Client socket = v2("test", Region.US_EAST_1);
|
||||
private String apiId;
|
||||
|
||||
private Fixture(boolean websocket) {
|
||||
this.websocket = websocket;
|
||||
String name = "model-template-" + UUID.randomUUID();
|
||||
apiId = websocket ? socket.createApi(request -> request.name(name).protocolType("WEBSOCKET")
|
||||
.routeSelectionExpression("$request.body.action")).apiId()
|
||||
: rest.createRestApi(request -> request.name(name)).id();
|
||||
}
|
||||
|
||||
private String createModel(String name, String schema) {
|
||||
return websocket ? socket.createModel(request -> request.apiId(apiId).name(name)
|
||||
.contentType("application/json").schema(schema)).modelId()
|
||||
: rest.createModel(request -> request.restApiId(apiId).name(name)
|
||||
.contentType("application/json").schema(schema)).name();
|
||||
}
|
||||
|
||||
private String template(String model) {
|
||||
return websocket ? socket.getModelTemplate(request -> request.apiId(apiId).modelId(model)).value()
|
||||
: rest.getModelTemplate(request -> request.restApiId(apiId).modelName(model)).value();
|
||||
}
|
||||
|
||||
private String templateAs(String model, String key, Region region) {
|
||||
try (ApiGatewayClient otherRest = v1(key, region); ApiGatewayV2Client otherSocket = v2(key, region)) {
|
||||
return websocket ? otherSocket.getModelTemplate(request -> request.apiId(apiId).modelId(model)).value()
|
||||
: otherRest.getModelTemplate(request -> request.restApiId(apiId).modelName(model)).value();
|
||||
}
|
||||
}
|
||||
|
||||
private void update(String model, String schema) {
|
||||
if (websocket) {
|
||||
socket.updateModel(request -> request.apiId(apiId).modelId(model).schema(schema));
|
||||
} else {
|
||||
rest.updateModel(request -> request.restApiId(apiId).modelName(model).patchOperations(
|
||||
PatchOperation.builder().op("replace").path("/schema").value(schema).build()));
|
||||
}
|
||||
}
|
||||
|
||||
private String schema(String model) {
|
||||
return websocket ? socket.getModel(request -> request.apiId(apiId).modelId(model)).schema()
|
||||
: rest.getModel(request -> request.restApiId(apiId).modelName(model)).schema();
|
||||
}
|
||||
|
||||
private void deleteModel(String model) {
|
||||
if (websocket) {
|
||||
socket.deleteModel(request -> request.apiId(apiId).modelId(model));
|
||||
} else {
|
||||
rest.deleteModel(request -> request.restApiId(apiId).modelName(model));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
if (websocket) {
|
||||
socket.deleteApi(request -> request.apiId(apiId));
|
||||
} else {
|
||||
rest.deleteRestApi(request -> request.restApiId(apiId));
|
||||
}
|
||||
} finally {
|
||||
rest.close();
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-6
@@ -4,7 +4,9 @@ import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
@@ -17,7 +19,7 @@ class ApiGatewayV2DeleteApiCascadeTest {
|
||||
String apiId = null;
|
||||
try {
|
||||
// 1. setup: create the API and every flavor of child resource under it.
|
||||
apiId = createApi("cascade-probe");
|
||||
apiId = createApi("cascade-probe", "WEBSOCKET");
|
||||
String integrationId = createIntegration(apiId);
|
||||
String routeId = createRoute(apiId, integrationId);
|
||||
createStage(apiId);
|
||||
@@ -82,9 +84,19 @@ class ApiGatewayV2DeleteApiCascadeTest {
|
||||
// ──────────────────────────── creation helpers ────────────────────────────
|
||||
|
||||
private static String createApi(String name) {
|
||||
return createApi(name, "HTTP");
|
||||
}
|
||||
|
||||
private static String createApi(String name, String protocol) {
|
||||
Map<String, String> request = new LinkedHashMap<>();
|
||||
request.put("name", name);
|
||||
request.put("protocolType", protocol);
|
||||
if ("WEBSOCKET".equals(protocol)) {
|
||||
request.put("routeSelectionExpression", "$request.body.action");
|
||||
}
|
||||
return given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"" + name + "\",\"protocolType\":\"HTTP\"}")
|
||||
.body(request)
|
||||
.when().post("/v2/apis")
|
||||
.then().statusCode(201)
|
||||
.extract().path("apiId");
|
||||
@@ -106,7 +118,7 @@ class ApiGatewayV2DeleteApiCascadeTest {
|
||||
return given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"routeKey":"GET /hello","target":"integrations/%s"}
|
||||
{"routeKey":"hello","target":"integrations/%s"}
|
||||
""".formatted(integrationId))
|
||||
.when().post("/v2/apis/" + apiId + "/routes")
|
||||
.then().statusCode(201)
|
||||
@@ -127,9 +139,9 @@ class ApiGatewayV2DeleteApiCascadeTest {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"authorizerType":"JWT","name":"probe-jwt",
|
||||
"identitySource":["$request.header.Authorization"],
|
||||
"jwtConfiguration":{"issuer":"https://example.com","audience":["a"]}}
|
||||
{"authorizerType":"REQUEST","name":"probe-authorizer",
|
||||
"identitySource":["route.request.header.Authorization"],
|
||||
"authorizerUri":"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:probe/invocations"}
|
||||
""")
|
||||
.when().post("/v2/apis/" + apiId + "/authorizers")
|
||||
.then().statusCode(201);
|
||||
|
||||
+3
-3
@@ -24,14 +24,14 @@ class ApiGatewayV2ModelsIntegrationTest {
|
||||
apiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"name":"models-rest-test","protocolType":"HTTP"}
|
||||
{"name":"models-rest-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}
|
||||
""")
|
||||
.when().post("/v2/apis")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiId", notNullValue())
|
||||
.body("name", equalTo("models-rest-test"))
|
||||
.body("protocolType", equalTo("HTTP"))
|
||||
.body("protocolType", equalTo("WEBSOCKET"))
|
||||
.extract().path("apiId");
|
||||
}
|
||||
|
||||
@@ -168,7 +168,7 @@ class ApiGatewayV2ModelsIntegrationTest {
|
||||
String secondApiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"name":"models-rest-test-2","protocolType":"HTTP"}
|
||||
{"name":"models-rest-test-2","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}
|
||||
""")
|
||||
.when().post("/v2/apis")
|
||||
.then()
|
||||
|
||||
@@ -43,7 +43,7 @@ class ApiGatewayV2ModelsJson11Test {
|
||||
.header("X-Amz-Target", TARGET_PREFIX + "CreateApi")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("""
|
||||
{"Name":"models-json11-test","ProtocolType":"HTTP"}
|
||||
{"Name":"models-json11-test","ProtocolType":"WEBSOCKET","RouteSelectionExpression":"$request.body.action"}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then()
|
||||
|
||||
@@ -127,6 +127,7 @@ action_count_sources:
|
||||
DeleteV2DomainName: DeleteDomainName
|
||||
CreateV2Model: CreateModel
|
||||
GetV2Model: GetModel
|
||||
GetV2ModelTemplate: GetModelTemplate
|
||||
GetV2Models: GetModels
|
||||
UpdateV2Model: UpdateModel
|
||||
DeleteV2Model: DeleteModel
|
||||
|
||||
Reference in new issue
Block a user