feat(cloudformation): provision Cognito user pool identity providers (#7350)

This commit is contained in:
Ronald Li 🛠️ authored and GitHub committed 2026-11-03 08:21:09 -04:00
1 parent 121dc22563
commit d0747f26d1
15 files changed
+1617 -345

No files matched your search

@@ -0,0 +1,211 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoPoolScopedLifecycle.Identity;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoPoolScopedLifecycle.Prior;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Provisions {@code AWS::Cognito::UserPoolIdentityProvider}. {@code Ref} is the bare
* {@code ProviderName}, while the provider is addressed by its pool and name, so the stack
* lifecycle is {@link CognitoPoolScopedLifecycle}'s. {@code ProviderDetails}, {@code AttributeMapping}
* and {@code IdpIdentifiers} update in place and roll back from a snapshot. A change to
* {@code UserPoolId} or {@code ProviderName} replaces the provider. {@code ProviderType} is
* create-only too, but the name is always the template's, so changing only the type would need a
* replacement at the same address, which, as on AWS, is refused before anything is changed.
*/
@ApplicationScoped
public class CognitoIdentityProviderCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::Cognito::UserPoolIdentityProvider";
private final CognitoService cognitoService;
private final CognitoPoolScopedLifecycle lifecycle;
@Inject
public CognitoIdentityProviderCfnProvisioner(CognitoService cognitoService) {
this.cognitoService = cognitoService;
this.lifecycle = new CognitoPoolScopedLifecycle("identity provider", "__FlociIdentityProviderPoolId",
"__FlociIdentityProviderUpdate", "providerName",
identity -> cognitoService.deleteIdentityProvider(identity.poolId(), identity.name()),
this::restore);
}
@Override
public Set<String> resourceTypes() {
return Set.of(TYPE);
}
@Override
public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {
String poolId = required(ctx.resolveOptional(properties, "UserPoolId"), "UserPoolId");
String providerName = required(ctx.resolveOptional(properties, "ProviderName"), "ProviderName");
String providerType = required(ctx.resolveOptional(properties, "ProviderType"), "ProviderType");
validateString(poolId, "UserPoolId", 55, "[\\w-]+_[0-9a-zA-Z]+");
validateString(providerName, "ProviderName", 32,
"[^_\\p{Z}][\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}][^_\\p{Z}]+");
if (!CognitoService.PROVIDER_TYPES.contains(providerType)) {
throw new AwsException("ValidationError", TYPE + " has invalid ProviderType", 400);
}
Map<String, String> providerDetails = stringMap(properties, "ProviderDetails", ctx);
if (providerDetails == null) {
throw new AwsException("ValidationError", TYPE + " requires ProviderDetails", 400);
}
Map<String, String> attributeMapping = stringMap(properties, "AttributeMapping", ctx);
List<String> idpIdentifiers = idpIdentifiers(properties, ctx);
lifecycle.beginUpdate(resource, ctx);
Prior prior = lifecycle.prior(resource, ctx);
Identity current = prior.identity();
boolean replacement = current != null
&& (!current.poolId().equals(poolId) || !current.name().equals(providerName));
Identity target = current;
if (current == null || replacement) {
cognitoService.createIdentityProvider(poolId, providerName, providerType, providerDetails,
attributeMapping, idpIdentifiers);
target = new Identity(poolId, providerName);
} else {
IdentityProvider existing = cognitoService.describeIdentityProvider(current.poolId(), current.name());
if (!providerType.equals(existing.getProviderType())) {
throw new AwsException("ValidationError",
"CloudFormation cannot update a stack when a custom-named resource requires "
+ "replacing. Rename " + providerName + " and update the stack again.", 400);
}
ObjectNode snapshot = lifecycle.snapshot(current);
snapshot.set("providerDetails", CognitoPoolScopedLifecycle.MAPPER.valueToTree(existing.getProviderDetails()));
snapshot.set("attributeMapping",
CognitoPoolScopedLifecycle.MAPPER.valueToTree(existing.getAttributeMapping()));
snapshot.set("idpIdentifiers", CognitoPoolScopedLifecycle.MAPPER.valueToTree(existing.getIdpIdentifiers()));
lifecycle.saveSnapshot(resource, snapshot);
cognitoService.updateIdentityProvider(poolId, providerName, providerDetails, attributeMapping,
idpIdentifiers);
}
lifecycle.commit(resource, ctx, prior, target);
}
/** Puts every in-place member back explicitly, so a value the update cleared returns too. */
private void restore(Identity identity, ObjectNode snapshot) {
cognitoService.updateIdentityProvider(identity.poolId(), identity.name(),
snapshotMap(snapshot.path("providerDetails")), snapshotMap(snapshot.path("attributeMapping")),
snapshotList(snapshot.path("idpIdentifiers")));
}
private static String required(String value, String property) {
if (value == null || value.isBlank()) {
throw new AwsException("ValidationError", TYPE + " requires " + property, 400);
}
return value;
}
private static void validateString(String value, String property, int maximum, String pattern) {
if (value.length() > maximum || !value.matches(pattern)) {
throw new AwsException("ValidationError", TYPE + " has invalid " + property, 400);
}
}
/** A map-of-strings property, or null when it is absent or resolves to {@code AWS::NoValue}. */
private static Map<String, String> stringMap(JsonNode properties, String property, ProvisionContext ctx) {
if (properties == null || !properties.has(property) || properties.get(property).isNull()) {
return null;
}
JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(properties.get(property));
if (resolved != null && resolved.isMissingNode()) {
return null;
}
if (resolved == null || !resolved.isObject()) {
throw new AwsException("ValidationError", TYPE + " " + property + " must be a map of strings", 400);
}
Map<String, String> values = new LinkedHashMap<>();
Iterator<Map.Entry<String, JsonNode>> fields = resolved.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
if (!field.getValue().isValueNode() || field.getValue().isNull()) {
throw new AwsException("ValidationError", TYPE + " " + property + " must be a map of strings", 400);
}
values.put(field.getKey(), field.getValue().asText());
}
return values;
}
/** The template's identifiers, or null when it declares none, so an update keeps the stored ones. */
private static List<String> idpIdentifiers(JsonNode properties, ProvisionContext ctx) {
if (properties == null || !properties.has("IdpIdentifiers") || properties.get("IdpIdentifiers").isNull()) {
return null;
}
List<String> identifiers = ctx.resolveStringList(properties, "IdpIdentifiers");
if (identifiers.size() > 50) {
throw new AwsException("ValidationError", TYPE + " allows at most 50 IdpIdentifiers", 400);
}
return identifiers;
}
private static Map<String, String> snapshotMap(JsonNode node) {
Map<String, String> values = new LinkedHashMap<>();
node.fields().forEachRemaining(field -> values.put(field.getKey(), field.getValue().asText()));
return values;
}
private static List<String> snapshotList(JsonNode node) {
List<String> values = new ArrayList<>();
node.forEach(value -> values.add(value.asText()));
return values;
}
@Override
public void delete(StackResource resource, String region) {
lifecycle.delete(resource, region);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
return lifecycle.rollbackUpdate(resource);
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return lifecycle.hasReplacementUpdate(resource);
}
@Override
public boolean retainsFailedUpdateState(StackResource resource) {
return lifecycle.retainsFailedUpdateState(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return lifecycle.updateCleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return lifecycle.completeUpdate(resource);
}
@Override
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
return lifecycle.completeDeleteCleanup(resource);
}
@Override
public void clearDeleteCleanup(StackResource resource) {
lifecycle.clearDeleteCleanup(resource);
}
@Override
public void clearUpdate(StackResource resource) {
lifecycle.clearUpdate(resource);
}
}
@@ -0,0 +1,370 @@
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 com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* Stack lifecycle shared by the Cognito types whose {@code Ref} is a bare name within a user pool,
* while Cognito addresses them by pool and name: {@code AWS::Cognito::UserPoolResourceServer} and
* {@code AWS::Cognito::UserPoolIdentityProvider}.
*
* <p>The pool lives in an attribute next to the bare physical id. Every lifecycle record works on a
* detached projection whose physical id is the encoded {@code [poolId, name]} pair, so
* {@link ReplacementCleanup} can delete a displaced entity from its own pool; no encoded id is ever
* assigned to the stack resource or passed to the template engine. An in-place update keeps a
* snapshot, written by the provisioner and put back by its {@link SnapshotRestorer}, so a failed
* update rolls back.
*/
final class CognitoPoolScopedLifecycle {
static final ObjectMapper MAPPER = new ObjectMapper();
/** A pool-scoped entity's address. */
record Identity(String poolId, String name) {
}
/** What an update found on the resource before provisioning it. */
record Prior(String physicalId, boolean stub, Identity identity) {
}
@FunctionalInterface
interface EntityDeleter {
void delete(Identity identity);
}
@FunctionalInterface
interface SnapshotRestorer {
void restore(Identity identity, ObjectNode snapshot);
}
private final String label;
private final String poolAttr;
private final String updateAttr;
private final String snapshotNameKey;
private final EntityDeleter deleter;
private final SnapshotRestorer restorer;
/**
* @param label the entity's name in messages, lower case (for example {@code "resource server"})
* @param poolAttr the attribute holding the owning pool id
* @param updateAttr the attribute holding an in-place update's snapshot
* @param snapshotNameKey the snapshot field naming the entity next to {@code poolId}
*/
CognitoPoolScopedLifecycle(String label, String poolAttr, String updateAttr, String snapshotNameKey,
EntityDeleter deleter, SnapshotRestorer restorer) {
this.label = label;
this.poolAttr = poolAttr;
this.updateAttr = updateAttr;
this.snapshotNameKey = snapshotNameKey;
this.deleter = deleter;
this.restorer = restorer;
}
/**
* Opens an update: ends the previous rollback's retry window and finishes a rollback the last
* attempt left pending, so its snapshot or cleanup identity is not overwritten.
*/
void beginUpdate(StackResource resource, ProvisionContext ctx) {
if (!ctx.isUpdate()) {
return;
}
// Rolling this update back undoes it alone; only ContinueUpdateRollback retries the
// delete the last rollback could not make.
ReplacementCleanup.endRollbackRetry(resource);
if (retainsFailedUpdateState(resource)) {
try {
rollbackUpdate(resource);
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
} catch (RuntimeException failure) {
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, failure.getMessage());
throw new IllegalStateException("Could not finish the previous " + label + " update rollback",
failure);
}
}
}
/** The resource's address before this provision: none on a create or a dispatcher stub. */
Prior prior(StackResource resource, ProvisionContext ctx) {
String priorPhysicalId = ctx.isUpdate() ? resource.getPhysicalId() : null;
boolean priorIsStub = ctx.isUpdate()
&& CfnResourceDispatcher.isStub(priorPhysicalId, resource.getAttributes());
Identity identity = ctx.isUpdate() && !priorIsStub ? identity(resource, priorPhysicalId) : null;
return new Prior(priorPhysicalId, priorIsStub, identity);
}
/** A snapshot holding the address, for the provisioner to add its in-place configuration to. */
ObjectNode snapshot(Identity identity) {
return MAPPER.createObjectNode().put("poolId", identity.poolId()).put(snapshotNameKey, identity.name());
}
void saveSnapshot(StackResource resource, ObjectNode snapshot) {
resource.getAttributes().put(updateAttr, snapshot.toString());
}
/** Assigns {@code target} to the resource and records what an update displaced or must roll back. */
void commit(StackResource resource, ProvisionContext ctx, Prior prior, Identity target) {
Map<String, String> attributesBefore = new HashMap<>(resource.getAttributes());
setIdentity(resource, target);
if (prior.stub()) {
resource.getAttributes().remove("Arn");
}
String cleanupPrior = prior.stub() ? prior.physicalId()
: prior.identity() == null ? null : encode(prior.identity());
ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(),
ctx.stackName(), cleanupPrior, ctx.progress(), ctx.priorProperties());
withProjection(resource, projected -> {
ReplacementCleanup.record(projected, cleanupContext, attributesBefore);
return null;
});
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
}
private Identity identity(StackResource resource, String name) {
String poolId = resource.getAttributes().get(poolAttr);
if (poolId == null || poolId.isBlank() || name == null || name.isBlank()) {
throw new IllegalStateException("Missing Cognito " + label + " identity for " + resource.getLogicalId());
}
return new Identity(poolId, name);
}
private void setIdentity(StackResource resource, Identity identity) {
resource.setPhysicalId(identity.name());
resource.getAttributes().put(poolAttr, identity.poolId());
}
private static String encode(Identity identity) {
return MAPPER.createArrayNode().add(identity.poolId()).add(identity.name()).toString();
}
private Identity decode(String physicalId) {
try {
JsonNode address = MAPPER.readTree(physicalId);
if (address != null && address.isArray() && address.size() == 2
&& address.get(0).isTextual() && !address.get(0).asText().isBlank()
&& address.get(1).isTextual() && !address.get(1).asText().isBlank()) {
return new Identity(address.get(0).asText(), address.get(1).asText());
}
} catch (JsonProcessingException invalid) {
throw new IllegalStateException("Invalid Cognito " + label + " cleanup address", invalid);
}
throw new IllegalStateException("Invalid Cognito " + label + " cleanup address");
}
/*
* Ref is only the name, whereas the entity's delete address also includes its pool.
* Only this detached view gives ReplacementCleanup the full address.
*/
private StackResource project(StackResource resource) {
StackResource projected = new StackResource();
projected.setLogicalId(resource.getLogicalId());
projected.setResourceType(resource.getResourceType());
projected.setStatus(resource.getStatus());
projected.setDeletionPolicy(resource.getDeletionPolicy());
projected.setUpdateReplacePolicy(resource.getUpdateReplacePolicy());
projected.setAttributes(new HashMap<>(resource.getAttributes()));
if (resource.getPhysicalId() != null) {
projected.setPhysicalId(CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())
? resource.getPhysicalId() : encode(identity(resource, resource.getPhysicalId())));
}
validateCleanup(projected);
return projected;
}
private <T> T withProjection(StackResource resource, Function<StackResource, T> operation) {
StackResource projected = project(resource);
try {
return operation.apply(projected);
} finally {
// Rollback restores the prior identity before deleting the replacement, even if that delete fails.
boolean restoredStub = CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes());
Identity restored = projected.getPhysicalId() == null || restoredStub
? null : decode(projected.getPhysicalId());
resource.getAttributes().clear();
resource.getAttributes().putAll(projected.getAttributes());
if (restoredStub) {
resource.setPhysicalId(projected.getPhysicalId());
resource.getAttributes().remove(poolAttr);
} else if (restored != null) {
setIdentity(resource, restored);
}
}
}
private void requireIdentity(Identity identity) {
if (identity.poolId().isBlank() || identity.name().isBlank()) {
throw new IllegalStateException("Invalid Cognito " + label + " lifecycle identity");
}
}
private void validateCleanup(StackResource projected) {
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
if (cleanup == null) {
return;
}
if (cleanup.has("displaced") && !cleanup.path("displaced").isArray()) {
throw new IllegalStateException("Invalid Cognito " + label + " cleanup entries");
}
for (JsonNode entry : cleanup.path("displaced")) {
if (!entry.isObject() || !entry.path("physicalId").isTextual()
|| entry.path("cleanupAttempts").asInt(0) < 0) {
throw new IllegalStateException("Invalid Cognito " + label + " cleanup entry");
}
decode(entry.path("physicalId").asText());
}
if (cleanup.hasNonNull("priorPhysicalId")) {
if (!cleanup.path("priorAttributes").isObject()) {
throw new IllegalStateException("Invalid Cognito " + label + " rollback attributes");
}
Map<String, String> priorAttributes = new HashMap<>();
cleanup.path("priorAttributes").fields()
.forEachRemaining(entry -> priorAttributes.put(entry.getKey(), entry.getValue().asText()));
String priorPhysicalId = cleanup.path("priorPhysicalId").asText();
if (!CfnResourceDispatcher.isStub(priorPhysicalId, priorAttributes)) {
decode(priorPhysicalId);
}
}
}
private void deleteAddress(String resourceType, String physicalId, String region) {
Identity identity = decode(physicalId);
CfnDeletes.safeDelete("Cognito " + label, identity.name(), () -> deleter.delete(identity),
"ResourceNotFoundException");
}
void delete(StackResource resource, String region) {
withProjection(resource, projected -> {
if (projected.getPhysicalId() != null
&& !CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes())) {
deleteAddress(projected.getResourceType(), projected.getPhysicalId(), region);
}
projected.getAttributes().remove(updateAttr);
projected.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
ReplacementCleanup.clear(projected);
return null;
});
}
boolean rollbackUpdate(StackResource resource) {
return withProjection(resource, projected -> {
if (ReplacementCleanup.rollback(projected, this::deleteAddress)) {
return true;
}
ObjectNode snapshot = read(projected, updateAttr);
if (snapshot == null) {
return false;
}
Identity prior = new Identity(snapshot.path("poolId").asText(), snapshot.path(snapshotNameKey).asText());
requireIdentity(prior);
restorer.restore(prior, snapshot);
projected.setPhysicalId(encode(prior));
projected.getAttributes().remove(updateAttr);
return true;
});
}
boolean hasReplacementUpdate(StackResource resource) {
return withProjection(resource, ReplacementCleanup::hasReplacement);
}
private boolean hasPendingRollback(StackResource projected) {
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
return projected.getAttributes().containsKey(updateAttr)
|| (cleanup != null && cleanup.hasNonNull("priorPhysicalId"));
}
boolean retainsFailedUpdateState(StackResource resource) {
return withProjection(resource, this::hasPendingRollback);
}
String updateCleanupPhysicalId(StackResource resource) {
return withProjection(resource, projected -> {
String physicalId = ReplacementCleanup.cleanupPhysicalId(projected);
return physicalId == null ? null : decode(physicalId).name();
});
}
private UpdateCleanupResult publicResult(UpdateCleanupResult result) {
String physicalId = result.previousPhysicalId();
return new UpdateCleanupResult(result.applicable(), result.complete(),
physicalId == null ? null : decode(physicalId).name(),
result.attempts(), result.failureReason());
}
UpdateCleanupResult completeUpdate(StackResource resource) {
return withProjection(resource, projected -> {
if ("UPDATE_FAILED".equals(projected.getStatus()) && hasPendingRollback(projected)) {
throw new IllegalStateException(Character.toUpperCase(label.charAt(0)) + label.substring(1)
+ " rollback is still pending; its original configuration cannot be discarded by "
+ "another resource's update cleanup");
}
boolean updated = projected.getAttributes().remove(updateAttr) != null;
ObjectNode committed = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
if (committed != null) {
// Committing the update spends its rollback identity, independently of delete retry debt.
committed.remove("priorPhysicalId");
committed.remove("priorAttributes");
projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, committed.toString());
}
UpdateCleanupResult cleanup = ReplacementCleanup.complete(projected, this::deleteAddress);
return !cleanup.applicable() && updated
? new UpdateCleanupResult(true, true, null, 0, null) : publicResult(cleanup);
});
}
UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
return withProjection(resource, projected -> publicResult(ReplacementCleanup.complete(projected,
this::deleteAddress)));
}
void clearDeleteCleanup(StackResource resource) {
withProjection(resource, projected -> {
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
JsonNode prior = cleanup == null ? null : cleanup.get("priorPhysicalId");
JsonNode attributes = cleanup == null ? null : cleanup.get("priorAttributes");
ReplacementCleanup.clear(projected);
if (prior != null) {
ObjectNode remaining = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
if (remaining == null) {
remaining = MAPPER.createObjectNode();
remaining.putArray("displaced");
}
remaining.set("priorPhysicalId", prior);
remaining.set("priorAttributes", attributes);
projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, remaining.toString());
}
return null;
});
}
void clearUpdate(StackResource resource) {
withProjection(resource, projected -> {
projected.getAttributes().remove(updateAttr);
ReplacementCleanup.clear(projected);
return null;
});
}
private ObjectNode read(StackResource resource, String attribute) {
String raw = resource.getAttributes().get(attribute);
if (raw == null) {
return null;
}
try {
JsonNode node = MAPPER.readTree(raw);
if (node instanceof ObjectNode object) {
return object;
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid Cognito " + label + " lifecycle record", e);
}
throw new IllegalStateException("Invalid Cognito " + label + " lifecycle record");
}
}
@@ -1,11 +1,11 @@
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 com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoPoolScopedLifecycle.Identity;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoPoolScopedLifecycle.Prior;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.cognito.model.ResourceServer;
import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;
@@ -13,25 +13,24 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
@ApplicationScoped
public class CognitoResourceServerCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::Cognito::UserPoolResourceServer";
private static final String POOL_ATTR = "__FlociResourceServerPoolId";
private static final String UPDATE_ATTR = "__FlociResourceServerUpdate";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final CognitoService cognitoService;
private final CognitoPoolScopedLifecycle lifecycle;
@Inject
public CognitoResourceServerCfnProvisioner(CognitoService cognitoService) {
this.cognitoService = cognitoService;
this.lifecycle = new CognitoPoolScopedLifecycle("resource server", "__FlociResourceServerPoolId",
"__FlociResourceServerUpdate", "identifier",
identity -> cognitoService.deleteResourceServer(identity.poolId(), identity.name()),
this::restore);
}
@Override
@@ -49,49 +48,29 @@ public class CognitoResourceServerCfnProvisioner implements CfnResourceProvision
validateString(name, "Name", 256, "[\\w\\s+=,.@-]+");
List<ResourceServerScope> scopes = scopes(properties, ctx);
if (ctx.isUpdate()) {
// Rolling this update back undoes it alone; only ContinueUpdateRollback retries the
// delete the last rollback could not make.
ReplacementCleanup.endRollbackRetry(resource);
}
if (ctx.isUpdate() && retainsFailedUpdateState(resource)) {
try {
rollbackUpdate(resource);
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
} catch (RuntimeException failure) {
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, failure.getMessage());
throw new IllegalStateException("Could not finish the previous resource server update rollback", failure);
}
}
String priorPhysicalId = ctx.isUpdate() ? resource.getPhysicalId() : null;
boolean priorIsStub = ctx.isUpdate()
&& CfnResourceDispatcher.isStub(priorPhysicalId, resource.getAttributes());
Identity prior = ctx.isUpdate() && !priorIsStub ? identity(resource, priorPhysicalId) : null;
boolean replacement = prior != null
&& (!prior.poolId().equals(poolId) || !prior.identifier().equals(identifier));
Identity target = prior;
if (prior == null || replacement) {
lifecycle.beginUpdate(resource, ctx);
Prior prior = lifecycle.prior(resource, ctx);
Identity current = prior.identity();
boolean replacement = current != null
&& (!current.poolId().equals(poolId) || !current.name().equals(identifier));
Identity target = current;
if (current == null || replacement) {
cognitoService.createResourceServer(poolId, identifier, name, scopes);
target = new Identity(poolId, identifier);
} else {
ResourceServer existing = cognitoService.describeResourceServer(prior.poolId(), prior.identifier());
resource.getAttributes().put(UPDATE_ATTR, snapshot(prior, existing).toString());
ResourceServer existing = cognitoService.describeResourceServer(current.poolId(), current.name());
ObjectNode snapshot = lifecycle.snapshot(current);
snapshot.put("name", existing.getName());
snapshot.set("scopes", CognitoPoolScopedLifecycle.MAPPER.valueToTree(existing.getScopes()));
lifecycle.saveSnapshot(resource, snapshot);
cognitoService.updateResourceServer(poolId, identifier, name, scopes);
}
Map<String, String> attributesBefore = new HashMap<>(resource.getAttributes());
setIdentity(resource, target);
if (priorIsStub) {
resource.getAttributes().remove("Arn");
}
ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(),
ctx.stackName(), priorIsStub ? priorPhysicalId : prior == null ? null : encode(prior),
ctx.progress(), ctx.priorProperties());
withProjection(resource, projected -> {
ReplacementCleanup.record(projected, cleanupContext, attributesBefore);
return null;
});
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
lifecycle.commit(resource, ctx, prior, target);
}
private void restore(Identity identity, ObjectNode snapshot) {
cognitoService.updateResourceServer(identity.poolId(), identity.name(), snapshot.path("name").asText(),
scopes(snapshot.path("scopes")));
}
private static String required(String value, String property) {
@@ -131,6 +110,17 @@ public class CognitoResourceServerCfnProvisioner implements CfnResourceProvision
return scopes;
}
private static List<ResourceServerScope> scopes(JsonNode nodes) {
List<ResourceServerScope> scopes = new ArrayList<>();
for (JsonNode node : nodes) {
ResourceServerScope scope = new ResourceServerScope();
scope.setScopeName(node.path("scopeName").asText());
scope.setScopeDescription(node.path("scopeDescription").asText(null));
scopes.add(scope);
}
return scopes;
}
private static void validateString(String value, String property, int maximum, String pattern) {
if (value.length() > maximum || !value.matches(pattern)) {
throw new AwsException("ValidationError", TYPE + " has invalid " + property, 400);
@@ -145,287 +135,48 @@ public class CognitoResourceServerCfnProvisioner implements CfnResourceProvision
return !value.isEmpty() && value.length() <= 256;
}
private record Identity(String poolId, String identifier) {
}
private static Identity identity(StackResource resource, String identifier) {
String poolId = resource.getAttributes().get(POOL_ATTR);
if (poolId == null || poolId.isBlank() || identifier == null || identifier.isBlank()) {
throw new IllegalStateException("Missing Cognito resource server identity for " + resource.getLogicalId());
}
return new Identity(poolId, identifier);
}
private static Identity identity(JsonNode node) {
return new Identity(node.path("poolId").asText(), node.path("identifier").asText());
}
private static void setIdentity(StackResource resource, Identity identity) {
resource.setPhysicalId(identity.identifier());
resource.getAttributes().put(POOL_ATTR, identity.poolId());
}
private static ObjectNode address(Identity identity) {
return MAPPER.createObjectNode().put("poolId", identity.poolId()).put("identifier", identity.identifier());
}
private static ObjectNode snapshot(Identity identity, ResourceServer server) {
ObjectNode snapshot = address(identity);
snapshot.put("name", server.getName());
snapshot.set("scopes", MAPPER.valueToTree(server.getScopes()));
return snapshot;
}
private static String encode(Identity identity) {
return MAPPER.createArrayNode().add(identity.poolId()).add(identity.identifier()).toString();
}
private static Identity decode(String physicalId) {
try {
JsonNode address = MAPPER.readTree(physicalId);
if (address != null && address.isArray() && address.size() == 2
&& address.get(0).isTextual() && !address.get(0).asText().isBlank()
&& address.get(1).isTextual() && !address.get(1).asText().isBlank()) {
return new Identity(address.get(0).asText(), address.get(1).asText());
}
} catch (JsonProcessingException invalid) {
throw new IllegalStateException("Invalid Cognito resource server cleanup address", invalid);
}
throw new IllegalStateException("Invalid Cognito resource server cleanup address");
}
/*
* Ref is only Identifier, whereas a resource server's delete address also includes its pool.
* Only this detached view gives ReplacementCleanup the full address; no encoded id is assigned
* to the stack resource or passed to the template engine.
*/
private static StackResource project(StackResource resource) {
StackResource projected = new StackResource();
projected.setLogicalId(resource.getLogicalId());
projected.setResourceType(resource.getResourceType());
projected.setStatus(resource.getStatus());
projected.setDeletionPolicy(resource.getDeletionPolicy());
projected.setUpdateReplacePolicy(resource.getUpdateReplacePolicy());
projected.setAttributes(new HashMap<>(resource.getAttributes()));
if (resource.getPhysicalId() != null) {
projected.setPhysicalId(CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())
? resource.getPhysicalId() : encode(identity(resource, resource.getPhysicalId())));
}
validateCleanup(projected);
return projected;
}
private static <T> T withProjection(StackResource resource, Function<StackResource, T> operation) {
StackResource projected = project(resource);
try {
return operation.apply(projected);
} finally {
// Rollback restores the prior identity before deleting the replacement, even if that delete fails.
boolean restoredStub = CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes());
Identity restored = projected.getPhysicalId() == null || restoredStub
? null : decode(projected.getPhysicalId());
resource.getAttributes().clear();
resource.getAttributes().putAll(projected.getAttributes());
if (restoredStub) {
resource.setPhysicalId(projected.getPhysicalId());
resource.getAttributes().remove(POOL_ATTR);
} else if (restored != null) {
setIdentity(resource, restored);
}
}
}
private static void requireIdentity(Identity identity) {
if (identity.poolId().isBlank() || identity.identifier().isBlank()) {
throw new IllegalStateException("Invalid Cognito resource server lifecycle identity");
}
}
private static void validateCleanup(StackResource projected) {
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
if (cleanup == null) {
return;
}
if (cleanup.has("displaced") && !cleanup.path("displaced").isArray()) {
throw new IllegalStateException("Invalid Cognito resource server cleanup entries");
}
for (JsonNode entry : cleanup.path("displaced")) {
if (!entry.isObject() || !entry.path("physicalId").isTextual()
|| entry.path("cleanupAttempts").asInt(0) < 0) {
throw new IllegalStateException("Invalid Cognito resource server cleanup entry");
}
decode(entry.path("physicalId").asText());
}
if (cleanup.hasNonNull("priorPhysicalId")) {
if (!cleanup.path("priorAttributes").isObject()) {
throw new IllegalStateException("Invalid Cognito resource server rollback attributes");
}
Map<String, String> priorAttributes = new HashMap<>();
cleanup.path("priorAttributes").fields()
.forEachRemaining(entry -> priorAttributes.put(entry.getKey(), entry.getValue().asText()));
String priorPhysicalId = cleanup.path("priorPhysicalId").asText();
if (!CfnResourceDispatcher.isStub(priorPhysicalId, priorAttributes)) {
decode(priorPhysicalId);
}
}
}
private void deleteAddress(String resourceType, String physicalId, String region) {
delete(decode(physicalId));
}
private void delete(Identity identity) {
CfnDeletes.safeDelete("Cognito resource server", identity.identifier(),
() -> cognitoService.deleteResourceServer(identity.poolId(), identity.identifier()),
"ResourceNotFoundException");
}
@Override
public void delete(StackResource resource, String region) {
withProjection(resource, projected -> {
if (projected.getPhysicalId() != null
&& !CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes())) {
deleteAddress(projected.getResourceType(), projected.getPhysicalId(), region);
}
projected.getAttributes().remove(UPDATE_ATTR);
projected.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
ReplacementCleanup.clear(projected);
return null;
});
lifecycle.delete(resource, region);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
return withProjection(resource, projected -> {
if (ReplacementCleanup.rollback(projected, this::deleteAddress)) {
return true;
}
ObjectNode snapshot = read(projected, UPDATE_ATTR);
if (snapshot == null) {
return false;
}
Identity prior = identity(snapshot);
requireIdentity(prior);
cognitoService.updateResourceServer(prior.poolId(), prior.identifier(), snapshot.path("name").asText(),
scopes(snapshot.path("scopes")));
projected.setPhysicalId(encode(prior));
projected.getAttributes().remove(UPDATE_ATTR);
return true;
});
}
private static List<ResourceServerScope> scopes(JsonNode nodes) {
List<ResourceServerScope> scopes = new ArrayList<>();
for (JsonNode node : nodes) {
ResourceServerScope scope = new ResourceServerScope();
scope.setScopeName(node.path("scopeName").asText());
scope.setScopeDescription(node.path("scopeDescription").asText(null));
scopes.add(scope);
}
return scopes;
return lifecycle.rollbackUpdate(resource);
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return withProjection(resource, ReplacementCleanup::hasReplacement);
}
private static boolean hasPendingRollback(StackResource projected) {
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
return projected.getAttributes().containsKey(UPDATE_ATTR)
|| (cleanup != null && cleanup.hasNonNull("priorPhysicalId"));
return lifecycle.hasReplacementUpdate(resource);
}
@Override
public boolean retainsFailedUpdateState(StackResource resource) {
return withProjection(resource, CognitoResourceServerCfnProvisioner::hasPendingRollback);
return lifecycle.retainsFailedUpdateState(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return withProjection(resource, projected -> {
String physicalId = ReplacementCleanup.cleanupPhysicalId(projected);
return physicalId == null ? null : decode(physicalId).identifier();
});
}
private static UpdateCleanupResult publicResult(UpdateCleanupResult result) {
String physicalId = result.previousPhysicalId();
return new UpdateCleanupResult(result.applicable(), result.complete(),
physicalId == null ? null : decode(physicalId).identifier(),
result.attempts(), result.failureReason());
return lifecycle.updateCleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return withProjection(resource, projected -> {
if ("UPDATE_FAILED".equals(projected.getStatus()) && hasPendingRollback(projected)) {
throw new IllegalStateException("Resource server rollback is still pending; its original configuration "
+ "cannot be discarded by another resource's update cleanup");
}
boolean updated = projected.getAttributes().remove(UPDATE_ATTR) != null;
ObjectNode committed = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
if (committed != null) {
// Committing the update spends its rollback identity, independently of delete retry debt.
committed.remove("priorPhysicalId");
committed.remove("priorAttributes");
projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, committed.toString());
}
UpdateCleanupResult cleanup = ReplacementCleanup.complete(projected, this::deleteAddress);
return !cleanup.applicable() && updated
? new UpdateCleanupResult(true, true, null, 0, null) : publicResult(cleanup);
});
return lifecycle.completeUpdate(resource);
}
@Override
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
return withProjection(resource, projected -> publicResult(ReplacementCleanup.complete(projected,
this::deleteAddress)));
return lifecycle.completeDeleteCleanup(resource);
}
@Override
public void clearDeleteCleanup(StackResource resource) {
withProjection(resource, projected -> {
ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
JsonNode prior = cleanup == null ? null : cleanup.get("priorPhysicalId");
JsonNode attributes = cleanup == null ? null : cleanup.get("priorAttributes");
ReplacementCleanup.clear(projected);
if (prior != null) {
ObjectNode remaining = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);
if (remaining == null) {
remaining = MAPPER.createObjectNode();
remaining.putArray("displaced");
}
remaining.set("priorPhysicalId", prior);
remaining.set("priorAttributes", attributes);
projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, remaining.toString());
}
return null;
});
lifecycle.clearDeleteCleanup(resource);
}
@Override
public void clearUpdate(StackResource resource) {
withProjection(resource, projected -> {
projected.getAttributes().remove(UPDATE_ATTR);
ReplacementCleanup.clear(projected);
return null;
});
}
private static ObjectNode read(StackResource resource, String attribute) {
String raw = resource.getAttributes().get(attribute);
if (raw == null) {
return null;
}
try {
JsonNode node = MAPPER.readTree(raw);
if (node instanceof ObjectNode object) {
return object;
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid Cognito resource server lifecycle record", e);
}
throw new IllegalStateException("Invalid Cognito resource server lifecycle record");
lifecycle.clearUpdate(resource);
}
}
@@ -1664,7 +1664,7 @@ public class CognitoService implements ResourceProvider {
// ──────────────────────────── Identity Providers ────────────────────────────
private static final Set<String> PROVIDER_TYPES =
public static final Set<String> PROVIDER_TYPES =
Set.of("Facebook", "SAML", "SignInWithApple", "LoginWithAmazon", "OIDC", "Google");
public IdentityProvider createIdentityProvider(String userPoolId, String providerName, String providerType,