Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): provision Cognito resource servers (#4832)
XuJianebae2ba0e090
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex a19956d461..88873bd2d4 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -164,6 +164,8 @@ import java.security.cert.X509Certificate;import java.time.Duration;import java.util.List;import java.util.UUID;+import java.util.function.BooleanSupplier;+import java.util.function.Supplier;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;@@ -206,6 +208,29 @@ public final class TestFixtures {return "aws".equalsIgnoreCase(System.getenv("FLOCI_TARGET"));}+ /**+ * Polls a compatibility condition while preserving each test's timeout and AWS/local cadence.+ * Terminal-state and service-exception handling stays in the condition supplied by the test.+ */+ public static void await(BooleanSupplier condition, String resourceName, String expected,+ long timeoutNanos, long pollMillis) throws InterruptedException {+ await(condition, resourceName, expected, timeoutNanos, pollMillis, () -> "");+ }++ /** Polls a condition and appends lazily produced diagnostics when the wait expires. */+ public static void await(BooleanSupplier condition, String resourceName, String expected,+ long timeoutNanos, long pollMillis, Supplier<String> timeoutDetails)+ throws InterruptedException {+ long deadline = System.nanoTime() + timeoutNanos;+ while (System.nanoTime() < deadline) {+ if (condition.getAsBoolean()) {+ return;+ }+ Thread.sleep(pollMillis);+ }+ throw new AssertionError(resourceName + " timed out waiting for " + expected + timeoutDetails.get());+ }+/** The region every fixture client signs for, for tests that build or compare region-scoped values. */public static Region region() {return REGION;diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoResourceServerTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoResourceServerTest.javanew file mode 100644index 0000000000..14b18eafbb--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoResourceServerTest.java@@ -0,0 +1,485 @@+package com.floci.test;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;+import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;+import software.amazon.awssdk.services.cloudformation.model.Output;+import software.amazon.awssdk.services.cloudformation.model.Parameter;+import software.amazon.awssdk.services.cloudformation.model.Stack;+import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;+import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceNotFoundException;+import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceServerScopeType;+import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceServerType;++import java.util.List;+import java.util.stream.Collectors;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.assertj.core.api.Assertions.tuple;++/**+ * Exercises resource servers through both CloudFormation and Cognito SDK clients. Pools live+ * outside the stack so replacement and rollback cleanup remain observable after stack deletion.+ */+@DisplayName("CloudFormation AWS::Cognito::UserPoolResourceServer")+class CloudFormationCognitoResourceServerTest {++ private static final long TIMEOUT_NANOS = 300_000_000_000L;++ private static final String TEMPLATE = """+ {+ "Parameters": {+ "Identifier": {"Type": "String"},+ "UserPoolId": {"Type": "String"},+ "Name": {"Type": "String"},+ "ScopeName": {"Type": "String"},+ "ScopeDescription": {"Type": "String"},+ "IncludeScopes": {"Type": "String", "Default": "true"},+ "IncludeWrite": {"Type": "String", "Default": "false"},+ "Fail": {"Type": "String", "Default": "false"}+ },+ "Conditions": {+ "IncludeScopes": {"Fn::Equals": [{"Ref": "IncludeScopes"}, "true"]},+ "IncludeWrite": {"Fn::Equals": [{"Ref": "IncludeWrite"}, "true"]},+ "Fail": {"Fn::Equals": [{"Ref": "Fail"}, "true"]}+ },+ "Resources": {+ "Server": {+ "Type": "AWS::Cognito::UserPoolResourceServer",+ "Properties": {+ "UserPoolId": {"Ref": "UserPoolId"},+ "Identifier": {"Ref": "Identifier"},+ "Name": {"Ref": "Name"},+ "Scopes": {"Fn::If": ["IncludeScopes", [+ {"ScopeName": {"Ref": "ScopeName"}, "ScopeDescription": {"Ref": "ScopeDescription"}},+ {"Fn::If": ["IncludeWrite",+ {"ScopeName": "write", "ScopeDescription": "Write access"},+ {"Ref": "AWS::NoValue"}]}+ ], {"Ref": "AWS::NoValue"}]}+ }+ },+ "Duplicate": {+ "Type": "AWS::Cognito::UserPoolResourceServer",+ "Condition": "Fail",+ "DependsOn": "Server",+ "Properties": {+ "UserPoolId": {"Ref": "UserPoolId"},+ "Identifier": {"Ref": "Server"},+ "Name": "Duplicate API"+ }+ }+ },+ "Outputs": {+ "ServerRef": {"Value": {"Ref": "Server"}}+ }+ }+ """;++ private static CloudFormationClient cfn;+ private static CognitoIdentityProviderClient cognito;++ private String stackName;+ private String stackId;+ private String p1;+ private String p2;++ @BeforeAll+ static void clients() {+ cfn = TestFixtures.cloudFormationClient();+ cognito = TestFixtures.cognitoClient();+ }++ @BeforeEach+ void setup() {+ stackName = TestFixtures.uniqueName("compat-cfn-crs");+ p1 = cognito.createUserPool(r -> r.poolName(stackName + "-p1")).userPool().id();+ p2 = cognito.createUserPool(r -> r.poolName(stackName + "-p2")).userPool().id();+ }++ @AfterEach+ void cleanup() throws InterruptedException {+ try {+ deleteStack();+ } finally {+ for (String pool : new String[] {p1, p2}) {+ if (pool == null) {+ continue;+ }+ try {+ cognito.deleteUserPool(r -> r.userPoolId(pool));+ } catch (ResourceNotFoundException expected) {+ // The pool never finished creating or was already removed.+ }+ }+ p1 = null;+ p2 = null;+ }+ }++ @AfterAll+ static void closeClients() {+ cfn.close();+ cognito.close();+ }++ @Test+ @DisplayName("Ref is Identifier, and Name and Scopes update in place before stack deletion")+ void nameAndScopesUpdateInPlaceAndStackDeletionRemovesTheServer() throws InterruptedException {+ String identifier = stackName + "-api";+ createStack(parameters(identifier, p1, "Original API", "read", "Read access", true, false, false));+ assertIdentity(identifier);+ assertServer(p1, identifier, "Original API", "read", "Read access");++ updateStack(parameters(identifier, p1, "Updated API", "browse", "Browse access", true, false, false),+ "UPDATE_COMPLETE");+ assertIdentity(identifier);+ assertServer(p1, identifier, "Updated API", "browse", "Browse access");+ assertThat(identifiers(p1)).containsExactly(identifier);+ assertThat(identifiers(p2)).isEmpty();++ deleteStack();+ assertServerNotFound(p1, identifier);+ assertThat(identifiers(p1)).isEmpty();+ }++ @Test+ @DisplayName("Changing only the Scopes condition omits, restores and clears the whole property")+ void changingOnlyTheConditionOmitsAndRestoresAllScopes() throws InterruptedException {+ String identifier = stackName + "-api";+ createStack(parameters(identifier, p1, "API", "read", "Read access", false, false, false));+ assertThat(server(p1, identifier).scopes()).isEmpty();++ updateStack(parameters(identifier, p1, "API", "read", "Read access", true, false, false), "UPDATE_COMPLETE");+ assertServer(p1, identifier, "API", "read", "Read access");+ updateStack(parameters(identifier, p1, "API", "read", "Read access", false, false, false), "UPDATE_COMPLETE");+ assertThat(server(p1, identifier).scopes()).isEmpty();+ assertIdentity(identifier);+ assertThat(identifiers(p1)).containsExactly(identifier);+ }++ @Test+ @DisplayName("AWS::NoValue omits one scope entry while preserving the other scope")+ void changingOnlyTheConditionOmitsAndRestoresOneScopeEntry() throws InterruptedException {+ String identifier = stackName + "-api";+ createStack(parameters(identifier, p1, "API", "read", "Read access", true, true, false));+ assertThat(server(p1, identifier).scopes())+ .extracting(ResourceServerScopeType::scopeName, ResourceServerScopeType::scopeDescription)+ .containsExactly(tuple("read", "Read access"), tuple("write", "Write access"));++ updateStack(parameters(identifier, p1, "API", "read", "Read access", true, false, false), "UPDATE_COMPLETE");+ assertServer(p1, identifier, "API", "read", "Read access");+ updateStack(parameters(identifier, p1, "API", "read", "Read access", true, true, false), "UPDATE_COMPLETE");+ assertThat(server(p1, identifier).scopes())+ .extracting(ResourceServerScopeType::scopeName, ResourceServerScopeType::scopeDescription)+ .containsExactly(tuple("read", "Read access"), tuple("write", "Write access"));+ assertIdentity(identifier);+ }++ @Test+ @DisplayName("Changing Identifier replaces the server and deletes the old identifier")+ void changingTheIdentifierReplacesTheServerAndDeletesTheOldOne() throws InterruptedException {+ String original = stackName + "-api";+ String replacement = stackName + "-new-api";+ createStack(parameters(original, p1, "API", "read", "Read access", true, false, false));++ updateStack(parameters(replacement, p1, "API", "read", "Read access", true, false, false), "UPDATE_COMPLETE");+ assertIdentity(replacement);+ assertServer(p1, replacement, "API", "read", "Read access");+ assertServerNotFound(p1, original);+ assertThat(identifiers(p1)).containsExactly(replacement);++ deleteStack();+ assertThat(identifiers(p1)).isEmpty();+ }++ @Test+ @DisplayName("Changing UserPoolId replaces the server even when Ref stays the same")+ void changingThePoolReplacesTheServerAndDeletesItFromTheOldPool() throws InterruptedException {+ String identifier = stackName + "-api";+ createStack(parameters(identifier, p1, "API", "read", "Read access", true, false, false));++ updateStack(parameters(identifier, p2, "API", "read", "Read access", true, false, false), "UPDATE_COMPLETE");+ assertIdentity(identifier);+ assertServer(p2, identifier, "API", "read", "Read access");+ assertServerNotFound(p1, identifier);+ assertThat(identifiers(p1)).isEmpty();+ assertThat(identifiers(p2)).containsExactly(identifier);++ deleteStack();+ assertThat(identifiers(p1)).isEmpty();+ assertThat(identifiers(p2)).isEmpty();+ }++ @Test+ @DisplayName("A failed dependent resource restores the prior Name and Scopes")+ void failedDependentResourceRestoresTheInPlaceConfiguration() throws InterruptedException {+ String identifier = stackName + "-api";+ createStack(parameters(identifier, p1, "Original API", "read", "Read access", true, false, false));++ updateStack(parameters(identifier, p1, "Attempted API", "browse", "Browse access", true, false, true),+ "UPDATE_ROLLBACK_COMPLETE");+ assertDependentFailure();+ assertIdentity(identifier);+ assertServer(p1, identifier, "Original API", "read", "Read access");+ assertThat(identifiers(p1)).containsExactly(identifier);+ assertThat(identifiers(p2)).isEmpty();+ assertStackDeletionClearsBothPools();+ }++ @Test+ @DisplayName("A failed dependent resource deletes a replacement identifier and restores the original")+ void failedDependentResourceRollsBackAnIdentifierReplacement() throws InterruptedException {+ String original = stackName + "-api";+ String replacement = stackName + "-new-api";+ createStack(parameters(original, p1, "Original API", "read", "Read access", true, false, false));++ updateStack(parameters(replacement, p1, "Attempted API", "browse", "Browse access", true, false, true),+ "UPDATE_ROLLBACK_COMPLETE");+ assertDependentFailure();+ assertIdentity(original);+ assertServer(p1, original, "Original API", "read", "Read access");+ assertServerNotFound(p1, replacement);+ assertThat(identifiers(p1)).containsExactly(original);+ assertThat(identifiers(p2)).isEmpty();+ assertStackDeletionClearsBothPools();+ }++ @Test+ @DisplayName("A failed dependent resource deletes the new pool's server and restores the prior pool")+ void failedDependentResourceRollsBackAPoolReplacement() throws InterruptedException {+ String identifier = stackName + "-api";+ createStack(parameters(identifier, p1, "Original API", "read", "Read access", true, false, false));++ updateStack(parameters(identifier, p2, "Attempted API", "browse", "Browse access", true, false, true),+ "UPDATE_ROLLBACK_COMPLETE");+ assertDependentFailure();+ assertIdentity(identifier);+ assertServer(p1, identifier, "Original API", "read", "Read access");+ assertServerNotFound(p2, identifier);+ assertThat(identifiers(p1)).containsExactly(identifier);+ assertThat(identifiers(p2)).isEmpty();+ assertStackDeletionClearsBothPools();+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ @DisplayName("Explicit and resolved null Scopes fail without clearing the existing server")+ void nullScopesUpdatesPreserveTheExistingConfiguration(boolean conditional) throws Exception {+ String identifier = stackName + "-api";+ List<Parameter> original = parameters(identifier, p1, "Original API", "read", "Read access", true, false, false);+ createStack(original);+ String invalidTemplate = nullScopesTemplate(conditional);++ cfn.updateStack(r -> r.stackName(stackName).templateBody(invalidTemplate)+ .parameters(parameters(identifier, p1, "Changed API", "write", "Write access", true, false, false)));+ awaitStatus("UPDATE_ROLLBACK_COMPLETE");++ assertThat(failedEvents()).contains("Scopes must be a list");+ assertIdentity(identifier);+ assertServer(p1, identifier, "Original API", "read", "Read access");+ updateStack(parameters(identifier, p1, "Recovered API", "write", "Write access", true, false, false),+ "UPDATE_COMPLETE");+ assertServer(p1, identifier, "Recovered API", "write", "Write access");+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ @DisplayName("A missing old server does not block an Identifier or UserPoolId replacement")+ void replacingAnExternallyDeletedServerCreatesTheNewAddress(boolean changePool) throws InterruptedException {+ String original = stackName + "-api";+ String targetIdentifier = changePool ? original : stackName + "-replacement";+ String targetPool = changePool ? p2 : p1;+ createStack(parameters(original, p1, "Original API", "read", "Read access", true, false, false));+ cognito.deleteResourceServer(r -> r.userPoolId(p1).identifier(original));++ updateStack(parameters(targetIdentifier, targetPool, "Replacement API", "write", "Write access",+ true, false, false), "UPDATE_COMPLETE");++ assertIdentity(targetIdentifier);+ assertServer(targetPool, targetIdentifier, "Replacement API", "write", "Write access");+ assertServerNotFound(p1, original);+ deleteStack();+ assertServerNotFound(targetPool, targetIdentifier);+ }++ @Test+ @DisplayName("A same-address update still fails when its backing server was deleted")+ void updatingAMissingServerAtTheSameAddressStillFails() throws InterruptedException {+ String identifier = stackName + "-api";+ createStack(parameters(identifier, p1, "Original API", "read", "Read access", true, false, false));+ cognito.deleteResourceServer(r -> r.userPoolId(p1).identifier(identifier));++ updateStack(parameters(identifier, p1, "Changed API", "write", "Write access", true, false, false),+ "UPDATE_ROLLBACK_COMPLETE");++ assertIdentity(identifier);+ assertServerNotFound(p1, identifier);+ }++ @Test+ @DisplayName("Rollback of a missing-old replacement restores its address and deletes only the new server")+ void failedDependentResourceRollsBackAReplacementWhoseOldServerWasDeleted() throws InterruptedException {+ String identifier = stackName + "-api";+ createStack(parameters(identifier, p1, "Original API", "read", "Read access", true, false, false));+ cognito.deleteResourceServer(r -> r.userPoolId(p1).identifier(identifier));++ updateStack(parameters(identifier, p2, "Replacement API", "write", "Write access", true, false, true),+ "UPDATE_ROLLBACK_COMPLETE");++ assertDependentFailure();+ assertIdentity(identifier);+ assertServerNotFound(p1, identifier);+ assertServerNotFound(p2, identifier);+ assertStackDeletionClearsBothPools();+ }++ private static String nullScopesTemplate(boolean conditional) throws JsonProcessingException {+ ObjectMapper mapper = new ObjectMapper();+ ObjectNode template = (ObjectNode) mapper.readTree(TEMPLATE);+ ObjectNode properties = (ObjectNode) template.path("Resources").path("Server").path("Properties");+ if (conditional) {+ properties.putObject("Scopes").putArray("Fn::If")+ .add("IncludeScopes").addNull().add(mapper.createArrayNode());+ } else {+ properties.putNull("Scopes");+ }+ return template.toString();+ }++ private static List<Parameter> parameters(String identifier, String userPoolId, String name, String scopeName,+ String scopeDescription, boolean includeScopes, boolean includeWrite,+ boolean fail) {+ return List.of(+ parameter("Identifier", identifier),+ parameter("UserPoolId", userPoolId),+ parameter("Name", name),+ parameter("ScopeName", scopeName),+ parameter("ScopeDescription", scopeDescription),+ parameter("IncludeScopes", String.valueOf(includeScopes)),+ parameter("IncludeWrite", String.valueOf(includeWrite)),+ parameter("Fail", String.valueOf(fail)));+ }++ private static Parameter parameter(String key, String value) {+ return Parameter.builder().parameterKey(key).parameterValue(value).build();+ }++ private void createStack(List<Parameter> parameters) throws InterruptedException {+ stackId = cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameters)).stackId();+ awaitStatus("CREATE_COMPLETE");+ }++ private void updateStack(List<Parameter> parameters, String expected) throws InterruptedException {+ cfn.updateStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameters));+ awaitStatus(expected);+ }++ private void assertIdentity(String identifier) {+ assertThat(cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0).outputs())+ .filteredOn(o -> "ServerRef".equals(o.outputKey())).extracting(Output::outputValue)+ .as("Ref is the bare Identifier").containsExactly(identifier);+ assertThat(cfn.describeStackResource(r -> r.stackName(stackId).logicalResourceId("Server"))+ .stackResourceDetail().physicalResourceId())+ .as("the physical id is the bare Identifier").isEqualTo(identifier);+ }++ private ResourceServerType server(String pool, String identifier) {+ return cognito.describeResourceServer(r -> r.userPoolId(pool).identifier(identifier)).resourceServer();+ }++ private void assertServer(String pool, String identifier, String name, String scopeName, String scopeDescription) {+ ResourceServerType server = server(pool, identifier);+ assertThat(server.userPoolId()).isEqualTo(pool);+ assertThat(server.identifier()).isEqualTo(identifier);+ assertThat(server.name()).isEqualTo(name);+ assertThat(server.scopes()).extracting(ResourceServerScopeType::scopeName, ResourceServerScopeType::scopeDescription)+ .containsExactly(tuple(scopeName, scopeDescription));+ }++ private void assertServerNotFound(String pool, String identifier) {+ assertThatThrownBy(() -> server(pool, identifier)).isInstanceOf(ResourceNotFoundException.class);+ }++ private List<String> identifiers(String pool) {+ return cognito.listResourceServersPaginator(r -> r.userPoolId(pool)).resourceServers().stream()+ .map(ResourceServerType::identifier).sorted().toList();+ }++ private void assertStackDeletionClearsBothPools() throws InterruptedException {+ deleteStack();+ assertThat(identifiers(p1)).isEmpty();+ assertThat(identifiers(p2)).isEmpty();+ }++ private void assertDependentFailure() {+ assertThat(cfn.describeStackEvents(r -> r.stackName(stackId)).stackEvents())+ .anySatisfy(event -> {+ assertThat(event.logicalResourceId()).isEqualTo("Duplicate");+ assertThat(event.resourceStatusAsString()).isIn("CREATE_FAILED", "UPDATE_FAILED");+ assertThat(event.resourceStatusReason()).contains("already exists");+ });+ }++ private void awaitStatus(String expected) throws InterruptedException {+ TestFixtures.await(() -> {+ Stack stack = cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0);+ String status = stack.stackStatusAsString();+ if (expected.equals(status)) {+ return true;+ }+ if (!status.endsWith("_IN_PROGRESS") && (status.contains("FAILED") || status.contains("ROLLBACK"))) {+ throw new AssertionError(stackName + " reached " + status + " instead of " + expected + ": "+ + stack.stackStatusReason() + failedEvents());+ }+ return false;+ }, stackName, expected, TIMEOUT_NANOS, TestFixtures.isRealAws() ? 2_000 : 100);+ }++ private String failedEvents() {+ return cfn.describeStackEvents(r -> r.stackName(stackId)).stackEvents().stream()+ .filter(event -> event.resourceStatusAsString().endsWith("_FAILED"))+ .map(event -> event.logicalResourceId() + " " + event.resourceStatusAsString() + ": "+ + event.resourceStatusReason())+ .collect(Collectors.joining("; ", " [", "]"));+ }++ private void deleteStack() throws InterruptedException {+ if (stackId == null) {+ return;+ }+ cfn.deleteStack(r -> r.stackName(stackId));+ TestFixtures.await(() -> {+ try {+ List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackId)).stacks();+ if (stacks.isEmpty()) {+ return true;+ }+ Stack stack = stacks.get(0);+ if ("DELETE_FAILED".equals(stack.stackStatusAsString())) {+ throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason());+ }+ return "DELETE_COMPLETE".equals(stack.stackStatusAsString());+ } catch (CloudFormationException e) {+ if ("ValidationError".equals(e.awsErrorDetails().errorCode())+ && e.getMessage().contains("does not exist")) {+ return true;+ }+ throw e;+ }+ }, stackName, "stack deletion", TIMEOUT_NANOS, TestFixtures.isRealAws() ? 2_000 : 100);+ stackId = null;+ }+++}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolGroupTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolGroupTest.javaindex a7fea3ffe4..ed4c8aadb4 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolGroupTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolGroupTest.java@@ -17,7 +17,6 @@ import software.amazon.awssdk.services.cognitoidentityprovider.model.GroupType;import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceNotFoundException;import java.util.List;-import java.util.function.BooleanSupplier;import java.util.stream.Collectors;import static org.assertj.core.api.Assertions.assertThat;@@ -377,7 +376,7 @@ class CloudFormationCognitoUserPoolGroupTest {}private void awaitStatus(String expected) throws InterruptedException {- await(() -> {+ TestFixtures.await(() -> {Stack stack = cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0);String status = stack.stackStatusAsString();if (expected.equals(status)) {@@ -388,7 +387,7 @@ class CloudFormationCognitoUserPoolGroupTest {+ stack.stackStatusReason() + failedEvents());}return false;- }, expected);+ }, stackName, expected, TIMEOUT_NANOS, TestFixtures.isRealAws() ? 2_000 : 100);}private List<StackEvent> groupEvents() {@@ -410,7 +409,7 @@ class CloudFormationCognitoUserPoolGroupTest {return;}cfn.deleteStack(r -> r.stackName(stackId));- await(() -> {+ TestFixtures.await(() -> {try {List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackId)).stacks();if (stacks.isEmpty()) {@@ -428,19 +427,9 @@ class CloudFormationCognitoUserPoolGroupTest {}throw e;}- }, "stack deletion");+ }, stackName, "stack deletion", TIMEOUT_NANOS, TestFixtures.isRealAws() ? 2_000 : 100);stackId = null;}- private void await(BooleanSupplier condition, String expected) throws InterruptedException {- long pollMillis = TestFixtures.isRealAws() ? 2_000 : 100;- long deadline = System.nanoTime() + TIMEOUT_NANOS;- while (System.nanoTime() < deadline) {- if (condition.getAsBoolean()) {- return;- }- Thread.sleep(pollMillis);- }- throw new AssertionError(stackName + " timed out waiting for " + expected);- }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserToGroupAttachmentTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserToGroupAttachmentTest.javaindex 4ecd11c26a..13f9a801b7 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserToGroupAttachmentTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserToGroupAttachmentTest.java@@ -15,7 +15,6 @@ import software.amazon.awssdk.services.cognitoidentityprovider.model.GroupType;import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;import java.util.List;-import java.util.function.BooleanSupplier;import static org.assertj.core.api.Assertions.assertThat;@@ -117,14 +116,14 @@ class CloudFormationCognitoUserToGroupAttachmentTest {}private void awaitStatus(String expected) throws InterruptedException {- await(() -> {+ TestFixtures.await(() -> {Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);String status = stack.stackStatusAsString();if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());}return expected.equals(status);- }, expected);+ }, stackName, expected, 60_000_000_000L, 100);}private void deleteStack() throws InterruptedException {@@ -132,7 +131,7 @@ class CloudFormationCognitoUserToGroupAttachmentTest {return;}cfn.deleteStack(r -> r.stackName(stackName));- await(() -> {+ TestFixtures.await(() -> {try {List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();if (stacks.isEmpty()) {@@ -150,18 +149,9 @@ class CloudFormationCognitoUserToGroupAttachmentTest {}throw e;}- }, "stack deletion");+ }, stackName, "stack deletion", 60_000_000_000L, 100);stackCreated = false;}- private void await(BooleanSupplier condition, String expected) throws InterruptedException {- long deadline = System.nanoTime() + 60_000_000_000L;- while (System.nanoTime() < deadline) {- if (condition.getAsBoolean()) {- return;- }- Thread.sleep(100);- }- throw new AssertionError(stackName + " timed out waiting for " + expected);- }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsArchiveTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsArchiveTest.javaindex b4f22156e2..9e833ac0fc 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsArchiveTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsArchiveTest.java@@ -19,7 +19,6 @@ import software.amazon.awssdk.services.eventbridge.model.ResourceNotFoundExceptiimport java.util.ArrayList;import java.util.List;-import java.util.function.BooleanSupplier;import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;@@ -297,14 +296,14 @@ class CloudFormationEventsArchiveTest {/** Waits for {@code expected}, failing as soon as the stack settles on any other status. */private void awaitStatus(String expected) throws InterruptedException {- await(() -> {+ TestFixtures.await(() -> {Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);String status = stack.stackStatusAsString();if (!expected.equals(status) && !status.endsWith("_IN_PROGRESS")) {throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());}return expected.equals(status);- }, expected);+ }, stackName, expected, 60_000_000_000L, 100);}private void deleteStack() throws InterruptedException {@@ -312,7 +311,7 @@ class CloudFormationEventsArchiveTest {return;}cfn.deleteStack(r -> r.stackName(stackName));- await(() -> {+ TestFixtures.await(() -> {try {List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();if (stacks.isEmpty()) {@@ -330,18 +329,9 @@ class CloudFormationEventsArchiveTest {}throw e;}- }, "stack deletion");+ }, stackName, "stack deletion", 60_000_000_000L, 100);stackCreated = false;}- private void await(BooleanSupplier condition, String expected) throws InterruptedException {- long deadline = System.nanoTime() + 60_000_000_000L;- while (System.nanoTime() < deadline) {- if (condition.getAsBoolean()) {- return;- }- Thread.sleep(100);- }- throw new AssertionError(stackName + " timed out waiting for " + expected);- }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationIotAuthorizerTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationIotAuthorizerTest.javaindex a75544f7ac..cb6884d006 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationIotAuthorizerTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationIotAuthorizerTest.java@@ -32,7 +32,6 @@ import java.util.List;import java.util.Map;import java.util.Set;import java.util.UUID;-import java.util.function.BooleanSupplier;import java.util.stream.Collectors;import static org.assertj.core.api.Assertions.assertThat;@@ -336,14 +335,14 @@ class CloudFormationIotAuthorizerTest {}private void awaitStatus(String expected) throws InterruptedException {- await(() -> {+ TestFixtures.await(() -> {Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);String status = stack.stackStatusAsString();if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());}return expected.equals(status);- }, expected);+ }, stackName, expected, TIMEOUT_NANOS, TestFixtures.isRealAws() ? 2_000 : 100);}private void deleteStack() throws InterruptedException {@@ -351,7 +350,7 @@ class CloudFormationIotAuthorizerTest {return;}cfn.deleteStack(r -> r.stackName(stackId));- await(() -> {+ TestFixtures.await(() -> {try {List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackId)).stacks();if (stacks.isEmpty()) {@@ -369,19 +368,9 @@ class CloudFormationIotAuthorizerTest {}throw e;}- }, "stack deletion");+ }, stackName, "stack deletion", TIMEOUT_NANOS, TestFixtures.isRealAws() ? 2_000 : 100);stackId = null;}- private void await(BooleanSupplier condition, String expected) throws InterruptedException {- long pollMillis = TestFixtures.isRealAws() ? 2_000 : 100;- long deadline = System.nanoTime() + TIMEOUT_NANOS;- while (System.nanoTime() < deadline) {- if (condition.getAsBoolean()) {- return;- }- Thread.sleep(pollMillis);- }- throw new AssertionError(stackName + " timed out waiting for " + expected);- }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLogStreamTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLogStreamTest.javaindex ce4fdd9dd0..bf22265927 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLogStreamTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLogStreamTest.java@@ -20,7 +20,6 @@ import software.amazon.awssdk.services.cloudwatchlogs.model.ResourceNotFoundExceimport java.time.Instant;import java.util.ArrayList;import java.util.List;-import java.util.function.BooleanSupplier;import static org.assertj.core.api.Assertions.assertThat;@@ -214,20 +213,20 @@ class CloudFormationLogStreamTest {private void assertWritable(String group, String stream, String message) throws InterruptedException {logs.putLogEvents(r -> r.logGroupName(group).logStreamName(stream).logEvents(InputLogEvent.builder().timestamp(Instant.now().toEpochMilli()).message(message).build()));- await(() -> logs.getLogEvents(r -> r.logGroupName(group).logStreamName(stream).startFromHead(true))+ TestFixtures.await(() -> logs.getLogEvents(r -> r.logGroupName(group).logStreamName(stream).startFromHead(true)).events().stream().map(OutputLogEvent::message).toList().equals(List.of(message)),- "the event written to " + group + "/" + stream);+ stackName, "the event written to " + group + "/" + stream, 60_000_000_000L, 100);}private void awaitStatus(String expected) throws InterruptedException {- await(() -> {+ TestFixtures.await(() -> {Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);String status = stack.stackStatusAsString();if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());}return expected.equals(status);- }, expected);+ }, stackName, expected, 60_000_000_000L, 100);}private void deleteStack() throws InterruptedException {@@ -235,7 +234,7 @@ class CloudFormationLogStreamTest {return;}cfn.deleteStack(r -> r.stackName(stackName));- await(() -> {+ TestFixtures.await(() -> {try {List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();if (stacks.isEmpty()) {@@ -253,18 +252,9 @@ class CloudFormationLogStreamTest {}throw e;}- }, "stack deletion");+ }, stackName, "stack deletion", 60_000_000_000L, 100);stackCreated = false;}- private void await(BooleanSupplier condition, String expected) throws InterruptedException {- long deadline = System.nanoTime() + 60_000_000_000L;- while (System.nanoTime() < deadline) {- if (condition.getAsBoolean()) {- return;- }- Thread.sleep(100);- }- throw new AssertionError(stackName + " timed out waiting for " + expected);- }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLogsMetricFilterTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLogsMetricFilterTest.javaindex 9e0b3e9550..d5b09bd3c4 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLogsMetricFilterTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLogsMetricFilterTest.java@@ -28,7 +28,6 @@ import java.util.Collections;import java.util.List;import java.util.Map;import java.util.Set;-import java.util.function.BooleanSupplier;import java.util.stream.Collectors;import static org.assertj.core.api.Assertions.assertThat;@@ -271,27 +270,18 @@ class CloudFormationLogsMetricFilterTest {}private void awaitStatus(String status) throws InterruptedException {- await(() -> status.equals(cfn.describeStacks(r -> r.stackName(stack)).stacks().get(0).stackStatusAsString())+ TestFixtures.await(() -> status.equals(cfn.describeStacks(r -> r.stackName(stack)).stacks().get(0).stackStatusAsString())&& newEvents().stream().anyMatch(e -> stack.equals(e.logicalResourceId())- && status.equals(e.resourceStatusAsString())), "new operation " + status);+ && status.equals(e.resourceStatusAsString())), stack, "new operation " + status, 60_000_000_000L, 100, () -> "; events: " + newEvents());}- private void await(BooleanSupplier condition, String expected) throws InterruptedException {- long deadline = System.nanoTime() + 60_000_000_000L;- while (System.nanoTime() < deadline) {- if (condition.getAsBoolean()) {- return;- }- Thread.sleep(100);- }- throw new AssertionError(stack + " timed out waiting for " + expected + "; events: " + newEvents());- }+private void assertSample(String message, double expected, String route) throws InterruptedException {Instant timestamp = Instant.now();logs.putLogEvents(r -> r.logGroupName(group).logStreamName("events").logEvents(InputLogEvent.builder().timestamp(timestamp.toEpochMilli()).message(message).build()));- await(() -> {+ TestFixtures.await(() -> {List<Datapoint> data = metrics.getMetricStatistics(r -> {r.namespace(stack).metricName("Count").period(60).startTime(timestamp.minusSeconds(60)).endTime(timestamp.plusSeconds(60)).statistics(Statistic.SUM, Statistic.SAMPLE_COUNT);@@ -302,13 +292,13 @@ class CloudFormationLogsMetricFilterTest {}).datapoints();return data.stream().mapToDouble(Datapoint::sum).sum() == expected&& data.stream().mapToDouble(Datapoint::sampleCount).sum() == 1;- }, "one published sample of " + expected);+ }, stack, "one published sample of " + expected, 60_000_000_000L, 100, () -> "; events: " + newEvents());}private void deleteStack() throws InterruptedException {try {cfn.deleteStack(r -> r.stackName(stack));- await(() -> {+ TestFixtures.await(() -> {try {return "DELETE_COMPLETE".equals(cfn.describeStacks(r -> r.stackName(stack)).stacks().get(0).stackStatusAsString());@@ -318,7 +308,7 @@ class CloudFormationLogsMetricFilterTest {}throw e;}- }, "stack deletion");+ }, stack, "stack deletion", 60_000_000_000L, 100, () -> "; events: " + newEvents());} catch (CloudFormationException e) {if (!"ValidationError".equals(e.awsErrorDetails().errorCode()) || !e.getMessage().contains("does not exist")) {throw e;diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackIdTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackIdTest.javaindex 965f0f2bd6..ccb288ee20 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackIdTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackIdTest.java@@ -17,7 +17,6 @@ import software.amazon.awssdk.services.cloudformation.model.UpdateStackResponse;import software.amazon.awssdk.services.ssm.SsmClient;import java.util.List;-import java.util.function.BooleanSupplier;import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;@@ -96,8 +95,8 @@ class CloudFormationStackIdTest {.templateBody(TEMPLATE).parameters(parameters("second")));assertThat(created.stackId()).isEqualTo(stackId);- await(() -> "CREATE_COMPLETE".equals(describeChangeSet(created.id(), stackId).statusAsString()),- "change set CREATE_COMPLETE");+ TestFixtures.await(() -> "CREATE_COMPLETE".equals(describeChangeSet(created.id(), stackId).statusAsString()),+ stackName, "change set CREATE_COMPLETE", TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L, TestFixtures.isRealAws() ? 5_000 : 100);DescribeChangeSetResponse described = describeChangeSet(created.id(), stackId);assertThat(described.stackName()).isEqualTo(stackName);assertThat(described.stackId()).isEqualTo(stackId);@@ -166,14 +165,14 @@ class CloudFormationStackIdTest {}private void awaitStatus(String expected) throws InterruptedException {- await(() -> {+ TestFixtures.await(() -> {Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);String status = stack.stackStatusAsString();if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());}return expected.equals(status);- }, expected);+ }, stackName, expected, TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L, TestFixtures.isRealAws() ? 5_000 : 100);}private void deleteStack() throws InterruptedException {@@ -181,7 +180,7 @@ class CloudFormationStackIdTest {return;}cfn.deleteStack(r -> r.stackName(stackName));- await(() -> {+ TestFixtures.await(() -> {try {List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();if (stacks.isEmpty()) {@@ -200,18 +199,9 @@ class CloudFormationStackIdTest {}throw e;}- }, "stack deletion");+ }, stackName, "stack deletion", TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L, TestFixtures.isRealAws() ? 5_000 : 100);stackCreated = false;}- private void await(BooleanSupplier condition, String expected) throws InterruptedException {- long deadline = System.nanoTime() + (TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L);- while (System.nanoTime() < deadline) {- if (condition.getAsBoolean()) {- return;- }- Thread.sleep(TestFixtures.isRealAws() ? 5_000 : 100);- }- throw new AssertionError(stackName + " timed out waiting for " + expected);- }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationWafV2WebAclAssociationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationWafV2WebAclAssociationTest.javaindex ef68e61b81..e4a53d9ab0 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationWafV2WebAclAssociationTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationWafV2WebAclAssociationTest.java@@ -14,7 +14,6 @@ import software.amazon.awssdk.services.wafv2.model.WebACL;import java.util.List;import java.util.Map;-import java.util.function.BooleanSupplier;import java.util.logging.Level;import java.util.logging.Logger;import java.util.stream.Collectors;@@ -144,19 +143,19 @@ class CloudFormationWafV2WebAclAssociationTest {}private static void awaitStatus(String expected) throws InterruptedException {- await(() -> {+ TestFixtures.await(() -> {Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);String status = stack.stackStatusAsString();if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());}return expected.equals(status);- }, expected);+ }, stackName, expected, 300_000_000_000L, 250);}private static void deleteStack() throws InterruptedException {cfn.deleteStack(r -> r.stackName(stackName));- await(() -> {+ TestFixtures.await(() -> {try {Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);if ("DELETE_FAILED".equals(stack.stackStatusAsString())) {@@ -169,17 +168,8 @@ class CloudFormationWafV2WebAclAssociationTest {}throw e;}- }, "stack deletion");+ }, stackName, "stack deletion", 300_000_000_000L, 250);}- private static void await(BooleanSupplier condition, String expected) throws InterruptedException {- long deadline = System.nanoTime() + 300_000_000_000L;- while (System.nanoTime() < deadline) {- if (condition.getAsBoolean()) {- return;- }- Thread.sleep(250);- }- throw new AssertionError(stackName + " timed out waiting for " + expected);- }+}diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex c97f362ffd..22e5712682 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -111,6 +111,27 @@ filter pattern) can fail after deletion and trigger restoration. The CFN schema256-character metric namespace, but Floci's Logs API validation currently accepts at most 255:passing model validation does not imply provider acceptance.+## Cognito user pool resource servers++`AWS::Cognito::UserPoolResourceServer` returns its `Identifier` for `Ref`. Changing `Identifier`+or `UserPoolId` replaces the server; changing `Name` or `Scopes` updates it in place. Optional+`Scopes` or individual scope entries can be omitted by `Fn::If` selecting `AWS::NoValue`.+The provisioner keeps the pool and identifier together in private replacement bookkeeping,+so changing only the pool still cleans up the displaced server without changing the `Ref` value.++Replacement rollback and historical cleanup use the shared bounded replacement lifecycle.+Provisioning leaves historical cleanup for a committed update or stack deletion. A failed provision+keeps that debt and its remaining retry budget.+Committed replacements honor `UpdateReplacePolicy: Retain`; failed rollback replacements remain+owed cleanup while their retry budget remains. Exhausted historical records are abandoned across+later updates and stack-delete retries. Historical cleanup is address-based and does not provide+an atomic ownership check against another stack or a direct Cognito API writer reusing the address.++Failed in-place restoration preserves the original name and scopes for a later update retry.+Deleting the current server keeps this snapshot if deletion fails. An update that skips a server+with pending restoration can remain in `UPDATE_COMPLETE_CLEANUP_IN_PROGRESS`, blocking another+update. `ContinueUpdateRollback` remains unsupported.+## Supported Resource TypesResource types provisioned during `CreateStack` / `UpdateStack` / `DeleteStack`. Each delegates to@@ -154,7 +175,7 @@ cross-resource references.| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` || CodeBuild | `Project` || Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |-| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolUser`, `UserPoolUserToGroupAttachment` |+| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` || ACM | `Certificate` || EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored) || EventBridge Scheduler | `ScheduleGroup` |diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisioner.javanew file mode 100644index 0000000000..0af5b6c954--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisioner.java@@ -0,0 +1,426 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.cognito.CognitoService;+import io.github.hectorvent.floci.services.cognito.model.ResourceServer;+import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.function.Function;++@ApplicationScoped+public class CognitoResourceServerCfnProvisioner implements CfnResourceProvisioner {++ private static final String TYPE = "AWS::Cognito::UserPoolResourceServer";+ private static final String POOL_ATTR = "__FlociResourceServerPoolId";+ private static final String UPDATE_ATTR = "__FlociResourceServerUpdate";+ private static final ObjectMapper MAPPER = new ObjectMapper();++ private final CognitoService cognitoService;++ @Inject+ public CognitoResourceServerCfnProvisioner(CognitoService cognitoService) {+ this.cognitoService = cognitoService;+ }++ @Override+ public Set<String> resourceTypes() {+ return Set.of(TYPE);+ }++ @Override+ public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {+ String poolId = required(ctx.resolveOptional(properties, "UserPoolId"), "UserPoolId");+ String identifier = required(ctx.resolveOptional(properties, "Identifier"), "Identifier");+ String name = required(ctx.resolveOptional(properties, "Name"), "Name");+ validateString(poolId, "UserPoolId", 55, "[\\w-]+_[0-9a-zA-Z]+");+ validateString(identifier, "Identifier", 256, "[\\x21\\x23-\\x5B\\x5D-\\x7E]+");+ validateString(name, "Name", 256, "[\\w\\s+=,.@-]+");+ List<ResourceServerScope> scopes = scopes(properties, ctx);++ if (ctx.isUpdate() && retainsFailedUpdateState(resource)) {+ try {+ rollbackUpdate(resource);+ resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);+ resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);+ } catch (RuntimeException failure) {+ resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, failure.getMessage());+ throw new IllegalStateException("Could not finish the previous resource server update rollback", failure);+ }+ }+ String priorPhysicalId = ctx.isUpdate() ? resource.getPhysicalId() : null;+ boolean priorIsStub = ctx.isUpdate()+ && CfnResourceDispatcher.isStub(priorPhysicalId, resource.getAttributes());+ Identity prior = ctx.isUpdate() && !priorIsStub ? identity(resource, priorPhysicalId) : null;+ boolean replacement = prior != null+ && (!prior.poolId().equals(poolId) || !prior.identifier().equals(identifier));+ Identity target = prior;+ if (prior == null || replacement) {+ cognitoService.createResourceServer(poolId, identifier, name, scopes);+ target = new Identity(poolId, identifier);+ } else {+ ResourceServer existing = cognitoService.describeResourceServer(prior.poolId(), prior.identifier());+ resource.getAttributes().put(UPDATE_ATTR, snapshot(prior, existing).toString());+ cognitoService.updateResourceServer(poolId, identifier, name, scopes);+ }+ Map<String, String> attributesBefore = new HashMap<>(resource.getAttributes());+ setIdentity(resource, target);+ if (priorIsStub) {+ resource.getAttributes().remove("Arn");+ }+ ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(),+ ctx.stackName(), priorIsStub ? priorPhysicalId : prior == null ? null : encode(prior),+ ctx.progress(), ctx.priorProperties());+ withProjection(resource, projected -> {+ ReplacementCleanup.record(projected, cleanupContext, attributesBefore);+ return null;+ });+ resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");+ }++ private static String required(String value, String property) {+ if (value == null || value.isBlank()) {+ throw new AwsException("ValidationError", TYPE + " requires " + property, 400);+ }+ return value;+ }++ private static List<ResourceServerScope> scopes(JsonNode properties, ProvisionContext ctx) {+ if (properties == null || !properties.has("Scopes")) {+ return List.of();+ }+ JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(properties.get("Scopes"));+ if (resolved != null && resolved.isMissingNode()) {+ return List.of();+ }+ if (resolved == null || !resolved.isArray()) {+ throw new AwsException("ValidationError", TYPE + " Scopes must be a list", 400);+ }+ if (resolved.size() > 100) {+ throw new AwsException("ValidationError", TYPE + " allows at most 100 Scopes", 400);+ }+ List<ResourceServerScope> scopes = new ArrayList<>();+ for (JsonNode node : resolved) {+ if (!node.isObject() || !node.path("ScopeName").isTextual()+ || !node.path("ScopeDescription").isTextual()+ || !validScopeName(node.path("ScopeName").asText())+ || !validScopeDescription(node.path("ScopeDescription").asText())) {+ throw new AwsException("ValidationError", TYPE + " scopes require ScopeName and ScopeDescription", 400);+ }+ ResourceServerScope scope = new ResourceServerScope();+ scope.setScopeName(node.path("ScopeName").asText());+ scope.setScopeDescription(node.path("ScopeDescription").asText());+ scopes.add(scope);+ }+ return scopes;+ }++ private static void validateString(String value, String property, int maximum, String pattern) {+ if (value.length() > maximum || !value.matches(pattern)) {+ throw new AwsException("ValidationError", TYPE + " has invalid " + property, 400);+ }+ }++ private static boolean validScopeName(String value) {+ return value.length() <= 256 && value.matches("[\\x21\\x23-\\x2E\\x30-\\x5B\\x5D-\\x7E]+");+ }++ private static boolean validScopeDescription(String value) {+ return !value.isEmpty() && value.length() <= 256;+ }++ private record Identity(String poolId, String identifier) {+ }++ private static Identity identity(StackResource resource, String identifier) {+ String poolId = resource.getAttributes().get(POOL_ATTR);+ if (poolId == null || poolId.isBlank() || identifier == null || identifier.isBlank()) {+ throw new IllegalStateException("Missing Cognito resource server identity for " + resource.getLogicalId());+ }+ return new Identity(poolId, identifier);+ }++ private static Identity identity(JsonNode node) {+ return new Identity(node.path("poolId").asText(), node.path("identifier").asText());+ }++ private static void setIdentity(StackResource resource, Identity identity) {+ resource.setPhysicalId(identity.identifier());+ resource.getAttributes().put(POOL_ATTR, identity.poolId());+ }++ private static ObjectNode address(Identity identity) {+ return MAPPER.createObjectNode().put("poolId", identity.poolId()).put("identifier", identity.identifier());+ }++ private static ObjectNode snapshot(Identity identity, ResourceServer server) {+ ObjectNode snapshot = address(identity);+ snapshot.put("name", server.getName());+ snapshot.set("scopes", MAPPER.valueToTree(server.getScopes()));+ return snapshot;+ }++ private static String encode(Identity identity) {+ return MAPPER.createArrayNode().add(identity.poolId()).add(identity.identifier()).toString();+ }++ private static Identity decode(String physicalId) {+ try {+ JsonNode address = MAPPER.readTree(physicalId);+ if (address != null && address.isArray() && address.size() == 2+ && address.get(0).isTextual() && !address.get(0).asText().isBlank()+ && address.get(1).isTextual() && !address.get(1).asText().isBlank()) {+ return new Identity(address.get(0).asText(), address.get(1).asText());+ }+ } catch (JsonProcessingException invalid) {+ throw new IllegalStateException("Invalid Cognito resource server cleanup address", invalid);+ }+ throw new IllegalStateException("Invalid Cognito resource server cleanup address");+ }++ /*+ * Ref is only Identifier, whereas a resource server's delete address also includes its pool.+ * Only this detached view gives ReplacementCleanup the full address; no encoded id is assigned+ * to the stack resource or passed to the template engine.+ */+ private static StackResource project(StackResource resource) {+ StackResource projected = new StackResource();+ projected.setLogicalId(resource.getLogicalId());+ projected.setResourceType(resource.getResourceType());+ projected.setStatus(resource.getStatus());+ projected.setDeletionPolicy(resource.getDeletionPolicy());+ projected.setUpdateReplacePolicy(resource.getUpdateReplacePolicy());+ projected.setAttributes(new HashMap<>(resource.getAttributes()));+ if (resource.getPhysicalId() != null) {+ projected.setPhysicalId(CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())+ ? resource.getPhysicalId() : encode(identity(resource, resource.getPhysicalId())));+ }+ validateCleanup(projected);+ return projected;+ }++ private static <T> T withProjection(StackResource resource, Function<StackResource, T> operation) {+ StackResource projected = project(resource);+ try {+ return operation.apply(projected);+ } finally {+ // Rollback restores the prior identity before deleting the replacement, even if that delete fails.+ boolean restoredStub = CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes());+ Identity restored = projected.getPhysicalId() == null || restoredStub+ ? null : decode(projected.getPhysicalId());+ resource.getAttributes().clear();+ resource.getAttributes().putAll(projected.getAttributes());+ if (restoredStub) {+ resource.setPhysicalId(projected.getPhysicalId());+ resource.getAttributes().remove(POOL_ATTR);+ } else if (restored != null) {+ setIdentity(resource, restored);+ }+ }+ }++ private static void requireIdentity(Identity identity) {+ if (identity.poolId().isBlank() || identity.identifier().isBlank()) {+ throw new IllegalStateException("Invalid Cognito resource server lifecycle identity");+ }+ }++ private static void validateCleanup(StackResource projected) {+ ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);+ if (cleanup == null) {+ return;+ }+ if (cleanup.has("displaced") && !cleanup.path("displaced").isArray()) {+ throw new IllegalStateException("Invalid Cognito resource server cleanup entries");+ }+ for (JsonNode entry : cleanup.path("displaced")) {+ if (!entry.isObject() || !entry.path("physicalId").isTextual()+ || entry.path("cleanupAttempts").asInt(0) < 0) {+ throw new IllegalStateException("Invalid Cognito resource server cleanup entry");+ }+ decode(entry.path("physicalId").asText());+ }+ if (cleanup.hasNonNull("priorPhysicalId")) {+ if (!cleanup.path("priorAttributes").isObject()) {+ throw new IllegalStateException("Invalid Cognito resource server rollback attributes");+ }+ Map<String, String> priorAttributes = new HashMap<>();+ cleanup.path("priorAttributes").fields()+ .forEachRemaining(entry -> priorAttributes.put(entry.getKey(), entry.getValue().asText()));+ String priorPhysicalId = cleanup.path("priorPhysicalId").asText();+ if (!CfnResourceDispatcher.isStub(priorPhysicalId, priorAttributes)) {+ decode(priorPhysicalId);+ }+ }+ }++ private void deleteAddress(String resourceType, String physicalId, String region) {+ delete(decode(physicalId));+ }++ private void delete(Identity identity) {+ CfnDeletes.safeDelete("Cognito resource server", identity.identifier(),+ () -> cognitoService.deleteResourceServer(identity.poolId(), identity.identifier()),+ "ResourceNotFoundException");+ }++ @Override+ public void delete(StackResource resource, String region) {+ withProjection(resource, projected -> {+ if (projected.getPhysicalId() != null+ && !CfnResourceDispatcher.isStub(projected.getPhysicalId(), projected.getAttributes())) {+ deleteAddress(projected.getResourceType(), projected.getPhysicalId(), region);+ }+ projected.getAttributes().remove(UPDATE_ATTR);+ projected.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);+ ReplacementCleanup.clear(projected);+ return null;+ });+ }++ @Override+ public boolean rollbackUpdate(StackResource resource) {+ return withProjection(resource, projected -> {+ if (ReplacementCleanup.rollback(projected, this::deleteAddress)) {+ return true;+ }+ ObjectNode snapshot = read(projected, UPDATE_ATTR);+ if (snapshot == null) {+ return false;+ }+ Identity prior = identity(snapshot);+ requireIdentity(prior);+ cognitoService.updateResourceServer(prior.poolId(), prior.identifier(), snapshot.path("name").asText(),+ scopes(snapshot.path("scopes")));+ projected.setPhysicalId(encode(prior));+ projected.getAttributes().remove(UPDATE_ATTR);+ return true;+ });+ }++ private static List<ResourceServerScope> scopes(JsonNode nodes) {+ List<ResourceServerScope> scopes = new ArrayList<>();+ for (JsonNode node : nodes) {+ ResourceServerScope scope = new ResourceServerScope();+ scope.setScopeName(node.path("scopeName").asText());+ scope.setScopeDescription(node.path("scopeDescription").asText(null));+ scopes.add(scope);+ }+ return scopes;+ }++ @Override+ public boolean hasReplacementUpdate(StackResource resource) {+ return withProjection(resource, ReplacementCleanup::hasReplacement);+ }++ private static boolean hasPendingRollback(StackResource projected) {+ ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);+ return projected.getAttributes().containsKey(UPDATE_ATTR)+ || (cleanup != null && cleanup.hasNonNull("priorPhysicalId"));+ }++ @Override+ public boolean retainsFailedUpdateState(StackResource resource) {+ return withProjection(resource, CognitoResourceServerCfnProvisioner::hasPendingRollback);+ }++ @Override+ public String updateCleanupPhysicalId(StackResource resource) {+ return withProjection(resource, projected -> {+ String physicalId = ReplacementCleanup.cleanupPhysicalId(projected);+ return physicalId == null ? null : decode(physicalId).identifier();+ });+ }++ private static UpdateCleanupResult publicResult(UpdateCleanupResult result) {+ String physicalId = result.previousPhysicalId();+ return new UpdateCleanupResult(result.applicable(), result.complete(),+ physicalId == null ? null : decode(physicalId).identifier(),+ result.attempts(), result.failureReason());+ }++ @Override+ public UpdateCleanupResult completeUpdate(StackResource resource) {+ return withProjection(resource, projected -> {+ if ("UPDATE_FAILED".equals(projected.getStatus()) && hasPendingRollback(projected)) {+ throw new IllegalStateException("Resource server rollback is still pending; its original configuration "+ + "cannot be discarded by another resource's update cleanup");+ }+ boolean updated = projected.getAttributes().remove(UPDATE_ATTR) != null;+ ObjectNode committed = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);+ if (committed != null) {+ // Committing the update spends its rollback identity, independently of delete retry debt.+ committed.remove("priorPhysicalId");+ committed.remove("priorAttributes");+ projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, committed.toString());+ }+ UpdateCleanupResult cleanup = ReplacementCleanup.complete(projected, this::deleteAddress);+ return !cleanup.applicable() && updated+ ? new UpdateCleanupResult(true, true, null, 0, null) : publicResult(cleanup);+ });+ }++ @Override+ public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {+ return withProjection(resource, projected -> publicResult(ReplacementCleanup.complete(projected,+ this::deleteAddress)));+ }++ @Override+ public void clearDeleteCleanup(StackResource resource) {+ withProjection(resource, projected -> {+ ObjectNode cleanup = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);+ JsonNode prior = cleanup == null ? null : cleanup.get("priorPhysicalId");+ JsonNode attributes = cleanup == null ? null : cleanup.get("priorAttributes");+ ReplacementCleanup.clear(projected);+ if (prior != null) {+ ObjectNode remaining = read(projected, CfnRollback.REPLACEMENT_CLEANUP_ATTR);+ if (remaining == null) {+ remaining = MAPPER.createObjectNode();+ remaining.putArray("displaced");+ }+ remaining.set("priorPhysicalId", prior);+ remaining.set("priorAttributes", attributes);+ projected.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, remaining.toString());+ }+ return null;+ });+ }++ @Override+ public void clearUpdate(StackResource resource) {+ withProjection(resource, projected -> {+ projected.getAttributes().remove(UPDATE_ATTR);+ ReplacementCleanup.clear(projected);+ return null;+ });+ }++ private static ObjectNode read(StackResource resource, String attribute) {+ String raw = resource.getAttributes().get(attribute);+ if (raw == null) {+ return null;+ }+ try {+ JsonNode node = MAPPER.readTree(raw);+ if (node instanceof ObjectNode object) {+ return object;+ }+ } catch (JsonProcessingException e) {+ throw new IllegalStateException("Invalid Cognito resource server lifecycle record", e);+ }+ throw new IllegalStateException("Invalid Cognito resource server lifecycle record");+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.javaindex 1ba4c78c77..1482ee78c5 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java@@ -152,6 +152,7 @@ public class CognitoService implements ResourceProvider {private final StorageBackend<String, UserPool> poolStore;private final StorageBackend<String, UserPoolClient> clientStore;private final StorageBackend<String, ResourceServer> resourceServerStore;+ private final Object resourceServerCreateLock = new Object();private final StorageBackend<String, UserPoolDomain> domainStore;private final StorageBackend<String, IdentityProvider> identityProviderStore;private final StorageBackend<String, CognitoUser> userStore;@@ -1502,17 +1503,19 @@ public class CognitoService implements ResourceProvider {}String key = resourceServerKey(userPoolId, identifier);- if (resourceServerStore.get(key).isPresent()) {- throw new AwsException("ResourceConflictException", "Resource server already exists", 400);- }+ synchronized (resourceServerCreateLock) {+ if (resourceServerStore.get(key).isPresent()) {+ throw new AwsException("ResourceConflictException", "Resource server already exists", 400);+ }- ResourceServer server = new ResourceServer();- server.setUserPoolId(userPoolId);- server.setIdentifier(identifier);- server.setName(name);- server.setScopes(normalizeScopes(scopes));- resourceServerStore.put(key, server);- return server;+ ResourceServer server = new ResourceServer();+ server.setUserPoolId(userPoolId);+ server.setIdentifier(identifier);+ server.setName(name);+ server.setScopes(normalizeScopes(scopes));+ resourceServerStore.put(key, server);+ return server;+ }}public ResourceServer describeResourceServer(String userPoolId, String identifier) {diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.jsonindex 99c1439c90..e212a16862 100644--- a/src/main/resources/cloudformation/create-only-properties.json+++ b/src/main/resources/cloudformation/create-only-properties.json@@ -205,6 +205,10 @@"UserPoolId","GroupName"],+ "AWS::Cognito::UserPoolResourceServer": [+ "Identifier",+ "UserPoolId"+ ],"AWS::Config::ConfigRule": ["ConfigRuleName"],diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.javaindex 1353ea3bce..ebc256147d 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java@@ -42,6 +42,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTraiimport 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));diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoResourceServerCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoResourceServerCfnIntegrationTest.javanew file mode 100644index 0000000000..2ee80e31e2--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoResourceServerCfnIntegrationTest.java@@ -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"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.javanew file mode 100644index 0000000000..db07f0d41a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoResourceServerCfnProvisionerTest.java@@ -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);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.javaindex fd9d113efa..ab4bf2bc23 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java@@ -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", "[email protected]"), "TempPass1!");diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsvindex deb6896a53..f7030ba587 100644--- a/src/test/resources/cloudformation/supported-resource-types.tsv+++ b/src/test/resources/cloudformation/supported-resource-types.tsv@@ -61,6 +61,7 @@ AWS::Cognito::UserPool CognitoCfnProvisionerAWS::Cognito::UserPoolClient CognitoCfnProvisionerAWS::Cognito::UserPoolDomain CognitoCfnProvisionerAWS::Cognito::UserPoolGroup CognitoUserPoolGroupCfnProvisioner+AWS::Cognito::UserPoolResourceServer CognitoResourceServerCfnProvisionerAWS::Cognito::UserPoolUser CognitoUserPoolUserCfnProvisionerAWS::Cognito::UserPoolUserToGroupAttachment CognitoUserPoolUserToGroupAttachmentCfnProvisionerAWS::Config::ConfigRule ConfigCfnProvisioner