feat(cloudformation): expand SAM AWS::Serverless::HttpApi to ApiGatew… (#1956)

* 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 '<id>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 <id>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
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-08-23 15:20:20 -04:00
1 parent 0e3391cac2
commit 6fa53abd7c
9 files changed
+2190 -8

No files matched your search

@@ -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<String, Object> request) {
Authorizer auth = getAuthorizer(region, apiId, authorizerId);
@@ -356,9 +372,11 @@ public class ApiGatewayV2Service {
public Route createRoute(String region, String apiId, Map<String, Object> 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<String> 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<String, Object> 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<String, Object> request) {
Integration integration = getIntegration(region, apiId, integrationId);
@@ -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<String> routeIds = new ArrayList<>();
List<String> integrationIds = new ArrayList<>();
List<String> authorizerIds = new ArrayList<>();
try {
Map<String, OpenApiAuthorizerBinding> authorizers = materializeApiGatewayV2BodyAuthorizers(
region, apiId, body, authorizerIds);
JsonNode paths = body.path("paths");
if (!paths.isObject()) {
return new ApiGatewayV2BodyResources(routeIds, integrationIds, authorizerIds);
}
Iterator<Map.Entry<String, JsonNode>> pathEntries = paths.fields();
while (pathEntries.hasNext()) {
Map.Entry<String, JsonNode> pathEntry = pathEntries.next();
if (!pathEntry.getValue().isObject()) {
continue;
}
Iterator<Map.Entry<String, JsonNode>> operations = pathEntry.getValue().fields();
while (operations.hasNext()) {
Map.Entry<String, JsonNode> operation = operations.next();
String method = operation.getKey();
if (!isHttpApiOperation(method) || !operation.getValue().isObject()) {
continue;
}
Map<String, Object> 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<String, Object> 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<RuntimeException> cleanupFailures = cleanupApiGatewayV2BodyResources(region, apiId, partial);
if (!cleanupFailures.isEmpty()) {
cleanupFailures.forEach(e::addSuppressed);
throw new ApiGatewayV2BodyMaterializationException(e, partial);
}
throw e;
}
}
private Map<String, OpenApiAuthorizerBinding> materializeApiGatewayV2BodyAuthorizers(
String region, String apiId, JsonNode body, List<String> authorizerIds) {
Map<String, OpenApiAuthorizerBinding> bindings = new LinkedHashMap<>();
JsonNode schemes = body.path("components").path("securitySchemes");
if (!schemes.isObject()) {
return bindings;
}
Iterator<Map.Entry<String, JsonNode>> entries = schemes.fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> 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<String, Object> 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<String, Object> 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<String, OpenApiAuthorizerBinding> authorizers,
Map<String, Object> 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<Map.Entry<String, JsonNode>> schemes = requirement.fields();
while (schemes.hasNext()) {
Map.Entry<String, JsonNode> 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<String> 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<String, Object> 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<String, Object> 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<String> 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<String> 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<Route> 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<Integration> 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<Authorizer> 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<RuntimeException> 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<RuntimeException> cleanupApiGatewayV2BodyResources(String region, String apiId,
ApiGatewayV2BodyResources resources) {
List<RuntimeException> 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<String> resourceIds) {
LinkedHashSet<String> retained = new LinkedHashSet<>(apiGatewayV2BodyResourceIds(r, attributeName));
retained.addAll(resourceIds);
storeApiGatewayV2BodyResourceIds(r, attributeName, new ArrayList<>(retained));
}
private static List<String> 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<String> 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<String> routeIds, List<String> integrationIds,
List<String> authorizerIds) {}
private record ApiGatewayV2BodyResourceState(List<Route> routes, List<Integration> integrations,
List<Authorizer> 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<String, Object> request, String requestKey,
JsonNode integration, String openApiKey) {
String value = textOrNull(integration, openApiKey);
if (value != null) {
request.put(requestKey, value);
}
}
private Map<String, String> parseApiGatewayV2Tags(JsonNode tagsNode, CloudFormationTemplateEngine engine) {
@@ -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)) {
@@ -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()) {