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

* feat(cloudformation): provision Cognito resource servers

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

* fix(cloudformation): abandon exhausted Cognito replacement cleanup

* fix(cloudformation): verify Cognito resource server ownership

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

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

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

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

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

* fix(cloudformation): abandon exhausted Cognito cleanup

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

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

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

No files matched your search

@@ -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;
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -19,7 +19,6 @@ import software.amazon.awssdk.services.eventbridge.model.ResourceNotFoundExcepti
import 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);
}
}
@@ -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);
}
}
@@ -20,7 +20,6 @@ import software.amazon.awssdk.services.cloudwatchlogs.model.ResourceNotFoundExce
import 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);
}
}
@@ -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;
@@ -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);
}
}
@@ -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);
}
}