refactor(cloudformation): add the provisioner-migration enablers (#2732)

Groundwork for moving the remaining resource types out of
CloudFormationResourceProvisioner into per-service provisioners. No
behaviour change: every type is provisioned and deleted as before.

Make a dropped type fail loudly. The provision switch's default arm stubs
an unknown type with a fake ARN and reports CREATE_COMPLETE, so a type
that fell out of both the switch and the registry would pass every test
while provisioning nothing. Adds registeredTypes() on the registry, a
LEGACY_SWITCH_TYPES constant, a throwing default arm for a declared type
with no arm, and a checked-in inventory of all 112 types and their owner.
The inventory test runs under QuarkusTest so it compares against the
CDI-resolved registry, catching a provisioner written without
@ApplicationScoped.

Fix delete precedence. The registry lookup in delete(StackResource,
region) sat after a Custom:: prefix branch and nine attribute-aware
special cases, so migrating one of those types would leave its
provisioner's delete unreachable. The lookup now runs first, the nine
branches sit behind a DELETE_NEEDS_STACK_RESOURCE set that gates them,
and a duplicated AWS::Events::Rule block is removed.

Replace 13 positional constructions with one fixture. Every test built
the provisioner with 30-plus positional nulls, so each constructor change
edited all of them. CfnProvisionerFixture gives one named setter per
argument; removing the already-dead sqsService argument now touches only
that file.

Add the helpers the slices will use: ProvisionContext.isUpdate() and
resolveTags, CfnDeletes.safeDelete with explicit tolerated error codes,
and CfnDynamicReferences, which extracts 189 lines of dynamic-reference
handling so a future RDS provisioner injects one collaborator instead of
two unrelated services. resolveTags migrates no call sites: the seven
existing copies disagree on real behaviour and each adopts it in its own
slice.

Also fixes AslExecutorTaskHistoryEventsTest, which does not compile on
main: #2703 added it and #2688 then added a CustomResourceLiveness
parameter to AslExecutor without updating the call.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-08-29 22:44:07 -04:00
1 parent 477e8ae7b9
commit bdfaa01c46
25 files changed
+1447 -327

No files matched your search

@@ -38,12 +38,11 @@ class ApiGatewayV2CfnProvisionerTest {
@BeforeEach
void setUp() {
apiGatewayV2Service = mock(ApiGatewayV2Service.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null, null, null, null, null, null,
null, apiGatewayV2Service, null, null, null, null, mapper,
null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null,
new CloudFormationResourceRegistry(java.util.List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.apiGatewayV2(apiGatewayV2Service)
.objectMapper(mapper)
.registry(new CloudFormationResourceRegistry(java.util.List.of()))
.build();
Api api = new Api();
api.setApiId(API_ID);
@@ -0,0 +1,64 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Guards the delete dispatch order in {@link CloudFormationResourceProvisioner}.
*
* <p>Deleting a resource takes one of three routes: an extracted provisioner, the attribute-aware
* branches for {@code DELETE_NEEDS_STACK_RESOURCE}, or the generic type/physicalId switch. The
* registry is consulted first so an exact match beats the {@code Custom::} prefix branch, which is
* what lets {@code Custom::DynamoDBReplica} move to a provisioner at all.
*
* <p>The cost of registry-first is that a leftover attribute-aware branch for a migrated type
* becomes unreachable rather than wrong. That is the safe direction, but it would let a slice quietly
* drop delete logic that only that branch implemented, so this test makes the overlap a build
* failure: migrating one of those types must move its logic into the provisioner's
* {@code delete(StackResource, String)} override and drop its entry from the set.
*/
@QuarkusTest
class CfnDeletePrecedenceTest {
@Inject
CloudFormationResourceRegistry registry;
@Test
void noTypeIsServedByBothAProvisionerAndAnAttributeAwareBranch() {
List<String> both = CloudFormationResourceProvisioner.DELETE_NEEDS_STACK_RESOURCE.stream()
.filter(type -> registry.forType(type).isPresent())
.sorted()
.toList();
assertTrue(both.isEmpty(),
"These types have an extracted provisioner, so their attribute-aware delete branch "
+ "is now unreachable. Move that logic into the provisioner's "
+ "delete(StackResource, String) override and remove the entry from "
+ "DELETE_NEEDS_STACK_RESOURCE: " + both);
}
/**
* Every attribute-aware type is one Floci actually provisions. A typo in the set
* ({@code AWS::Events::Rules}) would never match, sending the real type down the
* type/physicalId path where its delete silently no-ops and leaves the resource live.
*/
@Test
void everyAttributeAwareTypeIsAProvisionedType() {
List<String> unknown = CloudFormationResourceProvisioner.DELETE_NEEDS_STACK_RESOURCE.stream()
.filter(type -> registry.forType(type).isEmpty())
.filter(type -> !CloudFormationResourceProvisioner.LEGACY_SWITCH_TYPES.contains(type))
.sorted()
.toList();
assertTrue(unknown.isEmpty(),
"DELETE_NEEDS_STACK_RESOURCE names types that nothing provisions, so the entry is "
+ "dead and the real type (if misspelled here) deletes by physical id alone: "
+ unknown);
}
}
@@ -0,0 +1,335 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.docdb.DocDbService;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ecr.EcrService;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.eks.EksService;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.pipes.PipesService;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.ssm.SsmService;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
import java.util.Arrays;
import java.util.List;
/**
* Builds {@link CloudFormationResourceProvisioner} for tests without a wall of positional nulls.
*
* <p>The provisioner takes one constructor argument per service it still provisions, so every test
* that built it directly had to pass 30-plus {@code null}s in the right order, and every argument
* added or removed edited all of them. Naming only what a test actually uses keeps the intent
* visible and, more importantly, makes the arity a one-file change: as types migrate to per-service
* provisioners their arguments fall away, and only this class needs updating.
*
* <p>Tests exercising a type that has already migrated must register its provisioner with
* {@link Builder#provisioners} rather than leaving the registry empty. With an empty registry a
* migrated type reaches the provisioner's default arm and is stubbed with a fake ARN and
* CREATE_COMPLETE, so the test passes while provisioning nothing.
*/
final class CfnProvisionerFixture {
private CfnProvisionerFixture() {
}
static Builder builder() {
return new Builder();
}
static final class Builder {
private S3Service s3Service;
private SnsService snsService;
private DynamoDbService dynamoDbService;
private LambdaService lambdaService;
private IamService iamService;
private SsmService ssmService;
private KmsService kmsService;
private SecretsManagerService secretsManagerService;
private EventBridgeService eventBridgeService;
private ApiGatewayService apiGatewayService;
private ApiGatewayV2Service apiGatewayV2Service;
private EcrService ecrService;
private PipesService pipesService;
private CognitoService cognitoService;
private LambdaLayerService lambdaLayerService;
private ObjectMapper objectMapper;
private CustomResourceResponseStore customResourceResponseStore;
private ContainerReachableEndpoint reachableEndpoint;
private EcsService ecsService;
private ElbV2Service elbV2Service;
private StepFunctionsService stepFunctionsService;
private BatchService batchService;
private Ec2Service ec2Service;
private RdsService rdsService;
private EksService eksService;
private CloudWatchLogsService logsService;
private KinesisService kinesisService;
private CloudWatchMetricsService cloudWatchMetricsService;
private AutoScalingService autoScalingService;
private FirehoseService firehoseService;
private DocDbService docDbService;
private CloudFrontService cloudFrontService;
private CloudFormationResourceRegistry resourceRegistry;
private CfnDynamicReferences dynamicReferences;
private EmulatorConfig config;
private Builder() {
this.objectMapper = new ObjectMapper();
this.resourceRegistry = new CloudFormationResourceRegistry(List.of());
}
/** Registers extracted provisioners, the way production CDI discovery would. */
public Builder provisioners(CfnResourceProvisioner... provisioners) {
this.resourceRegistry = new CloudFormationResourceRegistry(Arrays.asList(provisioners));
return this;
}
public Builder s3(S3Service v) {
this.s3Service = v;
return this;
}
public Builder sns(SnsService v) {
this.snsService = v;
return this;
}
public Builder dynamoDb(DynamoDbService v) {
this.dynamoDbService = v;
return this;
}
public Builder lambda(LambdaService v) {
this.lambdaService = v;
return this;
}
public Builder iam(IamService v) {
this.iamService = v;
return this;
}
public Builder ssm(SsmService v) {
this.ssmService = v;
return this;
}
public Builder kms(KmsService v) {
this.kmsService = v;
return this;
}
public Builder secretsManager(SecretsManagerService v) {
this.secretsManagerService = v;
return this;
}
public Builder eventBridge(EventBridgeService v) {
this.eventBridgeService = v;
return this;
}
public Builder apiGateway(ApiGatewayService v) {
this.apiGatewayService = v;
return this;
}
public Builder apiGatewayV2(ApiGatewayV2Service v) {
this.apiGatewayV2Service = v;
return this;
}
public Builder ecr(EcrService v) {
this.ecrService = v;
return this;
}
public Builder pipes(PipesService v) {
this.pipesService = v;
return this;
}
public Builder cognito(CognitoService v) {
this.cognitoService = v;
return this;
}
public Builder lambdaLayer(LambdaLayerService v) {
this.lambdaLayerService = v;
return this;
}
public Builder objectMapper(ObjectMapper v) {
this.objectMapper = v;
return this;
}
public Builder customResourceResponseStore(CustomResourceResponseStore v) {
this.customResourceResponseStore = v;
return this;
}
public Builder reachableEndpoint(ContainerReachableEndpoint v) {
this.reachableEndpoint = v;
return this;
}
public Builder ecs(EcsService v) {
this.ecsService = v;
return this;
}
public Builder elbV2(ElbV2Service v) {
this.elbV2Service = v;
return this;
}
public Builder stepFunctions(StepFunctionsService v) {
this.stepFunctionsService = v;
return this;
}
public Builder batch(BatchService v) {
this.batchService = v;
return this;
}
public Builder ec2(Ec2Service v) {
this.ec2Service = v;
return this;
}
public Builder rds(RdsService v) {
this.rdsService = v;
return this;
}
public Builder eks(EksService v) {
this.eksService = v;
return this;
}
public Builder logs(CloudWatchLogsService v) {
this.logsService = v;
return this;
}
public Builder kinesis(KinesisService v) {
this.kinesisService = v;
return this;
}
public Builder cloudWatchMetrics(CloudWatchMetricsService v) {
this.cloudWatchMetricsService = v;
return this;
}
public Builder autoScaling(AutoScalingService v) {
this.autoScalingService = v;
return this;
}
public Builder firehose(FirehoseService v) {
this.firehoseService = v;
return this;
}
public Builder docDb(DocDbService v) {
this.docDbService = v;
return this;
}
public Builder cloudFront(CloudFrontService v) {
this.cloudFrontService = v;
return this;
}
public Builder registry(CloudFormationResourceRegistry v) {
this.resourceRegistry = v;
return this;
}
public Builder dynamicReferences(CfnDynamicReferences v) {
this.dynamicReferences = v;
return this;
}
public Builder config(EmulatorConfig v) {
this.config = v;
return this;
}
public CloudFormationResourceProvisioner build() {
if (dynamicReferences == null) {
// Wire it from the services already named, the way CDI does in production, so a
// test resolving {{resolve:ssm:...}} or {{resolve:secretsmanager:...}} does not
// have to know that resolution moved out of the provisioner.
dynamicReferences = new CfnDynamicReferences(
secretsManagerService, ssmService, objectMapper);
}
return new CloudFormationResourceProvisioner(
s3Service,
snsService,
dynamoDbService,
lambdaService,
iamService,
ssmService,
kmsService,
secretsManagerService,
eventBridgeService,
apiGatewayService,
apiGatewayV2Service,
ecrService,
pipesService,
cognitoService,
lambdaLayerService,
objectMapper,
customResourceResponseStore,
reachableEndpoint,
ecsService,
elbV2Service,
stepFunctionsService,
batchService,
ec2Service,
rdsService,
eksService,
logsService,
kinesisService,
cloudWatchMetricsService,
autoScalingService,
firehoseService,
docDbService,
cloudFrontService,
resourceRegistry,
dynamicReferences,
config);
}
}
}
@@ -0,0 +1,151 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Pins the full set of CloudFormation resource types Floci provisions, and who serves each one.
*
* <p>This is the guard for the per-service provisioner migration. {@code provision}'s default arm
* stubs an unknown type with {@code arn:aws:stub:::<logicalId>} and reports CREATE_COMPLETE, so a
* type that falls out of both the switch and the registry would otherwise pass every test while
* provisioning nothing. Making the inventory a checked-in file turns each migration slice into an
* intentional two-line diff.
*
* <p>Runs under {@code @QuarkusTest} deliberately: the registry is compared as CDI resolved it, so
* a provisioner written without {@code @ApplicationScoped} is caught. That mistake leaves the
* source looking correct and is invisible to a plain unit test.
*/
@QuarkusTest
class CfnResourceInventoryTest {
private static final Path INVENTORY =
Path.of("src/test/resources/cloudformation/supported-resource-types.tsv");
private static final Path SCHEMA_DIR = Path.of("local/aws/cfn-resource-schemas/us-east-1");
private static final String LEGACY_OWNER = "LEGACY_SWITCH";
/**
* Types with no CloudFormation registry schema. {@code AWS::CDK::Metadata} is emitted by the
* CDK toolchain rather than published by AWS, so it has no schema to check against.
*/
private static final Set<String> TYPES_WITHOUT_SCHEMA = Set.of("AWS::CDK::Metadata");
@Inject
CloudFormationResourceRegistry registry;
@Test
void inventoryMatchesTheRegistryAndTheLegacySwitch() {
Map<String, String> actual = new TreeMap<>();
for (String type : registry.registeredTypes()) {
actual.put(type, registry.ownerOf(type));
}
for (String type : CloudFormationResourceProvisioner.LEGACY_SWITCH_TYPES) {
actual.put(type, LEGACY_OWNER);
}
assertEquals(render(readInventory()), render(actual),
"The provisioned resource-type inventory changed. If that was intentional, write "
+ "this exact content to " + INVENTORY + ".");
}
@Test
void noTypeIsServedByBothTheRegistryAndTheSwitch() {
List<String> both = registry.registeredTypes().stream()
.filter(CloudFormationResourceProvisioner.LEGACY_SWITCH_TYPES::contains)
.sorted()
.toList();
assertTrue(both.isEmpty(),
"A type served by an extracted provisioner must have its switch arm removed; the "
+ "registry wins, leaving the arm as dead code that still looks live: " + both);
}
@Test
void inventoryFileIsSortedAndFreeOfDuplicates() {
List<String> types = readTypeColumn();
assertEquals(types.stream().distinct().toList(), types,
"Duplicate type rows in " + INVENTORY + "; each type is served by exactly one owner.");
assertEquals(types.stream().sorted().toList(), types,
"Keep " + INVENTORY + " sorted by type so slice diffs stay reviewable.");
}
/**
* Every declared AWS type exists in the published CloudFormation registry schemas. Catches a
* typo'd type string, which is otherwise permanently silent: it never matches a template and
* the default arm stubs it. Skipped where the schema corpus is absent (it lives under the
* gitignored {@code local/}), so this is a local correctness aid, not a CI gate.
*/
@Test
void everyDeclaredTypeIsARealAwsResourceType() {
if (!Files.isDirectory(SCHEMA_DIR)) {
return;
}
List<String> unknown = readInventory().keySet().stream()
.filter(type -> type.startsWith("AWS::"))
.filter(type -> !TYPES_WITHOUT_SCHEMA.contains(type))
.filter(type -> !Files.exists(SCHEMA_DIR.resolve(schemaFileName(type))))
.toList();
assertTrue(unknown.isEmpty(), "No CloudFormation registry schema for: " + unknown);
}
/** {@code AWS::SQS::Queue} to {@code aws-sqs-queue.json}. */
private static String schemaFileName(String type) {
return type.replace("::", "-").toLowerCase(Locale.ROOT) + ".json";
}
/** The type column in file order, so duplicate and ordering defects survive to be asserted. */
private static List<String> readTypeColumn() {
try {
return Files.readAllLines(INVENTORY, StandardCharsets.UTF_8).stream()
.filter(line -> !line.isBlank())
.map(line -> line.split("\t", 2)[0])
.toList();
} catch (IOException e) {
throw new UncheckedIOException("Cannot read " + INVENTORY, e);
}
}
private static Map<String, String> readInventory() {
try {
Map<String, String> rows = new LinkedHashMap<>();
for (String line : Files.readAllLines(INVENTORY, StandardCharsets.UTF_8)) {
if (line.isBlank()) {
continue;
}
String[] parts = line.split("\t", 2);
assertEquals(2, parts.length, "Expected 'type<TAB>owner' but found: " + line);
rows.put(parts[0], parts[1]);
}
return rows;
} catch (IOException e) {
throw new UncheckedIOException("Cannot read " + INVENTORY, e);
}
}
private static String render(Map<String, String> rows) {
return rows.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> e.getKey() + "\t" + e.getValue())
.collect(Collectors.joining("\n"));
}
}
@@ -1,14 +1,11 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertSame;
@@ -29,15 +26,10 @@ class CloudFormationDeleteIdempotencyTest {
void setUp() {
dynamoDbService = mock(DynamoDbService.class);
lambdaService = mock(LambdaService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, dynamoDbService, lambdaService,
null, null, null, null, null,
null, null, null, null, null, null,
new ObjectMapper(),
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
null, null,
new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.dynamoDb(dynamoDbService)
.lambda(lambdaService)
.build();
}
@Test
@@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
@@ -13,7 +12,6 @@ import io.github.hectorvent.floci.services.ec2.model.Reservation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@@ -38,11 +36,10 @@ class CloudFormationEc2ProvisionerTest {
@BeforeEach
void setUp() {
ec2Service = mock(Ec2Service.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, mapper, null, null, null, null, null, null,
ec2Service, null, null, null, null, null, null, null,
null, null, new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.objectMapper(mapper)
.ec2(ec2Service)
.build();
}
@Test
@@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
@@ -47,14 +46,11 @@ class CloudFormationIamAttachmentProvisionerTest {
@BeforeEach
void setUp() {
iamService = mock(IamService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null, iamService, null, null, null, null,
null, null, null, null, null, null,
mapper,
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
null, null,
new CloudFormationResourceRegistry(List.of(new IamRoleCfnProvisioner(iamService))), null);
provisioner = CfnProvisionerFixture.builder()
.iam(iamService)
.objectMapper(mapper)
.provisioners(new IamRoleCfnProvisioner(iamService))
.build();
}
@Test
@@ -3,7 +3,6 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import org.junit.jupiter.api.BeforeEach;
@@ -48,14 +47,10 @@ class CloudFormationLambdaLegacyNameModeTest {
.thenAnswer(inv -> lambdaFunction(inv.getArgument(1)));
when(lambdaService.updateFunctionCode(anyString(), anyString(), anyMap()))
.thenAnswer(inv -> lambdaFunction(inv.getArgument(1)));
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, lambdaService, null, null, null, null, null,
null, null, null, null, null, null,
mapper,
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
null, null,
new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.lambda(lambdaService)
.objectMapper(mapper)
.build();
}
@Test
@@ -3,12 +3,10 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@@ -41,14 +39,10 @@ class CloudFormationLogGroupProvisionerTest {
@BeforeEach
void setUp() {
logsService = mock(CloudWatchLogsService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null,
mapper,
null, null, null, null, null, null, null,
null, null, logsService, null, null, null, null,
null, null,
new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.objectMapper(mapper)
.logs(logsService)
.build();
}
@Test
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.lambda.LambdaService;
@@ -51,12 +52,13 @@ class CustomResourceProviderFrameworkTest {
ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class);
when(endpoint.baseUrl()).thenReturn("http://floci:4566");
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, lambdaService, null, null, null, null, null,
null, null, null, null, null, null, mapper, store, endpoint, null, null, null, null, null, null, null, null, null, null, null, null,
null, null,
new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()),
mock(io.github.hectorvent.floci.config.EmulatorConfig.class));
provisioner = CfnProvisionerFixture.builder()
.lambda(lambdaService)
.objectMapper(mapper)
.customResourceResponseStore(store)
.reachableEndpoint(endpoint)
.config(mock(EmulatorConfig.class))
.build();
}
private CloudFormationTemplateEngine engine() {
@@ -46,11 +46,12 @@ class CustomResourceProvisionerTest {
ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class);
when(endpoint.baseUrl()).thenReturn("http://floci:4566");
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, lambdaService, null, null, null, null, null,
null, null, null, null, null, null, mapper, store, endpoint, null, null, null, null, null, null, null, null, null, null, null, null,
null, null,
new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.lambda(lambdaService)
.objectMapper(mapper)
.customResourceResponseStore(store)
.reachableEndpoint(endpoint)
.build();
}
private CloudFormationTemplateEngine engine() {
@@ -3,7 +3,6 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -31,11 +30,10 @@ class DynamoDbReplicaCfnProvisionerTest {
@BeforeEach
void setUp() {
dynamoDbService = mock(DynamoDbService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, dynamoDbService, null, null, null, null, null, null,
null, null, null, null, null, null, mapper, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null,
new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.dynamoDb(dynamoDbService)
.objectMapper(mapper)
.build();
}
@Test
@@ -3,13 +3,11 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@@ -49,11 +47,10 @@ class DynamoDbStreamSpecificationCfnProvisionerTest {
@BeforeEach
void setUp() {
dynamoDbService = mock(DynamoDbService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, dynamoDbService, null, null, null, null, null, null,
null, null, null, null, null, null, mapper, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null,
new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.dynamoDb(dynamoDbService)
.objectMapper(mapper)
.build();
TableDefinition created = new TableDefinition();
created.setTableName(TABLE);
@@ -1,16 +1,13 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -38,15 +35,9 @@ class EventBusDeleteOwnershipTest {
@BeforeEach
void setUp() {
eventBridgeService = mock(EventBridgeService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null,
null, null, null, null, eventBridgeService,
null, null, null, null, null, null,
new ObjectMapper(),
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
null, null,
new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.eventBridge(eventBridgeService)
.build();
}
@Test
@@ -5,14 +5,12 @@ 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.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@@ -51,15 +49,10 @@ class EventBusProvisionOwnershipTest {
@BeforeEach
void setUp() {
eventBridgeService = mock(EventBridgeService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null,
null, null, null, null, eventBridgeService,
null, null, null, null, null, null,
MAPPER,
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
null, null,
new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.eventBridge(eventBridgeService)
.objectMapper(MAPPER)
.build();
}
/**
@@ -64,14 +64,12 @@ class RdsCfnProvisionerTest {
rdsService = mock(RdsService.class);
secretsManagerService = mock(SecretsManagerService.class);
ssmService = mock(SsmService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null, null, ssmService, null, secretsManagerService, null,
null, null, null, null, null, null,
mapper,
null, null, null, null, null, null, null,
rdsService, null, null, null, null, null, null,
null, null,
new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.ssm(ssmService)
.secretsManager(secretsManagerService)
.objectMapper(mapper)
.rds(rdsService)
.build();
}
private CloudFormationTemplateEngine engine() {
@@ -5,7 +5,6 @@ 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.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.docdb.DocDbService;
import io.github.hectorvent.floci.services.docdb.model.DocDbCluster;
import io.github.hectorvent.floci.services.docdb.model.DocDbInstance;
@@ -64,14 +63,12 @@ class SecretTargetAttachmentCfnProvisionerTest {
docDbService = mock(DocDbService.class);
when(secretsManagerService.claimTargetAttachment(any(), any(), any())).thenReturn(true);
when(secretsManagerService.canManageTargetAttachment(any(), any(), any())).thenReturn(true);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null, null, null, null, secretsManagerService, null,
null, null, null, null, null, null,
mapper,
null, null, null, null, null, null, null,
rdsService, null, null, null, null, null, null,
docDbService, null,
new CloudFormationResourceRegistry(List.of()), null);
provisioner = CfnProvisionerFixture.builder()
.secretsManager(secretsManagerService)
.objectMapper(mapper)
.rds(rdsService)
.docDb(docDbService)
.build();
}
@Test
@@ -0,0 +1,59 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CfnDeletesTest {
@Test
void runsTheDelete() {
AtomicBoolean deleted = new AtomicBoolean();
CfnDeletes.safeDelete("queue", "q1", () -> deleted.set(true), "NoSuchEntity");
assertTrue(deleted.get());
}
@Test
void toleratesTheNamedAlreadyGoneCode() {
assertDoesNotThrow(() -> CfnDeletes.safeDelete("DB proxy", "proxy-1", () -> {
throw new AwsException("DBProxyNotFoundFault", "not found", 404);
}, "DBProxyNotFoundFault"));
}
/**
* The reason the tolerated codes are explicit. A stack deletion reports DELETE_FAILED when a
* delete throws, which is how a genuine failure such as a non-empty bucket surfaces; swallowing
* everything would report a clean deletion while the resource is still there.
*/
@Test
void propagatesAnyOtherFailure() {
AwsException thrown = assertThrows(AwsException.class,
() -> CfnDeletes.safeDelete("bucket", "my-bucket", () -> {
throw new AwsException("BucketNotEmpty", "The bucket you tried to delete is not empty", 409);
}, "NoSuchBucket"));
assertEquals("BucketNotEmpty", thrown.getErrorCode());
}
@Test
void toleratesNothingWhenNoCodesAreGiven() {
assertThrows(AwsException.class, () -> CfnDeletes.safeDelete("topic", "t1", () -> {
throw new AwsException("NotFound", "gone", 404);
}));
}
@Test
void acceptsSeveralAlreadyGoneCodes() {
assertDoesNotThrow(() -> CfnDeletes.safeDelete("target group", "tg-1", () -> {
throw new AwsException("DBProxyTargetGroupNotFoundFault", "not found", 404);
}, "DBProxyNotFoundFault", "DBProxyTargetGroupNotFoundFault"));
}
}
@@ -0,0 +1,139 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** The shared helpers on {@link ProvisionContext} that extracted provisioners build on. */
class ProvisionContextTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private CloudFormationTemplateEngine engine;
@BeforeEach
void setUp() {
// The engine resolves intrinsics; these tests are about what ProvisionContext asks it to
// resolve, so it passes values through the way it would with no intrinsics present.
engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
when(engine.resolve(any())).thenAnswer(i -> {
JsonNode node = i.getArgument(0);
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
}
private ProvisionContext context(String priorPhysicalId) {
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
private static JsonNode props(String json) {
try {
return MAPPER.readTree(json);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
@Test
void isUpdateReflectsWhetherAPriorPhysicalIdExists() {
assertFalse(context(null).isUpdate(), "a first-time create has no prior physical id");
assertFalse(context(" ").isUpdate(), "a blank id is not a prior provision");
assertTrue(context("my-stack-Queue-abc123").isUpdate());
}
/**
* The four-argument form is what the existing construction sites use, so it must keep meaning
* "create".
*/
@Test
void theCreateOnlyConstructorIsNotAnUpdate() {
ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
assertFalse(ctx.isUpdate());
assertNull(ctx.priorPhysicalId());
}
@Test
void resolveTagsKeepsTemplateOrderAndDefaultsAMissingValue() {
Map<String, String> tags = context(null).resolveTags(
props("""
{
"Tags": [
{"Key": "zeta", "Value": "z"},
{"Key": "alpha", "Value": "a"},
{"Key": "novalue"}
]
}
"""),
"Tags");
assertEquals(List.of("zeta", "alpha", "novalue"), List.copyOf(tags.keySet()),
"tag order follows the template, not hash order");
assertEquals("z", tags.get("zeta"));
assertEquals("", tags.get("novalue"), "a missing Value becomes empty, not null");
}
@Test
void resolveTagsSkipsBlankKeysAndNeverReturnsNull() {
Map<String, String> blankKeys = context(null).resolveTags(
props("""
{
"Tags": [
{"Key": "", "Value": "v"},
{"Key": " ", "Value": "v"},
{"Key": "ok", "Value": "v"}
]
}
"""),
"Tags");
assertEquals(Map.of("ok", "v"), blankKeys);
assertEquals(Map.of(), context(null).resolveTags(props("{}"), "Tags"),
"an absent property is an empty map");
assertEquals(Map.of(), context(null).resolveTags(props("""
{"Tags": "not-a-list"}
"""), "Tags"),
"a non-array property is an empty map");
assertEquals(Map.of(), context(null).resolveTags(null, "Tags"));
}
/**
* The whole property is handed to the engine, which is what lets an intrinsic wrapping the list
* work. Resolving only each entry would see an unresolved {@code Fn::If} object and yield
* nothing.
*/
@Test
void resolveTagsResolvesAnIntrinsicWrappingTheWholeList() {
JsonNode wrapped = props("""
{
"Tags": {
"Fn::If": [
"isProd",
[{"Key": "env", "Value": "prod"}],
[{"Key": "env", "Value": "dev"}]
]
}
}
""");
JsonNode chosenBranch = props("""
[{"Key": "env", "Value": "prod"}]
""");
when(engine.resolveNode(wrapped.get("Tags"))).thenReturn(chosenBranch);
assertEquals(Map.of("env", "prod"), context(null).resolveTags(wrapped, "Tags"));
}
}