mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(apigateway): validate and normalize imported integration types (#5543)
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
eba058266b
commit
63e0302c12
9 files changed
+489
-3
No files matched your search
@@ -14,6 +14,7 @@
|
||||
# published partition metadata (plus two CDK region rules) by tools/aws/regen_partitions.py.
|
||||
# src/main/resources/aws/dynamodb-request-shapes.json is generated from botocore's DynamoDB
|
||||
# model by tools/aws/regen_dynamodb_shapes.py.
|
||||
# API Gateway integration types come from the public service model via tools/aws/regen_apigateway_types.py.
|
||||
|
||||
PYTHON ?= python3
|
||||
|
||||
@@ -204,6 +205,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p
|
||||
$(PYTHON) tools/aws/regen_partitions.py
|
||||
$(PYTHON) tools/aws/regen_region_facts.py
|
||||
$(PYTHON) tools/aws/regen_dynamodb_shapes.py
|
||||
$(PYTHON) tools/aws/regen_apigateway_types.py
|
||||
$(PYTHON) tools/aws/regen_managed_policies.py
|
||||
|
||||
aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
|
||||
@@ -225,6 +227,10 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_apigateway_types.py --check || { \
|
||||
echo "error: API Gateway integration types are out of date; run 'make aws-data-sync'."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_managed_policies.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: the IAM managed-policy catalog (src/main/resources/iam/managed-polic*) is out of date or malformed."; \
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
"""OpenAPI integration type readback verified against live API Gateway."""
|
||||
|
||||
import json
|
||||
import uuid
|
||||
from contextlib import closing
|
||||
|
||||
import boto3
|
||||
import pytest
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
def test_imported_integration_types(aws_config):
|
||||
expected_types = {
|
||||
"aws": "AWS", "aws_proxy": "AWS_PROXY", "http": "HTTP",
|
||||
"http_proxy": "HTTP_PROXY", "mock": "MOCK", "any": "MOCK",
|
||||
"AWS": "AWS", "AWS_PROXY": "AWS_PROXY", "HTTP": "HTTP",
|
||||
"HTTP_PROXY": "HTTP_PROXY", "MOCK": "MOCK",
|
||||
"Aws": "AWS", "Aws_Proxy": "AWS_PROXY", "Http": "HTTP",
|
||||
"Http_Proxy": "HTTP_PROXY", "Mock": "MOCK",
|
||||
}
|
||||
paths = {}
|
||||
for name in expected_types:
|
||||
integration_type = "mock" if name == "any" else name
|
||||
integration = {"type": integration_type, "timeoutInMillis": 12000}
|
||||
normalized_type = integration_type.lower()
|
||||
if normalized_type != "mock":
|
||||
integration["httpMethod"] = "POST"
|
||||
if normalized_type.startswith("aws"):
|
||||
integration["uri"] = (
|
||||
"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/"
|
||||
"functions/arn:aws:lambda:us-east-1:000000000000:function:fixture:live/invocations")
|
||||
elif normalized_type.startswith("http"):
|
||||
integration["uri"] = "https://example.com/original"
|
||||
if normalized_type in ("aws", "http", "mock"):
|
||||
integration["responses"] = {"default": {"statusCode": "200"}}
|
||||
operation = "x-amazon-apigateway-any-method" if name == "any" else "get"
|
||||
paths["/" + name] = {operation: {
|
||||
"responses": {"200": {"description": "ok"}},
|
||||
"x-amazon-apigateway-integration": integration,
|
||||
}}
|
||||
document = {"openapi": "3.0.2", "info": {
|
||||
"title": "integration-types-" + uuid.uuid4().hex, "version": "1"}, "paths": paths}
|
||||
|
||||
with closing(boto3.client("apigateway", **aws_config)) as api:
|
||||
api_id = api.import_rest_api(body=json.dumps(document), failOnWarnings=True)["id"]
|
||||
try:
|
||||
for mode, timeout in [(None, 12000), ("merge", 14000), ("overwrite", 15000)]:
|
||||
for path in paths.values():
|
||||
integration = next(iter(path.values()))["x-amazon-apigateway-integration"]
|
||||
integration["timeoutInMillis"] = timeout
|
||||
if mode and "uri" in integration:
|
||||
integration["uri"] = integration["uri"].replace(
|
||||
":live/", ":next/").replace("/original", "/replacement")
|
||||
if mode:
|
||||
api.put_rest_api(restApiId=api_id, mode=mode,
|
||||
body=json.dumps(document), failOnWarnings=True)
|
||||
resources = api.get_resources(restApiId=api_id)["items"]
|
||||
resources = {resource["path"]: resource["id"] for resource in resources}
|
||||
for name, expected_type in expected_types.items():
|
||||
method = {"restApiId": api_id, "resourceId": resources["/" + name],
|
||||
"httpMethod": "ANY" if name == "any" else "GET"}
|
||||
integration = api.get_integration(**method)
|
||||
embedded = api.get_method(**method)["methodIntegration"]
|
||||
expected = next(iter(paths["/" + name].values()))["x-amazon-apigateway-integration"]
|
||||
assert integration["type"] == embedded["type"] == expected_type
|
||||
for field in ("uri", "httpMethod", "timeoutInMillis"):
|
||||
if field in expected:
|
||||
assert integration[field] == embedded[field] == expected[field]
|
||||
finally:
|
||||
api.delete_rest_api(restApiId=api_id)
|
||||
|
||||
|
||||
def test_unknown_integration_types(aws_config):
|
||||
invalid_types = [
|
||||
"custom_type", "CuStOm_TyPe", "", " mock", "mock ", "http-proxy", "hıttp", "mοck", "moc\u212A",
|
||||
]
|
||||
paths = {
|
||||
"/case" + str(index): {"get": {
|
||||
"responses": {"200": {"description": "ok"}},
|
||||
"x-amazon-apigateway-integration": {"type": value},
|
||||
}}
|
||||
for index, value in enumerate(invalid_types)
|
||||
}
|
||||
expected_warnings = {
|
||||
f"Unknown integration type '{value}' for 'GET /case{index}'. Ignoring."
|
||||
for index, value in enumerate(invalid_types)
|
||||
}
|
||||
document = {"openapi": "3.0.2", "info": {
|
||||
"title": "invalid-integration-types-" + uuid.uuid4().hex, "version": "1"}, "paths": paths}
|
||||
body = json.dumps(document)
|
||||
with closing(boto3.client("apigateway", **aws_config)) as api:
|
||||
with pytest.raises(ClientError) as rejected:
|
||||
api.import_rest_api(body=body, failOnWarnings=True)
|
||||
assert rejected.value.response["Error"]["Code"] == "BadRequestException"
|
||||
assert all(warning in rejected.value.response["Error"]["Message"] for warning in expected_warnings)
|
||||
imported = api.import_rest_api(body=body, failOnWarnings=False)
|
||||
api_id = imported["id"]
|
||||
try:
|
||||
for mode in [None, "merge", "overwrite"]:
|
||||
if mode:
|
||||
with pytest.raises(ClientError) as rejected:
|
||||
api.put_rest_api(restApiId=api_id, mode=mode, body=body, failOnWarnings=True)
|
||||
assert rejected.value.response["Error"]["Code"] == "BadRequestException"
|
||||
imported = api.put_rest_api(
|
||||
restApiId=api_id, mode=mode, body=body, failOnWarnings=False)
|
||||
assert set(imported["warnings"]) == expected_warnings
|
||||
resources = api.get_resources(restApiId=api_id)["items"]
|
||||
for resource in resources:
|
||||
if resource["path"] == "/":
|
||||
continue
|
||||
method = {"restApiId": api_id, "resourceId": resource["id"], "httpMethod": "GET"}
|
||||
with pytest.raises(ClientError) as missing:
|
||||
api.get_integration(**method)
|
||||
assert missing.value.response["Error"]["Code"] == "NotFoundException"
|
||||
assert "methodIntegration" not in api.get_method(**method)
|
||||
finally:
|
||||
api.delete_rest_api(restApiId=api_id)
|
||||
@@ -76,6 +76,17 @@ throughout the definition before parsing it. Values come from the request region
|
||||
account, so the same definition can be imported across regions and partitions. This
|
||||
includes mapping templates and applies to both `ImportRestApi` and `PutRestApi`.
|
||||
|
||||
OpenAPI integration types `aws`, `aws_proxy`, `http`, `http_proxy`, and `mock`, including
|
||||
uppercase and mixed-case spellings, are
|
||||
stored as the public Integration values `AWS`, `AWS_PROXY`, `HTTP`, `HTTP_PROXY`,
|
||||
and `MOCK`. Both `GetIntegration` and `GetMethod.methodIntegration` return these
|
||||
canonical values after import, merge, or overwrite.
|
||||
The accepted type list is generated from Botocore's public API Gateway service model
|
||||
and checked by `make aws-data-check`; importing an API requires no AWS SDK or network lookup.
|
||||
Unknown integration type strings produce warnings and leave the method without an
|
||||
integration. With `failOnWarnings=true`, the import or update is rejected before
|
||||
changing the API. Leading/trailing whitespace and non-ASCII lookalikes are not accepted.
|
||||
|
||||
### Supported Operations
|
||||
|
||||
| Category | Operations |
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** Integration types generated from Botocore's public API Gateway service model. */
|
||||
final class ApiGatewayIntegrationTypes {
|
||||
|
||||
private static final String RESOURCE_NAME = "aws/apigateway-integration-types.json";
|
||||
private static final Map<String, String> TYPES = load();
|
||||
|
||||
private ApiGatewayIntegrationTypes() {
|
||||
}
|
||||
|
||||
static String canonical(String value) {
|
||||
if (value.chars().anyMatch(character -> character > 0x7f)) {
|
||||
return null;
|
||||
}
|
||||
return TYPES.get(value.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
private static Map<String, String> load() {
|
||||
try (InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(RESOURCE_NAME)) {
|
||||
if (input == null) {
|
||||
throw new IllegalStateException("Missing API Gateway integration types: " + RESOURCE_NAME);
|
||||
}
|
||||
JsonNode values = new ObjectMapper().readTree(input).path("integrationTypes");
|
||||
if (!values.isArray() || values.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no integrationTypes");
|
||||
}
|
||||
Map<String, String> types = new HashMap<>();
|
||||
for (JsonNode value : values) {
|
||||
if (!value.isTextual() || value.asText().isBlank()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries an invalid integration type");
|
||||
}
|
||||
types.put(value.asText().toLowerCase(Locale.ROOT), value.asText());
|
||||
}
|
||||
return Map.copyOf(types);
|
||||
} catch (IOException error) {
|
||||
throw new IllegalStateException("Failed to read " + RESOURCE_NAME, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
-3
@@ -3675,21 +3675,38 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
if (openAPI.getPaths() != null) {
|
||||
for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
|
||||
PathItem pathItem = entry.getValue();
|
||||
for (Map.Entry<PathItem.HttpMethod, Operation> operation : pathItem.readOperationsMap().entrySet()) {
|
||||
addImportedIntegrationWarning(entry.getKey(), operation.getKey().name(),
|
||||
operation.getValue(), warnings);
|
||||
}
|
||||
Object anyMethod = pathItem.getExtensions() != null
|
||||
? pathItem.getExtensions().get("x-amazon-apigateway-any-method") : null;
|
||||
if (anyMethod != null) {
|
||||
OpenAPIDeserializer.ParseResult anyResult = new OpenAPIDeserializer.ParseResult();
|
||||
parseAnyMethodOperation(entry.getKey(), anyMethod, anyResult);
|
||||
Operation operation = parseAnyMethodOperation(entry.getKey(), anyMethod, anyResult);
|
||||
warnings.addAll(anyResult.getMessages());
|
||||
addImportedIntegrationWarning(entry.getKey(), "ANY", operation, warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failOnWarnings && !warnings.isEmpty()) {
|
||||
throw new AwsException("BadRequestException", String.join("; ", warnings), 400);
|
||||
throw new AwsException("BadRequestException",
|
||||
"Warnings found during import:\n\t" + String.join("\n\t", warnings), 400);
|
||||
}
|
||||
return new ParsedOpenApi(openAPI, List.copyOf(warnings));
|
||||
}
|
||||
|
||||
private static void addImportedIntegrationWarning(String path, String httpMethod,
|
||||
Operation operation, List<String> warnings) {
|
||||
Object extension = operation.getExtensions() == null
|
||||
? null : operation.getExtensions().get("x-amazon-apigateway-integration");
|
||||
if (extension instanceof Map<?, ?> integration
|
||||
&& integration.get("type") instanceof String type
|
||||
&& ApiGatewayIntegrationTypes.canonical(type) == null) {
|
||||
warnings.add("Unknown integration type '" + type + "' for '" + httpMethod + " " + path + "'. Ignoring.");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateImportedAuthorizers(OpenAPI openAPI) {
|
||||
if (openAPI.getComponents() == null || openAPI.getComponents().getSecuritySchemes() == null) {
|
||||
return;
|
||||
@@ -4395,7 +4412,13 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
String httpMethod, Map<String, Object> integrationExt) {
|
||||
Map<String, Object> integrationRequest = new HashMap<>();
|
||||
Object integrationType = integrationExt.get("type");
|
||||
integrationRequest.put("type", integrationType instanceof String type ? type.toUpperCase(Locale.ROOT) : integrationType);
|
||||
if (integrationType instanceof String type) {
|
||||
integrationType = ApiGatewayIntegrationTypes.canonical(type);
|
||||
if (integrationType == null) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
integrationRequest.put("type", integrationType);
|
||||
integrationRequest.put("httpMethod", integrationExt.get("httpMethod"));
|
||||
integrationRequest.put("uri", integrationExt.get("uri"));
|
||||
Object passthrough = integrationExt.get("passthroughBehavior");
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_apigateway_types.py",
|
||||
"botocore": "botocore 1.43.111 (installed package)",
|
||||
"model": "apigateway/2015-07-09/service-2.json",
|
||||
"shape": "IntegrationType"
|
||||
},
|
||||
"integrationTypes": [
|
||||
"AWS",
|
||||
"AWS_PROXY",
|
||||
"HTTP",
|
||||
"HTTP_PROXY",
|
||||
"MOCK"
|
||||
]
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
@QuarkusTest
|
||||
class ApiGatewayImportedIntegrationTypeIntegrationTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String LAMBDA_URI = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/"
|
||||
+ "functions/arn:aws:lambda:us-east-1:000000000000:function:fixture:live/invocations";
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"aws, AWS, get, GET",
|
||||
"aws_proxy, AWS_PROXY, get, GET",
|
||||
"http, HTTP, get, GET",
|
||||
"http_proxy, HTTP_PROXY, get, GET",
|
||||
"mock, MOCK, get, GET",
|
||||
"AWS, AWS, get, GET",
|
||||
"AWS_PROXY, AWS_PROXY, get, GET",
|
||||
"HTTP, HTTP, get, GET",
|
||||
"HTTP_PROXY, HTTP_PROXY, get, GET",
|
||||
"MOCK, MOCK, get, GET",
|
||||
"Aws, AWS, get, GET",
|
||||
"Aws_Proxy, AWS_PROXY, get, GET",
|
||||
"Http, HTTP, get, GET",
|
||||
"Http_Proxy, HTTP_PROXY, get, GET",
|
||||
"Mock, MOCK, get, GET",
|
||||
"mock, MOCK, x-amazon-apigateway-any-method, ANY"
|
||||
})
|
||||
void importMergeAndOverwriteExposeCanonicalMetadataWithoutChangingOtherFields(
|
||||
String importedType, String expectedType, String operation, String verb) throws Exception {
|
||||
Map<String, Object> integration = integration(importedType);
|
||||
String apiId = importApi(document(operation, integration));
|
||||
try {
|
||||
assertMetadata(apiId, verb, integration, expectedType);
|
||||
|
||||
for (String mode : List.of("merge", "overwrite")) {
|
||||
Map<String, Object> replacement = new LinkedHashMap<>(integration);
|
||||
replacement.put("timeoutInMillis", "merge".equals(mode) ? 14000 : 15000);
|
||||
if (replacement.containsKey("uri")) {
|
||||
replacement.put("uri", replacement.get("uri").toString().replace("live", "next")
|
||||
.replace("/original", "/replacement"));
|
||||
}
|
||||
given().contentType(ContentType.JSON).body(document(operation, replacement))
|
||||
.put("/restapis/" + apiId + "?mode=" + mode)
|
||||
.then().statusCode(200);
|
||||
assertMetadata(apiId, verb, replacement, expectedType);
|
||||
}
|
||||
} finally {
|
||||
given().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"custom_type, get, GET",
|
||||
"CuStOm_TyPe, get, GET",
|
||||
"'', get, GET",
|
||||
"' mock', get, GET",
|
||||
"'mock ', get, GET",
|
||||
"http-proxy, get, GET",
|
||||
"hıttp, get, GET",
|
||||
"mοck, get, GET",
|
||||
"moc\u212A, get, GET",
|
||||
"CuStOm_TyPe, x-amazon-apigateway-any-method, ANY"
|
||||
})
|
||||
void unknownTypesWarnAndOmitIntegrationOrRefuseBeforeChangingApi(
|
||||
String type, String operation, String verb) throws Exception {
|
||||
Map<String, Object> invalid = document(operation, Map.of("type", type));
|
||||
String warning = "Unknown integration type '" + type + "' for '" + verb + " /status'. Ignoring.";
|
||||
String error = "Warnings found during import:\n\t" + warning;
|
||||
given().contentType(ContentType.JSON).body(invalid)
|
||||
.post("/restapis?mode=import&failonwarnings=true")
|
||||
.then().statusCode(400).body("message", equalTo(error));
|
||||
String apiId = given().contentType(ContentType.JSON).body(invalid)
|
||||
.post("/restapis?mode=import")
|
||||
.then().statusCode(201).body("warnings", equalTo(List.of(warning))).extract().path("id");
|
||||
try {
|
||||
assertMissingIntegration(apiId, verb);
|
||||
Map<String, Object> valid = integration("mock");
|
||||
for (String mode : List.of("merge", "overwrite")) {
|
||||
given().contentType(ContentType.JSON).body(document(operation, valid))
|
||||
.put("/restapis/" + apiId + "?mode=overwrite").then().statusCode(200);
|
||||
given().contentType(ContentType.JSON).body(invalid)
|
||||
.put("/restapis/" + apiId + "?mode=" + mode + "&failonwarnings=true")
|
||||
.then().statusCode(400).body("message", equalTo(error));
|
||||
assertMetadata(apiId, verb, valid, "MOCK");
|
||||
given().contentType(ContentType.JSON).body(invalid)
|
||||
.put("/restapis/" + apiId + "?mode=" + mode)
|
||||
.then().statusCode(200).body("warnings", equalTo(List.of(warning)));
|
||||
assertMissingIntegration(apiId, verb);
|
||||
}
|
||||
} finally {
|
||||
given().delete("/restapis/" + apiId).then().statusCode(202);
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertMissingIntegration(String apiId, String verb) throws Exception {
|
||||
String path = methodPath(apiId, verb);
|
||||
given().get(path + "/integration").then().statusCode(404);
|
||||
assertFalse(get(path).has("methodIntegration"));
|
||||
}
|
||||
|
||||
private static Map<String, Object> integration(String type) {
|
||||
Map<String, Object> integration = new LinkedHashMap<>();
|
||||
integration.put("type", type);
|
||||
String normalizedType = type.toLowerCase(Locale.ROOT);
|
||||
integration.put("timeoutInMillis", 12000);
|
||||
if (!"mock".equals(normalizedType)) {
|
||||
integration.put("httpMethod", "POST");
|
||||
}
|
||||
if ("aws".equals(normalizedType) || "aws_proxy".equals(normalizedType)) {
|
||||
integration.put("uri", LAMBDA_URI);
|
||||
} else if (!"mock".equals(normalizedType)) {
|
||||
integration.put("uri", "https://example.com/original");
|
||||
}
|
||||
if (List.of("aws", "http", "mock").contains(normalizedType)) {
|
||||
integration.put("responses", Map.of("default", Map.of("statusCode", "200")));
|
||||
}
|
||||
return integration;
|
||||
}
|
||||
|
||||
private static Map<String, Object> document(String verb, Map<String, Object> integration) {
|
||||
return Map.of(
|
||||
"openapi", "3.0.2",
|
||||
"info", Map.of("title", "integration-type", "version", "1"),
|
||||
"paths", Map.of("/status", Map.of(verb, Map.of(
|
||||
"responses", Map.of("200", Map.of("description", "ok")),
|
||||
"x-amazon-apigateway-integration", integration))));
|
||||
}
|
||||
|
||||
private static String importApi(Map<String, Object> document) {
|
||||
return given().contentType(ContentType.JSON).body(document)
|
||||
.post("/restapis?mode=import").then().statusCode(201).extract().path("id");
|
||||
}
|
||||
|
||||
private static String methodPath(String apiId, String verb) throws Exception {
|
||||
JsonNode resources = get("/restapis/" + apiId + "/resources").path("item");
|
||||
for (JsonNode resource : resources) {
|
||||
if ("/status".equals(resource.path("path").asText())) {
|
||||
return "/restapis/" + apiId + "/resources/" + resource.path("id").asText() + "/methods/" + verb;
|
||||
}
|
||||
}
|
||||
throw new AssertionError("Imported status resource is missing");
|
||||
}
|
||||
|
||||
private static void assertMetadata(String apiId, String verb, Map<String, Object> expected,
|
||||
String expectedType) throws Exception {
|
||||
String path = methodPath(apiId, verb);
|
||||
JsonNode method = get(path);
|
||||
JsonNode integration = get(path + "/integration");
|
||||
assertEquals(expectedType, integration.path("type").asText());
|
||||
assertEquals(integration, method.path("methodIntegration"));
|
||||
for (Map.Entry<String, Object> field : expected.entrySet()) {
|
||||
if (!List.of("type", "responses").contains(field.getKey())) {
|
||||
assertEquals(MAPPER.valueToTree(field.getValue()), integration.get(field.getKey()), field.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode get(String path) throws Exception {
|
||||
return MAPPER.readTree(given().get(path).then().statusCode(200).extract().asString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate API Gateway integration types from Botocore's public service model.
|
||||
|
||||
Source: apigateway/2015-07-09/service-2.json, shape IntegrationType.
|
||||
Botocore is Apache-2.0 licensed: https://github.com/boto/botocore.
|
||||
Run directly to regenerate, or with --check to detect drift in CI.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from regen_partitions import load_model, resolve_botocore_data, service_model, strip_source
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/apigateway-integration-types.json"
|
||||
MODEL = Path("apigateway/2015-07-09")
|
||||
|
||||
|
||||
def build(model: dict, provenance: str) -> dict:
|
||||
values = model["shapes"]["IntegrationType"]["enum"]
|
||||
if not values or any(not isinstance(value, str) or not value for value in values):
|
||||
raise ValueError("IntegrationType must be a nonempty string enum")
|
||||
return {
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_apigateway_types.py",
|
||||
"botocore": provenance,
|
||||
"model": str(MODEL / "service-2.json"),
|
||||
"shape": "IntegrationType",
|
||||
},
|
||||
"integrationTypes": sorted(set(values)),
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
parser.add_argument("--botocore-data", type=Path)
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT)
|
||||
args = parser.parse_args(argv)
|
||||
data, provenance = resolve_botocore_data(args.botocore_data)
|
||||
source = service_model(data / MODEL)
|
||||
if source is None:
|
||||
raise SystemExit(f"error: no service model found in {data / MODEL}")
|
||||
fresh = json.dumps(build(load_model(source), provenance), indent=2) + "\n"
|
||||
if args.check:
|
||||
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
|
||||
if strip_source(current) != strip_source(fresh):
|
||||
print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
args.output.write_text(fresh, encoding="utf-8")
|
||||
print(f"wrote {args.output} from {provenance}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
import json
|
||||
|
||||
import regen_apigateway_types as r
|
||||
|
||||
|
||||
def test_extracts_new_model_values_without_a_handwritten_allowlist():
|
||||
model = {"shapes": {"IntegrationType": {"type": "string", "enum": ["FUTURE_TYPE", "MOCK"]}}}
|
||||
assert r.build(model, "test")["integrationTypes"] == ["FUTURE_TYPE", "MOCK"]
|
||||
|
||||
|
||||
def test_check_detects_drift_without_rewriting_the_catalog(tmp_path, monkeypatch):
|
||||
data = tmp_path / r.MODEL
|
||||
data.mkdir(parents=True)
|
||||
model = {"shapes": {"IntegrationType": {"type": "string", "enum": ["MOCK", "FUTURE_TYPE"]}}}
|
||||
(data / "service-2.json").write_text(json.dumps(model))
|
||||
output = tmp_path / "types.json"
|
||||
stale = json.dumps({"integrationTypes": ["MOCK"]})
|
||||
output.write_text(stale)
|
||||
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "test"))
|
||||
|
||||
assert r.main(["--check", "--output", str(output)]) == 1
|
||||
assert output.read_text() == stale
|
||||
|
||||
output.write_text(json.dumps(r.build(model, "different provenance")))
|
||||
assert r.main(["--check", "--output", str(output)]) == 0
|
||||
Reference in new issue
Block a user