From 6fa53abd7cd9db183addee8d0bd2a80c38449e20 Mon Sep 17 00:00:00 2001 From: Aniket Shukla <0aniketshukla1@gmail.com> Date: Mon, 24 Aug 2026 00:50:20 +0530 Subject: [PATCH] =?UTF-8?q?feat(cloudformation):=20expand=20SAM=20AWS::Ser?= =?UTF-8?q?verless::HttpApi=20to=20ApiGatew=E2=80=A6=20(#1956)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(cloudformation): preserve HttpApi routes and avoid stage-id collisions expandServerlessHttpApi dropped the SAM DefinitionBody, so route-bearing AWS::Serverless::HttpApi templates expanded into an ApiGatewayV2 API with no routes. Carry DefinitionBody over as the ApiGatewayV2::Api Body. It also synthesized a 'Stage' resource with resources.set(...), silently overwriting any resource the user already declared under that logical id. Skip synthesis (and warn) when the id is taken instead of clobbering the user's resource. Tests cover both: DefinitionBody preserved as Body, and a user-declared Stage left intact. * fix(cloudformation): provision SAM HttpApi routes * fix(cloudformation): reconcile SAM HttpApi routes * fix(cloudformation): stage HttpApi route replacements * fix(cloudformation): roll back failed HttpApi replacements * fix(cloudformation): resolve intrinsic HttpApi definitions * fix(cloudformation): roll back HttpApi definition removal * fix(cloudformation): retain failed HttpApi route cleanup * test(cloudformation): align HttpApi fixture with main * chore(ci): retrigger flaky Neptune test * fix(apigatewayv2): prevent duplicate routes on rollback * fix(cloudformation): persist failed cleanup ownership * fix(cloudformation): preserve OpenAPI route authorization * fix(cloudformation): reject unsupported auth conjunctions * fix(apigatewayv2): preserve rollback and auth semantics * fix(cloudformation): surface incomplete update rollback * fix(cloudformation): merge overlapping SAM HTTP API routes * fix(cloudformation): preserve merged route authorization * test(cloudformation): document SAM auth defaults --- .../apigatewayv2/ApiGatewayV2Service.java | 84 ++- .../CloudFormationResourceProvisioner.java | 611 ++++++++++++++++++ .../cloudformation/CloudFormationService.java | 36 +- .../cloudformation/SamTransformProcessor.java | 176 +++++ .../ApiGatewayV2IntegrationTest.java | 80 +++ .../ApiGatewayV2CfnProvisionerTest.java | 511 +++++++++++++++ ...ionApiGatewayV2CleanupIntegrationTest.java | 200 ++++++ .../SamTransformIntegrationTest.java | 269 ++++++++ .../SamTransformProcessorTest.java | 231 +++++++ 9 files changed, 2190 insertions(+), 8 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2CleanupIntegrationTest.java 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.java index 91f9780bfe..cf00436652 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 @@ -307,6 +307,22 @@ public class ApiGatewayV2Service { authorizerStore.delete(authorizerKey(region, apiId, authorizerId)); } + /** Restores an authorizer with its original ID for a higher-level transactional rollback. */ + public void restoreAuthorizer(String region, String apiId, Authorizer authorizer) { + getApi(region, apiId); + Authorizer restored = new Authorizer(); + restored.setAuthorizerId(authorizer.getAuthorizerId()); + restored.setAuthorizerType(authorizer.getAuthorizerType()); + restored.setName(authorizer.getName()); + restored.setJwtConfiguration(authorizer.getJwtConfiguration()); + restored.setIdentitySource(authorizer.getIdentitySource()); + restored.setAuthorizerUri(authorizer.getAuthorizerUri()); + restored.setAuthorizerPayloadFormatVersion(authorizer.getAuthorizerPayloadFormatVersion()); + restored.setAuthorizerResultTtlInSeconds(authorizer.getAuthorizerResultTtlInSeconds()); + restored.setEnableSimpleResponses(authorizer.getEnableSimpleResponses()); + authorizerStore.put(authorizerKey(region, apiId, restored.getAuthorizerId()), restored); + } + public Authorizer updateAuthorizer(String region, String apiId, String authorizerId, Map request) { Authorizer auth = getAuthorizer(region, apiId, authorizerId); @@ -356,9 +372,11 @@ public class ApiGatewayV2Service { public Route createRoute(String region, String apiId, Map request) { getApi(region, apiId); + String requestedRouteKey = (String) request.get("routeKey"); + ensureRouteKeyAvailable(region, apiId, requestedRouteKey, null); Route route = new Route(); route.setRouteId(shortId(8)); - route.setRouteKey((String) request.get("routeKey")); + route.setRouteKey(requestedRouteKey); route.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE")); route.setAuthorizerId((String) request.get("authorizerId")); route.setAuthorizationScopes(toStringList(request.get("authorizationScopes"))); @@ -385,11 +403,52 @@ public class ApiGatewayV2Service { routeStore.delete(routeKey(region, apiId, routeId)); } + /** Restores a route without treating any conflicting route as rollback-owned. */ + public void restoreRoute(String region, String apiId, Route route) { + restoreRoute(region, apiId, route, java.util.Set.of()); + } + + /** + * Restores a route with its original ID for a higher-level transactional rollback. + * Only conflicts explicitly identified as part of the failed replacement may be removed; + * independently managed routes must never be deleted as a rollback side effect. + */ + public void restoreRoute(String region, String apiId, Route route, + java.util.Collection replaceableRouteIds) { + getApi(region, apiId); + // A failed cleanup can leave a replacement route behind. Remove that conflicting + // route only when the caller proves it belongs to that failed replacement. + for (Route existing : getRoutes(region, apiId)) { + if (!java.util.Objects.equals(existing.getRouteId(), route.getRouteId()) + && java.util.Objects.equals(existing.getRouteKey(), route.getRouteKey())) { + if (replaceableRouteIds.contains(existing.getRouteId())) { + routeStore.delete(routeKey(region, apiId, existing.getRouteId())); + } else { + throw new AwsException("ConflictException", + "Cannot restore route with key '" + route.getRouteKey() + + "' because an independently managed route already exists", + 409); + } + } + } + Route restored = new Route(); + restored.setRouteId(route.getRouteId()); + restored.setRouteKey(route.getRouteKey()); + restored.setAuthorizationType(route.getAuthorizationType()); + restored.setAuthorizerId(route.getAuthorizerId()); + restored.setAuthorizationScopes(route.getAuthorizationScopes()); + restored.setTarget(route.getTarget()); + restored.setRouteResponseSelectionExpression(route.getRouteResponseSelectionExpression()); + routeStore.put(routeKey(region, apiId, restored.getRouteId()), restored); + } + public Route updateRoute(String region, String apiId, String routeId, Map request) { Route route = getRoute(region, apiId, routeId); if (request.containsKey("routeKey") && request.get("routeKey") != null) { - route.setRouteKey((String) request.get("routeKey")); + String requestedRouteKey = (String) request.get("routeKey"); + ensureRouteKeyAvailable(region, apiId, requestedRouteKey, routeId); + route.setRouteKey(requestedRouteKey); } if (request.containsKey("authorizationType") && request.get("authorizationType") != null) { route.setAuthorizationType((String) request.get("authorizationType")); @@ -411,6 +470,20 @@ public class ApiGatewayV2Service { return route; } + private void ensureRouteKeyAvailable(String region, String apiId, String requestedRouteKey, + String currentRouteId) { + if (requestedRouteKey == null) { + return; + } + boolean duplicate = getRoutes(region, apiId).stream() + .anyMatch(existing -> !java.util.Objects.equals(existing.getRouteId(), currentRouteId) + && requestedRouteKey.equals(existing.getRouteKey())); + if (duplicate) { + throw new AwsException("ConflictException", + "Route with key '" + requestedRouteKey + "' already exists", 409); + } + } + // JSON bodies can carry non-string elements (numbers, booleans); downstream code // (response serialization, scope enforcement) assumes String elements, so normalize // at ingestion instead of unchecked-casting. A present-but-non-array value must be @@ -545,6 +618,13 @@ public class ApiGatewayV2Service { integrationStore.delete(integrationKey(region, apiId, integrationId)); } + /** Restores an integration with its original ID for a higher-level transactional rollback. */ + public void restoreIntegration(String region, String apiId, Integration integration) { + getApi(region, apiId); + integrationStore.put(integrationKey(region, apiId, integration.getIntegrationId()), + new Integration(integration)); + } + public Integration updateIntegration(String region, String apiId, String integrationId, Map request) { Integration integration = getIntegration(region, apiId, integrationId); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 0e379aaf79..1bdcd3431b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -137,6 +137,7 @@ public class CloudFormationResourceProvisioner { private static final String LAMBDA_NAME_MODE_ATTR = "FlociLambdaFunctionNameMode"; private static final String LAMBDA_PACKAGE_TYPE_ATTR = "FlociLambdaPackageType"; static final String UPDATE_ROLLBACK_RESTORED_ATTR = "__FlociUpdateRollbackRestored"; + static final String UPDATE_ROLLBACK_FAILURE_ATTR = "__FlociUpdateRollbackFailure"; private static final String INLINE_CLEANUP_POLICY_NAME_ATTR = "__FlociInlineCleanupPolicyName"; private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets"; private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets"; @@ -166,6 +167,11 @@ public class CloudFormationResourceProvisioner { private static final int LAMBDA_DEFAULT_MEMORY_MB = 128; private static final int LAMBDA_DEFAULT_EPHEMERAL_STORAGE_MB = 512; private static final String LAMBDA_DEFAULT_TRACING_MODE = "PassThrough"; + private static final String APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR = "__FlociApiGatewayV2BodyRouteIds"; + private static final String APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR = + "__FlociApiGatewayV2BodyIntegrationIds"; + private static final String APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR = + "__FlociApiGatewayV2BodyAuthorizerIds"; /** Reserved attribute keys used to carry custom-resource state to the later Delete invocation. */ private static final String CR_SERVICE_TOKEN_ATTR = "__FlociServiceToken"; @@ -5188,6 +5194,611 @@ public class CloudFormationResourceProvisioner { } r.setPhysicalId(api.getApiId()); r.getAttributes().put("ApiEndpoint", api.getApiEndpoint()); + reconcileApiGatewayV2BodyRoutes(r, region, api.getApiId(), props, engine); + } + + /** + * Reconciles the routes, integrations, and authorizers materialized from an ApiGatewayV2 OpenAPI body. + * Only IDs stored on this CloudFormation resource are removed, so separately declared V2 + * resources remain outside this generated-resource lifecycle. + */ + private void reconcileApiGatewayV2BodyRoutes(StackResource r, String region, String apiId, JsonNode props, + CloudFormationTemplateEngine engine) { + JsonNode body = resolveApiGatewayV2OpenApiBody(props, engine); + ApiGatewayV2BodyResourceState previous = null; + try { + previous = snapshotApiGatewayV2BodyResources(r, region, apiId); + // API Gateway requires route keys to be unique. Remove only the tracked body-generated + // resources before creating their replacements; rollback restores this snapshot. + deleteApiGatewayV2BodyResources(r, region, apiId); + } catch (RuntimeException e) { + rollbackApiGatewayV2BodyReplacement(r, region, apiId, + new ApiGatewayV2BodyResources(List.of(), List.of(), List.of()), previous, e); + throw e; + } + + if (body == null) { + return; + } + + ApiGatewayV2BodyResources replacement; + try { + replacement = materializeApiGatewayV2BodyRoutes(region, apiId, body); + } catch (ApiGatewayV2BodyMaterializationException e) { + rollbackApiGatewayV2BodyReplacement(r, region, apiId, e.resources(), previous, e); + throw e; + } catch (RuntimeException e) { + // materializeApiGatewayV2BodyRoutes already removed its partial replacement. + rollbackApiGatewayV2BodyReplacement(r, region, apiId, + new ApiGatewayV2BodyResources(List.of(), List.of(), List.of()), previous, e); + throw e; + } + storeApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR, replacement.routeIds()); + storeApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR, + replacement.integrationIds()); + storeApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR, + replacement.authorizerIds()); + } + + private JsonNode resolveApiGatewayV2OpenApiBody(JsonNode props, CloudFormationTemplateEngine engine) { + if (props == null) { + return null; + } + if (props.hasNonNull("Body")) { + return engine.resolveNode(props.get("Body")); + } + if (!props.hasNonNull("BodyS3Location")) { + return null; + } + + JsonNode location = engine.resolveNode(props.get("BodyS3Location")); + ApiGatewayV2BodyS3Location bodyS3Location = parseApiGatewayV2BodyS3Location(location); + + try { + byte[] document = s3Service.getObject(bodyS3Location.bucket(), bodyS3Location.key(), + bodyS3Location.version()).getData(); + String content = new String(document, StandardCharsets.UTF_8).trim(); + if (content.startsWith("{") || content.startsWith("[")) { + return objectMapper.readTree(content); + } + return new CloudFormationYamlParser(objectMapper).parse(content); + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw new AwsException("ValidationException", + "Unable to parse OpenAPI document from s3://" + bodyS3Location.bucket() + "/" + + bodyS3Location.key(), 400); + } + } + + private ApiGatewayV2BodyS3Location parseApiGatewayV2BodyS3Location(JsonNode location) { + if (location != null && location.isTextual()) { + String uri = location.asText(); + if (uri.startsWith("s3://")) { + String withoutScheme = uri.substring("s3://".length()); + int slash = withoutScheme.indexOf('/'); + if (slash > 0 && slash < withoutScheme.length() - 1) { + return new ApiGatewayV2BodyS3Location(withoutScheme.substring(0, slash), + withoutScheme.substring(slash + 1), null); + } + } + } else if (location != null && location.isObject()) { + String bucket = textOrNull(location, "Bucket"); + String key = textOrNull(location, "Key"); + if (bucket != null && !bucket.isBlank() && key != null && !key.isBlank()) { + return new ApiGatewayV2BodyS3Location(bucket, key, textOrNull(location, "Version")); + } + } + throw new AwsException("ValidationException", + "BodyS3Location must resolve to a non-empty S3 location", 400); + } + + /** + * CloudFormation's ApiGatewayV2 {@code Body} is an OpenAPI document. Materialize each + * declared HTTP operation as the route that API Gateway V2 serves, including its OpenAPI + * security requirement and a route target when it declares an integration extension. + */ + private ApiGatewayV2BodyResources materializeApiGatewayV2BodyRoutes(String region, String apiId, + JsonNode body) { + List routeIds = new ArrayList<>(); + List integrationIds = new ArrayList<>(); + List authorizerIds = new ArrayList<>(); + try { + Map authorizers = materializeApiGatewayV2BodyAuthorizers( + region, apiId, body, authorizerIds); + JsonNode paths = body.path("paths"); + if (!paths.isObject()) { + return new ApiGatewayV2BodyResources(routeIds, integrationIds, authorizerIds); + } + + Iterator> pathEntries = paths.fields(); + while (pathEntries.hasNext()) { + Map.Entry pathEntry = pathEntries.next(); + if (!pathEntry.getValue().isObject()) { + continue; + } + Iterator> operations = pathEntry.getValue().fields(); + while (operations.hasNext()) { + Map.Entry operation = operations.next(); + String method = operation.getKey(); + if (!isHttpApiOperation(method) || !operation.getValue().isObject()) { + continue; + } + + Map routeRequest = new HashMap<>(); + routeRequest.put("routeKey", openApiRouteKey(method, pathEntry.getKey())); + applyOpenApiRouteSecurity(body, operation.getValue(), pathEntry.getKey(), method, + authorizers, routeRequest); + JsonNode integration = operation.getValue().path("x-amazon-apigateway-integration"); + if (integration.isObject()) { + String integrationType = textOrNull(integration, "type"); + if (integrationType != null && !integrationType.isBlank()) { + Map integrationRequest = new HashMap<>(); + integrationRequest.put("integrationType", integrationType.toUpperCase(Locale.ROOT)); + putOpenApiIntegrationValue(integrationRequest, "integrationUri", integration, "uri"); + putOpenApiIntegrationValue(integrationRequest, "integrationMethod", integration, + "httpMethod"); + putOpenApiIntegrationValue(integrationRequest, "payloadFormatVersion", integration, + "payloadFormatVersion"); + Integration createdIntegration = apiGatewayV2Service.createIntegration(region, apiId, + integrationRequest); + integrationIds.add(createdIntegration.getIntegrationId()); + routeRequest.put("target", "integrations/" + createdIntegration.getIntegrationId()); + } + } + Route createdRoute = apiGatewayV2Service.createRoute(region, apiId, routeRequest); + routeIds.add(createdRoute.getRouteId()); + } + } + return new ApiGatewayV2BodyResources(routeIds, integrationIds, authorizerIds); + } catch (RuntimeException e) { + ApiGatewayV2BodyResources partial = new ApiGatewayV2BodyResources( + routeIds, integrationIds, authorizerIds); + List cleanupFailures = cleanupApiGatewayV2BodyResources(region, apiId, partial); + if (!cleanupFailures.isEmpty()) { + cleanupFailures.forEach(e::addSuppressed); + throw new ApiGatewayV2BodyMaterializationException(e, partial); + } + throw e; + } + } + + private Map materializeApiGatewayV2BodyAuthorizers( + String region, String apiId, JsonNode body, List authorizerIds) { + Map bindings = new LinkedHashMap<>(); + JsonNode schemes = body.path("components").path("securitySchemes"); + if (!schemes.isObject()) { + return bindings; + } + + Iterator> entries = schemes.fields(); + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + String schemeName = entry.getKey(); + JsonNode scheme = entry.getValue(); + if (!scheme.isObject()) { + continue; + } + + JsonNode definition = scheme.path("x-amazon-apigateway-authorizer"); + if (!definition.isObject()) { + continue; + } + + String type = textOrNull(definition, "type"); + String authorizerType; + String routeAuthorizationType; + if ("jwt".equalsIgnoreCase(type)) { + authorizerType = "JWT"; + routeAuthorizationType = "JWT"; + } else if ("request".equalsIgnoreCase(type)) { + authorizerType = "REQUEST"; + routeAuthorizationType = "CUSTOM"; + } else { + throw invalidOpenApiV2Security("Authorizer " + schemeName + + " must declare type jwt or request"); + } + + Map request = new HashMap<>(); + request.put("name", schemeName); + request.put("authorizerType", authorizerType); + putOpenApiAuthorizerIdentitySource(request, definition); + putOpenApiAuthorizerValue(request, "authorizerUri", definition, "authorizerUri"); + putOpenApiAuthorizerValue(request, "authorizerPayloadFormatVersion", definition, + "authorizerPayloadFormatVersion"); + putOpenApiAuthorizerValue(request, "authorizerResultTtlInSeconds", definition, + "authorizerResultTtlInSeconds"); + putOpenApiAuthorizerValue(request, "enableSimpleResponses", definition, + "enableSimpleResponses"); + + if ("JWT".equals(authorizerType)) { + JsonNode jwt = definition.path("jwtConfiguration"); + if (!jwt.isObject()) { + throw invalidOpenApiV2Security("JWT authorizer " + schemeName + + " must declare jwtConfiguration"); + } + Map jwtConfiguration = new HashMap<>(); + jwtConfiguration.put("issuer", textOrNull(jwt, "issuer")); + jwtConfiguration.put("audience", openApiStringList(jwt.get("audience"), + "jwtConfiguration.audience for authorizer " + schemeName)); + request.put("jwtConfiguration", jwtConfiguration); + } + + Authorizer created = apiGatewayV2Service.createAuthorizer(region, apiId, request); + authorizerIds.add(created.getAuthorizerId()); + bindings.put(schemeName, + new OpenApiAuthorizerBinding(routeAuthorizationType, created.getAuthorizerId())); + } + return bindings; + } + + private void applyOpenApiRouteSecurity(JsonNode body, JsonNode operation, String path, String method, + Map authorizers, + Map routeRequest) { + JsonNode security = operation.has("security") ? operation.get("security") : body.get("security"); + if (security == null || security.isNull() || security.isMissingNode()) { + return; + } + if (!security.isArray()) { + throw invalidOpenApiV2Security("security must be an array"); + } + if (security.isEmpty()) { + routeRequest.put("authorizationType", "NONE"); + return; // An operation-level empty array explicitly overrides inherited security. + } + + // Each object is one alternative in the outer OR-list, but names inside one object are + // an AND requirement. A V2 route can attach only one authorizer, so accepting a multi-name + // object would silently weaken its authentication contract. AWS classifies multiple + // security requirements as an HTTP API import error: + // https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-open-api.html + // Validate every alternative before selecting a representable one. + for (JsonNode requirement : security) { + if (!requirement.isObject()) { + throw invalidOpenApiV2Security("security requirements must be objects"); + } + if (requirement.isEmpty()) { + routeRequest.put("authorizationType", "NONE"); + return; // An empty requirement allows anonymous access by OpenAPI definition. + } + if (requirement.size() > 1) { + throw invalidOpenApiV2Security( + "HTTP API routes do not support AND security requirements with multiple schemes"); + } + } + if (security.size() > 1) { + throw invalidOpenApiV2Security( + "HTTP API routes do not support OR security requirements with multiple alternatives"); + } + + String unsupportedScheme = null; + for (JsonNode requirement : security) { + Iterator> schemes = requirement.fields(); + while (schemes.hasNext()) { + Map.Entry scheme = schemes.next(); + OpenApiAuthorizerBinding binding = authorizers.get(scheme.getKey()); + if (binding == null) { + unsupportedScheme = scheme.getKey(); + continue; + } + routeRequest.put("authorizationType", binding.authorizationType()); + if (binding.authorizerId() != null) { + routeRequest.put("authorizerId", binding.authorizerId()); + } + if ("JWT".equals(binding.authorizationType())) { + List scopes = openApiStringList(scheme.getValue(), + "security scopes for scheme " + scheme.getKey()); + if (!scopes.isEmpty()) { + routeRequest.put("authorizationScopes", scopes); + } + } + return; + } + } + throw invalidOpenApiV2Security( + "Protected operation " + openApiRouteKey(method, path) + + " references unsupported security scheme '" + unsupportedScheme + "'"); + } + + private static void putOpenApiAuthorizerIdentitySource(Map request, JsonNode definition) { + JsonNode identitySource = definition.get("identitySource"); + if (identitySource == null || identitySource.isNull()) { + return; + } + if (identitySource.isTextual()) { + request.put("identitySource", identitySource.asText()); + return; + } + request.put("identitySource", openApiStringList(identitySource, "authorizer identitySource")); + } + + private static void putOpenApiAuthorizerValue(Map request, String requestKey, + JsonNode definition, String definitionKey) { + JsonNode value = definition.get(definitionKey); + if (value == null || value.isNull()) { + return; + } + if (value.isTextual()) { + request.put(requestKey, value.asText()); + } else if (value.isBoolean()) { + request.put(requestKey, value.booleanValue()); + } else if (value.isIntegralNumber()) { + request.put(requestKey, value.intValue()); + } else { + throw invalidOpenApiV2Security(definitionKey + " has an invalid value"); + } + } + + private static List openApiStringList(JsonNode value, String fieldName) { + if (value == null || value.isNull()) { + return List.of(); + } + if (!value.isArray()) { + throw invalidOpenApiV2Security(fieldName + " must be an array of strings"); + } + List values = new ArrayList<>(); + for (JsonNode element : value) { + if (!element.isTextual()) { + throw invalidOpenApiV2Security(fieldName + " must be an array of strings"); + } + values.add(element.asText()); + } + return values; + } + + private static AwsException invalidOpenApiV2Security(String message) { + return new AwsException("ValidationException", message, 400); + } + + private void deleteApiGatewayV2BodyResources(StackResource r, String region, String apiId) { + deleteApiGatewayV2BodyResources(region, apiId, new ApiGatewayV2BodyResources( + apiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR), + apiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR), + apiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR))); + r.getAttributes().remove(APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR); + r.getAttributes().remove(APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR); + r.getAttributes().remove(APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR); + } + + private void deleteApiGatewayV2BodyResources(String region, String apiId, + ApiGatewayV2BodyResources resources) { + for (String routeId : resources.routeIds()) { + deleteApiGatewayV2BodyRouteIfPresent(region, apiId, routeId); + } + for (String integrationId : resources.integrationIds()) { + deleteApiGatewayV2BodyIntegrationIfPresent(region, apiId, integrationId); + } + for (String authorizerId : resources.authorizerIds()) { + deleteApiGatewayV2BodyAuthorizerIfPresent(region, apiId, authorizerId); + } + } + + private ApiGatewayV2BodyResourceState snapshotApiGatewayV2BodyResources(StackResource r, String region, + String apiId) { + List routes = new ArrayList<>(); + for (String routeId : apiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR)) { + try { + routes.add(apiGatewayV2Service.getRoute(region, apiId, routeId)); + } catch (AwsException e) { + if (e.getHttpStatus() != 404) { + throw e; + } + } + } + + List integrations = new ArrayList<>(); + for (String integrationId : apiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR)) { + try { + integrations.add(apiGatewayV2Service.getIntegration(region, apiId, integrationId)); + } catch (AwsException e) { + if (e.getHttpStatus() != 404) { + throw e; + } + } + } + + List authorizers = new ArrayList<>(); + for (String authorizerId : apiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR)) { + try { + authorizers.add(apiGatewayV2Service.getAuthorizer(region, apiId, authorizerId)); + } catch (AwsException e) { + if (e.getHttpStatus() != 404) { + throw e; + } + } + } + return new ApiGatewayV2BodyResourceState(routes, integrations, authorizers); + } + + private void rollbackApiGatewayV2BodyReplacement(StackResource r, String region, String apiId, + ApiGatewayV2BodyResources replacement, + ApiGatewayV2BodyResourceState previous, + RuntimeException failure) { + List cleanupFailures = cleanupApiGatewayV2BodyResources(region, apiId, replacement); + + if (previous != null) { + storeApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR, + previous.routes().stream().map(Route::getRouteId).toList()); + storeApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR, + previous.integrations().stream().map(Integration::getIntegrationId).toList()); + storeApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR, + previous.authorizers().stream().map(Authorizer::getAuthorizerId).toList()); + } + if (!cleanupFailures.isEmpty()) { + cleanupFailures.forEach(failure::addSuppressed); + retainApiGatewayV2BodyResourceIds(r, replacement); + } + if (previous == null) { + return; + } + try { + // Routes refer to integrations and authorizers, so restore both before their routes. + for (Authorizer authorizer : previous.authorizers()) { + apiGatewayV2Service.restoreAuthorizer(region, apiId, authorizer); + } + for (Integration integration : previous.integrations()) { + apiGatewayV2Service.restoreIntegration(region, apiId, integration); + } + for (Route route : previous.routes()) { + apiGatewayV2Service.restoreRoute(region, apiId, route, replacement.routeIds()); + } + } catch (RuntimeException restoreFailure) { + failure.addSuppressed(restoreFailure); + String reason = restoreFailure.getMessage() != null + ? restoreFailure.getMessage() + : restoreFailure.getClass().getSimpleName(); + r.getAttributes().put(UPDATE_ROLLBACK_FAILURE_ATTR, reason); + } + } + + private List cleanupApiGatewayV2BodyResources(String region, String apiId, + ApiGatewayV2BodyResources resources) { + List failures = new ArrayList<>(); + for (String routeId : resources.routeIds()) { + try { + deleteApiGatewayV2BodyRouteIfPresent(region, apiId, routeId); + } catch (RuntimeException e) { + failures.add(e); + } + } + for (String integrationId : resources.integrationIds()) { + try { + deleteApiGatewayV2BodyIntegrationIfPresent(region, apiId, integrationId); + } catch (RuntimeException e) { + failures.add(e); + } + } + for (String authorizerId : resources.authorizerIds()) { + try { + deleteApiGatewayV2BodyAuthorizerIfPresent(region, apiId, authorizerId); + } catch (RuntimeException e) { + failures.add(e); + } + } + return failures; + } + + private void retainApiGatewayV2BodyResourceIds(StackResource r, ApiGatewayV2BodyResources resources) { + retainApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR, resources.routeIds()); + retainApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR, + resources.integrationIds()); + retainApiGatewayV2BodyResourceIds(r, APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR, + resources.authorizerIds()); + } + + /** + * Carries ownership discovered by a failed update onto the last known-good resource metadata + * that CloudFormation restores. Only additive cleanup tracking belongs here; normal attempted + * attributes must not overwrite the committed resource state. + */ + void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + if (!"AWS::ApiGatewayV2::Api".equals(previous.getResourceType()) + || !Objects.equals(previous.getResourceType(), attempted.getResourceType())) { + return; + } + retainApiGatewayV2BodyResourceIds(previous, APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR, + apiGatewayV2BodyResourceIds(attempted, APIGATEWAY_V2_BODY_ROUTE_IDS_ATTR)); + retainApiGatewayV2BodyResourceIds(previous, APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR, + apiGatewayV2BodyResourceIds(attempted, APIGATEWAY_V2_BODY_INTEGRATION_IDS_ATTR)); + retainApiGatewayV2BodyResourceIds(previous, APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR, + apiGatewayV2BodyResourceIds(attempted, APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR)); + } + + private static void retainApiGatewayV2BodyResourceIds(StackResource r, String attributeName, + List resourceIds) { + LinkedHashSet retained = new LinkedHashSet<>(apiGatewayV2BodyResourceIds(r, attributeName)); + retained.addAll(resourceIds); + storeApiGatewayV2BodyResourceIds(r, attributeName, new ArrayList<>(retained)); + } + + private static List apiGatewayV2BodyResourceIds(StackResource r, String attributeName) { + String ids = r.getAttributes().get(attributeName); + return ids == null || ids.isBlank() ? List.of() : Arrays.asList(ids.split(",")); + } + + private static void storeApiGatewayV2BodyResourceIds(StackResource r, String attributeName, + List resourceIds) { + if (resourceIds.isEmpty()) { + r.getAttributes().remove(attributeName); + } else { + r.getAttributes().put(attributeName, String.join(",", resourceIds)); + } + } + + private void deleteApiGatewayV2BodyRouteIfPresent(String region, String apiId, String routeId) { + try { + apiGatewayV2Service.deleteRoute(region, apiId, routeId); + } catch (AwsException e) { + if (e.getHttpStatus() != 404) { + throw e; + } + } + } + + private void deleteApiGatewayV2BodyIntegrationIfPresent(String region, String apiId, String integrationId) { + try { + apiGatewayV2Service.deleteIntegration(region, apiId, integrationId); + } catch (AwsException e) { + if (e.getHttpStatus() != 404) { + throw e; + } + } + } + + private void deleteApiGatewayV2BodyAuthorizerIfPresent(String region, String apiId, String authorizerId) { + try { + apiGatewayV2Service.deleteAuthorizer(region, apiId, authorizerId); + } catch (AwsException e) { + if (e.getHttpStatus() != 404) { + throw e; + } + } + } + + private record ApiGatewayV2BodyResources(List routeIds, List integrationIds, + List authorizerIds) {} + + private record ApiGatewayV2BodyResourceState(List routes, List integrations, + List authorizers) {} + + private record OpenApiAuthorizerBinding(String authorizationType, String authorizerId) {} + + private record ApiGatewayV2BodyS3Location(String bucket, String key, String version) {} + + private static final class ApiGatewayV2BodyMaterializationException extends RuntimeException { + private final ApiGatewayV2BodyResources resources; + + private ApiGatewayV2BodyMaterializationException(RuntimeException cause, + ApiGatewayV2BodyResources resources) { + super(cause.getMessage(), cause); + this.resources = resources; + } + + private ApiGatewayV2BodyResources resources() { + return resources; + } + } + + private static boolean isHttpApiOperation(String method) { + return switch (method.toLowerCase(Locale.ROOT)) { + case "get", "put", "post", "delete", "options", "head", "patch", "trace", + "x-amazon-apigateway-any-method" -> true; + default -> false; + }; + } + + private static String openApiRouteKey(String method, String path) { + String routeMethod = "x-amazon-apigateway-any-method".equals(method) ? "ANY" + : method.toUpperCase(Locale.ROOT); + return routeMethod + " " + path; + } + + private static void putOpenApiIntegrationValue(Map request, String requestKey, + JsonNode integration, String openApiKey) { + String value = textOrNull(integration, openApiKey); + if (value != null) { + request.put(requestKey, value); + } } private Map parseApiGatewayV2Tags(JsonNode tagsNode, CloudFormationTemplateEngine engine) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 49271756e6..1585d604d1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -735,12 +735,27 @@ public class CloudFormationService { // Provisioners work on a copy of the stored resource metadata. Keep the // last known-good identity and status when an update attempt fails so a // later retry or stack deletion still manages the original resource. - // The rollback walker must also know this resource is already restored; - // otherwise an earlier UPDATE_COMPLETE status looks like an unhandled - // mutation and incorrectly turns a safe rollback into ROLLBACK_FAILED. - previousResource.getAttributes().put( - CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR, - "true"); + // Preserve any additional resources that the failed attempt could not + // clean up, otherwise restoring this object would orphan them. + provisioner.mergeFailedUpdateResourceTracking(previousResource, resource); + String rollbackFailure = resource.getAttributes().get( + CloudFormationResourceProvisioner.UPDATE_ROLLBACK_FAILURE_ATTR); + if (rollbackFailure == null) { + // The rollback walker must know this resource is already restored; + // otherwise an earlier UPDATE_COMPLETE status looks like an + // unhandled mutation and incorrectly becomes ROLLBACK_FAILED. + previousResource.getAttributes().put( + CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR, + "true"); + } else { + // Restoration was attempted eagerly by the provisioner but did not + // complete. Carry that failure onto the committed resource so the + // rollback walker reports UPDATE_ROLLBACK_FAILED rather than claiming + // the stale snapshot is live. + previousResource.getAttributes().put( + CloudFormationResourceProvisioner.UPDATE_ROLLBACK_FAILURE_ATTR, + rollbackFailure); + } stack.getResources().put(logicalId, previousResource); } break; @@ -1105,6 +1120,15 @@ public class CloudFormationService { resource.getResourceType(), "DELETE_COMPLETE", "Resource creation cancelled during update rollback"); removedResources.add(resource.getLogicalId()); + } else if (resource.getAttributes().containsKey( + CloudFormationResourceProvisioner.UPDATE_ROLLBACK_FAILURE_ATTR)) { + String reason = resource.getAttributes().remove( + CloudFormationResourceProvisioner.UPDATE_ROLLBACK_FAILURE_ATTR); + failures.add(resource.getLogicalId()); + resource.setStatus("UPDATE_FAILED"); + resource.setStatusReason(reason); + addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(), + resource.getResourceType(), "UPDATE_FAILED", reason); } else if ("true".equals(resource.getAttributes().remove( CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR)) || provisioner.rollbackUpdate(resource)) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java index 90e72c47c9..80c1cdd922 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java @@ -210,6 +210,18 @@ class SamTransformProcessor { apiProps.set("Name", !name.isMissingNode() ? name.deepCopy() : objectMapper.getNodeFactory().textNode(logicalId)); apiProps.put("ProtocolType", "HTTP"); copyIfPresent(properties, "Description", apiProps); + + // Preserve inline OpenAPI route definitions so the ApiGatewayV2 provisioner can + // materialize the routes and integrations declared by SAM DefinitionBody. + JsonNode definitionBody = properties.path("DefinitionBody"); + if (!definitionBody.isMissingNode() && !definitionBody.isNull()) { + apiProps.set("Body", definitionBody.deepCopy()); + } else { + ObjectNode bodyS3Location = buildHttpApiBodyS3Location(properties.path("DefinitionUri")); + if (bodyS3Location != null) { + apiProps.set("BodyS3Location", bodyS3Location); + } + } apiDef.set("Properties", apiProps); resources.set(logicalId, apiDef); @@ -247,10 +259,135 @@ class SamTransformProcessor { if (!logicalId.equals(route.apiLogicalId())) { continue; } + JsonNode defaultAuthorizer = defaultAuthorizerName == null + ? objectMapper.missingNode() : authorizers.path(defaultAuthorizerName); + if (mergeHttpApiRouteIntoDefinitionBody(apiProps.path("Body"), route, + defaultAuthorizerName, defaultAuthorizer)) { + expandHttpApiPermission(logicalId, route, resources); + continue; + } expandHttpApiRoute(logicalId, route, defaultAuthorizerLogicalId, resources); } } + /** + * SAM merges a Function HttpApi event into an existing OpenAPI operation instead of emitting a + * second route with the same key. Preserve the operation's documentation while adding the + * Lambda integration only when the body does not already provide one. + */ + private boolean mergeHttpApiRouteIntoDefinitionBody(JsonNode definitionBody, HttpApiRoute route, + String defaultAuthorizerName, + JsonNode defaultAuthorizer) { + JsonNode pathItem = definitionBody.path("paths").path(route.path()); + if (!pathItem.isObject()) { + return false; + } + String operationName = "ANY".equalsIgnoreCase(route.httpMethod()) + ? "x-amazon-apigateway-any-method" : route.httpMethod(); + JsonNode operation = fieldIgnoreCase(pathItem, operationName); + if (!operation.isObject()) { + return false; + } + ObjectNode operationObject = (ObjectNode) operation; + if (!operationObject.path("x-amazon-apigateway-integration").isObject()) { + ObjectNode integration = objectMapper.createObjectNode(); + integration.put("type", "aws_proxy"); + integration.put("httpMethod", "POST"); + integration.put("payloadFormatVersion", "2.0"); + integration.set("uri", lambdaInvokeUri(route.functionLogicalId())); + operationObject.set("x-amazon-apigateway-integration", integration); + } + applyMergedHttpApiRouteAuthorization(definitionBody, operationObject, route, + defaultAuthorizerName, defaultAuthorizer); + return true; + } + + /** + * The SAM translator mutates matching DefinitionBody operations with both the Function event's + * integration and its effective authorization. Without the latter, merging an authenticated + * event would silently expose the route because the API Gateway V2 body importer defaults the + * operation to {@code NONE}. + */ + private void applyMergedHttpApiRouteAuthorization(JsonNode definitionBody, ObjectNode operation, + HttpApiRoute route, String defaultAuthorizerName, + JsonNode defaultAuthorizer) { + if (route.noAuthorizer()) { + // SAM represents this opt-out with a synthetic NONE requirement. An empty operation-level + // OpenAPI security array is the standard equivalent and is understood by our body importer. + operation.set("security", objectMapper.createArrayNode()); + return; + } + if (defaultAuthorizerName == null || !defaultAuthorizer.isObject() + || hasNonEmptySecurity(operation.get("security"))) { + return; + } + + // AWS SAM deliberately treats an absent, null, or empty operation security value as unset + // when applying DefaultAuthorizer. A public per-event override is represented separately by + // Authorizer: NONE and is handled above. Keep this truthiness rule aligned with + // OpenApiEditor.set_path_default_authorizer: + // https://github.com/aws/serverless-application-model/blob/develop/samtranslator/open_api/open_api.py + addOpenApiJwtAuthorizer(definitionBody, defaultAuthorizerName, defaultAuthorizer); + ObjectNode requirement = objectMapper.createObjectNode(); + JsonNode configuredScopes = defaultAuthorizer.path("AuthorizationScopes"); + requirement.set(defaultAuthorizerName, configuredScopes.isArray() + ? configuredScopes.deepCopy() : objectMapper.createArrayNode()); + ArrayNode security = objectMapper.createArrayNode(); + security.add(requirement); + operation.set("security", security); + } + + private static boolean hasNonEmptySecurity(JsonNode security) { + return security != null && !security.isNull() + && (!security.isContainerNode() || security.size() > 0); + } + + /** + * Emits the same JWT security-scheme shape as + * {@code ApiGatewayV2Authorizer.generate_openapi} in AWS SAM. The ApiGatewayV2 body provisioner + * materializes this scheme first, then binds the operation's security requirement to it. + */ + private void addOpenApiJwtAuthorizer(JsonNode definitionBody, String authorizerName, + JsonNode samAuthorizer) { + ObjectNode body = (ObjectNode) definitionBody; + ObjectNode components = objectChild(body, "components", "DefinitionBody.components"); + ObjectNode schemes = objectChild(components, "securitySchemes", + "DefinitionBody.components.securitySchemes"); + + ObjectNode scheme = objectMapper.createObjectNode(); + scheme.put("type", "oauth2"); + ObjectNode extension = objectMapper.createObjectNode(); + extension.set("identitySource", resolveIdentitySource(authorizerName, samAuthorizer)); + extension.put("type", "jwt"); + + JsonNode samJwt = samAuthorizer.path("JwtConfiguration"); + ObjectNode jwt = objectMapper.createObjectNode(); + JsonNode issuer = fieldIgnoreCase(samJwt, "issuer"); + if (!issuer.isMissingNode()) { + jwt.set("issuer", issuer.deepCopy()); + } + JsonNode audience = fieldIgnoreCase(samJwt, "audience"); + if (audience.isArray()) { + jwt.set("audience", audience.deepCopy()); + } + extension.set("jwtConfiguration", jwt); + scheme.set("x-amazon-apigateway-authorizer", extension); + schemes.set(authorizerName, scheme); + } + + private ObjectNode objectChild(ObjectNode parent, String fieldName, String fieldPath) { + JsonNode existing = parent.get(fieldName); + if (existing == null || existing.isNull()) { + ObjectNode created = objectMapper.createObjectNode(); + parent.set(fieldName, created); + return created; + } + if (!existing.isObject()) { + throw new AwsException("ValidationError", fieldPath + " must be an object", 400); + } + return (ObjectNode) existing; + } + private ObjectNode buildHttpApiAuthorizer(String apiLogicalId, String authorizerName, JsonNode samAuthorizer) { ObjectNode authDef = objectMapper.createObjectNode(); authDef.put("Type", "AWS::ApiGatewayV2::Authorizer"); @@ -362,6 +499,10 @@ class SamTransformProcessor { routeDef.set("Properties", routeProps); resources.set(routeLogicalId, routeDef); + expandHttpApiPermission(apiLogicalId, route, resources); + } + + private void expandHttpApiPermission(String apiLogicalId, HttpApiRoute route, ObjectNode resources) { String permissionLogicalId = uniqueId( route.functionLogicalId() + "HttpApiPermission" + sanitize(apiLogicalId), resources); ObjectNode perm = objectMapper.createObjectNode(); @@ -949,6 +1090,41 @@ class SamTransformProcessor { resources.set(stageLogicalId, stageDef); } + /** + * {@code DefinitionUri} is SAM's S3-backed OpenAPI source. ApiGatewayV2 accepts the same + * source through {@code BodyS3Location}, with the S3 URI split into its bucket and key. + */ + private ObjectNode buildHttpApiBodyS3Location(JsonNode definitionUri) { + if (definitionUri == null || definitionUri.isMissingNode() || definitionUri.isNull()) { + return null; + } + ObjectNode location = objectMapper.createObjectNode(); + if (definitionUri.isTextual()) { + String uri = definitionUri.asText(); + if (!uri.startsWith("s3://")) { + return null; + } + String withoutScheme = uri.substring("s3://".length()); + int slash = withoutScheme.indexOf('/'); + if (slash <= 0 || slash == withoutScheme.length() - 1) { + return null; + } + location.put("Bucket", withoutScheme.substring(0, slash)); + location.put("Key", withoutScheme.substring(slash + 1)); + return location; + } + if (definitionUri.isObject()) { + copyIfPresent(definitionUri, "Bucket", location); + copyIfPresent(definitionUri, "Key", location); + copyIfPresent(definitionUri, "Version", location); + // An intrinsic expression (for example Ref or Fn::Sub) cannot be split until the + // CloudFormation engine resolves it during provisioning. Preserve it as-is instead + // of silently dropping the HttpApi definition and its routes. + return location.has("Bucket") && location.has("Key") ? location : definitionUri.deepCopy(); + } + return null; + } + private void copyIfPresent(JsonNode source, String field, ObjectNode target) { JsonNode value = source.path(field); if (!value.isMissingNode() && !value.isNull()) { diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2IntegrationTest.java index 0405be2589..f496908ec4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2IntegrationTest.java @@ -1,5 +1,9 @@ package io.github.hectorvent.floci.services.apigatewayv2; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer; +import io.github.hectorvent.floci.services.apigatewayv2.model.Route; +import jakarta.inject.Inject; import io.quarkus.test.junit.QuarkusTest; import io.restassured.http.ContentType; import org.junit.jupiter.api.MethodOrderer; @@ -7,13 +11,22 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import java.util.List; +import java.util.Map; +import java.util.Set; + import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; @QuarkusTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class ApiGatewayV2IntegrationTest { + @Inject + ApiGatewayV2Service apiGatewayV2Service; + private static String apiId; private static String routeId; private static String integrationId; @@ -154,6 +167,60 @@ class ApiGatewayV2IntegrationTest { .body("items.routeId", hasItem(routeId)); } + @Test @Order(23) + void duplicateRouteKeyIsRejected() { + given() + .contentType(ContentType.JSON) + .body(""" + {"routeKey":"GET /users","target":"integrations/%s"} + """.formatted(integrationId)) + .when().post("/v2/apis/" + apiId + "/routes") + .then() + .statusCode(409); + } + + @Test @Order(24) + void restoringRouteRemovesAConflictingReplacement() { + Route oldRoute = new Route(); + oldRoute.setRouteId("restored-route"); + oldRoute.setRouteKey("GET /users"); + oldRoute.setAuthorizationType("NONE"); + oldRoute.setAuthorizationScopes(List.of("read:users")); + oldRoute.setTarget("integrations/" + integrationId); + + String replacementRouteId = routeId; + apiGatewayV2Service.restoreRoute("us-east-1", apiId, oldRoute, Set.of(replacementRouteId)); + + assertEquals(1, apiGatewayV2Service.getRoutes("us-east-1", apiId).stream() + .filter(route -> "GET /users".equals(route.getRouteKey())) + .count()); + assertEquals("restored-route", + apiGatewayV2Service.findRouteByKey("us-east-1", apiId, "GET /users").getRouteId()); + assertEquals(List.of("read:users"), + apiGatewayV2Service.getRoute("us-east-1", apiId, "restored-route").getAuthorizationScopes()); + assertThrows(AwsException.class, + () -> apiGatewayV2Service.getRoute("us-east-1", apiId, replacementRouteId)); + routeId = oldRoute.getRouteId(); + } + + @Test @Order(25) + void restoringRouteDoesNotDeleteAnIndependentConflict() { + Route independent = apiGatewayV2Service.createRoute("us-east-1", apiId, + Map.of("routeKey", "GET /independent")); + Route snapshot = new Route(); + snapshot.setRouteId("rollback-snapshot"); + snapshot.setRouteKey("GET /independent"); + + assertThrows(AwsException.class, + () -> apiGatewayV2Service.restoreRoute("us-east-1", apiId, snapshot, Set.of("other-route"))); + assertEquals(independent.getRouteId(), apiGatewayV2Service + .findRouteByKey("us-east-1", apiId, "GET /independent").getRouteId()); + assertThrows(AwsException.class, + () -> apiGatewayV2Service.getRoute("us-east-1", apiId, snapshot.getRouteId())); + + apiGatewayV2Service.deleteRoute("us-east-1", apiId, independent.getRouteId()); + } + // ──────────────────────────── Authorizers ──────────────────────────── @Test @Order(30) @@ -198,6 +265,19 @@ class ApiGatewayV2IntegrationTest { .body("items.authorizerId", hasItem(authorizerId)); } + @Test @Order(33) + void restoreAuthorizerPreservesEnforcementConfiguration() { + Authorizer snapshot = apiGatewayV2Service.getAuthorizer("us-east-1", apiId, authorizerId); + apiGatewayV2Service.deleteAuthorizer("us-east-1", apiId, authorizerId); + apiGatewayV2Service.restoreAuthorizer("us-east-1", apiId, snapshot); + + Authorizer restored = apiGatewayV2Service.getAuthorizer("us-east-1", apiId, authorizerId); + assertEquals("JWT", restored.getAuthorizerType()); + assertEquals(List.of("$request.header.Authorization"), restored.getIdentitySource()); + assertEquals("https://example.com", restored.getJwtConfiguration().issuer()); + assertEquals(List.of("api"), restored.getJwtConfiguration().audience()); + } + // ──────────────────────────── Deployments ──────────────────────────── @Test @Order(40) diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java new file mode 100644 index 0000000000..745ea4eac9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java @@ -0,0 +1,511 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +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; +import io.github.hectorvent.floci.services.apigatewayv2.model.Route; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ApiGatewayV2CfnProvisionerTest { + + private static final String REGION = "us-east-1"; + private static final String API_ID = "api-123"; + private final ObjectMapper mapper = new ObjectMapper(); + private ApiGatewayV2Service apiGatewayV2Service; + private CloudFormationResourceProvisioner provisioner; + + @BeforeEach + void setUp() { + apiGatewayV2Service = mock(ApiGatewayV2Service.class); + provisioner = new CloudFormationResourceProvisioner( + null, null, null, null, null, null, null, null, null, null, + null, apiGatewayV2Service, null, null, null, null, mapper, + null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, + new CloudFormationResourceRegistry(java.util.List.of())); + + Api api = new Api(); + api.setApiId(API_ID); + api.setApiEndpoint("https://" + API_ID + ".execute-api.localhost"); + when(apiGatewayV2Service.createApi(eq(REGION), anyMap())).thenReturn(api); + when(apiGatewayV2Service.updateApi(eq(REGION), eq(API_ID), anyMap())).thenReturn(api); + } + + @Test + void restoresExistingRoutesAndCleansPartialReplacementWhenRouteCreationFails() throws Exception { + Route oldRoute = route("old-route", "GET /before"); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + Map request = invocation.getArgument(2); + return switch ((String) request.get("routeKey")) { + case "GET /before" -> oldRoute; + case "GET /first" -> route("partial-route", "GET /first"); + case "GET /second" -> throw new AwsException("InternalFailure", "simulated route failure", 500); + default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey")); + }; + }); + when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-route")).thenReturn(oldRoute); + + StackResource original = provision(body(""" + {"paths":{"/before":{"get":{}}}} + """), null, Map.of()); + + StackResource replacement = provision(body(""" + {"paths":{"/first":{"get":{}},"/second":{"get":{}}}} + """), original.getPhysicalId(), original.getAttributes()); + + assertEquals("CREATE_COMPLETE", original.getStatus()); + assertEquals("CREATE_FAILED", replacement.getStatus()); + assertEquals("old-route", replacement.getAttributes().get("__FlociApiGatewayV2BodyRouteIds")); + verify(apiGatewayV2Service).deleteRoute(REGION, API_ID, "old-route"); + verify(apiGatewayV2Service).deleteRoute(REGION, API_ID, "partial-route"); + verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldRoute, java.util.List.of()); + } + + @Test + void retainsPartialRoutesWhenMaterializationCleanupFails() throws Exception { + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + Map request = invocation.getArgument(2); + return switch ((String) request.get("routeKey")) { + case "GET /first" -> route("partial-route", "GET /first"); + case "GET /second" -> throw new AwsException("InternalFailure", "simulated route failure", 500); + default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey")); + }; + }); + doAnswer(invocation -> { + throw new AwsException("InternalFailure", "simulated cleanup failure", 500); + }).when(apiGatewayV2Service).deleteRoute(REGION, API_ID, "partial-route"); + + StackResource failed = provision(body(""" + {"paths":{"/first":{"get":{}},"/second":{"get":{}}}} + """), null, Map.of()); + + assertEquals("CREATE_FAILED", failed.getStatus()); + assertEquals("partial-route", failed.getAttributes().get("__FlociApiGatewayV2BodyRouteIds")); + } + + @Test + void restoresExistingRouteWhenReplacementCleanupKeepsAConflictingRoute() throws Exception { + Route oldRoute = route("old-route", "GET /same"); + Route replacementRoute = route("replacement-route", "GET /same"); + AtomicInteger sameRouteCreations = new AtomicInteger(); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + Map request = invocation.getArgument(2); + return switch ((String) request.get("routeKey")) { + case "GET /same" -> sameRouteCreations.getAndIncrement() == 0 ? oldRoute : replacementRoute; + case "GET /second" -> throw new AwsException("InternalFailure", "simulated route failure", 500); + default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey")); + }; + }); + when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-route")).thenReturn(oldRoute); + doAnswer(invocation -> { + if ("replacement-route".equals(invocation.getArgument(2))) { + throw new AwsException("InternalFailure", "simulated cleanup failure", 500); + } + return null; + }).when(apiGatewayV2Service).deleteRoute(eq(REGION), eq(API_ID), anyString()); + + StackResource original = provision(body(""" + {"paths":{"/same":{"get":{}}}} + """), null, Map.of()); + StackResource replacement = provision(body(""" + {"paths":{"/same":{"get":{}},"/second":{"get":{}}}} + """), original.getPhysicalId(), original.getAttributes()); + + assertEquals("CREATE_COMPLETE", original.getStatus()); + assertEquals("CREATE_FAILED", replacement.getStatus()); + assertEquals("old-route,replacement-route", + replacement.getAttributes().get("__FlociApiGatewayV2BodyRouteIds")); + verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldRoute, + java.util.List.of("replacement-route")); + } + + @Test + void mergesFailedUpdateRouteAndIntegrationOwnershipIntoCommittedMetadata() { + StackResource previous = new StackResource(); + previous.setResourceType("AWS::ApiGatewayV2::Api"); + previous.getAttributes().put("__FlociApiGatewayV2BodyRouteIds", "old-route"); + previous.getAttributes().put("__FlociApiGatewayV2BodyIntegrationIds", "old-integration"); + previous.getAttributes().put("__FlociApiGatewayV2BodyAuthorizerIds", "old-authorizer"); + + StackResource attempted = new StackResource(); + attempted.setResourceType("AWS::ApiGatewayV2::Api"); + attempted.getAttributes().put("__FlociApiGatewayV2BodyRouteIds", + "old-route,surviving-route"); + attempted.getAttributes().put("__FlociApiGatewayV2BodyIntegrationIds", + "old-integration,surviving-integration"); + attempted.getAttributes().put("__FlociApiGatewayV2BodyAuthorizerIds", + "old-authorizer,surviving-authorizer"); + + provisioner.mergeFailedUpdateResourceTracking(previous, attempted); + + assertEquals("old-route,surviving-route", + previous.getAttributes().get("__FlociApiGatewayV2BodyRouteIds")); + assertEquals("old-integration,surviving-integration", + previous.getAttributes().get("__FlociApiGatewayV2BodyIntegrationIds")); + assertEquals("old-authorizer,surviving-authorizer", + previous.getAttributes().get("__FlociApiGatewayV2BodyAuthorizerIds")); + } + + @Test + void materializesInheritedJwtSecurityAndHonorsOperationOptOut() throws Exception { + Authorizer authorizer = new Authorizer(); + authorizer.setAuthorizerId("body-authorizer"); + when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(authorizer); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + Map request = invocation.getArgument(2); + return route("route-" + request.get("routeKey"), (String) request.get("routeKey")); + }); + + StackResource resource = provision(body(""" + { + "components":{"securitySchemes":{"JwtAuth":{ + "type":"oauth2", + "x-amazon-apigateway-authorizer":{ + "type":"jwt", + "identitySource":"$request.header.Authorization", + "jwtConfiguration":{ + "issuer":"https://issuer.example.com", + "audience":["client-id"] + } + } + }}}, + "security":[{"JwtAuth":["orders/read"]}], + "paths":{ + "/protected":{"get":{}}, + "/public":{"get":{"security":[]}} + } + } + """), null, Map.of()); + + assertEquals("CREATE_COMPLETE", resource.getStatus()); + assertEquals("body-authorizer", + resource.getAttributes().get("__FlociApiGatewayV2BodyAuthorizerIds")); + verify(apiGatewayV2Service).createAuthorizer(eq(REGION), eq(API_ID), argThat(request -> + "JwtAuth".equals(request.get("name")) + && "JWT".equals(request.get("authorizerType")) + && "$request.header.Authorization".equals(request.get("identitySource")))); + verify(apiGatewayV2Service).createRoute(eq(REGION), eq(API_ID), argThat(request -> + "GET /protected".equals(request.get("routeKey")) + && "JWT".equals(request.get("authorizationType")) + && "body-authorizer".equals(request.get("authorizerId")) + && java.util.List.of("orders/read").equals(request.get("authorizationScopes")))); + verify(apiGatewayV2Service).createRoute(eq(REGION), eq(API_ID), argThat(request -> + "GET /public".equals(request.get("routeKey")) + && "NONE".equals(request.get("authorizationType")) + && !request.containsKey("authorizerId"))); + } + + @Test + void rejectsProtectedOperationWhenSecuritySchemeCannotBeResolved() throws Exception { + StackResource resource = provision(body(""" + { + "security":[{"MissingAuthorizer":[]}], + "paths":{"/protected":{"get":{}}} + } + """), null, Map.of()); + + assertEquals("CREATE_FAILED", resource.getStatus()); + assertEquals("Protected operation GET /protected references unsupported security scheme 'MissingAuthorizer'", + resource.getStatusReason()); + verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), anyMap()); + } + + @Test + void rejectsAndSecurityRequirementInsteadOfApplyingOnlyOneScheme() throws Exception { + Authorizer first = new Authorizer(); + first.setAuthorizerId("first-authorizer"); + Authorizer second = new Authorizer(); + second.setAuthorizerId("second-authorizer"); + when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(first, second); + + StackResource resource = provision(body(""" + { + "components":{"securitySchemes":{ + "First":{"x-amazon-apigateway-authorizer":{ + "type":"jwt","jwtConfiguration":{"issuer":"https://first.example.com"} + }}, + "Second":{"x-amazon-apigateway-authorizer":{ + "type":"jwt","jwtConfiguration":{"issuer":"https://second.example.com"} + }} + }}, + "security":[{"First":[],"Second":[]}], + "paths":{"/protected":{"get":{}}} + } + """), null, Map.of()); + + assertEquals("CREATE_FAILED", resource.getStatus()); + verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), anyMap()); + verify(apiGatewayV2Service).deleteAuthorizer(REGION, API_ID, "first-authorizer"); + verify(apiGatewayV2Service).deleteAuthorizer(REGION, API_ID, "second-authorizer"); + } + + @Test + void rejectsUnrepresentableSecurityOrAlternativesInsteadOfChoosingOne() throws Exception { + StackResource resource = provision(body(""" + { + "security":[{"First":[]},{"Second":[]}], + "paths":{"/protected":{"get":{}}} + } + """), null, Map.of()); + + assertEquals("CREATE_FAILED", resource.getStatus()); + verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), anyMap()); + } + + @Test + void honorsAnonymousAlternativeInSecurityOrList() throws Exception { + Authorizer authorizer = new Authorizer(); + authorizer.setAuthorizerId("optional-authorizer"); + when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(authorizer); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(route("optional-route", "GET /optional")); + + StackResource resource = provision(body(""" + { + "components":{"securitySchemes":{"JwtAuth":{ + "x-amazon-apigateway-authorizer":{ + "type":"jwt","jwtConfiguration":{"issuer":"https://issuer.example.com"} + } + }}}, + "security":[{"JwtAuth":[]},{}], + "paths":{"/optional":{"get":{}}} + } + """), null, Map.of()); + + assertEquals("CREATE_COMPLETE", resource.getStatus()); + verify(apiGatewayV2Service).createRoute(eq(REGION), eq(API_ID), argThat(request -> + "GET /optional".equals(request.get("routeKey")) + && "NONE".equals(request.get("authorizationType")))); + } + + @Test + void materializesRequestAuthorizerSecurityAsCustomAuthorization() throws Exception { + Authorizer authorizer = new Authorizer(); + authorizer.setAuthorizerId("request-authorizer"); + when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(authorizer); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(route("protected-route", "POST /protected")); + + StackResource resource = provision(body(""" + { + "components":{"securitySchemes":{"RequestAuth":{ + "type":"apiKey", + "x-amazon-apigateway-authorizer":{ + "type":"request", + "identitySource":["$request.header.Authorization"], + "authorizerUri":"arn:aws:apigateway:us-east-1:lambda:path/functions/auth/invocations", + "authorizerPayloadFormatVersion":"2.0", + "enableSimpleResponses":true + } + }}}, + "paths":{"/protected":{"post":{"security":[{"RequestAuth":[]}]}}} + } + """), null, Map.of()); + + assertEquals("CREATE_COMPLETE", resource.getStatus()); + verify(apiGatewayV2Service).createAuthorizer(eq(REGION), eq(API_ID), argThat(request -> + "REQUEST".equals(request.get("authorizerType")) + && Boolean.TRUE.equals(request.get("enableSimpleResponses")))); + verify(apiGatewayV2Service).createRoute(eq(REGION), eq(API_ID), argThat(request -> + "POST /protected".equals(request.get("routeKey")) + && "CUSTOM".equals(request.get("authorizationType")) + && "request-authorizer".equals(request.get("authorizerId")))); + } + + @Test + void restoresBodyAuthorizerWhenSecuredRouteReplacementFails() throws Exception { + Authorizer oldAuthorizer = new Authorizer(); + oldAuthorizer.setAuthorizerId("old-authorizer"); + Authorizer replacementAuthorizer = new Authorizer(); + replacementAuthorizer.setAuthorizerId("replacement-authorizer"); + when(apiGatewayV2Service.createAuthorizer(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(oldAuthorizer, replacementAuthorizer); + + Route oldRoute = route("old-route", "GET /protected"); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())) + .thenReturn(oldRoute) + .thenThrow(new AwsException("InternalFailure", "simulated route failure", 500)); + when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-route")).thenReturn(oldRoute); + when(apiGatewayV2Service.getAuthorizer(REGION, API_ID, "old-authorizer")) + .thenReturn(oldAuthorizer); + + String securedBody = """ + { + "components":{"securitySchemes":{"JwtAuth":{ + "x-amazon-apigateway-authorizer":{ + "type":"jwt", + "jwtConfiguration":{"issuer":"https://issuer.example.com"} + } + }}}, + "security":[{"JwtAuth":[]}], + "paths":{"/protected":{"get":{}}} + } + """; + StackResource original = provision(body(securedBody), null, Map.of()); + StackResource replacement = provision(body(securedBody), original.getPhysicalId(), + original.getAttributes()); + + assertEquals("CREATE_COMPLETE", original.getStatus()); + assertEquals("CREATE_FAILED", replacement.getStatus()); + assertEquals("old-authorizer", + replacement.getAttributes().get("__FlociApiGatewayV2BodyAuthorizerIds")); + verify(apiGatewayV2Service).deleteAuthorizer(REGION, API_ID, "old-authorizer"); + verify(apiGatewayV2Service).deleteAuthorizer(REGION, API_ID, "replacement-authorizer"); + verify(apiGatewayV2Service).restoreAuthorizer(REGION, API_ID, oldAuthorizer); + verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldRoute, java.util.List.of()); + } + + @Test + void rejectsSigV4SecurityUntilHttpApiIamEnforcementIsSupported() throws Exception { + StackResource resource = provision(body(""" + { + "components":{"securitySchemes":{"SigV4":{ + "type":"apiKey", + "x-amazon-apigateway-authtype":"awsSigv4" + }}}, + "security":[{"SigV4":[]}], + "paths":{"/iam":{"get":{}}} + } + """), null, Map.of()); + + assertEquals("CREATE_FAILED", resource.getStatus()); + verify(apiGatewayV2Service, never()).createAuthorizer(eq(REGION), eq(API_ID), anyMap()); + verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), anyMap()); + } + + @Test + void restoresExistingRoutesWhenOldRouteDeletionFails() throws Exception { + Route oldOne = route("old-one", "GET /before-one"); + Route oldTwo = route("old-two", "GET /before-two"); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + Map request = invocation.getArgument(2); + return switch ((String) request.get("routeKey")) { + case "GET /before-one" -> oldOne; + case "GET /before-two" -> oldTwo; + case "GET /after" -> route("replacement-route", "GET /after"); + default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey")); + }; + }); + when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-one")).thenReturn(oldOne); + when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-two")).thenReturn(oldTwo); + doAnswer(invocation -> { + if ("old-two".equals(invocation.getArgument(2))) { + throw new AwsException("InternalFailure", "simulated delete failure", 500); + } + return null; + }).when(apiGatewayV2Service).deleteRoute(eq(REGION), eq(API_ID), anyString()); + + StackResource original = provision(body(""" + {"paths":{"/before-one":{"get":{}},"/before-two":{"get":{}}}} + """), null, Map.of()); + + StackResource replacement = provision(body(""" + {"paths":{"/after":{"get":{}}}} + """), original.getPhysicalId(), original.getAttributes()); + + assertEquals("CREATE_COMPLETE", original.getStatus()); + assertEquals("CREATE_FAILED", replacement.getStatus()); + assertEquals("old-one,old-two", replacement.getAttributes().get("__FlociApiGatewayV2BodyRouteIds")); + verify(apiGatewayV2Service, never()).createRoute(eq(REGION), eq(API_ID), + argThat(request -> "GET /after".equals(request.get("routeKey")))); + verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldOne, java.util.List.of()); + verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldTwo, java.util.List.of()); + } + + @Test + void restoresExistingRoutesWhenDefinitionRemovalFails() throws Exception { + Route oldOne = route("old-one", "GET /before-one"); + Route oldTwo = route("old-two", "GET /before-two"); + when(apiGatewayV2Service.createRoute(eq(REGION), eq(API_ID), anyMap())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + Map request = invocation.getArgument(2); + return switch ((String) request.get("routeKey")) { + case "GET /before-one" -> oldOne; + case "GET /before-two" -> oldTwo; + default -> throw new AssertionError("Unexpected route key: " + request.get("routeKey")); + }; + }); + when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-one")).thenReturn(oldOne); + when(apiGatewayV2Service.getRoute(REGION, API_ID, "old-two")).thenReturn(oldTwo); + doAnswer(invocation -> { + if ("old-two".equals(invocation.getArgument(2))) { + throw new AwsException("InternalFailure", "simulated delete failure", 500); + } + return null; + }).when(apiGatewayV2Service).deleteRoute(eq(REGION), eq(API_ID), anyString()); + + StackResource original = provision(body(""" + {"paths":{"/before-one":{"get":{}},"/before-two":{"get":{}}}} + """), null, Map.of()); + + StackResource removal = provision(propertiesWithoutBody(), original.getPhysicalId(), + original.getAttributes()); + + assertEquals("CREATE_COMPLETE", original.getStatus()); + assertEquals("CREATE_FAILED", removal.getStatus()); + assertEquals("old-one,old-two", removal.getAttributes().get("__FlociApiGatewayV2BodyRouteIds")); + verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldOne, java.util.List.of()); + verify(apiGatewayV2Service).restoreRoute(REGION, API_ID, oldTwo, java.util.List.of()); + } + + private StackResource provision(JsonNode properties, String existingPhysicalId, + Map existingAttributes) { + return provisioner.provision("HttpApi", "AWS::ApiGatewayV2::Api", properties, engine(), REGION, + "000000000000", "test-stack", existingPhysicalId, existingAttributes); + } + + private JsonNode body(String body) throws Exception { + return mapper.readTree(""" + {"Name":"test-api","ProtocolType":"HTTP","Body":%s} + """.formatted(body)); + } + + private JsonNode propertiesWithoutBody() throws Exception { + return mapper.readTree(""" + {"Name":"test-api","ProtocolType":"HTTP"} + """); + } + + private CloudFormationTemplateEngine engine() { + return new CloudFormationTemplateEngine("000000000000", REGION, "test-stack", "stack/id", + Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper, + (Function) name -> null); + } + + private static Route route(String id, String routeKey) { + Route route = new Route(); + route.setRouteId(id); + route.setRouteKey(routeKey); + return route; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2CleanupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2CleanupIntegrationTest.java new file mode 100644 index 0000000000..654b70bd06 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2CleanupIntegrationTest.java @@ -0,0 +1,200 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; +import io.github.hectorvent.floci.services.apigatewayv2.model.Route; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doCallRealMethod; + +@QuarkusTest +class CloudFormationApiGatewayV2CleanupIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String ROUTE_IDS_ATTR = "__FlociApiGatewayV2BodyRouteIds"; + + @InjectSpy + ApiGatewayV2Service apiGatewayV2Service; + + @Inject + CloudFormationService cloudFormationService; + + private String stackName; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void deleteStack() { + if (stackName != null) { + doCallRealMethod().when(apiGatewayV2Service) + .deleteRoute(anyString(), anyString(), anyString()); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when() + .post("/"); + } + } + + @Test + void failedUpdatePersistsOwnershipOfAReplacementThatCleanupCouldNotDelete() { + String suffix = Long.toString(System.nanoTime(), 36); + stackName = "http-api-cleanup-" + suffix; + String apiName = "http-api-cleanup-" + suffix; + + createStack(httpApiTemplate(apiName, List.of("/before"))); + waitForStackStatus("CREATE_COMPLETE"); + String apiId = apiIdForName(apiName); + String oldRouteId = apiGatewayV2Service.findRouteByKey(REGION, apiId, "GET /before").getRouteId(); + + AtomicReference survivingRouteId = new AtomicReference<>(); + doAnswer(invocation -> { + @SuppressWarnings("unchecked") + Map request = invocation.getArgument(2); + if ("GET /fail".equals(request.get("routeKey"))) { + throw new AwsException("InternalFailure", "simulated route failure", 500); + } + Route route = (Route) invocation.callRealMethod(); + if ("GET /survivor".equals(route.getRouteKey())) { + survivingRouteId.set(route.getRouteId()); + } + return route; + }).when(apiGatewayV2Service).createRoute(eq(REGION), eq(apiId), anyMap()); + doAnswer(invocation -> { + String routeId = invocation.getArgument(2); + if (routeId.equals(survivingRouteId.get())) { + throw new AwsException("InternalFailure", "simulated cleanup failure", 500); + } + return invocation.callRealMethod(); + }).when(apiGatewayV2Service).deleteRoute(eq(REGION), eq(apiId), anyString()); + + updateStack(httpApiTemplate(apiName, List.of("/survivor", "/fail"))); + waitForStackStatus("UPDATE_ROLLBACK_COMPLETE"); + + StackResource persisted = cloudFormationService.describeStacks(stackName, REGION) + .getFirst().getResources().get("HttpApi"); + assertEquals("CREATE_COMPLETE", persisted.getStatus()); + assertTrue(Arrays.asList(persisted.getAttributes().get(ROUTE_IDS_ATTR).split(",")) + .containsAll(List.of(oldRouteId, survivingRouteId.get()))); + } + + @Test + void failedSnapshotRestorationMarksUpdateRollbackFailed() { + String suffix = Long.toString(System.nanoTime(), 36); + stackName = "http-api-restore-failure-" + suffix; + String apiName = "http-api-restore-failure-" + suffix; + + createStack(httpApiTemplate(apiName, List.of("/before"))); + waitForStackStatus("CREATE_COMPLETE"); + String apiId = apiIdForName(apiName); + String oldRouteId = apiGatewayV2Service.findRouteByKey(REGION, apiId, "GET /before").getRouteId(); + + AtomicReference independentRouteId = new AtomicReference<>(); + doAnswer(invocation -> { + @SuppressWarnings("unchecked") + Map request = invocation.getArgument(2); + if ("GET /fail".equals(request.get("routeKey"))) { + Route independent = apiGatewayV2Service.createRoute( + REGION, apiId, Map.of("routeKey", "GET /before")); + independentRouteId.set(independent.getRouteId()); + throw new AwsException("InternalFailure", "simulated route failure", 500); + } + return invocation.callRealMethod(); + }).when(apiGatewayV2Service).createRoute(eq(REGION), eq(apiId), anyMap()); + + updateStack(httpApiTemplate(apiName, List.of("/fail"))); + waitForStackStatus("UPDATE_ROLLBACK_FAILED"); + + Route independent = apiGatewayV2Service.findRouteByKey(REGION, apiId, "GET /before"); + assertEquals(independentRouteId.get(), independent.getRouteId()); + assertThrows(AwsException.class, + () -> apiGatewayV2Service.getRoute(REGION, apiId, oldRouteId)); + } + + private void createStack(String template) { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + } + + private void updateStack(String template) { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + } + + private void waitForStackStatus(String expected) { + for (int attempt = 0; attempt < 100; attempt++) { + String status = cloudFormationService.describeStacks(stackName, REGION).getFirst().getStatus(); + if (expected.equals(status)) { + return; + } + try { + Thread.sleep(25); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError("Interrupted while waiting for stack status", e); + } + } + throw new AssertionError("Stack did not reach " + expected); + } + + private static String apiIdForName(String apiName) { + return given() + .when() + .get("/v2/apis") + .then() + .statusCode(200) + .extract() + .path("items.find { it.name == '" + apiName + "' }.apiId"); + } + + private static String httpApiTemplate(String apiName, List paths) { + String pathDefinitions = paths.stream() + .map(path -> "\"" + path + "\":{\"get\":{}}") + .collect(java.util.stream.Collectors.joining(",")); + return """ + {"AWSTemplateFormatVersion":"2010-09-09", + "Transform":"AWS::Serverless-2016-10-31", + "Resources":{"HttpApi":{"Type":"AWS::Serverless::HttpApi","Properties":{ + "Name":"%s","DefinitionBody":{"openapi":"3.0.1","paths":{%s}} + }}}} + """.formatted(apiName, pathDefinitions); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java index b3c8003764..1a0a98da98 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java @@ -13,7 +13,10 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; @QuarkusTest @@ -466,6 +469,272 @@ class SamTransformIntegrationTest { assertThat(resourcesXml, not(containsString("AWS::Serverless::Api"))); } + @Test + void samHttpApi_definitionBodyCreatesApiGatewayV2Routes() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sam-http-api-" + suffix; + String apiName = "sam-http-api-" + suffix; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + HttpApi: + Type: AWS::Serverless::HttpApi + Properties: + Name: %s + DefinitionBody: + openapi: 3.0.1 + paths: + /hello: + get: {} + /widgets: + post: {} + """.formatted(apiName); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + waitForStackStatus(stackName, "CREATE_COMPLETE"); + + String apiId = given() + .when() + .get("/v2/apis") + .then() + .statusCode(200) + .body("items.find { it.name == '" + apiName + "' }.protocolType", equalTo("HTTP")) + .extract() + .path("items.find { it.name == '" + apiName + "' }.apiId"); + + given() + .when() + .get("/v2/apis/" + apiId + "/routes") + .then() + .statusCode(200) + .body("items.routeKey", hasItems("GET /hello", "POST /widgets")); + } + + @Test + void samHttpApi_matchingDefinitionBodyAndFunctionEventCreateOneIntegratedRoute() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sam-http-api-overlap-" + suffix; + String apiName = "sam-http-api-overlap-" + suffix; + String functionName = "sam-http-overlap-fn-" + suffix; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + HttpApi: + Type: AWS::Serverless::HttpApi + Properties: + Name: %s + Auth: + DefaultAuthorizer: JwtAuth + Authorizers: + JwtAuth: + IdentitySource: '$request.header.Authorization' + AuthorizationScopes: [read:items] + JwtConfiguration: + issuer: https://issuer.example.com + audience: [items-client] + DefinitionBody: + openapi: 3.0.1 + info: {title: overlap, version: '1.0'} + components: {} + paths: + /items: + get: + responses: {'200': {description: ok}} + Handler: + Type: AWS::Serverless::Function + Properties: + FunctionName: %s + Runtime: python3.12 + Handler: index.handler + InlineCode: 'def handler(e,c): return {}' + Events: + Api: + Type: HttpApi + Properties: + ApiId: {Ref: HttpApi} + Path: /items + Method: GET + """.formatted(apiName, functionName); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + waitForStackStatus(stackName, "CREATE_COMPLETE"); + String apiId = apiIdForName(apiName); + + given() + .when() + .get("/v2/apis/" + apiId + "/routes") + .then() + .statusCode(200) + .body("items.size()", equalTo(1)) + .body("items[0].routeKey", equalTo("GET /items")) + .body("items[0].authorizationType", equalTo("JWT")) + .body("items[0].authorizationScopes", hasItem("read:items")) + .body("items[0].authorizerId", notNullValue()) + .body("items[0].target", containsString("integrations/")); + + given() + .when() + .get("/v2/apis/" + apiId + "/integrations") + .then() + .statusCode(200) + .body("items.size()", equalTo(1)) + .body("items[0].integrationUri", containsString(functionName)); + } + + @Test + void samHttpApi_intrinsicDefinitionUriCreatesApiGatewayV2Routes() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sam-http-api-uri-" + suffix; + String apiName = "sam-http-api-uri-" + suffix; + String bucketName = "sam-http-api-spec-" + suffix; + stacksToDelete.add(stackName); + + given() + .when() + .put("/" + bucketName) + .then() + .statusCode(200); + + given() + .contentType("application/json") + .body(""" + {"openapi":"3.0.1","paths":{"/from-uri":{"get":{}}}} + """) + .when() + .put("/" + bucketName + "/openapi.json") + .then() + .statusCode(200); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + HttpApi: + Type: AWS::Serverless::HttpApi + Properties: + Name: %s + DefinitionUri: + Fn::Sub: s3://%s/openapi.json + """.formatted(apiName, bucketName); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + waitForStackStatus(stackName, "CREATE_COMPLETE"); + + String apiId = apiIdForName(apiName); + given() + .when() + .get("/v2/apis/" + apiId + "/routes") + .then() + .statusCode(200) + .body("items.routeKey", hasItem("GET /from-uri")); + } + + @Test + void samHttpApi_definitionBodyReconcilesRoutesOnStackUpdate() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "sam-http-api-update-" + suffix; + String apiName = "sam-http-api-update-" + suffix; + stacksToDelete.add(stackName); + + String initialTemplate = httpApiTemplate(apiName, "/before"); + String updatedTemplate = httpApiTemplate(apiName, "/after"); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", initialTemplate) + .when() + .post("/") + .then() + .statusCode(200); + + waitForStackStatus(stackName, "CREATE_COMPLETE"); + String apiId = apiIdForName(apiName); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", updatedTemplate) + .when() + .post("/") + .then() + .statusCode(200); + + waitForStackStatus(stackName, "UPDATE_COMPLETE"); + + given() + .when() + .get("/v2/apis/" + apiId + "/routes") + .then() + .statusCode(200) + .body("items.routeKey", hasItem("GET /after")) + .body("items.routeKey", not(hasItem("GET /before"))); + } + + private static String httpApiTemplate(String apiName, String path) { + return """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + HttpApi: + Type: AWS::Serverless::HttpApi + Properties: + Name: %s + DefinitionBody: + openapi: 3.0.1 + paths: + %s: + get: {} + """.formatted(apiName, path); + } + + private static String apiIdForName(String apiName) { + return given() + .when() + .get("/v2/apis") + .then() + .statusCode(200) + .body("items.find { it.name == '" + apiName + "' }.protocolType", equalTo("HTTP")) + .extract() + .path("items.find { it.name == '" + apiName + "' }.apiId"); + } + @Test void samFunction_withCodeUri_s3Reference() { String stackName = "sam-s3code-stack"; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java index 25be1e1117..59203d5873 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java @@ -897,4 +897,235 @@ class SamTransformProcessorTest { assertTrue(expanded.path("Transform").isMissingNode()); assertTrue(expanded.path("Globals").isMissingNode()); } + @Test + void expandSamTemplate_httpApiPreservesDefinitionBodyAsRoutes() throws Exception { + // Regression for #1956: a route-bearing HttpApi carries its routes in the inline + // OpenAPI DefinitionBody, which must survive as the ApiGatewayV2::Api Body — otherwise + // the API expands with no routes. + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "DefinitionBody": { + "openapi": "3.0.1", + "paths": { + "/hello": { "get": { "x-amazon-apigateway-integration": { "type": "aws_proxy" } } } + } + } + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + + JsonNode api = resources.path("MyHttpApi"); + assertEquals("AWS::ApiGatewayV2::Api", api.path("Type").asText()); + JsonNode body = api.path("Properties").path("Body"); + assertFalse(body.isMissingNode(), "DefinitionBody must be preserved as the API Body"); + assertEquals("3.0.1", body.path("openapi").asText()); + assertTrue(body.path("paths").has("/hello"), "route definitions must survive the transform"); + } + + @Test + void expandSamTemplate_httpApiEventMergesIntoMatchingDefinitionBodyOperation() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "Auth": { + "DefaultAuthorizer": "JwtAuth", + "Authorizers": { + "JwtAuth": { + "IdentitySource": "$request.header.Authorization", + "AuthorizationScopes": ["read:items"], + "JwtConfiguration": { + "Issuer": "https://issuer.example.com", + "Audience": ["items-client"] + } + } + } + }, + "DefinitionBody": { + "openapi": "3.0.1", + "paths": { + "/items": { + "get": { + "security": [], + "responses": { "200": { "description": "ok" } } + } + } + } + } + } + }, + "MyFunction": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e,c): return {}", + "Events": { + "Api": { + "Type": "HttpApi", + "Properties": { + "ApiId": { "Ref": "MyHttpApi" }, + "Path": "/items", + "Method": "GET" + } + } + } + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + JsonNode operation = resources.path("MyHttpApi").path("Properties").path("Body") + .path("paths").path("/items").path("get"); + JsonNode integration = operation.path("x-amazon-apigateway-integration"); + JsonNode authorizer = resources.path("MyHttpApi").path("Properties").path("Body") + .path("components").path("securitySchemes").path("JwtAuth"); + + assertEquals("ok", operation.path("responses").path("200").path("description").asText()); + assertEquals("aws_proxy", integration.path("type").asText()); + assertEquals("POST", integration.path("httpMethod").asText()); + assertEquals("2.0", integration.path("payloadFormatVersion").asText()); + assertEquals("MyFunction", integration.path("uri").path("Fn::Sub").path(1) + .path("FnArn").path("Fn::GetAtt").path(0).asText()); + assertEquals("oauth2", authorizer.path("type").asText()); + assertEquals("jwt", authorizer.path("x-amazon-apigateway-authorizer").path("type").asText()); + assertEquals("$request.header.Authorization", authorizer.path("x-amazon-apigateway-authorizer") + .path("identitySource").path(0).asText()); + assertEquals("https://issuer.example.com", authorizer.path("x-amazon-apigateway-authorizer") + .path("jwtConfiguration").path("issuer").asText()); + assertEquals("items-client", authorizer.path("x-amazon-apigateway-authorizer") + .path("jwtConfiguration").path("audience").path(0).asText()); + assertEquals("read:items", operation.path("security").path(0).path("JwtAuth").path(0).asText()); + + int routeResources = 0; + int integrationResources = 0; + int permissionResources = 0; + Iterator definitions = resources.elements(); + while (definitions.hasNext()) { + String type = definitions.next().path("Type").asText(); + routeResources += "AWS::ApiGatewayV2::Route".equals(type) ? 1 : 0; + integrationResources += "AWS::ApiGatewayV2::Integration".equals(type) ? 1 : 0; + permissionResources += "AWS::Lambda::Permission".equals(type) ? 1 : 0; + } + assertEquals(0, routeResources, "matching body operations must not emit a duplicate route resource"); + assertEquals(0, integrationResources, "the body owns the merged integration"); + assertEquals(1, permissionResources, "API Gateway still needs permission to invoke the function"); + } + + @Test + void expandSamTemplate_matchingHttpApiEventCanOptOutOfDefaultAuthorizer() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "HttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "Auth": { + "DefaultAuthorizer": "JwtAuth", + "Authorizers": { + "JwtAuth": { + "IdentitySource": ["$request.header.Authorization"], + "JwtConfiguration": { + "issuer": "https://issuer.example.com", + "audience": ["client-id"] + } + } + } + }, + "DefinitionBody": { + "openapi": "3.0.1", + "paths": { "/public": { "get": {} } } + } + } + }, + "Handler": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e,c): return {}", + "Events": { + "Public": { + "Type": "HttpApi", + "Properties": { + "ApiId": { "Ref": "HttpApi" }, + "Path": "/public", + "Method": "GET", + "Auth": { "Authorizer": "NONE" } + } + } + } + } + } + } + } + """); + + JsonNode operation = processor.expandSamTemplate(template).path("Resources") + .path("HttpApi").path("Properties").path("Body") + .path("paths").path("/public").path("get"); + + assertTrue(operation.path("security").isArray()); + assertTrue(operation.path("security").isEmpty(), + "Authorizer NONE must override the API's default authorizer"); + assertTrue(operation.path("x-amazon-apigateway-integration").isObject()); + } + + @Test + void expandSamTemplate_httpApiMapsDefinitionUriToBodyS3Location() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { "DefinitionUri": "s3://api-specs/openapi.yaml" } + } + } + } + """); + + JsonNode properties = processor.expandSamTemplate(template) + .path("Resources").path("MyHttpApi").path("Properties"); + + assertTrue(properties.path("Body").isMissingNode(), "DefinitionUri must not become an inline Body"); + assertEquals("api-specs", properties.path("BodyS3Location").path("Bucket").asText()); + assertEquals("openapi.yaml", properties.path("BodyS3Location").path("Key").asText()); + } + @Test + void expandSamTemplate_httpApiPreservesIntrinsicDefinitionUriForProvisioning() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyHttpApi": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "DefinitionUri": { "Fn::Sub": "s3://${SpecBucket}/openapi.yaml" } + } + } + } + } + """); + + JsonNode bodyS3Location = processor.expandSamTemplate(template) + .path("Resources").path("MyHttpApi").path("Properties").path("BodyS3Location"); + + assertEquals("s3://${SpecBucket}/openapi.yaml", bodyS3Location.path("Fn::Sub").asText()); + } }