diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsArchiveTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsArchiveTest.java new file mode 100644 index 0000000000..b4f22156e2 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsArchiveTest.java @@ -0,0 +1,347 @@ +package com.floci.test; + +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 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.eventbridge.EventBridgeClient; +import software.amazon.awssdk.services.eventbridge.model.ArchiveState; +import software.amazon.awssdk.services.eventbridge.model.DescribeArchiveResponse; +import software.amazon.awssdk.services.eventbridge.model.EventBridgeException; +import software.amazon.awssdk.services.eventbridge.model.ResourceNotFoundException; + +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; + +@DisplayName("CloudFormation AWS::Events::Archive") +class CloudFormationEventsArchiveTest { + + private static final String PATTERN = "{\"source\":[\"app.orders\"]}"; + + private static CloudFormationClient cfn; + private static EventBridgeClient eventBridge; + private String stackName; + private boolean stackCreated; + private final List buses = new ArrayList<>(); + + @BeforeAll + static void clients() { + cfn = TestFixtures.cloudFormationClient(); + eventBridge = TestFixtures.eventBridgeClient(); + } + + @BeforeEach + void setup() { + stackName = TestFixtures.uniqueName("compat-cfn-archive"); + } + + @AfterEach + void cleanup() throws InterruptedException { + try { + deleteStack(); + } finally { + for (String bus : buses) { + eventBridge.deleteEventBus(r -> r.name(bus)); + } + } + } + + @AfterAll + static void closeClients() { + cfn.close(); + eventBridge.close(); + } + + @Test + void createsArchiveThatReadsBackThroughDescribeArchiveAndDeletesItWithTheStack() + throws InterruptedException { + String bus = createBus(); + String name = TestFixtures.uniqueName("orders"); + + createStack(template(name, true), parameters(bus, "7")); + + assertThat(output("ArchiveRef")).as("Ref is the archive name").isEqualTo(name); + DescribeArchiveResponse archive = eventBridge.describeArchive(r -> r.archiveName(name)); + assertThat(output("ArchiveArn")).as("GetAtt Arn is the archive ARN").isEqualTo(archive.archiveArn()); + assertThat(archive.eventSourceArn()).isEqualTo(bus); + assertThat(archive.eventPattern()).isEqualTo(PATTERN); + assertThat(archive.retentionDays()).isEqualTo(7); + assertThat(archive.description()).isEqualTo("orders archive"); + assertThat(archive.state()).isEqualTo(ArchiveState.ENABLED); + + deleteStack(); + assertThatThrownBy(() -> eventBridge.describeArchive(r -> r.archiveName(name))) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + void inPlaceUpdateKeepsTheArchiveAndADescriptionRemovedFromTheTemplate() throws InterruptedException { + String bus = createBus(); + String name = TestFixtures.uniqueName("orders"); + createStack(template(name, true), parameters(bus, "7")); + String arn = output("ArchiveArn"); + + cfn.updateStack(r -> r.stackName(stackName).templateBody(template(name, false)) + .parameters(parameters(bus, "30"))); + awaitStatus("UPDATE_COMPLETE"); + + assertThat(output("ArchiveRef")).isEqualTo(name); + assertThat(output("ArchiveArn")).isEqualTo(arn); + DescribeArchiveResponse archive = eventBridge.describeArchive(r -> r.archiveName(name)); + assertThat(archive.retentionDays()).isEqualTo(30); + assertThat(archive.description()) + .as("a property removed from the template keeps its value") + .isEqualTo("orders archive"); + assertThat(archive.eventPattern()).isEqualTo(PATTERN); + } + + @Test + void changingTheSourceReplacesAGeneratedArchive() throws InterruptedException { + String first = createBus(); + String second = createBus(); + createStack(template(null, false), parameters(first, "7")); + String original = output("ArchiveRef"); + assertThat(original).contains("Archive-").hasSizeLessThanOrEqualTo(48); + + cfn.updateStack(r -> r.stackName(stackName).templateBody(template(null, false)) + .parameters(parameters(second, "7"))); + awaitStatus("UPDATE_COMPLETE"); + + String replacement = output("ArchiveRef"); + assertThat(replacement).contains("Archive-").isNotEqualTo(original).hasSizeLessThanOrEqualTo(48); + assertThat(eventBridge.describeArchive(r -> r.archiveName(replacement)).eventSourceArn()) + .isEqualTo(second); + assertThatThrownBy(() -> eventBridge.describeArchive(r -> r.archiveName(original))) + .as("the displaced archive is deleted once the update commits") + .isInstanceOf(ResourceNotFoundException.class); + + deleteStack(); + assertThatThrownBy(() -> eventBridge.describeArchive(r -> r.archiveName(replacement))) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + void declaringTheGeneratedNameExplicitlyIsRefusedAsACustomNamedReplacement() throws InterruptedException { + String bus = createBus(); + createStack(template(null, false), parameters(bus, "7")); + String generated = cfn.describeStackResource(r -> r.stackName(stackName).logicalResourceId("Archive")) + .stackResourceDetail().physicalResourceId(); + + cfn.updateStack(r -> r.stackName(stackName).templateBody(template(generated, false)) + .parameters(parameters(bus, "7"))); + awaitStatus("UPDATE_ROLLBACK_COMPLETE"); + + String reason = "CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename " + generated + " and update the stack again."; + assertThat(cfn.describeStackEvents(r -> r.stackName(stackName)).stackEvents()) + .anyMatch(e -> "Archive".equals(e.logicalResourceId()) + && "UPDATE_FAILED".equals(e.resourceStatusAsString()) + && reason.equals(e.resourceStatusReason())); + assertThat(output("ArchiveRef")).isEqualTo(generated); + DescribeArchiveResponse archive = eventBridge.describeArchive(r -> r.archiveName(generated)); + assertThat(archive.eventSourceArn()).isEqualTo(bus); + assertThat(archive.retentionDays()).isEqualTo(7); + } + + @Test + void failedUpdateRestoresTheInPlaceChangeMadeBeforeALaterResourceFailed() throws InterruptedException { + String name = TestFixtures.uniqueName("orders"); + String broken = TestFixtures.uniqueName("broken"); + createStack(defaultBusTemplate(name, "orders archive", 7, null), List.of()); + + cfn.updateStack(r -> r.stackName(stackName) + .templateBody(defaultBusTemplate(name, "changed archive", 30, broken))); + awaitStatus("UPDATE_ROLLBACK_COMPLETE"); + + DescribeArchiveResponse archive = eventBridge.describeArchive(r -> r.archiveName(name)); + assertThat(archive.description()).isEqualTo("orders archive"); + assertThat(archive.retentionDays()).isEqualTo(7); + assertThatThrownBy(() -> eventBridge.describeArchive(r -> r.archiveName(broken))) + .as("the archive on a missing bus is never created") + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + void createArchiveAndUpdateArchiveRejectOutOfRangeFieldsBeforeAnyOtherCheck() { + String missingBus = eventBridge.describeEventBus(r -> r.name("default")).arn() + .replace("event-bus/default", "event-bus/" + TestFixtures.uniqueName("compat-archive-missing")); + String name = TestFixtures.uniqueName("compat-archive-invalid"); + String description = "d".repeat(513); + String pattern = "{\"source\":[\"" + "a".repeat(4082) + "\"]}"; + + assertThatThrownBy(() -> eventBridge.createArchive(r -> r.archiveName(name).eventSourceArn(missingBus) + .description(description).eventPattern(pattern).retentionDays(-1))) + .as("validation runs before the source check") + .isInstanceOfSatisfying(EventBridgeException.class, error -> { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ValidationException"); + assertThat(error.awsErrorDetails().errorMessage()) + .startsWith("3 validation errors detected: Value '-1' at 'retentionDays'") + .contains("at 'description' failed to satisfy constraint: " + + "Member must have length less than or equal to 512", + "at 'eventPattern' failed to satisfy constraint: " + + "Member must have length less than or equal to 4096"); + }); + assertThatThrownBy(() -> eventBridge.updateArchive(r -> r.archiveName(name).retentionDays(-1))) + .as("validation runs before the archive is looked up") + .isInstanceOfSatisfying(EventBridgeException.class, error -> { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ValidationException"); + assertThat(error.awsErrorDetails().errorMessage()).isEqualTo("1 validation error detected: " + + "Value '-1' at 'retentionDays' failed to satisfy constraint: " + + "Member must have value greater than or equal to 0"); + }); + } + + /** + * An archive on the account's 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 changed. + */ + private static String defaultBusTemplate(String name, String description, int retention, String brokenName) { + String broken = brokenName == null ? "" : """ + , + "Broken": { + "Type": "AWS::Events::Archive", + "DependsOn": "Archive", + "Properties": { + "ArchiveName": "%s", + "SourceArn": {"Fn::Sub": "arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/%s"} + } + }""".formatted(brokenName, brokenName + "-missing-bus"); + return """ + { + "Resources": { + "Archive": { + "Type": "AWS::Events::Archive", + "Properties": { + "ArchiveName": "%s", + "Description": "%s", + "SourceArn": {"Fn::Sub": "arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/default"}, + "RetentionDays": %d + } + }%s + } + } + """.formatted(name, description, retention, broken); + } + + private static String template(String archiveName, boolean withDescription) { + String name = archiveName == null ? "" : "\"ArchiveName\": \"" + archiveName + "\","; + String description = withDescription ? "\"Description\": \"orders archive\"," : ""; + return """ + { + "Parameters": { + "Source": {"Type": "String"}, + "Retention": {"Type": "Number"} + }, + "Resources": { + "Archive": { + "Type": "AWS::Events::Archive", + "Properties": { + %s + %s + "SourceArn": {"Ref": "Source"}, + "EventPattern": {"source": ["app.orders"]}, + "RetentionDays": {"Ref": "Retention"} + } + } + }, + "Outputs": { + "ArchiveRef": {"Value": {"Ref": "Archive"}}, + "ArchiveArn": {"Value": {"Fn::GetAtt": ["Archive", "Arn"]}} + } + } + """.formatted(name, description); + } + + private static List parameters(String source, String retention) { + return List.of( + Parameter.builder().parameterKey("Source").parameterValue(source).build(), + Parameter.builder().parameterKey("Retention").parameterValue(retention).build()); + } + + private String createBus() { + String bus = TestFixtures.uniqueName("compat-archive-bus"); + String arn = eventBridge.createEventBus(r -> r.name(bus)).eventBusArn(); + buses.add(bus); + return arn; + } + + private void createStack(String template, List parameters) throws InterruptedException { + cfn.createStack(r -> { + r.stackName(stackName).templateBody(template); + if (!parameters.isEmpty()) { + r.parameters(parameters); + } + }); + stackCreated = true; + awaitStatus("CREATE_COMPLETE"); + } + + private String output(String key) { + return cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).outputs().stream() + .filter(o -> key.equals(o.outputKey())).map(Output::outputValue) + .findFirst().orElseThrow(); + } + + /** Waits for {@code expected}, failing as soon as the stack settles on any other status. */ + private void awaitStatus(String expected) throws InterruptedException { + 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); + } + + private void deleteStack() throws InterruptedException { + if (!stackCreated) { + return; + } + cfn.deleteStack(r -> r.stackName(stackName)); + await(() -> { + try { + List stacks = cfn.describeStacks(r -> r.stackName(stackName)).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; + } + }, "stack deletion"); + stackCreated = false; + } + + private void await(BooleanSupplier condition, String expected) throws InterruptedException { + long deadline = System.nanoTime() + 60_000_000_000L; + while (System.nanoTime() < deadline) { + if (condition.getAsBoolean()) { + return; + } + Thread.sleep(100); + } + throw new AssertionError(stackName + " timed out waiting for " + expected); + } +} diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 05e898532e..ee7223b0ed 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -153,7 +153,7 @@ cross-resource references. | Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` | | Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `/`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolUser` | | ACM | `Certificate` | -| EventBridge | `Rule`, `EventBus`, `EventBusPolicy` | +| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `Archive` (`KmsKeyIdentifier` is ignored) | | EventBridge Scheduler | `ScheduleGroup` | | Transfer Family | `Server` (management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported) | | Backup | `BackupVault` | @@ -200,6 +200,25 @@ available. `Policy` is applied when the bus is created. Changing `Description`, during `UpdateStack` is rejected until transactional resource rollback is available; this prevents a failed stack update from leaving the live bus in the rejected configuration. +## EventBridge archives + +`AWS::Events::Archive` creates a real archive of the events sent to `SourceArn`, which must be an +existing event bus in the stack's account and region, as `CreateArchive` requires. `ArchiveName` is +optional; when omitted, CloudFormation generates a name and keeps it across updates. `Ref` returns +the archive name and `Fn::GetAtt Arn` the archive ARN. A missing `RetentionDays` stores 0, and an +`EventPattern` object reads back from `DescribeArchive` as a compact JSON string. +`KmsKeyIdentifier` is ignored. A `Description` over 512 characters, an `EventPattern` over 4096, or a +negative `RetentionDays` fails the resource with the `CreateArchive` or `UpdateArchive` validation +message, as on AWS. + +Changing `Description`, `EventPattern`, or `RetentionDays` updates the archive in place. A property +removed from the template is not sent, so the archive keeps its previous value, as on AWS. Changing +`SourceArn` or `ArchiveName`, or dropping an explicit `ArchiveName`, replaces the archive: the new +archive is created during the update and the previous one is deleted once the update commits. A +replacement that keeps the same explicit `ArchiveName`, or declares the generated name explicitly, +fails with CloudFormation's custom-named resource error and leaves the archive unchanged. Stack +deletion removes the archive and tolerates one that was already deleted. + ## Secrets Manager Target Attachments `AWS::SecretsManager::SecretTargetAttachment` adds the target's database connection fields to the diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 05d7c0d7f1..a9389fda17 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -78,6 +78,14 @@ public final class CfnRollback { */ public static final String DASHBOARD_UPDATE_SNAPSHOT_ATTR = "__FlociDashboardUpdateSnapshot"; + /** + * Holds the description, event pattern and retention an EventBridge archive carried before an + * in-place update changed them, so a failed stack update can put them back. Written by + * {@code EventsArchiveCfnProvisioner} before its update call and spent by its + * {@code rollbackUpdate}. + */ + public static final String ARCHIVE_UPDATE_SNAPSHOT_ATTR = "__FlociArchiveUpdateSnapshot"; + /** * Holds the name, description and endpoint configuration a REST API had before an in-place * update patched them, and whether the update also re-applied an OpenAPI document, so a failed diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsArchiveCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsArchiveCfnProvisioner.java new file mode 100644 index 0000000000..f644152029 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsArchiveCfnProvisioner.java @@ -0,0 +1,240 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; +import io.github.hectorvent.floci.services.eventbridge.model.Archive; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Provisions {@code AWS::Events::Archive}. Rules, buses and bus policies belong to + * {@link EventsCfnProvisioner}; this class takes only the EventBridge service so the test fixture + * can wire it from that service. + * + *

The archive name is the physical id and {@code Ref}, generated when the template gives none + * and kept across updates; {@code Fn::GetAtt Arn} is the archive ARN. The name and the source are + * create-only. An update that keeps both changes the archive in place through UpdateArchive, sending + * only the properties the template declares, so a property dropped from the template keeps its + * stored value, and keeps the description, pattern and retention it replaces on the resource so a + * failed stack update can put them back. An update that changes either, or drops an explicit name + * for a generated one, creates the new archive and leaves the displaced one to the + * {@link ReplacementCleanup} record; a replacement that would keep an explicit name is refused, as + * CloudFormation refuses it for any custom-named resource, and so is declaring a generated name + * explicitly. + */ +@ApplicationScoped +public class EventsArchiveCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::Events::Archive"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final int ARCHIVE_NAME_MAX_LENGTH = 48; + /** The registry schema's {@code ArchiveName} constraint: its pattern within lengths 1 to 48. */ + private static final Pattern ARCHIVE_NAME = Pattern.compile("[.\\-_A-Za-z0-9]{1,48}"); + /** + * Records whether the archive's name came from the template or was generated, so a later + * update can tell an explicit name being dropped, which replaces the archive on AWS, from an + * unnamed archive keeping the name it was given. Read back off the stored attributes. + */ + private static final String NAME_MODE_ATTR = "FlociArchiveNameMode"; + private static final String NAME_MODE_EXPLICIT = "explicit"; + private static final String NAME_MODE_GENERATED = "generated"; + + private final EventBridgeService eventBridgeService; + + @Inject + public EventsArchiveCfnProvisioner(EventBridgeService eventBridgeService) { + this.eventBridgeService = eventBridgeService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR); + Map attributesBefore = Map.copyOf(r.getAttributes()); + String explicitName = resolvePresent(props, "ArchiveName", ctx); + boolean hasExplicitName = explicitName != null; + if (hasExplicitName && !ARCHIVE_NAME.matcher(explicitName).matches()) { + throw new AwsException("ValidationError", TYPE + " ArchiveName must be 1 to 48 characters from " + + "[.\\-_A-Za-z0-9], got " + explicitName, 400); + } + String sourceArn = ctx.resolveOptional(props, "SourceArn"); + if (sourceArn == null || sourceArn.isBlank()) { + throw new AwsException("ValidationError", TYPE + " requires SourceArn", 400); + } + String description = resolvePresent(props, "Description", ctx); + // The pattern is a string on the wire; a template writes it as a JSON object, so blank can + // only be AWS::NoValue, which the engine resolves to an empty string. + String eventPattern = props == null ? null + : ctx.engine().resolveJsonAttribute(props.path("EventPattern")); + if (eventPattern != null && eventPattern.isBlank()) { + eventPattern = null; + } + Integer retentionDays = retentionDays(props, ctx); + + // A stack from before this type had a provisioner holds the dispatcher's stub here, which + // names no archive and never recorded a name mode, so the archive is created as on a first deploy. + boolean updatesArchive = ctx.isUpdate() && attributesBefore.containsKey(NAME_MODE_ATTR); + Archive prior = updatesArchive + ? eventBridgeService.describeArchive(ctx.priorPhysicalId(), ctx.region()) + : null; + boolean sourceChanged = prior != null && !sourceArn.equals(prior.getEventSourceArn()); + boolean nameWasGenerated = NAME_MODE_GENERATED.equals(attributesBefore.get(NAME_MODE_ATTR)); + if ((sourceChanged || nameWasGenerated) && hasExplicitName && explicitName.equals(ctx.priorPhysicalId())) { + throw new AwsException("ValidationError", + "CloudFormation cannot update a stack when a custom-named resource requires " + + "replacing. Rename " + explicitName + " and update the stack again.", 400); + } + String name = physicalName(r, ctx, explicitName, hasExplicitName, updatesArchive, sourceChanged); + + Archive archive; + if (updatesArchive && ctx.reusesPriorEntity(name)) { + snapshotBeforeUpdate(r, prior, ctx.region()); + archive = eventBridgeService.updateArchive(name, description, eventPattern, retentionDays, ctx.region()); + } else { + archive = eventBridgeService.createArchive(name, sourceArn, description, eventPattern, + retentionDays == null ? 0 : retentionDays, ctx.region()); + } + r.setPhysicalId(name); + r.getAttributes().put("Arn", archive.getArchiveArn()); + r.getAttributes().put(NAME_MODE_ATTR, hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED); + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** + * The resolved property, or null when it is absent or an intrinsic resolved to AWS::NoValue, + * which the engine yields as an empty string. A literal string is kept as written. + */ + private static String resolvePresent(JsonNode props, String name, ProvisionContext ctx) { + String value = ctx.resolveOptional(props, name); + boolean literal = props != null && props.path(name).isTextual(); + return literal || (value != null && !value.isBlank()) ? value : null; + } + + /** The template's retention, or null when it gives none so an update leaves the stored one alone. */ + private static Integer retentionDays(JsonNode props, ProvisionContext ctx) { + String raw = ctx.resolveOptional(props, "RetentionDays"); + if (raw == null || raw.isBlank()) { + return null; + } + try { + return Integer.valueOf(raw.trim()); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", + TYPE + " RetentionDays must be an integer, got " + raw, 400); + } + } + + /** + * The template's name when it gives one; otherwise the generated name the archive already has, + * unless the previous name was explicit or the source changed, since either replaces the + * archive on AWS, or the prior resource names no archive; and a fresh generated name otherwise. + */ + private static String physicalName(StackResource r, ProvisionContext ctx, String explicitName, + boolean hasExplicitName, boolean updatesArchive, boolean sourceChanged) { + if (hasExplicitName) { + return explicitName; + } + boolean explicitNameRemoved = ctx.isUpdate() + && NAME_MODE_EXPLICIT.equals(r.getAttributes().get(NAME_MODE_ATTR)); + if (updatesArchive && !explicitNameRemoved && !sourceChanged) { + return ctx.priorPhysicalId(); + } + return ctx.generatePhysicalName(r.getLogicalId(), ARCHIVE_NAME_MAX_LENGTH, false); + } + + /** + * Keeps the description, pattern and retention the archive has before an in-place update + * changes them, so {@link #rollbackUpdate} can put them back. + */ + private static void snapshotBeforeUpdate(StackResource r, Archive current, String region) { + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", region); + snapshot.put("name", current.getArchiveName()); + snapshot.put("description", current.getDescription()); + snapshot.put("eventPattern", current.getEventPattern()); + snapshot.put("retentionDays", current.getRetentionDays()); + r.getAttributes().put(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + CfnDeletes.safeDelete("EventBridge archive", physicalId, + () -> eventBridgeService.deleteArchive(physicalId, region), + "ResourceNotFoundException"); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement is undone through the cleanup record and an in-place update from the snapshot + * taken before it. UpdateArchive leaves an omitted field alone, so a field the snapshot holds + * no value for is sent empty to clear what the update set. With neither on the resource the + * provision failed before it changed anything, so there is nothing to undo. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + // The snapshot is spent only once the restore succeeded: a restore that throws leaves it in + // place for the next attempt instead of reporting a rollback that never happened. + String raw = resource.getAttributes().get(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR); + if (raw == null) { + return true; + } + JsonNode snapshot; + try { + snapshot = MAPPER.readTree(raw); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the archive update snapshot for " + + resource.getLogicalId(), e); + } + eventBridgeService.updateArchive(snapshot.path("name").asText(), + textOrEmpty(snapshot.path("description")), + textOrEmpty(snapshot.path("eventPattern")), + snapshot.path("retentionDays").asInt(), + snapshot.path("region").asText()); + resource.getAttributes().remove(CfnRollback.ARCHIVE_UPDATE_SNAPSHOT_ATTR); + return true; + } + + private static String textOrEmpty(JsonNode value) { + return value.isTextual() ? value.textValue() : ""; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java index fd94295aee..5a8307eef0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java @@ -461,7 +461,8 @@ public class EventBridgeHandler { String archiveName = request.path("ArchiveName").asText(null); String description = request.path("Description").asText(null); String eventPattern = request.path("EventPattern").asText(null); - int retentionDays = request.path("RetentionDays").asInt(0); + Integer retentionDays = request.hasNonNull("RetentionDays") + ? request.get("RetentionDays").asInt() : null; Archive archive = eventBridgeService.updateArchive( archiveName, description, eventPattern, retentionDays, region); ObjectNode response = objectMapper.createObjectNode(); diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java index 93b3566c40..11c857e5cc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java @@ -1206,12 +1206,14 @@ public class EventBridgeService implements ResourceProvider { public Archive createArchive(String archiveName, String eventSourceArn, String description, String eventPattern, int retentionDays, String region) { + requireArchiveFields(description, eventPattern, retentionDays); if (archiveName == null || archiveName.isBlank()) { throw new AwsException("ValidationException", "ArchiveName is required.", 400); } if (eventSourceArn == null || eventSourceArn.isBlank()) { throw new AwsException("ValidationException", "EventSourceArn is required.", 400); } + requireArchiveSource(eventSourceArn, region); String key = archiveKey(region, archiveName); if (archiveStore.get(key).isPresent()) { throw new AwsException("ResourceAlreadyExistsException", @@ -1231,23 +1233,84 @@ public class EventBridgeService implements ResourceProvider { return archive; } + /** + * The request constraints CreateArchive and UpdateArchive enforce before any other check, all + * violations reported together in AWS's order. A null argument is absent and not checked. + */ + private void requireArchiveFields(String description, String eventPattern, Integer retentionDays) { + List violations = new ArrayList<>(); + if (retentionDays != null && retentionDays < 0) { + violations.add("Value '" + retentionDays + "' at 'retentionDays' failed to satisfy constraint: " + + "Member must have value greater than or equal to 0"); + } + if (description != null && description.length() > 512) { + violations.add("Value '" + description + "' at 'description' failed to satisfy constraint: " + + "Member must have length less than or equal to 512"); + } + if (eventPattern != null && eventPattern.length() > 4096) { + violations.add("Value '" + eventPattern + "' at 'eventPattern' failed to satisfy constraint: " + + "Member must have length less than or equal to 4096"); + } + if (!violations.isEmpty()) { + String header = violations.size() == 1 + ? "1 validation error detected: " + : violations.size() + " validation errors detected: "; + throw new AwsException("ValidationException", header + String.join("; ", violations), 400); + } + } + + /** + * Checked as AWS does, before the name: the source's account, then its region, then that it is + * the ARN of an existing bus. Anything else, a malformed ARN included, is reported as a missing + * bus, since an archive on it could never capture an event. + */ + private void requireArchiveSource(String eventSourceArn, String region) { + String accountId = regionResolver.getAccountId(); + AwsArnUtils.Arn source = AwsArnUtils.isArn(eventSourceArn) ? AwsArnUtils.parse(eventSourceArn) : null; + if (source != null && !accountId.equals(source.accountId())) { + throw new AwsException("AccessDeniedException", "Archive event source " + eventSourceArn + + " does not belong to account " + accountId + ".", 400); + } + if (source != null && !region.equals(source.region())) { + throw new AwsException("ValidationException", + "Parameter EventSourceArn is not valid. Reason: Creating cross-region archive is not permitted.", + 400); + } + String busName = eventSourceArn.substring(eventSourceArn.indexOf('/') + 1); + EventBus bus = "default".equals(busName) + ? getOrCreateDefaultBus(region) + : busStore.get(busKey(region, busName)).orElse(null); + if (bus == null || !eventSourceArn.equals(bus.getArn())) { + throw new AwsException("ResourceNotFoundException", "Event bus " + busName + " does not exist.", 400); + } + } + public Archive describeArchive(String archiveName, String region) { return archiveStore.get(archiveKey(region, archiveName)) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Archive not found: " + archiveName, 400)); } + /** + * A partial update, as on AWS: a null argument leaves the stored value alone, and an empty + * description or event pattern clears it. + */ public Archive updateArchive(String archiveName, String description, - String eventPattern, int retentionDays, String region) { + String eventPattern, Integer retentionDays, String region) { + requireArchiveFields(description, eventPattern, retentionDays); String key = archiveKey(region, archiveName); Archive archive = archiveStore.get(key) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Archive not found: " + archiveName, 400)); if (description != null) { - archive.setDescription(description); + archive.setDescription(description.isEmpty() ? null : description); + } + if (eventPattern != null) { + archive.setEventPattern(eventPattern.isEmpty() ? null : eventPattern); + } + if (retentionDays != null) { + archive.setRetentionDays(retentionDays); } - archive.setEventPattern(eventPattern); - archive.setRetentionDays(retentionDays); archiveStore.put(key, archive); return archive; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 774146bae3..78490811f0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -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)); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventsArchiveIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventsArchiveIntegrationTest.java new file mode 100644 index 0000000000..d9569bcdcf --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventsArchiveIntegrationTest.java @@ -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 stacks = new ArrayList<>(); + private final List 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 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 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 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 created = archiveProperties(name, bus); + created.put("Description", "orders archive"); + created.put("EventPattern", MAPPER.readTree(PATTERN)); + String stack = createStack(template(created), "CREATE_COMPLETE"); + + Map 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 created = archiveProperties(name, bus); + created.put("Description", "orders archive"); + String stack = createStack(template(created), "CREATE_COMPLETE"); + + Map 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 created = archiveProperties(name, first); + created.put("RetentionDays", 7); + String stack = createStack(template(created), "CREATE_COMPLETE"); + + Map 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 created = archiveProperties(null, bus); + created.put("RetentionDays", 7); + String stack = createStack(template(created), "CREATE_COMPLETE"); + String generated = output(awaitStatus(stack, "CREATE_COMPLETE"), "ArchiveRef"); + + Map 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 -<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 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 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 reason) { + List> 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 archiveProperties(String name, Object sourceArn) { + Map properties = new LinkedHashMap<>(); + if (name != null) { + properties.put("ArchiveName", name); + } + properties.put("SourceArn", sourceArn); + return properties; + } + + private static String template(Map archiveProperties) throws Exception { + Map 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 archive = archiveProperties(name, busArnSub("default")); + archive.put("Description", description); + archive.put("RetentionDays", retention); + Map 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 busArnSub(String bus) { + return Map.of("Fn::Sub", "arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/" + bus); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsArchiveCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsArchiveCfnProvisionerTest.java new file mode 100644 index 0000000000..a2398b2654 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsArchiveCfnProvisionerTest.java @@ -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 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.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.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; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeReplayIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeReplayIntegrationTest.java index 49985cbde5..eb9a5826b0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeReplayIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeReplayIntegrationTest.java @@ -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); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java index dffa7e30e6..5fde6d09a0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java @@ -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 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 diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 41385dec23..3d998464b7 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -86,6 +86,7 @@ AWS::ElasticLoadBalancingV2::Listener ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::ListenerRule ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::LoadBalancer ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::TargetGroup ElbV2CfnProvisioner +AWS::Events::Archive EventsArchiveCfnProvisioner AWS::Events::EventBus EventsCfnProvisioner AWS::Events::EventBusPolicy EventsCfnProvisioner AWS::Events::Rule EventsCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index d568dda5c5..5e6bb756bc 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -170,6 +170,7 @@ notes: AWS::IoT::Policy: 'deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached' Custom::DynamoDBReplica: applied natively against DynamoDB, not via a provider Lambda AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `/`' + AWS::Events::Archive: '`KmsKeyIdentifier` is ignored' # Trailing prose appended to a row after its type list, for behaviour that belongs to the service # rather than to one type.