mirror of
https://github.com/floci-io/floci.git
synced 2026-11-29 16:35:29 -05:00
feat(apigateway): export deployed REST APIs as OpenAPI (#5131)
* feat(apigateway): export deployed REST APIs as OpenAPI * fix(apigateway): reject lossy export round trips * fix(apigateway): preserve native export round trips --------- Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
This commit is contained in:
1 parent
760c38ef99
commit
1acedaf068
13 files changed
+1132
-12
No files matched your search
+31
@@ -1,10 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.io.JsonStringEncoder;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
|
||||
@@ -274,6 +276,35 @@ public class ApiGatewayController {
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/stages/{stageName}/exports/{exportType}")
|
||||
@Produces({MediaType.APPLICATION_JSON, "application/yaml"})
|
||||
public Response getExport(@Context HttpHeaders headers, @PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName, @PathParam("exportType") String exportType,
|
||||
@QueryParam("extensions") String extensions) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
ObjectNode document = service.exportRestApi(region, apiId, stageName, exportType, extensions);
|
||||
String contentType = MediaType.APPLICATION_JSON;
|
||||
for (MediaType acceptable : headers.getAcceptableMediaTypes()) {
|
||||
if (acceptable.isCompatible(MediaType.APPLICATION_JSON_TYPE)) {
|
||||
break;
|
||||
}
|
||||
if (acceptable.isCompatible(MediaType.valueOf("application/yaml"))) {
|
||||
contentType = "application/yaml";
|
||||
break;
|
||||
}
|
||||
}
|
||||
try {
|
||||
String body = "application/yaml".equals(contentType)
|
||||
? new YAMLMapper().writeValueAsString(document) : document.toString();
|
||||
return Response.ok(body).type(contentType)
|
||||
.header("Content-Disposition", "attachment; filename=\"" + apiId + "-" + exportType
|
||||
+ ("application/yaml".equals(contentType) ? ".yaml" : ".json") + "\"").build();
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Cannot serialize API export", e);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/stages/{stageName}")
|
||||
public Response getStage(@Context HttpHeaders headers,
|
||||
|
||||
+112
-6
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -10,6 +11,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartition;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartitions;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.CloudFrontEdgeDomain;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ReservedTags;
|
||||
@@ -25,6 +27,7 @@ import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.DeploymentExportSnapshot;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.EndpointType;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
|
||||
@@ -68,6 +71,7 @@ import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
@@ -775,7 +779,16 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
public Deployment createDeployment(String region, String apiId, Map<String, Object> request) {
|
||||
getRestApi(region, apiId);
|
||||
String description = (String) request.getOrDefault("description", "");
|
||||
Deployment deployment = new Deployment(shortId(10), description, System.currentTimeMillis() / 1000L);
|
||||
String snapshot;
|
||||
try {
|
||||
snapshot = JSON.writeValueAsString(new DeploymentExportSnapshot(getRestApi(region, apiId),
|
||||
getResources(region, apiId), getModels(region, apiId), getAuthorizers(region, apiId),
|
||||
getRequestValidators(region, apiId), getGatewayResponses(region, apiId).stream()
|
||||
.filter(response -> !response.isDefaultResponse()).toList()));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Cannot capture REST API deployment", e);
|
||||
}
|
||||
Deployment deployment = new Deployment(shortId(10), description, System.currentTimeMillis() / 1000L, snapshot);
|
||||
deploymentStore.put(deploymentKey(region, apiId, deployment.id()), deployment);
|
||||
LOG.infov("Created deployment {0} for API {1}", deployment.id(), apiId);
|
||||
|
||||
@@ -851,13 +864,48 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
}
|
||||
newDescription = value;
|
||||
}
|
||||
Deployment updated = new Deployment(existing.id(), newDescription, existing.createdDate());
|
||||
Deployment updated = new Deployment(existing.id(), newDescription, existing.createdDate(), existing.exportSnapshot());
|
||||
deploymentStore.put(deploymentKey(region, apiId, deploymentId), updated);
|
||||
return updated;
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
public ObjectNode exportRestApi(String region, String apiId, String stageName, String exportType,
|
||||
String extensions) {
|
||||
Stage stage = getStage(region, apiId, stageName);
|
||||
if (!"oas30".equals(exportType) && !"swagger".equals(exportType)) {
|
||||
throw new AwsException("BadRequestException", "Invalid export type: " + exportType, 400);
|
||||
}
|
||||
Set<String> selected = extensions == null || extensions.isBlank()
|
||||
? Set.of() : new HashSet<>(List.of(extensions.split(",")));
|
||||
if (!Set.of("integrations", "authorizers", "apigateway").containsAll(selected)) {
|
||||
throw new AwsException("BadRequestException", "Unsupported export extensions: " + extensions, 400);
|
||||
}
|
||||
Deployment deployment = getDeployment(region, apiId, stage.getDeploymentId());
|
||||
if (deployment.exportSnapshot() == null) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"This deployment predates export snapshots. Redeploy the API before exporting it.", 400);
|
||||
}
|
||||
try {
|
||||
DeploymentExportSnapshot snapshot = JSON.readValue(deployment.exportSnapshot(), DeploymentExportSnapshot.class);
|
||||
boolean all = selected.contains("apigateway");
|
||||
ObjectNode document = RestApiOpenApiExporter.export(snapshot, "swagger".equals(exportType),
|
||||
all || selected.contains("integrations"), all || selected.contains("authorizers"), all);
|
||||
String host = apiId + ".execute-api." + region + "." + AwsRegions.dnsSuffixFor(region);
|
||||
if ("swagger".equals(exportType)) {
|
||||
document.put("host", host);
|
||||
document.put("basePath", "/" + stageName);
|
||||
document.putArray("schemes").add("https");
|
||||
} else {
|
||||
document.putArray("servers").addObject().put("url", "https://" + host + "/" + stageName);
|
||||
}
|
||||
return document;
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Cannot read REST API deployment snapshot", e);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Stages ────────────────────────────
|
||||
|
||||
public Stage createStage(String region, String apiId, Map<String, Object> request) {
|
||||
@@ -3646,12 +3694,20 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
if (openAPI.getComponents() == null || openAPI.getComponents().getSecuritySchemes() == null) {
|
||||
return;
|
||||
}
|
||||
for (var entry : openAPI.getComponents().getSecuritySchemes().entrySet()) {
|
||||
Set<String> referencedSchemes = referencedSecuritySchemes(openAPI);
|
||||
for (Map.Entry<String, SecurityScheme> entry : openAPI.getComponents().getSecuritySchemes().entrySet()) {
|
||||
String schemeName = entry.getKey();
|
||||
SecurityScheme scheme = entry.getValue();
|
||||
importedAuthorizationType(scheme, schemeName);
|
||||
String authorizationType = importedAuthorizationType(scheme, schemeName);
|
||||
Map<String, Object> authDef = importedAuthorizerDefinition(scheme, schemeName);
|
||||
if (authDef == null) {
|
||||
if (referencedSchemes.contains(schemeName)
|
||||
&& ("custom".equalsIgnoreCase(authorizationType)
|
||||
|| "cognito_user_pools".equalsIgnoreCase(authorizationType))) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Missing authorizer definition for security scheme " + schemeName
|
||||
+ ". Export with extensions=authorizers or extensions=apigateway before importing.", 400);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
String type = importedAuthorizerType(authDef, schemeName);
|
||||
@@ -3669,6 +3725,30 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> referencedSecuritySchemes(OpenAPI openAPI) {
|
||||
Set<String> schemes = new HashSet<>();
|
||||
if (openAPI.getPaths() == null) {
|
||||
return schemes;
|
||||
}
|
||||
for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
|
||||
PathItem path = entry.getValue();
|
||||
List<Operation> operations = new ArrayList<>(path.readOperations());
|
||||
Object anyMethod = path.getExtensions() == null
|
||||
? null : path.getExtensions().get("x-amazon-apigateway-any-method");
|
||||
if (anyMethod != null) {
|
||||
operations.add(parseAnyMethodOperation(entry.getKey(), anyMethod));
|
||||
}
|
||||
for (Operation operation : operations) {
|
||||
List<SecurityRequirement> requirements = operation.getSecurity() != null
|
||||
? operation.getSecurity() : openAPI.getSecurity();
|
||||
if (requirements != null) {
|
||||
requirements.forEach(requirement -> schemes.addAll(requirement.keySet()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return schemes;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> importedAuthorizerDefinition(SecurityScheme scheme, String schemeName) {
|
||||
if (scheme == null || scheme.getExtensions() == null) {
|
||||
@@ -3850,6 +3930,16 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
String defaultValidatorId = null;
|
||||
Map<String, Object> topExtensions = openAPI.getExtensions();
|
||||
if (topExtensions != null) {
|
||||
RestApi api = getRestApi(region, apiId);
|
||||
Object binaryTypes = topExtensions.get("x-amazon-apigateway-binary-media-types");
|
||||
if (binaryTypes instanceof List<?> types) {
|
||||
api.setBinaryMediaTypes(types.stream().filter(String.class::isInstance).map(String.class::cast).toList());
|
||||
}
|
||||
Object policy = topExtensions.get("x-amazon-apigateway-policy");
|
||||
if (policy != null) {
|
||||
api.setPolicy(JSON.valueToTree(policy).toString());
|
||||
}
|
||||
apiStore.put(apiKey(region, apiId), api);
|
||||
Map<String, Object> validators = (Map<String, Object>) topExtensions
|
||||
.get("x-amazon-apigateway-request-validators");
|
||||
if (validators != null) {
|
||||
@@ -4206,6 +4296,19 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
if (integrationExt != null) {
|
||||
applyIntegration(region, apiId, resourceId, httpMethod, integrationExt);
|
||||
}
|
||||
if (operation.getResponses() != null) {
|
||||
operation.getResponses().forEach((status, response) -> {
|
||||
if (!status.matches("[1-5][0-9]{2}")) {
|
||||
return;
|
||||
}
|
||||
Map<String, Boolean> headers = new HashMap<>();
|
||||
if (response.getHeaders() != null) {
|
||||
response.getHeaders().forEach((name, header) ->
|
||||
headers.put("method.response.header." + name, Boolean.TRUE.equals(header.getRequired())));
|
||||
}
|
||||
putMethodResponse(region, apiId, resourceId, httpMethod, status, Map.of("responseParameters", headers));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static final String PARAMETER_REF_PREFIX = "#/components/parameters/";
|
||||
@@ -4291,10 +4394,12 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
private void applyIntegration(String region, String apiId, String resourceId,
|
||||
String httpMethod, Map<String, Object> integrationExt) {
|
||||
Map<String, Object> integrationRequest = new HashMap<>();
|
||||
integrationRequest.put("type", integrationExt.get("type"));
|
||||
Object integrationType = integrationExt.get("type");
|
||||
integrationRequest.put("type", integrationType instanceof String type ? type.toUpperCase(Locale.ROOT) : integrationType);
|
||||
integrationRequest.put("httpMethod", integrationExt.get("httpMethod"));
|
||||
integrationRequest.put("uri", integrationExt.get("uri"));
|
||||
integrationRequest.put("passthroughBehavior", integrationExt.get("passthroughBehavior"));
|
||||
Object passthrough = integrationExt.get("passthroughBehavior");
|
||||
integrationRequest.put("passthroughBehavior", passthrough instanceof String behavior ? behavior.toUpperCase(Locale.ROOT) : passthrough);
|
||||
for (String field : List.of("contentHandling", "timeoutInMillis", "connectionType",
|
||||
"connectionId", "credentials", "cacheNamespace", "cacheKeyParameters", "tlsConfig",
|
||||
"responseTransferMode")) {
|
||||
@@ -4325,6 +4430,7 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
irRequest.put("selectionPattern", pattern);
|
||||
irRequest.put("responseParameters", respDef.get("responseParameters"));
|
||||
irRequest.put("responseTemplates", respDef.get("responseTemplates"));
|
||||
irRequest.put("contentHandling", respDef.get("contentHandling"));
|
||||
|
||||
putIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode, irRequest);
|
||||
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import io.swagger.models.Model;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.v3.oas.models.media.Schema;
|
||||
|
||||
/** Registers the model hierarchies Jackson reads and writes during OpenAPI import. */
|
||||
@RegisterForReflection(targets = {Model.class, Property.class, Schema.class}, registerFullHierarchy = true)
|
||||
public class OpenApiSchemaNativeSupport {}
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.DeploymentExportSnapshot;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Integration;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.MethodResponse;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Model;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.RequestValidator;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/** Serializes the supported REST configuration retained by a deployment. */
|
||||
final class RestApiOpenApiExporter {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private RestApiOpenApiExporter() {
|
||||
}
|
||||
|
||||
static ObjectNode export(DeploymentExportSnapshot snapshot, boolean swagger,
|
||||
boolean integrations, boolean authorizers, boolean apigateway) {
|
||||
ObjectNode document = JSON.createObjectNode();
|
||||
document.put(swagger ? "swagger" : "openapi", swagger ? "2.0" : "3.0.1");
|
||||
ObjectNode info = document.putObject("info");
|
||||
info.put("title", snapshot.api().getName());
|
||||
info.put("version", "1.0");
|
||||
put(info, "description", snapshot.api().getDescription());
|
||||
ObjectNode components = swagger ? document : document.putObject("components");
|
||||
ObjectNode schemas = components.putObject(swagger ? "definitions" : "schemas");
|
||||
for (Model model : snapshot.models()) {
|
||||
if (!"application/json".equals(model.getContentType())) {
|
||||
throw new AwsException("BadRequestException", "Only found non-JSON body models for " + model.getName(), 400);
|
||||
}
|
||||
try {
|
||||
JsonNode schema = JSON.readTree(model.getSchema());
|
||||
if (schema == null || !schema.isObject()) {
|
||||
throw new AwsException("BadRequestException", "Invalid JSON body model: " + model.getName(), 400);
|
||||
}
|
||||
schemas.set(model.getName(), schema);
|
||||
} catch (JsonProcessingException | IllegalArgumentException e) {
|
||||
throw new AwsException("BadRequestException", "Invalid JSON body model: " + model.getName(), 400);
|
||||
}
|
||||
}
|
||||
ObjectNode securitySchemes = components.putObject(swagger ? "securityDefinitions" : "securitySchemes");
|
||||
Map<String, String> authorizerNames = new HashMap<>();
|
||||
for (Authorizer authorizer : snapshot.authorizers()) {
|
||||
authorizerNames.put(authorizer.getId(), authorizer.getName());
|
||||
ObjectNode scheme = securitySchemes.putObject(authorizer.getName());
|
||||
scheme.put("type", "apiKey");
|
||||
scheme.put("in", "header");
|
||||
String source = authorizer.getIdentitySource();
|
||||
scheme.put("name", source != null && source.startsWith("method.request.header.")
|
||||
? source.substring("method.request.header.".length()) : "Authorization");
|
||||
scheme.put("x-amazon-apigateway-authtype", "COGNITO_USER_POOLS".equals(authorizer.getType())
|
||||
? "cognito_user_pools" : "custom");
|
||||
if (authorizers) {
|
||||
ObjectNode definition = scheme.putObject("x-amazon-apigateway-authorizer");
|
||||
definition.put("type", authorizer.getType().toLowerCase(Locale.ROOT));
|
||||
put(definition, "authorizerUri", authorizer.getAuthorizerUri());
|
||||
put(definition, "identitySource", source);
|
||||
if (authorizer.getAuthorizerResultTtlInSeconds() != null) {
|
||||
definition.put("authorizerResultTtlInSeconds",
|
||||
Integer.parseInt(authorizer.getAuthorizerResultTtlInSeconds()));
|
||||
}
|
||||
if (authorizer.getProviderARNs() != null) {
|
||||
definition.set("providerARNs", JSON.valueToTree(authorizer.getProviderARNs()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Map<String, String> validators = new HashMap<>();
|
||||
if (apigateway && !snapshot.validators().isEmpty()) {
|
||||
ObjectNode definitions = document.putObject("x-amazon-apigateway-request-validators");
|
||||
for (RequestValidator validator : snapshot.validators()) {
|
||||
validators.put(validator.getId(), validator.getName());
|
||||
ObjectNode definition = definitions.putObject(validator.getName());
|
||||
definition.put("validateRequestBody", validator.isValidateRequestBody());
|
||||
definition.put("validateRequestParameters", validator.isValidateRequestParameters());
|
||||
}
|
||||
}
|
||||
String iamScheme = availableName(securitySchemes, "sigv4");
|
||||
String keyScheme = availableName(securitySchemes, "api_key");
|
||||
ObjectNode paths = document.putObject("paths");
|
||||
for (ApiGatewayResource resource : snapshot.resources().stream()
|
||||
.sorted(Comparator.comparing(ApiGatewayResource::getPath)).toList()) {
|
||||
if (resource.getResourceMethods().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode path = paths.putObject(resource.getPath());
|
||||
for (Map.Entry<String, MethodConfig> entry : new TreeMap<>(resource.getResourceMethods()).entrySet()) {
|
||||
MethodConfig method = entry.getValue();
|
||||
ObjectNode operation = path.putObject("ANY".equals(entry.getKey())
|
||||
? "x-amazon-apigateway-any-method" : entry.getKey().toLowerCase(Locale.ROOT));
|
||||
exportParameters(operation, method, swagger);
|
||||
exportResponses(operation, method, swagger);
|
||||
ObjectNode requirement = JSON.createObjectNode();
|
||||
if ("AWS_IAM".equals(method.getAuthorizationType())) {
|
||||
ObjectNode scheme = securitySchemes.putObject(iamScheme);
|
||||
scheme.put("type", "apiKey");
|
||||
scheme.put("name", "Authorization");
|
||||
scheme.put("in", "header");
|
||||
scheme.put("x-amazon-apigateway-authtype", "awsSigv4");
|
||||
requirement.putArray(iamScheme);
|
||||
} else if ("CUSTOM".equals(method.getAuthorizationType())
|
||||
|| "COGNITO_USER_POOLS".equals(method.getAuthorizationType())) {
|
||||
String name = authorizerNames.get(method.getAuthorizerId());
|
||||
if (name == null) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Missing authorizer for protected method " + entry.getKey() + " " + resource.getPath(), 400);
|
||||
}
|
||||
requirement.set(name, JSON.valueToTree(method.getAuthorizationScopes()));
|
||||
}
|
||||
if (method.isApiKeyRequired()) {
|
||||
ObjectNode scheme = securitySchemes.putObject(keyScheme);
|
||||
scheme.put("type", "apiKey");
|
||||
scheme.put("name", "x-api-key");
|
||||
scheme.put("in", "header");
|
||||
requirement.putArray(keyScheme);
|
||||
}
|
||||
if (!requirement.isEmpty()) {
|
||||
operation.putArray("security").add(requirement);
|
||||
}
|
||||
put(operation, "x-amazon-apigateway-request-validator", validators.get(method.getRequestValidatorId()));
|
||||
if (integrations && method.getMethodIntegration() != null) {
|
||||
operation.set("x-amazon-apigateway-integration", exportIntegration(method.getMethodIntegration()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (apigateway) {
|
||||
if (!snapshot.api().getBinaryMediaTypes().isEmpty()) {
|
||||
document.set("x-amazon-apigateway-binary-media-types", JSON.valueToTree(snapshot.api().getBinaryMediaTypes()));
|
||||
}
|
||||
if (snapshot.api().getPolicy() != null) {
|
||||
try {
|
||||
document.set("x-amazon-apigateway-policy", JSON.readTree(snapshot.api().getPolicy()));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("BadRequestException", "Invalid JSON API policy", 400);
|
||||
}
|
||||
}
|
||||
ObjectNode responses = document.putObject("x-amazon-apigateway-gateway-responses");
|
||||
for (GatewayResponse response : snapshot.gatewayResponses()) {
|
||||
if (!response.isDefaultResponse()) {
|
||||
ObjectNode definition = responses.putObject(response.getResponseType());
|
||||
put(definition, "statusCode", response.getStatusCode());
|
||||
definition.set("responseParameters", JSON.valueToTree(response.getResponseParameters()));
|
||||
definition.set("responseTemplates", JSON.valueToTree(response.getResponseTemplates()));
|
||||
}
|
||||
}
|
||||
}
|
||||
rewriteSchemaReferences(document, swagger);
|
||||
return document;
|
||||
}
|
||||
|
||||
private static void exportParameters(ObjectNode operation, MethodConfig method, boolean swagger) {
|
||||
ArrayNode parameters = operation.putArray("parameters");
|
||||
for (Map.Entry<String, Boolean> entry : new TreeMap<>(method.getRequestParameters()).entrySet()) {
|
||||
String[] parts = entry.getKey().split("\\.", 4);
|
||||
if (parts.length != 4) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode parameter = parameters.addObject();
|
||||
parameter.put("name", parts[3]);
|
||||
String location = "querystring".equals(parts[2]) ? "query" : parts[2];
|
||||
parameter.put("in", location);
|
||||
parameter.put("required", "path".equals(location) || Boolean.TRUE.equals(entry.getValue()));
|
||||
if (swagger) {
|
||||
parameter.put("type", "string");
|
||||
} else {
|
||||
parameter.putObject("schema").put("type", "string");
|
||||
}
|
||||
}
|
||||
if (!method.getRequestModels().isEmpty()) {
|
||||
if (swagger) {
|
||||
if (method.getRequestModels().values().stream().distinct().count() != 1) {
|
||||
throw new AwsException("BadRequestException", "Swagger export requires one request body model per method", 400);
|
||||
}
|
||||
ObjectNode body = parameters.addObject();
|
||||
body.put("name", "body");
|
||||
body.put("in", "body");
|
||||
body.putObject("schema").put("$ref", "#/components/schemas/" + method.getRequestModels().values().iterator().next());
|
||||
operation.set("consumes", JSON.valueToTree(method.getRequestModels().keySet()));
|
||||
} else {
|
||||
ObjectNode content = operation.putObject("requestBody").putObject("content");
|
||||
method.getRequestModels().forEach((type, name) ->
|
||||
content.putObject(type).putObject("schema").put("$ref", "#/components/schemas/" + name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void exportResponses(ObjectNode operation, MethodConfig method, boolean swagger) {
|
||||
ObjectNode responses = operation.putObject("responses");
|
||||
for (MethodResponse response : new TreeMap<>(method.getMethodResponses()).values()) {
|
||||
ObjectNode definition = responses.putObject(response.statusCode());
|
||||
definition.put("description", response.statusCode() + " response");
|
||||
if (response.responseParameters() != null && !response.responseParameters().isEmpty()) {
|
||||
ObjectNode headers = definition.putObject("headers");
|
||||
response.responseParameters().forEach((name, required) -> {
|
||||
String prefix = "method.response.header.";
|
||||
if (name.startsWith(prefix)) {
|
||||
ObjectNode header = headers.putObject(name.substring(prefix.length()));
|
||||
if (swagger) {
|
||||
header.put("type", "string");
|
||||
} else {
|
||||
header.putObject("schema").put("type", "string");
|
||||
header.put("required", Boolean.TRUE.equals(required));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if (responses.isEmpty()) {
|
||||
responses.putObject("default").put("description", "Default response");
|
||||
}
|
||||
}
|
||||
|
||||
private static ObjectNode exportIntegration(Integration integration) {
|
||||
ObjectNode node = JSON.createObjectNode();
|
||||
node.put("type", integration.getType().toLowerCase(Locale.ROOT));
|
||||
put(node, "uri", integration.getUri());
|
||||
put(node, "httpMethod", integration.getHttpMethod());
|
||||
put(node, "credentials", integration.getCredentials());
|
||||
put(node, "passthroughBehavior", integration.getPassthroughBehavior() != null
|
||||
? integration.getPassthroughBehavior().toLowerCase(Locale.ROOT) : null);
|
||||
put(node, "contentHandling", integration.getContentHandling());
|
||||
put(node, "connectionType", integration.getConnectionType());
|
||||
put(node, "connectionId", integration.getConnectionId());
|
||||
put(node, "cacheNamespace", integration.getCacheNamespace());
|
||||
node.set("cacheKeyParameters", JSON.valueToTree(integration.getCacheKeyParameters()));
|
||||
node.set("requestParameters", JSON.valueToTree(integration.getRequestParameters()));
|
||||
node.set("requestTemplates", JSON.valueToTree(integration.getRequestTemplates()));
|
||||
if (integration.getTimeoutInMillis() != null) {
|
||||
node.put("timeoutInMillis", integration.getTimeoutInMillis());
|
||||
}
|
||||
put(node, "responseTransferMode", integration.getResponseTransferMode());
|
||||
if (integration.getTlsConfig() != null) {
|
||||
node.putObject("tlsConfig").put("insecureSkipVerification", integration.getTlsConfig().isInsecureSkipVerification());
|
||||
}
|
||||
ObjectNode responses = node.putObject("responses");
|
||||
for (IntegrationResponse response : new TreeMap<>(integration.getIntegrationResponses()).values()) {
|
||||
String pattern = response.selectionPattern();
|
||||
if ("default".equals(pattern)) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Cannot export the reserved integration response selection pattern 'default'", 400);
|
||||
}
|
||||
String key = pattern == null || pattern.isEmpty() ? "default" : pattern;
|
||||
if (responses.has(key)) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Cannot export duplicate integration response selection pattern '" + key + "'", 400);
|
||||
}
|
||||
ObjectNode definition = responses.putObject(key);
|
||||
definition.put("statusCode", response.statusCode());
|
||||
definition.set("responseParameters", JSON.valueToTree(response.responseParameters()));
|
||||
definition.set("responseTemplates", JSON.valueToTree(response.responseTemplates()));
|
||||
put(definition, "contentHandling", response.contentHandling());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static void rewriteSchemaReferences(JsonNode node, boolean swagger) {
|
||||
if (node instanceof ObjectNode object) {
|
||||
JsonNode ref = object.get("$ref");
|
||||
String source = swagger ? "#/components/schemas/" : "#/definitions/";
|
||||
String target = swagger ? "#/definitions/" : "#/components/schemas/";
|
||||
if (ref != null && ref.isTextual() && ref.asText().startsWith(source)) {
|
||||
object.put("$ref", ref.asText().replace(source, target));
|
||||
}
|
||||
}
|
||||
for (JsonNode child : node) {
|
||||
rewriteSchemaReferences(child, swagger);
|
||||
}
|
||||
}
|
||||
|
||||
private static String availableName(ObjectNode schemes, String preferred) {
|
||||
String name = preferred;
|
||||
int suffix = 1;
|
||||
while (schemes.has(name)) {
|
||||
name = preferred + "_" + suffix++;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private static void put(ObjectNode node, String field, String value) {
|
||||
if (value != null) {
|
||||
node.put(field, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import io.swagger.v3.parser.converter.SwaggerConverter;
|
||||
|
||||
/** Keeps the Swagger 2.0 parser provider available for OpenAPIParser's ServiceLoader. */
|
||||
@RegisterForReflection(targets = SwaggerConverter.class, methods = false, fields = false, ignoreNested = true)
|
||||
public class SwaggerParserNativeSupport {}
|
||||
@@ -8,6 +8,10 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
public record Deployment(
|
||||
String id,
|
||||
String description,
|
||||
long createdDate
|
||||
long createdDate,
|
||||
String exportSnapshot
|
||||
) {
|
||||
public Deployment(String id, String description, long createdDate) {
|
||||
this(id, description, createdDate, null);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@RegisterForReflection
|
||||
public record DeploymentExportSnapshot(
|
||||
RestApi api,
|
||||
List<ApiGatewayResource> resources,
|
||||
List<Model> models,
|
||||
List<Authorizer> authorizers,
|
||||
List<RequestValidator> validators,
|
||||
List<GatewayResponse> gatewayResponses
|
||||
) {
|
||||
}
|
||||
Reference in new issue
Block a user