From 29fc72d156a8abe0a04e03bd683a345b2abd1043 Mon Sep 17 00:00:00 2001 From: Oleksandr Nikolaichuk <57410473+Sekator778@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:06:09 +0300 Subject: [PATCH] fix(cloudformation): update an API Gateway authorizer in place and replace it on a RestApiId change (#8841) --- docs/services/cloudformation.md | 2 +- .../apigateway/ApiGatewayService.java | 89 +++++++-- .../ApiGatewayRestApiCfnProvisioner.java | 182 +++++++++++++++++- .../provisioners/CfnRollback.java | 8 + ...atewayUpdateAuthorizerIntegrationTest.java | 23 +++ ...wayAuthorizerCfnUpdateIntegrationTest.java | 111 +++++++++++ .../resources/cloudformation/drop-policy.tsv | 7 + tools/docs/cfn_resource_types.yaml | 1 + 8 files changed, 402 insertions(+), 21 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cloudformation/ApiGatewayAuthorizerCfnUpdateIntegrationTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 528e27ac43..1de0ec7430 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -231,7 +231,7 @@ cross-resource references. | Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` | | Route 53 | `HostedZone`, `RecordSet`, `RecordSetGroup` (written in one change batch, so a record set that cannot be written leaves the zone unchanged; every record set must be in the group's hosted zone), `HealthCheck` | | Cloud Map | `HttpNamespace`, `PrivateDnsNamespace`, `PublicDnsNamespace`, `Service` | -| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` | +| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer` (created with `Name`, `Type`, `AuthorizerUri`, `IdentitySource`, `AuthorizerResultTtlInSeconds` and `ProviderARNs`; updated in place for those, keeping the id; a template that drops `AuthorizerResultTtlInSeconds`, `IdentitySource` or `ProviderARNs` restores the TTL of 300 and clears the identity source and the pools, a dropped `AuthorizerUri` keeps the current one, and dropping `IdentitySource` from a `TOKEN` or `COGNITO_USER_POOLS` authorizer fails the resource, as AWS requires it there; a change to `RestApiId` replaces the authorizer, as the registry marks it create-only, and deletes the old one once the update commits; `AuthorizerCredentials`, `AuthType` and `IdentityValidationExpression` are not stored), `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` | | API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment`, `DomainName`, `ApiMapping`, `VpcLink` | | AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey`. `Ref` on `GraphQLApi` and `ApiKey` returns the id where AWS returns the ARN. See [AppSync](appsync.md#cloudformation) for `Ref` and `Fn::GetAtt` compared with AWS. | | AppConfig | `Application`, `Environment` (`Tags` and `DeletionProtectionCheck` are accepted and not stored), `ConfigurationProfile` (`Tags`, `KmsKeyIdentifier`, `RetrievalRoleArn`, `Validators` and `DeletionProtectionCheck` are accepted and not stored), `DeploymentStrategy` (`Tags` are accepted and not stored; `ReplicateTo: SSM_DOCUMENT` writes no SSM document). `Ref` returns the AppConfig ID of each. See [AppConfig](appconfig.md#cloudformation) for updates and replacement. | diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java index 18296b82fe..9a6672231b 100644 --- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java +++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java @@ -1220,12 +1220,12 @@ public class ApiGatewayService implements ResourceProvider, Resettable { Authorizer authorizer = new Authorizer(); authorizer.setId(authorizerId); authorizer.setName((String) request.get("name")); - authorizer.setType((String) request.get("type")); + authorizer.setType(validateAuthorizerType((String) request.get("type"))); authorizer.setAuthorizerUri((String) request.get("authorizerUri")); authorizer.setIdentitySource((String) request.get("identitySource")); authorizer.setAuthorizerResultTtlInSeconds(String.valueOf(request.getOrDefault("authorizerResultTtlInSeconds", "300"))); - validateRequestAuthorizerIdentitySource(authorizer.getType(), authorizer.getIdentitySource(), - authorizer.getAuthorizerResultTtlInSeconds()); + validateAuthorizerIdentitySource(authorizer.getType(), authorizer.getIdentitySource(), + authorizer.getAuthorizerResultTtlInSeconds(), false); // COGNITO_USER_POOLS authorizers carry the pool ARNs; keep them so get-authorizer reflects them. if (request.get("providerARNs") instanceof List arns) { List providerArns = new ArrayList<>(); @@ -1292,9 +1292,13 @@ public class ApiGatewayService implements ResourceProvider, Resettable { // The store hands back live objects, so every op is validated against pending values first and // only applied once the whole patch is known to be good. String newName = authorizer.getName(); + String newType = authorizer.getType(); String newAuthorizerUri = authorizer.getAuthorizerUri(); String newIdentitySource = authorizer.getIdentitySource(); String newTtl = authorizer.getAuthorizerResultTtlInSeconds(); + boolean identityOrTypePatched = false; + List newProviderArns = authorizer.getProviderARNs() == null + ? null : new ArrayList<>(authorizer.getProviderARNs()); if (patchOperations != null) { for (Map op : patchOperations) { if (op == null) { @@ -1303,18 +1307,34 @@ public class ApiGatewayService implements ResourceProvider, Resettable { String path = op.get("path"); String value = op.get("value"); String opType = op.get("op"); - if (!"add".equals(opType) && !"replace".equals(opType)) { + // remove clears the identity source and takes one pool ARN off the list. + boolean clearable = "/identitySource".equals(path); + boolean providerArns = "/providerARNs".equals(path); + boolean remove = "remove".equals(opType) && (clearable || providerArns); + boolean add = "add".equals(opType) || ("replace".equals(opType) && !providerArns); + if (!add && !remove) { throw new AwsException("BadRequestException", "Invalid operation", 400); } - if (path == null || value == null) { + if (path == null || (value == null && !(remove && clearable))) { throw new AwsException("BadRequestException", "Missing path or value", 400); } if ("/name".equals(path)) { newName = value; + } else if ("/type".equals(path)) { + newType = validateAuthorizerType(value); + identityOrTypePatched = true; } else if ("/authorizerUri".equals(path)) { newAuthorizerUri = value; } else if ("/identitySource".equals(path)) { - newIdentitySource = value; + newIdentitySource = remove ? null : value; + identityOrTypePatched = true; + } else if (providerArns) { + newProviderArns = newProviderArns == null ? new ArrayList<>() : newProviderArns; + if (remove) { + newProviderArns.remove(value); + } else if (!newProviderArns.contains(value)) { + newProviderArns.add(value); + } } else if ("/authorizerResultTtlInSeconds".equals(path)) { // Validate before accepting: the store hands back live objects, and an unparseable TTL // would break serialisation on every later GetAuthorizer/GetAuthorizers. @@ -1331,16 +1351,59 @@ public class ApiGatewayService implements ResourceProvider, Resettable { } } } - validateRequestAuthorizerIdentitySource(authorizer.getType(), newIdentitySource, newTtl); - authorizer.setName(newName); - authorizer.setAuthorizerUri(newAuthorizerUri); - authorizer.setIdentitySource(newIdentitySource); - authorizer.setAuthorizerResultTtlInSeconds(newTtl); - authorizerStore.put(authorizerKey(region, apiId, authorizerId), authorizer); + validateAuthorizerIdentitySource(newType, newIdentitySource, newTtl, identityOrTypePatched); + return writeAuthorizer(region, apiId, authorizer, newName, newType, newAuthorizerUri, + newIdentitySource, newTtl, newProviderArns); + } + + /** The authorizer types AWS accepts; a missing type is left to the caller, as create always did. */ + private static String validateAuthorizerType(String type) { + if (type != null && !List.of("TOKEN", "REQUEST", "COGNITO_USER_POOLS").contains(type)) { + throw new AwsException("BadRequestException", + "Authorizer type must be TOKEN, REQUEST or COGNITO_USER_POOLS", 400); + } + return type; + } + + /** + * Writes back an authorizer exactly as a stack update's snapshot held it, a null URI included, + * which a patch cannot express. For the stack rollback only. + */ + public void restoreAuthorizer(String region, String apiId, Authorizer snapshot) { + writeAuthorizer(region, apiId, getAuthorizer(region, apiId, snapshot.getId()), snapshot.getName(), + snapshot.getType(), snapshot.getAuthorizerUri(), snapshot.getIdentitySource(), + snapshot.getAuthorizerResultTtlInSeconds(), + snapshot.getProviderARNs() == null ? null : new ArrayList<>(snapshot.getProviderARNs())); + } + + private Authorizer writeAuthorizer(String region, String apiId, Authorizer authorizer, String name, + String type, String authorizerUri, String identitySource, String ttl, + List providerArns) { + authorizer.setName(name); + authorizer.setType(type); + authorizer.setAuthorizerUri(authorizerUri); + authorizer.setIdentitySource(identitySource); + authorizer.setAuthorizerResultTtlInSeconds(ttl); + authorizer.setProviderARNs(providerArns); + authorizerStore.put(authorizerKey(region, apiId, authorizer.getId()), authorizer); return authorizer; } - private static void validateRequestAuthorizerIdentitySource(String type, String identitySource, String ttl) { + /** + * Checks the identity source of an authorizer's final values: AWS requires it for REQUEST when + * caching is on, and for TOKEN and COGNITO_USER_POOLS. Create does not enforce the second rule + * yet, and a patch enforces it only when it has an op on {@code /identitySource} or {@code /type} + * ({@code requiredForTokenAndCognito}), so an authorizer created without one can still be renamed. + */ + private static void validateAuthorizerIdentitySource(String type, String identitySource, String ttl, + boolean requiredForTokenAndCognito) { + if (requiredForTokenAndCognito && ("TOKEN".equals(type) || "COGNITO_USER_POOLS".equals(type))) { + if (identitySource == null || identitySource.isBlank()) { + throw new AwsException("BadRequestException", + "Identity source is required for a " + type + " authorizer", 400); + } + return; + } if (!"REQUEST".equals(type)) { return; } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java index badabbad7c..28bebeaf9d 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java @@ -57,6 +57,9 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { * after the update commits, or a rollback, deletes the right one. */ private static final String LOCATIONS_ATTR = "__FlociApiGatewayLocations"; + /** Where a {@link Location} names an authorizer, in place of the HTTP method. */ + private static final String AUTHORIZER_KIND = "AUTHORIZER"; + private static final String AUTHORIZER_SNAPSHOT_ATTR = CfnRollback.APIGW_AUTHORIZER_UPDATE_SNAPSHOT_ATTR; private static final String VPC_ENDPOINT_IDS_PATH = "/endpointConfiguration/vpcEndpointIds"; private final ApiGatewayService apiGatewayService; @@ -91,8 +94,9 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { /** * A Resource or Method can sit on an API outside the stack, where no RestApi delete cascades to - * it, so each removes its own entity, found through the location recorded for it. Deployment, - * Stage and Authorizer have no delete of their own yet. + * it, so each removes its own entity, found through the location recorded for it. Deployment + * and Stage have no delete of their own yet. An Authorizer is deleted at the API recorded for it; one + * created before its location was recorded is not deleted. */ @Override public void delete(StackResource resource, String region) { @@ -129,7 +133,10 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { } private void deleteLocation(String physicalId, Location location, String region) { - if (location.httpMethod() == null) { + if (location.authorizer()) { + CfnDeletes.safeDelete("API authorizer", physicalId, () -> apiGatewayService.deleteAuthorizer( + region, location.restApiId(), location.resourceId()), "NotFoundException"); + } else if (location.httpMethod() == null) { CfnDeletes.safeDelete("API resource", physicalId, () -> apiGatewayService.deleteResource( region, location.restApiId(), location.resourceId()), "NotFoundException"); } else { @@ -169,6 +176,7 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { */ @Override public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(AUTHORIZER_SNAPSHOT_ATTR); return ReplacementCleanup.complete(resource, (type, physicalId, region) -> deleteEntity(resource, physicalId, region)); } @@ -176,6 +184,7 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { @Override public void clearUpdate(StackResource resource) { resource.getAttributes().remove(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR); + resource.getAttributes().remove(AUTHORIZER_SNAPSHOT_ATTR); ReplacementCleanup.clear(resource); } @@ -195,13 +204,19 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { } /** - * Puts a replaced RestApi, Resource or Method back when a later resource fails the update, and a - * RestApi patched in place back to its snapshot. Without a replacement, a Resource update + * Puts a replaced RestApi, Resource, Method or Authorizer back when a later resource fails the + * update, a RestApi patched in place back to its snapshot, and an Authorizer patched in place, or + * created because the prior was gone, back through its own snapshot. Without a replacement, a Resource update * changed nothing, since all its properties are createOnly, so there is nothing to undo. A * Method the update kept was written in place, with no snapshot to put back. */ @Override public boolean rollbackUpdate(StackResource resource) { + JsonNode authorizerSnapshot = AUTHORIZER.equals(resource.getResourceType()) + ? CfnRollback.updateSnapshot(resource, AUTHORIZER_SNAPSHOT_ATTR) : null; + if (authorizerSnapshot != null) { + return rollbackAuthorizerUpdate(resource, authorizerSnapshot); + } if (ReplacementCleanup.rollback(resource, (type, physicalId, region) -> deleteEntity(resource, physicalId, region))) { return true; @@ -231,8 +246,16 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { return true; } - /** A resource of a REST API, or with an HTTP method, one of that resource's methods. */ + /** + * A resource of a REST API, or with an HTTP method, one of that resource's methods. An + * authorizer is the API and the authorizer id, with the kind in place of the method. + */ private record Location(String restApiId, String resourceId, String httpMethod) { + + /** An authorizer, recorded with {@link #AUTHORIZER_KIND} where a method would name its verb. */ + boolean authorizer() { + return AUTHORIZER_KIND.equals(httpMethod); + } } private Map locations(StackResource r) { @@ -504,8 +527,29 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { } } + /** + * RestApiId is the one create-only property: a change to it replaces the authorizer, and any + * other change patches the authorizer in place, which keeps its id for the methods that name it. + */ private void provisionAuthorizer(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(AUTHORIZER_SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + String region = ctx.region(); String apiId = ctx.resolveOptional(props, "RestApiId"); + PropertyChanges changes = ctx.isUpdate() ? ctx.changes(AUTHORIZER, props) : null; + boolean replaces = changes != null && changes.requiresReplacement(); + Authorizer live = ctx.isUpdate() && !replaces + ? findPrior("API authorizer", ctx.priorPhysicalId(), + () -> apiGatewayService.getAuthorizer(region, apiId, ctx.priorPhysicalId())) + : null; + if (live != null) { + updateAuthorizerInPlace(r, props, ctx, apiId, live); + return; + } Map req = new HashMap<>(); req.put("name", ctx.resolveOptional(props, "Name")); req.put("type", ctx.resolveOptional(props, "Type")); @@ -518,9 +562,133 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { if (props != null && props.has("ProviderARNs")) { req.put("providerARNs", ctx.resolveStringList(props, "ProviderARNs")); } - Authorizer authorizer = apiGatewayService.createAuthorizer(ctx.region(), apiId, req); + Authorizer authorizer = apiGatewayService.createAuthorizer(region, apiId, req); r.setPhysicalId(authorizer.getId()); r.getAttributes().put("AuthorizerId", authorizer.getId()); + recordLocation(r, ctx, new Location(apiId, authorizer.getId(), AUTHORIZER_KIND)); + if (ctx.isUpdate() && !replaces) { + // The authorizer the update started from is gone, so this one is the update's to undo. + CfnRollback.recordCreatedByUpdate(r, ctx, AUTHORIZER_SNAPSHOT_ATTR); + } + if (ctx.isUpdate()) { + // The authorizer the prior physical id named is deleted once the update commits, and the + // new one is removed if the update rolls back. + ReplacementCleanup.record(r, ctx, attributesBefore, replaces); + } + } + + /** + * Patches the authorizer to the template. A declared property is set; a dropped one goes back to + * its create default (the TTL, 300) or is cleared (identity source, Cognito pools), except the URI, + * which the patch cannot remove and which is kept; one the + * template never declared keeps what the authorizer has. + */ + private void updateAuthorizerInPlace(StackResource r, JsonNode props, ProvisionContext ctx, String apiId, + Authorizer live) { + ObjectNode snapshot = objectMapper.createObjectNode(); + snapshot.put("region", ctx.region()); + snapshot.put("apiId", apiId); + snapshot.put("authorizerId", live.getId()); + snapshot.put("name", live.getName()); + snapshot.put("type", live.getType()); + snapshot.put("authorizerUri", live.getAuthorizerUri()); + snapshot.put("identitySource", live.getIdentitySource()); + snapshot.put("authorizerResultTtlInSeconds", live.getAuthorizerResultTtlInSeconds()); + ArrayNode providers = snapshot.putArray("providerARNs"); + providerArns(live).forEach(providers::add); + r.getAttributes().put(AUTHORIZER_SNAPSHOT_ATTR, snapshot.toString()); + + Set dropped = ctx.droppedProperties(props); + String name = ctx.resolveOptional(props, "Name"); + String type = ctx.resolveOptional(props, "Type"); + String uri = ctx.resolveOptional(props, "AuthorizerUri"); + String identity = ctx.resolveOptional(props, "IdentitySource"); + String ttl = ctx.resolveOptional(props, "AuthorizerResultTtlInSeconds"); + List arns = props != null && props.has("ProviderARNs") + ? ctx.resolveStringList(props, "ProviderARNs") : null; + applyAuthorizer(ctx.region(), apiId, live, + name != null ? name : live.getName(), + type != null ? type : live.getType(), + orLive(uri, live.getAuthorizerUri()), + identity != null || !dropped.contains("IdentitySource") + ? orLive(identity, live.getIdentitySource()) : null, + ttl != null ? ttl : dropped.contains("AuthorizerResultTtlInSeconds") ? "300" + : live.getAuthorizerResultTtlInSeconds(), + arns != null ? arns : dropped.contains("ProviderARNs") ? List.of() : providerArns(live)); + r.setPhysicalId(live.getId()); + r.getAttributes().put("AuthorizerId", live.getId()); + recordLocation(r, ctx, new Location(apiId, live.getId(), AUTHORIZER_KIND)); + } + + private static String orLive(String declared, String live) { + return declared != null ? declared : live; + } + + private static List providerArns(Authorizer authorizer) { + return authorizer.getProviderARNs() == null ? List.of() : authorizer.getProviderARNs(); + } + + /** + * One UpdateAuthorizer patch that takes {@code live} to the values given; a null identity + * source clears it. Nothing is sent when the authorizer already has them. + */ + private void applyAuthorizer(String region, String apiId, Authorizer live, String name, String type, + String uri, String identitySource, String ttl, List providerArns) { + List> ops = new ArrayList<>(); + addIfChanged(ops, "/name", live.getName(), name); + addIfChanged(ops, "/type", live.getType(), type); + if (uri != null) { + // The patch has no remove for the URI: a drop keeps it, and a rollback writes it back whole. + addIfChanged(ops, "/authorizerUri", live.getAuthorizerUri(), uri); + } + addIfChanged(ops, "/identitySource", live.getIdentitySource(), identitySource); + addIfChanged(ops, "/authorizerResultTtlInSeconds", live.getAuthorizerResultTtlInSeconds(), ttl); + for (String arn : providerArns) { + if (!providerArns(live).contains(arn)) { + ops.add(Map.of("op", "add", "path", "/providerARNs", "value", arn)); + } + } + for (String arn : providerArns(live)) { + if (!providerArns.contains(arn)) { + ops.add(Map.of("op", "remove", "path", "/providerARNs", "value", arn)); + } + } + if (!ops.isEmpty()) { + apiGatewayService.updateAuthorizer(region, apiId, live.getId(), ops); + } + } + + private void addIfChanged(List> ops, String path, String current, String desired) { + if (Objects.equals(current, desired)) { + return; + } + ops.add(desired == null ? Map.of("op", "remove", "path", path) : replacePatchOp(path, desired)); + } + + /** + * Puts an authorizer the update patched back as it was, or deletes the one the update created + * because the prior was gone. Spent only once it succeeded, so a failure can be retried. + */ + private boolean rollbackAuthorizerUpdate(StackResource resource, JsonNode snapshot) { + if (CfnRollback.undoCreatedByUpdate(resource, snapshot, AUTHORIZER_SNAPSHOT_ATTR, "AuthorizerId", + (createdId, region) -> deleteEntity(resource, createdId, region))) { + return true; + } + String region = snapshot.path("region").asText(); + String apiId = snapshot.path("apiId").asText(); + List arns = new ArrayList<>(); + snapshot.path("providerARNs").forEach(arn -> arns.add(arn.asText())); + Authorizer prior = new Authorizer(); + prior.setId(snapshot.path("authorizerId").asText()); + prior.setName(CfnRollback.snapshotText(snapshot, "name")); + prior.setType(CfnRollback.snapshotText(snapshot, "type")); + prior.setAuthorizerUri(CfnRollback.snapshotText(snapshot, "authorizerUri")); + prior.setIdentitySource(CfnRollback.snapshotText(snapshot, "identitySource")); + prior.setAuthorizerResultTtlInSeconds(CfnRollback.snapshotText(snapshot, "authorizerResultTtlInSeconds")); + prior.setProviderARNs(arns); + apiGatewayService.restoreAuthorizer(region, apiId, prior); + resource.getAttributes().remove(AUTHORIZER_SNAPSHOT_ATTR); + return true; } private void provisionMethod(StackResource r, JsonNode props, ProvisionContext ctx) { diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index f696f01cc1..4c376d55e3 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -190,6 +190,14 @@ public final class CfnRollback { */ public static final String KMS_KEY_UPDATE_SNAPSHOT_ATTR = "__FlociKmsKeyUpdateSnapshot"; + /** + * The name, type, URI, identity source, cache TTL and Cognito pools an API Gateway authorizer + * carried before an in-place update changed them, or the authorizer an update created because the + * prior was gone, so a failed stack update can put them back or delete the created one. Written + * and spent by {@code ApiGatewayRestApiCfnProvisioner}. + */ + public static final String APIGW_AUTHORIZER_UPDATE_SNAPSHOT_ATTR = "__FlociApiGatewayAuthorizerUpdateSnapshot"; + public static final String STACK_SET_UPDATE_SNAPSHOT_ATTR = "__FlociStackSetUpdateSnapshot"; /** diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUpdateAuthorizerIntegrationTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUpdateAuthorizerIntegrationTest.java index 27434df5d9..3703d0cd47 100644 --- a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUpdateAuthorizerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUpdateAuthorizerIntegrationTest.java @@ -8,6 +8,7 @@ import java.util.Map; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; @QuarkusTest class ApiGatewayUpdateAuthorizerIntegrationTest { @@ -209,5 +210,27 @@ class ApiGatewayUpdateAuthorizerIntegrationTest { .then() .statusCode(200) .body("name", equalTo("original-name")); + + String path = "/restapis/" + apiId + "/authorizers/" + authorizerId; + for (String ops : new String[]{ + "{\"op\":\"replace\",\"path\":\"/type\",\"value\":\"BOGUS\"}", + "{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"x\"}," + + "{\"op\":\"replace\",\"path\":\"/type\",\"value\":\"BOGUS\"}", + "{\"op\":\"remove\",\"path\":\"/identitySource\"}"}) { + given().contentType("application/json").body("{\"patchOperations\":[" + ops + "]}") + .when().patch(path).then().statusCode(400); + given().when().get(path).then().statusCode(200).body("name", equalTo("original-name")) + .body("type", equalTo("TOKEN")).body("identitySource", equalTo("method.request.header.Authorization")) + .body("authorizerUri", equalTo("arn:aws:lambda:us-east-1:123456789012:function:my-authorizer")); + } + + String requestId = given().contentType("application/json").body( + "{\"name\":\"req\",\"type\":\"REQUEST\",\"authorizerUri\":\"arn:aws:lambda:us-east-1:123456789012:function:a\"," + + "\"identitySource\":\"method.request.header.X\",\"authorizerResultTtlInSeconds\":0}") + .when().post("/restapis/" + apiId + "/authorizers").then().statusCode(201).extract().path("id"); + given().contentType("application/json") + .body("{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/identitySource\"}]}") + .when().patch("/restapis/" + apiId + "/authorizers/" + requestId).then().statusCode(200) + .body("identitySource", nullValue()); } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayAuthorizerCfnUpdateIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayAuthorizerCfnUpdateIntegrationTest.java new file mode 100644 index 0000000000..f488605624 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/ApiGatewayAuthorizerCfnUpdateIntegrationTest.java @@ -0,0 +1,111 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CfnStackWaits; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; + +import static io.floci.aws.services.cloudformation.CfnStackTestSupport.physicalId; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * An AWS::ApiGateway::Authorizer updated through a stack: a change that needs no replacement keeps the + * authorizer's id and applies on a later retry after a rollback, and a changed RestApiId replaces it. + */ +@QuarkusTest +class ApiGatewayAuthorizerCfnUpdateIntegrationTest { + + private static final String SETTINGS = "\"Name\":\"n1\",\"AuthorizerResultTtlInSeconds\":60"; + private static final String CHANGED = "\"Name\":\"n2\""; + /** A Cognito authorizer created without an AuthorizerUri, after Auth; {@code uri} is appended to its properties. */ + private static String cognito(String uri) { + return ",\"Cog\":{\"Type\":\"AWS::ApiGateway::Authorizer\",\"DependsOn\":\"Auth\",\"Properties\":{" + + "\"RestApiId\":{\"Ref\":\"ApiA\"},\"Type\":\"COGNITO_USER_POOLS\",\"Name\":\"cog\"," + + "\"ProviderARNs\":[\"arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_x\"]," + + "\"IdentitySource\":\"method.request.header.Authorization\"" + uri + "}}"; + } + + private static CloudFormationClient client() { + return AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + } + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void anInPlaceUpdateKeepsTheAuthorizerAndARollbackRestoresIt() { + String stack = "apigw-cfn-authorizer-inplace-it"; + CloudFormationClient cf = client(); + try { + CfnStackWaits.createStack(cf, stack, template("ApiA", SETTINGS, cognito("")), "CREATE_COMPLETE"); + String apiId = physicalId(cf, stack, "ApiA"); + String authorizerId = physicalId(cf, stack, "Auth"); + String cognitoId = physicalId(cf, stack, "Cog"); + + CfnStackWaits.updateStack(cf, stack, + template("ApiA", CHANGED, cognito(",\"AuthorizerUri\":\"u2\"") + + CfnStackWaits.failingResourceAfter("Cog")), + "UPDATE_ROLLBACK_COMPLETE"); + given().when().get("/restapis/" + apiId + "/authorizers/" + cognitoId).then().statusCode(200) + .body("authorizerUri", nullValue()); + assertEquals(authorizerId, physicalId(cf, stack, "Auth")); + given().when().get("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(200) + .body("name", equalTo("n1")).body("authorizerResultTtlInSeconds", equalTo(60)); + + CfnStackWaits.updateStack(cf, stack, template("ApiA", CHANGED, cognito("")), "UPDATE_COMPLETE"); + assertEquals(authorizerId, physicalId(cf, stack, "Auth")); + given().when().get("/restapis/" + apiId + "/authorizers").then().statusCode(200) + .body("item", hasSize(2)); + given().when().get("/restapis/" + apiId + "/authorizers/" + authorizerId).then().statusCode(200) + .body("name", equalTo("n2")).body("authorizerResultTtlInSeconds", equalTo(300)); + } finally { + CfnStackWaits.deleteStack(cf, stack); + cf.close(); + } + } + + @Test + void aChangedRestApiIdReplacesTheAuthorizer() { + String stack = "apigw-cfn-authorizer-replace-it"; + CloudFormationClient cf = client(); + try { + CfnStackWaits.createStack(cf, stack, template("ApiA", SETTINGS, ""), "CREATE_COMPLETE"); + String apiA = physicalId(cf, stack, "ApiA"); + String apiB = physicalId(cf, stack, "ApiB"); + String authorizerId = physicalId(cf, stack, "Auth"); + + CfnStackWaits.updateStack(cf, stack, template("ApiB", SETTINGS, ""), "UPDATE_COMPLETE"); + assertNotEquals(authorizerId, physicalId(cf, stack, "Auth")); + given().when().get("/restapis/" + apiA + "/authorizers").then().statusCode(200) + .body("item", hasSize(0)); + given().when().get("/restapis/" + apiB + "/authorizers").then().statusCode(200) + .body("item", hasSize(1)); + } finally { + CfnStackWaits.deleteStack(cf, stack); + cf.close(); + } + } + + /** Two REST APIs and a TOKEN authorizer on {@code apiRef}; {@code later} is appended to the resources. */ + private static String template(String apiRef, String settings, String later) { + return """ + {"Resources":{ + "ApiA":{"Type":"AWS::ApiGateway::RestApi","Properties":{"Name":"cfn-authorizer-a"}}, + "ApiB":{"Type":"AWS::ApiGateway::RestApi","Properties":{"Name":"cfn-authorizer-b"}}, + "Auth":{"Type":"AWS::ApiGateway::Authorizer","Properties":{ + "RestApiId":{"Ref":"%s"},"Type":"TOKEN","AuthorizerUri":"u1", + "IdentitySource":"method.request.header.Auth",%s}}%s}} + """.formatted(apiRef, settings, later); + } +} diff --git a/src/test/resources/cloudformation/drop-policy.tsv b/src/test/resources/cloudformation/drop-policy.tsv index 223350832a..70e485fa88 100644 --- a/src/test/resources/cloudformation/drop-policy.tsv +++ b/src/test/resources/cloudformation/drop-policy.tsv @@ -1,3 +1,10 @@ +AWS::ApiGateway::Authorizer AuthorizerResultTtlInSeconds default:300 +AWS::ApiGateway::Authorizer AuthorizerUri keep:the patch cannot remove it +AWS::ApiGateway::Authorizer IdentitySource clear the field reads back absent; a drop from a TOKEN or COGNITO_USER_POOLS authorizer fails, as AWS requires it there +AWS::ApiGateway::Authorizer Name keep:required by AWS +AWS::ApiGateway::Authorizer ProviderARNs clear the field reads back empty +AWS::ApiGateway::Authorizer RestApiId create-only a drop fails: the rest api is not found +AWS::ApiGateway::Authorizer Type keep:required by AWS AWS::ApiGatewayV2::Authorizer ApiId create-only a drop fails: the authorizer is not found AWS::ApiGatewayV2::Authorizer AuthorizerPayloadFormatVersion clear a create without it accepts the authorizer AWS::ApiGatewayV2::Authorizer AuthorizerResultTtlInSeconds clear the field reads back absent diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 930315c52c..46e2d72719 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -227,6 +227,7 @@ notes: AWS::EKS::Cluster: 'created with `Name`, `Version`, `RoleArn`, `Tags`, `EncryptionConfig`, `ResourcesVpcConfig`, `Logging`, `AccessConfig` and `KubernetesNetworkConfig.IpFamily` and `ServiceIpv4Cidr`, a replacement included; a change to `EncryptionConfig`, `IpFamily` or `ServiceIpv4Cidr` replaces the cluster with the new value applied; `ElasticLoadBalancing`, `ServiceIpv6Cidr` and `ResourcesVpcConfig.ControlPlaneEgressMode` are accepted and ignored; updated in place for `Tags`, keeping tags added outside the stack; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version`, `ResourcesVpcConfig`, `Logging` or `AccessConfig` is accepted with a warning and not applied, as the emulator has no `UpdateClusterVersion` or `UpdateClusterConfig`' AWS::EKS::Nodegroup: 'created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place' AWS::IAM::User: 'template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete' + AWS::ApiGateway::Authorizer: 'created with `Name`, `Type`, `AuthorizerUri`, `IdentitySource`, `AuthorizerResultTtlInSeconds` and `ProviderARNs`; updated in place for those, keeping the id; a template that drops `AuthorizerResultTtlInSeconds`, `IdentitySource` or `ProviderARNs` restores the TTL of 300 and clears the identity source and the pools, a dropped `AuthorizerUri` keeps the current one, and dropping `IdentitySource` from a `TOKEN` or `COGNITO_USER_POOLS` authorizer fails the resource, as AWS requires it there; a change to `RestApiId` replaces the authorizer, as the registry marks it create-only, and deletes the old one once the update commits; `AuthorizerCredentials`, `AuthType` and `IdentityValidationExpression` are not stored' AWS::KMS::Key: 'created with `Description`, `KeyPolicy`, `KeySpec`, `KeyUsage`, `Origin`, `MultiRegion`, `Enabled`, `EnableKeyRotation` and `Tags`; updated in place for `Description`, `KeyPolicy`, `Enabled`, `EnableKeyRotation` and `Tags`, keeping tags added outside the stack; a template that drops `Description`, `Enabled` or `EnableKeyRotation` clears the description, enables the key and turns rotation off, a dropped `KeyPolicy` keeps the current policy, and one the stack never declared keeps the value set outside it; a rotation change on a key that stays disabled fails, as AWS raises `DisabledException`; a change to `KeySpec`, `KeyUsage`, `Origin` or `MultiRegion` fails the update, as on AWS, and the stack rolls back' AWS::IoT::DomainConfiguration: '`ServerCertificates` resolves to a JSON string' AWS::IoT::Policy: 'deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached'