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:
Mario Toffia authored and GitHub committed 2026-10-04 13:39:49 -04:00
1 parent dc3e9cacec
commit 66f04cde25
13 files changed
+1816 -6

No files matched your search

@@ -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
@@ -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.
*
* <p>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<String> 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<String, String> 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() : "";
}
}
@@ -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();
@@ -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<String> 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;
}