refactor(cloudformation): move Cognito UserPool and UserPoolClient to CognitoCfnProvisioner (#3164)

* refactor(cloudformation): move Cognito UserPool and UserPoolClient to CognitoCfnProvisioner

Batch 3 of the CloudFormationResourceProvisioner split. AWS::Cognito::UserPool and
AWS::Cognito::UserPoolClient join the provisioner that already owns UserPoolDomain;
the two arms, their switch cases, the type-list entries, the Cognito-only
resolveStringMapOrNull helper and the CognitoService dependency leave the monolith.

Behaviour is preserved except for what the split's conventions require:

- the create/update branch reads ctx.isUpdate() instead of the resource's physical
  id, which provision overwrites as it runs
- deletes go through CfnDeletes.safeDelete tolerating only ResourceNotFoundException;
  a pool that still has a domain keeps failing the stack delete with
  InvalidParameterException, as on AWS
- the client also exposes Name, the read-only attribute the registry schema declares
  (ClientName stays for now), so CfnSchemaCoverageTest needs no gaps row
- the ReplacementCleanup hooks are wired for both types; nothing replaces yet, so
  they are inert until create-only properties are honoured

The unit test covers both types with a mocked service: request map and generated
names, update carrying the prior id, the exact attribute sets, positional client
arguments, and delete tolerance. The domain delete path now branches on type first,
since a pool resource also carries a UserPoolId attribute.

* fix(cloudformation): replace a Cognito user pool client when its create-only properties change

UserPoolId and GenerateSecret are createOnlyProperties in the AWS::Cognito::UserPoolClient
registry schema: on AWS a change to either creates a new client and deletes the old one
after the update commits. The provisioner passed the new pool id to UpdateUserPoolClient,
which fails with ResourceNotFoundException because a client is only found through the
pool that owns it, and a changed GenerateSecret was silently ignored since the update
call has no such parameter.

The provisioner now looks the prior client up by id, updates in place only when both
create-only properties are unchanged, and otherwise creates the replacement; the
ReplacementCleanup record deletes the displaced client once the update completes or
restores it on rollback. A prior client that is already gone is created anew. The by-id
describeUserPoolClient overload is new on CognitoService, mirroring its delete pair.

* fix(cloudformation): resolve Cognito UserPoolTags as the map the schema declares

AWS::Cognito::UserPool.UserPoolTags is an object (the type's tagProperty), not the
[{Key, Value}] list most types carry. The provisioner parsed it with the list helper,
which yields nothing for a map, so the tags only reached the service through the raw
property map, where a non-string tag value arrives as a number. The tags are now
resolved as a string map and put explicitly, on create and on update.

* fix(cloudformation): give Fn::GetAtt ProviderName on a Cognito user pool AWS's shape

The attribute returned the pool name. On AWS it is cognito-idp.<region>.amazonaws.com/<pool id>,
the value templates feed into an identity pool's CognitoIdentityProviders (CDK derives the
same string in UserPool.fromUserPoolArn). ProviderURL deliberately stays Floci's local
issuer, <base-url>/<pool id>, since that is the iss of the tokens Floci mints and a template
wiring it into a JWT authorizer must validate locally; the generated resource-type table
now says so.

* fix(cognito): apply PoolName on UpdateUserPool so a CloudFormation rename takes effect

UpdateUserPoolRequest carries PoolName in the service model and AWS::Cognito::UserPool
lists UserPoolName as updatable in place, but updateUserPool only ran populateUserPool,
which never sets the name, so a renamed pool kept its old name through both the API and
a stack update. The service now applies a non-blank PoolName.

The provisioner sends PoolName on update only when the template names the pool: an
unnamed pool keeps the name its first execution generated instead of being renamed to a
freshly generated one on every update.

* fix(cloudformation): expose only the schema's attributes on a Cognito user pool client

The AWS::Cognito::UserPoolClient registry schema declares ClientId, Name and ClientSecret
as its read-only properties. ClientName is a request property, not an attribute; on AWS
Fn::GetAtt Client.ClientName fails template validation, so no working template depends on
it. It is dropped in favour of Name.

* fix(cloudformation): validate Cognito user pool client properties instead of dropping them

A non-integer AccessTokenValidity, IdTokenValidity or RefreshTokenValidity was parsed to
null and silently ignored, so the template's intent was lost without a word. The
provisioner now fails the resource with ValidationError "Value of property X must be an
integer.", as the ECS provisioner does for DesiredCount. UserPoolId, the schema's one
required property, is likewise rejected when missing rather than passed through as null.

* test(cloudformation): cover Cognito user pool client replacement end to end

Through the CloudFormation API: a client moved to another pool and one whose
GenerateSecret flips are each replaced, with the displaced client gone once the update
completes; a rename updates the client in place; Fn::GetAtt Name and the pool's
ProviderName carry their AWS shapes; deleting the stack removes client and pools.

* fix(cloudformation): drop a stale ClientSecret attribute when a replacement client has none

The engine hands an update the prior attributes, and the provisioner only wrote
ClientSecret when the new client had one, so replacing a secret-bearing client with
GenerateSecret: false left the displaced client's secret readable through Fn::GetAtt.
The attribute is now removed when the client has no secret; rollback still restores it
from the cleanup record's snapshot.

* fix(cloudformation): refuse a Cognito client replacement that would reuse the prior client id

AWS client ids are random, so a replacement never collides with the client it replaces.
Under Floci's floci:override-cognito-client-id tag the id follows the client name, and a
replacement that kept the name (a GenerateSecret flip, or a move to a pool with the same
override) was created under the prior id: the store overwrote the prior client, the cleanup
record saw an unchanged id and recorded nothing, and the update could not be rolled back.
Neither overwriting nor delete-then-create can preserve the prior client, so the update is
now refused with ValidationError before anything changes and the stack rolls back intact.

CognitoService gains deterministicClientIdFor(userPoolId, clientName), sharing the id rule
with createUserPoolClient; the provisioner compares it with the prior id in the replacement
branch only.

* fix(cloudformation): refuse a Cognito client whose derived id another client already holds

The round-1 guard compared the derived id only with the client being replaced. Under
floci:override-cognito-client-id the store is keyed by client id alone, so a name whose
derived id belongs to any other client, in this pool or another, would overwrite that client
on create, and neither the cleanup record nor rollback knows about it. The guard now refuses
whenever an existing client holds the derived id, on a fresh create as well as a replacement.

* fix(cloudformation): make the deterministic Cognito client-id guard atomic and ignore orphaned records

Two gaps in the round-2 guard. CloudFormationService runs stack operations on a cached
thread pool and CognitoService's client store write is unconditional, so two stacks could
both find a derived id free and the later create overwrote the earlier stack's client; the
existence check and the create now run under one lock whenever the id is derived from the
name. And deleting a user pool does not remove its clients yet (#2949 adds that), so a client
of a deleted pool kept its derived id and the guard refused a legitimate create in another
pool; a holder whose pool no longer exists is now treated as a stale record the create may
take over. Random ids take neither path.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-06 22:51:50 -05:00
1 parent 3bd1be3d42
commit 0321ae0ac8
10 files changed
+1259 -153

No files matched your search

@@ -576,7 +576,6 @@ final class CfnProvisionerFixture {
apiGatewayV2Service,
ecrService,
pipesService,
cognitoService,
lambdaLayerService,
objectMapper,
customResourceResponseStore,
@@ -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.
*/
@QuarkusTest
class 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")
@@ -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());
}
}
@@ -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());
}
@Test
void updateUserPoolWithReservedTagStripsIt() {
UserPool pool = service.createUserPool(Map.of("PoolName", "PinnedPool"), "us-east-1");