mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user