fix(cloudformation): roll back in-place Cognito user pool and client updates (#5006)

* fix(cloudformation): roll back in-place Cognito user pool and client updates

A stack update that changed a user pool or user pool client in place and
then failed on a later resource ended in UPDATE_ROLLBACK_FAILED, because the
provisioner kept no snapshot to put them back. It now snapshots the settings
an update can change before the update call and restores them on rollback,
spending the snapshot only once the restore succeeds.

UpdateUserPool and UpdateUserPoolClient only apply what a request names, so
they cannot clear a setting the update added. CognitoService gains
userPoolSettings/restoreUserPoolSettings and their client counterparts,
which copy exactly those settings, leave the pool's signing keys and the
client's secrets out of the snapshot, and put the settings back on the
stored entity.

* fix(cloudformation): drop the Cognito update snapshot when the update commits

Greptile on #5006: once a stack update commits, the engine calls
completeUpdate for every resource but clearUpdate only after a
replacement's cleanup, so an in-place pool or client update left its
settings snapshot in the stored stack metadata until the resource was next
provisioned. completeUpdate now drops it before delegating to the
replacement cleanup; the update committed and nothing will roll it back.

Also orders the test's org imports (org.junit before org.mockito), which
were already out of order on main.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-03 10:35:45 -04:00
1 parent 0740adf9ae
commit 7ffe43f48f
6 files changed
+447 -9

No files matched your search

@@ -128,6 +128,13 @@ public final class CfnRollback {
*/
public static final String SQS_UPDATE_SNAPSHOT_ATTR = "__FlociSqsUpdateSnapshot";
/**
* Holds the settings a Cognito user pool or user pool client had before an in-place update
* changed them, so a failed stack update can put them back. Written by
* {@code CognitoCfnProvisioner} before its update call and spent by its {@code rollbackUpdate}.
*/
public static final String COGNITO_UPDATE_SNAPSHOT_ATTR = "__FlociCognitoUpdateSnapshot";
/**
* Holds the configuration an Auto Scaling group carried before an in-place update changed it,
* so a failed stack update can restore it.
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsEndpoints;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -32,6 +34,8 @@ import java.util.function.Supplier;
* updated in place unless {@code UserPoolId} or {@code GenerateSecret}, its create-only properties,
* changed, in which case a new client is created and the {@link ReplacementCleanup} record deletes
* the displaced one once the update commits or restores it on rollback, as CloudFormation does.
* Before an in-place update of either, the settings it can change are snapshotted, so a stack update
* that fails later puts them back.
*
* <p>{@code AWS::Cognito::UserPoolDomain}: the physical id is the domain name, as in AWS, and
* {@code Fn::GetAtt CloudFrontDistribution} is the CloudFront name a custom domain's DNS alias
@@ -43,6 +47,7 @@ import java.util.function.Supplier;
public class CognitoCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(CognitoCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String NOT_FOUND = "ResourceNotFoundException";
private static final String USER_POOL = "AWS::Cognito::UserPool";
@@ -73,11 +78,14 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
case USER_POOL -> {
// A snapshot describes the update in flight; one an earlier update left behind is stale.
r.getAttributes().remove(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR);
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
provisionUserPool(r, props, ctx);
ReplacementCleanup.record(r, ctx, attributesBefore);
}
case USER_POOL_CLIENT -> {
r.getAttributes().remove(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR);
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
provisionUserPoolClient(r, props, ctx);
ReplacementCleanup.record(r, ctx, attributesBefore);
@@ -141,24 +149,64 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
/**
* The engine calls this for every resource once a stack update commits, but {@link #clearUpdate}
* only after a replacement's cleanup, so an in-place update's snapshot is dropped here: the update
* committed and nothing will roll it back.
*/
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
}
/**
* A replacement is undone through the cleanup record. Without one the entity was updated in
* place, and putting that back needs a snapshot this provisioner does not keep, so the engine
* reports it as not rolled back, as it did for the switch.
* A replacement is undone through the cleanup record, and an in-place update of a pool or a
* client from the snapshot taken before it. With neither, a pool or client provision failed
* before it changed anything, since its update call is preceded by the snapshot, so there is
* nothing to undo. A domain keeps no snapshot: its in-place update is still reported as not
* rolled back.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
return ReplacementCleanup.rollback(resource, this::delete);
if (ReplacementCleanup.rollback(resource, this::delete)) {
return true;
}
if (USER_POOL_DOMAIN.equals(resource.getResourceType())) {
return false;
}
// The snapshot is spent only once the restore succeeded: a restore that throws leaves it in
// place for the next attempt instead of reporting a rollback that never happened.
String raw = resource.getAttributes().get(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR);
if (raw == null) {
return true;
}
try {
if (USER_POOL.equals(resource.getResourceType())) {
cognitoService.restoreUserPoolSettings(MAPPER.readValue(raw, UserPool.class));
} else {
cognitoService.restoreUserPoolClientSettings(MAPPER.readValue(raw, UserPoolClient.class));
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the Cognito update snapshot for "
+ resource.getLogicalId(), e);
}
resource.getAttributes().remove(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR);
return true;
}
private static void snapshot(StackResource r, Object settings) {
try {
r.getAttributes().put(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR, MAPPER.writeValueAsString(settings));
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not snapshot " + r.getLogicalId() + " before its update", e);
}
}
private void provisionUserPool(StackResource r, JsonNode props, ProvisionContext ctx) {
@@ -183,6 +231,7 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {
UserPool pool;
if (ctx.isUpdate()) {
req.put("UserPoolId", ctx.priorPhysicalId());
snapshot(r, cognitoService.userPoolSettings(ctx.priorPhysicalId()));
pool = cognitoService.updateUserPool(req, ctx.region());
} else {
pool = cognitoService.createUserPool(req, ctx.region());
@@ -236,6 +285,7 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {
UserPoolClient client;
if (prior != null && Objects.equals(userPoolId, prior.getUserPoolId())
&& generateSecret == prior.isGenerateSecret()) {
snapshot(r, cognitoService.userPoolClientSettings(userPoolId, prior.getClientId()));
client = cognitoService.updateUserPoolClient(
userPoolId, prior.getClientId(), clientName, allowedOAuthFlowsUserPoolClient,
allowedOAuthFlows, allowedOAuthScopes, analyticsConfiguration, callbackURLs,
@@ -357,6 +357,61 @@ public class CognitoService implements ResourceProvider {
return updatedPool;
}
/**
* A copy of the settings {@link #updateUserPool} can change, and nothing else (no signing
* material), for a caller that puts them back with {@link #restoreUserPoolSettings}: the rollback
* of a CloudFormation update that changed the pool in place.
*/
public UserPool userPoolSettings(String userPoolId) {
UserPool settings = new UserPool();
settings.setId(userPoolId);
copyUserPoolSettings(describeUserPool(userPoolId), settings);
return MAPPER.convertValue(settings, UserPool.class);
}
/**
* Puts back the settings {@link #userPoolSettings} copied, including clearing one the update
* added, which {@link #updateUserPool} cannot do since it only applies what a request names.
* Everything else on the pool, its users and signing keys among them, stays as it is now.
*/
public UserPool restoreUserPoolSettings(UserPool settings) {
UserPool pool = describeUserPool(settings.getId());
UserPool restored = MAPPER.convertValue(pool, UserPool.class);
copyUserPoolSettings(MAPPER.convertValue(settings, UserPool.class), restored);
restored.setLastModifiedDate(System.currentTimeMillis() / 1000L);
poolStore.put(restored.getId(), restored);
LOG.infov("Restored User Pool settings: {0}", restored.getId());
return restored;
}
/** The name and every field {@code populateUserPool} sets, which is what an update can change. */
private static void copyUserPoolSettings(UserPool from, UserPool to) {
to.setName(from.getName());
to.setPolicies(from.getPolicies());
to.setDeletionProtection(from.getDeletionProtection());
to.setLambdaConfig(from.getLambdaConfig());
to.setSchemaAttributes(from.getSchemaAttributes());
to.setAutoVerifiedAttributes(from.getAutoVerifiedAttributes());
to.setAliasAttributes(from.getAliasAttributes());
to.setUsernameAttributes(from.getUsernameAttributes());
to.setSmsVerificationMessage(from.getSmsVerificationMessage());
to.setEmailVerificationMessage(from.getEmailVerificationMessage());
to.setEmailVerificationSubject(from.getEmailVerificationSubject());
to.setVerificationMessageTemplate(from.getVerificationMessageTemplate());
to.setSmsAuthenticationMessage(from.getSmsAuthenticationMessage());
to.setMfaConfiguration(from.getMfaConfiguration());
to.setDeviceConfiguration(from.getDeviceConfiguration());
to.setEmailConfiguration(from.getEmailConfiguration());
to.setSmsConfiguration(from.getSmsConfiguration());
to.setUserPoolTags(from.getUserPoolTags());
to.setAdminCreateUserConfig(from.getAdminCreateUserConfig());
to.setUserPoolAddOns(from.getUserPoolAddOns());
to.setUsernameConfiguration(from.getUsernameConfiguration());
to.setAccountRecoverySetting(from.getAccountRecoverySetting());
to.setUserAttributeUpdateSettings(from.getUserAttributeUpdateSettings());
to.setUserPoolTier(from.getUserPoolTier());
}
public void addCustomAttributes(String userPoolId, List<Map<String, Object>> customAttributes) {
UserPool pool = describeUserPool(userPoolId);
List<Map<String, Object>> schema = pool.getSchemaAttributes();
@@ -1188,6 +1243,59 @@ public class CognitoService implements ResourceProvider {
return client;
}
/**
* A copy of the settings {@link #updateUserPoolClient} can change, for a caller that puts them
* back with {@link #restoreUserPoolClientSettings}: the rollback of a CloudFormation update that
* changed the client in place. A deep copy, since an update mutates the stored client.
*/
public UserPoolClient userPoolClientSettings(String userPoolId, String clientId) {
UserPoolClient settings = new UserPoolClient();
settings.setUserPoolId(userPoolId);
settings.setClientId(clientId);
copyUserPoolClientSettings(describeUserPoolClient(userPoolId, clientId), settings);
return MAPPER.convertValue(settings, UserPoolClient.class);
}
/**
* Puts back the settings {@link #userPoolClientSettings} copied, including clearing one the
* update added, which {@link #updateUserPoolClient} cannot do since a null there keeps the
* current value. The client's id, secrets and branding stay as they are now.
*/
public UserPoolClient restoreUserPoolClientSettings(UserPoolClient settings) {
UserPoolClient client = describeUserPoolClient(settings.getUserPoolId(), settings.getClientId());
UserPoolClient restored = MAPPER.convertValue(client, UserPoolClient.class);
copyUserPoolClientSettings(MAPPER.convertValue(settings, UserPoolClient.class), restored);
restored.setLastModifiedDate(System.currentTimeMillis() / 1000L);
clientStore.put(restored.getClientId(), restored);
LOG.infov("Restored User Pool Client settings: {0} for pool {1}", restored.getClientId(),
restored.getUserPoolId());
return restored;
}
/** The name and every field {@link #updateUserPoolClient} sets. */
private static void copyUserPoolClientSettings(UserPoolClient from, UserPoolClient to) {
to.setClientName(from.getClientName());
to.setAllowedOAuthFlowsUserPoolClient(from.isAllowedOAuthFlowsUserPoolClient());
to.setAllowedOAuthFlows(from.getAllowedOAuthFlows());
to.setAllowedOAuthScopes(from.getAllowedOAuthScopes());
to.setAnalyticsConfiguration(from.getAnalyticsConfiguration());
to.setCallbackURLs(from.getCallbackURLs());
to.setDefaultRedirectURI(from.getDefaultRedirectURI());
to.setExplicitAuthFlows(from.getExplicitAuthFlows());
to.setAccessTokenValidity(from.getAccessTokenValidity());
to.setIdTokenValidity(from.getIdTokenValidity());
to.setAuthSessionValidity(from.getAuthSessionValidity());
to.setLogoutURLs(from.getLogoutURLs());
to.setPreventUserExistenceErrors(from.getPreventUserExistenceErrors());
to.setReadAttributes(from.getReadAttributes());
to.setRefreshTokenValidity(from.getRefreshTokenValidity());
to.setSupportedIdentityProviders(from.getSupportedIdentityProviders());
to.setTokenValidityUnits(from.getTokenValidityUnits());
to.setWriteAttributes(from.getWriteAttributes());
to.setRefreshTokenRotation(from.getRefreshTokenRotation());
to.setEnableTokenRevocation(from.getEnableTokenRevocation());
}
private static void validateAuthSessionValidity(Integer authSessionValidity) {
if (authSessionValidity != null && (authSessionValidity < 3 || authSessionValidity > 15)) {
String constraint = authSessionValidity < 3
@@ -0,0 +1,147 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
/**
* A stack update that changes a Cognito user pool and its client in place and then fails on a later
* resource rolls both back: the pool and the client carry the settings they had before the update,
* including a setting the update added being cleared again, and the stack ends in
* UPDATE_ROLLBACK_COMPLETE rather than UPDATE_ROLLBACK_FAILED.
*/
@QuarkusTest
class CloudFormationCognitoUpdateRollbackIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TEMPLATE = """
{
"Resources": {
"Pool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {
"UserPoolName": "%s",
"UserPoolTags": {"team": "%s"}%s
}
},
"Client": {
"Type": "AWS::Cognito::UserPoolClient",
"Properties": {"UserPoolId": {"Ref": "Pool"}, "ClientName": "%s"}
}%s
},
"Outputs": {
"PoolId": {"Value": {"Ref": "Pool"}},
"ClientId": {"Value": {"Ref": "Client"}}
}
}
""";
private static final String FAILING_RESOURCE = """
,
"BadSecret": {
"Type": "AWS::SecretsManager::Secret",
"DependsOn": "Client",
"Properties": {
"Name": "cognito-rollback-%s",
"SecretString": "explicit",
"GenerateSecretString": {"PasswordLength": 32}
}
}""";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aFailedUpdatePutsThePoolAndTheClientBack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "cfn-cognito-rb-" + suffix;
String poolName = "pool-rb-" + suffix;
cloudFormation(stack, "CreateStack", TEMPLATE.formatted(poolName, "auth", "", "web", ""));
Map<String, String> outputs = outputs(describeStacks(stack, "CREATE_COMPLETE"));
String poolId = outputs.get("PoolId");
String clientId = outputs.get("ClientId");
String failingUpdate = TEMPLATE.formatted(poolName + "-v2", "data",
",\n \"AutoVerifiedAttributes\": [\"email\"]", "web-v2", FAILING_RESOURCE.formatted(suffix));
cloudFormation(stack, "UpdateStack", failingUpdate);
describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
describeUserPool(poolId).then()
.statusCode(200)
.body("UserPool.Name", equalTo(poolName))
.body("UserPool.UserPoolTags.team", equalTo("auth"))
.body("UserPool.AutoVerifiedAttributes", empty());
describeUserPoolClient(poolId, clientId).then()
.statusCode(200)
.body("UserPoolClient.ClientName", equalTo("web"));
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
private static void cloudFormation(String stack, String action, String templateBody) {
if (templateBody == null) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack)
.when().post("/").then().statusCode(200);
return;
}
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack)
.formParam("TemplateBody", templateBody)
.when().post("/").then().statusCode(200);
}
private static String describeStacks(String stack, String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
private static Map<String, String> outputs(String describeStacksXml) {
return XmlParser.extractPairs(describeStacksXml, "Outputs", "OutputKey", "OutputValue");
}
private static Response describeUserPool(String poolId) {
return given()
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPool")
.contentType(COGNITO_CONTENT_TYPE)
.body("{\"UserPoolId\": \"" + poolId + "\"}")
.when().post("/");
}
private static Response describeUserPoolClient(String poolId, String clientId) {
return given()
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPoolClient")
.contentType(COGNITO_CONTENT_TYPE)
.body("{\"UserPoolId\": \"" + poolId + "\", \"ClientId\": \"" + clientId + "\"}")
.when().post("/");
}
}
@@ -10,8 +10,9 @@ import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.util.HashMap;
import java.util.List;
@@ -35,6 +36,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -807,14 +809,101 @@ class CognitoCfnProvisionerTest {
}
@Test
void anInPlaceUserPoolClientUpdateCannotBeRolledBack() {
void anInPlaceUserPoolClientUpdateIsRolledBackFromTheSnapshotTakenBeforeIt() {
when(cognito.describeUserPoolClient(CLIENT_ID)).thenReturn(client("web", null));
stubClientUpdate(client("web", null));
UserPoolClient before = client("web", null);
before.setCallbackURLs(List.of("https://before.example.com/callback"));
when(cognito.userPoolClientSettings(POOL_ID, CLIENT_ID)).thenReturn(before);
stubClientUpdate(client("web-renamed", null));
StackResource r = resource(USER_POOL_CLIENT, "Client");
r.setPhysicalId(CLIENT_ID);
provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", POOL_ID), ctx(CLIENT_ID));
provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web-renamed"),
ctx(CLIENT_ID));
assertFalse(provisioner.rollbackUpdate(r));
InOrder order = inOrder(cognito);
order.verify(cognito).userPoolClientSettings(POOL_ID, CLIENT_ID);
order.verify(cognito).updateUserPoolClient(any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<UserPoolClient> restored = ArgumentCaptor.forClass(UserPoolClient.class);
verify(cognito).restoreUserPoolClientSettings(restored.capture());
assertEquals(CLIENT_ID, restored.getValue().getClientId());
assertEquals("web", restored.getValue().getClientName());
assertEquals(List.of("https://before.example.com/callback"), restored.getValue().getCallbackURLs());
assertFalse(r.getAttributes().containsKey(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR), "the snapshot is spent");
}
@Test
void anInPlaceUserPoolUpdateIsRolledBackFromTheSnapshotTakenBeforeIt() {
UserPool before = pool(POOL_ID, "my-pool");
before.setMfaConfiguration("OFF");
when(cognito.userPoolSettings(POOL_ID)).thenReturn(before);
when(cognito.updateUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "renamed-pool"));
StackResource r = resource(USER_POOL, "Pool");
r.setPhysicalId(POOL_ID);
provisioner.provision(r, mapper.createObjectNode().put("UserPoolName", "renamed-pool")
.put("MfaConfiguration", "OPTIONAL"), ctx(POOL_ID));
InOrder order = inOrder(cognito);
order.verify(cognito).userPoolSettings(POOL_ID);
order.verify(cognito).updateUserPool(any(), eq(REGION));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<UserPool> restored = ArgumentCaptor.forClass(UserPool.class);
verify(cognito).restoreUserPoolSettings(restored.capture());
assertEquals(POOL_ID, restored.getValue().getId());
assertEquals("my-pool", restored.getValue().getName());
assertEquals("OFF", restored.getValue().getMfaConfiguration());
assertFalse(r.getAttributes().containsKey(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR), "the snapshot is spent");
}
@Test
void aFailedRestoreKeepsTheSnapshotForTheNextAttempt() {
when(cognito.userPoolSettings(POOL_ID)).thenReturn(pool(POOL_ID, "my-pool"));
when(cognito.updateUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "renamed-pool"));
when(cognito.restoreUserPoolSettings(any()))
.thenThrow(new AwsException("InternalErrorException", "storage unavailable", 500));
StackResource r = resource(USER_POOL, "Pool");
r.setPhysicalId(POOL_ID);
provisioner.provision(r, mapper.createObjectNode().put("UserPoolName", "renamed-pool"), ctx(POOL_ID));
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertTrue(r.getAttributes().containsKey(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR));
}
@Test
void anInPlaceUpdateDropsItsSnapshotWhenTheUpdateCommits() {
// The engine's post-commit cleanup calls completeUpdate for every resource, but clearUpdate
// only after a replacement, so an in-place update relies on completeUpdate.
when(cognito.userPoolSettings(POOL_ID)).thenReturn(pool(POOL_ID, "my-pool"));
when(cognito.updateUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "renamed-pool"));
StackResource r = resource(USER_POOL, "Pool");
r.setPhysicalId(POOL_ID);
provisioner.provision(r, mapper.createObjectNode().put("UserPoolName", "renamed-pool"), ctx(POOL_ID));
assertTrue(r.getAttributes().containsKey(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR));
assertFalse(provisioner.completeUpdate(r).applicable(), "an in-place update owes no replacement cleanup");
assertFalse(r.getAttributes().containsKey(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR));
}
@Test
void aCommittedUpdateDropsTheSnapshotAndTheNextProvisionStartsWithoutOne() {
when(cognito.userPoolSettings(POOL_ID)).thenReturn(pool(POOL_ID, "my-pool"));
when(cognito.updateUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "renamed-pool"));
StackResource r = resource(USER_POOL, "Pool");
r.setPhysicalId(POOL_ID);
provisioner.provision(r, mapper.createObjectNode().put("UserPoolName", "renamed-pool"), ctx(POOL_ID));
provisioner.clearUpdate(r);
assertFalse(r.getAttributes().containsKey(CfnRollback.COGNITO_UPDATE_SNAPSHOT_ATTR));
assertTrue(provisioner.rollbackUpdate(r), "nothing to undo once the update committed");
verify(cognito, never()).restoreUserPoolSettings(any());
}
@Test
@@ -171,6 +171,43 @@ class CognitoServiceTest {
assertEquals(List.of("email"), pool.getUsernameAttributes());
}
@Test
void restoreUserPoolSettingsPutsBackWhatAnUpdateChangedAndKeepsTheSigningKeys() {
UserPool pool = service.createUserPool(Map.of("PoolName", "before"), "us-east-1");
String signingKeyId = service.describeUserPool(pool.getId()).getSigningKeyId();
UserPool settings = service.userPoolSettings(pool.getId());
assertNull(settings.getSigningPrivateKey(), "the settings copy carries no signing material");
service.updateUserPool(Map.of("UserPoolId", pool.getId(), "PoolName", "after",
"AutoVerifiedAttributes", List.of("email"), "MfaConfiguration", "OPTIONAL"), "us-east-1");
service.restoreUserPoolSettings(settings);
UserPool restored = service.describeUserPool(pool.getId());
assertEquals("before", restored.getName());
assertEquals(List.of(), restored.getAutoVerifiedAttributes(), "a setting the update added is cleared");
assertEquals("OFF", restored.getMfaConfiguration());
assertEquals(signingKeyId, restored.getSigningKeyId(), "the pool keeps the keys it signs with");
}
@Test
void restoreUserPoolClientSettingsPutsBackWhatAnUpdateChanged() {
UserPool pool = service.createUserPool(Map.of("PoolName", "pool"), "us-east-1");
UserPoolClient client = service.createUserPoolClient(pool.getId(), "web", false, false, List.of(), List.of());
UserPoolClient settings = service.userPoolClientSettings(pool.getId(), client.getClientId());
// The stored client is updated in place, so the expectation is copied before the update.
List<String> flowsBefore = List.copyOf(client.getExplicitAuthFlows());
service.updateUserPoolClient(pool.getId(), client.getClientId(), "web-v2", null, null, null, null,
null, null, List.of("ALLOW_USER_PASSWORD_AUTH"), null, null, null, null, null, null, null,
null, null, null, null);
service.restoreUserPoolClientSettings(settings);
UserPoolClient restored = service.describeUserPoolClient(pool.getId(), client.getClientId());
assertEquals("web", restored.getClientName());
assertEquals(flowsBefore, restored.getExplicitAuthFlows());
assertEquals(client.getClientId(), restored.getClientId());
}
@Test
void initiateAuthRejectsUnrecognizedAuthFlowWithoutIssuingTokens() {
UserPool pool = createPoolAndUser();