Light, fluffy, and always free - The AWS Local Emulator alternative
refactor(cloudformation): move Cognito UserPool and UserPoolClient to CognitoCfnProvisioner (#3164)
Hector Ventura0321ae0ac8ad
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 887cb3061e..2a7f16486f 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -90,7 +90,7 @@ cross-resource references.| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` || CodeBuild | `Project` || Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |-| Cognito | `UserPool`, `UserPoolClient`, `UserPoolDomain` |+| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`), `UserPoolClient`, `UserPoolDomain` || ACM | `Certificate` || EventBridge | `Rule`, `EventBus`, `EventBusPolicy` || EventBridge Scheduler | `ScheduleGroup` |diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex cec665961f..886030ad54 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -87,9 +87,6 @@ import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;import io.github.hectorvent.floci.services.apigatewayv2.model.*;-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.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;@@ -213,8 +210,6 @@ public class CloudFormationResourceProvisioner {"AWS::Batch::JobQueue","AWS::CloudFormation::CustomResource","AWS::CloudFront::Distribution",- "AWS::Cognito::UserPool",- "AWS::Cognito::UserPoolClient","AWS::DynamoDB::GlobalTable","AWS::DynamoDB::Table","AWS::EC2::EIP",@@ -272,7 +267,6 @@ public class CloudFormationResourceProvisioner {private final EventBridgeService eventBridgeService;private final ApiGatewayService apiGatewayService;private final ApiGatewayV2Service apiGatewayV2Service;- private final CognitoService cognitoService;private final LambdaLayerService lambdaLayerService;private final ObjectMapper objectMapper;private final CustomResourceResponseStore customResourceResponseStore;@@ -304,7 +298,6 @@ public class CloudFormationResourceProvisioner {ApiGatewayV2Service apiGatewayV2Service,EcrService ecrService,PipesService pipesService,- CognitoService cognitoService,LambdaLayerService lambdaLayerService,ObjectMapper objectMapper,CustomResourceResponseStore customResourceResponseStore,@@ -334,7 +327,6 @@ public class CloudFormationResourceProvisioner {this.eventBridgeService = eventBridgeService;this.apiGatewayService = apiGatewayService;this.apiGatewayV2Service = apiGatewayV2Service;- this.cognitoService = cognitoService;this.lambdaLayerService = lambdaLayerService;this.objectMapper = objectMapper;this.customResourceResponseStore = customResourceResponseStore;@@ -430,10 +422,6 @@ public class CloudFormationResourceProvisioner {region,accountId,stackName);- case "AWS::Cognito::UserPool" ->- provisionCognitoUserPool(resource, properties, engine, region, accountId, stackName);- case "AWS::Cognito::UserPoolClient" ->- provisionCognitoUserPoolClient(resource, properties, engine, region, accountId, stackName);case "AWS::CloudFormation::CustomResource" ->provisionCustomResource(resource, properties, engine, region, accountId, stackName);case "Custom::DynamoDBReplica" -> provisionDynamoDbReplica(resource, properties, engine, region);@@ -718,8 +706,6 @@ public class CloudFormationResourceProvisioner {case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);case "AWS::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId);case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);- case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);- case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);case "AWS::ElasticLoadBalancingV2::LoadBalancer" -> elbV2Service.deleteLoadBalancer(region, physicalId);case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);case "AWS::ElasticLoadBalancingV2::Listener" -> elbV2Service.deleteListener(region, physicalId);@@ -5770,97 +5756,6 @@ public class CloudFormationResourceProvisioner {r.setPhysicalId(deployment.getDeploymentId());}- // ── Cognito ──────────────────────────────────────────────────────────────-- private void provisionCognitoUserPool(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,- String region, String accountId, String stackName) {- String poolName = resolveOptional(props, "UserPoolName", engine);- if (poolName == null || poolName.isBlank()) {- poolName = generatePhysicalName(stackName, r.getLogicalId(), 128, false);- }-- Map<String, Object> req = new HashMap<>();- if (props != null) {- req.putAll(jsonObjectToMap(engine.resolveNode(props)));- }- req.put("PoolName", poolName);-- // Handle Tags- Map<String, String> tags = parseCfnTags(props != null ? props.get("UserPoolTags") : null, engine);- if (!tags.isEmpty()) {- req.put("UserPoolTags", tags);- }-- UserPool pool;- if (r.getPhysicalId() == null) {- pool = cognitoService.createUserPool(req, region);- } else {- req.put("UserPoolId", r.getPhysicalId());- pool = cognitoService.updateUserPool(req, region);- }-- r.setPhysicalId(pool.getId());- r.getAttributes().put("Arn", pool.getArn());- r.getAttributes().put("UserPoolId", pool.getId());- r.getAttributes().put("ProviderName", pool.getName());- r.getAttributes().put("ProviderURL", cognitoService.getIssuer(pool.getId()));- }-- private void provisionCognitoUserPoolClient(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,- String region, String accountId, String stackName) {- String userPoolId = resolveOptional(props, "UserPoolId", engine);- String clientName = resolveOptional(props, "ClientName", engine);- if (clientName == null || clientName.isBlank()) {- clientName = generatePhysicalName(stackName, r.getLogicalId(), 128, false);- }- boolean generateSecret = Boolean.parseBoolean(resolveOrDefault(props, "GenerateSecret", engine, "false"));- boolean allowedOAuthFlowsUserPoolClient = Boolean.parseBoolean(resolveOrDefault(props, "AllowedOAuthFlowsUserPoolClient", engine, "false"));- List<String> allowedOAuthFlows = resolveStringListOrEmpty(props, "AllowedOAuthFlows", engine);- List<String> allowedOAuthScopes = resolveStringListOrEmpty(props, "AllowedOAuthScopes", engine);-- Map<String, Object> analyticsConfiguration = resolveMapOrDefault(props, "AnalyticsConfiguration", engine, null);- List<String> callbackURLs = resolveStringListOrEmpty(props, "CallbackURLs", engine);- String defaultRedirectURI = resolveOptional(props, "DefaultRedirectURI", engine);- List<String> explicitAuthFlows = resolveStringListOrEmpty(props, "ExplicitAuthFlows", engine);- Integer accessTokenValidity = parseIntegerPropOrNull(props, "AccessTokenValidity", engine);- Integer idTokenValidity = parseIntegerPropOrNull(props, "IdTokenValidity", engine);- List<String> logoutURLs = resolveStringListOrEmpty(props, "LogoutURLs", engine);- String preventUserExistenceErrors = resolveOptional(props, "PreventUserExistenceErrors", engine);- List<String> readAttributes = resolveStringListOrEmpty(props, "ReadAttributes", engine);- Integer refreshTokenValidity = parseIntegerPropOrNull(props, "RefreshTokenValidity", engine);- List<String> supportedIdentityProviders = resolveStringListOrEmpty(props, "SupportedIdentityProviders", engine);- Map<String, String> tokenValidityUnits = resolveStringMapOrNull(props, "TokenValidityUnits", engine);- List<String> writeAttributes = resolveStringListOrEmpty(props, "WriteAttributes", engine);- Map<String, Object> refreshTokenRotation = resolveMapOrDefault(props, "RefreshTokenRotation", engine, null);- Boolean enableTokenRevocation = parseBooleanOrNull(resolveOptional(props, "EnableTokenRevocation", engine));-- UserPoolClient client;- if (r.getPhysicalId() == null) {- client = cognitoService.createUserPoolClient(- userPoolId, clientName, generateSecret, allowedOAuthFlowsUserPoolClient,- allowedOAuthFlows, allowedOAuthScopes, analyticsConfiguration, callbackURLs,- defaultRedirectURI, explicitAuthFlows, accessTokenValidity, idTokenValidity,- logoutURLs, preventUserExistenceErrors, readAttributes, refreshTokenValidity,- supportedIdentityProviders, tokenValidityUnits, writeAttributes,- refreshTokenRotation, enableTokenRevocation);- } else {- client = cognitoService.updateUserPoolClient(- userPoolId, r.getPhysicalId(), clientName, allowedOAuthFlowsUserPoolClient,- allowedOAuthFlows, allowedOAuthScopes, analyticsConfiguration, callbackURLs,- defaultRedirectURI, explicitAuthFlows, accessTokenValidity, idTokenValidity,- logoutURLs, preventUserExistenceErrors, readAttributes, refreshTokenValidity,- supportedIdentityProviders, tokenValidityUnits, writeAttributes,- refreshTokenRotation, enableTokenRevocation);- }-- r.setPhysicalId(client.getClientId());- r.getAttributes().put("ClientId", client.getClientId());- r.getAttributes().put("ClientName", client.getClientName());- if (client.getClientSecret() != null) {- r.getAttributes().put("ClientSecret", client.getClientSecret());- }- }-private Integer parseIntegerPropOrNull(JsonNode props, String name, CloudFormationTemplateEngine engine) {String value = resolveOptional(props, name, engine);if (value == null || value.isBlank()) {@@ -5873,19 +5768,6 @@ public class CloudFormationResourceProvisioner {}}- private Map<String, String> resolveStringMapOrNull(JsonNode props, String source, CloudFormationTemplateEngine engine) {- if (props == null || !props.has(source) || props.get(source).isNull()) {- return null;- }- JsonNode resolved = engine.resolveNode(props.get(source));- if (resolved == null || !resolved.isObject()) {- return null;- }- Map<String, String> out = new LinkedHashMap<>();- resolved.fields().forEachRemaining(e -> out.put(e.getKey(), e.getValue().asText()));- return out;- }-// ── Lambda LayerVersion ──────────────────────────────────────────────────//// Without this, layer versions (e.g. CDK's AwsCliLayer) fall through to the stub, so thediff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisioner.javaindex 0ecf39f711..1786b6614a 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisioner.java@@ -4,22 +4,39 @@ import com.fasterxml.jackson.databind.JsonNode;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;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 jakarta.enterprise.context.ApplicationScoped;import org.jboss.logging.Logger;+import java.util.ArrayList;+import java.util.HashMap;import java.util.LinkedHashMap;+import java.util.List;import java.util.Map;+import java.util.Objects;import java.util.Set;+import java.util.function.Supplier;/**- * Provisions {@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+ * Provisions the Cognito user pool types.+ *+ * <p>{@code AWS::Cognito::UserPool}: the physical id is the pool id, the whole resolved property+ * set is handed to the service as the API request, and the pool name falls back to a generated one.+ * {@code Fn::GetAtt ProviderName} has AWS's shape, {@code cognito-idp.<region>.amazonaws.com/<id>},+ * while {@code ProviderURL} is the issuer of the tokens Floci mints, {@code <base-url>/<id>}.+ * {@code AWS::Cognito::UserPoolClient}: the physical id is the client id and {@code ClientSecret}+ * is only an attribute when the client has one, as on AWS. A pool is updated in place. A client is+ * 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.+ *+ * <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* points at. A prefix domain has no distribution of its own in Floci, so for one the attribute is* empty rather than the literal {@code LogicalId.CloudFrontDistribution} an unset attribute yields.- *- * <p>{@code Routing} (regional failover) is accepted and ignored; nothing in the emulator fails- * over. {@code AWS::Cognito::UserPool} and {@code UserPoolClient} still live in the legacy switch.+ * {@code Routing} (regional failover) is accepted and ignored; nothing in the emulator fails over.*/@ApplicationScopedpublic class CognitoCfnProvisioner implements CfnResourceProvisioner {@@ -27,6 +44,19 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {private static final Logger LOG = Logger.getLogger(CognitoCfnProvisioner.class);private static final String NOT_FOUND = "ResourceNotFoundException";+ private static final String USER_POOL = "AWS::Cognito::UserPool";+ private static final String USER_POOL_CLIENT = "AWS::Cognito::UserPoolClient";+ private static final String USER_POOL_DOMAIN = "AWS::Cognito::UserPoolDomain";++ /**+ * Serialises the existence check and the create of a client whose id is derived from its name.+ * The service's store write is unconditional and the engine runs stack operations on a thread+ * pool, so two stacks could otherwise both find the id free and the later create would+ * overwrite the earlier stack's client. Static so every instance, the CDI bean and the test+ * fixture's, shares it.+ */+ private static final Object DETERMINISTIC_CLIENT_ID_LOCK = new Object();+private final CognitoService cognitoService;public CognitoCfnProvisioner(CognitoService cognitoService) {@@ -35,11 +65,220 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {@Overridepublic Set<String> resourceTypes() {- return Set.of("AWS::Cognito::UserPoolDomain");+ return Set.of(USER_POOL, USER_POOL_CLIENT, USER_POOL_DOMAIN);}@Overridepublic void provision(StackResource r, JsonNode props, ProvisionContext ctx) {+ switch (r.getResourceType()) {+ case USER_POOL -> {+ Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());+ provisionUserPool(r, props, ctx);+ ReplacementCleanup.record(r, ctx, attributesBefore);+ }+ case USER_POOL_CLIENT -> {+ Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());+ provisionUserPoolClient(r, props, ctx);+ ReplacementCleanup.record(r, ctx, attributesBefore);+ }+ // The domain replaces and removes its predecessor within the provision itself, since the+ // domain name is unique across pools, so it keeps no cleanup record.+ case USER_POOL_DOMAIN -> provisionUserPoolDomain(r, props, ctx);+ default -> throw new IllegalStateException("CognitoCfnProvisioner cannot handle " + r.getResourceType());+ }+ }++ /**+ * A user pool domain deletes from the pool recorded at create time, since DeleteUserPoolDomain+ * needs both; without that record it looks the pool up. The other types delete by id.+ */+ @Override+ public void delete(StackResource resource, String region) {+ if (!USER_POOL_DOMAIN.equals(resource.getResourceType())) {+ delete(resource.getResourceType(), resource.getPhysicalId(), region);+ return;+ }+ String userPoolId = resource.getAttributes() == null ? null : resource.getAttributes().get("UserPoolId");+ if (userPoolId == null || userPoolId.isBlank()) {+ delete(resource.getResourceType(), resource.getPhysicalId(), region);+ return;+ }+ deleteDomain(resource.getPhysicalId(), userPoolId);+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ if (physicalId == null || physicalId.isBlank()) {+ return;+ }+ switch (resourceType) {+ // Only the service's own not-found code is tolerated. A pool that still has a domain is+ // refused with InvalidParameterException, and that must fail the stack delete as it does+ // on AWS; in a stack the domain resource depends on the pool, so it is deleted first.+ case USER_POOL -> CfnDeletes.safeDelete("user pool", physicalId,+ () -> cognitoService.deleteUserPool(physicalId), NOT_FOUND);+ case USER_POOL_CLIENT -> CfnDeletes.safeDelete("user pool client", physicalId,+ () -> cognitoService.deleteUserPoolClient(physicalId), NOT_FOUND);+ // Only the domain itself can say which pool owns it here; one already gone needs nothing.+ case USER_POOL_DOMAIN -> {+ UserPoolDomain existing = findExisting(physicalId);+ if (existing != null) {+ deleteDomain(physicalId, existing.getUserPoolId());+ }+ }+ default -> { }+ }+ }++ @Override+ public boolean hasReplacementUpdate(StackResource resource) {+ return ReplacementCleanup.hasReplacement(resource);+ }++ @Override+ public String updateCleanupPhysicalId(StackResource resource) {+ return ReplacementCleanup.cleanupPhysicalId(resource);+ }++ @Override+ public UpdateCleanupResult completeUpdate(StackResource resource) {+ return ReplacementCleanup.complete(resource, this::delete);+ }++ @Override+ public void clearUpdate(StackResource resource) {+ 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.+ */+ @Override+ public boolean rollbackUpdate(StackResource resource) {+ return ReplacementCleanup.rollback(resource, this::delete);+ }++ private void provisionUserPool(StackResource r, JsonNode props, ProvisionContext ctx) {+ Map<String, Object> req = new HashMap<>();+ if (props != null) {+ req.putAll(jsonObjectToMap(ctx.engine().resolveNode(props)));+ }+ // UserPoolName is updatable in place. A pool the template does not name keeps the name its+ // first execution generated: sending a fresh generated name on every update would rename it.+ String poolName = ctx.resolveOptional(props, "UserPoolName");+ if (poolName != null && !poolName.isBlank()) {+ req.put("PoolName", poolName);+ } else if (!ctx.isUpdate()) {+ req.put("PoolName", ctx.generatePhysicalName(r.getLogicalId(), 128, false));+ }++ Map<String, String> tags = resolveUserPoolTags(props, ctx);+ if (tags != null) {+ req.put("UserPoolTags", tags);+ }++ UserPool pool;+ if (ctx.isUpdate()) {+ req.put("UserPoolId", ctx.priorPhysicalId());+ pool = cognitoService.updateUserPool(req, ctx.region());+ } else {+ pool = cognitoService.createUserPool(req, ctx.region());+ }++ r.setPhysicalId(pool.getId());+ r.getAttributes().put("Arn", pool.getArn());+ r.getAttributes().put("UserPoolId", pool.getId());+ // ProviderName is what a template feeds into an identity pool's CognitoIdentityProviders,+ // cognito-idp.<region>.amazonaws.com/<pool id> on AWS. ProviderURL stays the issuer Floci+ // mints tokens with, so a template wiring it into a JWT authorizer validates locally.+ r.getAttributes().put("ProviderName", "cognito-idp." + ctx.region() + ".amazonaws.com/" + pool.getId());+ r.getAttributes().put("ProviderURL", cognitoService.getIssuer(pool.getId()));+ }++ private void provisionUserPoolClient(StackResource r, JsonNode props, ProvisionContext ctx) {+ String userPoolId = ctx.resolveOptional(props, "UserPoolId");+ if (userPoolId == null || userPoolId.isBlank()) {+ throw new AwsException("ValidationError", "AWS::Cognito::UserPoolClient requires UserPoolId", 400);+ }+ String requestedClientName = ctx.resolveOptional(props, "ClientName");+ String clientName = requestedClientName == null || requestedClientName.isBlank()+ ? ctx.generatePhysicalName(r.getLogicalId(), 128, false)+ : requestedClientName;+ boolean generateSecret = Boolean.parseBoolean(resolveOrDefault(props, "GenerateSecret", ctx, "false"));+ boolean allowedOAuthFlowsUserPoolClient =+ Boolean.parseBoolean(resolveOrDefault(props, "AllowedOAuthFlowsUserPoolClient", ctx, "false"));+ List<String> allowedOAuthFlows = ctx.resolveStringList(props, "AllowedOAuthFlows");+ List<String> allowedOAuthScopes = ctx.resolveStringList(props, "AllowedOAuthScopes");++ Map<String, Object> analyticsConfiguration = resolveMapOrNull(props, "AnalyticsConfiguration", ctx);+ List<String> callbackURLs = ctx.resolveStringList(props, "CallbackURLs");+ String defaultRedirectURI = ctx.resolveOptional(props, "DefaultRedirectURI");+ List<String> explicitAuthFlows = ctx.resolveStringList(props, "ExplicitAuthFlows");+ Integer accessTokenValidity = parseInteger(props, "AccessTokenValidity", ctx);+ Integer idTokenValidity = parseInteger(props, "IdTokenValidity", ctx);+ List<String> logoutURLs = ctx.resolveStringList(props, "LogoutURLs");+ String preventUserExistenceErrors = ctx.resolveOptional(props, "PreventUserExistenceErrors");+ List<String> readAttributes = ctx.resolveStringList(props, "ReadAttributes");+ Integer refreshTokenValidity = parseInteger(props, "RefreshTokenValidity", ctx);+ List<String> supportedIdentityProviders = ctx.resolveStringList(props, "SupportedIdentityProviders");+ Map<String, String> tokenValidityUnits = resolveStringMapOrNull(props, "TokenValidityUnits", ctx);+ List<String> writeAttributes = ctx.resolveStringList(props, "WriteAttributes");+ Map<String, Object> refreshTokenRotation = resolveMapOrNull(props, "RefreshTokenRotation", ctx);+ Boolean enableTokenRevocation = parseBooleanOrNull(ctx.resolveOptional(props, "EnableTokenRevocation"));++ // UserPoolId and GenerateSecret are createOnly in the schema: a change to either replaces+ // the client, as on AWS, and the service's own update would refuse the pool move anyway,+ // since a client is only found through the pool that owns it.+ UserPoolClient prior = ctx.isUpdate() ? findClient(ctx.priorPhysicalId()) : null;+ UserPoolClient client;+ if (prior != null && Objects.equals(userPoolId, prior.getUserPoolId())+ && generateSecret == prior.isGenerateSecret()) {+ client = cognitoService.updateUserPoolClient(+ userPoolId, prior.getClientId(), clientName, allowedOAuthFlowsUserPoolClient,+ allowedOAuthFlows, allowedOAuthScopes, analyticsConfiguration, callbackURLs,+ defaultRedirectURI, explicitAuthFlows, accessTokenValidity, idTokenValidity,+ logoutURLs, preventUserExistenceErrors, readAttributes, refreshTokenValidity,+ supportedIdentityProviders, tokenValidityUnits, writeAttributes,+ refreshTokenRotation, enableTokenRevocation);+ } else {+ Supplier<UserPoolClient> create = () -> cognitoService.createUserPoolClient(+ userPoolId, clientName, generateSecret, allowedOAuthFlowsUserPoolClient,+ allowedOAuthFlows, allowedOAuthScopes, analyticsConfiguration, callbackURLs,+ defaultRedirectURI, explicitAuthFlows, accessTokenValidity, idTokenValidity,+ logoutURLs, preventUserExistenceErrors, readAttributes, refreshTokenValidity,+ supportedIdentityProviders, tokenValidityUnits, writeAttributes,+ refreshTokenRotation, enableTokenRevocation);+ // AWS client ids are random, so a create never collides with an existing client. Under+ // Floci's floci:override-cognito-client-id tag the id follows the name, and the store+ // would overwrite whichever client already holds it, the one being replaced or any+ // other, with no way back; so the create is refused before anything changes, and the+ // check and the create happen under one lock so a concurrent stack cannot slip between.+ String derivedId = cognitoService.deterministicClientIdFor(userPoolId, clientName);+ if (derivedId == null) {+ client = create.get();+ } else {+ synchronized (DETERMINISTIC_CLIENT_ID_LOCK) {+ refuseIfALiveClientHolds(derivedId);+ client = create.get();+ }+ }+ }++ r.setPhysicalId(client.getClientId());+ r.getAttributes().put("ClientId", client.getClientId());+ r.getAttributes().put("Name", client.getClientName());+ // The engine hands an update the prior attributes, so a replacement without a secret must+ // drop the displaced client's, or Fn::GetAtt ClientSecret keeps serving it.+ if (client.getClientSecret() != null) {+ r.getAttributes().put("ClientSecret", client.getClientSecret());+ } else {+ r.getAttributes().remove("ClientSecret");+ }+ }++ private void provisionUserPoolDomain(StackResource r, JsonNode props, ProvisionContext ctx) {String domain = ctx.resolveOptional(props, "Domain");String userPoolId = ctx.resolveOptional(props, "UserPoolId");if (domain == null || domain.isBlank() || userPoolId == null || userPoolId.isBlank()) {@@ -71,23 +310,40 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {provisioned.getCloudFrontDistribution() == null ? "" : provisioned.getCloudFrontDistribution());}- /** Deletes the domain from the pool recorded at create time; without that record, looks the pool up. */- @Override- public void delete(StackResource resource, String region) {- String userPoolId = resource.getAttributes() == null ? null : resource.getAttributes().get("UserPoolId");- if (userPoolId == null || userPoolId.isBlank()) {- delete(resource.getResourceType(), resource.getPhysicalId(), region);+ /**+ * A record whose pool no longer exists is an orphan of a deleted pool (the pool delete does not+ * cascade to clients yet, see #2949), not a live client: the create may take its id over.+ */+ private void refuseIfALiveClientHolds(String derivedId) {+ UserPoolClient holder = findClient(derivedId);+ if (holder == null) {return;}- deleteDomain(resource.getPhysicalId(), userPoolId);+ try {+ cognitoService.describeUserPool(holder.getUserPoolId());+ } catch (AwsException e) {+ if (!NOT_FOUND.equals(e.getErrorCode())) {+ throw e;+ }+ LOG.debugv("User pool client {0} belongs to deleted pool {1}; treating the record as stale",+ derivedId, holder.getUserPoolId());+ return;+ }+ throw new AwsException("ValidationError", "User pool client id " + derivedId+ + ", derived from ClientName under the pool's floci:override-cognito-client-id override,"+ + " already belongs to an existing client; give the client a different ClientName"+ + " or remove the override.", 400);}- /** Only the domain itself can say which pool owns it here; one that is already gone needs nothing. */- @Override- public void delete(String resourceType, String physicalId, String region) {- UserPoolDomain existing = findExisting(physicalId);- if (existing != null) {- deleteDomain(physicalId, existing.getUserPoolId());+ private UserPoolClient findClient(String clientId) {+ try {+ return cognitoService.describeUserPoolClient(clientId);+ } catch (AwsException e) {+ if (!NOT_FOUND.equals(e.getErrorCode())) {+ throw e;+ }+ LOG.debugv("User pool client {0} does not exist", clientId);+ return null;}}@@ -108,6 +364,23 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {}}+ /**+ * UserPoolTags is a map in the schema (the type's tagProperty), not the Key/Value list most types+ * carry, so it is resolved as one; through the raw property map a numeric tag value would reach+ * the service as a number. The list shape, which hand-written templates sometimes use and which+ * the switch accepted, is still taken.+ */+ private static Map<String, String> resolveUserPoolTags(JsonNode props, ProvisionContext ctx) {+ if (props == null || !props.has("UserPoolTags") || props.get("UserPoolTags").isNull()) {+ return null;+ }+ JsonNode resolved = ctx.engine().resolveNode(props.get("UserPoolTags"));+ if (resolved != null && resolved.isArray()) {+ return ctx.resolveTags(props, "UserPoolTags");+ }+ return resolveStringMapOrNull(props, "UserPoolTags", ctx);+ }+private static Map<String, Object> resolveCustomDomainConfig(JsonNode props, ProvisionContext ctx) {if (props == null || !props.hasNonNull("CustomDomainConfig")) {return null;@@ -138,4 +411,76 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner {"AWS::Cognito::UserPoolDomain ManagedLoginVersion must be an integer, got: " + value, e);}}++ private static String resolveOrDefault(JsonNode props, String name, ProvisionContext ctx, String defaultValue) {+ String value = ctx.resolveOptional(props, name);+ return (value != null && !value.isBlank()) ? value : defaultValue;+ }++ private static Integer parseInteger(JsonNode props, String name, ProvisionContext ctx) {+ String value = ctx.resolveOptional(props, name);+ if (value == null || value.isBlank()) {+ return null;+ }+ try {+ return Integer.valueOf(value.trim());+ } catch (NumberFormatException e) {+ throw new AwsException("ValidationError", "Value of property " + name + " must be an integer.", 400);+ }+ }++ private static Boolean parseBooleanOrNull(String value) {+ return (value == null || value.isBlank()) ? null : Boolean.valueOf(value);+ }++ private static Map<String, Object> resolveMapOrNull(JsonNode props, String name, ProvisionContext ctx) {+ if (props == null || !props.has(name) || props.get(name).isNull()) {+ return null;+ }+ JsonNode resolved = ctx.engine().resolveNode(props.get(name));+ return resolved != null && resolved.isObject() ? jsonObjectToMap(resolved) : null;+ }++ private static Map<String, String> resolveStringMapOrNull(JsonNode props, String name, ProvisionContext ctx) {+ if (props == null || !props.has(name) || props.get(name).isNull()) {+ return null;+ }+ JsonNode resolved = ctx.engine().resolveNode(props.get(name));+ if (resolved == null || !resolved.isObject()) {+ return null;+ }+ Map<String, String> out = new LinkedHashMap<>();+ resolved.fields().forEachRemaining(e -> out.put(e.getKey(), e.getValue().asText()));+ return out;+ }++ private static Map<String, Object> jsonObjectToMap(JsonNode node) {+ Map<String, Object> out = new LinkedHashMap<>();+ node.fields().forEachRemaining(e -> out.put(e.getKey(), jsonNodeToValue(e.getValue())));+ return out;+ }++ private static Object jsonNodeToValue(JsonNode node) {+ if (node == null || node.isNull()) {+ return null;+ }+ if (node.isObject()) {+ return jsonObjectToMap(node);+ }+ if (node.isArray()) {+ List<Object> values = new ArrayList<>();+ node.forEach(v -> values.add(jsonNodeToValue(v)));+ return values;+ }+ if (node.isBoolean()) {+ return node.asBoolean();+ }+ if (node.isIntegralNumber()) {+ return node.asLong();+ }+ if (node.isFloatingPointNumber()) {+ return node.asDouble();+ }+ return node.asText();+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.javaindex 2ad3524794..fddb185c81 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java@@ -255,6 +255,9 @@ public class CognitoService implements ResourceProvider {UserPool updatedPool = MAPPER.convertValue(pool, UserPool.class);populateUserPool(updatedPool, request);+ if (request.get("PoolName") instanceof String poolName && !poolName.isBlank()) {+ updatedPool.setName(poolName);+ }updatedPool.setLastModifiedDate(System.currentTimeMillis() / 1000L);poolStore.put(id, updatedPool);@@ -572,7 +575,7 @@ public class CognitoService implements ResourceProvider {Boolean enableTokenRevocation) {UserPool userPool = describeUserPool(userPoolId);- String clientId = UUID.randomUUID().toString().replace("-", "").substring(0, 26);+ String clientId = clientIdFor(userPool, clientName);List<String> normalizedAllowedOAuthFlows = normalizeStringList(allowedOAuthFlows);List<String> normalizedAllowedOAuthScopes = normalizeStringList(allowedOAuthScopes);List<String> normalizedCallbackUrls = normalizeStringList(callbackURLs);@@ -599,15 +602,6 @@ public class CognitoService implements ResourceProvider {);UserPoolClient client = new UserPoolClient();- if (userPool.getClientIdOverride() != null) {- if (userPool.getClientIdOverride().equalsIgnoreCase("use-name")) {- clientId = clientName;- } else if (userPool.getClientIdOverride().startsWith("append-to-name:")) {- clientId = clientName + userPool.getClientIdOverride().substring(15);- } else if (userPool.getClientIdOverride().startsWith("prepend-to-name:")) {- clientId = userPool.getClientIdOverride().substring(16) + clientName;- }- }client.setClientId(clientId);client.setUserPoolId(userPoolId);client.setClientName(clientName);@@ -657,14 +651,43 @@ public class CognitoService implements ResourceProvider {}public UserPoolClient describeUserPoolClient(String userPoolId, String clientId) {- UserPoolClient client = clientStore.get(clientId)- .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400));+ UserPoolClient client = describeUserPoolClient(clientId);if (!client.getUserPoolId().equals(userPoolId)) {throw new AwsException("ResourceNotFoundException", "User pool client not found", 400);}return client;}+ /**+ * The id a client created now with this name in this pool would get: derived from the name when+ * the pool carries the {@code floci:override-cognito-client-id} tag, otherwise null because it+ * would be random. Lets a caller that must not overwrite an existing client check first.+ */+ public String deterministicClientIdFor(String userPoolId, String clientName) {+ UserPool userPool = describeUserPool(userPoolId);+ return userPool.getClientIdOverride() == null ? null : clientIdFor(userPool, clientName);+ }++ private static String clientIdFor(UserPool userPool, String clientName) {+ String override = userPool.getClientIdOverride();+ if (override != null) {+ if (override.equalsIgnoreCase("use-name")) {+ return clientName;+ } else if (override.startsWith("append-to-name:")) {+ return clientName + override.substring(15);+ } else if (override.startsWith("prepend-to-name:")) {+ return override.substring(16) + clientName;+ }+ }+ return UUID.randomUUID().toString().replace("-", "").substring(0, 26);+ }++ /** By id alone, for callers that hold only the client id, such as a CloudFormation stack resource. */+ public UserPoolClient describeUserPoolClient(String clientId) {+ return clientStore.get(clientId)+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400));+ }+public List<UserPoolClient> listUserPoolClients(String userPoolId) {describeUserPool(userPoolId);return clientStore.scan(k -> clientStore.get(k).map(c -> c.getUserPoolId().equals(userPoolId)).orElse(false));diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.javaindex bfa090883e..6dc6b26153 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java@@ -576,7 +576,6 @@ final class CfnProvisionerFixture {apiGatewayV2Service,ecrService,pipesService,- cognitoService,lambdaLayerService,objectMapper,customResourceResponseStore,diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.javaindex 2f4c538875..462f5884ea 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java@@ -14,6 +14,8 @@ import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsAction;import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotEquals;@@ -31,6 +33,13 @@ import static org.junit.jupiter.api.Assertions.fail;* that deleting the stack removes the domain before the pool that owns it and the certificate after* the domain that uses it. A prefix domain, which* has no distribution of its own, resolves the attribute to an empty string rather than the literal.+ *+ * <p>The client case moves an {@code AWS::Cognito::UserPoolClient} between pools and flips+ * {@code GenerateSecret}, its two create-only properties: each is a replacement whose displaced client+ * is removed once the update completes, while a renamed client is updated in place. A replacement+ * without a secret leaves no stale {@code ClientSecret} behind. Under Floci's deterministic client-id+ * override a create whose derived id an existing client already holds is refused and the stack rolls+ * back intact, whether the holder is the client being replaced or one in another stack.*/@QuarkusTestclass CognitoCfnIntegrationTest {@@ -42,6 +51,29 @@ class CognitoCfnIntegrationTest {private static final String DOMAIN = "auth.cognito-cfn-it.example.com";private static final String REPLACEMENT_DOMAIN = "login.cognito-cfn-it.example.com";private static final String PREFIX_DOMAIN = "cognito-cfn-it-prefix";+ private static final String CLIENT_STACK = "cognito-cfn-client-it";++ private static String clientTemplate(String poolLogicalId, boolean generateSecret, String clientName) {+ return """+ {+ "Resources": {+ "PoolA": {"Type": "AWS::Cognito::UserPool", "Properties": {"UserPoolName": "cognito-cfn-client-it-a"}},+ "PoolB": {"Type": "AWS::Cognito::UserPool", "Properties": {"UserPoolName": "cognito-cfn-client-it-b"}},+ "Client": {+ "Type": "AWS::Cognito::UserPoolClient",+ "Properties": {"UserPoolId": {"Ref": "%s"}, "ClientName": "%s", "GenerateSecret": %s}+ }+ },+ "Outputs": {+ "PoolA": {"Value": {"Ref": "PoolA"}},+ "PoolB": {"Value": {"Ref": "PoolB"}},+ "ClientId": {"Value": {"Ref": "Client"}},+ "Name": {"Value": {"Fn::GetAtt": ["Client", "Name"]}},+ "ProviderName": {"Value": {"Fn::GetAtt": ["PoolA", "ProviderName"]}}+ }+ }+ """.formatted(poolLogicalId, clientName, generateSecret);+ }/*** The certificate carries the logical id so a rotation can add a new certificate resource and@@ -207,6 +239,169 @@ class CognitoCfnIntegrationTest {assertDomainIsGone(PREFIX_DOMAIN);}+ private static final String OVERRIDE_STACK = "cognito-cfn-override-it";++ /**+ * A client in a pool whose clients take their id from their name, through Floci's reserved+ * override tag. The pool lives outside the stack: an in-place pool update has no rollback in+ * the engine yet, and this case is about the client.+ */+ private static String overrideClientTemplate(String poolId, boolean generateSecret) {+ return """+ {+ "Resources": {+ "Client": {+ "Type": "AWS::Cognito::UserPoolClient",+ "Properties": {"UserPoolId": "%s", "ClientName": "override-web", "GenerateSecret": %s}+ }+ },+ "Outputs": {"ClientId": {"Value": {"Ref": "Client"}}}+ }+ """.formatted(poolId, generateSecret);+ }++ @Test+ void aDerivedIdLeftBehindByADeletedPoolDoesNotBlockAStackInAnotherPool() throws Exception {+ // Deleting a pool does not remove its clients yet (#2949 adds that), so the record of+ // orphan-web lingers under its id; a stack in a live pool must still be able to claim it.+ String deletedPool = cognitoJson("CreateUserPool", """+ {"PoolName": "cognito-cfn-orphan-a", "UserPoolTags": {"floci:override-cognito-client-id": "use-name"}}+ """).path("UserPool").path("Id").asText();+ cognitoAction("CreateUserPoolClient", "{\"UserPoolId\": \"" + deletedPool + "\", \"ClientName\": \"orphan-web\"}")+ .then().statusCode(200);+ cognitoAction("DeleteUserPool", "{\"UserPoolId\": \"" + deletedPool + "\"}").then().statusCode(200);+ String livePool = cognitoJson("CreateUserPool", """+ {"PoolName": "cognito-cfn-orphan-b", "UserPoolTags": {"floci:override-cognito-client-id": "use-name"}}+ """).path("UserPool").path("Id").asText();+ String stack = "cognito-cfn-orphan-it";++ cloudFormation(stack, "CreateStack", overrideClientTemplate(livePool, false).replace("override-web", "orphan-web"));++ String stacks = describeStacks(stack, "CREATE_COMPLETE");+ assertEquals("orphan-web", outputValue(stacks, "ClientId"));+ assertClientInPool(livePool, "orphan-web", "orphan-web");++ cloudFormation(stack, "DeleteStack", null);+ awaitStackDeleted(stack);+ cognitoAction("DeleteUserPool", "{\"UserPoolId\": \"" + livePool + "\"}").then().statusCode(200);+ }++ @Test+ void aReplacementThatWouldReuseADeterministicClientIdRollsTheUpdateBackWithThePriorClientIntact() throws Exception {+ String poolId = cognitoJson("CreateUserPool", """+ {"PoolName": "cognito-cfn-override-it", "UserPoolTags": {"floci:override-cognito-client-id": "use-name"}}+ """).path("UserPool").path("Id").asText();+ cloudFormation(OVERRIDE_STACK, "CreateStack", overrideClientTemplate(poolId, false));++ String stacks = describeStacks(OVERRIDE_STACK, "CREATE_COMPLETE");+ assertEquals("override-web", outputValue(stacks, "ClientId"), "the override makes the id the name");+ assertClientInPool(poolId, "override-web", "override-web");++ // GenerateSecret is createOnly, but the replacement would be created under the same id and+ // overwrite the client it replaces, so the update is refused and the stack rolls back.+ cloudFormation(OVERRIDE_STACK, "UpdateStack", overrideClientTemplate(poolId, true));++ stacks = describeStacks(OVERRIDE_STACK, "UPDATE_ROLLBACK_COMPLETE");+ String events = describeStackEvents(OVERRIDE_STACK);+ assertTrue(events.contains("already belongs to an existing client"), events);+ assertEquals("override-web", outputValue(stacks, "ClientId"));+ cognitoAction("DescribeUserPoolClient", "{\"UserPoolId\": \"" + poolId + "\", \"ClientId\": \"override-web\"}")+ .then()+ .statusCode(200)+ .body("UserPoolClient.ClientName", equalTo("override-web"))+ .body("UserPoolClient.ClientSecret", nullValue());++ // A second stack claiming the same derived id must not overwrite the first stack's client.+ cloudFormation(OVERRIDE_STACK + "-2", "CreateStack", overrideClientTemplate(poolId, false));+ describeStacks(OVERRIDE_STACK + "-2", "ROLLBACK_COMPLETE");+ assertClientInPool(poolId, "override-web", "override-web");+ cloudFormation(OVERRIDE_STACK + "-2", "DeleteStack", null);+ awaitStackDeleted(OVERRIDE_STACK + "-2");+ assertClientInPool(poolId, "override-web", "override-web");++ cloudFormation(OVERRIDE_STACK, "DeleteStack", null);+ awaitStackDeleted(OVERRIDE_STACK);+ assertClientIsGone(poolId, "override-web");+ cognitoAction("DeleteUserPool", "{\"UserPoolId\": \"" + poolId + "\"}").then().statusCode(200);+ }++ @Test+ void clientCreateOnlyChangesReplaceItAndARenameUpdatesItInPlace() throws Exception {+ cloudFormation(CLIENT_STACK, "CreateStack", clientTemplate("PoolA", false, "web"));++ String stacks = describeStacks(CLIENT_STACK, "CREATE_COMPLETE");+ String poolA = outputValue(stacks, "PoolA");+ String poolB = outputValue(stacks, "PoolB");+ String clientId = outputValue(stacks, "ClientId");+ assertEquals("web", outputValue(stacks, "Name"));+ assertEquals("cognito-idp.us-east-1.amazonaws.com/" + poolA, outputValue(stacks, "ProviderName"));+ assertClientInPool(poolA, clientId, "web");++ // UserPoolId is createOnly: the client is created in the new pool and the old one removed.+ cloudFormation(CLIENT_STACK, "UpdateStack", clientTemplate("PoolB", false, "web"));++ stacks = describeStacks(CLIENT_STACK, "UPDATE_COMPLETE");+ String moved = outputValue(stacks, "ClientId");+ assertNotEquals(clientId, moved, "a pool move must be a replacement");+ assertClientInPool(poolB, moved, "web");+ assertClientIsGone(poolA, clientId);++ // GenerateSecret is createOnly too: the replacement has a secret, the displaced client goes.+ cloudFormation(CLIENT_STACK, "UpdateStack", clientTemplate("PoolB", true, "web"));++ stacks = describeStacks(CLIENT_STACK, "UPDATE_COMPLETE");+ String withSecret = outputValue(stacks, "ClientId");+ assertNotEquals(moved, withSecret, "a GenerateSecret change must be a replacement");+ assertClientInPool(poolB, withSecret, "web");+ assertClientIsGone(poolB, moved);+ cognitoAction("DescribeUserPoolClient", "{\"UserPoolId\": \"" + poolB + "\", \"ClientId\": \"" + withSecret + "\"}")+ .then()+ .statusCode(200)+ .body("UserPoolClient.ClientSecret", notNullValue());++ // ClientName is updatable: same client, new name.+ cloudFormation(CLIENT_STACK, "UpdateStack", clientTemplate("PoolB", true, "web-renamed"));++ stacks = describeStacks(CLIENT_STACK, "UPDATE_COMPLETE");+ assertEquals(withSecret, outputValue(stacks, "ClientId"), "a rename must update the client in place");+ assertEquals("web-renamed", outputValue(stacks, "Name"));+ assertClientInPool(poolB, withSecret, "web-renamed");++ // GenerateSecret back to false: a replacement again, and the new client carries no secret.+ cloudFormation(CLIENT_STACK, "UpdateStack", clientTemplate("PoolB", false, "web-renamed"));++ stacks = describeStacks(CLIENT_STACK, "UPDATE_COMPLETE");+ String withoutSecret = outputValue(stacks, "ClientId");+ assertNotEquals(withSecret, withoutSecret, "a GenerateSecret change must be a replacement");+ assertClientIsGone(poolB, withSecret);+ cognitoAction("DescribeUserPoolClient", "{\"UserPoolId\": \"" + poolB + "\", \"ClientId\": \"" + withoutSecret + "\"}")+ .then()+ .statusCode(200)+ .body("UserPoolClient.ClientSecret", nullValue());++ cloudFormation(CLIENT_STACK, "DeleteStack", null);+ awaitStackDeleted(CLIENT_STACK);++ assertClientIsGone(poolB, withoutSecret);+ cognitoAction("DescribeUserPool", "{\"UserPoolId\": \"" + poolB + "\"}")+ .then()+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ private static void assertClientInPool(String poolId, String clientId, String name) {+ cognitoAction("DescribeUserPoolClient", "{\"UserPoolId\": \"" + poolId + "\", \"ClientId\": \"" + clientId + "\"}")+ .then()+ .statusCode(200)+ .body("UserPoolClient.UserPoolId", equalTo(poolId))+ .body("UserPoolClient.ClientName", equalTo(name));+ }++ private static void assertClientIsGone(String poolId, String clientId) {+ cognitoAction("DescribeUserPoolClient", "{\"UserPoolId\": \"" + poolId + "\", \"ClientId\": \"" + clientId + "\"}")+ .then()+ .body("__type", equalTo("ResourceNotFoundException"));+ }+private static void cloudFormation(String stack, String action, String templateBody) {RequestSpecification request = given().contentType("application/x-www-form-urlencoded")@@ -219,6 +414,16 @@ class CognitoCfnIntegrationTest {request.when().post("/").then().statusCode(200);}+ private static String describeStackEvents(String stack) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStackEvents")+ .formParam("StackName", stack)+ .when().post("/").then().statusCode(200)+ .extract().asString();+ }+private static String describeStacks(String stack, String expectedStatus) {return given().contentType("application/x-www-form-urlencoded")diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisionerTest.javaindex 4719c8a073..14dbc6e1d7 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisionerTest.java@@ -7,16 +7,31 @@ import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;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 java.util.HashMap;+import java.util.List;import java.util.Map;+import java.util.Set;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.ArgumentMatchers.isNull;import static org.mockito.Mockito.doThrow;@@ -33,6 +48,11 @@ import static org.mockito.Mockito.when;class CognitoCfnProvisionerTest {private static final String TYPE = "AWS::Cognito::UserPoolDomain";+ private static final String USER_POOL = "AWS::Cognito::UserPool";+ private static final String USER_POOL_CLIENT = "AWS::Cognito::UserPoolClient";+ private static final String CLIENT_ID = "1h57kf5cpq17m0eml12EXAMPLE";+ private static final String POOL_ARN = "arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_AbCdEfGhI";+ private static final String ISSUER = "http://localhost:4566/us-east-1_AbCdEfGhI";private static final String REGION = "us-east-1";private static final String POOL_ID = "us-east-1_AbCdEfGhI";private static final String DOMAIN = "auth.example.com";@@ -57,6 +77,9 @@ class CognitoCfnProvisionerTest {return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();});when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));+ // resolveStringList delegates to the real engine method; for the literal arrays these+ // tests use it just walks the array and calls resolve(...) per element, stubbed above.+ when(engine.resolveStringList(any())).thenCallRealMethod();return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);}@@ -68,6 +91,13 @@ class CognitoCfnProvisionerTest {return r;}+ private static StackResource resource(String type, String logicalId) {+ StackResource r = resource();+ r.setLogicalId(logicalId);+ r.setResourceType(type);+ return r;+ }+private static StackResource resource(String physicalId, Map<String, String> attributes) {StackResource r = resource();r.setPhysicalId(physicalId);@@ -75,6 +105,50 @@ class CognitoCfnProvisionerTest {return r;}+ private static UserPool pool(String id, String name) {+ UserPool p = new UserPool();+ p.setId(id);+ p.setName(name);+ p.setArn(POOL_ARN);+ return p;+ }++ private static UserPoolClient client(String name, String secret) {+ return client(CLIENT_ID, POOL_ID, name, secret);+ }++ private static UserPoolClient client(String id, String poolId, String name, String secret) {+ UserPoolClient c = new UserPoolClient();+ c.setClientId(id);+ c.setUserPoolId(poolId);+ c.setClientName(name);+ c.setClientSecret(secret);+ c.setGenerateSecret(secret != null);+ return c;+ }++ private void verifyNoClientCreate() {+ verify(cognito, never()).createUserPoolClient(any(), any(), anyBoolean(), anyBoolean(), any(), any(),+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());+ }++ private void verifyNoClientUpdate() {+ verify(cognito, never()).updateUserPoolClient(any(), any(), any(), any(), any(), any(), any(), any(),+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());+ }++ private void stubClientCreate(UserPoolClient created) {+ when(cognito.createUserPoolClient(any(), any(), anyBoolean(), anyBoolean(), any(), any(), any(), any(),+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))+ .thenReturn(created);+ }++ private void stubClientUpdate(UserPoolClient updated) {+ when(cognito.updateUserPoolClient(any(), any(), any(), any(), any(), any(), any(), any(),+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))+ .thenReturn(updated);+ }+private static UserPoolDomain domain(String domain, String userPoolId, String cloudFront) {UserPoolDomain d = new UserPoolDomain();d.setDomain(domain);@@ -294,4 +368,550 @@ class CognitoCfnProvisionerTest {verify(cognito).deleteUserPoolDomain(DOMAIN, POOL_ID);}++ @Test+ void userPoolCreateHandsTheResolvedPropertiesToTheServiceAndSetsTheSchemaAttributes() {+ when(cognito.createUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "my-pool"));+ when(cognito.getIssuer(POOL_ID)).thenReturn(ISSUER);+ ObjectNode props = mapper.createObjectNode().put("UserPoolName", "my-pool").put("MfaConfiguration", "OFF");+ props.putObject("Policies").putObject("PasswordPolicy").put("MinimumLength", 12);+ StackResource r = resource(USER_POOL, "Pool");++ provisioner.provision(r, props, ctx());++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);+ verify(cognito).createUserPool(request.capture(), eq(REGION));+ assertEquals("my-pool", request.getValue().get("PoolName"));+ assertEquals("OFF", request.getValue().get("MfaConfiguration"));+ assertEquals(Map.of("PasswordPolicy", Map.of("MinimumLength", 12L)), request.getValue().get("Policies"));+ assertEquals(POOL_ID, r.getPhysicalId());+ assertEquals(Set.of("Arn", "UserPoolId", "ProviderName", "ProviderURL"), r.getAttributes().keySet());+ assertEquals(POOL_ARN, r.getAttributes().get("Arn"));+ assertEquals(POOL_ID, r.getAttributes().get("UserPoolId"));+ assertEquals("cognito-idp.us-east-1.amazonaws.com/" + POOL_ID, r.getAttributes().get("ProviderName"));+ assertEquals(ISSUER, r.getAttributes().get("ProviderURL"));+ }++ @Test+ void userPoolTagsAreResolvedAsAStringMap() {+ when(cognito.createUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "my-pool"));+ ObjectNode props = mapper.createObjectNode().put("UserPoolName", "my-pool");+ props.putObject("UserPoolTags").put("env", "test").put("cost-center", 42);++ provisioner.provision(resource(USER_POOL, "Pool"), props, ctx());++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);+ verify(cognito).createUserPool(request.capture(), eq(REGION));+ assertEquals(Map.of("env", "test", "cost-center", "42"), request.getValue().get("UserPoolTags"));+ }++ @Test+ void userPoolTagsGivenAsAKeyValueListAreStillAccepted() {+ when(cognito.createUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "my-pool"));+ ObjectNode props = mapper.createObjectNode().put("UserPoolName", "my-pool");+ props.putArray("UserPoolTags").addObject().put("Key", "team").put("Value", "auth");++ provisioner.provision(resource(USER_POOL, "Pool"), props, ctx());++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);+ verify(cognito).createUserPool(request.capture(), eq(REGION));+ assertEquals(Map.of("team", "auth"), request.getValue().get("UserPoolTags"));+ }++ @Test+ void userPoolUpdateCarriesTheTags() {+ when(cognito.updateUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "my-pool"));+ ObjectNode props = mapper.createObjectNode().put("UserPoolName", "my-pool");+ props.putObject("UserPoolTags").put("env", "prod");+ StackResource r = resource(USER_POOL, "Pool");+ r.setPhysicalId(POOL_ID);++ provisioner.provision(r, props, ctx(POOL_ID));++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);+ verify(cognito).updateUserPool(request.capture(), eq(REGION));+ assertEquals(Map.of("env", "prod"), request.getValue().get("UserPoolTags"));+ }++ @Test+ void userPoolWithoutANameGetsAGeneratedOne() {+ when(cognito.createUserPool(any(), eq(REGION))).thenAnswer(inv ->+ pool(POOL_ID, (String) inv.<Map<String, Object>>getArgument(0).get("PoolName")));+ StackResource r = resource(USER_POOL, "Pool");++ provisioner.provision(r, mapper.createObjectNode(), ctx());++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);+ verify(cognito).createUserPool(request.capture(), eq(REGION));+ String poolName = (String) request.getValue().get("PoolName");+ assertTrue(poolName.startsWith("my-stack-Pool-"), poolName);+ }++ @Test+ void userPoolUpdateCarriesThePriorPoolId() {+ when(cognito.updateUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "my-pool"));+ StackResource r = resource(USER_POOL, "Pool");+ r.setPhysicalId(POOL_ID);++ provisioner.provision(r, mapper.createObjectNode().put("UserPoolName", "my-pool"), ctx(POOL_ID));++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);+ verify(cognito).updateUserPool(request.capture(), eq(REGION));+ assertEquals(POOL_ID, request.getValue().get("UserPoolId"));+ verify(cognito, never()).createUserPool(any(), any());+ assertEquals(POOL_ID, r.getPhysicalId());+ }++ @Test+ void userPoolUpdateWithAnExplicitNameCarriesIt() {+ when(cognito.updateUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "renamed"));+ StackResource r = resource(USER_POOL, "Pool");+ r.setPhysicalId(POOL_ID);++ provisioner.provision(r, mapper.createObjectNode().put("UserPoolName", "renamed"), ctx(POOL_ID));++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);+ verify(cognito).updateUserPool(request.capture(), eq(REGION));+ assertEquals("renamed", request.getValue().get("PoolName"));+ }++ @Test+ void userPoolUpdateWithoutANameKeepsTheCurrentOne() {+ when(cognito.updateUserPool(any(), eq(REGION))).thenReturn(pool(POOL_ID, "my-stack-Pool-abc123"));+ StackResource r = resource(USER_POOL, "Pool");+ r.setPhysicalId(POOL_ID);++ provisioner.provision(r, mapper.createObjectNode().put("MfaConfiguration", "OFF"), ctx(POOL_ID));++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);+ verify(cognito).updateUserPool(request.capture(), eq(REGION));+ assertFalse(request.getValue().containsKey("PoolName"), "no PoolName means keep the current name");+ }++ @Test+ void userPoolClientCreatePassesEveryPropertyPositionally() {+ stubClientCreate(client("web", "s3cr3t"));+ ObjectNode props = mapper.createObjectNode()+ .put("UserPoolId", POOL_ID)+ .put("ClientName", "web")+ .put("GenerateSecret", true)+ .put("AccessTokenValidity", 60)+ .put("PreventUserExistenceErrors", "ENABLED");+ props.putArray("ExplicitAuthFlows").add("ALLOW_USER_SRP_AUTH").add("ALLOW_REFRESH_TOKEN_AUTH");+ props.putArray("CallbackURLs").add("https://app.example.com/cb");+ props.putObject("TokenValidityUnits").put("AccessToken", "minutes");+ StackResource r = resource(USER_POOL_CLIENT, "Client");++ provisioner.provision(r, props, ctx());++ verify(cognito).createUserPoolClient(eq(POOL_ID), eq("web"), eq(true), eq(false),+ eq(List.of()), eq(List.of()), isNull(), eq(List.of("https://app.example.com/cb")),+ isNull(), eq(List.of("ALLOW_USER_SRP_AUTH", "ALLOW_REFRESH_TOKEN_AUTH")), eq(60), isNull(),+ eq(List.of()), eq("ENABLED"), eq(List.of()), isNull(),+ eq(List.of()), eq(Map.of("AccessToken", "minutes")), eq(List.of()),+ isNull(), isNull());+ assertEquals(CLIENT_ID, r.getPhysicalId());+ assertEquals(Set.of("ClientId", "Name", "ClientSecret"), r.getAttributes().keySet());+ assertEquals(CLIENT_ID, r.getAttributes().get("ClientId"));+ assertEquals("web", r.getAttributes().get("Name"));+ assertEquals("s3cr3t", r.getAttributes().get("ClientSecret"));+ }++ @Test+ void userPoolClientWithoutASecretHasNoClientSecretAttribute() {+ stubClientCreate(client("web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");++ provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web"), ctx());++ assertEquals(Set.of("ClientId", "Name"), r.getAttributes().keySet());+ }++ @Test+ void userPoolClientWithoutANameGetsAGeneratedOne() {+ stubClientCreate(client("generated", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");++ provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", POOL_ID), ctx());++ ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);+ verify(cognito).createUserPoolClient(eq(POOL_ID), name.capture(), anyBoolean(), anyBoolean(), any(), any(),+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());+ assertTrue(name.getValue().startsWith("my-stack-Client-"), name.getValue());+ }++ @Test+ void userPoolClientUpdateUpdatesThePriorClientInPlace() {+ when(cognito.describeUserPoolClient(CLIENT_ID)).thenReturn(client("old-name", null));+ stubClientUpdate(client("web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);+ ObjectNode props = mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web")+ .put("EnableTokenRevocation", true);++ provisioner.provision(r, props, ctx(CLIENT_ID));++ verify(cognito).updateUserPoolClient(eq(POOL_ID), eq(CLIENT_ID), eq("web"), eq(false),+ eq(List.of()), eq(List.of()), isNull(), eq(List.of()), isNull(), eq(List.of()), isNull(), isNull(),+ eq(List.of()), isNull(), eq(List.of()), isNull(), eq(List.of()), isNull(), eq(List.of()),+ isNull(), eq(Boolean.TRUE));+ verifyNoClientCreate();+ assertEquals(CLIENT_ID, r.getPhysicalId());+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void movingAUserPoolClientToAnotherPoolReplacesIt() {+ when(cognito.describeUserPoolClient(CLIENT_ID)).thenReturn(client(CLIENT_ID, POOL_ID, "web", null));+ stubClientCreate(client("replacement-client", "us-east-1_OtherPool", "web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);+ r.getAttributes().putAll(Map.of("ClientId", CLIENT_ID, "Name", "web"));+ ObjectNode props = mapper.createObjectNode().put("UserPoolId", "us-east-1_OtherPool").put("ClientName", "web");++ provisioner.provision(r, props, ctx(CLIENT_ID));++ verify(cognito).createUserPoolClient(eq("us-east-1_OtherPool"), eq("web"), eq(false), anyBoolean(), any(),+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());+ verifyNoClientUpdate();+ assertEquals("replacement-client", r.getPhysicalId());+ assertTrue(provisioner.hasReplacementUpdate(r));+ assertEquals(CLIENT_ID, provisioner.updateCleanupPhysicalId(r));+ }++ @Test+ void changingGenerateSecretReplacesTheUserPoolClient() {+ when(cognito.describeUserPoolClient(CLIENT_ID)).thenReturn(client(CLIENT_ID, POOL_ID, "web", null));+ stubClientCreate(client("replacement-client", POOL_ID, "web", "s3cr3t"));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);+ ObjectNode props = mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web")+ .put("GenerateSecret", true);++ provisioner.provision(r, props, ctx(CLIENT_ID));++ verify(cognito).createUserPoolClient(eq(POOL_ID), eq("web"), eq(true), anyBoolean(), any(),+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());+ verifyNoClientUpdate();+ assertEquals("replacement-client", r.getPhysicalId());+ assertEquals("s3cr3t", r.getAttributes().get("ClientSecret"));+ assertEquals(CLIENT_ID, provisioner.updateCleanupPhysicalId(r));+ }++ @Test+ void replacingASecretBearingClientWithASecretlessOneDropsTheStaleSecretAndRollbackRestoresIt() {+ when(cognito.describeUserPoolClient(CLIENT_ID)).thenReturn(client(CLIENT_ID, POOL_ID, "web", "old-secret"));+ stubClientCreate(client("replacement-client", POOL_ID, "web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);+ r.getAttributes().putAll(Map.of("ClientId", CLIENT_ID, "Name", "web", "ClientSecret", "old-secret"));+ ObjectNode props = mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web")+ .put("GenerateSecret", false);++ provisioner.provision(r, props, ctx(CLIENT_ID));++ assertEquals("replacement-client", r.getPhysicalId());+ assertFalse(r.getAttributes().containsKey("ClientSecret"),+ "the displaced client's secret must not survive the replacement");+ assertEquals("replacement-client", r.getAttributes().get("ClientId"));++ assertTrue(provisioner.rollbackUpdate(r));+ assertEquals(CLIENT_ID, r.getPhysicalId());+ assertEquals("old-secret", r.getAttributes().get("ClientSecret"));+ }++ @Test+ void aReplacementThatWouldReuseThePriorClientIdIsRefusedBeforeAnythingChanges() {+ when(cognito.describeUserPoolClient("web")).thenReturn(client("web", POOL_ID, "web", null));+ when(cognito.deterministicClientIdFor(POOL_ID, "web")).thenReturn("web");+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId("web");+ ObjectNode props = mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web")+ .put("GenerateSecret", true);++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx("web")));++ assertEquals("ValidationError", e.getErrorCode());+ verifyNoClientCreate();+ verifyNoClientUpdate();+ assertEquals("web", r.getPhysicalId());+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void aReplacementWhoseDerivedIdBelongsToAnotherClientIsRefused() {+ when(cognito.describeUserPoolClient("web")).thenReturn(client("web", POOL_ID, "web", null));+ when(cognito.deterministicClientIdFor("us-east-1_OtherPool", "web"))+ .thenReturn("web");+ when(cognito.describeUserPoolClient("web")).thenReturn(client("web", POOL_ID, "web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId("web");+ // Same name in another pool with the same override: the derived id is the prior's, which+ // stands for any existing client the store would overwrite.+ ObjectNode props = mapper.createObjectNode().put("UserPoolId", "us-east-1_OtherPool").put("ClientName", "web");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx("web")));++ assertEquals("ValidationError", e.getErrorCode());+ verifyNoClientCreate();+ }++ @Test+ void aFreshClientWhoseDerivedIdIsTakenByAnotherClientIsRefused() {+ when(cognito.deterministicClientIdFor(POOL_ID, "taken")).thenReturn("taken");+ when(cognito.describeUserPoolClient("taken")).thenReturn(client("taken", "us-east-1_OtherPool", "taken", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,+ mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "taken"), ctx()));++ assertEquals("ValidationError", e.getErrorCode());+ verifyNoClientCreate();+ assertEquals(null, r.getPhysicalId());+ }++ @Test+ void aDerivedIdHeldByAClientOfADeletedPoolIsTakenOver() {+ when(cognito.deterministicClientIdFor(POOL_ID, "web")).thenReturn("web");+ when(cognito.describeUserPoolClient("web")).thenReturn(client("web", "us-east-1_DeletedPool", "web", null));+ when(cognito.describeUserPool("us-east-1_DeletedPool"))+ .thenThrow(new AwsException("ResourceNotFoundException", "User pool does not exist", 400));+ stubClientCreate(client("web", POOL_ID, "web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");++ provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web"), ctx());++ assertEquals("web", r.getPhysicalId());+ }++ @Test+ void concurrentCreatesOfTheSameDerivedIdLetExactlyOneThrough() throws Exception {+ when(cognito.deterministicClientIdFor(POOL_ID, "web")).thenReturn("web");+ AtomicBoolean created = new AtomicBoolean();+ when(cognito.describeUserPoolClient("web")).thenAnswer(inv -> {+ if (created.get()) {+ return client("web", POOL_ID, "web", null);+ }+ throw new AwsException("ResourceNotFoundException", "User pool client not found", 400);+ });+ AtomicInteger creates = new AtomicInteger();+ when(cognito.createUserPoolClient(any(), any(), anyBoolean(), anyBoolean(), any(), any(), any(), any(),+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))+ .thenAnswer(inv -> {+ creates.incrementAndGet();+ Thread.sleep(50);+ created.set(true);+ return client("web", POOL_ID, "web", null);+ });+ CountDownLatch ready = new CountDownLatch(2);+ ExecutorService pool = Executors.newFixedThreadPool(2);+ try {+ List<Future<Throwable>> outcomes = new java.util.ArrayList<>();+ for (int i = 0; i < 2; i++) {+ outcomes.add(pool.submit(() -> {+ ready.countDown();+ ready.await(5, TimeUnit.SECONDS);+ try {+ provisioner.provision(resource(USER_POOL_CLIENT, "Client"),+ mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web"), ctx());+ return null;+ } catch (Throwable t) {+ return t;+ }+ }));+ }+ long refused = outcomes.stream().map(f -> {+ try {+ return f.get(10, TimeUnit.SECONDS);+ } catch (Exception e) {+ throw new AssertionError(e);+ }+ }).filter(t -> t instanceof AwsException a && "ValidationError".equals(a.getErrorCode())).count();++ assertEquals(1, creates.get(), "exactly one create");+ assertEquals(1, refused, "the other provision is refused, not silently overwriting");+ } finally {+ pool.shutdownNow();+ }+ }++ @Test+ void aFreshClientWhoseDerivedIdIsFreeIsCreated() {+ when(cognito.deterministicClientIdFor(POOL_ID, "web")).thenReturn("web");+ when(cognito.describeUserPoolClient("web"))+ .thenThrow(new AwsException("ResourceNotFoundException", "User pool client not found", 400));+ stubClientCreate(client("web", POOL_ID, "web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");++ provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web"), ctx());++ assertEquals("web", r.getPhysicalId());+ }++ @Test+ void aReplacementWhoseDerivedIdDiffersProceeds() {+ when(cognito.describeUserPoolClient("web")).thenReturn(client("web", POOL_ID, "web", null));+ when(cognito.deterministicClientIdFor(POOL_ID, "web-v2")).thenReturn("web-v2");+ when(cognito.describeUserPoolClient("web-v2"))+ .thenThrow(new AwsException("ResourceNotFoundException", "User pool client not found", 400));+ stubClientCreate(client("web-v2", POOL_ID, "web-v2", "s3cr3t"));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId("web");+ ObjectNode props = mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web-v2")+ .put("GenerateSecret", true);++ provisioner.provision(r, props, ctx("web"));++ assertEquals("web-v2", r.getPhysicalId());+ assertEquals("web", provisioner.updateCleanupPhysicalId(r));+ }++ @Test+ void replacedUserPoolClientIsDeletedWhenTheUpdateCompletes() {+ when(cognito.describeUserPoolClient(CLIENT_ID)).thenReturn(client(CLIENT_ID, POOL_ID, "web", null));+ stubClientCreate(client("replacement-client", "us-east-1_OtherPool", "web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);+ provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", "us-east-1_OtherPool"), ctx(CLIENT_ID));++ provisioner.completeUpdate(r);++ verify(cognito).deleteUserPoolClient(CLIENT_ID);+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void rollingBackAReplacedUserPoolClientRestoresThePriorOneAndDeletesTheReplacement() {+ when(cognito.describeUserPoolClient(CLIENT_ID)).thenReturn(client(CLIENT_ID, POOL_ID, "web", null));+ stubClientCreate(client("replacement-client", "us-east-1_OtherPool", "web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);+ r.getAttributes().putAll(Map.of("ClientId", CLIENT_ID, "Name", "web"));+ provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", "us-east-1_OtherPool"), ctx(CLIENT_ID));++ assertTrue(provisioner.rollbackUpdate(r));++ verify(cognito).deleteUserPoolClient("replacement-client");+ verify(cognito, never()).deleteUserPoolClient(CLIENT_ID);+ assertEquals(CLIENT_ID, r.getPhysicalId());+ assertEquals(CLIENT_ID, r.getAttributes().get("ClientId"));+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void anInPlaceUserPoolClientUpdateCannotBeRolledBack() {+ when(cognito.describeUserPoolClient(CLIENT_ID)).thenReturn(client("web", null));+ stubClientUpdate(client("web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);+ provisioner.provision(r, mapper.createObjectNode().put("UserPoolId", POOL_ID), ctx(CLIENT_ID));++ assertFalse(provisioner.rollbackUpdate(r));+ }++ @Test+ void aPriorUserPoolClientThatIsGoneIsCreatedAnew() {+ when(cognito.describeUserPoolClient(CLIENT_ID))+ .thenThrow(new AwsException("ResourceNotFoundException", "User pool client not found", 400));+ stubClientCreate(client("web", null));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);++ assertDoesNotThrow(() -> provisioner.provision(r,+ mapper.createObjectNode().put("UserPoolId", POOL_ID).put("ClientName", "web"), ctx(CLIENT_ID)));++ verifyNoClientUpdate();+ assertEquals(CLIENT_ID, r.getPhysicalId());+ }++ @Test+ void aFailingPriorUserPoolClientLookupPropagates() {+ when(cognito.describeUserPoolClient(CLIENT_ID))+ .thenThrow(new AwsException("InternalErrorException", "storage unavailable", 500));+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ r.setPhysicalId(CLIENT_ID);++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,+ mapper.createObjectNode().put("UserPoolId", POOL_ID), ctx(CLIENT_ID)));+ assertEquals("InternalErrorException", e.getErrorCode());+ }++ @Test+ void userPoolClientWithoutAUserPoolIdIsRejected() {+ StackResource r = resource(USER_POOL_CLIENT, "Client");++ AwsException e = assertThrows(AwsException.class,+ () -> provisioner.provision(r, mapper.createObjectNode().put("ClientName", "web"), ctx()));+ assertEquals("ValidationError", e.getErrorCode());+ verifyNoClientCreate();+ }++ @Test+ void nonIntegerTokenValidityIsRejectedInsteadOfDropped() {+ for (String property : List.of("AccessTokenValidity", "IdTokenValidity", "RefreshTokenValidity")) {+ StackResource r = resource(USER_POOL_CLIENT, "Client");+ ObjectNode props = mapper.createObjectNode().put("UserPoolId", POOL_ID).put(property, "sixty");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()), property);+ assertEquals("ValidationError", e.getErrorCode());+ assertEquals("Value of property " + property + " must be an integer.", e.getMessage());+ }+ verifyNoClientCreate();+ }++ @Test+ void unknownTypeIsRejected() {+ StackResource r = resource("AWS::Cognito::IdentityPool", "Identity");++ assertThrows(IllegalStateException.class, () -> provisioner.provision(r, mapper.createObjectNode(), ctx()));+ }++ @Test+ void deleteUserPoolToleratesAMissingPoolAndPropagatesADomainRefusal() {+ doThrow(new AwsException("ResourceNotFoundException", "User pool does not exist", 400))+ .when(cognito).deleteUserPool("us-east-1_gone");+ doThrow(new AwsException("InvalidParameterException", "User pool cannot be deleted.", 400))+ .when(cognito).deleteUserPool(POOL_ID);++ assertDoesNotThrow(() -> provisioner.delete(USER_POOL, "us-east-1_gone", REGION));+ AwsException refused = assertThrows(AwsException.class, () -> provisioner.delete(USER_POOL, POOL_ID, REGION));+ assertEquals("InvalidParameterException", refused.getErrorCode());+ }++ @Test+ void deleteUserPoolClientToleratesAnAlreadyDeletedClient() {+ doThrow(new AwsException("ResourceNotFoundException", "User pool client not found", 400))+ .when(cognito).deleteUserPoolClient(CLIENT_ID);++ assertDoesNotThrow(() -> provisioner.delete(USER_POOL_CLIENT, CLIENT_ID, REGION));+ verify(cognito).deleteUserPoolClient(CLIENT_ID);+ }++ @Test+ void deletingAUserPoolThroughTheResourceOverloadDeletesThePoolNotADomain() {+ StackResource r = resource(USER_POOL, "Pool");+ r.setPhysicalId(POOL_ID);+ r.getAttributes().put("UserPoolId", POOL_ID);++ provisioner.delete(r, REGION);++ verify(cognito).deleteUserPool(POOL_ID);+ verify(cognito, never()).deleteUserPoolDomain(any(), any());+ }++ @Test+ void deleteWithoutAPhysicalIdIsANoOp() {+ assertDoesNotThrow(() -> provisioner.delete(USER_POOL, null, REGION));+ assertDoesNotThrow(() -> provisioner.delete(USER_POOL_CLIENT, "", REGION));+ verify(cognito, never()).deleteUserPool(any());+ verify(cognito, never()).deleteUserPoolClient(any());+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.javaindex 5eaea88e87..ed52882011 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java@@ -860,6 +860,37 @@ class CognitoServiceTest {assertEquals("InvalidParameterException", hashException.getErrorCode());}+ @Test+ void deterministicClientIdFollowsThePoolOverrideAndIsNullWithoutOne() {+ UserPool plain = service.createUserPool(Map.of("PoolName", "plain"), "us-east-1");+ assertNull(service.deterministicClientIdFor(plain.getId(), "web"));++ UserPool useName = service.createUserPool(Map.of("PoolName", "use-name",+ "UserPoolTags", Map.of(ReservedTags.OVERRIDE_COGNITO_CLIENT_ID_KEY, "use-name")), "us-east-1");+ assertEquals("web", service.deterministicClientIdFor(useName.getId(), "web"));++ UserPool append = service.createUserPool(Map.of("PoolName", "append",+ "UserPoolTags", Map.of(ReservedTags.OVERRIDE_COGNITO_CLIENT_ID_KEY, "append-to-name:-id")), "us-east-1");+ assertEquals("web-id", service.deterministicClientIdFor(append.getId(), "web"));++ UserPool prepend = service.createUserPool(Map.of("PoolName", "prepend",+ "UserPoolTags", Map.of(ReservedTags.OVERRIDE_COGNITO_CLIENT_ID_KEY, "prepend-to-name:app-")), "us-east-1");+ assertEquals("app-web", service.deterministicClientIdFor(prepend.getId(), "web"));+ assertEquals("app-web", service.createUserPoolClient(prepend.getId(), "web", false, false,+ List.of(), List.of()).getClientId());+ }++ @Test+ void updateUserPoolRenamesThePoolWhenPoolNameIsGiven() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "before"), "us-east-1");++ service.updateUserPool(Map.of("UserPoolId", pool.getId(), "PoolName", "after"), "us-east-1");+ assertEquals("after", service.describeUserPool(pool.getId()).getName());++ service.updateUserPool(Map.of("UserPoolId", pool.getId(), "MfaConfiguration", "OFF"), "us-east-1");+ assertEquals("after", service.describeUserPool(pool.getId()).getName());+ }+@Testvoid updateUserPoolWithReservedTagStripsIt() {UserPool pool = service.createUserPool(Map.of("PoolName", "PinnedPool"), "us-east-1");diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsvindex 53e1bf9776..a7a558d61b 100644--- a/src/test/resources/cloudformation/supported-resource-types.tsv+++ b/src/test/resources/cloudformation/supported-resource-types.tsv@@ -33,8 +33,8 @@ AWS::CodeBuild::Project CodeBuildCfnProvisionerAWS::CodePipeline::CustomActionType CodePipelineCfnProvisionerAWS::CodePipeline::Pipeline CodePipelineCfnProvisionerAWS::CodePipeline::Webhook CodePipelineCfnProvisioner-AWS::Cognito::UserPool LEGACY_SWITCH-AWS::Cognito::UserPoolClient LEGACY_SWITCH+AWS::Cognito::UserPool CognitoCfnProvisioner+AWS::Cognito::UserPoolClient CognitoCfnProvisionerAWS::Cognito::UserPoolDomain CognitoCfnProvisionerAWS::Config::ConfigRule ConfigCfnProvisionerAWS::DynamoDB::GlobalTable LEGACY_SWITCHdiff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yamlindex 6cda91ee01..ca4a97c0e6 100644--- a/tools/docs/cfn_resource_types.yaml+++ b/tools/docs/cfn_resource_types.yaml@@ -152,6 +152,7 @@ notes: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'Custom::DynamoDBReplica: applied natively against DynamoDB, not via a provider Lambda+ AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`'# Trailing prose appended to a row after its type list, for behaviour that belongs to the service# rather than to one type.