Light, fluffy, and always free - The AWS Local Emulator alternative
feat(apigatewayv2): OpenAPI import and Terraform-visible API/stage attributes (#2714)
Brian Taylor881695ea3b1c
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.mdindex a7b2edc9cb..aea738948f 100644--- a/docs/services/api-gateway.md+++ b/docs/services/api-gateway.md@@ -230,7 +230,7 @@ this default hostname with `404 Not Found`, matching AWS HTTP API behavior.| Category | Operations ||---|---|-| **APIs** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, DeleteCorsConfiguration |+| **APIs** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, DeleteCorsConfiguration, ImportApi, ReimportApi || **Routes** | CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute || **Route Responses** | CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse || **Integrations** | CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration |@@ -303,7 +303,7 @@ DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Disconn### Not Implemented-- `ReimportApi`, `ExportApi`, `UpdateDomainName`, `UpdateApiMapping`+- `ExportApi`, `UpdateDomainName`, `UpdateApiMapping`- `UpdateVpcLink` — the other four VPC Link operations are implemented; see the table above### Examplesdiff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.javaindex 9bc62c4ddc..7b650546f1 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java@@ -29,6 +29,7 @@ import io.github.hectorvent.floci.services.apigateway.model.RequestValidator;import io.github.hectorvent.floci.services.apigateway.model.RestApi;import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2OpenApiImporter;import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;import io.github.hectorvent.floci.services.apigatewayv2.model.Api;import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;@@ -66,14 +67,17 @@ public class ApiGatewayController {private final ApiGatewayService service;private final ApiGatewayV2Service v2Service;+ private final ApiGatewayV2OpenApiImporter v2OpenApiImporter;private final RegionResolver regionResolver;private final ObjectMapper objectMapper;@Injectpublic ApiGatewayController(ApiGatewayService service, ApiGatewayV2Service v2Service,+ ApiGatewayV2OpenApiImporter v2OpenApiImporter,RegionResolver regionResolver, ObjectMapper objectMapper) {this.service = service;this.v2Service = v2Service;+ this.v2OpenApiImporter = v2OpenApiImporter;this.regionResolver = regionResolver;this.objectMapper = objectMapper;}@@ -1099,6 +1103,19 @@ public class ApiGatewayController {}}+ @PUT+ @Path("/v2/apis")+ @Consumes(MediaType.WILDCARD)+ public Response importApi(@Context HttpHeaders headers,+ @QueryParam("basepath") String basePath,+ @QueryParam("failOnWarnings") Boolean failOnWarnings,+ String body) {+ String region = regionResolver.resolveRegion(headers);+ Api api = v2OpenApiImporter.importApi(region, extractOpenApiBody(body), basePath,+ Boolean.TRUE.equals(failOnWarnings));+ return Response.status(201).entity(toV2ApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();+ }+@GET@Path("/v2/apis")public Response getApis(@Context HttpHeaders headers) {@@ -1148,6 +1165,40 @@ public class ApiGatewayController {return Response.noContent().build();}+ @PUT+ @Path("/v2/apis/{apiId}")+ @Consumes(MediaType.WILDCARD)+ public Response reimportApi(@Context HttpHeaders headers,+ @PathParam("apiId") String apiId,+ @QueryParam("basepath") String basePath,+ @QueryParam("failOnWarnings") Boolean failOnWarnings,+ String body) {+ String region = regionResolver.resolveRegion(headers);+ Api api = v2OpenApiImporter.reimportApi(region, apiId, extractOpenApiBody(body), basePath,+ Boolean.TRUE.equals(failOnWarnings));+ return Response.status(201).entity(toV2ApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();+ }++ /**+ * ImportApi/ReimportApi wrap the OpenAPI document in a restJson1 envelope — {@code {"body": "..."}} —+ * unlike the v1 ImportRestApi/PutRestApi pair, which post the document as the raw HTTP body.+ * Fall back to treating the payload as the document itself so a hand-rolled curl still works.+ */+ private String extractOpenApiBody(String payload) {+ if (payload == null || payload.isBlank()) {+ throw new AwsException("BadRequestException", "Body is required for OpenAPI import", 400);+ }+ try {+ com.fasterxml.jackson.databind.JsonNode root = objectMapper.readTree(payload);+ if (root.isObject() && root.hasNonNull("body") && root.get("body").isTextual()) {+ return root.get("body").asText();+ }+ } catch (IOException e) {+ // Not JSON at all — a raw YAML/JSON OpenAPI document.+ }+ return payload;+ }+@POST@Path("/v2/apis/{apiId}/routes")public Response createRoute(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {@@ -2255,6 +2306,17 @@ public class ApiGatewayController {if (api.getRouteSelectionExpression() != null) node.put("routeSelectionExpression", api.getRouteSelectionExpression());if (api.getDescription() != null) node.put("description", api.getDescription());if (api.getApiKeySelectionExpression() != null) node.put("apiKeySelectionExpression", api.getApiKeySelectionExpression());+ if (api.getVersion() != null) {+ node.put("version", api.getVersion());+ }+ if (api.getWarnings() != null && !api.getWarnings().isEmpty()) {+ ArrayNode warnings = node.putArray("warnings");+ api.getWarnings().forEach(warnings::add);+ }+ if (api.getImportInfo() != null && !api.getImportInfo().isEmpty()) {+ ArrayNode importInfo = node.putArray("importInfo");+ api.getImportInfo().forEach(importInfo::add);+ }if (api.getTags() != null && !api.getTags().isEmpty()) {ObjectNode tagsNode = objectMapper.createObjectNode();api.getTags().forEach(tagsNode::put);@@ -2374,6 +2436,45 @@ public class ApiGatewayController {ObjectNode tags = node.putObject("tags");s.getTags().forEach(tags::put);}+ if (s.getDescription() != null) {+ node.put("description", s.getDescription());+ }+ if (s.getAccessLogSettings() != null) {+ ObjectNode logs = node.putObject("accessLogSettings");+ if (s.getAccessLogSettings().destinationArn() != null) {+ logs.put("destinationArn", s.getAccessLogSettings().destinationArn());+ }+ if (s.getAccessLogSettings().format() != null) {+ logs.put("format", s.getAccessLogSettings().format());+ }+ }+ if (s.getDefaultRouteSettings() != null) {+ node.set("defaultRouteSettings", toV2RouteSettingsNode(s.getDefaultRouteSettings()));+ }+ if (s.getRouteSettings() != null && !s.getRouteSettings().isEmpty()) {+ ObjectNode routeSettings = node.putObject("routeSettings");+ s.getRouteSettings().forEach((k, v) -> routeSettings.set(k, toV2RouteSettingsNode(v)));+ }+ return node;+ }++ private ObjectNode toV2RouteSettingsNode(Stage.RouteSettings rs) {+ ObjectNode node = objectMapper.createObjectNode();+ if (rs.detailedMetricsEnabled() != null) {+ node.put("detailedMetricsEnabled", rs.detailedMetricsEnabled());+ }+ if (rs.dataTraceEnabled() != null) {+ node.put("dataTraceEnabled", rs.dataTraceEnabled());+ }+ if (rs.loggingLevel() != null) {+ node.put("loggingLevel", rs.loggingLevel());+ }+ if (rs.throttlingBurstLimit() != null) {+ node.put("throttlingBurstLimit", rs.throttlingBurstLimit());+ }+ if (rs.throttlingRateLimit() != null) {+ node.put("throttlingRateLimit", rs.throttlingRateLimit());+ }return node;}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.javaindex 24b68f0304..28e3af53bb 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java@@ -19,11 +19,15 @@ import java.util.Map;public class ApiGatewayV2JsonHandler {private final ApiGatewayV2Service service;+ private final ApiGatewayV2OpenApiImporter openApiImporter;private final ObjectMapper objectMapper;@Inject- public ApiGatewayV2JsonHandler(ApiGatewayV2Service service, ObjectMapper objectMapper) {+ public ApiGatewayV2JsonHandler(ApiGatewayV2Service service,+ ApiGatewayV2OpenApiImporter openApiImporter,+ ObjectMapper objectMapper) {this.service = service;+ this.openApiImporter = openApiImporter;this.objectMapper = objectMapper;}@@ -31,6 +35,8 @@ public class ApiGatewayV2JsonHandler {try {return switch (action) {case "CreateApi" -> handleCreateApi(request, region);+ case "ImportApi" -> handleImportApi(request, region);+ case "ReimportApi" -> handleReimportApi(request, region);case "GetApis" -> handleGetApis(region);case "GetApi" -> handleGetApi(request, region);case "UpdateApi" -> handleUpdateApi(request, region);@@ -94,6 +100,19 @@ public class ApiGatewayV2JsonHandler {return Response.status(201).entity(toApiNode(api).toString()).build();}+ private Response handleImportApi(JsonNode request, String region) {+ Api api = openApiImporter.importApi(region, request.path("Body").asText(null),+ request.path("Basepath").asText(null), request.path("FailOnWarnings").asBoolean(false));+ return Response.status(201).entity(toApiNode(api).toString()).build();+ }++ private Response handleReimportApi(JsonNode request, String region) {+ String apiId = request.path("ApiId").asText();+ Api api = openApiImporter.reimportApi(region, apiId, request.path("Body").asText(null),+ request.path("Basepath").asText(null), request.path("FailOnWarnings").asBoolean(false));+ return Response.status(201).entity(toApiNode(api).toString()).build();+ }+private Response handleGetApis(String region) {List<Api> apis = service.getApis(region);ObjectNode root = objectMapper.createObjectNode();@@ -505,6 +524,17 @@ public class ApiGatewayV2JsonHandler {if (api.getApiKeySelectionExpression() != null) {node.put("ApiKeySelectionExpression", api.getApiKeySelectionExpression());}+ if (api.getVersion() != null) {+ node.put("Version", api.getVersion());+ }+ if (api.getWarnings() != null && !api.getWarnings().isEmpty()) {+ ArrayNode warnings = node.putArray("Warnings");+ api.getWarnings().forEach(warnings::add);+ }+ if (api.getImportInfo() != null && !api.getImportInfo().isEmpty()) {+ ArrayNode importInfo = node.putArray("ImportInfo");+ api.getImportInfo().forEach(importInfo::add);+ }if (api.getTags() != null && !api.getTags().isEmpty()) {ObjectNode tagsNode = node.putObject("Tags");api.getTags().forEach(tagsNode::put);@@ -636,6 +666,45 @@ public class ApiGatewayV2JsonHandler {ObjectNode tags = node.putObject("Tags");s.getTags().forEach(tags::put);}+ if (s.getDescription() != null) {+ node.put("Description", s.getDescription());+ }+ if (s.getAccessLogSettings() != null) {+ ObjectNode logs = node.putObject("AccessLogSettings");+ if (s.getAccessLogSettings().destinationArn() != null) {+ logs.put("DestinationArn", s.getAccessLogSettings().destinationArn());+ }+ if (s.getAccessLogSettings().format() != null) {+ logs.put("Format", s.getAccessLogSettings().format());+ }+ }+ if (s.getDefaultRouteSettings() != null) {+ node.set("DefaultRouteSettings", toRouteSettingsNode(s.getDefaultRouteSettings()));+ }+ if (s.getRouteSettings() != null && !s.getRouteSettings().isEmpty()) {+ ObjectNode routeSettings = node.putObject("RouteSettings");+ s.getRouteSettings().forEach((k, v) -> routeSettings.set(k, toRouteSettingsNode(v)));+ }+ return node;+ }++ private ObjectNode toRouteSettingsNode(Stage.RouteSettings rs) {+ ObjectNode node = objectMapper.createObjectNode();+ if (rs.detailedMetricsEnabled() != null) {+ node.put("DetailedMetricsEnabled", rs.detailedMetricsEnabled());+ }+ if (rs.dataTraceEnabled() != null) {+ node.put("DataTraceEnabled", rs.dataTraceEnabled());+ }+ if (rs.loggingLevel() != null) {+ node.put("LoggingLevel", rs.loggingLevel());+ }+ if (rs.throttlingBurstLimit() != null) {+ node.put("ThrottlingBurstLimit", rs.throttlingBurstLimit());+ }+ if (rs.throttlingRateLimit() != null) {+ node.put("ThrottlingRateLimit", rs.throttlingRateLimit());+ }return node;}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2OpenApiImporter.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2OpenApiImporter.javanew file mode 100644index 0000000000..b7ed2863ad--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2OpenApiImporter.java@@ -0,0 +1,770 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.apigatewayv2.model.Api;+import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;+import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;+import io.github.hectorvent.floci.services.apigatewayv2.model.Route;+import io.swagger.v3.oas.models.OpenAPI;+import io.swagger.v3.oas.models.Operation;+import io.swagger.v3.oas.models.PathItem;+import io.swagger.v3.oas.models.security.SecurityRequirement;+import io.swagger.v3.oas.models.security.SecurityScheme;+import io.swagger.v3.oas.models.servers.Server;+import io.swagger.v3.oas.models.servers.ServerVariable;+import io.swagger.v3.parser.core.models.SwaggerParseResult;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.function.BiConsumer;++/**+ * OpenAPI import for HTTP APIs (ImportApi / ReimportApi).+ *+ * <p>Mirrors {@code ApiGatewayService#importRestApi}/{@code putRestApi} for the v1 REST API, but+ * materialises the v2 object model (routes + integrations + authorizers) instead of the v1+ * resource/method tree. The AWS extensions honoured are+ * {@code x-amazon-apigateway-integration}, {@code x-amazon-apigateway-authorizer},+ * {@code x-amazon-apigateway-any-method} and {@code x-amazon-apigateway-cors}.+ */+@ApplicationScoped+public class ApiGatewayV2OpenApiImporter {++ private static final Logger LOG = Logger.getLogger(ApiGatewayV2OpenApiImporter.class);++ private static final String EXT_INTEGRATION = "x-amazon-apigateway-integration";+ private static final String EXT_AUTHORIZER = "x-amazon-apigateway-authorizer";+ private static final String EXT_ANY_METHOD = "x-amazon-apigateway-any-method";+ private static final String EXT_CORS = "x-amazon-apigateway-cors";++ private final ApiGatewayV2Service service;++ @Inject+ public ApiGatewayV2OpenApiImporter(ApiGatewayV2Service service) {+ this.service = service;+ }++ // ──────────────────────────── Entry points ────────────────────────────++ /** ImportApi — creates a brand new HTTP API from an OpenAPI 3 document. */+ public Api importApi(String region, String specBody, String basePathMode, boolean failOnWarnings) {+ ImportPlan plan = plan(specBody, basePathMode, failOnWarnings);+ OpenAPI openAPI = plan.openAPI();++ Map<String, Object> request = new HashMap<>();+ request.put("protocolType", "HTTP");+ request.put("name", specTitle(openAPI, "Imported API"));+ String description = specDescription(openAPI);+ if (description != null) {+ request.put("description", description);+ }+ String version = specVersion(openAPI);+ if (version != null) {+ request.put("version", version);+ }+ Map<String, Object> cors = corsConfiguration(openAPI);+ if (cors != null) {+ request.put("corsConfiguration", cors);+ }++ Api api = service.createApi(region, request);+ applySpec(region, api.getApiId(), plan);+ recordImportDiagnostics(region, api.getApiId(), plan);+ LOG.infov("Imported HTTP API from OpenAPI spec: {0} ({1})", api.getName(), api.getApiId());+ return service.getApi(region, api.getApiId());+ }++ /**+ * ReimportApi — replaces the definition of an existing HTTP API.+ *+ * <p>AWS replaces the whole definition, so every route, integration and authorizer is dropped+ * before the spec is applied. API-level settings that an OpenAPI document cannot express (CORS+ * when the spec carries no {@code x-amazon-apigateway-cors}, tags, the execute-api toggle) are+ * left untouched, which is what keeps a Terraform {@code aws_apigatewayv2_api} whose+ * {@code cors_configuration} lives on the resource rather than in {@code body} from flapping.+ */+ public Api reimportApi(String region, String apiId, String specBody, String basePathMode,+ boolean failOnWarnings) {+ Api api = service.getApi(region, apiId);+ if (!"HTTP".equals(api.getProtocolType())) {+ throw new AwsException("BadRequestException",+ "Cannot import an OpenAPI definition into a " + api.getProtocolType() + " API", 400);+ }++ // Parse and validate before touching anything: failOnWarnings must roll the whole+ // operation back, and a half-replaced API is worse than a rejected one.+ ImportPlan plan = plan(specBody, basePathMode, failOnWarnings);+ OpenAPI openAPI = plan.openAPI();++ for (Route route : service.getRoutes(region, apiId)) {+ service.deleteRoute(region, apiId, route.getRouteId());+ }+ for (Integration integration : service.getIntegrations(region, apiId)) {+ service.deleteIntegration(region, apiId, integration.getIntegrationId());+ }+ for (Authorizer authorizer : service.getAuthorizers(region, apiId)) {+ service.deleteAuthorizer(region, apiId, authorizer.getAuthorizerId());+ }++ Map<String, Object> update = new HashMap<>();+ String title = specTitle(openAPI, null);+ if (title != null) {+ update.put("name", title);+ }+ String description = specDescription(openAPI);+ if (description != null) {+ update.put("description", description);+ }+ String version = specVersion(openAPI);+ if (version != null) {+ update.put("version", version);+ }+ Map<String, Object> cors = corsConfiguration(openAPI);+ if (cors != null) {+ update.put("corsConfiguration", cors);+ }+ if (!update.isEmpty()) {+ service.updateApi(region, apiId, update);+ }++ applySpec(region, apiId, plan);+ recordImportDiagnostics(region, apiId, plan);+ LOG.infov("Reimported HTTP API from OpenAPI spec: {0} ({1})", api.getName(), apiId);+ return service.getApi(region, apiId);+ }++ // ──────────────────────────── Planning ────────────────────────────++ /**+ * A parsed document plus everything decided before the first write: the route path prefix the+ * basepath mode implies, and the diagnostics AWS reports back on the Api.+ */+ private record ImportPlan(OpenAPI openAPI, String pathPrefix, List<AuthorizerSpec> authorizerSpecs,+ List<String> warnings, List<String> importInfo) {}++ private ImportPlan plan(String specBody, String basePathMode, boolean failOnWarnings) {+ if (specBody == null || specBody.isBlank()) {+ throw new AwsException("BadRequestException", "Body is required for OpenAPI import", 400);+ }+ String mode = basePathMode == null || basePathMode.isBlank()+ ? "ignore"+ : basePathMode.toLowerCase(Locale.ROOT);+ if (!List.of("ignore", "prepend", "split").contains(mode)) {+ throw new AwsException("BadRequestException",+ "Invalid basepath '" + basePathMode + "'; valid values are ignore, prepend and split", 400);+ }++ SwaggerParseResult result = new io.swagger.parser.OpenAPIParser().readContents(specBody, null, null);+ if (result.getOpenAPI() == null) {+ String errors = result.getMessages() != null ? String.join(", ", result.getMessages()) : "unknown error";+ throw new AwsException("BadRequestException", "Failed to parse OpenAPI spec: " + errors, 400);+ }+ OpenAPI openAPI = result.getOpenAPI();++ List<String> warnings = new ArrayList<>();+ if (result.getMessages() != null) {+ result.getMessages().stream().filter(m -> m != null && !m.isBlank()).forEach(warnings::add);+ }++ List<String> importInfo = new ArrayList<>();+ String pathPrefix = pathPrefix(openAPI, mode, importInfo);+ collectImportInfo(openAPI, importInfo);++ // Resolve the authorizers here rather than during application: this is what makes a+ // rejected reimport leave the previous definition intact.+ List<AuthorizerSpec> authorizerSpecs = authorizerSpecs(openAPI);+ collectUnresolvedSecurity(openAPI, authorizerSpecs, warnings);++ if (failOnWarnings && !warnings.isEmpty()) {+ throw new AwsException("BadRequestException",+ "Warnings found during import: " + String.join(", ", warnings), 400);+ }+ return new ImportPlan(openAPI, pathPrefix, authorizerSpecs, warnings, importInfo);+ }++ /**+ * Flags security requirements that name a scheme HTTP APIs cannot enforce — a plain bearer or+ * apiKey scheme with no {@code x-amazon-apigateway-authorizer}, or a misspelled scheme name.+ * Such a route is imported as NONE, so without this the document would appear to secure an+ * endpoint that ends up publicly invokable. Raised as a warning rather than an error so+ * failOnWarnings decides whether it is fatal.+ */+ private static void collectUnresolvedSecurity(OpenAPI openAPI, List<AuthorizerSpec> specs,+ List<String> warnings) {+ Map<String, String> bindable = new LinkedHashMap<>();+ specs.forEach(spec -> bindable.put(spec.schemeName(), spec.authorizationType()));++ java.util.Set<String> reported = new java.util.LinkedHashSet<>();+ BiConsumer<String, List<SecurityRequirement>> check = (routeKey, security) -> {+ if (security == null || security.isEmpty()) {+ return;+ }+ boolean anyResolves = security.stream()+ .flatMap(requirement -> requirement.keySet().stream())+ .anyMatch(bindable::containsKey);+ if (!anyResolves) {+ String names = security.stream()+ .flatMap(requirement -> requirement.keySet().stream())+ .distinct()+ .collect(java.util.stream.Collectors.joining(", "));+ reported.add("Security requirement (" + names + ") on " + routeKey+ + " does not resolve to a supported authorizer; the route is imported as NONE"+ + " and will accept unauthenticated requests");+ return;+ }+ // Several schemes inside one SecurityRequirement is OpenAPI's AND: the caller must+ // satisfy all of them. A route carries exactly one authorizer, so only the first+ // resolvable scheme is enforced and the rest are dropped.+ security.stream()+ .filter(requirement -> requirement.keySet().size() > 1)+ .findFirst()+ .ifPresent(requirement -> {+ String enforced = requirement.keySet().stream()+ .filter(bindable::containsKey)+ .findFirst()+ .orElse(null);+ reported.add("Security requirement on " + routeKey + " combines ("+ + String.join(", ", requirement.keySet())+ + "); HTTP API routes carry a single authorizer, so only "+ + enforced + " is enforced and the remaining schemes are dropped");+ });++ // AWS_IAM is recorded on the route because that is what AWS records, but the HTTP API+ // dispatcher only enforces JWT and CUSTOM, so nothing checks the signature. Say so+ // rather than let a sigv4-protected document look enforced locally.+ security.stream()+ .flatMap(requirement -> requirement.keySet().stream())+ .filter(scheme -> "AWS_IAM".equals(bindable.get(scheme)))+ .findFirst()+ .ifPresent(scheme -> reported.add("Security scheme " + scheme + " on " + routeKey+ + " imports as AWS_IAM, which this emulator records but does not enforce;"+ + " requests reach the integration without a verified SigV4 signature"));+ };++ List<SecurityRequirement> globalSecurity = openAPI.getSecurity();+ forEachImportedOperation(openAPI, (method, path, operation) -> {+ List<SecurityRequirement> security =+ operation != null && operation.getSecurity() != null+ ? operation.getSecurity()+ : globalSecurity;+ check.accept(method + " " + path, security);+ });+ warnings.addAll(reported);+ }++ /**+ * Resolves the base path the way the Import API does for OpenAPI 3: a {@code basePath} server+ * variable wins (the first, if several are declared), otherwise any path carried by+ * {@code server.url}. "prepend" puts the whole thing in front of every route; "split" drops its+ * first segment first; "ignore" — the default — contributes nothing.+ */+ private static String pathPrefix(OpenAPI openAPI, String mode, List<String> importInfo) {+ if ("ignore".equals(mode)) {+ return "";+ }+ String basePath = resolveBasePath(openAPI);+ if (basePath == null) {+ importInfo.add("basepath=" + mode + " was requested but the definition declares no base path");+ return "";+ }+ if ("split".equals(mode)) {+ int nextSlash = basePath.indexOf('/', 1);+ return nextSlash < 0 ? "" : trimTrailingSlash(basePath.substring(nextSlash));+ }+ return trimTrailingSlash(basePath);+ }++ private static String resolveBasePath(OpenAPI openAPI) {+ if (openAPI.getServers() == null) {+ return null;+ }+ for (Server server : openAPI.getServers()) {+ if (server.getVariables() != null) {+ ServerVariable variable = server.getVariables().get("basePath");+ if (variable != null && variable.getDefault() != null && !variable.getDefault().isBlank()) {+ return leadingSlash(variable.getDefault());+ }+ }+ }+ for (Server server : openAPI.getServers()) {+ String path = serverUrlPath(server.getUrl());+ if (path != null) {+ return path;+ }+ }+ return null;+ }++ /** The path portion of a server URL, or null when it carries none beyond "/". */+ private static String serverUrlPath(String url) {+ if (url == null || url.isBlank()) {+ return null;+ }+ String path = url;+ int schemeEnd = path.indexOf("://");+ if (schemeEnd >= 0) {+ int hostEnd = path.indexOf('/', schemeEnd + 3);+ path = hostEnd < 0 ? "" : path.substring(hostEnd);+ }+ path = trimTrailingSlash(path);+ return path.isEmpty() || "/".equals(path) ? null : leadingSlash(path);+ }++ private static String leadingSlash(String value) {+ return value.startsWith("/") ? value : "/" + value;+ }++ private static String trimTrailingSlash(String value) {+ return value.length() > 1 && value.endsWith("/") ? value.substring(0, value.length() - 1) : value;+ }++ /** Notes definition properties the import does not carry into the v2 object model. */+ private static void collectImportInfo(OpenAPI openAPI, List<String> importInfo) {+ if (openAPI.getComponents() != null && openAPI.getComponents().getSchemas() != null+ && !openAPI.getComponents().getSchemas().isEmpty()) {+ importInfo.add("Ignoring component schemas; HTTP APIs do not perform request validation");+ }+ forEachImportedOperation(openAPI, (method, path, operation) -> {+ if (operation != null && extensionAsMap(operation.getExtensions(), EXT_INTEGRATION) == null) {+ importInfo.add("No " + EXT_INTEGRATION + " for " + method + " " + path+ + "; the route was created without an integration");+ }+ });+ }++ private void recordImportDiagnostics(String region, String apiId, ImportPlan plan) {+ Api api = service.getApi(region, apiId);+ api.setWarnings(plan.warnings().isEmpty() ? null : List.copyOf(plan.warnings()));+ api.setImportInfo(plan.importInfo().isEmpty() ? null : List.copyOf(plan.importInfo()));+ service.putApi(region, api);+ }++ // ──────────────────────────── Spec application ────────────────────────────++ /** Receives every operation the import turns into a route. */+ @FunctionalInterface+ private interface OperationVisitor {+ void visit(String method, String path, Operation operation);+ }++ /**+ * Single enumeration of the operations an import materialises, so route creation and the+ * diagnostic passes can never disagree about which they are. The+ * {@code x-amazon-apigateway-any-method} extension is not part of {@code readOperationsMap()},+ * and walking that map alone left ANY-method routes unexamined by the warning collectors.+ */+ private static void forEachImportedOperation(OpenAPI openAPI, OperationVisitor visitor) {+ if (openAPI.getPaths() == null) {+ return;+ }+ openAPI.getPaths().forEach((path, pathItem) -> {+ if (pathItem == null) {+ return;+ }+ pathItem.readOperationsMap()+ .forEach((method, operation) -> visitor.visit(method.name(), path, operation));+ Operation anyMethod = anyMethodOperation(pathItem);+ if (anyMethod != null) {+ visitor.visit("ANY", path, anyMethod);+ }+ });+ }++ private void applySpec(String region, String apiId, ImportPlan plan) {+ OpenAPI openAPI = plan.openAPI();+ Map<String, SchemeBinding> schemes = createAuthorizers(region, apiId, plan);+ List<SecurityRequirement> globalSecurity = openAPI.getSecurity();++ forEachImportedOperation(openAPI, (method, path, operation) ->+ createRouteForOperation(region, apiId, method, plan.pathPrefix() + path,+ operation, schemes, globalSecurity));+ }++ private void createRouteForOperation(String region, String apiId, String method, String path,+ Operation operation, Map<String, SchemeBinding> schemes,+ List<SecurityRequirement> globalSecurity) {+ Map<String, Object> routeRequest = new HashMap<>();+ routeRequest.put("routeKey", routeKey(method, path));++ Map<String, Object> integrationDef = extensionAsMap(+ operation == null ? null : operation.getExtensions(), EXT_INTEGRATION);+ if (integrationDef != null) {+ Integration integration = service.createIntegration(region, apiId,+ toIntegrationRequest(integrationDef));+ routeRequest.put("target", "integrations/" + integration.getIntegrationId());+ }++ List<SecurityRequirement> security =+ operation != null && operation.getSecurity() != null ? operation.getSecurity() : globalSecurity;+ SchemeBinding binding = resolveSecurity(security, schemes);+ if (binding == null) {+ routeRequest.put("authorizationType", "NONE");+ } else {+ routeRequest.put("authorizationType", binding.authorizationType());+ if (binding.authorizerId() != null) {+ routeRequest.put("authorizerId", binding.authorizerId());+ }+ }++ service.createRoute(region, apiId, routeRequest);+ }++ /**+ * AWS route keys are "{METHOD} {path}", with the path always leading with a slash. "$default"+ * is passed through untouched so a spec can declare the catch-all route.+ */+ private static String routeKey(String method, String path) {+ if ("$default".equals(path)) {+ return "$default";+ }+ String normalized = path.startsWith("/") ? path : "/" + path;+ return method.toUpperCase(Locale.ROOT) + " " + normalized;+ }++ private static Operation anyMethodOperation(PathItem pathItem) {+ Map<String, Object> anyMethod = extensionAsMap(pathItem.getExtensions(), EXT_ANY_METHOD);+ if (anyMethod == null) {+ return null;+ }+ // The extension holds a bare operation object; only its extensions and security matter here.+ Operation operation = new Operation();+ Map<String, Object> integrationDef = extensionAsMap(anyMethod, EXT_INTEGRATION);+ if (integrationDef != null) {+ operation.addExtension(EXT_INTEGRATION, integrationDef);+ }+ Object security = anyMethod.get("security");+ if (security instanceof List<?> list) {+ operation.setSecurity(toSecurityRequirements(list));+ }+ return operation;+ }++ @SuppressWarnings("unchecked")+ private static List<SecurityRequirement> toSecurityRequirements(List<?> raw) {+ List<SecurityRequirement> requirements = new ArrayList<>();+ for (Object entry : raw) {+ if (!(entry instanceof Map<?, ?> map)) {+ continue;+ }+ SecurityRequirement requirement = new SecurityRequirement();+ for (Map.Entry<?, ?> e : map.entrySet()) {+ List<String> scopes = e.getValue() instanceof List<?> scopeList+ ? (List<String>) scopeList+ : List.of();+ requirement.addList(String.valueOf(e.getKey()), scopes);+ }+ requirements.add(requirement);+ }+ return requirements;+ }++ // ──────────────────────────── Authorizers ────────────────────────────++ /** What a security scheme name resolves to once its authorizer (if any) has been created. */+ private record SchemeBinding(String authorizationType, String authorizerId) {}++ /**+ * A security scheme resolved to the CreateAuthorizer call it implies. {@code request} is null+ * for schemes that select an authorization type without an authorizer of their own — sigv4,+ * which is simply AWS_IAM.+ */+ private record AuthorizerSpec(String schemeName, String authorizationType, Map<String, Object> request) {}++ /**+ * Turns the document's security schemes into CreateAuthorizer calls, rejecting anything HTTP+ * APIs cannot express. Deliberately side-effect free: {@link #plan} runs this before+ * {@link #reimportApi} deletes anything, so a definition that is syntactically valid but+ * carries an unusable authorizer is refused with the previous definition still intact.+ */+ private static List<AuthorizerSpec> authorizerSpecs(OpenAPI openAPI) {+ List<AuthorizerSpec> specs = new ArrayList<>();+ if (openAPI.getComponents() == null || openAPI.getComponents().getSecuritySchemes() == null) {+ return specs;+ }++ for (Map.Entry<String, SecurityScheme> entry : openAPI.getComponents().getSecuritySchemes().entrySet()) {+ String schemeName = entry.getKey();+ SecurityScheme scheme = entry.getValue();+ if (scheme == null) {+ continue;+ }++ Map<String, Object> authDef = extensionAsMap(scheme.getExtensions(), EXT_AUTHORIZER);+ if (authDef == null) {+ // A scheme with no AWS authorizer extension still selects an authorization type:+ // sigv4 means IAM, everything else is unauthenticated as far as HTTP APIs go.+ if ("awsSigv4".equalsIgnoreCase(scheme.getName())+ || SecurityScheme.Type.HTTP.equals(scheme.getType())+ && "aws.v4".equalsIgnoreCase(scheme.getScheme())) {+ specs.add(new AuthorizerSpec(schemeName, "AWS_IAM", null));+ }+ continue;+ }++ String type = stringValue(authDef.get("type"));+ String authorizerType = type == null ? null : switch (type.toLowerCase(Locale.ROOT)) {+ case "request" -> "REQUEST";+ case "jwt" -> "JWT";+ default -> null;+ };+ if (authorizerType == null) {+ throw new AwsException("BadRequestException",+ "Unsupported " + EXT_AUTHORIZER + ".type '" + type + "' for security scheme "+ + schemeName + "; HTTP APIs support 'request' and 'jwt'", 400);+ }++ Map<String, Object> request = new HashMap<>();+ request.put("name", schemeName);+ request.put("authorizerType", authorizerType);++ List<String> identitySource = identitySource(authDef, scheme, authorizerType);+ if (!identitySource.isEmpty()) {+ request.put("identitySource", identitySource);+ }+ putIfPresent(request, "authorizerUri", stringValue(authDef.get("authorizerUri")));+ putIfPresent(request, "authorizerPayloadFormatVersion",+ stringValue(authDef.get("authorizerPayloadFormatVersion")));+ if (authDef.get("authorizerResultTtlInSeconds") instanceof Number ttl) {+ request.put("authorizerResultTtlInSeconds", ttl);+ }+ if (authDef.get("enableSimpleResponses") != null) {+ request.put("enableSimpleResponses", authDef.get("enableSimpleResponses"));+ }+ Map<String, Object> jwtConfiguration = extensionAsMap(authDef, "jwtConfiguration");+ if (jwtConfiguration != null) {+ request.put("jwtConfiguration", normalisedJwtConfiguration(jwtConfiguration, schemeName));+ }++ if ("REQUEST".equals(authorizerType)) {+ Object ttl = request.get("authorizerResultTtlInSeconds");+ boolean cachingEnabled = ttl instanceof Number n && n.intValue() > 0;+ if (cachingEnabled && identitySource.isEmpty()) {+ throw new AwsException("BadRequestException",+ "REQUEST authorizer " + schemeName+ + " must specify identitySource when authorizer caching is enabled.", 400);+ }+ }++ specs.add(new AuthorizerSpec(schemeName,+ "JWT".equals(authorizerType) ? "JWT" : "CUSTOM", request));+ }+ return specs;+ }++ private Map<String, SchemeBinding> createAuthorizers(String region, String apiId, ImportPlan plan) {+ Map<String, SchemeBinding> bindings = new LinkedHashMap<>();+ for (AuthorizerSpec spec : plan.authorizerSpecs()) {+ if (spec.request() == null) {+ bindings.put(spec.schemeName(), new SchemeBinding(spec.authorizationType(), null));+ continue;+ }+ Authorizer authorizer = service.createAuthorizer(region, apiId, spec.request());+ bindings.put(spec.schemeName(),+ new SchemeBinding(spec.authorizationType(), authorizer.getAuthorizerId()));+ }+ return bindings;+ }++ /**+ * Coerces jwtConfiguration into the shape CreateAuthorizer expects, in the planning phase.+ * {@code audience} reaches the store as a {@code List<String>} and is cast as one, so a scalar+ * — which the extension is commonly written with — would otherwise throw a ClassCastException+ * during application, after ReimportApi had already dropped the previous definition.+ */+ private static Map<String, Object> normalisedJwtConfiguration(Map<String, Object> jwtConfiguration,+ String schemeName) {+ Map<String, Object> normalised = new LinkedHashMap<>(jwtConfiguration);+ Object audience = normalised.get("audience");+ if (audience instanceof String single) {+ normalised.put("audience", List.of(single));+ } else if (audience instanceof List<?> list) {+ List<String> values = new ArrayList<>();+ for (Object item : list) {+ if (item == null) {+ continue;+ }+ values.add(String.valueOf(item));+ }+ normalised.put("audience", values);+ } else if (audience != null) {+ throw new AwsException("BadRequestException",+ "jwtConfiguration.audience for security scheme " + schemeName+ + " must be a string or an array of strings", 400);+ }++ Object issuer = normalised.get("issuer");+ if (issuer != null && !(issuer instanceof String)) {+ throw new AwsException("BadRequestException",+ "jwtConfiguration.issuer for security scheme " + schemeName + " must be a string", 400);+ }+ return normalised;+ }++ /**+ * REQUEST authorizers carry identitySource on the extension (a comma-separated string or an+ * array); JWT authorizers derive it from where the security scheme says the token lives.+ */+ private static List<String> identitySource(Map<String, Object> authDef, SecurityScheme scheme,+ String authorizerType) {+ Object raw = authDef.get("identitySource");+ if (raw instanceof String s && !s.isBlank()) {+ List<String> sources = new ArrayList<>();+ for (String part : s.split(",")) {+ String trimmed = part.trim();+ if (!trimmed.isEmpty()) {+ sources.add(trimmed);+ }+ }+ return sources;+ }+ if (raw instanceof List<?> list) {+ List<String> sources = new ArrayList<>();+ for (Object item : list) {+ String value = stringValue(item);+ if (value != null && !value.isBlank()) {+ sources.add(value.trim());+ }+ }+ return sources;+ }+ if ("JWT".equals(authorizerType) && scheme.getName() != null) {+ String in = scheme.getIn() == null ? "header" : scheme.getIn().toString().toLowerCase(Locale.ROOT);+ return List.of("$request." + in + "." + scheme.getName());+ }+ return List.of();+ }++ private static SchemeBinding resolveSecurity(List<SecurityRequirement> security,+ Map<String, SchemeBinding> schemes) {+ if (security == null || security.isEmpty()) {+ return null;+ }+ for (SecurityRequirement requirement : security) {+ for (String schemeName : requirement.keySet()) {+ SchemeBinding binding = schemes.get(schemeName);+ if (binding != null) {+ return binding;+ }+ }+ }+ return null;+ }++ // ──────────────────────────── Integrations ────────────────────────────++ private static Map<String, Object> toIntegrationRequest(Map<String, Object> definition) {+ Map<String, Object> request = new HashMap<>();++ String type = stringValue(definition.get("type"));+ if (type != null) {+ request.put("integrationType", type.toUpperCase(Locale.ROOT));+ }+ putIfPresent(request, "integrationUri", stringValue(definition.get("uri")));+ putIfPresent(request, "integrationMethod", stringValue(definition.get("httpMethod")));+ putIfPresent(request, "connectionType", upper(stringValue(definition.get("connectionType"))));+ putIfPresent(request, "connectionId", stringValue(definition.get("connectionId")));+ putIfPresent(request, "templateSelectionExpression",+ stringValue(definition.get("templateSelectionExpression")));++ String payloadFormatVersion = stringValue(definition.get("payloadFormatVersion"));+ if (payloadFormatVersion != null) {+ request.put("payloadFormatVersion", payloadFormatVersion);+ }+ if (definition.get("timeoutInMillis") instanceof Number timeout) {+ request.put("timeoutInMillis", timeout);+ }++ copyStringMap(definition, request, "requestParameters");+ copyStringMap(definition, request, "requestTemplates");+ copyStringMap(definition, request, "responseTemplates");++ return request;+ }++ // ──────────────────────────── CORS ────────────────────────────++ private static Map<String, Object> corsConfiguration(OpenAPI openAPI) {+ Map<String, Object> cors = extensionAsMap(openAPI.getExtensions(), EXT_CORS);+ if (cors == null) {+ return null;+ }+ Map<String, Object> configuration = new HashMap<>();+ copyStringList(cors, configuration, "allowOrigins");+ copyStringList(cors, configuration, "allowMethods");+ copyStringList(cors, configuration, "allowHeaders");+ copyStringList(cors, configuration, "exposeHeaders");+ if (cors.get("maxAge") instanceof Number maxAge) {+ configuration.put("maxAge", maxAge);+ }+ if (cors.get("allowCredentials") != null) {+ configuration.put("allowCredentials", cors.get("allowCredentials"));+ }+ return configuration.isEmpty() ? null : configuration;+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private static String specTitle(OpenAPI openAPI, String fallback) {+ if (openAPI.getInfo() != null && openAPI.getInfo().getTitle() != null) {+ return openAPI.getInfo().getTitle();+ }+ return fallback;+ }++ private static String specDescription(OpenAPI openAPI) {+ return openAPI.getInfo() == null ? null : openAPI.getInfo().getDescription();+ }++ /** AWS carries the document's info.version through to the API's Version. */+ private static String specVersion(OpenAPI openAPI) {+ return openAPI.getInfo() == null ? null : openAPI.getInfo().getVersion();+ }++ @SuppressWarnings("unchecked")+ private static Map<String, Object> extensionAsMap(Map<String, Object> source, String key) {+ if (source == null) {+ return null;+ }+ Object value = source.get(key);+ return value instanceof Map<?, ?> ? (Map<String, Object>) value : null;+ }++ private static void copyStringMap(Map<String, Object> source, Map<String, Object> target, String key) {+ if (!(source.get(key) instanceof Map<?, ?> map) || map.isEmpty()) {+ return;+ }+ Map<String, String> copy = new LinkedHashMap<>();+ map.forEach((k, v) -> copy.put(String.valueOf(k), v == null ? null : String.valueOf(v)));+ target.put(key, copy);+ }++ private static void copyStringList(Map<String, Object> source, Map<String, Object> target, String key) {+ if (!(source.get(key) instanceof List<?> list) || list.isEmpty()) {+ return;+ }+ List<String> copy = new ArrayList<>();+ list.forEach(item -> copy.add(item == null ? null : String.valueOf(item)));+ target.put(key, copy);+ }++ private static void putIfPresent(Map<String, Object> request, String key, String value) {+ if (value != null && !value.isBlank()) {+ request.put(key, value);+ }+ }++ private static String stringValue(Object value) {+ return value == null ? null : String.valueOf(value);+ }++ private static String upper(String value) {+ return value == null ? null : value.toUpperCase(Locale.ROOT);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.javaindex 43eef52e73..b1358fd1cc 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java@@ -103,6 +103,7 @@ public class ApiGatewayV2Service {api.setRouteSelectionExpression(routeSelectionExpression);api.setDescription(description);api.setApiKeySelectionExpression(apiKeySelectionExpression);+ api.setVersion((String) request.get("version"));api.setDisableExecuteApiEndpoint(booleanValue(request.get("disableExecuteApiEndpoint")));if ("WEBSOCKET".equals(protocolType)) {@@ -131,6 +132,11 @@ public class ApiGatewayV2Service {.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404));}+ /** Persists an Api the caller already holds — used to attach OpenAPI import diagnostics. */+ public void putApi(String region, Api api) {+ apiStore.put(apiKey(region, api.getApiId()), api);+ }+/*** Mirrors ApiGatewayService#resolveRestApiRegion: unsigned data-plane requests carry no* region, so preferredRegion is whatever RegionResolver defaults to, which need not match@@ -207,6 +213,9 @@ public class ApiGatewayV2Service {if (request.containsKey("routeSelectionExpression") && request.get("routeSelectionExpression") != null) {api.setRouteSelectionExpression((String) request.get("routeSelectionExpression"));}+ if (request.containsKey("version") && request.get("version") != null) {+ api.setVersion((String) request.get("version"));+ }if (request.containsKey("apiKeySelectionExpression") && request.get("apiKeySelectionExpression") != null) {api.setApiKeySelectionExpression((String) request.get("apiKeySelectionExpression"));}@@ -257,6 +266,51 @@ public class ApiGatewayV2Service {return new Api.Cors(allowOrigins, allowMethods, allowHeaders, exposeHeaders, maxAge, allowCredentials);}+ // ──────────────────────────── Stage settings coercion ────────────────────────────++ private static Stage.AccessLogSettings toAccessLogSettings(Object raw) {+ if (!(raw instanceof Map<?, ?> m) || m.isEmpty()) {+ return null;+ }+ return new Stage.AccessLogSettings(+ stringOrNull(m.get("destinationArn")),+ stringOrNull(m.get("format")));+ }++ private static Stage.RouteSettings toRouteSettings(Object raw) {+ if (!(raw instanceof Map<?, ?> m) || m.isEmpty()) {+ return null;+ }+ return new Stage.RouteSettings(+ booleanOrNull(m.get("detailedMetricsEnabled")),+ booleanOrNull(m.get("dataTraceEnabled")),+ stringOrNull(m.get("loggingLevel")),+ m.get("throttlingBurstLimit") instanceof Number burst ? burst.intValue() : null,+ m.get("throttlingRateLimit") instanceof Number rate ? rate.doubleValue() : null);+ }++ private static Map<String, Stage.RouteSettings> toRouteSettingsMap(Object raw) {+ if (!(raw instanceof Map<?, ?> m) || m.isEmpty()) {+ return null;+ }+ Map<String, Stage.RouteSettings> settings = new java.util.LinkedHashMap<>();+ m.forEach((key, value) -> {+ Stage.RouteSettings parsed = toRouteSettings(value);+ if (parsed != null) {+ settings.put(String.valueOf(key), parsed);+ }+ });+ return settings.isEmpty() ? null : settings;+ }++ private static String stringOrNull(Object value) {+ return value == null ? null : String.valueOf(value);+ }++ private static Boolean booleanOrNull(Object value) {+ return value == null ? null : Boolean.parseBoolean(String.valueOf(value));+ }+// ──────────────────────────── Authorizer CRUD ────────────────────────────public Authorizer createAuthorizer(String region, String apiId, Map<String, Object> request) {@@ -701,6 +755,11 @@ public class ApiGatewayV2Service {stage.setTags(ReservedTags.stripApiGatewayReservedTags(tags));}+ stage.setDescription((String) request.get("description"));+ stage.setAccessLogSettings(toAccessLogSettings(request.get("accessLogSettings")));+ stage.setDefaultRouteSettings(toRouteSettings(request.get("defaultRouteSettings")));+ stage.setRouteSettings(toRouteSettingsMap(request.get("routeSettings")));+stageStore.put(stageKey(region, apiId, stage.getStageName()), stage);LOG.infov("Created stage: {0} for API {1}", stage.getStageName(), apiId);return stage;@@ -737,6 +796,18 @@ public class ApiGatewayV2Service {Map<String, String> stageVariables = (Map<String, String>) request.get("stageVariables");stage.setStageVariables(stageVariables);}+ if (request.containsKey("description") && request.get("description") != null) {+ stage.setDescription((String) request.get("description"));+ }+ if (request.containsKey("accessLogSettings") && request.get("accessLogSettings") != null) {+ stage.setAccessLogSettings(toAccessLogSettings(request.get("accessLogSettings")));+ }+ if (request.containsKey("defaultRouteSettings") && request.get("defaultRouteSettings") != null) {+ stage.setDefaultRouteSettings(toRouteSettings(request.get("defaultRouteSettings")));+ }+ if (request.containsKey("routeSettings") && request.get("routeSettings") != null) {+ stage.setRouteSettings(toRouteSettingsMap(request.get("routeSettings")));+ }stage.setLastUpdatedDate(System.currentTimeMillis());stageStore.put(stageKey(region, apiId, stageName), stage);@@ -1031,13 +1102,22 @@ public class ApiGatewayV2Service {// ──────────────────────────── Standalone Tagging ────────────────────────────+ /** A taggable v2 resource: an API, or a stage within one. */+ private record TaggedResource(String region, String apiId, String stageName) {+ boolean isStage() {+ return stageName != null;+ }+ }+/**- * Parses an API Gateway v2 resource ARN and returns a two-element array- * [region, apiId]. Throws BadRequestException if the ARN is malformed.+ * Parses an API Gateway v2 resource ARN.*- * Expected format: arn:aws:apigateway:{region}::/apis/{apiId}+ * <p>Accepted forms: {@code arn:aws:apigateway:{region}::/apis/{apiId}} and+ * {@code arn:aws:apigateway:{region}::/apis/{apiId}/stages/{stageName}}. Matching on the+ * trailing segment alone would read a stage ARN's stage name as the API id, which surfaces as+ * a misleading "Invalid API id specified" on TagResource.*/- private String[] parseArn(String resourceArn) {+ private TaggedResource parseArn(String resourceArn) {if (resourceArn == null || resourceArn.isBlank()) {throw new AwsException("BadRequestException", "ResourceArn must not be blank", 400);}@@ -1049,48 +1129,65 @@ public class ApiGatewayV2Service {"Invalid ResourceArn format: " + resourceArn, 400);}String region = arn.region();- String resource = arn.resource(); // e.g. "/apis/abc1234567"- int lastSlash = resource.lastIndexOf('/');- if (lastSlash < 0 || lastSlash == resource.length() - 1) {- throw new AwsException("BadRequestException",- "Cannot extract apiId from ResourceArn: " + resourceArn, 400);+ // e.g. "/apis/abc1234567" or "/apis/abc1234567/stages/$default"+ String[] segments = arn.resource().replaceFirst("^/", "").split("/");+ if (segments.length >= 4 && "apis".equals(segments[0]) && "stages".equals(segments[2])+ && !segments[1].isEmpty() && !segments[3].isEmpty()) {+ return new TaggedResource(region, segments[1], segments[3]);}- String apiId = resource.substring(lastSlash + 1);- return new String[]{region, apiId};+ if (segments.length >= 2 && "apis".equals(segments[0]) && !segments[1].isEmpty()) {+ return new TaggedResource(region, segments[1], null);+ }+ throw new AwsException("BadRequestException",+ "Cannot extract apiId from ResourceArn: " + resourceArn, 400);}public void tagResource(String resourceArn, Map<String, String> tags) {ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);- String[] parsed = parseArn(resourceArn);- String region = parsed[0];- String apiId = parsed[1];- Api api = getApi(region, apiId);+ TaggedResource target = parseArn(resourceArn);+ if (target.isStage()) {+ Stage stage = getStage(target.region(), target.apiId(), target.stageName());+ if (tags != null && !tags.isEmpty()) {+ if (stage.getTags() == null) {+ stage.setTags(new java.util.HashMap<>());+ }+ stage.getTags().putAll(tags);+ }+ stageStore.put(stageKey(target.region(), target.apiId(), target.stageName()), stage);+ return;+ }+ Api api = getApi(target.region(), target.apiId());if (tags != null && !tags.isEmpty()) {if (api.getTags() == null) {api.setTags(new java.util.HashMap<>());}api.getTags().putAll(tags);}- apiStore.put(apiKey(region, apiId), api);+ apiStore.put(apiKey(target.region(), target.apiId()), api);}public void untagResource(String resourceArn, List<String> tagKeys) {- String[] parsed = parseArn(resourceArn);- String region = parsed[0];- String apiId = parsed[1];- Api api = getApi(region, apiId);+ TaggedResource target = parseArn(resourceArn);+ if (target.isStage()) {+ Stage stage = getStage(target.region(), target.apiId(), target.stageName());+ if (tagKeys != null && stage.getTags() != null) {+ tagKeys.forEach(k -> stage.getTags().remove(k));+ }+ stageStore.put(stageKey(target.region(), target.apiId(), target.stageName()), stage);+ return;+ }+ Api api = getApi(target.region(), target.apiId());if (tagKeys != null && api.getTags() != null) {tagKeys.forEach(k -> api.getTags().remove(k));}- apiStore.put(apiKey(region, apiId), api);+ apiStore.put(apiKey(target.region(), target.apiId()), api);}public Map<String, String> getTags(String resourceArn) {- String[] parsed = parseArn(resourceArn);- String region = parsed[0];- String apiId = parsed[1];- Api api = getApi(region, apiId);- Map<String, String> tags = api.getTags();+ TaggedResource target = parseArn(resourceArn);+ Map<String, String> tags = target.isStage()+ ? getStage(target.region(), target.apiId(), target.stageName()).getTags()+ : getApi(target.region(), target.apiId()).getTags();return (tags != null) ? new java.util.HashMap<>(tags) : java.util.Collections.emptyMap();}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Api.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Api.javaindex 35ade0c40c..8763f8d8e2 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Api.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Api.java@@ -21,6 +21,11 @@ public class Api {private String apiKeySelectionExpression;private boolean disableExecuteApiEndpoint;private Cors corsConfiguration;+ private String version;+ /** Warnings reported when failOnWarnings is off during an OpenAPI import. */+ private List<String> warnings;+ /** Definition properties that the import ignored. */+ private List<String> importInfo;public Api() {}@@ -59,6 +64,16 @@ public class Api {public Cors getCorsConfiguration() { return corsConfiguration; }public void setCorsConfiguration(Cors corsConfiguration) { this.corsConfiguration = corsConfiguration; }+ /** Caller-supplied API version string, e.g. "1.0.0". Opaque to AWS. */+ public String getVersion() { return version; }+ public void setVersion(String version) { this.version = version; }++ public List<String> getWarnings() { return warnings; }+ public void setWarnings(List<String> warnings) { this.warnings = warnings; }++ public List<String> getImportInfo() { return importInfo; }+ public void setImportInfo(List<String> importInfo) { this.importInfo = importInfo; }+@RegisterForReflectionpublic record Cors(List<String> allowOrigins,diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Stage.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Stage.javaindex d7e86155e1..81c7269045 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Stage.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Stage.java@@ -16,6 +16,11 @@ public class Stage {private long lastUpdatedDate;private Map<String, String> stageVariables;private Map<String, String> tags = new HashMap<>();+ private String description;+ private AccessLogSettings accessLogSettings;+ private RouteSettings defaultRouteSettings;+ /** Per-route overrides, keyed by route key (e.g. "POST /orders"). */+ private Map<String, RouteSettings> routeSettings;public Stage() {}@@ -39,4 +44,36 @@ public class Stage {public Map<String, String> getTags() { return tags; }public void setTags(Map<String, String> tags) { this.tags = tags; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }+++ public AccessLogSettings getAccessLogSettings() { return accessLogSettings; }+ public void setAccessLogSettings(AccessLogSettings accessLogSettings) { this.accessLogSettings = accessLogSettings; }++ public RouteSettings getDefaultRouteSettings() { return defaultRouteSettings; }+ public void setDefaultRouteSettings(RouteSettings defaultRouteSettings) { this.defaultRouteSettings = defaultRouteSettings; }++ public Map<String, RouteSettings> getRouteSettings() { return routeSettings; }+ public void setRouteSettings(Map<String, RouteSettings> routeSettings) { this.routeSettings = routeSettings; }++ /** CloudWatch Logs destination and format for stage access logging. */+ @RegisterForReflection+ @JsonIgnoreProperties(ignoreUnknown = true)+ public record AccessLogSettings(String destinationArn, String format) {}++ /**+ * Throttling and logging knobs, used both as a stage's defaults and as a per-route override.+ * All fields are boxed: AWS omits unset ones rather than defaulting them, and Terraform treats+ * an absent value differently from an explicit zero.+ */+ @RegisterForReflection+ @JsonIgnoreProperties(ignoreUnknown = true)+ public record RouteSettings(+ Boolean detailedMetricsEnabled,+ Boolean dataTraceEnabled,+ String loggingLevel,+ Integer throttlingBurstLimit,+ Double throttlingRateLimit) {}}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2OpenApiImportTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2OpenApiImportTest.javanew file mode 100644index 0000000000..62382b5cdc--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2OpenApiImportTest.java@@ -0,0 +1,659 @@+package io.github.hectorvent.floci.services.apigatewayv2;++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.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Integration tests for HTTP API (v2) OpenAPI import.+ * Covers ImportApi (PUT /v2/apis) and ReimportApi (PUT /v2/apis/{apiId}).+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class ApiGatewayV2OpenApiImportTest {++ private static final ObjectMapper mapper = new ObjectMapper();++ private static final String SPEC_WITH_AUTHORIZER = """+ {+ "openapi": "3.0.1",+ "info": {"title": "ImportedHttpApi", "description": "imported", "version": "1.0"},+ "security": [{"LambdaAuth": []}],+ "components": {+ "securitySchemes": {+ "LambdaAuth": {+ "type": "apiKey",+ "name": "Authorization",+ "in": "header",+ "x-amazon-apigateway-authorizer": {+ "type": "request",+ "authorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:auth/invocations",+ "authorizerPayloadFormatVersion": "2.0",+ "enableSimpleResponses": true,+ "identitySource": "$request.header.Authorization,$context.routeKey",+ "authorizerResultTtlInSeconds": 300+ }+ }+ }+ },+ "paths": {+ "/api/items": {+ "get": {+ "x-amazon-apigateway-integration": {+ "type": "aws_proxy",+ "httpMethod": "POST",+ "uri": "arn:aws:lambda:us-east-1:000000000000:function:items",+ "payloadFormatVersion": "2.0",+ "timeoutInMillis": 30000+ }+ }+ },+ "/api/public": {+ "get": {+ "security": [],+ "x-amazon-apigateway-integration": {+ "type": "aws_proxy",+ "httpMethod": "POST",+ "uri": "arn:aws:lambda:us-east-1:000000000000:function:public",+ "payloadFormatVersion": "2.0"+ }+ }+ }+ }+ }+ """;++ /** ImportApi/ReimportApi take the document inside a restJson1 envelope. */+ private static String envelope(String spec) throws Exception {+ return mapper.writeValueAsString(mapper.createObjectNode().put("body", spec));+ }++ private static JsonNode get(String path) throws Exception {+ return mapper.readTree(given().when().get(path).then().statusCode(200).extract().asString());+ }++ private static JsonNode findRoute(JsonNode routes, String routeKey) {+ for (JsonNode route : routes.get("items")) {+ if (routeKey.equals(route.path("routeKey").asText())) {+ return route;+ }+ }+ return null;+ }++ @Test+ @Order(1)+ void importApi_createsRoutesIntegrationsAndAuthorizer() throws Exception {+ String response = given()+ .contentType(ContentType.JSON)+ .body(envelope(SPEC_WITH_AUTHORIZER))+ .when().put("/v2/apis")+ .then().statusCode(201)+ .extract().asString();++ JsonNode api = mapper.readTree(response);+ String apiId = api.get("apiId").asText();+ assertEquals("ImportedHttpApi", api.get("name").asText());+ assertEquals("HTTP", api.get("protocolType").asText());++ JsonNode authorizers = get("/v2/apis/" + apiId + "/authorizers");+ assertEquals(1, authorizers.get("items").size());+ JsonNode authorizer = authorizers.get("items").get(0);+ assertEquals("LambdaAuth", authorizer.get("name").asText());+ assertEquals("REQUEST", authorizer.get("authorizerType").asText());+ assertEquals("2.0", authorizer.get("authorizerPayloadFormatVersion").asText());+ assertTrue(authorizer.get("enableSimpleResponses").asBoolean());+ assertEquals(300, authorizer.get("authorizerResultTtlInSeconds").asInt());+ // The comma-separated extension value becomes the AWS list form.+ assertEquals(2, authorizer.get("identitySource").size());+ assertEquals("$request.header.Authorization", authorizer.get("identitySource").get(0).asText());+ assertEquals("$context.routeKey", authorizer.get("identitySource").get(1).asText());++ JsonNode integrations = get("/v2/apis/" + apiId + "/integrations");+ assertEquals(2, integrations.get("items").size());+ JsonNode integration = integrations.get("items").get(0);+ assertEquals("AWS_PROXY", integration.get("integrationType").asText());+ assertEquals("POST", integration.get("integrationMethod").asText());+ assertEquals("2.0", integration.get("payloadFormatVersion").asText());++ JsonNode routes = get("/v2/apis/" + apiId + "/routes");+ assertEquals(2, routes.get("items").size());++ JsonNode secured = findRoute(routes, "GET /api/items");+ assertNotNull(secured);+ assertEquals("CUSTOM", secured.get("authorizationType").asText());+ assertEquals(authorizer.get("authorizerId").asText(), secured.get("authorizerId").asText());+ assertTrue(secured.get("target").asText().startsWith("integrations/"));++ // security: [] on the operation overrides the document-level requirement.+ JsonNode publicRoute = findRoute(routes, "GET /api/public");+ assertNotNull(publicRoute);+ assertEquals("NONE", publicRoute.get("authorizationType").asText());+ assertTrue(publicRoute.path("authorizerId").isMissingNode()+ || publicRoute.get("authorizerId").isNull());+ }++ @Test+ @Order(2)+ void reimportApi_replacesDefinitionAndKeepsResourceLevelCors() throws Exception {+ // CreateApi carries CORS, exactly as Terraform's cors_configuration block does.+ String created = given()+ .contentType(ContentType.JSON)+ .body("""+ {+ "name": "ReimportTarget",+ "protocolType": "HTTP",+ "corsConfiguration": {"allowOrigins": ["https://example.com"], "allowMethods": ["GET"]}+ }+ """)+ .when().post("/v2/apis")+ .then().statusCode(201)+ .extract().asString();+ String apiId = mapper.readTree(created).get("apiId").asText();++ // A route that the spec does not declare must not survive the reimport.+ given().contentType(ContentType.JSON)+ .body("{\"routeKey\": \"GET /stale\"}")+ .when().post("/v2/apis/" + apiId + "/routes")+ .then().statusCode(201);++ given().contentType(ContentType.JSON)+ .body(envelope(SPEC_WITH_AUTHORIZER))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(201);++ JsonNode routes = get("/v2/apis/" + apiId + "/routes");+ assertEquals(2, routes.get("items").size());+ assertNull(findRoute(routes, "GET /stale"));+ assertNotNull(findRoute(routes, "GET /api/items"));++ JsonNode api = get("/v2/apis/" + apiId);+ assertEquals("ImportedHttpApi", api.get("name").asText());+ // The spec has no x-amazon-apigateway-cors, so the API keeps the CORS it was created with.+ assertEquals("https://example.com",+ api.get("corsConfiguration").get("allowOrigins").get(0).asText());+ }++ @Test+ @Order(3)+ void reimportApi_isIdempotent() throws Exception {+ String created = given()+ .contentType(ContentType.JSON)+ .body("{\"name\": \"IdempotentTarget\", \"protocolType\": \"HTTP\"}")+ .when().post("/v2/apis")+ .then().statusCode(201)+ .extract().asString();+ String apiId = mapper.readTree(created).get("apiId").asText();++ for (int i = 0; i < 2; i++) {+ given().contentType(ContentType.JSON)+ .body(envelope(SPEC_WITH_AUTHORIZER))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(201);+ }++ assertEquals(2, get("/v2/apis/" + apiId + "/routes").get("items").size());+ assertEquals(2, get("/v2/apis/" + apiId + "/integrations").get("items").size());+ assertEquals(1, get("/v2/apis/" + apiId + "/authorizers").get("items").size());+ }++ @Test+ @Order(4)+ void importApi_supportsYamlAndAnyMethod() throws Exception {+ String yamlSpec = """+ openapi: 3.0.1+ info:+ title: YamlApi+ version: "1.0"+ paths:+ /proxy:+ x-amazon-apigateway-any-method:+ x-amazon-apigateway-integration:+ type: http_proxy+ httpMethod: ANY+ uri: https://example.com+ payloadFormatVersion: "1.0"+ """;++ String response = given()+ .contentType(ContentType.JSON)+ .body(envelope(yamlSpec))+ .when().put("/v2/apis")+ .then().statusCode(201)+ .extract().asString();+ String apiId = mapper.readTree(response).get("apiId").asText();++ JsonNode routes = get("/v2/apis/" + apiId + "/routes");+ assertEquals(1, routes.get("items").size());+ assertNotNull(findRoute(routes, "ANY /proxy"));++ JsonNode integrations = get("/v2/apis/" + apiId + "/integrations");+ assertEquals("HTTP_PROXY", integrations.get("items").get(0).get("integrationType").asText());+ }++ @Test+ @Order(5)+ void reimportApi_unknownApiReturns404() throws Exception {+ given().contentType(ContentType.JSON)+ .body(envelope(SPEC_WITH_AUTHORIZER))+ .when().put("/v2/apis/doesnotexist")+ .then().statusCode(404);+ }++ @Test+ @Order(6)+ void importApi_invalidSpecReturns400() {+ given().contentType(ContentType.JSON)+ .body("{\"body\": \"this is not an openapi document\"}")+ .when().put("/v2/apis")+ .then().statusCode(400);+ }++ // ──────────────────────────── basepath ────────────────────────────++ /** A base path declared the OpenAPI 3 way: a "basePath" server variable. */+ private static final String SPEC_WITH_BASE_PATH = """+ {+ "openapi": "3.0.1",+ "info": {"title": "BasePathApi", "version": "1.0"},+ "servers": [{+ "url": "https://example.com/{basePath}",+ "variables": {"basePath": {"default": "/a/b/c"}}+ }],+ "paths": {+ "/e": {"get": {"x-amazon-apigateway-integration": {+ "type": "http_proxy", "httpMethod": "GET", "uri": "https://example.com/e",+ "payloadFormatVersion": "1.0"}}}+ }+ }+ """;++ private static String importWithBasePath(String basepath) throws Exception {+ String response = given()+ .contentType(ContentType.JSON)+ .queryParam("basepath", basepath)+ .body(envelope(SPEC_WITH_BASE_PATH))+ .when().put("/v2/apis")+ .then().statusCode(201)+ .extract().asString();+ String apiId = mapper.readTree(response).get("apiId").asText();+ return get("/v2/apis/" + apiId + "/routes").get("items").get(0).get("routeKey").asText();+ }++ @Test+ @Order(7)+ void basePathIgnoreIsTheDefault() throws Exception {+ assertEquals("GET /e", importWithBasePath("ignore"));++ // Omitting the parameter entirely must behave the same as ignore.+ String response = given().contentType(ContentType.JSON)+ .body(envelope(SPEC_WITH_BASE_PATH))+ .when().put("/v2/apis")+ .then().statusCode(201).extract().asString();+ String apiId = mapper.readTree(response).get("apiId").asText();+ assertEquals("GET /e", get("/v2/apis/" + apiId + "/routes").get("items").get(0).get("routeKey").asText());+ }++ @Test+ @Order(8)+ void basePathPrependAndSplit() throws Exception {+ assertEquals("GET /a/b/c/e", importWithBasePath("prepend"));+ // split drops the first segment of the base path.+ assertEquals("GET /b/c/e", importWithBasePath("split"));+ }++ @Test+ @Order(9)+ void basePathFallsBackToTheServerUrlPath() throws Exception {+ String spec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "ServerUrlApi", "version": "1.0"},+ "servers": [{"url": "https://example.com/v1/api"}],+ "paths": {"/e": {"get": {}}}+ }+ """;+ String response = given().contentType(ContentType.JSON)+ .queryParam("basepath", "prepend")+ .body(envelope(spec))+ .when().put("/v2/apis")+ .then().statusCode(201).extract().asString();+ String apiId = mapper.readTree(response).get("apiId").asText();+ assertEquals("GET /v1/api/e",+ get("/v2/apis/" + apiId + "/routes").get("items").get(0).get("routeKey").asText());+ }++ @Test+ @Order(10)+ void invalidBasePathIsRejected() throws Exception {+ given().contentType(ContentType.JSON)+ .queryParam("basepath", "sideways")+ .body(envelope(SPEC_WITH_AUTHORIZER))+ .when().put("/v2/apis")+ .then().statusCode(400);+ }++ // ──────────────────────────── failOnWarnings / importInfo ────────────────────────────++ @Test+ @Order(11)+ void importInfoReportsOperationsWithoutAnIntegration() throws Exception {+ String spec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "NoIntegrationApi", "version": "1.0"},+ "paths": {"/bare": {"get": {}}}+ }+ """;+ String response = given().contentType(ContentType.JSON)+ .body(envelope(spec))+ .when().put("/v2/apis")+ .then().statusCode(201)+ .extract().asString();++ JsonNode api = mapper.readTree(response);+ JsonNode importInfo = get("/v2/apis/" + api.get("apiId").asText()).get("importInfo");+ assertNotNull(importInfo);+ assertTrue(importInfo.toString().contains("GET /bare"));+ }++ @Test+ @Order(12)+ void failOnWarningsRollsBackWithoutMutatingAnExistingApi() throws Exception {+ // A $ref to a schema that does not exist makes swagger-parser emit a message.+ String warnSpec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "WarnApi", "version": "1.0"},+ "paths": {"/w": {"get": {"responses": {"200": {"description": "ok",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Missing"}}}}}}}}+ }+ """;++ String created = given().contentType(ContentType.JSON)+ .body("{\"name\": \"failOnWarningsTarget\", \"protocolType\": \"HTTP\"}")+ .when().post("/v2/apis")+ .then().statusCode(201).extract().asString();+ String apiId = mapper.readTree(created).get("apiId").asText();++ given().contentType(ContentType.JSON)+ .body(envelope(SPEC_WITH_AUTHORIZER))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(201);+ assertEquals(2, get("/v2/apis/" + apiId + "/routes").get("items").size());++ given().contentType(ContentType.JSON)+ .queryParam("failOnWarnings", "true")+ .body(envelope(warnSpec))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(400);++ // The rejected reimport must not have deleted the routes it was going to replace.+ JsonNode routes = get("/v2/apis/" + apiId + "/routes");+ assertEquals(2, routes.get("items").size());+ assertNotNull(findRoute(routes, "GET /api/items"));++ // Without the flag the same document imports, recording the warning instead.+ given().contentType(ContentType.JSON)+ .body(envelope(warnSpec))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(201);+ assertNotNull(get("/v2/apis/" + apiId).get("warnings"));+ }++ @Test+ @Order(13)+ void rejectedAuthorizerLeavesThePreviousDefinitionIntact() throws Exception {+ // Syntactically valid, but HTTP APIs have no such authorizer type. The rejection has to+ // happen before the existing routes are deleted.+ String badAuthorizerSpec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "BadAuthApi", "version": "1.0"},+ "security": [{"Tokenish": []}],+ "components": {"securitySchemes": {"Tokenish": {+ "type": "apiKey", "name": "Authorization", "in": "header",+ "x-amazon-apigateway-authorizer": {"type": "token", "authorizerUri": "arn:aws:lambda:x"}+ }}},+ "paths": {"/x": {"get": {}}}+ }+ """;++ String created = given().contentType(ContentType.JSON)+ .body("{\"name\": \"badAuthorizerTarget\", \"protocolType\": \"HTTP\"}")+ .when().post("/v2/apis")+ .then().statusCode(201).extract().asString();+ String apiId = mapper.readTree(created).get("apiId").asText();++ given().contentType(ContentType.JSON)+ .body(envelope(SPEC_WITH_AUTHORIZER))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(201);+ assertEquals(2, get("/v2/apis/" + apiId + "/routes").get("items").size());+ assertEquals(1, get("/v2/apis/" + apiId + "/authorizers").get("items").size());++ given().contentType(ContentType.JSON)+ .body(envelope(badAuthorizerSpec))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(400);++ JsonNode routes = get("/v2/apis/" + apiId + "/routes");+ assertEquals(2, routes.get("items").size());+ assertNotNull(findRoute(routes, "GET /api/items"));+ assertEquals(2, get("/v2/apis/" + apiId + "/integrations").get("items").size());+ assertEquals(1, get("/v2/apis/" + apiId + "/authorizers").get("items").size());+ }++ @Test+ @Order(14)+ void securityThatResolvesToNoAuthorizerIsWarnedAbout() throws Exception {+ // A plain bearer scheme carries no AWS binding, so the route can only be imported as NONE.+ // Silently doing so would make a document that declares security produce a public route.+ String spec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "UnboundSecurityApi", "version": "1.0"},+ "components": {"securitySchemes": {"BearerAuth": {"type": "http", "scheme": "bearer"}}},+ "paths": {"/secret": {"get": {"security": [{"BearerAuth": []}]}}}+ }+ """;++ String response = given().contentType(ContentType.JSON)+ .body(envelope(spec))+ .when().put("/v2/apis")+ .then().statusCode(201)+ .extract().asString();+ String apiId = mapper.readTree(response).get("apiId").asText();++ JsonNode warnings = get("/v2/apis/" + apiId).get("warnings");+ assertNotNull(warnings);+ assertTrue(warnings.toString().contains("GET /secret"));+ assertTrue(warnings.toString().contains("BearerAuth"));++ JsonNode route = findRoute(get("/v2/apis/" + apiId + "/routes"), "GET /secret");+ assertNotNull(route);+ assertEquals("NONE", route.get("authorizationType").asText());++ // failOnWarnings turns that same document into a rejection.+ given().contentType(ContentType.JSON)+ .queryParam("failOnWarnings", "true")+ .body(envelope(spec))+ .when().put("/v2/apis")+ .then().statusCode(400);+ }++ @Test+ @Order(15)+ void anyMethodSecurityIsCheckedToo() throws Exception {+ // x-amazon-apigateway-any-method is not part of readOperationsMap(), so a diagnostic pass+ // that walks only that map leaves ANY routes unexamined.+ String spec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "AnyMethodSecurityApi", "version": "1.0"},+ "components": {"securitySchemes": {"BearerAuth": {"type": "http", "scheme": "bearer"}}},+ "paths": {"/proxy": {"x-amazon-apigateway-any-method": {+ "security": [{"BearerAuth": []}],+ "x-amazon-apigateway-integration": {+ "type": "http_proxy", "httpMethod": "ANY", "uri": "https://example.com",+ "payloadFormatVersion": "1.0"}+ }}}+ }+ """;++ String response = given().contentType(ContentType.JSON)+ .body(envelope(spec))+ .when().put("/v2/apis")+ .then().statusCode(201)+ .extract().asString();+ String apiId = mapper.readTree(response).get("apiId").asText();++ JsonNode warnings = get("/v2/apis/" + apiId).get("warnings");+ assertNotNull(warnings, "ANY-method security must be examined like any other operation");+ assertTrue(warnings.toString().contains("ANY /proxy"));++ assertNotNull(findRoute(get("/v2/apis/" + apiId + "/routes"), "ANY /proxy"));++ given().contentType(ContentType.JSON)+ .queryParam("failOnWarnings", "true")+ .body(envelope(spec))+ .when().put("/v2/apis")+ .then().statusCode(400);+ }++ @Test+ @Order(16)+ void compoundSecurityRequirementIsWarnedAbout() throws Exception {+ // Two schemes inside one requirement is AND. A route holds one authorizer, so the second+ // cannot be enforced — that has to be visible rather than silently dropped.+ String spec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "CompoundSecurityApi", "version": "1.0"},+ "components": {"securitySchemes": {+ "LambdaAuth": {+ "type": "apiKey", "name": "Authorization", "in": "header",+ "x-amazon-apigateway-authorizer": {+ "type": "request",+ "authorizerUri": "arn:aws:lambda:us-east-1:000000000000:function:auth",+ "authorizerPayloadFormatVersion": "2.0",+ "identitySource": "$request.header.Authorization"+ }+ },+ "ExtraKey": {"type": "apiKey", "name": "X-Extra", "in": "header"}+ }},+ "paths": {"/both": {"get": {"security": [{"LambdaAuth": [], "ExtraKey": []}]}}}+ }+ """;++ String response = given().contentType(ContentType.JSON)+ .body(envelope(spec))+ .when().put("/v2/apis")+ .then().statusCode(201)+ .extract().asString();+ String apiId = mapper.readTree(response).get("apiId").asText();++ String warnings = get("/v2/apis/" + apiId).get("warnings").toString();+ assertTrue(warnings.contains("GET /both"), warnings);+ assertTrue(warnings.contains("ExtraKey"), warnings);++ // The resolvable half is still enforced.+ JsonNode route = findRoute(get("/v2/apis/" + apiId + "/routes"), "GET /both");+ assertEquals("CUSTOM", route.get("authorizationType").asText());+ }++ @Test+ @Order(17)+ void sigv4ImportsAsAwsIamAndSaysItIsNotEnforced() throws Exception {+ // The route records AWS_IAM because that is what AWS records, but this emulator's HTTP API+ // dispatch only enforces JWT and CUSTOM, so the document's guarantee does not hold locally.+ String spec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "SigV4Api", "version": "1.0"},+ "components": {"securitySchemes": {"sigv4": {+ "type": "http", "scheme": "aws.v4"+ }}},+ "paths": {"/signed": {"get": {"security": [{"sigv4": []}]}}}+ }+ """;++ String response = given().contentType(ContentType.JSON)+ .body(envelope(spec))+ .when().put("/v2/apis")+ .then().statusCode(201)+ .extract().asString();+ String apiId = mapper.readTree(response).get("apiId").asText();++ JsonNode route = findRoute(get("/v2/apis/" + apiId + "/routes"), "GET /signed");+ assertNotNull(route);+ assertEquals("AWS_IAM", route.get("authorizationType").asText());++ String warnings = get("/v2/apis/" + apiId).get("warnings").toString();+ assertTrue(warnings.contains("GET /signed"), warnings);+ assertTrue(warnings.contains("does not enforce"), warnings);+ }++ @Test+ @Order(18)+ void scalarJwtAudienceIsAcceptedAndDoesNotDestroyThePreviousDefinition() throws Exception {+ // audience is stored as a List<String> and cast as one, so a scalar has to be coerced+ // during planning — otherwise the cast throws after ReimportApi has already deleted.+ String scalarAudienceSpec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "ScalarAudienceApi", "version": "1.0"},+ "security": [{"Jwt": []}],+ "components": {"securitySchemes": {"Jwt": {+ "type": "oauth2",+ "x-amazon-apigateway-authorizer": {+ "type": "jwt",+ "jwtConfiguration": {"issuer": "https://issuer.example.com", "audience": "single-aud"},+ "identitySource": "$request.header.Authorization"+ }+ }}},+ "paths": {"/j": {"get": {}}}+ }+ """;++ String created = given().contentType(ContentType.JSON)+ .body("{\"name\": \"scalarAudienceTarget\", \"protocolType\": \"HTTP\"}")+ .when().post("/v2/apis")+ .then().statusCode(201).extract().asString();+ String apiId = mapper.readTree(created).get("apiId").asText();++ given().contentType(ContentType.JSON)+ .body(envelope(SPEC_WITH_AUTHORIZER))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(201);+ assertEquals(2, get("/v2/apis/" + apiId + "/routes").get("items").size());++ given().contentType(ContentType.JSON)+ .body(envelope(scalarAudienceSpec))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(201);++ JsonNode authorizer = get("/v2/apis/" + apiId + "/authorizers").get("items").get(0);+ assertEquals("JWT", authorizer.get("authorizerType").asText());+ assertEquals("single-aud", authorizer.get("jwtConfiguration").get("audience").get(0).asText());++ // A shape neither string nor array is refused, with the previous definition kept.+ String badAudience = scalarAudienceSpec.replace("\"single-aud\"", "{\"nope\": 1}");+ given().contentType(ContentType.JSON)+ .body(envelope(badAudience))+ .when().put("/v2/apis/" + apiId)+ .then().statusCode(400);+ assertNotNull(findRoute(get("/v2/apis/" + apiId + "/routes"), "GET /j"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2StageSettingsTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2StageSettingsTest.javanew file mode 100644index 0000000000..eb7cb8eaed--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2StageSettingsTest.java@@ -0,0 +1,125 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.notNullValue;++/**+ * Stage access logging, throttling defaults and per-route overrides, plus the API's version.+ *+ * <p>These are all write-accepted/read-dropped attributes: Terraform sends them on create and+ * re-proposes them on every subsequent plan when a read does not echo them back.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class ApiGatewayV2StageSettingsTest {++ private static final ObjectMapper mapper = new ObjectMapper();+ private static String apiId;++ @Test+ @Order(1)+ void createApiWithVersion() {+ apiId = given()+ .contentType(ContentType.JSON)+ .body("{\"name\":\"stage-settings-api\",\"protocolType\":\"HTTP\",\"version\":\"1.0.0\"}")+ .when().post("/v2/apis")+ .then().statusCode(201)+ .body("version", equalTo("1.0.0"))+ .body("apiId", notNullValue())+ .extract().path("apiId");++ given().when().get("/v2/apis/" + apiId)+ .then().statusCode(200)+ .body("version", equalTo("1.0.0"));+ }++ @Test+ @Order(2)+ void updateApiVersion() {+ given().contentType(ContentType.JSON)+ .body("{\"version\":\"2.1.0\"}")+ .when().patch("/v2/apis/" + apiId)+ .then().statusCode(200)+ .body("version", equalTo("2.1.0"));++ given().when().get("/v2/apis/" + apiId)+ .then().statusCode(200)+ .body("version", equalTo("2.1.0"));+ }++ @Test+ @Order(3)+ void createStageWithAccessLogAndRouteSettings() throws Exception {+ String format = mapper.writeValueAsString(mapper.createObjectNode()+ .put("requestId", "$context.requestId")+ .put("status", "$context.status"));++ String body = mapper.writeValueAsString(mapper.createObjectNode()+ .put("stageName", "$default")+ .put("autoDeploy", true)+ .set("accessLogSettings", mapper.createObjectNode()+ .put("destinationArn", "arn:aws:logs:us-east-1:000000000000:log-group:/aws/apigatewayv2/test")+ .put("format", format)));++ given().contentType(ContentType.JSON).body(body)+ .when().post("/v2/apis/" + apiId + "/stages")+ .then().statusCode(201)+ .body("accessLogSettings.destinationArn",+ equalTo("arn:aws:logs:us-east-1:000000000000:log-group:/aws/apigatewayv2/test"))+ .body("accessLogSettings.format", equalTo(format));++ given().when().get("/v2/apis/" + apiId + "/stages/$default")+ .then().statusCode(200)+ .body("accessLogSettings.format", equalTo(format));+ }++ @Test+ @Order(4)+ void updateStageDefaultAndPerRouteSettings() {+ given().contentType(ContentType.JSON)+ .body("""+ {+ "defaultRouteSettings": {+ "throttlingRateLimit": 300,+ "throttlingBurstLimit": 600,+ "dataTraceEnabled": false+ },+ "routeSettings": {+ "POST /api/chatbot": {"throttlingRateLimit": 10, "throttlingBurstLimit": 20}+ }+ }+ """)+ .when().patch("/v2/apis/" + apiId + "/stages/$default")+ .then().statusCode(200);++ given().when().get("/v2/apis/" + apiId + "/stages/$default")+ .then().statusCode(200)+ .body("defaultRouteSettings.throttlingRateLimit", equalTo(300.0f))+ .body("defaultRouteSettings.throttlingBurstLimit", equalTo(600))+ .body("defaultRouteSettings.dataTraceEnabled", equalTo(false))+ .body("routeSettings.'POST /api/chatbot'.throttlingRateLimit", equalTo(10.0f))+ .body("routeSettings.'POST /api/chatbot'.throttlingBurstLimit", equalTo(20));+ }++ @Test+ @Order(5)+ void unsetThrottlingFieldsAreOmittedNotZeroed() {+ // AWS omits unset knobs; emitting 0 would make Terraform see a changed value forever.+ given().contentType(ContentType.JSON)+ .body("{\"stageName\":\"sparse\",\"defaultRouteSettings\":{\"throttlingRateLimit\":50}}")+ .when().post("/v2/apis/" + apiId + "/stages")+ .then().statusCode(201)+ .body("defaultRouteSettings.throttlingRateLimit", equalTo(50.0f))+ .body("defaultRouteSettings.throttlingBurstLimit", org.hamcrest.Matchers.nullValue())+ .body("defaultRouteSettings.dataTraceEnabled", org.hamcrest.Matchers.nullValue());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2StageTaggingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2StageTaggingTest.javanew file mode 100644index 0000000000..882d39ab13--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2StageTaggingTest.java@@ -0,0 +1,97 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;++/**+ * Tagging a stage rather than an API. A stage ARN carries two more segments than an API ARN+ * ({@code /apis/{apiId}/stages/{stageName}}); reading only the trailing segment takes the stage+ * name for the API id, which surfaces as "Invalid API id specified" on TagResource.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class ApiGatewayV2StageTaggingTest {++ private static String apiId;++ private static String stageArn() {+ return "arn:aws:apigateway:us-east-1::/apis/" + apiId + "/stages/$default";+ }++ @Test+ @Order(1)+ void createApiAndStageWithTags() {+ apiId = given()+ .contentType(ContentType.JSON)+ .body("{\"name\":\"stage-tagging-test-api\",\"protocolType\":\"HTTP\"}")+ .when().post("/v2/apis")+ .then().statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Tags supplied at CreateStage must survive a read, or Terraform re-tags on every plan.+ given().contentType(ContentType.JSON)+ .body("{\"stageName\":\"$default\",\"autoDeploy\":true,\"tags\":{\"Tier\":\"base\"}}")+ .when().post("/v2/apis/" + apiId + "/stages")+ .then().statusCode(201)+ .body("tags.Tier", equalTo("base"));++ given().when().get("/v2/apis/" + apiId + "/stages/$default")+ .then().statusCode(200)+ .body("tags.Tier", equalTo("base"));+ }++ @Test+ @Order(2)+ void tagResourceOnStageArn() {+ given().contentType(ContentType.JSON)+ .body("{\"tags\":{\"Feature\":\"api\"}}")+ .when().post("/v2/tags/" + stageArn())+ .then().statusCode(201);++ given().when().get("/v2/tags/" + stageArn())+ .then().statusCode(200)+ .body("tags.Feature", equalTo("api"))+ .body("tags.Tier", equalTo("base"));++ // The API itself must not have picked up the stage's tags.+ given().when().get("/v2/tags/arn:aws:apigateway:us-east-1::/apis/" + apiId)+ .then().statusCode(200)+ .body("tags.Feature", nullValue());+ }++ @Test+ @Order(3)+ void untagResourceOnStageArn() {+ given().when().delete("/v2/tags/" + stageArn() + "?tagKeys=Feature")+ .then().statusCode(anyOf204());++ given().when().get("/v2/tags/" + stageArn())+ .then().statusCode(200)+ .body("tags.Feature", nullValue())+ .body("tags.Tier", equalTo("base"));+ }++ /** UntagResource replies 204 on AWS; accept 200 too rather than pin an unrelated detail. */+ private static org.hamcrest.Matcher<Integer> anyOf204() {+ return org.hamcrest.Matchers.anyOf(equalTo(204), equalTo(200));+ }++ @Test+ @Order(4)+ void unknownStageArnIsNotFound() {+ given().contentType(ContentType.JSON)+ .body("{\"tags\":{\"a\":\"b\"}}")+ .when().post("/v2/tags/arn:aws:apigateway:us-east-1::/apis/" + apiId + "/stages/nope")+ .then().statusCode(404);+ }+}