feat(cloudformation): provision Cognito resource servers (#4832)

* feat(cloudformation): provision Cognito resource servers

* fix(cloudformation): align rollback tests with deletion cleanup

* fix(cloudformation): abandon exhausted Cognito replacement cleanup

* fix(cloudformation): verify Cognito resource server ownership

* test(cognito): use switch expression for ownership writers

* fix(cloudformation): share optional resolution and delete cleanup hooks

* fix(cognito): use resource server API addresses for stack lifecycle

* fix(cloudformation): avoid repeated Cognito cleanup on stack deletion

* fix(cloudformation): keep consumed resource server cleanup removed

* fix(cloudformation): abandon exhausted Cognito cleanup

* test(cloudformation): cover Cognito resource servers with AWS SDK

* fix(cloudformation): validate Cognito scopes and replace missing servers

* refactor(cloudformation): keep Cognito resource server change scoped
This commit is contained in:
XuJian authored and GitHub committed 2026-10-12 23:20:09 -04:00
1 parent 0edb6993ce
commit ebae2ba0e0
19 files changed
+2971 -139

No files matched your search

@@ -42,6 +42,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrai
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchDashboardCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoResourceServerCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolGroupCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolUserCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolUserToGroupAttachmentCfnProvisioner;
@@ -315,6 +316,7 @@ final class CfnProvisionerFixture {
}
if (cognitoService != null) {
discovered.add(new CognitoCfnProvisioner(cognitoService));
discovered.add(new CognitoResourceServerCfnProvisioner(cognitoService));
discovered.add(new CognitoUserPoolGroupCfnProvisioner(cognitoService));
discovered.add(new CognitoUserPoolUserCfnProvisioner(cognitoService));
discovered.add(new CognitoUserPoolUserToGroupAttachmentCfnProvisioner(cognitoService));
@@ -0,0 +1,857 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@QuarkusTest
class CognitoResourceServerCfnIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/cloudformation/aws4_request";
private static final String IDENTIFIER = "https://api.example.com";
private final ObjectMapper mapper = new ObjectMapper();
private final List<String> poolIds = new ArrayList<>();
private final String stack = "cognito-resource-server-" + Long.toString(System.nanoTime(), 36);
private boolean createdStack;
@InjectSpy
CognitoService cognitoService;
@Inject
CloudFormationService cloudFormationService;
@BeforeAll
static void configureAwsContentTypes() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@AfterEach
void cleanup() {
if (createdStack) {
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
for (String pool : poolIds) {
cognitoAction("DeleteUserPool", "{\"UserPoolId\":\"" + pool + "\"}").then().statusCode(200);
}
}
@Test
void stackCreatesUpdatesReplacesAndDeletesTheBackingResourceServer() throws Exception {
String poolA = createPool();
String poolB = createPool();
createStack(template(poolA, IDENTIFIER, "Original API", "read"));
assertEquals(IDENTIFIER, output("ServerRef"));
assertServer(poolA, IDENTIFIER, "Original API", "read");
JsonNode described = server(poolA, IDENTIFIER);
assertFalse(described.has("incarnationId"));
assertFalse(described.has("IncarnationId"));
JsonNode listed = cognitoJson("ListResourceServers", "{\"UserPoolId\":\"" + poolA + "\"}")
.path("ResourceServers").get(0);
assertFalse(listed.has("incarnationId"));
assertFalse(listed.has("IncarnationId"));
updateStack(template(poolA, IDENTIFIER, "Renamed API", "write"), "UPDATE_COMPLETE");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServer(poolA, IDENTIFIER, "Renamed API", "write");
updateStack(template(poolB, IDENTIFIER, "Moved API", "admin"), "UPDATE_COMPLETE");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServer(poolB, IDENTIFIER, "Moved API", "admin");
assertServerGone(poolA, IDENTIFIER);
String renamed = "https://new-api.example.com";
updateStack(template(poolB, renamed, "New API", "read"), "UPDATE_COMPLETE");
assertEquals(renamed, output("ServerRef"));
assertServerGone(poolB, IDENTIFIER);
assertServer(poolB, renamed, "New API", "read");
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(poolB, renamed);
}
@Test
void twoConsecutivePoolReplacementsKeepTheExactIdentifierRef() throws Exception {
String originalPool = createPool();
String secondPool = createPool();
String thirdPool = createPool();
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
assertEquals(IDENTIFIER, output("ServerRef"));
updateStack(template(secondPool, IDENTIFIER, "Second API", "write"), "UPDATE_COMPLETE");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServerGone(originalPool, IDENTIFIER);
assertServer(secondPool, IDENTIFIER, "Second API", "write");
updateStack(template(thirdPool, IDENTIFIER, "Third API", "admin"), "UPDATE_COMPLETE");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServerGone(originalPool, IDENTIFIER);
assertServerGone(secondPool, IDENTIFIER);
assertServer(thirdPool, IDENTIFIER, "Third API", "admin");
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(thirdPool, IDENTIFIER);
}
@Test
void aPoolReplacementAfterFailedRollbackUsesTheRestoredPoolAndClearsTheOrphan() throws Exception {
String originalPool = createPool();
String failedPool = createPool();
String finalPool = createPool();
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary replacement delete failure", 500))
.when(cognitoService).deleteResourceServer(failedPool, IDENTIFIER);
try {
ObjectNode attempted = template(failedPool, IDENTIFIER, "Failed replacement", "write");
addFailingDependentResource(attempted);
updateStack(attempted, "UPDATE_ROLLBACK_FAILED");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServer(originalPool, IDENTIFIER, "Original API", "read");
assertServer(failedPool, IDENTIFIER, "Failed replacement", "write");
} finally {
doCallRealMethod().when(cognitoService).deleteResourceServer(failedPool, IDENTIFIER);
}
clearInvocations(cognitoService);
updateStack(template(finalPool, IDENTIFIER, "Final API", "admin"), "UPDATE_COMPLETE");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServerGone(originalPool, IDENTIFIER);
assertServerGone(failedPool, IDENTIFIER);
assertServer(finalPool, IDENTIFIER, "Final API", "admin");
verify(cognitoService, times(1)).deleteResourceServer(failedPool, IDENTIFIER);
verify(cognitoService, times(1)).deleteResourceServer(originalPool, IDENTIFIER);
}
@Test
void removingScopesFromTheTemplateClearsTheBackingScopes() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
updateStack(template(pool, IDENTIFIER, "No scopes", null), "UPDATE_COMPLETE");
assertEquals(0, server(pool, IDENTIFIER).path("Scopes").size());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void nullScopesFailCreationWithoutCreatingABackingServer(boolean conditional) throws Exception {
String pool = createPool();
cloudFormation("CreateStack", nullScopesTemplate(pool, "Invalid API", conditional));
createdStack = true;
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
assertScopeValidationFailure();
assertServerGone(pool, IDENTIFIER);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void nullScopesFailUpdateAndPreserveTheBackingConfiguration(boolean conditional) throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
updateStack(nullScopesTemplate(pool, "Changed API", conditional), "UPDATE_ROLLBACK_COMPLETE");
assertScopeValidationFailure();
assertEquals(IDENTIFIER, output("ServerRef"));
assertServer(pool, IDENTIFIER, "Original API", "read");
updateStack(template(pool, IDENTIFIER, "Recovered API", "write"), "UPDATE_COMPLETE");
assertServer(pool, IDENTIFIER, "Recovered API", "write");
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void replacingAnExternallyDeletedServerCreatesTheNewAddress(boolean changePool) throws Exception {
String originalPool = createPool();
String targetPool = changePool ? createPool() : originalPool;
String targetIdentifier = changePool ? IDENTIFIER : "https://replacement.example.com";
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
deleteServer(originalPool);
updateStack(template(targetPool, targetIdentifier, "Replacement API", "write"), "UPDATE_COMPLETE");
assertEquals(targetIdentifier, output("ServerRef"));
assertServer(targetPool, targetIdentifier, "Replacement API", "write");
assertServerGone(originalPool, IDENTIFIER);
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(targetPool, targetIdentifier);
}
@Test
void updatingTheSameAddressStillFailsWhenTheBackingServerWasDeleted() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
deleteServer(pool);
updateStack(template(pool, IDENTIFIER, "Changed API", "write"), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServerGone(pool, IDENTIFIER);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void replacementRollbackRestoresMissingOldAddressMetadataAndDeletesTheNewServer(boolean changePool)
throws Exception {
String originalPool = createPool();
String targetPool = changePool ? createPool() : originalPool;
String targetIdentifier = changePool ? IDENTIFIER : "https://replacement.example.com";
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
deleteServer(originalPool);
ObjectNode attempted = template(targetPool, targetIdentifier, "Replacement API", "write");
addFailingDependentResource(attempted);
updateStack(attempted, "UPDATE_ROLLBACK_COMPLETE");
verify(cognitoService).createResourceServer(eq(targetPool), eq(targetIdentifier), eq("Replacement API"), any());
verify(cognitoService).deleteResourceServer(targetPool, targetIdentifier);
assertEquals(IDENTIFIER, output("ServerRef"));
assertServerGone(originalPool, IDENTIFIER);
assertServerGone(targetPool, targetIdentifier);
String restoredPool = cloudFormationService.describeStacks(stack, "us-east-1", "000000000000")
.getFirst().getResources().get("Server")
.getAttributes().get("__FlociResourceServerPoolId");
assertEquals(originalPool, restoredPool);
}
@Test
void updatingAnOutOfBandRecreatedServerRestoresTheTemplateConfiguration() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
deleteServer(pool);
createServer(pool, "Out of band API", "admin");
updateStack(template(pool, IDENTIFIER, "Template API", "write"), "UPDATE_COMPLETE");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServer(pool, IDENTIFIER, "Template API", "write");
}
@Test
void deletingAStackDeletesTheOutOfBandRecreatedServerAtItsManagedAddress() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
deleteServer(pool);
createServer(pool, "Out of band API", "admin");
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(pool, IDENTIFIER);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void laterStackOperationsDoNotDeleteAnOldServerAbandonedAfterThreeFailures(boolean anotherUpdate)
throws Exception {
String originalPool = createPool();
String replacementPool = createPool();
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary old server delete failure", 500))
.when(cognitoService).deleteResourceServer(originalPool, IDENTIFIER);
try {
updateStack(template(replacementPool, IDENTIFIER, "Replacement API", "write"), "UPDATE_COMPLETE");
verify(cognitoService, times(3)).deleteResourceServer(originalPool, IDENTIFIER);
assertServer(originalPool, IDENTIFIER, "Original API", "read");
assertServer(replacementPool, IDENTIFIER, "Replacement API", "write");
} finally {
doCallRealMethod().when(cognitoService).deleteResourceServer(originalPool, IDENTIFIER);
}
ObjectNode outsideStack = mapper.createObjectNode().put("UserPoolId", originalPool)
.put("Identifier", IDENTIFIER).put("Name", "Managed outside stack");
outsideStack.putArray("Scopes").addObject().put("ScopeName", "read").put("ScopeDescription", "Access");
cognitoAction("UpdateResourceServer", outsideStack.toString()).then().statusCode(200);
if (anotherUpdate) {
updateStack(template(replacementPool, IDENTIFIER, "Later API", "admin"), "UPDATE_COMPLETE");
assertServer(replacementPool, IDENTIFIER, "Later API", "admin");
assertServer(originalPool, IDENTIFIER, "Managed outside stack", "read");
}
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(replacementPool, IDENTIFIER);
assertServer(originalPool, IDENTIFIER, "Managed outside stack", "read");
verify(cognitoService, times(3)).deleteResourceServer(originalPool, IDENTIFIER);
}
@Test
void changingOnlyTheConditionClearsAndRestoresOptionalScopes() throws Exception {
String pool = createPool();
createStack(conditionalScopeTemplate(pool, false, false));
assertEquals(0, server(pool, IDENTIFIER).path("Scopes").size());
updateStack(conditionalScopeTemplate(pool, true, false), "UPDATE_COMPLETE");
assertServer(pool, IDENTIFIER, "Conditional API", "read");
updateStack(conditionalScopeTemplate(pool, false, false), "UPDATE_COMPLETE");
assertEquals(0, server(pool, IDENTIFIER).path("Scopes").size());
assertEquals(IDENTIFIER, output("ServerRef"));
updateStack(conditionalScopeTemplate(pool, true, false), "UPDATE_COMPLETE");
assertServer(pool, IDENTIFIER, "Conditional API", "read");
}
@Test
void changingOnlyTheConditionOmitsOneScopeAndPreservesTheOther() throws Exception {
String pool = createPool();
createStack(conditionalScopeTemplate(pool, true, true));
assertEquals(2, server(pool, IDENTIFIER).path("Scopes").size());
assertEquals("write", server(pool, IDENTIFIER).path("Scopes").get(1).path("ScopeName").asText());
updateStack(conditionalScopeTemplate(pool, false, true), "UPDATE_COMPLETE");
assertServer(pool, IDENTIFIER, "Conditional API", "read");
updateStack(conditionalScopeTemplate(pool, true, true), "UPDATE_COMPLETE");
assertEquals(2, server(pool, IDENTIFIER).path("Scopes").size());
assertEquals("write", server(pool, IDENTIFIER).path("Scopes").get(1).path("ScopeName").asText());
assertEquals(IDENTIFIER, output("ServerRef"));
}
@Test
void stackResolvesTheDeclaredUserPoolAndNestedScopeParameter() throws Exception {
ObjectNode template = template("placeholder", IDENTIFIER, "Example API", "placeholder");
template.putObject("Parameters").putObject("Scope").put("Type", "String").put("Default", "read");
ObjectNode resources = (ObjectNode) template.path("Resources");
ObjectNode pool = resources.putObject("Pool");
pool.put("Type", "AWS::Cognito::UserPool");
pool.putObject("Properties").put("UserPoolName", stack);
ObjectNode properties = (ObjectNode) resources.path("Server").path("Properties");
properties.putObject("UserPoolId").put("Ref", "Pool");
((ObjectNode) properties.path("Scopes").get(0)).putObject("ScopeName").put("Ref", "Scope");
((ObjectNode) template.path("Outputs")).putObject("PoolRef").putObject("Value").put("Ref", "Pool");
createStack(template);
String poolId = output("PoolRef");
assertEquals(IDENTIFIER, output("ServerRef"));
assertServer(poolId, IDENTIFIER, "Example API", "read");
}
@Test
void failingResourceServerUpdateRestoresItsNameAndScopes() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
ObjectNode attempted = template(pool, IDENTIFIER, "Attempted name", "write");
ObjectNode properties = (ObjectNode) attempted.path("Resources").path("Server").path("Properties");
properties.withArray("Scopes").addObject().put("ScopeName", "write").put("ScopeDescription", "Duplicate");
updateStack(attempted, "UPDATE_ROLLBACK_COMPLETE");
assertServer(pool, IDENTIFIER, "Original API", "read");
assertEquals(IDENTIFIER, output("ServerRef"));
}
@Test
void aFailedDependentResourceRestoresThePriorInPlaceConfiguration() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
ObjectNode attempted = template(pool, IDENTIFIER, "Attempted name", "write");
addFailingDependentResource(attempted);
updateStack(attempted, "UPDATE_ROLLBACK_COMPLETE");
assertServer(pool, IDENTIFIER, "Original API", "read");
}
@Test
void aFailedDependentResourceDeletesTheReplacementAndRestoresThePriorPool() throws Exception {
String poolA = createPool();
String poolB = createPool();
createStack(template(poolA, IDENTIFIER, "Original API", "read"));
ObjectNode attempted = template(poolB, IDENTIFIER, "Replacement API", "write");
addFailingDependentResource(attempted);
updateStack(attempted, "UPDATE_ROLLBACK_COMPLETE");
assertServer(poolA, IDENTIFIER, "Original API", "read");
assertServerGone(poolB, IDENTIFIER);
assertEquals(IDENTIFIER, output("ServerRef"));
}
@Test
void pendingInPlaceRestorationRecoversTheTemplateAfterOutOfBandRecreation() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary restore failure", 500))
.when(cognitoService).updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
try {
ObjectNode attempted = template(pool, IDENTIFIER, "Failed attempt", "write");
addFailingDependentResource(attempted);
updateStack(attempted, "UPDATE_ROLLBACK_FAILED");
} finally {
doCallRealMethod().when(cognitoService)
.updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
}
deleteServer(pool);
createServer(pool, "Out of band API", "admin");
ObjectNode nextAttempt = template(pool, IDENTIFIER, "Next attempt", "write");
addFailingDependentResource(nextAttempt);
nextAttempt.withObject("/Resources/Broken/Properties").put("ClientName", "second-broken");
updateStack(nextAttempt, "UPDATE_ROLLBACK_COMPLETE");
assertServer(pool, IDENTIFIER, "Original API", "read");
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(pool, IDENTIFIER);
}
@Test
void aFreshReplacementAtAnOldCleanupAddressKeepsItsOwnDeletionResponsibility() throws Exception {
String originalPool = createPool();
String replacementPool = createPool();
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary replacement delete failure", 500))
.when(cognitoService).deleteResourceServer(replacementPool, IDENTIFIER);
try {
ObjectNode firstAttempt = template(replacementPool, IDENTIFIER, "First attempt", "write");
addFailingDependentResource(firstAttempt);
updateStack(firstAttempt, "UPDATE_ROLLBACK_FAILED");
assertServer(replacementPool, IDENTIFIER, "First attempt", "write");
} finally {
doCallRealMethod().when(cognitoService).deleteResourceServer(replacementPool, IDENTIFIER);
}
deleteServer(replacementPool);
doAnswer(invocation -> {
cognitoService.describeResourceServer(replacementPool, IDENTIFIER);
throw new AwsException("InternalErrorException", "new replacement delete failure", 500);
}).when(cognitoService).deleteResourceServer(replacementPool, IDENTIFIER);
try {
ObjectNode secondAttempt = template(replacementPool, IDENTIFIER, "Second attempt", "admin");
addFailingDependentResource(secondAttempt);
secondAttempt.withObject("/Resources/Broken/Properties").put("ClientName", "second-broken");
updateStack(secondAttempt, "UPDATE_ROLLBACK_FAILED");
assertServer(originalPool, IDENTIFIER, "Original API", "read");
assertServer(replacementPool, IDENTIFIER, "Second attempt", "admin");
} finally {
doCallRealMethod().when(cognitoService).deleteResourceServer(replacementPool, IDENTIFIER);
}
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(originalPool, IDENTIFIER);
assertServerGone(replacementPool, IDENTIFIER);
}
@Test
void aFailedProvisionRetryPreservesHistoricalCleanupUntilStackDeletion() throws Exception {
String originalPool = createPool();
String historicalPool = createPool();
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary replacement delete failure", 500))
.when(cognitoService).deleteResourceServer(historicalPool, IDENTIFIER);
try {
ObjectNode attempted = template(historicalPool, IDENTIFIER, "Failed replacement", "write");
addFailingDependentResource(attempted);
updateStack(attempted, "UPDATE_ROLLBACK_FAILED");
} finally {
doCallRealMethod().when(cognitoService).deleteResourceServer(historicalPool, IDENTIFIER);
}
assertServer(historicalPool, IDENTIFIER, "Failed replacement", "write");
deleteServer(originalPool);
clearInvocations(cognitoService);
updateStack(template(originalPool, IDENTIFIER, "Retry API", "read"), "UPDATE_ROLLBACK_COMPLETE");
verify(cognitoService, times(0)).deleteResourceServer(historicalPool, IDENTIFIER);
verify(cognitoService, times(1)).describeResourceServer(originalPool, IDENTIFIER);
assertServer(historicalPool, IDENTIFIER, "Failed replacement", "write");
Stack owner = cloudFormationService.describeStacks(stack, "us-east-1", "000000000000").getFirst();
assertTrue(owner.resourcesSnapshot().get("Server").getAttributes()
.containsKey(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
clearInvocations(cognitoService);
updateStack(template(originalPool, IDENTIFIER, "Second retry API", "write"), "UPDATE_ROLLBACK_COMPLETE");
verify(cognitoService, times(0)).deleteResourceServer(historicalPool, IDENTIFIER);
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(historicalPool, IDENTIFIER);
verify(cognitoService, times(1)).deleteResourceServer(historicalPool, IDENTIFIER);
}
@Test
void aPendingRollbackSurvivesFailedUpdatesUntilItCanBeRestored() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary restore failure", 500))
.when(cognitoService).updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
try {
ObjectNode firstAttempt = template(pool, IDENTIFIER, "First attempt", "write");
addFailingDependentResource(firstAttempt);
updateStack(firstAttempt, "UPDATE_ROLLBACK_FAILED");
assertServer(pool, IDENTIFIER, "First attempt", "write");
ObjectNode nextAttempt = template(pool, IDENTIFIER, "Next attempt", "admin");
addFailingDependentResource(nextAttempt);
nextAttempt.withObject("/Resources/Broken/Properties").put("ClientName", "broken-next");
updateStack(nextAttempt, "UPDATE_ROLLBACK_FAILED");
assertServer(pool, IDENTIFIER, "First attempt", "write");
doCallRealMethod().when(cognitoService)
.updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
ObjectNode recoveryAttempt = template(pool, IDENTIFIER, "Recovery attempt", "write");
addFailingDependentResource(recoveryAttempt);
recoveryAttempt.withObject("/Resources/Broken/Properties").put("ClientName", "broken-recovery");
updateStack(recoveryAttempt, "UPDATE_ROLLBACK_COMPLETE");
assertServer(pool, IDENTIFIER, "Original API", "read");
assertEquals(IDENTIFIER, output("ServerRef"));
} finally {
doCallRealMethod().when(cognitoService)
.updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
}
}
@Test
void skippingAPendingRollbackPreservesRestorationAndBlocksAnotherUpdate() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary restore failure", 500))
.when(cognitoService).updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
try {
ObjectNode firstAttempt = template(pool, IDENTIFIER, "First attempt", "write");
addFailingDependentResource(firstAttempt);
updateStack(firstAttempt, "UPDATE_ROLLBACK_FAILED");
assertServer(pool, IDENTIFIER, "First attempt", "write");
ObjectNode outputsOnly = firstAttempt.deepCopy();
outputsOnly.withObject("/Resources").remove("Broken");
outputsOnly.withObject("/Outputs").putObject("Marker").put("Value", "unchanged-resource");
cloudFormation("UpdateStack", outputsOnly);
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertEquals("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", stackStatus(),
"Skipping the resource must not discard its pending restoration"));
assertServer(pool, IDENTIFIER, "First attempt", "write");
assertEquals(IDENTIFIER, output("ServerRef"));
ObjectNode nextAttempt = template(pool, IDENTIFIER, "Next attempt", "admin");
String error = given().contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH).formParam("Action", "UpdateStack")
.formParam("StackName", stack).formParam("TemplateBody", nextAttempt.toString())
.post("/").then().statusCode(400).extract().asString();
assertEquals("ValidationError", XmlParser.extractFirst(error, "Code", null));
assertTrue(XmlParser.extractFirst(error, "Message", "")
.contains("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"));
assertEquals("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", stackStatus());
assertServer(pool, IDENTIFIER, "First attempt", "write");
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(pool, IDENTIFIER);
} finally {
doCallRealMethod().when(cognitoService)
.updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
}
}
@Test
void aNameOnlyChangeSetUpdatesTheExistingServerWithoutReplacement() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
changeSet("CreateChangeSet", "rename-display", template(pool, IDENTIFIER, "Renamed API", "read"));
Map<String, String> change = resourceChange(changeSet("DescribeChangeSet", "rename-display", null));
assertEquals("Modify", change.get("Action"));
assertEquals("False", change.get("Replacement"));
changeSet("ExecuteChangeSet", "rename-display", null);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
assertServer(pool, IDENTIFIER, "Renamed API", "read");
assertEquals(IDENTIFIER, output("ServerRef"));
}
@Test
void deletingAPendingRollbackKeepsTrackingAfterADeleteFailureAndCanBeRetried() throws Exception {
String pool = createPool();
createStack(template(pool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary restore failure", 500))
.when(cognitoService).updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
doThrow(new AwsException("InternalErrorException", "temporary delete failure", 500))
.when(cognitoService).deleteResourceServer(pool, IDENTIFIER);
try {
ObjectNode attempted = template(pool, IDENTIFIER, "Attempted API", "write");
addFailingDependentResource(attempted);
updateStack(attempted, "UPDATE_ROLLBACK_FAILED");
assertServer(pool, IDENTIFIER, "Attempted API", "write");
cloudFormation("DeleteStack", null);
assertEquals("DELETE_FAILED", CfnStackWaits.awaitTerminal(stack).status());
assertServer(pool, IDENTIFIER, "Attempted API", "write");
doCallRealMethod().when(cognitoService).deleteResourceServer(pool, IDENTIFIER);
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServerGone(pool, IDENTIFIER);
} finally {
doCallRealMethod().when(cognitoService)
.updateResourceServer(eq(pool), eq(IDENTIFIER), eq("Original API"), any());
doCallRealMethod().when(cognitoService).deleteResourceServer(pool, IDENTIFIER);
}
}
@Test
void stackDeletionDoesNotRepeatExhaustedCleanupBeforeDeletingTheManagedServer() throws Exception {
String originalPool = createPool();
String replacementPool = createPool();
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
doThrow(new AwsException("InternalErrorException", "temporary replacement delete failure", 500))
.when(cognitoService).deleteResourceServer(replacementPool, IDENTIFIER);
doThrow(new AwsException("InternalErrorException", "temporary managed delete failure", 500))
.when(cognitoService).deleteResourceServer(originalPool, IDENTIFIER);
try {
ObjectNode attempted = template(replacementPool, IDENTIFIER, "Failed replacement", "write");
addFailingDependentResource(attempted);
updateStack(attempted, "UPDATE_ROLLBACK_FAILED");
clearInvocations(cognitoService);
cloudFormation("DeleteStack", null);
assertEquals("DELETE_FAILED", CfnStackWaits.awaitTerminal(stack).status());
verify(cognitoService, times(3)).deleteResourceServer(replacementPool, IDENTIFIER);
verify(cognitoService, times(1)).deleteResourceServer(originalPool, IDENTIFIER);
assertServer(originalPool, IDENTIFIER, "Original API", "read");
assertServer(replacementPool, IDENTIFIER, "Failed replacement", "write");
doCallRealMethod().when(cognitoService).deleteResourceServer(replacementPool, IDENTIFIER);
deleteServer(replacementPool);
createServer(replacementPool, "Directly reused API", "admin");
doCallRealMethod().when(cognitoService).deleteResourceServer(originalPool, IDENTIFIER);
clearInvocations(cognitoService);
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
createdStack = false;
assertServer(replacementPool, IDENTIFIER, "Directly reused API", "admin");
verify(cognitoService, times(0)).deleteResourceServer(replacementPool, IDENTIFIER);
verify(cognitoService, times(1)).deleteResourceServer(originalPool, IDENTIFIER);
assertServerGone(originalPool, IDENTIFIER);
} finally {
doCallRealMethod().when(cognitoService).deleteResourceServer(replacementPool, IDENTIFIER);
doCallRealMethod().when(cognitoService).deleteResourceServer(originalPool, IDENTIFIER);
}
}
@Test
void aPoolOnlyChangeSetReplacesTheServerEvenWhenItsRefStaysTheSame() throws Exception {
String originalPool = createPool();
String replacementPool = createPool();
createStack(template(originalPool, IDENTIFIER, "Original API", "read"));
changeSet("CreateChangeSet", "move-pool", template(replacementPool, IDENTIFIER, "Original API", "read"));
Map<String, String> change = resourceChange(changeSet("DescribeChangeSet", "move-pool", null));
assertEquals("Modify", change.get("Action"));
assertEquals("True", change.get("Replacement"));
changeSet("ExecuteChangeSet", "move-pool", null);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
assertServerGone(originalPool, IDENTIFIER);
assertServer(replacementPool, IDENTIFIER, "Original API", "read");
assertEquals(IDENTIFIER, output("ServerRef"));
}
private String createPool() throws Exception {
String id = cognitoJson("CreateUserPool", "{\"PoolName\":\"" + stack + "\"}")
.path("UserPool").path("Id").asText();
poolIds.add(id);
return id;
}
private void deleteServer(String pool) {
cognitoAction("DeleteResourceServer", mapper.createObjectNode().put("UserPoolId", pool)
.put("Identifier", IDENTIFIER).toString()).then().statusCode(200);
}
private void createServer(String pool, String name, String scope) {
ObjectNode request = mapper.createObjectNode().put("UserPoolId", pool).put("Identifier", IDENTIFIER).put("Name", name);
request.putArray("Scopes").addObject().put("ScopeName", scope).put("ScopeDescription", "Access");
cognitoAction("CreateResourceServer", request.toString()).then().statusCode(200);
}
private void createStack(ObjectNode template) {
cloudFormation("CreateStack", template);
createdStack = true;
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
}
private void updateStack(ObjectNode template, String expectedStatus) {
cloudFormation("UpdateStack", template);
assertEquals(expectedStatus, CfnStackWaits.awaitTerminal(stack).status());
}
private void cloudFormation(String action, ObjectNode template) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (template != null) {
request.formParam("TemplateBody", template.toString());
}
request.when().post("/").then().statusCode(200);
}
private String output(String key) {
String xml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200).extract().asString();
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
private String stackStatus() {
String xml = given().contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH).formParam("Action", "DescribeStacks")
.formParam("StackName", stack).post("/").then().statusCode(200).extract().asString();
return XmlParser.extractFirst(xml, "StackStatus", null);
}
private String changeSet(String action, String name, ObjectNode template) {
RequestSpecification request = given().contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH).formParam("Action", action)
.formParam("StackName", stack).formParam("ChangeSetName", name);
if (template != null) {
request.formParam("ChangeSetType", "UPDATE").formParam("TemplateBody", template.toString());
}
return request.post("/").then().statusCode(200).extract().asString();
}
private static Map<String, String> resourceChange(String xml) {
return XmlParser.extractGroups(xml, "ResourceChange").stream()
.filter(change -> "Server".equals(change.get("LogicalResourceId")))
.findFirst().orElseThrow();
}
private ObjectNode template(String pool, String identifier, String name, String scope) {
ObjectNode template = mapper.createObjectNode();
ObjectNode resource = template.putObject("Resources").putObject("Server");
resource.put("Type", "AWS::Cognito::UserPoolResourceServer");
ObjectNode properties = resource.putObject("Properties");
properties.put("UserPoolId", pool);
properties.put("Identifier", identifier);
properties.put("Name", name);
if (scope != null) {
properties.putArray("Scopes").addObject().put("ScopeName", scope).put("ScopeDescription", "Access");
}
template.putObject("Outputs").putObject("ServerRef").putObject("Value").put("Ref", "Server");
return template;
}
private ObjectNode conditionalScopeTemplate(String pool, boolean enabled, boolean entry) {
ObjectNode template = template(pool, IDENTIFIER, "Conditional API", "read");
template.putObject("Conditions").putObject("IncludeScopes")
.putArray("Fn::Equals").add("enabled").add(enabled ? "enabled" : "disabled");
ObjectNode properties = (ObjectNode) template.path("Resources").path("Server").path("Properties");
ObjectNode conditional = mapper.createObjectNode();
JsonNode included = entry
? mapper.createObjectNode().put("ScopeName", "write").put("ScopeDescription", "Write access")
: properties.path("Scopes");
conditional.putArray("Fn::If").add("IncludeScopes").add(included)
.add(mapper.createObjectNode().put("Ref", "AWS::NoValue"));
if (entry) {
properties.withArray("Scopes").add(conditional);
} else {
properties.set("Scopes", conditional);
}
return template;
}
private ObjectNode nullScopesTemplate(String pool, String name, boolean conditional) {
ObjectNode template = template(pool, IDENTIFIER, name, null);
ObjectNode properties = (ObjectNode) template.path("Resources").path("Server").path("Properties");
if (conditional) {
template.putObject("Conditions").putObject("UseNull")
.putArray("Fn::Equals").add("enabled").add("enabled");
properties.putObject("Scopes").putArray("Fn::If")
.add("UseNull").addNull().add(mapper.createArrayNode());
} else {
properties.putNull("Scopes");
}
return template;
}
private void assertScopeValidationFailure() {
String events = given().contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH).formParam("Action", "DescribeStackEvents")
.formParam("StackName", stack).post("/").then().statusCode(200).extract().asString();
assertTrue(events.contains("Scopes must be a list"));
}
private static void addFailingDependentResource(ObjectNode template) {
ObjectNode broken = ((ObjectNode) template.path("Resources")).putObject("Broken");
broken.put("Type", "AWS::Cognito::UserPoolClient");
broken.put("DependsOn", "Server");
broken.putObject("Properties").put("UserPoolId", "us-east-1_nonexistent").put("ClientName", "broken");
}
private static JsonNode server(String pool, String identifier) throws Exception {
return cognitoJson("DescribeResourceServer", "{\"UserPoolId\":\"" + pool
+ "\",\"Identifier\":\"" + identifier + "\"}").path("ResourceServer");
}
private static void assertServer(String pool, String identifier, String name, String scope) throws Exception {
JsonNode server = server(pool, identifier);
assertEquals(identifier, server.path("Identifier").asText());
assertEquals(name, server.path("Name").asText());
assertEquals(1, server.path("Scopes").size());
assertEquals(scope, server.path("Scopes").get(0).path("ScopeName").asText());
}
private static void assertServerGone(String pool, String identifier) {
cognitoAction("DescribeResourceServer", "{\"UserPoolId\":\"" + pool
+ "\",\"Identifier\":\"" + identifier + "\"}")
.then().statusCode(400).body("__type", equalTo("ResourceNotFoundException"));
}
}
@@ -0,0 +1,966 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.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.ResourceServer;
import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
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.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class CognitoResourceServerCfnProvisionerTest {
private static final String POOL = "us-east-1_original";
private static final String NEW_POOL = "us-east-1_replacement";
private static final String THIRD_POOL = "us-east-1_third";
private static final String IDENTIFIER = "https://api.example.com";
private final CognitoService cognito = mock(CognitoService.class);
private final CognitoResourceServerCfnProvisioner provisioner = new CognitoResourceServerCfnProvisioner(cognito);
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx(String priorId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(invocation -> {
JsonNode node = invocation.getArgument(0);
return node == null || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(invocation -> invocation.getArgument(0));
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(invocation -> invocation.getArgument(0));
return new ProvisionContext(engine, "us-east-1", "000000000000", "test-stack", priorId);
}
private ProvisionContext intrinsicContext() {
CloudFormationTemplateEngine engine = CloudFormationTemplateEngine.standalone(
"000000000000", "us-east-1", "test-stack", mapper, null);
return new ProvisionContext(engine, "us-east-1", "000000000000", "test-stack");
}
private ObjectNode properties(String poolId, String identifier, String name) {
ObjectNode properties = mapper.createObjectNode();
if (poolId != null) {
properties.put("UserPoolId", poolId);
}
if (identifier != null) {
properties.put("Identifier", identifier);
}
if (name != null) {
properties.put("Name", name);
}
return properties;
}
private StackResource resource(String identifier, String poolId) {
StackResource resource = new StackResource();
resource.setLogicalId("ApiResourceServer");
resource.setResourceType("AWS::Cognito::UserPoolResourceServer");
resource.setPhysicalId(identifier);
resource.setAttributes(new HashMap<>());
if (poolId != null) {
resource.getAttributes().put("__FlociResourceServerPoolId", poolId);
}
return resource;
}
private void oweCleanup(StackResource resource, String poolId, String identifier,
boolean retainable, int attempts) {
ObjectNode cleanup = mapper.createObjectNode().put("region", "us-east-1");
cleanup.putArray("displaced").addObject()
.put("physicalId", mapper.createArrayNode().add(poolId).add(identifier).toString())
.put("resourceType", resource.getResourceType())
.put("region", "us-east-1")
.put("retainable", retainable)
.put("cleanupAttempts", attempts);
resource.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, cleanup.toString());
}
private static ResourceServer server(String poolId, String identifier, String name) {
ResourceServer server = new ResourceServer();
server.setUserPoolId(poolId);
server.setIdentifier(identifier);
server.setName(name);
ResourceServerScope scope = new ResourceServerScope();
scope.setScopeName("read");
scope.setScopeDescription("Read access");
server.setScopes(List.of(scope));
return server;
}
@Test
void servesResourceServerType() {
assertEquals(Set.of("AWS::Cognito::UserPoolResourceServer"), provisioner.resourceTypes());
}
@Test
void createsResourceServerWithResolvedScopesAndSetsRefAndPoolTracking() {
ObjectNode properties = properties(POOL, IDENTIFIER, "Example API");
ObjectNode scope = properties.putArray("Scopes").addObject();
scope.put("ScopeName", "read");
scope.put("ScopeDescription", "Read access");
StackResource resource = resource(null, null);
provisioner.provision(resource, properties, ctx(null));
ArgumentCaptor<List<ResourceServerScope>> scopes = ArgumentCaptor.forClass(List.class);
verify(cognito).createResourceServer(eq(POOL), eq(IDENTIFIER), eq("Example API"), scopes.capture());
assertEquals("read", scopes.getValue().getFirst().getScopeName());
assertEquals("Read access", scopes.getValue().getFirst().getScopeDescription());
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
assertFalse(resource.getAttributes().containsKey("Identifier"));
assertFalse(resource.getAttributes().containsKey("Name"));
assertFalse(resource.getAttributes().containsKey("UserPoolId"));
}
private StackResource stub() {
StackResource resource = resource("ApiResourceServer-1a2b3c4d", null);
resource.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + resource.getLogicalId());
return resource;
}
@ParameterizedTest
@ValueSource(strings = {"null", "{}", "\"invalid\""})
void rejectsPresentMalformedCleanupEntriesBeforeDeletingAnything(String entries) throws Exception {
StackResource resource = resource(IDENTIFIER, POOL);
ObjectNode cleanup = mapper.createObjectNode();
cleanup.set("displaced", mapper.readTree(entries));
resource.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, cleanup.toString());
assertThrows(IllegalStateException.class, () -> provisioner.completeDeleteCleanup(resource));
verifyNoInteractions(cognito);
}
@Test
void migratesDispatcherStubByCreatingTheServerWithoutOwingTheFakeIdADelete() {
StackResource resource = stub();
provisioner.provision(resource, properties(POOL, IDENTIFIER, "API"), ctx(resource.getPhysicalId()));
verify(cognito).createResourceServer(POOL, IDENTIFIER, "API", List.of());
verify(cognito, never()).describeResourceServer(any(), any());
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
assertFalse(resource.getAttributes().containsKey("Arn"));
assertTrue(provisioner.retainsFailedUpdateState(resource));
assertFalse(provisioner.hasReplacementUpdate(resource));
assertNull(provisioner.updateCleanupPhysicalId(resource));
provisioner.completeUpdate(resource);
assertFalse(provisioner.retainsFailedUpdateState(resource));
verify(cognito, never()).deleteResourceServer(any(), any());
}
@Test
void rollingBackStubMigrationRestoresTheFakeIdentityAndDeletesOnlyTheCreatedServer() {
StackResource resource = stub();
String fakeId = resource.getPhysicalId();
provisioner.provision(resource, properties(POOL, IDENTIFIER, "API"), ctx(fakeId));
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals(fakeId, resource.getPhysicalId());
assertEquals(CfnResourceDispatcher.STUB_ARN_PREFIX + resource.getLogicalId(),
resource.getAttributes().get("Arn"));
assertFalse(resource.getAttributes().containsKey("__FlociResourceServerPoolId"));
assertFalse(provisioner.hasReplacementUpdate(resource));
assertFalse(provisioner.retainsFailedUpdateState(resource));
verify(cognito).deleteResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(any(), eq(fakeId));
}
@Test
void failedStubRollbackPreservesTheCreatedOrphanAndItsBudgetWhenPreviousMetadataIsRestored() {
StackResource previous = stub();
StackResource attempted = stub();
String fakeId = previous.getPhysicalId();
provisioner.provision(attempted, properties(POOL, IDENTIFIER, "API"), ctx(fakeId));
doThrow(new IllegalStateException("retry"))
.when(cognito).deleteResourceServer(POOL, IDENTIFIER);
assertThrows(IllegalStateException.class, () -> provisioner.rollbackUpdate(attempted));
assertEquals(fakeId, attempted.getPhysicalId());
ReplacementCleanup.mergeDisplaced(previous, attempted);
assertEquals(fakeId, previous.getPhysicalId());
assertEquals(IDENTIFIER, provisioner.updateCleanupPhysicalId(previous));
for (int attempt = 1; attempt <= 3; attempt++) {
UpdateCleanupResult result = provisioner.completeDeleteCleanup(previous);
assertFalse(result.complete());
assertEquals(IDENTIFIER, result.previousPhysicalId());
assertEquals(attempt, result.attempts());
}
provisioner.clearDeleteCleanup(previous);
assertFalse(provisioner.hasReplacementUpdate(previous));
assertFalse(previous.getAttributes().containsKey("__FlociResourceServerPoolId"));
assertEquals(fakeId, previous.getPhysicalId());
provisioner.completeDeleteCleanup(previous);
provisioner.delete(previous, "us-east-1");
verify(cognito, times(4)).deleteResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(any(), eq(fakeId));
}
@Test
void rejectsMissingRequiredPropertiesAndMalformedScopesBeforeCallingCognito() {
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
properties(null, IDENTIFIER, "API"), ctx(null)));
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
properties(POOL, null, "API"), ctx(null)));
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
properties(POOL, IDENTIFIER, null), ctx(null)));
ObjectNode invalid = properties(POOL, IDENTIFIER, "API");
invalid.putArray("Scopes").addObject().put("ScopeName", "read");
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null), invalid, ctx(null)));
verifyNoInteractions(cognito);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void rejectsNullScopesBeforeCreateOrUpdate(boolean update) {
ObjectNode properties = properties(POOL, IDENTIFIER, "Changed API");
properties.putNull("Scopes");
StackResource resource = resource(update ? IDENTIFIER : null, update ? POOL : null);
HashMap<String, String> priorAttributes = new HashMap<>(resource.getAttributes());
String priorPhysicalId = resource.getPhysicalId();
if (update) {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Original API"));
}
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource, properties,
ctx(update ? IDENTIFIER : null)));
assertEquals("ValidationError", failure.getErrorCode());
assertEquals(priorPhysicalId, resource.getPhysicalId());
assertEquals(priorAttributes, resource.getAttributes());
verifyNoInteractions(cognito);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void replacesExternallyDeletedServerBeforeCleaningItsOldAddress(boolean changePool) {
String targetPool = changePool ? NEW_POOL : POOL;
String targetIdentifier = changePool ? IDENTIFIER : "https://replacement.example.com";
StackResource resource = resource(IDENTIFIER, POOL);
when(cognito.describeResourceServer(POOL, IDENTIFIER))
.thenThrow(new AwsException("ResourceNotFoundException", "old server was deleted", 400));
doThrow(new AwsException("ResourceNotFoundException", "old server was deleted", 400))
.when(cognito).deleteResourceServer(POOL, IDENTIFIER);
provisioner.provision(resource, properties(targetPool, targetIdentifier, "Replacement API"), ctx(IDENTIFIER));
verify(cognito).createResourceServer(targetPool, targetIdentifier, "Replacement API", List.of());
verify(cognito, never()).describeResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(POOL, IDENTIFIER);
assertEquals(targetIdentifier, resource.getPhysicalId());
assertEquals(targetPool, resource.getAttributes().get("__FlociResourceServerPoolId"));
assertTrue(provisioner.hasReplacementUpdate(resource));
assertTrue(provisioner.completeUpdate(resource).complete());
verify(cognito).deleteResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(targetPool, targetIdentifier);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void rejectsConditionallyResolvedNullScopesWithoutChangingResourceMetadata(boolean update) throws Exception {
ObjectNode properties = properties(POOL, IDENTIFIER, "Changed API");
properties.set("Scopes", mapper.readTree("""
{"Fn::If": ["IncludeScopes", {"Ref": "AWS::NoValue"}, null]}
"""));
StackResource resource = resource(update ? IDENTIFIER : null, update ? POOL : null);
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, "previous rollback failure");
HashMap<String, String> priorAttributes = new HashMap<>(resource.getAttributes());
ProvisionContext initial = intrinsicContext();
ProvisionContext context = new ProvisionContext(initial.engine(), initial.region(), initial.accountId(),
initial.stackName(), update ? IDENTIFIER : null);
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource, properties, context));
assertEquals("ValidationError", failure.getErrorCode());
assertEquals(update ? IDENTIFIER : null, resource.getPhysicalId());
assertEquals(priorAttributes, resource.getAttributes());
verifyNoInteractions(cognito);
}
@Test
void aMissingServerStillFailsAnUpdateAtTheSameAddress() {
StackResource resource = resource(IDENTIFIER, POOL);
HashMap<String, String> priorAttributes = new HashMap<>(resource.getAttributes());
AwsException missing = new AwsException("ResourceNotFoundException", "server was deleted", 400);
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenThrow(missing);
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource,
properties(POOL, IDENTIFIER, "Changed API"), ctx(IDENTIFIER)));
assertEquals(missing, failure);
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(priorAttributes, resource.getAttributes());
verify(cognito, never()).createResourceServer(any(), any(), any(), any());
verify(cognito, never()).updateResourceServer(any(), any(), any(), any());
verify(cognito, never()).deleteResourceServer(any(), any());
}
@Test
void aFailedReplacementCreateLeavesThePriorAddressAndMetadataUnchanged() {
StackResource resource = resource(IDENTIFIER, POOL);
HashMap<String, String> priorAttributes = new HashMap<>(resource.getAttributes());
AwsException failure = new AwsException("InternalErrorException", "replacement creation failed", 500);
when(cognito.createResourceServer(NEW_POOL, IDENTIFIER, "Replacement API", List.of())).thenThrow(failure);
assertEquals(failure, assertThrows(AwsException.class, () -> provisioner.provision(resource,
properties(NEW_POOL, IDENTIFIER, "Replacement API"), ctx(IDENTIFIER))));
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(priorAttributes, resource.getAttributes());
verify(cognito, never()).describeResourceServer(any(), any());
verify(cognito, never()).deleteResourceServer(any(), any());
}
@Test
void replacementRollbackRestoresTheMissingOldAddressAndDeletesOnlyTheNewServer() {
StackResource resource = resource(IDENTIFIER, POOL);
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
HashMap<String, String> priorAttributes = new HashMap<>(resource.getAttributes());
when(cognito.describeResourceServer(POOL, IDENTIFIER))
.thenThrow(new AwsException("ResourceNotFoundException", "old server was deleted", 400));
provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "Replacement API"), ctx(IDENTIFIER));
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(priorAttributes, resource.getAttributes());
verify(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
verify(cognito, never()).describeResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).createResourceServer(eq(POOL), any(), any(), any());
verify(cognito, never()).updateResourceServer(any(), any(), any(), any());
}
@Test
void conditionallyOmittedScopesCreateAnEmptyScopeList() throws Exception {
ObjectNode properties = properties(POOL, IDENTIFIER, "Example API");
properties.set("Scopes", mapper.readTree("""
{"Fn::If": ["IncludeScopes", [{"ScopeName": "read", "ScopeDescription": "Access"}],
{"Ref": "AWS::NoValue"}]}
"""));
provisioner.provision(resource(null, null), properties, intrinsicContext());
verify(cognito).createResourceServer(POOL, IDENTIFIER, "Example API", List.of());
}
@Test
void conditionallyOmittedScopeEntriesPreserveTheOtherScopes() throws Exception {
ObjectNode properties = properties(POOL, IDENTIFIER, "Example API");
properties.set("Scopes", mapper.readTree("""
[{"ScopeName": "read", "ScopeDescription": "Access"},
{"Fn::If": ["IncludeWrite", {"ScopeName": "write", "ScopeDescription": "Write access"},
{"Ref": "AWS::NoValue"}]}]
"""));
provisioner.provision(resource(null, null), properties, intrinsicContext());
ArgumentCaptor<List<ResourceServerScope>> scopes = ArgumentCaptor.forClass(List.class);
verify(cognito).createResourceServer(eq(POOL), eq(IDENTIFIER), eq("Example API"), scopes.capture());
assertEquals(1, scopes.getValue().size());
assertEquals("read", scopes.getValue().getFirst().getScopeName());
}
@Test
void anOmittedEntryInsideAConditionalScopeListCreatesNoScopes() throws Exception {
ObjectNode properties = properties(POOL, IDENTIFIER, "Example API");
properties.set("Scopes", mapper.readTree("""
{"Fn::If": ["UseOtherScopes", [],
[{"Fn::If": ["IncludeScopes", {"ScopeName": "read", "ScopeDescription": "Access"},
{"Ref": "AWS::NoValue"}]}]]}
"""));
provisioner.provision(resource(null, null), properties, intrinsicContext());
verify(cognito).createResourceServer(POOL, IDENTIFIER, "Example API", List.of());
}
@Test
void literalEmptyStringsAndInvalidScopeEntriesAreNotOmitted() throws Exception {
for (String scopes : List.of("\"\"", "[\"\"]", "[null]", "[false]", "[{}]",
"[{\"ScopeName\":\"\",\"ScopeDescription\":\"Access\"}]")) {
ObjectNode properties = properties(POOL, IDENTIFIER, "Example API");
properties.set("Scopes", mapper.readTree(scopes));
assertThrows(AwsException.class, () ->
provisioner.provision(resource(null, null), properties, intrinsicContext()), scopes);
}
verifyNoInteractions(cognito);
}
@Test
void aFailedLaterUpdateCannotRollBackUsingAnOlderSnapshot() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "Committed API"), ctx(IDENTIFIER));
assertTrue(provisioner.completeUpdate(resource).complete());
provisioner.clearUpdate(resource);
assertThrows(AwsException.class, () -> provisioner.provision(resource,
properties(POOL, IDENTIFIER, null), ctx(IDENTIFIER)));
assertFalse(resource.getAttributes().containsKey("__FlociResourceServerUpdate"));
assertFalse(provisioner.rollbackUpdate(resource));
verify(cognito, never()).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), any());
}
@Test
void unchangedIdentityUpdatesInPlaceAndRollbackRestoresNameAndScopes() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
verify(cognito).updateResourceServer(POOL, IDENTIFIER, "New API", List.of());
verify(cognito, never()).createResourceServer(any(), any(), any(), any());
assertFalse(provisioner.hasReplacementUpdate(resource));
assertTrue(provisioner.rollbackUpdate(resource));
ArgumentCaptor<List<ResourceServerScope>> restored = ArgumentCaptor.forClass(List.class);
verify(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), restored.capture());
assertEquals("read", restored.getValue().getFirst().getScopeName());
assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
}
@Test
void aPendingRollbackIsRetriedBeforeAnotherAttemptCanReplaceItsSnapshot() {
ResourceServer original = server(POOL, IDENTIFIER, "Old API");
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(original);
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
doThrow(new AwsException("InternalErrorException", "restore failed", 500))
.when(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), any());
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource));
String pending = resource.getAttributes().get("__FlociResourceServerUpdate");
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "New API"));
assertThrows(RuntimeException.class, () -> provisioner.provision(resource,
properties(POOL, IDENTIFIER, "Third API"), ctx(IDENTIFIER)));
assertEquals(pending, resource.getAttributes().get("__FlociResourceServerUpdate"));
verify(cognito, never()).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Third API"), any());
doReturn(original).when(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), any());
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(original);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "Third API"), ctx(IDENTIFIER));
assertTrue(provisioner.rollbackUpdate(resource));
assertFalse(provisioner.retainsFailedUpdateState(resource));
}
@Test
void cleanupOfASkippedResourceCannotClearItsPendingRollbackSnapshot() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
doThrow(new AwsException("InternalErrorException", "restore failed", 500))
.when(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), any());
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource));
resource.setStatus("UPDATE_FAILED");
String pending = resource.getAttributes().get("__FlociResourceServerUpdate");
assertThrows(IllegalStateException.class, () -> provisioner.completeUpdate(resource));
assertEquals(pending, resource.getAttributes().get("__FlociResourceServerUpdate"));
}
@Test
void aRecoveredReplacementUsesTheRestoredIdentityForTheNextAttempt() {
String replacementIdentifier = "https://replacement.example.com";
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(NEW_POOL, replacementIdentifier, "New API"), ctx(IDENTIFIER));
provisioner.provision(resource, properties(POOL, IDENTIFIER, "Third API"), ctx(replacementIdentifier));
verify(cognito).deleteResourceServer(NEW_POOL, replacementIdentifier);
verify(cognito).updateResourceServer(POOL, IDENTIFIER, "Third API", List.of());
verify(cognito, never()).createResourceServer(eq(POOL), eq(IDENTIFIER), any(), any());
assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(resource));
verify(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), any());
}
@Test
void deletionCleanupKeepsAPendingSnapshotWhenDeletingTheManagedServerFails() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
resource.setStatus("UPDATE_FAILED");
String pending = resource.getAttributes().get("__FlociResourceServerUpdate");
provisioner.completeDeleteCleanup(resource);
provisioner.clearDeleteCleanup(resource);
assertEquals(pending, resource.getAttributes().get("__FlociResourceServerUpdate"));
doThrow(new AwsException("InternalErrorException", "delete failed", 500))
.doNothing().when(cognito).deleteResourceServer(POOL, IDENTIFIER);
assertThrows(AwsException.class, () -> provisioner.delete(resource, "us-east-1"));
assertEquals(pending, resource.getAttributes().get("__FlociResourceServerUpdate"));
provisioner.delete(resource, "us-east-1");
assertFalse(provisioner.retainsFailedUpdateState(resource));
verify(cognito, times(2)).deleteResourceServer(POOL, IDENTIFIER);
}
@Test
void changingPoolReplacesEvenWhenRefIdentifierIsUnchanged() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
verify(cognito).createResourceServer(NEW_POOL, IDENTIFIER, "New API", List.of());
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(NEW_POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
assertTrue(provisioner.hasReplacementUpdate(resource));
assertEquals(IDENTIFIER, provisioner.updateCleanupPhysicalId(resource));
assertTrue(provisioner.completeUpdate(resource).complete());
verify(cognito).deleteResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(NEW_POOL, IDENTIFIER);
}
@Test
void retainingAReplacementDoesNotDeleteThePriorResource() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
resource.setUpdateReplacePolicy("Retain");
provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
assertNull(provisioner.updateCleanupPhysicalId(resource));
assertTrue(provisioner.completeUpdate(resource).complete());
verify(cognito, never()).deleteResourceServer(any(), any());
}
@Test
void replacementRollbackRestoresPriorIdentityAndDeletesOnlyTheNewServer() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
verify(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(POOL, IDENTIFIER);
}
@Test
void deleteUsesStoredPoolAndOnlyToleratesAlreadyMissingServers() {
StackResource resource = resource(IDENTIFIER, POOL);
doThrow(new AwsException("ResourceNotFoundException", "gone", 400))
.when(cognito).deleteResourceServer(POOL, IDENTIFIER);
provisioner.delete(resource, "us-east-1");
verify(cognito).deleteResourceServer(POOL, IDENTIFIER);
StackResource failing = resource(IDENTIFIER, POOL);
doThrow(new AwsException("InternalError", "storage unavailable", 500))
.when(cognito).deleteResourceServer(POOL, IDENTIFIER);
assertThrows(AwsException.class, () -> provisioner.delete(failing, "us-east-1"));
}
@Test
void committedReplacementAbandonsOldServerAfterThreeCleanupFailures() throws Exception {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
doThrow(new AwsException("InternalError", "storage unavailable", 500))
.when(cognito).deleteResourceServer(POOL, IDENTIFIER);
for (int attempt = 1; attempt <= 3; attempt++) {
UpdateCleanupResult result = provisioner.completeUpdate(resource);
assertFalse(result.complete());
assertEquals(attempt, result.attempts());
}
provisioner.clearUpdate(resource);
assertFalse(resource.getAttributes().containsKey(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
assertFalse(provisioner.retainsFailedUpdateState(resource),
"A committed replacement must not be rolled back by a later update");
when(cognito.describeResourceServer(NEW_POOL, IDENTIFIER))
.thenReturn(server(NEW_POOL, IDENTIFIER, "New API"));
provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "Third API"), ctx(IDENTIFIER));
JsonNode snapshot = mapper.readTree(resource.getAttributes().get("__FlociResourceServerUpdate"));
assertEquals(NEW_POOL, snapshot.path("poolId").asText());
assertEquals("New API", snapshot.path("name").asText());
assertEquals("read", snapshot.path("scopes").get(0).path("scopeName").asText());
assertFalse(snapshot.has("replacement"));
assertFalse(resource.getAttributes().containsKey(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
assertEquals(NEW_POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
assertEquals(IDENTIFIER, resource.getPhysicalId());
verify(cognito, times(3)).deleteResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(NEW_POOL, IDENTIFIER);
verify(cognito, never()).createResourceServer(eq(POOL), any(), any(), any());
verify(cognito).createResourceServer(NEW_POOL, IDENTIFIER, "New API", List.of());
verify(cognito).updateResourceServer(NEW_POOL, IDENTIFIER, "Third API", List.of());
assertTrue(provisioner.rollbackUpdate(resource));
ArgumentCaptor<List<ResourceServerScope>> restored = ArgumentCaptor.forClass(List.class);
verify(cognito).updateResourceServer(eq(NEW_POOL), eq(IDENTIFIER), eq("New API"), restored.capture());
assertEquals("read", restored.getValue().getFirst().getScopeName());
assertEquals(NEW_POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
verify(cognito, never()).deleteResourceServer(NEW_POOL, IDENTIFIER);
}
@Test
void exhaustedRollbackCleanupIsAbandonedBeforeRetryingCurrentDeletion() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
doThrow(new AwsException("InternalError", "storage unavailable", 500))
.when(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource));
for (int attempt = 1; attempt <= 3; attempt++) {
UpdateCleanupResult result = provisioner.completeDeleteCleanup(resource);
assertFalse(result.complete());
assertEquals(attempt, result.attempts());
}
provisioner.clearDeleteCleanup(resource);
provisioner.clearUpdate(resource);
assertFalse(resource.getAttributes().containsKey(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
doNothing().when(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
assertFalse(provisioner.completeDeleteCleanup(resource).applicable());
provisioner.delete(resource, "us-east-1");
verify(cognito, times(4)).deleteResourceServer(NEW_POOL, IDENTIFIER);
verify(cognito).deleteResourceServer(POOL, IDENTIFIER);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void exhaustedCleanupHooksDoNotRetryHistoricalDeletion(boolean deleting) {
StackResource resource = resource(IDENTIFIER, POOL);
oweCleanup(resource, NEW_POOL, IDENTIFIER, false, 3);
doThrow(new AwsException("InternalErrorException", "historical deletion must not be retried", 500))
.when(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
UpdateCleanupResult result = deleting ? provisioner.completeDeleteCleanup(resource)
: provisioner.completeUpdate(resource);
assertTrue(result.applicable());
assertFalse(result.complete());
assertEquals(3, result.attempts());
verifyNoInteractions(cognito);
if (deleting) {
provisioner.clearDeleteCleanup(resource);
} else {
provisioner.clearUpdate(resource);
}
assertFalse(resource.getAttributes().containsKey(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
}
@ParameterizedTest
@ValueSource(ints = {0, 2, 3})
void failedProvisionPreservesHistoricalCleanupWithoutSpendingItsBudget(int attempts) throws Exception {
StackResource previous = resource(IDENTIFIER, POOL);
oweCleanup(previous, NEW_POOL, IDENTIFIER, false, attempts);
StackResource attempted = resource(IDENTIFIER, POOL);
attempted.getAttributes().putAll(previous.getAttributes());
AwsException currentFailure = new AwsException("ResourceNotFoundException", "current server missing", 400);
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenThrow(currentFailure);
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(attempted,
properties(POOL, IDENTIFIER, "Retry API"), ctx(IDENTIFIER)));
ReplacementCleanup.mergeDisplaced(previous, attempted);
assertEquals(currentFailure, failure);
JsonNode carried = mapper.readTree(previous.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR))
.path("displaced").get(0);
assertEquals(attempts, carried.path("cleanupAttempts").asInt());
assertEquals(mapper.createArrayNode().add(NEW_POOL).add(IDENTIFIER),
mapper.readTree(carried.path("physicalId").asText()));
verify(cognito, never()).deleteResourceServer(any(), any());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void clearingDeleteCleanupPreservesPendingSnapshotAndUnspentBudget(boolean exhausted) throws Exception {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
String pending = resource.getAttributes().get("__FlociResourceServerUpdate");
oweCleanup(resource, NEW_POOL, IDENTIFIER, false, exhausted ? 3 : 2);
provisioner.clearDeleteCleanup(resource);
assertEquals(pending, resource.getAttributes().get("__FlociResourceServerUpdate"));
if (exhausted) {
assertFalse(resource.getAttributes().containsKey(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
} else {
JsonNode debt = mapper.readTree(resource.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR))
.path("displaced").get(0);
assertEquals(2, debt.path("cleanupAttempts").asInt());
}
doThrow(new AwsException("InternalErrorException", "current deletion failed", 500))
.doNothing().when(cognito).deleteResourceServer(POOL, IDENTIFIER);
assertThrows(AwsException.class, () -> provisioner.delete(resource, "us-east-1"));
assertEquals(pending, resource.getAttributes().get("__FlociResourceServerUpdate"));
provisioner.delete(resource, "us-east-1");
assertFalse(provisioner.retainsFailedUpdateState(resource));
verify(cognito, times(2)).deleteResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(NEW_POOL, IDENTIFIER);
}
@Test
void aPartiallyAppliedUpdateKeepsTheSnapshotForRollback() {
ResourceServer stored = server(POOL, IDENTIFIER, "Old API");
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(stored);
doAnswer(invocation -> {
stored.setName("New API");
throw new AwsException("InternalErrorException", "write failed", 500);
}).when(cognito).updateResourceServer(POOL, IDENTIFIER, "New API", List.of());
StackResource resource = resource(IDENTIFIER, POOL);
assertThrows(AwsException.class, () -> provisioner.provision(resource,
properties(POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER)));
assertTrue(provisioner.retainsFailedUpdateState(resource));
assertTrue(provisioner.rollbackUpdate(resource));
verify(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), any());
assertFalse(provisioner.retainsFailedUpdateState(resource));
}
@Test
void failedReplacementRollbackKeepsCleanupTrackingOnTheRestoredResource() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource attempted = resource(IDENTIFIER, POOL);
provisioner.provision(attempted, properties(NEW_POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
doThrow(new AwsException("InternalErrorException", "delete failed", 500))
.when(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(attempted));
StackResource restored = resource(IDENTIFIER, POOL);
ReplacementCleanup.mergeDisplaced(restored, attempted);
assertEquals(POOL, restored.getAttributes().get("__FlociResourceServerPoolId"));
assertTrue(restored.getAttributes().containsKey(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
assertFalse(provisioner.completeDeleteCleanup(restored).complete());
verify(cognito, never()).deleteResourceServer(POOL, IDENTIFIER);
}
@Test
void successfulProvisionDefersHistoricalCleanupUntilCommit() {
StackResource resource = resource(IDENTIFIER, POOL);
oweCleanup(resource, NEW_POOL, IDENTIFIER, false, 2);
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
provisioner.provision(resource, properties(POOL, IDENTIFIER, "Retry API"), ctx(IDENTIFIER));
verify(cognito, never()).deleteResourceServer(any(), any());
assertTrue(provisioner.hasReplacementUpdate(resource));
assertTrue(provisioner.completeUpdate(resource).complete());
verify(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(POOL, IDENTIFIER);
assertFalse(provisioner.hasReplacementUpdate(resource));
}
@Test
void rejectedPropertiesPreserveHistoricalCleanupWithoutCallingCognito() throws Exception {
StackResource previous = resource(IDENTIFIER, POOL);
oweCleanup(previous, NEW_POOL, IDENTIFIER, false, 2);
StackResource attempted = resource(IDENTIFIER, POOL);
attempted.getAttributes().putAll(previous.getAttributes());
assertThrows(AwsException.class, () -> provisioner.provision(attempted,
properties(POOL, IDENTIFIER, null), ctx(IDENTIFIER)));
ReplacementCleanup.mergeDisplaced(previous, attempted);
JsonNode carried = mapper.readTree(previous.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR))
.path("displaced").get(0);
assertEquals(2, carried.path("cleanupAttempts").asInt());
assertEquals(mapper.createArrayNode().add(NEW_POOL).add(IDENTIFIER),
mapper.readTree(carried.path("physicalId").asText()));
verifyNoInteractions(cognito);
}
@Test
void validatesSchemaBoundsBeforeCallingCognito() {
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
properties(POOL, "contains a space", "API"), ctx(null)));
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null),
properties(POOL, IDENTIFIER, "n".repeat(257)), ctx(null)));
ObjectNode invalidScope = properties(POOL, IDENTIFIER, "API");
invalidScope.putArray("Scopes").addObject().put("ScopeName", "read/all").put("ScopeDescription", "Access");
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null), invalidScope, ctx(null)));
ObjectNode tooMany = properties(POOL, IDENTIFIER, "API");
for (int index = 0; index < 101; index++) {
tooMany.withArray("Scopes").addObject().put("ScopeName", "s" + index).put("ScopeDescription", "Access");
}
assertThrows(AwsException.class, () -> provisioner.provision(resource(null, null), tooMany, ctx(null)));
verifyNoInteractions(cognito);
}
@Test
void anUpdateUsesTheManagedAddressAndSnapshotsTheOutOfBandConfiguration() throws Exception {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Out of band API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "Template API"), ctx(IDENTIFIER));
verify(cognito).updateResourceServer(POOL, IDENTIFIER, "Template API", List.of());
verify(cognito, never()).createResourceServer(any(), any(), any(), any());
JsonNode snapshot = mapper.readTree(resource.getAttributes().get("__FlociResourceServerUpdate"));
assertEquals(POOL, snapshot.path("poolId").asText());
assertEquals(IDENTIFIER, snapshot.path("identifier").asText());
assertEquals("Out of band API", snapshot.path("name").asText());
assertFalse(snapshot.has("incarnationId"));
}
@Test
void snapshotRestorationUsesTheManagedAddressAfterAnOutOfBandChange() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(POOL, IDENTIFIER, "New API"), ctx(IDENTIFIER));
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Out of band API"));
assertTrue(provisioner.rollbackUpdate(resource));
verify(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Old API"), any());
assertFalse(provisioner.retainsFailedUpdateState(resource));
}
@Test
void savedInPlaceSnapshotRestoresNameScopesAndAddress() {
StackResource resource = resource(IDENTIFIER, POOL);
ObjectNode snapshot = mapper.createObjectNode().put("poolId", POOL).put("identifier", IDENTIFIER)
.put("name", "Original API");
snapshot.putArray("scopes").addObject().put("scopeName", "read").put("scopeDescription", "Read access");
resource.getAttributes().put("__FlociResourceServerUpdate", snapshot.toString());
assertTrue(provisioner.rollbackUpdate(resource));
ArgumentCaptor<List<ResourceServerScope>> restored = ArgumentCaptor.forClass(List.class);
verify(cognito).updateResourceServer(eq(POOL), eq(IDENTIFIER), eq("Original API"), restored.capture());
assertEquals("read", restored.getValue().getFirst().getScopeName());
assertFalse(provisioner.retainsFailedUpdateState(resource));
provisioner.delete(resource, "us-east-1");
verify(cognito).deleteResourceServer(POOL, IDENTIFIER);
}
@Test
void consecutivePoolReplacementsKeepAnIdentifierContainingAddressDelimiters() {
String identifier = "https://api.example.com|resource";
when(cognito.describeResourceServer(POOL, identifier)).thenReturn(server(POOL, identifier, "First API"));
when(cognito.describeResourceServer(NEW_POOL, identifier)).thenReturn(server(NEW_POOL, identifier, "Second API"));
StackResource resource = resource(identifier, POOL);
provisioner.provision(resource, properties(NEW_POOL, identifier, "Second API"), ctx(identifier));
assertEquals(identifier, provisioner.updateCleanupPhysicalId(resource));
assertEquals(identifier, provisioner.completeUpdate(resource).previousPhysicalId());
provisioner.clearUpdate(resource);
provisioner.provision(resource, properties(THIRD_POOL, identifier, "Third API"), ctx(identifier));
assertEquals(identifier, provisioner.completeUpdate(resource).previousPhysicalId());
provisioner.clearUpdate(resource);
assertEquals(identifier, resource.getPhysicalId());
assertEquals(THIRD_POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
assertFalse(resource.getAttributes().containsKey("UserPoolId"));
verify(cognito).deleteResourceServer(POOL, identifier);
verify(cognito).deleteResourceServer(NEW_POOL, identifier);
verify(cognito, never()).deleteResourceServer(THIRD_POOL, identifier);
assertFalse(provisioner.hasReplacementUpdate(resource));
}
@Test
void rollbackFailureFlushesTheRestoredAddressBeforeRetryingAnotherReplacement() {
when(cognito.describeResourceServer(POOL, IDENTIFIER)).thenReturn(server(POOL, IDENTIFIER, "Old API"));
StackResource resource = resource(IDENTIFIER, POOL);
provisioner.provision(resource, properties(NEW_POOL, IDENTIFIER, "Second API"), ctx(IDENTIFIER));
doThrow(new AwsException("InternalErrorException", "rollback deletion failed", 500))
.doNothing().when(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource));
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
assertFalse(provisioner.retainsFailedUpdateState(resource));
assertTrue(provisioner.hasReplacementUpdate(resource));
provisioner.provision(resource, properties(THIRD_POOL, IDENTIFIER, "Third API"), ctx(IDENTIFIER));
assertTrue(provisioner.completeUpdate(resource).complete());
provisioner.clearUpdate(resource);
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(THIRD_POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
verify(cognito, times(2)).deleteResourceServer(NEW_POOL, IDENTIFIER);
verify(cognito).deleteResourceServer(POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(THIRD_POOL, IDENTIFIER);
verify(cognito, never()).createResourceServer(eq(POOL), any(), any(), any());
}
@ParameterizedTest
@ValueSource(ints = {2, 3})
void sharedCleanupPreservesItsRemainingAttemptBudget(int attempts) {
StackResource resource = resource(IDENTIFIER, POOL);
oweCleanup(resource, NEW_POOL, IDENTIFIER, false, attempts);
doThrow(new AwsException("InternalErrorException", "historical deletion failed", 500))
.when(cognito).deleteResourceServer(NEW_POOL, IDENTIFIER);
UpdateCleanupResult result = provisioner.completeDeleteCleanup(resource);
assertEquals(3, result.attempts());
assertEquals(IDENTIFIER, result.previousPhysicalId());
assertFalse(result.complete());
provisioner.clearDeleteCleanup(resource);
assertFalse(provisioner.completeDeleteCleanup(resource).applicable());
verify(cognito, times(attempts == 2 ? 1 : 0)).deleteResourceServer(NEW_POOL, IDENTIFIER);
verify(cognito, never()).deleteResourceServer(POOL, IDENTIFIER);
assertEquals(IDENTIFIER, resource.getPhysicalId());
assertEquals(POOL, resource.getAttributes().get("__FlociResourceServerPoolId"));
}
@Test
void sharedRetainableCleanupKeepsTheOldPoolWhileAnOrphanStillGetsDeleted() {
StackResource retained = resource(IDENTIFIER, POOL);
retained.setUpdateReplacePolicy("Retain");
oweCleanup(retained, NEW_POOL, IDENTIFIER, true, 2);
assertNull(provisioner.updateCleanupPhysicalId(retained));
assertTrue(provisioner.completeDeleteCleanup(retained).complete());
provisioner.clearDeleteCleanup(retained);
verify(cognito, never()).deleteResourceServer(NEW_POOL, IDENTIFIER);
StackResource orphan = resource(IDENTIFIER, POOL);
orphan.setUpdateReplacePolicy("Retain");
oweCleanup(orphan, THIRD_POOL, IDENTIFIER, false, 0);
assertEquals(IDENTIFIER, provisioner.updateCleanupPhysicalId(orphan));
assertTrue(provisioner.completeDeleteCleanup(orphan).complete());
verify(cognito).deleteResourceServer(THIRD_POOL, IDENTIFIER);
}
}
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.acm.model.CertificateStatus;
import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
import io.github.hectorvent.floci.services.cognito.model.ResourceServer;
import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;
import io.github.hectorvent.floci.services.cognito.model.RevokedTokenInfo;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
@@ -35,6 +36,9 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.ArgumentCaptor;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
@@ -44,13 +48,16 @@ import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
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.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
@@ -112,6 +119,123 @@ class CognitoServiceTest {
);
}
@Test
void concurrentResourceServerCreatesPreserveTheWinningRequest() throws Exception {
UserPool pool = service.createUserPool(Map.of("PoolName", "ConcurrentResourceServers"), "us-east-1");
String identifier = "https://resource-server.floci.test";
String targetKey = pool.getId() + "::" + identifier;
CountDownLatch firstEmptyLookup = new CountDownLatch(1);
CountDownLatch secondEmptyLookup = new CountDownLatch(1);
CountDownLatch releaseFirst = new CountDownLatch(1);
AtomicInteger emptyLookups = new AtomicInteger();
AtomicReference<Thread> firstWorker = new AtomicReference<>();
AtomicReference<Thread> secondWorker = new AtomicReference<>();
InMemoryStorage<String, ResourceServer> resourceServers = new InMemoryStorage<>() {
@Override
public Optional<ResourceServer> get(String key) {
Optional<ResourceServer> snapshot = super.get(key);
if (!targetKey.equals(key) || snapshot.isPresent()) {
return snapshot;
}
int lookup = emptyLookups.incrementAndGet();
if (lookup == 1) {
firstEmptyLookup.countDown();
try {
assertTrue(releaseFirst.await(10, TimeUnit.SECONDS), "first lookup was not released");
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new AssertionError("first lookup was interrupted", interrupted);
}
} else if (lookup == 2) {
secondEmptyLookup.countDown();
}
return snapshot;
}
};
CognitoService concurrentService = new CognitoService(poolStore, new InMemoryStorage<>(), resourceServers,
userStore, groupStore, revokedTokenStore, "http://localhost:4566", "cloudfront.net",
regionResolver, null, acmService);
ResourceServerScope firstScope = new ResourceServerScope();
firstScope.setScopeName("first-read");
firstScope.setScopeDescription("First request scope");
ResourceServerScope secondScope = new ResourceServerScope();
secondScope.setScopeName("second-read");
secondScope.setScopeDescription("Second request scope");
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<ResourceServer> first = executor.submit(() -> {
firstWorker.set(Thread.currentThread());
return concurrentService.createResourceServer(pool.getId(), identifier, "First", List.of(firstScope));
});
assertTrue(firstEmptyLookup.await(5, TimeUnit.SECONDS), "first create did not capture an empty lookup");
Future<ResourceServer> second = executor.submit(() -> {
secondWorker.set(Thread.currentThread());
return concurrentService.createResourceServer(pool.getId(), identifier, "Second", List.of(secondScope));
});
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
boolean overlappingCreatesObserved = false;
while (System.nanoTime() < deadline) {
if (secondEmptyLookup.getCount() == 0) {
overlappingCreatesObserved = true;
break;
}
Thread worker = secondWorker.get();
ThreadInfo info = worker == null ? null : threads.getThreadInfo(worker.threadId(), 32);
if (info != null && info.getThreadState() == Thread.State.BLOCKED
&& info.getLockOwnerId() == firstWorker.get().threadId()) {
for (StackTraceElement frame : info.getStackTrace()) {
if (CognitoService.class.getName().equals(frame.getClassName())
&& "createResourceServer".equals(frame.getMethodName())) {
overlappingCreatesObserved = true;
break;
}
}
if (overlappingCreatesObserved) {
break;
}
}
Thread.sleep(1L);
}
assertTrue(overlappingCreatesObserved, "second create neither captured empty nor blocked on the first create");
releaseFirst.countDown();
List<ResourceServer> created = new ArrayList<>();
int conflicts = 0;
for (Future<ResourceServer> result : List.of(first, second)) {
try {
created.add(result.get(5, TimeUnit.SECONDS));
} catch (ExecutionException failure) {
AwsException conflict = assertInstanceOf(AwsException.class, failure.getCause());
assertEquals("ResourceConflictException", conflict.getErrorCode());
assertEquals(400, conflict.getHttpStatus());
conflicts++;
}
}
assertEquals(1, created.size(), "Concurrent empty lookup snapshots: " + emptyLookups.get());
assertEquals(1, conflicts);
ResourceServer winner = created.getFirst();
assertEquals("First", winner.getName());
assertEquals("first-read", winner.getScopes().getFirst().getScopeName());
assertEquals("First request scope", winner.getScopes().getFirst().getScopeDescription());
ResourceServer stored = concurrentService.describeResourceServer(pool.getId(), identifier);
assertEquals(pool.getId(), stored.getUserPoolId());
assertEquals(identifier, stored.getIdentifier());
assertEquals(winner.getName(), stored.getName());
assertEquals(1, stored.getScopes().size());
assertEquals(winner.getScopes().getFirst().getScopeName(), stored.getScopes().getFirst().getScopeName());
assertEquals(winner.getScopes().getFirst().getScopeDescription(),
stored.getScopes().getFirst().getScopeDescription());
List<ResourceServer> listed = concurrentService.listResourceServers(pool.getId());
assertEquals(1, listed.size());
assertEquals(winner.getName(), listed.getFirst().getName());
assertEquals(winner.getScopes().getFirst().getScopeName(), listed.getFirst().getScopes().getFirst().getScopeName());
} finally {
releaseFirst.countDown();
executor.shutdownNow();
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS), "create workers did not terminate");
}
}
private UserPool createPoolAndUser() {
UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "TempPass1!");