mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eventbridge): provision AWS::Events::Archive (#4818)
* fix(eventbridge): make UpdateArchive a partial update UpdateArchive reset the event pattern to null and the retention to 0 whenever a request omitted them. On AWS an omitted Description, EventPattern or RetentionDays keeps the stored value, an empty Description or EventPattern clears it, and RetentionDays 0 sets 0. * feat(eventbridge): provision AWS::Events::Archive CloudFormation stubbed AWS::Events::Archive with a fake ARN and created nothing. EventsArchiveCfnProvisioner now creates a real archive through EventBridgeService. Ref is the archive name and Fn::GetAtt Arn the archive ARN. ArchiveName is generated when omitted and kept across updates. Description, EventPattern and RetentionDays update in place, sending only the properties the template declares, and a failed stack update restores them from a snapshot. Changing SourceArn or ArchiveName, or dropping an explicit name, replaces the archive and deletes the displaced one once the update commits. A replacement that keeps an explicit name is refused with CloudFormation's custom-named resource error before any change. KmsKeyIdentifier is ignored. Closes #4815 * fix(eventbridge): reject an archive source that is not an existing bus of the account and region CreateArchive now checks EventSourceArn as AWS does, before the archive name: a bus in another account fails with AccessDeniedException, one in another region with ValidationException, and a bus that does not exist with ResourceNotFoundException. The AWS::Events::Archive provisioner goes through the same service call, so a stack can no longer reach CREATE_COMPLETE with an archive that could never capture an event. * test(eventbridge): roll back an in-place archive update when a later resource fails A stack update changes an archive's description and retention in place, then fails on a second archive whose source bus does not exist. The stack ends UPDATE_ROLLBACK_COMPLETE, DescribeArchive shows the original values and the second archive was never created. The golden case passes on AWS and is mirrored in the Floci integration test. * fix(cloudformation): refuse declaring a generated archive name explicitly Adding ArchiveName with the name CloudFormation generated for an unnamed archive asks AWS to replace the archive under the same custom name, which it refuses with the custom-named resource error and rolls the stack back. Floci took the in-place path and reached UPDATE_COMPLETE; the existing refusal now also fires when the previous name was generated. * fix(cloudformation): provision a real archive when updating a stack whose archive was stubbed A stack created before AWS::Events::Archive had a provisioner holds the dispatcher's stub, whose physical id names no archive. Its next update now creates the archive instead of failing to describe that id, and the stub id is left to the replacement cleanup. * fix(eventbridge): validate archive description, pattern and retention as CreateArchive and UpdateArchive do CreateArchive and UpdateArchive now reject a description over 512 characters, an event pattern over 4096 characters and a negative retention with the ValidationException AWS returns, all violations reported together. The check runs before the source, existence and duplicate checks, so it also fails the AWS::Events::Archive resource in a stack.
This commit is contained in:
1 parent
dc3e9cacec
commit
66f04cde25
13 files changed
+1816
-6
No files matched your search
+2
@@ -44,6 +44,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScali
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.BatchCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsArchiveCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
|
||||
@@ -390,6 +391,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (eventBridgeService != null) {
|
||||
discovered.add(new EventsCfnProvisioner(eventBridgeService));
|
||||
discovered.add(new EventsArchiveCfnProvisioner(eventBridgeService));
|
||||
}
|
||||
if (batchService != null) {
|
||||
discovered.add(new BatchCfnProvisioner(batchService));
|
||||
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.json.JsonPath;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Provisions an {@code AWS::Events::Archive} through a CloudFormation stack and reads it back
|
||||
* through the EventBridge API. {@code Ref} is the archive name and {@code Fn::GetAtt Arn} its ARN;
|
||||
* a description, pattern or retention change updates the archive in place, a property removed
|
||||
* from the template keeps its value, and a later resource failing rolls the change back; a source
|
||||
* change replaces the archive, and is refused for an explicitly named one, as is declaring a
|
||||
* generated name explicitly; an update of a stack whose archive was stubbed creates a real one;
|
||||
* a description EventBridge rejects fails the create with its validation message; and the stack
|
||||
* delete removes it. Custom source buses are created through the EventBridge API so the stacks
|
||||
* hold only archives.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationEventsArchiveIntegrationTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/cloudformation/aws4_request";
|
||||
private static final String EVENTS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/events/aws4_request";
|
||||
private static final String PATTERN = "{\"source\":[\"app.orders\"]}";
|
||||
private final List<String> stacks = new ArrayList<>();
|
||||
private final List<String> buses = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void configureContentTypes() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() throws Exception {
|
||||
for (String stack : List.copyOf(stacks)) {
|
||||
deleteStack(stack);
|
||||
}
|
||||
for (String bus : buses) {
|
||||
events("DeleteEventBus", Map.of("Name", bus)).then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReadsBackThroughDescribeArchive() throws Exception {
|
||||
String bus = createBus();
|
||||
String name = "orders-" + suffix();
|
||||
Map<String, Object> properties = archiveProperties(name, bus);
|
||||
properties.put("Description", "orders archive");
|
||||
properties.put("EventPattern", MAPPER.readTree(PATTERN));
|
||||
properties.put("RetentionDays", 7);
|
||||
|
||||
String body = awaitStatus(createStack(template(properties), "CREATE_COMPLETE"), "CREATE_COMPLETE");
|
||||
|
||||
assertEquals(name, output(body, "ArchiveRef"), "Ref is the archive name");
|
||||
JsonPath archive = describeArchive(name).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals(bus, archive.getString("EventSourceArn"));
|
||||
assertEquals(PATTERN, archive.getString("EventPattern"));
|
||||
assertEquals(7, archive.getInt("RetentionDays"));
|
||||
assertEquals("orders archive", archive.getString("Description"));
|
||||
assertEquals("ENABLED", archive.getString("State"));
|
||||
assertEquals(archive.getString("ArchiveArn"), output(body, "ArchiveArn"), "GetAtt Arn is the archive ARN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unnamedArchiveGetsAGeneratedNameAndZeroRetention() throws Exception {
|
||||
String stack = createStack(template(archiveProperties(null, createBus())), "CREATE_COMPLETE");
|
||||
String name = output(awaitStatus(stack, "CREATE_COMPLETE"), "ArchiveRef");
|
||||
|
||||
assertTrue(name.startsWith(stack + "-Archive-"), name);
|
||||
assertTrue(name.length() <= 48, name);
|
||||
JsonPath archive = describeArchive(name).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals(0, archive.getInt("RetentionDays"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inPlaceUpdateChangesRetentionAndKeepsARemovedDescription() throws Exception {
|
||||
String bus = createBus();
|
||||
String name = "orders-" + suffix();
|
||||
Map<String, Object> created = archiveProperties(name, bus);
|
||||
created.put("Description", "orders archive");
|
||||
created.put("EventPattern", MAPPER.readTree(PATTERN));
|
||||
created.put("RetentionDays", 7);
|
||||
String stack = createStack(template(created), "CREATE_COMPLETE");
|
||||
String arn = output(awaitStatus(stack, "CREATE_COMPLETE"), "ArchiveArn");
|
||||
|
||||
Map<String, Object> updated = archiveProperties(name, bus);
|
||||
updated.put("EventPattern", MAPPER.readTree(PATTERN));
|
||||
updated.put("RetentionDays", 30);
|
||||
updateStack(stack, template(updated));
|
||||
String body = awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
|
||||
assertEquals(name, output(body, "ArchiveRef"));
|
||||
assertEquals(arn, output(body, "ArchiveArn"));
|
||||
JsonPath archive = describeArchive(name).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals(30, archive.getInt("RetentionDays"));
|
||||
assertEquals("orders archive", archive.getString("Description"),
|
||||
"a property removed from the template keeps its value");
|
||||
assertEquals(PATTERN, archive.getString("EventPattern"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noValueDescriptionAndPatternKeepTheirStoredValues() throws Exception {
|
||||
String bus = createBus();
|
||||
String name = "orders-" + suffix();
|
||||
Map<String, Object> created = archiveProperties(name, bus);
|
||||
created.put("Description", "orders archive");
|
||||
created.put("EventPattern", MAPPER.readTree(PATTERN));
|
||||
String stack = createStack(template(created), "CREATE_COMPLETE");
|
||||
|
||||
Map<String, Object> updated = archiveProperties(name, bus);
|
||||
updated.put("Description", Map.of("Ref", "AWS::NoValue"));
|
||||
updated.put("EventPattern", Map.of("Ref", "AWS::NoValue"));
|
||||
updated.put("RetentionDays", 30);
|
||||
updateStack(stack, template(updated));
|
||||
awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
|
||||
JsonPath archive = describeArchive(name).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals(30, archive.getInt("RetentionDays"));
|
||||
assertEquals("orders archive", archive.getString("Description"));
|
||||
assertEquals(PATTERN, archive.getString("EventPattern"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void literalEmptyDescriptionClearsTheStoredDescription() throws Exception {
|
||||
String bus = createBus();
|
||||
String name = "orders-" + suffix();
|
||||
Map<String, Object> created = archiveProperties(name, bus);
|
||||
created.put("Description", "orders archive");
|
||||
String stack = createStack(template(created), "CREATE_COMPLETE");
|
||||
|
||||
Map<String, Object> updated = archiveProperties(name, bus);
|
||||
updated.put("Description", "");
|
||||
updateStack(stack, template(updated));
|
||||
awaitStatus(stack, "UPDATE_COMPLETE");
|
||||
|
||||
assertFalse(describeArchive(name).then().statusCode(200).extract().jsonPath()
|
||||
.getMap("$").containsKey("Description"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheSourceReplacesTheArchive() throws Exception {
|
||||
String first = createBus();
|
||||
String second = createBus();
|
||||
String stack = createStack(template(archiveProperties(null, first)), "CREATE_COMPLETE");
|
||||
String original = output(awaitStatus(stack, "CREATE_COMPLETE"), "ArchiveRef");
|
||||
|
||||
updateStack(stack, template(archiveProperties(null, second)));
|
||||
String replacement = output(awaitStatus(stack, "UPDATE_COMPLETE"), "ArchiveRef");
|
||||
|
||||
assertNotEquals(original, replacement);
|
||||
assertEquals(second, describeArchive(replacement).then().statusCode(200)
|
||||
.extract().jsonPath().getString("EventSourceArn"));
|
||||
assertArchiveGone(original);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacingAnExplicitlyNamedArchiveIsRefused() throws Exception {
|
||||
String first = createBus();
|
||||
String second = createBus();
|
||||
String name = "orders-" + suffix();
|
||||
Map<String, Object> created = archiveProperties(name, first);
|
||||
created.put("RetentionDays", 7);
|
||||
String stack = createStack(template(created), "CREATE_COMPLETE");
|
||||
|
||||
Map<String, Object> moved = archiveProperties(name, second);
|
||||
moved.put("RetentionDays", 30);
|
||||
updateStack(stack, template(moved));
|
||||
String body = awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertEquals(name, output(body, "ArchiveRef"));
|
||||
assertRefusedAsCustomNamedReplacement(stack, name);
|
||||
JsonPath archive = describeArchive(name).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals(first, archive.getString("EventSourceArn"));
|
||||
assertEquals(7, archive.getInt("RetentionDays"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void declaringTheGeneratedNameExplicitlyIsRefused() throws Exception {
|
||||
String bus = createBus();
|
||||
Map<String, Object> created = archiveProperties(null, bus);
|
||||
created.put("RetentionDays", 7);
|
||||
String stack = createStack(template(created), "CREATE_COMPLETE");
|
||||
String generated = output(awaitStatus(stack, "CREATE_COMPLETE"), "ArchiveRef");
|
||||
|
||||
Map<String, Object> named = archiveProperties(generated, bus);
|
||||
named.put("RetentionDays", 7);
|
||||
updateStack(stack, template(named));
|
||||
String body = awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
assertEquals(generated, output(body, "ArchiveRef"));
|
||||
assertRefusedAsCustomNamedReplacement(stack, generated);
|
||||
JsonPath archive = describeArchive(generated).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals(bus, archive.getString("EventSourceArn"));
|
||||
assertEquals(7, archive.getInt("RetentionDays"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedUpdateRestoresTheInPlaceChangeMadeBeforeALaterResourceFailed() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String broken = "broken-" + suffix();
|
||||
String stack = createStack(defaultBusTemplate(name, "orders archive", 7, null), "CREATE_COMPLETE");
|
||||
|
||||
updateStack(stack, defaultBusTemplate(name, "changed archive", 30, broken));
|
||||
awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
JsonPath archive = describeArchive(name).then().statusCode(200).extract().jsonPath();
|
||||
assertEquals("orders archive", archive.getString("Description"));
|
||||
assertEquals(7, archive.getInt("RetentionDays"));
|
||||
assertArchiveGone(broken);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateAfterStubUpgradeProvisionsTheRealArchive() throws Exception {
|
||||
// A stack created before AWS::Events::Archive had a provisioner holds the dispatcher's stub
|
||||
// for it, a <logicalId>-<8 hex> physical id naming no archive. Its next update must create
|
||||
// the archive instead of failing to describe that id.
|
||||
String stack = createStack(MAPPER.writeValueAsString(Map.of("Resources",
|
||||
Map.of("Archive", Map.of("Type", "AWS::Foo::Bar", "Properties", Map.of())))), "CREATE_COMPLETE");
|
||||
String stubId = XmlParser.extractFirst(cfn(stack, "DescribeStackResources", null).then().statusCode(200)
|
||||
.extract().asString(), "PhysicalResourceId", null);
|
||||
assertTrue(stubId != null && stubId.startsWith("Archive-"), stubId);
|
||||
|
||||
updateStack(stack, template(archiveProperties(null, busArnSub("default"))));
|
||||
String name = output(awaitStatus(stack, "UPDATE_COMPLETE"), "ArchiveRef");
|
||||
|
||||
assertNotEquals(stubId, name);
|
||||
assertTrue(name.startsWith(stack + "-Archive-"), name);
|
||||
String defaultBus = events("DescribeEventBus", Map.of("Name", "default")).then().statusCode(200)
|
||||
.extract().jsonPath().getString("Arn");
|
||||
assertEquals(defaultBus, describeArchive(name).then().statusCode(200)
|
||||
.extract().jsonPath().getString("EventSourceArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOverlongDescriptionFailsTheCreateWithTheEventBridgeValidationMessage() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
Map<String, Object> properties = archiveProperties(name, createBus());
|
||||
properties.put("Description", "d".repeat(513));
|
||||
|
||||
String stack = createStack(template(properties), "ROLLBACK_COMPLETE");
|
||||
|
||||
assertArchiveEvent(stack, "CREATE_FAILED", reason -> reason.contains("at 'description' failed to satisfy "
|
||||
+ "constraint: Member must have length less than or equal to 512"));
|
||||
assertArchiveGone(name);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStackRemovesTheArchive() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String stack = createStack(template(archiveProperties(name, createBus())), "CREATE_COMPLETE");
|
||||
describeArchive(name).then().statusCode(200);
|
||||
|
||||
deleteStack(stack);
|
||||
|
||||
assertArchiveGone(name);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStackToleratesAnArchiveDeletedOutOfBand() throws Exception {
|
||||
String name = "orders-" + suffix();
|
||||
String stack = createStack(template(archiveProperties(name, createBus())), "CREATE_COMPLETE");
|
||||
events("DeleteArchive", Map.of("ArchiveName", name)).then().statusCode(200);
|
||||
|
||||
deleteStack(stack);
|
||||
|
||||
assertArchiveGone(name);
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
private String createBus() throws Exception {
|
||||
String bus = "cfn-archive-bus-" + suffix();
|
||||
String arn = events("CreateEventBus", Map.of("Name", bus)).then().statusCode(200)
|
||||
.extract().jsonPath().getString("EventBusArn");
|
||||
buses.add(bus);
|
||||
return arn;
|
||||
}
|
||||
|
||||
private String createStack(String template, String status) {
|
||||
String stack = "cfn-archive-" + suffix();
|
||||
cfn(stack, "CreateStack", template).then().statusCode(200);
|
||||
stacks.add(stack);
|
||||
awaitStatus(stack, status);
|
||||
return stack;
|
||||
}
|
||||
|
||||
private static void updateStack(String stack, String template) {
|
||||
cfn(stack, "UpdateStack", template).then().statusCode(200);
|
||||
}
|
||||
|
||||
/** Waits for the stack to be gone, which a DELETE_FAILED stack never is. */
|
||||
private void deleteStack(String stack) {
|
||||
cfn(stack, "DeleteStack", null).then().statusCode(200);
|
||||
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> {
|
||||
Response response = cfn(stack, "DescribeStacks", null);
|
||||
assertEquals(400, response.statusCode(), response.asString());
|
||||
assertTrue(response.asString().contains("does not exist"), response.asString());
|
||||
});
|
||||
stacks.remove(stack);
|
||||
}
|
||||
|
||||
private static String awaitStatus(String stack, String status) {
|
||||
return await().atMost(Duration.ofSeconds(15)).until(
|
||||
() -> cfn(stack, "DescribeStacks", null).then().statusCode(200).extract().asString(),
|
||||
body -> status.equals(XmlParser.extractFirst(body, "StackStatus", null)));
|
||||
}
|
||||
|
||||
private static String output(String body, String key) {
|
||||
String value = XmlParser.extractPairs(body, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
assertFalse(value == null || value.isBlank(), body);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Response cfn(String stack, String action, String 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);
|
||||
}
|
||||
return request.post("/");
|
||||
}
|
||||
|
||||
private static Response events(String action, Map<String, ?> body) throws Exception {
|
||||
return given().contentType("application/x-amz-json-1.1").header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents." + action).body(MAPPER.writeValueAsString(body)).post("/");
|
||||
}
|
||||
|
||||
private static Response describeArchive(String name) throws Exception {
|
||||
return events("DescribeArchive", Map.of("ArchiveName", name));
|
||||
}
|
||||
|
||||
private static void assertArchiveGone(String name) throws Exception {
|
||||
assertEquals("ResourceNotFoundException", describeArchive(name).then().statusCode(400)
|
||||
.extract().jsonPath().getString("__type"));
|
||||
}
|
||||
|
||||
private static void assertRefusedAsCustomNamedReplacement(String stack, String name) {
|
||||
String expectedReason = "CloudFormation cannot update a stack when a custom-named resource requires "
|
||||
+ "replacing. Rename " + name + " and update the stack again.";
|
||||
assertArchiveEvent(stack, "UPDATE_FAILED", expectedReason::equals);
|
||||
}
|
||||
|
||||
private static void assertArchiveEvent(String stack, String status, Predicate<String> reason) {
|
||||
List<Map<String, String>> stackEvents = XmlParser.extractGroups(cfn(stack, "DescribeStackEvents", null)
|
||||
.then().statusCode(200).extract().asString(), "member");
|
||||
assertTrue(stackEvents.stream().anyMatch(event -> "Archive".equals(event.get("LogicalResourceId"))
|
||||
&& status.equals(event.get("ResourceStatus"))
|
||||
&& event.get("ResourceStatusReason") != null
|
||||
&& reason.test(event.get("ResourceStatusReason"))),
|
||||
"no " + status + " event with the expected reason in " + stackEvents);
|
||||
}
|
||||
|
||||
private static Map<String, Object> archiveProperties(String name, Object sourceArn) {
|
||||
Map<String, Object> properties = new LinkedHashMap<>();
|
||||
if (name != null) {
|
||||
properties.put("ArchiveName", name);
|
||||
}
|
||||
properties.put("SourceArn", sourceArn);
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static String template(Map<String, Object> archiveProperties) throws Exception {
|
||||
Map<String, Object> outputs = new LinkedHashMap<>();
|
||||
outputs.put("ArchiveRef", Map.of("Value", Map.of("Ref", "Archive")));
|
||||
outputs.put("ArchiveArn", Map.of("Value", Map.of("Fn::GetAtt", List.of("Archive", "Arn"))));
|
||||
return MAPPER.writeValueAsString(Map.of(
|
||||
"Resources", Map.of("Archive", Map.of("Type", "AWS::Events::Archive", "Properties", archiveProperties)),
|
||||
"Outputs", outputs));
|
||||
}
|
||||
|
||||
/**
|
||||
* An archive on the default bus and, when {@code brokenName} is given, a second one that depends
|
||||
* on it and names a bus that does not exist, so it fails after the first one changed.
|
||||
*/
|
||||
private static String defaultBusTemplate(String name, String description, int retention, String brokenName)
|
||||
throws Exception {
|
||||
Map<String, Object> archive = archiveProperties(name, busArnSub("default"));
|
||||
archive.put("Description", description);
|
||||
archive.put("RetentionDays", retention);
|
||||
Map<String, Object> resources = new LinkedHashMap<>();
|
||||
resources.put("Archive", Map.of("Type", "AWS::Events::Archive", "Properties", archive));
|
||||
if (brokenName != null) {
|
||||
resources.put("Broken", Map.of("Type", "AWS::Events::Archive", "DependsOn", "Archive",
|
||||
"Properties", archiveProperties(brokenName, busArnSub(brokenName + "-missing-bus"))));
|
||||
}
|
||||
return MAPPER.writeValueAsString(Map.of("Resources", resources));
|
||||
}
|
||||
|
||||
private static Map<String, String> busArnSub(String bus) {
|
||||
return Map.of("Fn::Sub", "arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/" + bus);
|
||||
}
|
||||
}
|
||||
+497
@@ -0,0 +1,497 @@
|
||||
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.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Archive;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
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.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@code AWS::Events::Archive}: the name is the physical id and {@code Ref}, {@code Arn} is the
|
||||
* archive ARN, the name and source are create-only, an in-place update sends only the properties
|
||||
* the template declares, and a changed source or name replaces the archive.
|
||||
*/
|
||||
class EventsArchiveCfnProvisionerTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String STACK = "my-stack";
|
||||
private static final String TYPE = "AWS::Events::Archive";
|
||||
private static final String BUS_ARN = "arn:aws:events:us-east-1:000000000000:event-bus/orders";
|
||||
private static final String OTHER_BUS_ARN = "arn:aws:events:us-east-1:000000000000:event-bus/billing";
|
||||
private static final String PATTERN = "{\"source\":[\"app.orders\"]}";
|
||||
|
||||
private EventBridgeService events;
|
||||
private CloudFormationTemplateEngine engine;
|
||||
private EventsArchiveCfnProvisioner provisioner;
|
||||
/** What the mocked service holds, so a describe answers what an earlier create stored. */
|
||||
private final Map<String, Archive> archives = new HashMap<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
events = mock(EventBridgeService.class);
|
||||
engine = mock(CloudFormationTemplateEngine.class);
|
||||
// Like the real engine, AWS::NoValue resolves to an empty string.
|
||||
when(engine.resolve(any())).thenAnswer(i -> {
|
||||
JsonNode node = i.getArgument(0);
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
return isNoValue(node) ? "" : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
|
||||
when(engine.resolveJsonAttribute(any())).thenAnswer(i -> {
|
||||
JsonNode node = i.getArgument(0);
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (isNoValue(node)) {
|
||||
return "";
|
||||
}
|
||||
return node.isTextual() ? node.asText() : node.toString();
|
||||
});
|
||||
when(events.createArchive(anyString(), anyString(), any(), any(), anyInt(), eq(REGION))).thenAnswer(i -> {
|
||||
Archive archive = archive(i.getArgument(0), i.getArgument(1), i.getArgument(2), i.getArgument(3),
|
||||
i.getArgument(4));
|
||||
archives.put(archive.getArchiveName(), archive);
|
||||
return archive;
|
||||
});
|
||||
when(events.describeArchive(anyString(), eq(REGION))).thenAnswer(i -> {
|
||||
Archive archive = archives.get(i.<String>getArgument(0));
|
||||
if (archive == null) {
|
||||
throw new AwsException("ResourceNotFoundException", "Archive not found: " + i.getArgument(0), 400);
|
||||
}
|
||||
return archive;
|
||||
});
|
||||
when(events.updateArchive(anyString(), any(), any(), any(), eq(REGION))).thenAnswer(i ->
|
||||
archives.get(i.<String>getArgument(0)));
|
||||
provisioner = new EventsArchiveCfnProvisioner(events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesOnlyTheArchiveType() {
|
||||
assertEquals(Set.of(TYPE), provisioner.resourceTypes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWithAnExplicitNameSetsRefAndArn() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN)
|
||||
.put("Description", "orders")
|
||||
.put("RetentionDays", 7)
|
||||
.set("EventPattern", pattern()));
|
||||
|
||||
verify(events).createArchive("orders-archive", BUS_ARN, "orders", PATTERN, 7, REGION);
|
||||
assertEquals("orders-archive", resource.getPhysicalId());
|
||||
assertEquals(arn("orders-archive"), resource.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWithoutRetentionDaysStoresZero() {
|
||||
create(props("orders-archive", BUS_ARN));
|
||||
|
||||
verify(events).createArchive("orders-archive", BUS_ARN, null, null, 0, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedNameIsGeneratedWithinTheArchiveNameLimit() {
|
||||
StackResource resource = resource();
|
||||
provisioner.provision(resource, props(null, BUS_ARN),
|
||||
new ProvisionContext(engine, REGION, ACCOUNT, "stack".repeat(20)));
|
||||
|
||||
String name = resource.getPhysicalId();
|
||||
assertTrue(name.length() <= 48, name);
|
||||
assertTrue(name.matches("[.\\-_A-Za-z0-9]+-[0-9a-f]{12}"), name);
|
||||
verify(events).createArchive(name, BUS_ARN, null, null, 0, REGION);
|
||||
assertEquals(arn(name), resource.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesOutsideTheSchemaAreRejectedBeforeAnyCall() {
|
||||
for (String name : List.of("bad:name", "a".repeat(49), "", " ")) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> create(props(name, BUS_ARN)), name);
|
||||
|
||||
assertEquals("ValidationError", error.getErrorCode(), name);
|
||||
assertTrue(error.getMessage().contains("1 to 48 characters"), error.getMessage());
|
||||
}
|
||||
verifyNoInteractions(events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameUsingEveryAllowedCharacterClassIsAccepted() {
|
||||
StackResource resource = create(props("a.b-c_D9", BUS_ARN));
|
||||
|
||||
assertEquals("a.b-c_D9", resource.getPhysicalId());
|
||||
verify(events).createArchive("a.b-c_D9", BUS_ARN, null, null, 0, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noValueNameIsGenerated() {
|
||||
ObjectNode properties = props(null, BUS_ARN);
|
||||
properties.set("ArchiveName", noValue());
|
||||
|
||||
StackResource resource = create(properties);
|
||||
|
||||
assertTrue(resource.getPhysicalId().startsWith(STACK + "-Archive-"), resource.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noValueDescriptionAndPatternAreAbsentOnCreate() {
|
||||
ObjectNode properties = props("orders-archive", BUS_ARN);
|
||||
properties.set("Description", noValue());
|
||||
properties.set("EventPattern", noValue());
|
||||
|
||||
create(properties);
|
||||
|
||||
verify(events).createArchive("orders-archive", BUS_ARN, null, null, 0, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noValueDescriptionAndPatternAreNotSentOnUpdate() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN)
|
||||
.put("Description", "orders")
|
||||
.set("EventPattern", pattern()));
|
||||
clearInvocations(events);
|
||||
ObjectNode properties = props("orders-archive", BUS_ARN).put("RetentionDays", 30);
|
||||
properties.set("Description", noValue());
|
||||
properties.set("EventPattern", noValue());
|
||||
|
||||
update(resource, properties);
|
||||
|
||||
verify(events).updateArchive("orders-archive", null, null, 30, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void literalEmptyNameOnUpdateIsRefusedWithoutAnyMutation() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
clearInvocations(events);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> update(resource, props("", BUS_ARN)));
|
||||
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
verify(events, never()).createArchive(anyString(), anyString(), any(), any(), anyInt(), anyString());
|
||||
verify(events, never()).updateArchive(anyString(), any(), any(), any(), anyString());
|
||||
verify(events, never()).deleteArchive(anyString(), anyString());
|
||||
assertEquals("orders-archive", resource.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void literalEmptyDescriptionIsSentOnUpdateToClearIt() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN).put("Description", "orders"));
|
||||
clearInvocations(events);
|
||||
|
||||
update(resource, props("orders-archive", BUS_ARN).put("Description", ""));
|
||||
|
||||
verify(events).updateArchive("orders-archive", "", null, null, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingSourceArnIsRejectedBeforeAnyCall() {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> create(props("orders-archive", null)));
|
||||
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
verifyNoInteractions(events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inPlaceUpdateSendsOnlyThePropertiesTheTemplateDeclares() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN)
|
||||
.put("Description", "orders")
|
||||
.put("RetentionDays", 7)
|
||||
.set("EventPattern", pattern()));
|
||||
clearInvocations(events);
|
||||
|
||||
update(resource, props("orders-archive", BUS_ARN).put("RetentionDays", 30));
|
||||
|
||||
verify(events).updateArchive("orders-archive", null, null, 30, REGION);
|
||||
verify(events, never()).createArchive(anyString(), anyString(), any(), any(), anyInt(), anyString());
|
||||
assertEquals("orders-archive", resource.getPhysicalId());
|
||||
assertEquals(arn("orders-archive"), resource.getAttributes().get("Arn"));
|
||||
assertFalse(provisioner.hasReplacementUpdate(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inPlaceUpdateKeepsAGeneratedName() {
|
||||
StackResource resource = create(props(null, BUS_ARN));
|
||||
String generated = resource.getPhysicalId();
|
||||
clearInvocations(events);
|
||||
|
||||
update(resource, props(null, BUS_ARN).put("Description", "orders"));
|
||||
|
||||
assertEquals(generated, resource.getPhysicalId());
|
||||
verify(events).updateArchive(generated, "orders", null, null, REGION);
|
||||
verify(events, never()).createArchive(anyString(), anyString(), any(), any(), anyInt(), anyString());
|
||||
assertFalse(provisioner.hasReplacementUpdate(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackUpdateRestoresTheSnapshotAndClearsWhatWasUnset() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN)
|
||||
.put("Description", "orders")
|
||||
.put("RetentionDays", 5));
|
||||
update(resource, props("orders-archive", BUS_ARN)
|
||||
.put("Description", "changed")
|
||||
.set("EventPattern", pattern()));
|
||||
assertTrue(resource.getAttributes().containsKey(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR));
|
||||
clearInvocations(events);
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
verify(events).updateArchive("orders-archive", "orders", "", 5, REGION);
|
||||
assertFalse(resource.getAttributes().containsKey(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackUpdateWithoutASnapshotChangesNothing() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
clearInvocations(events);
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
verifyNoInteractions(events);
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearUpdateDropsTheSnapshot() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
update(resource, props("orders-archive", BUS_ARN).put("RetentionDays", 3));
|
||||
|
||||
provisioner.clearUpdate(resource);
|
||||
|
||||
assertFalse(resource.getAttributes().containsKey(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStaleSnapshotIsDroppedWhenTheNextProvisionStarts() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
update(resource, props("orders-archive", BUS_ARN).put("RetentionDays", 3));
|
||||
commit(resource);
|
||||
resource.getAttributes().put(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR, "{\"stale\":true}");
|
||||
|
||||
update(resource, props("renamed-archive", BUS_ARN));
|
||||
|
||||
assertFalse(resource.getAttributes().containsKey(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheSourceOfAGeneratedNameReplacesTheArchive() {
|
||||
StackResource resource = create(props(null, BUS_ARN));
|
||||
String original = resource.getPhysicalId();
|
||||
clearInvocations(events);
|
||||
|
||||
update(resource, props(null, OTHER_BUS_ARN));
|
||||
|
||||
String replacement = resource.getPhysicalId();
|
||||
assertNotEquals(original, replacement);
|
||||
verify(events).createArchive(replacement, OTHER_BUS_ARN, null, null, 0, REGION);
|
||||
verify(events, never()).updateArchive(anyString(), any(), any(), any(), anyString());
|
||||
verify(events, never()).deleteArchive(anyString(), anyString());
|
||||
assertEquals(arn(replacement), resource.getAttributes().get("Arn"));
|
||||
assertTrue(provisioner.hasReplacementUpdate(resource));
|
||||
assertEquals(original, provisioner.updateCleanupPhysicalId(resource));
|
||||
|
||||
commit(resource);
|
||||
verify(events).deleteArchive(original, REGION);
|
||||
verify(events, never()).deleteArchive(replacement, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingTheSourceOfAnExplicitNameIsRefusedBeforeAnyMutation() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
clearInvocations(events);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> update(resource, props("orders-archive", OTHER_BUS_ARN)));
|
||||
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
|
||||
+ "Rename orders-archive and update the stack again.", error.getMessage());
|
||||
verify(events, never()).createArchive(anyString(), anyString(), any(), any(), anyInt(), anyString());
|
||||
verify(events, never()).updateArchive(anyString(), any(), any(), any(), anyString());
|
||||
verify(events, never()).deleteArchive(anyString(), anyString());
|
||||
assertEquals("orders-archive", resource.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppingTheExplicitNameReplacesTheArchive() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
clearInvocations(events);
|
||||
|
||||
update(resource, props(null, BUS_ARN));
|
||||
|
||||
String generated = resource.getPhysicalId();
|
||||
assertTrue(generated.startsWith(STACK + "-Archive-"), generated);
|
||||
verify(events).createArchive(generated, BUS_ARN, null, null, 0, REGION);
|
||||
assertEquals("orders-archive", provisioner.updateCleanupPhysicalId(resource));
|
||||
|
||||
commit(resource);
|
||||
verify(events).deleteArchive("orders-archive", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void renamingTheArchiveReplacesIt() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
clearInvocations(events);
|
||||
|
||||
update(resource, props("orders-archive-v2", OTHER_BUS_ARN));
|
||||
|
||||
assertEquals("orders-archive-v2", resource.getPhysicalId());
|
||||
verify(events).createArchive("orders-archive-v2", OTHER_BUS_ARN, null, null, 0, REGION);
|
||||
assertEquals("orders-archive", provisioner.updateCleanupPhysicalId(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedStackUpdateDeletesTheReplacementAndRestoresThePriorArchive() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
update(resource, props("orders-archive-v2", BUS_ARN));
|
||||
clearInvocations(events);
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
assertEquals("orders-archive", resource.getPhysicalId());
|
||||
assertEquals(arn("orders-archive"), resource.getAttributes().get("Arn"));
|
||||
verify(events).deleteArchive("orders-archive-v2", REGION);
|
||||
verify(events, never()).deleteArchive("orders-archive", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatingAnArchiveThatIsGoneFails() {
|
||||
StackResource resource = create(props("orders-archive", BUS_ARN));
|
||||
archives.clear();
|
||||
clearInvocations(events);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> update(resource, props("orders-archive", BUS_ARN)));
|
||||
|
||||
assertEquals("ResourceNotFoundException", error.getErrorCode());
|
||||
verify(events, never()).createArchive(anyString(), anyString(), any(), any(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesAnArchiveThatIsAlreadyGone() {
|
||||
doThrow(new AwsException("ResourceNotFoundException", "gone", 400))
|
||||
.when(events).deleteArchive("orders-archive", REGION);
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(TYPE, "orders-archive", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePropagatesOtherFailures() {
|
||||
AwsException unavailable = new AwsException("InternalException", "retry", 500);
|
||||
doThrow(unavailable).when(events).deleteArchive("orders-archive", REGION);
|
||||
|
||||
assertSame(unavailable, assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(TYPE, "orders-archive", REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSkipsABlankPhysicalId() {
|
||||
provisioner.delete(TYPE, " ", REGION);
|
||||
provisioner.delete(TYPE, null, REGION);
|
||||
|
||||
verifyNoInteractions(events);
|
||||
}
|
||||
|
||||
private StackResource create(ObjectNode properties) {
|
||||
StackResource resource = resource();
|
||||
provisioner.provision(resource, properties, context(null));
|
||||
return resource;
|
||||
}
|
||||
|
||||
private void update(StackResource resource, ObjectNode properties) {
|
||||
provisioner.provision(resource, properties, context(resource.getPhysicalId()));
|
||||
}
|
||||
|
||||
private void commit(StackResource resource) {
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
provisioner.clearUpdate(resource);
|
||||
}
|
||||
|
||||
private ProvisionContext context(String prior) {
|
||||
return new ProvisionContext(engine, REGION, ACCOUNT, STACK, prior);
|
||||
}
|
||||
|
||||
private static StackResource resource() {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("Archive");
|
||||
resource.setResourceType(TYPE);
|
||||
resource.setAttributes(new HashMap<>());
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static ObjectNode props(String name, String sourceArn) {
|
||||
ObjectNode properties = MAPPER.createObjectNode();
|
||||
if (name != null) {
|
||||
properties.put("ArchiveName", name);
|
||||
}
|
||||
if (sourceArn != null) {
|
||||
properties.put("SourceArn", sourceArn);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static JsonNode pattern() {
|
||||
try {
|
||||
return MAPPER.readTree(PATTERN);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode noValue() {
|
||||
return MAPPER.createObjectNode().put("Ref", "AWS::NoValue");
|
||||
}
|
||||
|
||||
private static boolean isNoValue(JsonNode node) {
|
||||
return node.isObject() && "AWS::NoValue".equals(node.path("Ref").asText());
|
||||
}
|
||||
|
||||
private static Archive archive(String name, String sourceArn, String description, String eventPattern,
|
||||
int retentionDays) {
|
||||
Archive archive = new Archive();
|
||||
archive.setArchiveName(name);
|
||||
archive.setArchiveArn(arn(name));
|
||||
archive.setEventSourceArn(sourceArn);
|
||||
archive.setDescription(description);
|
||||
archive.setEventPattern(eventPattern);
|
||||
archive.setRetentionDays(retentionDays);
|
||||
return archive;
|
||||
}
|
||||
|
||||
private static String arn(String name) {
|
||||
return "arn:aws:events:us-east-1:000000000000:archive/" + name;
|
||||
}
|
||||
}
|
||||
+93
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -319,4 +320,96 @@ class EventBridgeReplayIntegrationTest {
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(14)
|
||||
void updateArchiveKeepsTheFieldsTheRequestOmits() {
|
||||
createPartialUpdateArchive("partial-keep-archive");
|
||||
|
||||
updateArchive("""
|
||||
{"ArchiveName": "partial-keep-archive", "Description": "changed"}
|
||||
""");
|
||||
|
||||
describePartialUpdateArchive("partial-keep-archive")
|
||||
.body("Description", equalTo("changed"))
|
||||
.body("EventPattern", equalTo("{\"source\":[\"app.orders\"]}"))
|
||||
.body("RetentionDays", equalTo(5));
|
||||
deletePartialUpdateArchive("partial-keep-archive");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(15)
|
||||
void updateArchiveClearsTheDescriptionAndPatternGivenAsEmptyStrings() {
|
||||
createPartialUpdateArchive("partial-clear-archive");
|
||||
|
||||
updateArchive("""
|
||||
{"ArchiveName": "partial-clear-archive", "Description": "", "EventPattern": ""}
|
||||
""");
|
||||
|
||||
describePartialUpdateArchive("partial-clear-archive")
|
||||
.body("$", not(hasKey("Description")))
|
||||
.body("$", not(hasKey("EventPattern")))
|
||||
.body("RetentionDays", equalTo(5));
|
||||
deletePartialUpdateArchive("partial-clear-archive");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(16)
|
||||
void updateArchiveSetsAnExplicitZeroRetention() {
|
||||
createPartialUpdateArchive("partial-zero-archive");
|
||||
|
||||
updateArchive("""
|
||||
{"ArchiveName": "partial-zero-archive", "RetentionDays": 0}
|
||||
""");
|
||||
|
||||
describePartialUpdateArchive("partial-zero-archive")
|
||||
.body("Description", equalTo("original"))
|
||||
.body("EventPattern", equalTo("{\"source\":[\"app.orders\"]}"))
|
||||
.body("RetentionDays", equalTo(0));
|
||||
deletePartialUpdateArchive("partial-zero-archive");
|
||||
}
|
||||
|
||||
private static void createPartialUpdateArchive(String name) {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.CreateArchive")
|
||||
.body("""
|
||||
{
|
||||
"ArchiveName": "%s",
|
||||
"EventSourceArn": "%s",
|
||||
"Description": "original",
|
||||
"EventPattern": "{\\"source\\":[\\"app.orders\\"]}",
|
||||
"RetentionDays": 5
|
||||
}
|
||||
""".formatted(name, busArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void updateArchive(String body) {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.UpdateArchive")
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static ValidatableResponse describePartialUpdateArchive(String name) {
|
||||
return given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeArchive")
|
||||
.body("{\"ArchiveName\":\"" + name + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void deletePartialUpdateArchive(String name) {
|
||||
given()
|
||||
.contentType(EB_CT)
|
||||
.header("X-Amz-Target", "AWSEvents.DeleteArchive")
|
||||
.body("{\"ArchiveName\":\"" + name + "\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
+121
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Archive;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Replay;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.ReplayState;
|
||||
@@ -17,7 +18,9 @@ import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsT
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
@@ -25,6 +28,7 @@ import org.mockito.Mockito;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
@@ -36,6 +40,7 @@ class EventBridgeServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
private static final String DEFAULT_BUS = "arn:aws:events:us-east-1:000000000000:event-bus/default";
|
||||
|
||||
private EventBridgeService service;
|
||||
private TargetDispatcher dispatcherMock;
|
||||
@@ -218,6 +223,122 @@ class EventBridgeServiceTest {
|
||||
assertEquals(2, result.size());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Archives ────────────────────────────
|
||||
|
||||
@Test
|
||||
void createArchiveAcceptsTheDefaultBusAndAnExistingCustomBus() {
|
||||
String custom = service.createEventBus("orders", null, null, REGION).getArn();
|
||||
|
||||
assertEquals("arn:aws:events:us-east-1:000000000000:event-bus/default", service.createArchive(
|
||||
"on-default", "arn:aws:events:us-east-1:000000000000:event-bus/default", null, null, 0, REGION)
|
||||
.getEventSourceArn());
|
||||
assertEquals(custom, service.createArchive("on-custom", custom, null, null, 0, REGION)
|
||||
.getEventSourceArn());
|
||||
}
|
||||
|
||||
/** The messages AWS returns; the account is checked before the region. */
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"arn:aws:events:us-east-1:000000000000:event-bus/missing|ResourceNotFoundException|"
|
||||
+ "Event bus missing does not exist.",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/default|ValidationException|"
|
||||
+ "Parameter EventSourceArn is not valid. Reason: Creating cross-region archive is not permitted.",
|
||||
"arn:aws:events:us-east-1:111111111111:event-bus/default|AccessDeniedException|"
|
||||
+ "Archive event source arn:aws:events:us-east-1:111111111111:event-bus/default "
|
||||
+ "does not belong to account 000000000000.",
|
||||
"arn:aws:events:eu-west-1:111111111111:event-bus/missing|AccessDeniedException|"
|
||||
+ "Archive event source arn:aws:events:eu-west-1:111111111111:event-bus/missing "
|
||||
+ "does not belong to account 000000000000."
|
||||
})
|
||||
void createArchiveRejectsASourceThatIsNotAnExistingBusOfThisAccountAndRegion(
|
||||
String sourceArn, String code, String message) {
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.createArchive("orders-archive", sourceArn, null, null, 0, REGION));
|
||||
|
||||
assertEquals(code, error.getErrorCode());
|
||||
assertEquals(message, error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertTrue(service.listArchives(null, null, null, REGION).isEmpty());
|
||||
}
|
||||
|
||||
/** One out-of-range field each, with the message AWS returns for it. */
|
||||
static Stream<Arguments> outOfRangeArchiveFields() {
|
||||
String description = "d".repeat(513);
|
||||
String pattern = patternOfLength(4097);
|
||||
return Stream.of(
|
||||
Arguments.of(null, null, -1, "1 validation error detected: Value '-1' at 'retentionDays' "
|
||||
+ "failed to satisfy constraint: Member must have value greater than or equal to 0"),
|
||||
Arguments.of(description, null, 0, "1 validation error detected: Value '" + description
|
||||
+ "' at 'description' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 512"),
|
||||
Arguments.of(null, pattern, 0, "1 validation error detected: Value '" + pattern
|
||||
+ "' at 'eventPattern' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 4096"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("outOfRangeArchiveFields")
|
||||
void createArchiveRejectsAnOutOfRangeField(String description, String pattern, int retention, String message) {
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.createArchive("orders-archive", DEFAULT_BUS, description, pattern, retention, REGION));
|
||||
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(message, error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertTrue(service.listArchives(null, null, null, REGION).isEmpty());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("outOfRangeArchiveFields")
|
||||
void updateArchiveRejectsAnOutOfRangeFieldBeforeLookingTheArchiveUp(
|
||||
String description, String pattern, int retention, String message) {
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.updateArchive("missing-archive", description, pattern, retention, REGION));
|
||||
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(message, error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createArchiveReportsEveryViolationInAwsOrderBeforeCheckingTheSource() {
|
||||
String description = "d".repeat(513);
|
||||
String pattern = patternOfLength(4097);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.createArchive("orders-archive",
|
||||
"arn:aws:events:us-east-1:000000000000:event-bus/missing", description, pattern, -1, REGION));
|
||||
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals("3 validation errors detected: "
|
||||
+ "Value '-1' at 'retentionDays' failed to satisfy constraint: "
|
||||
+ "Member must have value greater than or equal to 0; "
|
||||
+ "Value '" + description + "' at 'description' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 512; "
|
||||
+ "Value '" + pattern + "' at 'eventPattern' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to 4096", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void archiveFieldsAtTheirLimitsAreAccepted() {
|
||||
String description = "d".repeat(512);
|
||||
String pattern = patternOfLength(4096);
|
||||
|
||||
service.createArchive("orders-archive", DEFAULT_BUS, description, pattern, 0, REGION);
|
||||
service.updateArchive("orders-archive", description, pattern, 0, REGION);
|
||||
|
||||
Archive archive = service.describeArchive("orders-archive", REGION);
|
||||
assertEquals(description, archive.getDescription());
|
||||
assertEquals(pattern, archive.getEventPattern());
|
||||
assertEquals(0, archive.getRetentionDays());
|
||||
}
|
||||
|
||||
private static String patternOfLength(int length) {
|
||||
String pattern = "{\"source\":[\"" + "a".repeat(length - 15) + "\"]}";
|
||||
assertEquals(length, pattern.length());
|
||||
return pattern;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Rules ────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user