mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): use bus|rule as the physical id of an Events rule on a custom bus (#8864)
This commit is contained in:
1 parent
2ac4554ea8
commit
9e65c12f8c
4 files changed
+228
-17
No files matched your search
@@ -347,6 +347,18 @@ tags the bus had before it are put back. Changing `Description` or `Policy` duri
|
||||
rejected until transactional resource rollback is available; this prevents a failed stack update
|
||||
from leaving the live bus in the rejected configuration.
|
||||
|
||||
## EventBridge rules
|
||||
|
||||
`AWS::Events::Rule` reports a rule on the default event bus by its name, and a rule on a custom event
|
||||
bus as `<event bus name>|<rule name>`, in `Ref` and in `DescribeStackResources`, as AWS's resource
|
||||
provider for the type does. A bus given by ARN counts by its name when it is in the stack's account,
|
||||
and keeps its ARN, `<event bus ARN>|<rule name>`, when it is in another account. EventBridge's own
|
||||
operations take the rule name and the bus separately, so split the value at the `|` before calling
|
||||
`DescribeRule` or `DeleteRule`. `Fn::GetAtt` still gives `RuleName` and `Arn`. A rule saved by an
|
||||
earlier Floci keeps its bare name as its id until an update changes the rule. An update that moves a
|
||||
rule to another bus, or renames it, creates the rule on that bus or under that name and leaves the
|
||||
old rule where it was.
|
||||
|
||||
## EventBridge archives
|
||||
|
||||
`AWS::Events::Archive` creates a real archive of the events sent to `SourceArn`, which must be an
|
||||
|
||||
+74
-17
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.eventbridge.EventBridgeService;
|
||||
@@ -42,10 +43,10 @@ import java.util.stream.Collectors;
|
||||
* {@code AWS::Events::EventBus} and {@code AWS::Events::EventBusPolicy}. Extracted from
|
||||
* the former CloudFormation monolith.
|
||||
*
|
||||
* <p>Two of these types need the resource's stored attributes to delete, not just the physical
|
||||
* id, so they are served by the {@link #delete(StackResource, String)} override rather than the
|
||||
* id-only form: a rule remembers the custom bus it lives on, and an event bus remembers the
|
||||
* creation time that proves the stack still owns it.
|
||||
* <p>Two of these types are served by the {@link #delete(StackResource, String)} override rather
|
||||
* than the id-only form: an event bus remembers the creation time that proves the stack still owns
|
||||
* it, and a rule saved before its physical id carried its custom bus finds that bus in the
|
||||
* {@code EventBusName} attribute it stored.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
@@ -53,6 +54,11 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final Logger LOG = Logger.getLogger(EventsCfnProvisioner.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private static final String DEFAULT_EVENT_BUS = "default";
|
||||
private static final String EVENT_BUS_RESOURCE_PREFIX = "event-bus/";
|
||||
/** Joins a custom bus to the rule name in a rule's physical id; neither name can contain it. */
|
||||
private static final char RULE_ID_SEPARATOR = '|';
|
||||
|
||||
/** The shape AWS::Events::Rule's resource schema declares for its targets. */
|
||||
private static final String TARGETS = CfnPropertyTypes.propertyShape("AWS::Events::Rule", "Targets");
|
||||
|
||||
@@ -92,14 +98,15 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
/**
|
||||
* A rule and an event bus both need attributes the physical id cannot carry: the rule's custom
|
||||
* bus, and the bus's recorded creation time. Deleting either by id alone would silently target
|
||||
* the default bus or skip the ownership check.
|
||||
* An event bus needs its stored creation time, which the physical id cannot carry; deleting
|
||||
* it by id alone would skip the ownership check. A rule's physical id names its custom bus, but
|
||||
* a rule saved before it did has only the rule name there and its bus in the stored
|
||||
* {@code EventBusName}, which deleting by id alone would silently trade for the default bus.
|
||||
*/
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
switch (resource.getResourceType()) {
|
||||
case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(resource.getPhysicalId(),
|
||||
case "AWS::Events::Rule" -> deleteRule(resource.getPhysicalId(),
|
||||
resource.getAttributes() != null ? resource.getAttributes().get("EventBusName") : null,
|
||||
region);
|
||||
case "AWS::Events::EventBus" -> deleteEventBusSafe(resource, region);
|
||||
@@ -113,7 +120,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
return;
|
||||
}
|
||||
switch (resourceType) {
|
||||
case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, null, region);
|
||||
case "AWS::Events::Rule" -> deleteRule(physicalId, null, region);
|
||||
case "AWS::Events::EventBus" -> deleteEventBusSafe(physicalId, region);
|
||||
case "AWS::Events::EventBusPolicy" -> removeEventBusPolicySafe(physicalId, region);
|
||||
case "AWS::Events::ApiDestination" -> deleteApiDestinationSafe(physicalId, region);
|
||||
@@ -128,11 +135,14 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
// before this run touches a target, so a rollback never puts back a target the rule stopped
|
||||
// carrying two updates ago.
|
||||
r.getAttributes().remove(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR);
|
||||
// Name is createOnly and the physical id is the rule name, so ctx.stablePhysicalName
|
||||
// applies directly: without it an unnamed rule was given a fresh random name on every
|
||||
// UpdateStack, creating a second rule and leaving the first behind with its targets.
|
||||
String ruleName = ctx.stablePhysicalName(
|
||||
ctx.resolveOptional(props, "Name"), r.getLogicalId(), 64, false);
|
||||
// Name is createOnly, so an unnamed rule keeps its name across an UpdateStack: without that it
|
||||
// was given a fresh random name on every update, creating a second rule and leaving the first
|
||||
// behind with its targets. The prior name comes out of the prior physical id, which for a rule
|
||||
// on a custom bus also carries the bus.
|
||||
String explicitName = ctx.resolveOptional(props, "Name");
|
||||
String ruleName = explicitName != null && !explicitName.isBlank()
|
||||
? explicitName
|
||||
: ruleNameOf(ctx.stablePhysicalName(null, r.getLogicalId(), 64, false));
|
||||
|
||||
String busName = ctx.resolveOptional(props, "EventBusName");
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
@@ -154,11 +164,11 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
Rule rule = eventBridgeService.putRule(ruleName, busName, eventPattern, scheduleExpression,
|
||||
state, description, roleArn, Map.of(), ctx.region());
|
||||
r.setPhysicalId(ruleName);
|
||||
r.setPhysicalId(rulePhysicalId(ruleName, busName, ctx.accountId()));
|
||||
r.getAttributes().put("Arn", rule.getArn());
|
||||
r.getAttributes().put("RuleName", ruleName);
|
||||
// A rule on a custom bus is keyed by that bus; remember it so the resource delete can target
|
||||
// the right bus (the physical id is only the rule name, which resolves to the default bus).
|
||||
// The bus as the template gave it, name or ARN. The physical id carries it too; this copy is
|
||||
// what a delete reads for a rule saved before the physical id did.
|
||||
if (busName != null && !busName.isBlank()) {
|
||||
r.getAttributes().put("EventBusName", busName);
|
||||
}
|
||||
@@ -713,6 +723,53 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
return bus.getCreatedTime() != null ? bus.getCreatedTime().toString() : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The physical id CloudFormation gives a rule, which is also what its {@code Ref} returns: the
|
||||
* rule name for a rule on the default event bus, and {@code <event bus name>|<rule name>} for a
|
||||
* rule on a custom bus. An event bus given by ARN counts by its name when it is in the stack's own
|
||||
* account, so the default bus given by ARN still yields the bare rule name; a bus in another
|
||||
* account keeps its ARN, {@code <event bus ARN>|<rule name>}. This is the format of AWS's resource
|
||||
* provider for the type. EventBridge's own operations take the rule name and the bus separately,
|
||||
* so a caller splits the value at the {@code |}.
|
||||
*/
|
||||
private static String rulePhysicalId(String ruleName, String busNameOrArn, String stackAccountId) {
|
||||
if (busNameOrArn == null || busNameOrArn.isBlank() || DEFAULT_EVENT_BUS.equals(busNameOrArn)) {
|
||||
return ruleName;
|
||||
}
|
||||
String busResource = AwsArnUtils.resourceIfArnFor(busNameOrArn, "events").orElse(null);
|
||||
if (busResource != null && busResource.startsWith(EVENT_BUS_RESOURCE_PREFIX)
|
||||
&& AwsArnUtils.parse(busNameOrArn).accountId().equals(stackAccountId)) {
|
||||
String busName = busResource.substring(EVENT_BUS_RESOURCE_PREFIX.length());
|
||||
return DEFAULT_EVENT_BUS.equals(busName) ? ruleName : busName + RULE_ID_SEPARATOR + ruleName;
|
||||
}
|
||||
return busNameOrArn + RULE_ID_SEPARATOR + ruleName;
|
||||
}
|
||||
|
||||
/** The rule name a rule's physical id carries: all of it, or what follows its custom bus. */
|
||||
private static String ruleNameOf(String physicalId) {
|
||||
int separator = physicalId.indexOf(RULE_ID_SEPARATOR);
|
||||
return separator < 0 ? physicalId : physicalId.substring(separator + 1);
|
||||
}
|
||||
|
||||
/** The custom bus, by name or ARN, a rule's physical id carries, or null for the default bus. */
|
||||
private static String busNameOf(String physicalId) {
|
||||
int separator = physicalId.indexOf(RULE_ID_SEPARATOR);
|
||||
return separator < 0 ? null : physicalId.substring(0, separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the rule a physical id names, on the bus the id carries. A rule saved before the id
|
||||
* carried its custom bus has only the rule name there; {@code storedBus}, the bus it stored at
|
||||
* creation, then says where it lives.
|
||||
*/
|
||||
private void deleteRule(String physicalId, String storedBus, String region) {
|
||||
if (physicalId == null || physicalId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
String busName = busNameOf(physicalId);
|
||||
deleteEventBridgeRuleSafe(ruleNameOf(physicalId), busName != null ? busName : storedBus, region);
|
||||
}
|
||||
|
||||
private void deleteEventBridgeRuleSafe(String ruleName, String busName, String region) {
|
||||
try {
|
||||
if (!eventBridgeService.ruleExists(ruleName, busName, region)) {
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.CfnTestStack;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.cloudformation.model.StackResource;
|
||||
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
|
||||
import software.amazon.awssdk.services.eventbridge.model.ResourceNotFoundException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** The physical id and {@code Ref} of an {@code AWS::Events::Rule} through the AWS SDK. */
|
||||
@QuarkusTest
|
||||
class CloudFormationEventsRulePhysicalIdIntegrationTest {
|
||||
|
||||
@RegisterExtension
|
||||
final CfnTestStack stack = new CfnTestStack("cfn-rule-id");
|
||||
|
||||
@Test
|
||||
void aRuleOnACustomBusIsReportedAsTheBusAndTheRuleNameAndTheStackDeleteRemovesIt() {
|
||||
String bus = stack.name() + "-bus";
|
||||
Stack created = stack.create("""
|
||||
{"Resources": {
|
||||
"Bus": {"Type": "AWS::Events::EventBus", "Properties": {"Name": "%s"}},
|
||||
"Queue": {"Type": "AWS::SQS::Queue"},
|
||||
"Rule": {"Type": "AWS::Events::Rule",
|
||||
"Properties": {"EventBusName": {"Ref": "Bus"}, "EventPattern": {"source": ["my.source"]},
|
||||
"Targets": [{"Id": "q", "Arn": {"Fn::GetAtt": ["Queue", "Arn"]}}]}},
|
||||
"DefaultBusRule": {"Type": "AWS::Events::Rule",
|
||||
"Properties": {"EventPattern": {"source": ["my.source"]}}}},
|
||||
"Outputs": {"RuleRef": {"Value": {"Ref": "Rule"}},
|
||||
"RuleName": {"Value": {"Fn::GetAtt": ["Rule", "RuleName"]}},
|
||||
"NameFromRef": {"Value": {"Fn::Select": [1, {"Fn::Split": ["|", {"Ref": "Rule"}]}]}},
|
||||
"BusFromRef": {"Value": {"Fn::Select": [0, {"Fn::Split": ["|", {"Ref": "Rule"}]}]}}}}"""
|
||||
.formatted(bus));
|
||||
|
||||
String ruleName = CfnStackWaits.output(created, "RuleName");
|
||||
assertEquals(bus + "|" + ruleName, CfnStackWaits.output(created, "RuleRef"));
|
||||
assertEquals(bus + "|" + ruleName, physicalId("Rule"));
|
||||
assertEquals(ruleName, CfnStackWaits.output(created, "NameFromRef"));
|
||||
assertEquals(bus, CfnStackWaits.output(created, "BusFromRef"));
|
||||
assertFalse(physicalId("DefaultBusRule").contains("|"));
|
||||
EventBridgeClient events = stack.client(EventBridgeClient.builder());
|
||||
assertEquals(ruleName, events.describeRule(r -> r.name(ruleName).eventBusName(bus)).name());
|
||||
|
||||
CfnStackWaits.deleteStack(stack.client(CloudFormationClient.builder()), stack.name());
|
||||
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> events.describeRule(r -> r.name(ruleName).eventBusName(bus)));
|
||||
assertThrows(ResourceNotFoundException.class, () -> events.describeEventBus(r -> r.name(bus)));
|
||||
}
|
||||
|
||||
private String physicalId(String logicalId) {
|
||||
return stack.client(CloudFormationClient.builder()).describeStackResources(r -> r.stackName(stack.name()))
|
||||
.stackResources().stream()
|
||||
.filter(resource -> logicalId.equals(resource.logicalResourceId()))
|
||||
.map(StackResource::physicalResourceId)
|
||||
.findFirst().orElseThrow();
|
||||
}
|
||||
}
|
||||
+76
@@ -16,6 +16,7 @@ import io.floci.aws.services.eventbridge.model.Target;
|
||||
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;
|
||||
@@ -128,6 +129,81 @@ class EventsCfnProvisionerTest {
|
||||
assertEquals("orders", r.getAttributes().get("RuleName"));
|
||||
}
|
||||
|
||||
// ── the physical id names a custom bus the way CloudFormation's does ─────
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@CsvSource(nullValues = "-", value = {
|
||||
"no bus, -, orders",
|
||||
"a blank bus, ' ', orders",
|
||||
"the default bus by name, default, orders",
|
||||
"the default bus by ARN, arn:aws:events:us-east-1:000000000000:event-bus/default, orders",
|
||||
"a custom bus by name, orders-bus, orders-bus|orders",
|
||||
"a custom bus by ARN, arn:aws:events:us-east-1:000000000000:event-bus/orders-bus, orders-bus|orders",
|
||||
"a custom bus by ARN in another partition,"
|
||||
+ " arn:aws-us-gov:events:us-gov-west-1:000000000000:event-bus/orders-bus, orders-bus|orders",
|
||||
"a bus of another account, arn:aws:events:us-east-1:111122223333:event-bus/orders-bus,"
|
||||
+ " arn:aws:events:us-east-1:111122223333:event-bus/orders-bus|orders",
|
||||
"a bus of another account in another partition,"
|
||||
+ " arn:aws-us-gov:events:us-gov-west-1:111122223333:event-bus/orders-bus,"
|
||||
+ " arn:aws-us-gov:events:us-gov-west-1:111122223333:event-bus/orders-bus|orders"})
|
||||
void aRulesPhysicalIdNamesItsBusUnlessItIsTheDefaultBus(String label, String bus, String physicalId) {
|
||||
stubPutRule();
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
ObjectNode props = mapper.createObjectNode().put("Name", "orders");
|
||||
if (bus != null) {
|
||||
props.put("EventBusName", bus);
|
||||
}
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
assertEquals(physicalId, r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnnamedRuleOnACustomBusKeepsItsNameAcrossUpdates() {
|
||||
stubPutRule();
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("EventBusName", "orders-bus"),
|
||||
ctx("orders-bus|my-stack-Rule-ab12cd"));
|
||||
|
||||
assertEquals("orders-bus|my-stack-Rule-ab12cd", r.getPhysicalId());
|
||||
verify(events).putRule(eq("my-stack-Rule-ab12cd"), eq("orders-bus"), any(), any(), any(), any(), any(),
|
||||
any(), anyString());
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@CsvSource(nullValues = "-", value = {
|
||||
"a custom bus in the id, orders-bus|orders, -, orders-bus",
|
||||
"a bus ARN in the id, arn:aws:events:us-east-1:111122223333:event-bus/orders-bus|orders, -,"
|
||||
+ " arn:aws:events:us-east-1:111122223333:event-bus/orders-bus",
|
||||
"a bare id and the stored bus, orders, orders-bus, orders-bus"})
|
||||
void deletingARuleTakesItsBusFromTheIdOrFromTheBusItStored(String label, String physicalId, String storedBus,
|
||||
String bus) {
|
||||
when(events.ruleExists("orders", bus, REGION)).thenReturn(true);
|
||||
when(events.listTargetsByRule("orders", bus, REGION)).thenReturn(List.of(storedTarget("t1")));
|
||||
StackResource r = resource("AWS::Events::Rule", "Rule");
|
||||
r.setPhysicalId(physicalId);
|
||||
if (storedBus != null) {
|
||||
r.getAttributes().put("EventBusName", storedBus);
|
||||
}
|
||||
|
||||
provisioner.delete(r, REGION);
|
||||
|
||||
verify(events).removeTargets("orders", bus, List.of("t1"), REGION);
|
||||
verify(events).deleteRule("orders", bus, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingByTheIdAloneFindsTheCustomBusInTheId() {
|
||||
when(events.ruleExists("orders", "orders-bus", REGION)).thenReturn(true);
|
||||
when(events.listTargetsByRule("orders", "orders-bus", REGION)).thenReturn(List.of());
|
||||
|
||||
provisioner.delete("AWS::Events::Rule", "orders-bus|orders", REGION);
|
||||
|
||||
verify(events).deleteRule("orders", "orders-bus", REGION);
|
||||
}
|
||||
|
||||
// ── targets are driven to the template's desired state ───────────────────
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user