fix(cloudformation): reconcile API Gateway V2 credentials (#9685)

Apply integration and authorizer credential ARNs during stack creation and updates. Clear only credentials removed from previously declared template properties, preserve externally configured values, and restore integration credentials during rollback. Preserve current integration subtype defaults and rollback behavior.

Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
Signed-off-by: Andre Kurait <akurait@amazon.com>
Signed-off-by: Jackson Price <jxnprice@amazon.com>
This commit is contained in:
Jackson PriceandAndre Kurait authored and GitHub committed 2026-11-28 18:39:09 -04:00
1 parent 986d774bdf
commit e36c5a39e3
12 files changed
+445 -47

No files matched your search

+4 -3
View File
@@ -903,9 +903,10 @@ HTTP targets. OpenAPI import and CloudFormation API `Body` map the integration
`credentials` and authorizer `authorizerCredentials` extensions to these fields.
Integration copies and authorizer restore paths retain them too.
This models credential selection; execution-role assumption and credential-based
Lambda invocation authorization are not implemented by this change. Dedicated
CloudFormation credential properties remain outside this support.
CloudFormation accepts `CredentialsArn` on integrations and `AuthorizerCredentialsArn` on
request authorizers. Updating a credential role preserves the resource ID. Removing the
property clears the role if the stack previously set it. If a stack update fails, rollback
restores the previous integration and authorizer roles, including an absent role.
**Protocol:** REST JSON
**Endpoint:** `http://localhost:4566/v2/apis/...`
@@ -498,21 +498,21 @@ public class ApiGatewayV2Service {
}
/**
* Sets the URI, payload format version, JWT configuration, result TTL and simple-responses flag
* exactly as given, null included. UpdateAuthorizer keeps a field the request leaves out, so it
* cannot remove one that CloudFormation dropped.
* Sets the template-owned authorizer settings exactly as given, including nulls.
* UpdateAuthorizer preserves omitted fields, so CloudFormation clears removed properties here.
*/
public Authorizer replaceAuthorizerSettings(String region, String apiId, String authorizerId,
String authorizerUri, String authorizerPayloadFormatVersion,
Authorizer.JwtConfiguration jwtConfiguration,
Integer authorizerResultTtlInSeconds,
Boolean enableSimpleResponses) {
Boolean enableSimpleResponses, String credentialsArn) {
Authorizer auth = getAuthorizer(region, apiId, authorizerId);
auth.setAuthorizerUri(authorizerUri);
auth.setAuthorizerPayloadFormatVersion(authorizerPayloadFormatVersion);
auth.setJwtConfiguration(jwtConfiguration);
auth.setAuthorizerResultTtlInSeconds(authorizerResultTtlInSeconds);
auth.setEnableSimpleResponses(enableSimpleResponses);
auth.setAuthorizerCredentialsArn(credentialsArn);
authorizerStore.put(authorizerKey(region, apiId, authorizerId), auth);
return auth;
}
@@ -853,6 +853,14 @@ public class ApiGatewayV2Service {
new Integration(integration));
}
/** Replaces template-owned credentials, including clearing a removed CloudFormation property. */
public void replaceIntegrationCredentials(String region, String apiId, String integrationId,
String credentialsArn) {
Integration resource = new Integration(getIntegration(region, apiId, integrationId));
resource.setCredentialsArn(credentialsArn);
integrationStore.put(integrationKey(region, apiId, integrationId), resource);
}
public Integration updateIntegration(String region, String apiId, String integrationId,
Map<String, Object> request) {
Integration integration = getIntegration(region, apiId, integrationId);
@@ -55,6 +55,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
private static final String DEPLOYMENT = "AWS::ApiGatewayV2::Deployment";
private static final String VPC_LINK = "AWS::ApiGatewayV2::VpcLink";
private static final String AUTHORIZER_SNAPSHOT = CfnRollback.API_GATEWAY_V2_AUTHORIZER_UPDATE_SNAPSHOT_ATTR;
private static final String BODY_ROUTE_IDS_ATTR = "__FlociApiGatewayV2BodyRouteIds";
private static final String BODY_INTEGRATION_IDS_ATTR = "__FlociApiGatewayV2BodyIntegrationIds";
private static final String BODY_AUTHORIZER_IDS_ATTR = "__FlociApiGatewayV2BodyAuthorizerIds";
@@ -148,6 +149,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(AUTHORIZER_SNAPSHOT);
resource.getAttributes().remove(CfnRollback.VPC_LINK_UPDATE_SNAPSHOT_ATTR);
resource.getAttributes().remove(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
@@ -158,6 +160,9 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
if (ReplacementCleanup.rollback(resource, this::delete)) {
return true;
}
if (AUTHORIZER.equals(resource.getResourceType())) {
return rollbackAuthorizerUpdate(resource);
}
if (VPC_LINK.equals(resource.getResourceType())) {
return rollbackVpcLinkUpdate(resource);
}
@@ -169,6 +174,10 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
@Override
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
if (AUTHORIZER.equals(previous.getResourceType())) {
CfnRollback.carryFailedUndoSnapshot(previous, attempted, AUTHORIZER_SNAPSHOT);
return;
}
// Only the Api carries body-generated sub-resource ids; keep any the failed attempt created
// so the restored resource still owns them for the next cleanup or stack delete.
if (!API.equals(previous.getResourceType())) {
@@ -831,6 +840,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
req.put("authorizerType", ctx.resolveOptional(props, "AuthorizerType"));
req.put("identitySource", resolveIdentitySource(props, "IdentitySource", engine));
req.put("authorizerUri", ctx.resolveOptional(props, "AuthorizerUri"));
req.put("authorizerCredentialsArn", ctx.resolveOptional(props, "AuthorizerCredentialsArn"));
req.put("authorizerPayloadFormatVersion", ctx.resolveOptional(props, "AuthorizerPayloadFormatVersion"));
String ttl = ctx.resolveOptional(props, "AuthorizerResultTtlInSeconds");
@@ -855,34 +865,68 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
req.put("jwtConfiguration", jwtConfig);
}
Authorizer authorizer;
if (r.getPhysicalId() == null) {
authorizer = apiGatewayV2Service.createAuthorizer(region, apiId, req);
} else {
authorizer = apiGatewayV2Service.updateAuthorizer(region, apiId, r.getPhysicalId(), req);
r.getAttributes().remove(AUTHORIZER_SNAPSHOT);
String authorizerId;
if (ctx.isUpdate()) {
authorizerId = ctx.priorPhysicalId();
Set<String> dropped = ctx.droppedProperties(props);
if (dropped.contains("AuthorizerUri") || dropped.contains("AuthorizerPayloadFormatVersion")
|| dropped.contains("JwtConfiguration") || dropped.contains("AuthorizerResultTtlInSeconds")
|| dropped.contains("EnableSimpleResponses")) {
// UpdateAuthorizer keeps a field it is not given, so a dropped one is cleared here and
// the others keep what the update left, a value set outside the stack included.
authorizer = apiGatewayV2Service.replaceAuthorizerSettings(region, apiId, r.getPhysicalId(),
dropped.contains("AuthorizerUri") ? null : authorizer.getAuthorizerUri(),
dropped.contains("AuthorizerPayloadFormatVersion")
? null : authorizer.getAuthorizerPayloadFormatVersion(),
dropped.contains("JwtConfiguration") ? null : authorizer.getJwtConfiguration(),
dropped.contains("AuthorizerResultTtlInSeconds")
? null : authorizer.getAuthorizerResultTtlInSeconds(),
dropped.contains("EnableSimpleResponses")
? null : authorizer.getEnableSimpleResponses());
if (req.get("authorizerCredentialsArn") != null || dropped.contains("AuthorizerCredentialsArn")) {
rememberAuthorizer(r, region, apiId, authorizerId);
CfnRollback.guarded(r, ctx, false, () -> { }, () -> rollbackAuthorizerUpdate(r),
() -> updateAuthorizer(region, apiId, authorizerId, req, dropped));
} else {
updateAuthorizer(region, apiId, authorizerId, req, dropped);
}
} else {
authorizerId = apiGatewayV2Service.createAuthorizer(region, apiId, req).getAuthorizerId();
}
r.setPhysicalId(authorizer.getAuthorizerId());
r.getAttributes().put("AuthorizerId", authorizer.getAuthorizerId());
// ApiId is needed by delete() to scope deleteAuthorizer; the id-only delete path has none.
r.setPhysicalId(authorizerId);
r.getAttributes().put("AuthorizerId", authorizerId);
r.getAttributes().put("ApiId", apiId);
}
private void rememberAuthorizer(StackResource resource, String region, String apiId, String authorizerId) {
Authorizer prior = apiGatewayV2Service.getAuthorizer(region, apiId, authorizerId);
ObjectNode snapshot = objectMapper.createObjectNode();
snapshot.put("region", region);
snapshot.put("apiId", apiId);
snapshot.set("authorizer", objectMapper.valueToTree(prior));
resource.getAttributes().put(AUTHORIZER_SNAPSHOT, snapshot.toString());
}
private void updateAuthorizer(String region, String apiId, String authorizerId, Map<String, Object> req,
Set<String> dropped) {
Authorizer authorizer = apiGatewayV2Service.updateAuthorizer(region, apiId, authorizerId, req);
if (dropped.contains("AuthorizerUri") || dropped.contains("AuthorizerPayloadFormatVersion")
|| dropped.contains("JwtConfiguration") || dropped.contains("AuthorizerResultTtlInSeconds")
|| dropped.contains("EnableSimpleResponses") || dropped.contains("AuthorizerCredentialsArn")) {
// UpdateAuthorizer keeps a field it is not given, so a dropped one is cleared here and
// the others keep what the update left, a value set outside the stack included.
apiGatewayV2Service.replaceAuthorizerSettings(region, apiId, authorizerId,
dropped.contains("AuthorizerUri") ? null : authorizer.getAuthorizerUri(),
dropped.contains("AuthorizerPayloadFormatVersion")
? null : authorizer.getAuthorizerPayloadFormatVersion(),
dropped.contains("JwtConfiguration") ? null : authorizer.getJwtConfiguration(),
dropped.contains("AuthorizerResultTtlInSeconds")
? null : authorizer.getAuthorizerResultTtlInSeconds(),
dropped.contains("EnableSimpleResponses")
? null : authorizer.getEnableSimpleResponses(),
dropped.contains("AuthorizerCredentialsArn") ? null : authorizer.getAuthorizerCredentialsArn());
}
}
private boolean rollbackAuthorizerUpdate(StackResource resource) {
JsonNode snapshot = CfnRollback.updateSnapshot(resource, AUTHORIZER_SNAPSHOT);
if (snapshot == null) {
return false;
}
Authorizer prior = objectMapper.convertValue(snapshot.required("authorizer"), Authorizer.class);
apiGatewayV2Service.restoreAuthorizer(snapshot.required("region").asText(),
snapshot.required("apiId").asText(), prior);
resource.getAttributes().remove(AUTHORIZER_SNAPSHOT);
return true;
}
// ── Route ────────────────────────────────────────────────────────────────
private void provisionRoute(StackResource r, JsonNode props, ProvisionContext ctx) {
@@ -929,6 +973,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
req.put("integrationType", ctx.resolveOptional(props, "IntegrationType"));
req.put("integrationSubtype", integrationSubtype);
req.put("integrationUri", ctx.resolveOptional(props, "IntegrationUri"));
req.put("credentialsArn", ctx.resolveOptional(props, "CredentialsArn"));
req.put("payloadFormatVersion", ctx.resolveOrDefault(props, "PayloadFormatVersion",
ApiGatewayV2Service.defaultPayloadFormatVersion(integrationSubtype)));
String connectionType = ctx.resolveOptional(props, "ConnectionType");
@@ -970,8 +1015,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
Integration prior = apiGatewayV2Service.getIntegration(region, apiId, r.getPhysicalId());
r.getAttributes().put(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR,
integrationConnectionSnapshot(region, apiId, prior, req));
// The connection changes first, in one call. If the update after it fails, the connection
// is the only change to undo.
// Restore the tracked fields if a later part of this update fails.
try {
// A connection removed from the template is removed here too. INTERNET is the AWS default.
apiGatewayV2Service.replaceIntegrationConnection(region, apiId, r.getPhysicalId(),
@@ -986,6 +1030,9 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
apiGatewayV2Service.replaceIntegrationSubtype(region, apiId, r.getPhysicalId(), null);
}
integration = apiGatewayV2Service.updateIntegration(region, apiId, r.getPhysicalId(), req);
if (ctx.droppedProperties(props).contains("CredentialsArn")) {
apiGatewayV2Service.replaceIntegrationCredentials(region, apiId, r.getPhysicalId(), null);
}
} catch (RuntimeException failure) {
// The stack skips rollbackUpdate for a resource whose own update failed, so undo it here.
try {
@@ -1006,7 +1053,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
}
/**
* The connection, the five settings and the subtype the integration had before this update, and
* The connection, settings, subtype and credentials the integration had before this update, and
* whether the update also changes another field. UpdateIntegration keeps a field the request
* leaves out, so only a value that is set and differs counts as a change.
*/
@@ -1027,6 +1074,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
snapshot.set("responseParameters", objectMapper.valueToTree(prior.getResponseParameters()));
snapshot.set("requestTemplates", objectMapper.valueToTree(prior.getRequestTemplates()));
snapshot.put("integrationSubtype", prior.getIntegrationSubtype());
snapshot.put("credentialsArn", prior.getCredentialsArn());
snapshot.put("otherFieldChanged", otherFieldChanged);
return snapshot.toString();
}
@@ -1036,7 +1084,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
}
/**
* Puts the connection and the settings back from the snapshot taken before the update. Answers
* Puts the connection, settings and credentials back from the snapshot taken before the update. Answers
* true only when the update changed nothing else: this provisioner keeps no copy of the other
* fields, so the stack must still report that their rollback is not implemented.
*/
@@ -1067,6 +1115,11 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
snapshot.path("apiId").asText(), resource.getPhysicalId(),
textOrNull(snapshot, "integrationSubtype"));
}
if (snapshot.has("credentialsArn")) {
apiGatewayV2Service.replaceIntegrationCredentials(snapshot.path("region").asText(),
snapshot.path("apiId").asText(), resource.getPhysicalId(),
textOrNull(snapshot, "credentialsArn"));
}
// Spent only once the restore succeeded, so a restore that throws can be tried again.
resource.getAttributes().remove(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR);
return !snapshot.path("otherFieldChanged").asBoolean();
@@ -351,6 +351,9 @@ public final class CfnRollback {
*/
public static final String VPC_LINK_UPDATE_SNAPSHOT_ATTR = "__FlociVpcLinkUpdateSnapshot";
/** The API Gateway V2 authorizer settings, including its optional role, before an in-place update. */
public static final String API_GATEWAY_V2_AUTHORIZER_UPDATE_SNAPSHOT_ATTR = "__FlociApiGatewayV2AuthorizerUpdate";
/**
* Holds the connection type and id an API Gateway V2 integration carried before an update, and
* whether that update also changed another field, so a failed stack update can put the
@@ -0,0 +1,253 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.Stack;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
import software.amazon.awssdk.services.apigatewayv2.model.NotFoundException;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.failingResourceAfter;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stack;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stackAction;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class ApiGatewayV2CfnCredentialsIntegrationTest {
private static final String ROLE = "arn:aws:iam::000000000000:role/gateway";
private static final String OTHER = "arn:aws:iam::000000000000:role/replacement";
@TestHTTPResource
URI endpoint;
@Inject
CloudFormationService cloudFormation;
@ParameterizedTest
@ValueSource(strings = {"HTTP", "WEBSOCKET"})
void templateCredentialsUpdateAndRemovalKeepResourceIds(String protocol) {
try (ApiGatewayV2Client api = api()) {
String name = "v2-credentials-" + UUID.randomUUID();
String apiId;
try (StackCleanup cleanup = new StackCleanup(name)) {
stackAction("CreateStack", name, template(protocol, ROLE, ROLE, false));
Map<String, String> ids = outputs(waitFor(name, "CREATE_COMPLETE"));
apiId = ids.get("Api");
assertEquals(ids.get("Integration"), ids.get("IntegrationAttr"));
assertEquals(ids.get("Authorizer"), ids.get("AuthorizerAttr"));
assertCredentials(api, ids, ROLE, ROLE);
// Ordinary management updates omit credentials and must retain them.
api.updateIntegration(b -> b.apiId(ids.get("Api")).integrationId(ids.get("Integration"))
.description("unchanged credentials"));
api.updateAuthorizer(b -> b.apiId(ids.get("Api")).authorizerId(ids.get("Authorizer"))
.name("renamed"));
assertCredentials(api, ids, ROLE, ROLE);
for (String credentials : new String[]{OTHER, "arn:aws:iam::*:user/*", null}) {
String authorizerCredentials = credentials == null ? null : OTHER;
stackAction("UpdateStack", name, template(protocol, credentials, authorizerCredentials, false));
assertEquals(ids, outputs(waitFor(name, "UPDATE_COMPLETE")));
assertCredentials(api, ids, credentials, authorizerCredentials);
}
}
assertThrows(NotFoundException.class, () -> api.getApi(b -> b.apiId(apiId)));
}
}
@ParameterizedTest
@ValueSource(strings = {"HTTP", "WEBSOCKET"})
void updatingBothChildrenPreservesCredentialsSetOutsideStack(String protocol) {
try (ApiGatewayV2Client api = api()) {
String name = "v2-external-credentials-" + UUID.randomUUID();
String apiId;
try (StackCleanup cleanup = new StackCleanup(name)) {
String original = template(protocol, null, null, false);
stackAction("CreateStack", name, original);
Map<String, String> ids = outputs(waitFor(name, "CREATE_COMPLETE"));
apiId = ids.get("Api");
api.updateIntegration(b -> b.apiId(apiId).integrationId(ids.get("Integration"))
.credentialsArn(ROLE));
api.updateAuthorizer(b -> b.apiId(apiId).authorizerId(ids.get("Authorizer"))
.authorizerCredentialsArn(OTHER));
assertCredentials(api, ids, ROLE, OTHER);
String updated = original.replace("\"IntegrationMethod\":\"POST\"",
"\"IntegrationMethod\":\"POST\",\"TimeoutInMillis\":12000")
.replace("\"Name\":\"auth\"", "\"Name\":\"renamed authorizer\"");
stackAction("UpdateStack", name, updated);
assertEquals(ids, outputs(waitFor(name, "UPDATE_COMPLETE")));
assertEquals(12000, api.getIntegration(b -> b.apiId(apiId)
.integrationId(ids.get("Integration"))).timeoutInMillis());
assertEquals("renamed authorizer", api.getAuthorizer(b -> b.apiId(apiId)
.authorizerId(ids.get("Authorizer"))).name());
assertCredentials(api, ids, ROLE, OTHER);
}
assertThrows(NotFoundException.class, () -> api.getApi(b -> b.apiId(apiId)));
}
}
@ParameterizedTest
@ValueSource(strings = {"HTTP", "WEBSOCKET"})
void failedLaterResourceRestoresBothCredentialRoles(String protocol) {
try (ApiGatewayV2Client api = api()) {
String name = "v2-credentials-rollback-" + UUID.randomUUID();
try (StackCleanup cleanup = new StackCleanup(name)) {
stackAction("CreateStack", name, template(protocol, ROLE, ROLE, false));
Map<String, String> ids = outputs(waitFor(name, "CREATE_COMPLETE"));
stackAction("UpdateStack", name, template(protocol, null, null, true));
assertRollbackAfterBrokenResource(name, 1);
assertCredentials(api, ids, ROLE, ROLE);
String rotated = template(protocol, ROLE, OTHER, true)
.replace("\"Name\":\"auth\"", "\"Name\":\"rotated\"");
stackAction("UpdateStack", name, rotated);
assertRollbackAfterBrokenResource(name, 2);
assertCredentials(api, ids, ROLE, ROLE);
assertEquals("auth", api.getAuthorizer(b -> b.apiId(ids.get("Api"))
.authorizerId(ids.get("Authorizer"))).name());
}
}
}
@ParameterizedTest
@ValueSource(strings = {"HTTP", "WEBSOCKET"})
void failedLaterResourceRestoresAbsentAuthorizerRole(String protocol) {
try (ApiGatewayV2Client api = api()) {
String name = "v2-credentials-null-rollback-" + UUID.randomUUID();
try (StackCleanup cleanup = new StackCleanup(name)) {
stackAction("CreateStack", name, template(protocol, ROLE, null, false));
Map<String, String> ids = outputs(waitFor(name, "CREATE_COMPLETE"));
stackAction("UpdateStack", name, template(protocol, ROLE, OTHER, true));
assertRollbackAfterBrokenResource(name, 1);
assertCredentials(api, ids, ROLE, null);
}
}
}
@Test
void cleanupPreservesFailureBeforeCreation() {
String name = "v2-cleanup-absent-" + UUID.randomUUID();
AssertionError original = new AssertionError("before creation");
AssertionError actual = assertThrows(AssertionError.class, () -> {
try (StackCleanup cleanup = new StackCleanup(name)) {
throw original;
}
});
assertSame(original, actual);
assertEquals(0, actual.getSuppressed().length);
}
@Test
void cleanupPreservesFailureAfterCreationAndDeletesResources() {
String name = "v2-cleanup-created-" + UUID.randomUUID();
AssertionError original = new AssertionError("after creation");
String[] apiId = new String[1];
AssertionError actual = assertThrows(AssertionError.class, () -> {
try (StackCleanup cleanup = new StackCleanup(name)) {
stackAction("CreateStack", name, template("HTTP", ROLE, ROLE, false));
apiId[0] = outputs(waitFor(name, "CREATE_COMPLETE")).get("Api");
throw original;
}
});
assertSame(original, actual);
assertEquals(0, actual.getSuppressed().length);
try (ApiGatewayV2Client api = api()) {
assertThrows(NotFoundException.class, () -> api.getApi(b -> b.apiId(apiId[0])));
}
}
private class StackCleanup implements AutoCloseable {
private final String name;
private StackCleanup(String name) {
this.name = name;
}
@Override
public void close() {
try {
cloudFormation.describeStacks(name, "us-east-1");
} catch (AwsException expected) {
if ("ValidationError".equals(expected.getErrorCode())
&& ("Stack with id " + name + " does not exist").equals(expected.getMessage())) {
// Creation may have failed before a stack was stored.
return;
}
throw expected;
}
CfnStackWaits.awaitTerminal(name);
CfnStackWaits.deleteStack(name);
}
}
private void assertCredentials(ApiGatewayV2Client api, Map<String, String> ids,
String integration, String authorizer) {
assertEquals(integration, api.getIntegration(b -> b.apiId(ids.get("Api"))
.integrationId(ids.get("Integration"))).credentialsArn());
assertEquals(authorizer, api.getAuthorizer(b -> b.apiId(ids.get("Api"))
.authorizerId(ids.get("Authorizer"))).authorizerCredentialsArn());
}
private String template(String protocol, String credentials, String authorizerCredentials, boolean broken) {
String integrationProperty = credentials == null ? "" : ",\"CredentialsArn\":\"" + credentials + "\"";
String authorizerProperty = authorizerCredentials == null ? ""
: ",\"AuthorizerCredentialsArn\":\"" + authorizerCredentials + "\"";
boolean websocket = "WEBSOCKET".equals(protocol);
String route = websocket ? ",\"RouteSelectionExpression\":\"$request.body.action\"" : "";
String payload = websocket ? "" : ",\"PayloadFormatVersion\":\"2.0\"";
String authorizerPayload = websocket ? "" : ",\"AuthorizerPayloadFormatVersion\":\"2.0\"";
String identity = websocket ? "route.request.header.Authorization" : "$request.header.Authorization";
String failingResource = broken ? failingResourceAfter("Integration", "Authorizer") : "";
return """
{"Resources":{
"Api":{"Type":"AWS::ApiGatewayV2::Api","Properties":{
"Name":"credentials","ProtocolType":"%s"%s}},
"Integration":{"Type":"AWS::ApiGatewayV2::Integration","Properties":{
"ApiId":{"Ref":"Api"},"IntegrationType":"AWS_PROXY","IntegrationMethod":"POST",
"IntegrationUri":"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:backend/invocations"%s%s}},
"Authorizer":{"Type":"AWS::ApiGatewayV2::Authorizer","Properties":{
"ApiId":{"Ref":"Api"},"Name":"auth","AuthorizerType":"REQUEST",
"AuthorizerUri":"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:auth/invocations",
"IdentitySource":["%s"]%s%s}}%s},
"Outputs":{"Api":{"Value":{"Ref":"Api"}},
"Integration":{"Value":{"Ref":"Integration"}},
"IntegrationAttr":{"Value":{"Fn::GetAtt":["Integration","IntegrationId"]}},
"Authorizer":{"Value":{"Ref":"Authorizer"}},
"AuthorizerAttr":{"Value":{"Fn::GetAtt":["Authorizer","AuthorizerId"]}}}}
""".formatted(protocol, route, payload, integrationProperty, identity, authorizerPayload,
authorizerProperty, failingResource);
}
private void assertRollbackAfterBrokenResource(String name, int failedAttempts) {
waitFor(name, "UPDATE_ROLLBACK_COMPLETE");
long failedCreates = cloudFormation.describeStackEvents(name, "us-east-1").stream()
.filter(event -> "Broken".equals(event.getLogicalResourceId()))
.filter(event -> "CREATE_FAILED".equals(event.getResourceStatus()))
.filter(event -> event.getResourceStatusReason().contains("requires SubnetIds"))
.count();
assertEquals(failedAttempts, failedCreates);
}
private Stack waitFor(String name, String status) {
CfnStackWaits.awaitStatus(name, status);
return stack(cloudFormation, name);
}
private Map<String, String> outputs(Stack stack) {
return stack.getOutputs();
}
private ApiGatewayV2Client api() {
return AwsTestClients.create(ApiGatewayV2Client.builder(), "test", "test", Region.US_EAST_1,
Apache5HttpClient.builder(), endpoint);
}
}
@@ -1170,6 +1170,58 @@ class ApiGatewayV2CfnProvisionerTest {
&& Map.of("application/json", "{\"a\":1}").equals(req.get("requestTemplates"));
}
@Test
void integrationCredentialsAreForwardedAndRestoredOnRollback() throws Exception {
Integration prior = priorVpcLinkIntegration();
prior.setCredentialsArn("arn:aws:iam::000000000000:role/old");
stubIntegrationUpdate(prior);
StackResource integration = provisionIntegration("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
"CredentialsArn":"arn:aws:iam::000000000000:role/new"}
""");
verify(apiGatewayV2Service).updateIntegration(eq(REGION), eq(API_ID), eq("int-1"),
argThat(req -> "arn:aws:iam::000000000000:role/new".equals(req.get("credentialsArn"))));
assertTrue(provisioner.rollbackUpdate(integration));
verify(apiGatewayV2Service).replaceIntegrationCredentials(REGION, API_ID, "int-1",
"arn:aws:iam::000000000000:role/old");
}
@Test
void removedIntegrationCredentialsAreExplicitlyCleared() throws Exception {
stubIntegrationUpdate(priorVpcLinkIntegration());
provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration",
mapper.readTree("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend"}
"""), engine(), REGION, "000000000000", "test-stack", "int-1", Map.of(),
event -> { }, mapper.readTree("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
"CredentialsArn":"arn:aws:iam::000000000000:role/old"}
"""));
verify(apiGatewayV2Service).replaceIntegrationCredentials(REGION, API_ID, "int-1", null);
}
@Test
void removedAuthorizerCredentialsAndTtlAreClearedTogether() throws Exception {
Authorizer auth = new Authorizer();
auth.setAuthorizerId("auth-1");
auth.setAuthorizerCredentialsArn("arn:aws:iam::000000000000:role/old");
auth.setAuthorizerResultTtlInSeconds(60);
auth.setAuthorizerPayloadFormatVersion("2.0");
when(apiGatewayV2Service.getAuthorizer(REGION, API_ID, "auth-1")).thenReturn(auth);
when(apiGatewayV2Service.updateAuthorizer(eq(REGION), eq(API_ID), eq("auth-1"), anyMap())).thenReturn(auth);
StackResource resource = provisioner.provision("Auth", "AWS::ApiGatewayV2::Authorizer",
mapper.readTree("{\"ApiId\":\"api-123\",\"Name\":\"auth\",\"AuthorizerType\":\"REQUEST\"}"),
engine(), REGION, "000000000000", "test-stack", "auth-1", Map.of(),
event -> { }, mapper.readTree("""
{"ApiId":"api-123","Name":"auth","AuthorizerType":"REQUEST",
"AuthorizerCredentialsArn":"arn:aws:iam::000000000000:role/old","AuthorizerResultTtlInSeconds":60}
"""));
assertEquals("auth-1", resource.getPhysicalId());
assertEquals("auth-1", resource.getAttributes().get("AuthorizerId"));
verify(apiGatewayV2Service).replaceAuthorizerSettings(REGION, API_ID, "auth-1",
null, "2.0", null, null, null, null);
}
private static Integration priorVpcLinkIntegration() {
Integration prior = new Integration();
prior.setIntegrationId("int-1");
@@ -259,14 +259,19 @@ class ApiGatewayV2RouteAuthorizerDropTest {
// ── Authorizer ───────────────────────────────────────────────────────────
@Test
void authorizerResultTtlDroppedFromTheTemplateReadsBackAbsent() throws Exception {
void droppingAuthorizerResultTtlPreservesCredentialsSetThroughTheApi() throws Exception {
String declared = ",\"AuthorizerResultTtlInSeconds\":300";
StackResource created = createAuthorizer(declared);
assertEquals(300, authorizer(created).getAuthorizerResultTtlInSeconds());
String externalRole = "arn:aws:iam::000000000000:role/external";
service.updateAuthorizer(REGION, apiId, created.getPhysicalId(),
Map.of("authorizerCredentialsArn", externalRole));
updateAuthorizer(created, declared, "");
assertNull(authorizer(created).getAuthorizerResultTtlInSeconds());
Authorizer updated = authorizer(created);
assertNull(updated.getAuthorizerResultTtlInSeconds());
assertEquals(externalRole, updated.getAuthorizerCredentialsArn());
}
@Test
@@ -1,5 +1,7 @@
package io.floci.aws.services.cloudformation;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
import io.floci.aws.services.apigatewayv2.model.Authorizer;
import io.floci.aws.services.apigatewayv2.model.Integration;
@@ -20,14 +22,20 @@ final class ApiGatewayV2StackTestSupport {
static final String REGION = "us-east-1";
/** A resource that fails to create, so an update that adds it rolls back. */
static final String FAILING_RESOURCE =
",\"Broken\":{\"Type\":\"AWS::ApiGatewayV2::VpcLink\",\"DependsOn\":\"Integration\","
+ "\"Properties\":{\"Name\":\"broken\"}}";
private ApiGatewayV2StackTestSupport() {
}
/** Adds a resource that fails after the named resources finish updating. */
static String failingResourceAfter(String... logicalIds) {
ArrayNode dependencies = JsonNodeFactory.instance.arrayNode();
for (String logicalId : logicalIds) {
dependencies.add(logicalId);
}
return """
,"Broken":{"Type":"AWS::ApiGatewayV2::VpcLink","DependsOn":%s,
"Properties":{"Name":"broken"}}""".formatted(dependencies);
}
static Integration integration(ApiGatewayV2Service apiGatewayV2Service, Stack stack) {
StackResource api = stack.getResources().get("HttpApi");
StackResource integration = stack.getResources().get("Integration");
@@ -14,8 +14,8 @@ import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.FAILING_RESOURCE;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.REGION;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.failingResourceAfter;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.integration;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stack;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stackAction;
@@ -105,7 +105,8 @@ class CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest {
stackAction("CreateStack", stackName, template(PARAMETERS.formatted("original") + TIMEOUT, ""));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
stackAction("UpdateStack", stackName, template(PARAMETERS.formatted("changed"), FAILING_RESOURCE));
stackAction("UpdateStack", stackName,
template(PARAMETERS.formatted("changed"), failingResourceAfter("Integration")));
CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
Stack rolledBack = stack(cloudFormationService, stackName);
@@ -122,7 +123,7 @@ class CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest {
stackAction("CreateStack", stackName, awsProxy(template("", "")));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
stackAction("UpdateStack", stackName, awsProxy(template(SUBTYPE, FAILING_RESOURCE)));
stackAction("UpdateStack", stackName, awsProxy(template(SUBTYPE, failingResourceAfter("Integration"))));
CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
Integration integration = integration(apiGatewayV2Service, stack(cloudFormationService, stackName));
@@ -15,8 +15,8 @@ import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.FAILING_RESOURCE;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.REGION;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.failingResourceAfter;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.integration;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stack;
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stackAction;
@@ -93,7 +93,8 @@ class CloudFormationApiGatewayV2VpcLinkIntegrationTest {
String vpcLinkId = stack(cloudFormationService, stackName).getOutputs().get("VpcLinkRef");
stackAction("UpdateStack", stackName,
template("rollback-link", "subnet-bbbb2222", "{}", VPC_LINK_CONNECTION, FAILING_RESOURCE));
template("rollback-link", "subnet-bbbb2222", "{}", VPC_LINK_CONNECTION,
failingResourceAfter("Integration")));
CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
Stack rolledBack = stack(cloudFormationService, stackName);
@@ -10,6 +10,7 @@ AWS::ApiGateway::Stage Description clear the field reads back absent
AWS::ApiGateway::Stage RestApiId create-only a drop fails: the rest api is not found
AWS::ApiGateway::Stage StageName create-only a drop fails: the stage name is required
AWS::ApiGatewayV2::Authorizer ApiId create-only a drop fails: the authorizer is not found
AWS::ApiGatewayV2::Authorizer AuthorizerCredentialsArn clear only credentials previously declared by the stack are cleared
AWS::ApiGatewayV2::Authorizer AuthorizerPayloadFormatVersion clear a create without it accepts the authorizer
AWS::ApiGatewayV2::Authorizer AuthorizerResultTtlInSeconds clear the field reads back absent
AWS::ApiGatewayV2::Authorizer AuthorizerType keep:required by AWS
@@ -18,6 +19,20 @@ AWS::ApiGatewayV2::Authorizer EnableSimpleResponses clear the field reads back a
AWS::ApiGatewayV2::Authorizer IdentitySource clear an update also clears it when the stack never declared it, so a value set outside the stack is lost
AWS::ApiGatewayV2::Authorizer JwtConfiguration clear a create without it accepts the authorizer
AWS::ApiGatewayV2::Authorizer Name keep:required by AWS
AWS::ApiGatewayV2::Integration ApiId create-only
AWS::ApiGatewayV2::Integration ConnectionId clear
AWS::ApiGatewayV2::Integration ConnectionType default:INTERNET
AWS::ApiGatewayV2::Integration CredentialsArn clear only credentials previously declared by the stack are cleared
AWS::ApiGatewayV2::Integration IntegrationMethod clear
AWS::ApiGatewayV2::Integration IntegrationSubtype clear
AWS::ApiGatewayV2::Integration IntegrationType keep:required by AWS
AWS::ApiGatewayV2::Integration IntegrationUri keep:management updates retain an omitted URI
AWS::ApiGatewayV2::Integration PayloadFormatVersion default:derived from IntegrationSubtype
AWS::ApiGatewayV2::Integration RequestParameters clear
AWS::ApiGatewayV2::Integration RequestTemplates clear
AWS::ApiGatewayV2::Integration ResponseParameters clear
AWS::ApiGatewayV2::Integration TemplateSelectionExpression clear
AWS::ApiGatewayV2::Integration TimeoutInMillis default:0
AWS::ApiGatewayV2::Route ApiId create-only a drop fails: the route is not found
AWS::ApiGatewayV2::Route AuthorizationScopes clear an update also clears it when the stack never declared it, so a value set outside the stack is lost
AWS::ApiGatewayV2::Route AuthorizationType default:NONE
1 AWS::ApiGateway::Authorizer AuthorizerResultTtlInSeconds default:300
10 AWS::ApiGateway::Stage RestApiId create-only
11 AWS::ApiGateway::Stage StageName create-only
12 AWS::ApiGatewayV2::Authorizer ApiId create-only
13 AWS::ApiGatewayV2::Authorizer AuthorizerCredentialsArn clear
14 AWS::ApiGatewayV2::Authorizer AuthorizerPayloadFormatVersion clear
15 AWS::ApiGatewayV2::Authorizer AuthorizerResultTtlInSeconds clear
16 AWS::ApiGatewayV2::Authorizer AuthorizerType keep:required by AWS
19 AWS::ApiGatewayV2::Authorizer IdentitySource clear
20 AWS::ApiGatewayV2::Authorizer JwtConfiguration clear
21 AWS::ApiGatewayV2::Authorizer Name keep:required by AWS
22 AWS::ApiGatewayV2::Integration ApiId create-only
23 AWS::ApiGatewayV2::Integration ConnectionId clear
24 AWS::ApiGatewayV2::Integration ConnectionType default:INTERNET
25 AWS::ApiGatewayV2::Integration CredentialsArn clear
26 AWS::ApiGatewayV2::Integration IntegrationMethod clear
27 AWS::ApiGatewayV2::Integration IntegrationSubtype clear
28 AWS::ApiGatewayV2::Integration IntegrationType keep:required by AWS
29 AWS::ApiGatewayV2::Integration IntegrationUri keep:management updates retain an omitted URI
30 AWS::ApiGatewayV2::Integration PayloadFormatVersion default:derived from IntegrationSubtype
31 AWS::ApiGatewayV2::Integration RequestParameters clear
32 AWS::ApiGatewayV2::Integration RequestTemplates clear
33 AWS::ApiGatewayV2::Integration ResponseParameters clear
34 AWS::ApiGatewayV2::Integration TemplateSelectionExpression clear
35 AWS::ApiGatewayV2::Integration TimeoutInMillis default:0
36 AWS::ApiGatewayV2::Route ApiId create-only
37 AWS::ApiGatewayV2::Route AuthorizationScopes clear
38 AWS::ApiGatewayV2::Route AuthorizationType default:NONE
@@ -44,11 +44,9 @@ AWS::ApiGatewayV2::Api IpAddressType accepted and ignored
AWS::ApiGatewayV2::Api RouteKey accepted and ignored
AWS::ApiGatewayV2::Api Target accepted and ignored
AWS::ApiGatewayV2::Api Version accepted and ignored
AWS::ApiGatewayV2::Authorizer AuthorizerCredentialsArn accepted and ignored
AWS::ApiGatewayV2::Authorizer IdentityValidationExpression accepted and ignored
AWS::ApiGatewayV2::Deployment StageName accepted and ignored
AWS::ApiGatewayV2::Integration ContentHandlingStrategy accepted and ignored
AWS::ApiGatewayV2::Integration CredentialsArn accepted and ignored
AWS::ApiGatewayV2::Integration Description accepted and ignored
AWS::ApiGatewayV2::Integration PassthroughBehavior accepted and ignored
AWS::ApiGatewayV2::Integration TlsConfig accepted and ignored
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
44 AWS::ApiGatewayV2::Api RouteKey accepted and ignored
45 AWS::ApiGatewayV2::Api Target accepted and ignored
46 AWS::ApiGatewayV2::Api Version accepted and ignored
AWS::ApiGatewayV2::Authorizer AuthorizerCredentialsArn accepted and ignored
47 AWS::ApiGatewayV2::Authorizer IdentityValidationExpression accepted and ignored
48 AWS::ApiGatewayV2::Deployment StageName accepted and ignored
49 AWS::ApiGatewayV2::Integration ContentHandlingStrategy accepted and ignored
AWS::ApiGatewayV2::Integration CredentialsArn accepted and ignored
50 AWS::ApiGatewayV2::Integration Description accepted and ignored
51 AWS::ApiGatewayV2::Integration PassthroughBehavior accepted and ignored
52 AWS::ApiGatewayV2::Integration TlsConfig accepted and ignored