diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 5767ce0755..9289eacdf1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -14,6 +14,7 @@ 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.ProvisionContext; +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.Ec2SecurityGroupRuleCfnProvisioner; import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; @@ -175,6 +176,117 @@ public class CloudFormationResourceProvisioner { private static final String APIGATEWAY_V2_BODY_AUTHORIZER_IDS_ATTR = "__FlociApiGatewayV2BodyAuthorizerIds"; + /** + * Every resource type the switch in {@link #provision} still serves. Load-bearing: the + * default arm throws for a member of this set, so deleting an arm during the migration to + * per-service provisioners without deleting its entry here fails loudly instead of + * silently stubbing the resource. Kept in step with the registry by + * {@code CfnResourceInventoryTest}. + */ + /** + * Types whose delete needs the whole {@link StackResource} — a create-time attribute (the + * rule's event bus, the authorizer's api id, the nodegroup's cluster) or the stashed + * custom-resource properties. Deleting one of these from type and physical id alone silently + * no-ops and leaves the resource live, so they route through + * {@link #deleteUsingCreateTimeAttributes} instead. + * + *

Gates that method, so the set cannot drift from its branches. When one of these types + * moves to a per-service provisioner, its logic moves into that provisioner's + * {@code delete(StackResource, String)} override and its entry leaves this set; + * {@code CfnDeletePrecedenceTest} fails while both claim it. + */ + static final Set DELETE_NEEDS_STACK_RESOURCE = Set.of( + "AWS::ApiGatewayV2::Authorizer", + "AWS::CloudFormation::CustomResource", + "AWS::EKS::Nodegroup", + "AWS::Events::EventBus", + "AWS::Events::Rule", + "AWS::IAM::ManagedPolicy", + "AWS::IAM::Policy", + "AWS::SecretsManager::SecretTargetAttachment", + "Custom::DynamoDBReplica"); + + static final Set LEGACY_SWITCH_TYPES = Set.of( + "AWS::ApiGateway::Authorizer", + "AWS::ApiGateway::Deployment", + "AWS::ApiGateway::Method", + "AWS::ApiGateway::Resource", + "AWS::ApiGateway::RestApi", + "AWS::ApiGateway::Stage", + "AWS::ApiGatewayV2::Api", + "AWS::ApiGatewayV2::Authorizer", + "AWS::ApiGatewayV2::Deployment", + "AWS::ApiGatewayV2::Integration", + "AWS::ApiGatewayV2::Route", + "AWS::ApiGatewayV2::Stage", + "AWS::AutoScaling::AutoScalingGroup", + "AWS::AutoScaling::LaunchConfiguration", + "AWS::Batch::ComputeEnvironment", + "AWS::Batch::JobDefinition", + "AWS::Batch::JobQueue", + "AWS::CDK::Metadata", + "AWS::CloudFormation::CustomResource", + "AWS::CloudFront::Distribution", + "AWS::CloudWatch::Alarm", + "AWS::Cognito::UserPool", + "AWS::Cognito::UserPoolClient", + "AWS::DynamoDB::GlobalTable", + "AWS::DynamoDB::Table", + "AWS::EC2::EIP", + "AWS::EC2::Instance", + "AWS::EC2::InternetGateway", + "AWS::EC2::NatGateway", + "AWS::EC2::Route", + "AWS::EC2::RouteTable", + "AWS::EC2::SecurityGroup", + "AWS::EC2::Subnet", + "AWS::EC2::SubnetRouteTableAssociation", + "AWS::ECR::Repository", + "AWS::ECS::Cluster", + "AWS::ECS::Service", + "AWS::ECS::TaskDefinition", + "AWS::EKS::Cluster", + "AWS::EKS::Nodegroup", + "AWS::ElasticLoadBalancingV2::Listener", + "AWS::ElasticLoadBalancingV2::ListenerRule", + "AWS::ElasticLoadBalancingV2::LoadBalancer", + "AWS::ElasticLoadBalancingV2::TargetGroup", + "AWS::Events::EventBus", + "AWS::Events::EventBusPolicy", + "AWS::Events::Rule", + "AWS::IAM::AccessKey", + "AWS::IAM::InstanceProfile", + "AWS::IAM::ManagedPolicy", + "AWS::IAM::Policy", + "AWS::IAM::User", + "AWS::KMS::Alias", + "AWS::KMS::Key", + "AWS::Kinesis::Stream", + "AWS::KinesisFirehose::DeliveryStream", + "AWS::Lambda::EventSourceMapping", + "AWS::Lambda::Function", + "AWS::Lambda::LayerVersion", + "AWS::Logs::LogGroup", + "AWS::Pipes::Pipe", + "AWS::RDS::DBCluster", + "AWS::RDS::DBClusterParameterGroup", + "AWS::RDS::DBInstance", + "AWS::RDS::DBParameterGroup", + "AWS::RDS::DBProxy", + "AWS::RDS::DBProxyTargetGroup", + "AWS::RDS::DBSubnetGroup", + "AWS::Route53::HostedZone", + "AWS::Route53::RecordSet", + "AWS::S3::Bucket", + "AWS::S3::BucketPolicy", + "AWS::SNS::Subscription", + "AWS::SNS::Topic", + "AWS::SSM::Parameter", + "AWS::SecretsManager::Secret", + "AWS::SecretsManager::SecretTargetAttachment", + "AWS::StepFunctions::StateMachine", + "Custom::DynamoDBReplica"); + /** Reserved attribute keys used to carry custom-resource state to the later Delete invocation. */ private static final String CR_SERVICE_TOKEN_ATTR = "__FlociServiceToken"; private static final String CR_PROPERTIES_ATTR = "__FlociResourceProperties"; @@ -186,7 +298,6 @@ public class CloudFormationResourceProvisioner { private static final Duration CR_RESPONSE_TIMEOUT = Duration.ofSeconds(10); private final S3Service s3Service; - private final SqsService sqsService; private final SnsService snsService; private final DynamoDbService dynamoDbService; private final LambdaService lambdaService; @@ -222,10 +333,11 @@ public class CloudFormationResourceProvisioner { // below. As types migrate, their switch cases and provisionXxx methods are removed here; the // now-dead service deps above are cleared in the final cleanup once the switch is empty. private final CloudFormationResourceRegistry resourceRegistry; + private final CfnDynamicReferences dynamicReferences; private final EmulatorConfig config; @Inject - public CloudFormationResourceProvisioner(S3Service s3Service, SqsService sqsService, + public CloudFormationResourceProvisioner(S3Service s3Service, SnsService snsService, DynamoDbService dynamoDbService, LambdaService lambdaService, IamService iamService, SsmService ssmService, KmsService kmsService, @@ -255,10 +367,10 @@ public class CloudFormationResourceProvisioner { DocDbService docDbService, CloudFrontService cloudFrontService, CloudFormationResourceRegistry resourceRegistry, + CfnDynamicReferences dynamicReferences, EmulatorConfig config) { this.config = config; this.s3Service = s3Service; - this.sqsService = sqsService; this.snsService = snsService; this.dynamoDbService = dynamoDbService; this.lambdaService = lambdaService; @@ -291,6 +403,7 @@ public class CloudFormationResourceProvisioner { this.docDbService = docDbService; this.cloudFrontService = cloudFrontService; this.resourceRegistry = resourceRegistry; + this.dynamicReferences = dynamicReferences; } /** @@ -324,7 +437,7 @@ public class CloudFormationResourceProvisioner { CfnResourceProvisioner extracted = resourceRegistry.forType(resourceType).orElse(null); if (extracted != null) { extracted.provision(resource, properties, - new ProvisionContext(engine, region, accountId, stackName)); + new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId)); resource.setStatus("CREATE_COMPLETE"); return resource; } @@ -447,6 +560,14 @@ public class CloudFormationResourceProvisioner { default -> { if (resourceType != null && resourceType.startsWith("Custom::")) { provisionCustomResource(resource, properties, engine, region, accountId, stackName); + } else if (LEGACY_SWITCH_TYPES.contains(resourceType)) { + // A declared legacy type reaching the default arm means its case was removed + // without removing its LEGACY_SWITCH_TYPES entry (or without registering a + // provisioner). Stubbing it would report CREATE_COMPLETE with a fake ARN and + // hide the mistake, so fail instead. + throw new IllegalStateException("No switch arm for declared legacy type " + + resourceType + " — remove its LEGACY_SWITCH_TYPES entry when it " + + "moves to a per-service provisioner."); } else { LOG.debugv("Stubbing unsupported resource type: {0} ({1})", resourceType, logicalId); resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8)); @@ -501,6 +622,35 @@ public class CloudFormationResourceProvisioner { * type-keyed {@link #delete(String, String, String)}. */ public void delete(StackResource resource, String region) { + String resourceType = resource.getResourceType(); + // Registry first. An extracted provisioner owns its type outright, and gets the whole + // resource so an attribute-aware delete can read its create-time attributes. Consulting it + // ahead of the branches below means an exact match always beats the Custom:: prefix branch + // (so Custom::DynamoDBReplica can move to a provisioner), and that migrating one of the + // DELETE_NEEDS_STACK_RESOURCE types cannot silently keep using the stale branch here. + CfnResourceProvisioner extractedForDelete = resourceRegistry.forType(resourceType).orElse(null); + if (extractedForDelete != null) { + extractedForDelete.delete(resource, region); + return; + } + if (DELETE_NEEDS_STACK_RESOURCE.contains(resourceType)) { + deleteUsingCreateTimeAttributes(resource, region); + return; + } + if (resourceType != null && resourceType.startsWith("Custom::")) { + deleteCustomResource(resource, region); + return; + } + delete(resourceType, resource.getPhysicalId(), region); + } + + /** + * Deletes one of the {@link #DELETE_NEEDS_STACK_RESOURCE} types, whose delete needs state the + * type/physicalId path cannot supply — a create-time attribute, or the stashed custom-resource + * properties. Reached only through that set, so the set and these branches stay in step: a + * listed type with no branch throws rather than silently no-opping. + */ + private void deleteUsingCreateTimeAttributes(StackResource resource, String region) { String resourceType = resource.getResourceType(); // Custom::DynamoDBReplica is applied natively against the DynamoDB service (not via its // provider Lambda), so remove the replica the same way rather than invoking the handler. @@ -508,9 +658,7 @@ public class CloudFormationResourceProvisioner { deleteDynamoDbReplicaSafe(resource, region); return; } - boolean custom = "AWS::CloudFormation::CustomResource".equals(resourceType) - || (resourceType != null && resourceType.startsWith("Custom::")); - if (custom) { + if ("AWS::CloudFormation::CustomResource".equals(resourceType)) { deleteCustomResource(resource, region); return; } @@ -566,27 +714,13 @@ public class CloudFormationResourceProvisioner { deleteManagedPolicy(resource); return; } - // A Rule on a custom bus is keyed by that bus; the physical id is only the rule name, so the - // type/physicalId path resolves to the "default" bus and never finds it — leaving the rule (and - // then its bus) undeletable. Pass the bus name captured at provision time. - if ("AWS::Events::Rule".equals(resourceType)) { - deleteEventBridgeRuleSafe(resource.getPhysicalId(), - resource.getAttributes().get("EventBusName"), region); - return; - } if ("AWS::Events::EventBus".equals(resourceType)) { deleteEventBusSafe(resource, region); return; } - // Extracted provisioners get the whole resource, so the ones whose delete needs more than - // the physical id can read their create-time attributes instead of guessing. Placed after - // the special cases above so extracting one of those types later cannot silently bypass them. - CfnResourceProvisioner extractedForDelete = resourceRegistry.forType(resourceType).orElse(null); - if (extractedForDelete != null) { - extractedForDelete.delete(resource, region); - return; - } - delete(resourceType, resource.getPhysicalId(), region); + throw new IllegalStateException("DELETE_NEEDS_STACK_RESOURCE lists " + resourceType + + " but no branch here deletes it — deleting it by physical id alone would " + + "silently no-op and leave the resource live."); } /** @@ -7236,194 +7370,12 @@ public class CloudFormationResourceProvisioner { return engine.resolve(props.get(name)); } - private static final Pattern DYNAMIC_REF = Pattern.compile("\\{\\{resolve:([a-z-]+):(.*?)\\}\\}"); - private static final Pattern SSM_DYNAMIC_REF_BODY = - Pattern.compile("([a-zA-Z0-9_.\\-/]+)(?::([0-9]+))?"); - /** - * Resolves CloudFormation dynamic references embedded in a string. Supports - * {@code {{resolve:secretsmanager::SecretString:::}}} - * and {@code {{resolve:ssm::}}} / {@code {{resolve:ssm-secure::}}}, - * which CloudFormation substitutes with the live value at deploy time (e.g. an RDS - * MasterUserPassword sourced from a generated secret). Unsupported services are left verbatim. + * Resolves CloudFormation dynamic references in a provisioned property value. Delegates to + * {@link CfnDynamicReferences}; the RDS master-credential paths are its only callers today. */ private String resolveDynamicReferences(String value, String region, boolean allowSsmSecure) { - if (value == null || !value.contains("{{resolve:")) { - return value; - } - Matcher m = DYNAMIC_REF.matcher(value); - StringBuilder sb = new StringBuilder(); - int previousEnd = 0; - while (m.find()) { - rejectUnclosedDynamicReference(value.substring(previousEnd, m.start())); - String replacement = resolveDynamicRef(m.group(1), m.group(2), region, allowSsmSecure); - m.appendReplacement(sb, Matcher.quoteReplacement(replacement)); - previousEnd = m.end(); - } - rejectUnclosedDynamicReference(value.substring(previousEnd)); - m.appendTail(sb); - return sb.toString(); - } - - private String resolveDynamicRef(String service, String body, String region, boolean allowSsmSecure) { - if ("secretsmanager".equals(service)) { - // body = :SecretString:::. The - // secret id may be an ARN (which itself contains colons), so split on the ":SecretString" - // marker rather than on ":". AWS also accepts :::: as shorthand for - // retrieving the whole current SecretString with the optional fields omitted. - String secretId; - String[] parts; - if (body.endsWith("::::")) { - secretId = body.substring(0, body.length() - 4); - parts = new String[0]; - } else if (isValidSecretsManagerSecretId(body)) { - secretId = body; - parts = new String[0]; - } else { - int marker = body.lastIndexOf(":SecretString"); - if (marker < 0) { - throw invalidSecretsManagerDynamicReference(); - } - secretId = body.substring(0, marker); - String rest = body.substring(marker + ":SecretString".length()); - if (!rest.isEmpty() && !rest.startsWith(":")) { - throw invalidSecretsManagerDynamicReference(); - } - parts = rest.startsWith(":") - ? rest.substring(1).split(":", -1) - : new String[0]; - } - if (!isValidSecretsManagerSecretId(secretId) || parts.length > 3) { - throw invalidSecretsManagerDynamicReference(); - } - String jsonKey = parts.length > 0 ? parts[0] : ""; - String versionStage = parts.length > 1 && !parts[1].isBlank() ? parts[1] : null; - String versionId = parts.length > 2 && !parts[2].isBlank() ? parts[2] : null; - if (versionStage != null && versionId != null) { - throw new AwsException("ValidationError", - "version-stage and version-id cannot both be specified", 400); - } - String secretRegion = AwsArnUtils.regionOrDefault(secretId, region); - String secretString = secretsManagerService - .getSecretValue(secretId, versionId, versionStage, secretRegion).getSecretString(); - if (secretString == null) { - // A binary-only secret has no SecretString to substitute, so resource creation fails. - throw new IllegalStateException( - "secret " + secretId + " has no SecretString value to resolve"); - } - if (jsonKey.isBlank()) { - return secretString; - } - JsonNode json; - try { - json = objectMapper.readTree(secretString); - } catch (Exception e) { - throw new AwsException("ValidationError", - "secret " + secretId + " does not contain valid JSON", 400); - } - if (!json.has(jsonKey)) { - // A missing key would otherwise resolve to "" — silently provisioning e.g. a blank - // MasterUserPassword. Fail resource creation instead. - throw new IllegalStateException( - "JSON key '" + jsonKey + "' not found in secret " + secretId); - } - return json.get(jsonKey).asText(); - } - if ("ssm".equals(service) || "ssm-secure".equals(service)) { - if ("ssm-secure".equals(service) && !allowSsmSecure) { - throw new AwsException("ValidationError", - "ssm-secure dynamic references are supported only for MasterUserPassword " - + "on AWS::RDS::DBInstance and AWS::RDS::DBCluster", 400); - } - Matcher reference = SSM_DYNAMIC_REF_BODY.matcher(body); - if (!reference.matches()) { - throw invalidSsmDynamicReference(); - } - String parameterName = reference.group(1); - String version = reference.group(2); - if (version != null) { - long wantedVersion; - try { - wantedVersion = Long.parseLong(version); - } catch (NumberFormatException e) { - throw new AwsException("ValidationError", - "SSM parameter version must be a positive integer: " + version, 400); - } - if (wantedVersion < 1) { - throw new AwsException("ValidationError", - "SSM parameter version must be a positive integer: " + version, 400); - } - ParameterHistory parameter = ssmService.getParameterHistory(parameterName, region).stream() - .filter(h -> h.getVersion() == wantedVersion) - .findFirst() - .orElseThrow(() -> new AwsException( - "ParameterVersionNotFound", - "Parameter version " + wantedVersion + " not found.", 400)); - return validatedSsmParameterValue( - service, parameterName, parameter.getType(), parameter.getValue()); - } - Parameter parameter = ssmService.getParameter(parameterName, region); - return validatedSsmParameterValue( - service, parameterName, parameter.getType(), parameter.getValue()); - } - // Other dynamic-reference services are not resolved here; leave verbatim. - return "{{resolve:" + service + ":" + body + "}}"; - } - - private static boolean isValidSecretsManagerSecretId(String secretId) { - if (secretId == null || secretId.isBlank()) { - return false; - } - if (!secretId.contains(":")) { - return true; - } - try { - AwsArnUtils.Arn arn = AwsArnUtils.parse(secretId); - String resource = arn.resource(); - return "secretsmanager".equals(arn.service()) - && !arn.region().isBlank() - && !arn.accountId().isBlank() - && resource.startsWith("secret:") - && resource.length() > "secret:".length() - && !resource.substring("secret:".length()).contains(":"); - } catch (IllegalArgumentException e) { - return false; - } - } - - private static AwsException invalidSecretsManagerDynamicReference() { - return new AwsException("ValidationError", - "Invalid Secrets Manager dynamic reference", 400); - } - - private static void rejectUnclosedDynamicReference(String value) { - if (value.contains("{{resolve:secretsmanager:")) { - throw invalidSecretsManagerDynamicReference(); - } - if (value.contains("{{resolve:ssm:") || value.contains("{{resolve:ssm-secure:")) { - throw invalidSsmDynamicReference(); - } - } - - private static String validatedSsmParameterValue( - String service, String parameterName, String parameterType, String value) { - boolean validType = "ssm-secure".equals(service) - ? "SecureString".equals(parameterType) - : "String".equals(parameterType) || "StringList".equals(parameterType); - if (!validType) { - String expectedType = "ssm-secure".equals(service) - ? "SecureString" - : "String or StringList"; - throw new AwsException("ValidationError", - "SSM parameter " + parameterName + " must be type " + expectedType - + " for an " + service + " dynamic reference", 400); - } - return value; - } - - private static AwsException invalidSsmDynamicReference() { - return new AwsException("ValidationError", - "Invalid SSM dynamic reference", 400); + return dynamicReferences.resolveDynamicReferences(value, region, allowSsmSecure); } private String resolveOrDefault(JsonNode props, String name, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDeletes.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDeletes.java new file mode 100644 index 0000000000..5973f2f4bc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDeletes.java @@ -0,0 +1,47 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import io.github.hectorvent.floci.core.common.AwsException; +import org.jboss.logging.Logger; + +import java.util.Set; + +/** + * Delete helpers shared by extracted provisioners. + * + *

A static utility rather than something on {@link ProvisionContext}, because the id-only + * {@code CfnResourceProvisioner#delete(String, String, String)} never receives a context. + */ +public final class CfnDeletes { + + private static final Logger LOG = Logger.getLogger(CfnDeletes.class); + + private CfnDeletes() { + } + + /** + * Runs a delete, treating only the named AWS error codes as "already gone". + * + *

The tolerated codes are explicit on purpose. Stack deletion reports DELETE_FAILED when a + * delete throws, which is how a real failure such as {@code BucketNotEmpty} reaches the user; a + * helper that swallowed every exception would turn those into stacks that report a clean + * deletion while the resource is still there. Pass exactly the not-found code the service + * raises when the resource has already been removed, and let everything else propagate. + * + * @param description what is being deleted, for the debug log (for example {@code "DB proxy"}) + * @param physicalId the resource being deleted, for the debug log + * @param delete the delete call itself + * @param tolerateErrorCodes AWS error codes meaning the resource is already gone + */ + public static void safeDelete(String description, String physicalId, Runnable delete, + String... tolerateErrorCodes) { + Set tolerated = Set.of(tolerateErrorCodes); + try { + delete.run(); + } catch (AwsException e) { + if (!tolerated.contains(e.getErrorCode())) { + throw e; + } + LOG.debugv("{0} already gone, treating as deleted: {1}", description, physicalId); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDynamicReferences.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDynamicReferences.java new file mode 100644 index 0000000000..25477a61ac --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDynamicReferences.java @@ -0,0 +1,230 @@ +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.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService; +import io.github.hectorvent.floci.services.ssm.SsmService; +import io.github.hectorvent.floci.services.ssm.model.Parameter; +import io.github.hectorvent.floci.services.ssm.model.ParameterHistory; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Resolves CloudFormation dynamic references ({@code {{resolve:secretsmanager:...}}}, + * {@code {{resolve:ssm:...}}}, {@code {{resolve:ssm-secure:...}}}) against the live services. + * + *

This is CloudFormation-wide behaviour that happens to be reached only from RDS today, and it + * needs both Secrets Manager and SSM. Keeping it here rather than inside a per-service provisioner + * lets {@code RdsCfnProvisioner} inject one collaborator instead of two unrelated services, and + * lets any later provisioner reuse it without copying ~190 lines. + */ +@ApplicationScoped +public class CfnDynamicReferences { + + private final SecretsManagerService secretsManagerService; + private final SsmService ssmService; + private final ObjectMapper objectMapper; + + @Inject + public CfnDynamicReferences(SecretsManagerService secretsManagerService, SsmService ssmService, + ObjectMapper objectMapper) { + this.secretsManagerService = secretsManagerService; + this.ssmService = ssmService; + this.objectMapper = objectMapper; + } + + private static final Pattern DYNAMIC_REF = Pattern.compile("\\{\\{resolve:([a-z-]+):(.*?)\\}\\}"); + private static final Pattern SSM_DYNAMIC_REF_BODY = + Pattern.compile("([a-zA-Z0-9_.\\-/]+)(?::([0-9]+))?"); + + /** + * Resolves CloudFormation dynamic references embedded in a string. Supports + * {@code {{resolve:secretsmanager::SecretString:::}}} + * and {@code {{resolve:ssm::}}} / {@code {{resolve:ssm-secure::}}}, + * which CloudFormation substitutes with the live value at deploy time (e.g. an RDS + * MasterUserPassword sourced from a generated secret). Unsupported services are left verbatim. + */ + public String resolveDynamicReferences(String value, String region, boolean allowSsmSecure) { + if (value == null || !value.contains("{{resolve:")) { + return value; + } + Matcher m = DYNAMIC_REF.matcher(value); + StringBuilder sb = new StringBuilder(); + int previousEnd = 0; + while (m.find()) { + rejectUnclosedDynamicReference(value.substring(previousEnd, m.start())); + String replacement = resolveDynamicRef(m.group(1), m.group(2), region, allowSsmSecure); + m.appendReplacement(sb, Matcher.quoteReplacement(replacement)); + previousEnd = m.end(); + } + rejectUnclosedDynamicReference(value.substring(previousEnd)); + m.appendTail(sb); + return sb.toString(); + } + + private String resolveDynamicRef(String service, String body, String region, boolean allowSsmSecure) { + if ("secretsmanager".equals(service)) { + // body = :SecretString:::. The + // secret id may be an ARN (which itself contains colons), so split on the ":SecretString" + // marker rather than on ":". AWS also accepts :::: as shorthand for + // retrieving the whole current SecretString with the optional fields omitted. + String secretId; + String[] parts; + if (body.endsWith("::::")) { + secretId = body.substring(0, body.length() - 4); + parts = new String[0]; + } else if (isValidSecretsManagerSecretId(body)) { + secretId = body; + parts = new String[0]; + } else { + int marker = body.lastIndexOf(":SecretString"); + if (marker < 0) { + throw invalidSecretsManagerDynamicReference(); + } + secretId = body.substring(0, marker); + String rest = body.substring(marker + ":SecretString".length()); + if (!rest.isEmpty() && !rest.startsWith(":")) { + throw invalidSecretsManagerDynamicReference(); + } + parts = rest.startsWith(":") + ? rest.substring(1).split(":", -1) + : new String[0]; + } + if (!isValidSecretsManagerSecretId(secretId) || parts.length > 3) { + throw invalidSecretsManagerDynamicReference(); + } + String jsonKey = parts.length > 0 ? parts[0] : ""; + String versionStage = parts.length > 1 && !parts[1].isBlank() ? parts[1] : null; + String versionId = parts.length > 2 && !parts[2].isBlank() ? parts[2] : null; + if (versionStage != null && versionId != null) { + throw new AwsException("ValidationError", + "version-stage and version-id cannot both be specified", 400); + } + String secretRegion = AwsArnUtils.regionOrDefault(secretId, region); + String secretString = secretsManagerService + .getSecretValue(secretId, versionId, versionStage, secretRegion).getSecretString(); + if (secretString == null) { + // A binary-only secret has no SecretString to substitute, so resource creation fails. + throw new IllegalStateException( + "secret " + secretId + " has no SecretString value to resolve"); + } + if (jsonKey.isBlank()) { + return secretString; + } + JsonNode json; + try { + json = objectMapper.readTree(secretString); + } catch (Exception e) { + throw new AwsException("ValidationError", + "secret " + secretId + " does not contain valid JSON", 400); + } + if (!json.has(jsonKey)) { + // A missing key would otherwise resolve to "" — silently provisioning e.g. a blank + // MasterUserPassword. Fail resource creation instead. + throw new IllegalStateException( + "JSON key '" + jsonKey + "' not found in secret " + secretId); + } + return json.get(jsonKey).asText(); + } + if ("ssm".equals(service) || "ssm-secure".equals(service)) { + if ("ssm-secure".equals(service) && !allowSsmSecure) { + throw new AwsException("ValidationError", + "ssm-secure dynamic references are supported only for MasterUserPassword " + + "on AWS::RDS::DBInstance and AWS::RDS::DBCluster", 400); + } + Matcher reference = SSM_DYNAMIC_REF_BODY.matcher(body); + if (!reference.matches()) { + throw invalidSsmDynamicReference(); + } + String parameterName = reference.group(1); + String version = reference.group(2); + if (version != null) { + long wantedVersion; + try { + wantedVersion = Long.parseLong(version); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", + "SSM parameter version must be a positive integer: " + version, 400); + } + if (wantedVersion < 1) { + throw new AwsException("ValidationError", + "SSM parameter version must be a positive integer: " + version, 400); + } + ParameterHistory parameter = ssmService.getParameterHistory(parameterName, region).stream() + .filter(h -> h.getVersion() == wantedVersion) + .findFirst() + .orElseThrow(() -> new AwsException( + "ParameterVersionNotFound", + "Parameter version " + wantedVersion + " not found.", 400)); + return validatedSsmParameterValue( + service, parameterName, parameter.getType(), parameter.getValue()); + } + Parameter parameter = ssmService.getParameter(parameterName, region); + return validatedSsmParameterValue( + service, parameterName, parameter.getType(), parameter.getValue()); + } + // Other dynamic-reference services are not resolved here; leave verbatim. + return "{{resolve:" + service + ":" + body + "}}"; + } + + private static boolean isValidSecretsManagerSecretId(String secretId) { + if (secretId == null || secretId.isBlank()) { + return false; + } + if (!secretId.contains(":")) { + return true; + } + try { + AwsArnUtils.Arn arn = AwsArnUtils.parse(secretId); + String resource = arn.resource(); + return "secretsmanager".equals(arn.service()) + && !arn.region().isBlank() + && !arn.accountId().isBlank() + && resource.startsWith("secret:") + && resource.length() > "secret:".length() + && !resource.substring("secret:".length()).contains(":"); + } catch (IllegalArgumentException e) { + return false; + } + } + + private static AwsException invalidSecretsManagerDynamicReference() { + return new AwsException("ValidationError", + "Invalid Secrets Manager dynamic reference", 400); + } + + private static void rejectUnclosedDynamicReference(String value) { + if (value.contains("{{resolve:secretsmanager:")) { + throw invalidSecretsManagerDynamicReference(); + } + if (value.contains("{{resolve:ssm:") || value.contains("{{resolve:ssm-secure:")) { + throw invalidSsmDynamicReference(); + } + } + + private static String validatedSsmParameterValue( + String service, String parameterName, String parameterType, String value) { + boolean validType = "ssm-secure".equals(service) + ? "SecureString".equals(parameterType) + : "String".equals(parameterType) || "StringList".equals(parameterType); + if (!validType) { + String expectedType = "ssm-secure".equals(service) + ? "SecureString" + : "String or StringList"; + throw new AwsException("ValidationError", + "SSM parameter " + parameterName + " must be type " + expectedType + + " for an " + service + " dynamic reference", 400); + } + return value; + } + + private static AwsException invalidSsmDynamicReference() { + return new AwsException("ValidationError", + "Invalid SSM dynamic reference", 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java index 5af5febeca..757918bf9a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFormationResourceRegistry.java @@ -8,6 +8,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; +import java.util.Set; /** * Maps a CloudFormation resource type to the {@link CfnResourceProvisioner} that serves it. @@ -43,4 +44,28 @@ public class CloudFormationResourceRegistry { public Optional forType(String resourceType) { return Optional.ofNullable(byType.get(resourceType)); } + + /** + * Every resource type served by an extracted provisioner, as resolved by CDI. Read by the + * inventory test: a provisioner missing {@code @ApplicationScoped} compiles and unit-tests + * green but never reaches this map, so only the discovered set can catch it. + */ + public Set registeredTypes() { + return Set.copyOf(byType.keySet()); + } + + /** + * The provisioner class serving {@code resourceType}, or null when none does. Under CDI the + * instance is an ArC client proxy ({@code SqsCfnProvisioner_ClientProxy}), so the generated + * suffix is trimmed to leave the authored class name. + */ + public String ownerOf(String resourceType) { + CfnResourceProvisioner provisioner = byType.get(resourceType); + if (provisioner == null) { + return null; + } + String name = provisioner.getClass().getSimpleName(); + int generatedSuffix = name.indexOf('_'); + return generatedSuffix < 0 ? name : name.substring(0, generatedSuffix); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java index a600eb60fa..a85e520e9e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java @@ -4,7 +4,9 @@ import com.fasterxml.jackson.databind.JsonNode; import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.UUID; /** @@ -14,7 +16,61 @@ import java.util.UUID; * so extracted provisioners produce byte-identical physical ids and resolved values. */ public record ProvisionContext(CloudFormationTemplateEngine engine, String region, - String accountId, String stackName) { + String accountId, String stackName, String priorPhysicalId) { + + /** A context for a first-time create, with no prior physical id. */ + public ProvisionContext(CloudFormationTemplateEngine engine, String region, + String accountId, String stackName) { + this(engine, region, accountId, stackName, null); + } + + /** + * Whether this logical resource already had a physical id from an earlier successful provision, + * i.e. {@code provision} is running as the update path rather than the create path. + * + *

Captured when the context is built rather than read from the {@code StackResource}, + * because {@code provision} assigns the new physical id onto that resource as it works: a + * resource-derived check flips from false to true mid-method and silently changes meaning. + * + *

Two things this does not mean. It is not "the stack is being updated" (a resource added by + * an UpdateStack reads false, correctly). And it is not "AWS would update rather than replace" + * — a replacing update still arrives here with the old physical id, so a provisioner treating + * this as "reuse the existing entity" must still reject or replace on createOnly properties. + */ + public boolean isUpdate() { + return priorPhysicalId != null && !priorPhysicalId.isBlank(); + } + + /** + * Resolves a CloudFormation {@code [{Key, Value}]} tag list to a map, preserving template + * order. The whole node is resolved first so an {@code Fn::If} wrapping the list works, not + * just intrinsics inside each entry. Entries whose key resolves blank are skipped and a + * missing value becomes {@code ""}; an absent or non-array property yields an empty map, never + * null. + * + *

Deliberately does not validate. Callers needing AWS's tag rules (the 50-tag cap, the + * reserved {@code aws:} prefix) keep their own validating parse, and callers using null to mean + * "the template said nothing, leave stored tags alone" must keep that distinction themselves. + */ + public Map resolveTags(JsonNode props, String name) { + Map tags = new LinkedHashMap<>(); + if (props == null || !props.has(name)) { + return tags; + } + JsonNode resolved = engine.resolveNode(props.get(name)); + if (resolved == null || !resolved.isArray()) { + return tags; + } + for (JsonNode tag : resolved) { + String key = engine.resolve(tag.path("Key")); + if (key == null || key.isBlank()) { + continue; + } + String value = engine.resolve(tag.path("Value")); + tags.put(key, value == null ? "" : value); + } + return tags; + } /** Resolves an optional property through the engine, or null when absent/explicitly null. */ public String resolveOptional(JsonNode props, String name) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java index 15c3ef4867..0d01ab1fe3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnDeletePrecedenceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnDeletePrecedenceTest.java new file mode 100644 index 0000000000..85e70a76e0 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnDeletePrecedenceTest.java @@ -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}. + * + *

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. + * + *

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 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 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); + } +} 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 new file mode 100644 index 0000000000..40ff2b54e7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -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. + * + *

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. + * + *

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); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnResourceInventoryTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnResourceInventoryTest.java new file mode 100644 index 0000000000..a1fe13c8fb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnResourceInventoryTest.java @@ -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. + * + *

This is the guard for the per-service provisioner migration. {@code provision}'s default arm + * stubs an unknown type with {@code arn:aws:stub:::} 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. + * + *

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 TYPES_WITHOUT_SCHEMA = Set.of("AWS::CDK::Metadata"); + + @Inject + CloudFormationResourceRegistry registry; + + @Test + void inventoryMatchesTheRegistryAndTheLegacySwitch() { + Map 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 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 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 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 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 readInventory() { + try { + Map 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 'typeowner' 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 rows) { + return rows.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(e -> e.getKey() + "\t" + e.getValue()) + .collect(Collectors.joining("\n")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java index 9019ce5078..b1b11250a2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java index 4ada05d9f2..d49f64ba08 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2ProvisionerTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java index 71caafd696..69ec475559 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLegacyNameModeTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLegacyNameModeTest.java index 7885418ae5..34ed7186fe 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLegacyNameModeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLegacyNameModeTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java index effd03a743..222c68ad5a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLogGroupProvisionerTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProviderFrameworkTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProviderFrameworkTest.java index 977b75a50a..6772b04c4a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProviderFrameworkTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProviderFrameworkTest.java @@ -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() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java index 32c6e4265f..4a9230e445 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java @@ -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() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbReplicaCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbReplicaCfnProvisionerTest.java index 1aab4c9d8f..64649172f7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbReplicaCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbReplicaCfnProvisionerTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbStreamSpecificationCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbStreamSpecificationCfnProvisionerTest.java index 407e227742..2a2e2f3682 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbStreamSpecificationCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/DynamoDbStreamSpecificationCfnProvisionerTest.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java index bdf0b8997c..cf2eedaae4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java index 8ae60484d4..5284565cee 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java @@ -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(); } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java index 33c929b286..868b1f4ee6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java @@ -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() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java index 5622981cde..f6d85a119a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDeletesTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDeletesTest.java new file mode 100644 index 0000000000..f4686253b3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnDeletesTest.java @@ -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")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java new file mode 100644 index 0000000000..9fa282ea8a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java @@ -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 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 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")); + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv new file mode 100644 index 0000000000..58a30b7cf9 --- /dev/null +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -0,0 +1,112 @@ +AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner +AWS::ApiGateway::Authorizer LEGACY_SWITCH +AWS::ApiGateway::Deployment LEGACY_SWITCH +AWS::ApiGateway::Method LEGACY_SWITCH +AWS::ApiGateway::Resource LEGACY_SWITCH +AWS::ApiGateway::RestApi LEGACY_SWITCH +AWS::ApiGateway::Stage LEGACY_SWITCH +AWS::ApiGatewayV2::Api LEGACY_SWITCH +AWS::ApiGatewayV2::Authorizer LEGACY_SWITCH +AWS::ApiGatewayV2::Deployment LEGACY_SWITCH +AWS::ApiGatewayV2::Integration LEGACY_SWITCH +AWS::ApiGatewayV2::Route LEGACY_SWITCH +AWS::ApiGatewayV2::Stage LEGACY_SWITCH +AWS::AutoScaling::AutoScalingGroup LEGACY_SWITCH +AWS::AutoScaling::LaunchConfiguration LEGACY_SWITCH +AWS::AutoScaling::LifecycleHook AutoScalingLifecycleHookCfnProvisioner +AWS::Batch::ComputeEnvironment LEGACY_SWITCH +AWS::Batch::JobDefinition LEGACY_SWITCH +AWS::Batch::JobQueue LEGACY_SWITCH +AWS::CDK::Metadata LEGACY_SWITCH +AWS::CloudFormation::CustomResource LEGACY_SWITCH +AWS::CloudFront::Distribution LEGACY_SWITCH +AWS::CloudWatch::Alarm LEGACY_SWITCH +AWS::CodeBuild::Project CodeBuildCfnProvisioner +AWS::CodePipeline::CustomActionType CodePipelineCfnProvisioner +AWS::CodePipeline::Pipeline CodePipelineCfnProvisioner +AWS::CodePipeline::Webhook CodePipelineCfnProvisioner +AWS::Cognito::UserPool LEGACY_SWITCH +AWS::Cognito::UserPoolClient LEGACY_SWITCH +AWS::Config::ConfigRule ConfigCfnProvisioner +AWS::DynamoDB::GlobalTable LEGACY_SWITCH +AWS::DynamoDB::Table LEGACY_SWITCH +AWS::EC2::EIP LEGACY_SWITCH +AWS::EC2::FlowLog Ec2FlowLogCfnProvisioner +AWS::EC2::Instance LEGACY_SWITCH +AWS::EC2::InternetGateway LEGACY_SWITCH +AWS::EC2::LaunchTemplate Ec2LaunchTemplateCfnProvisioner +AWS::EC2::NatGateway LEGACY_SWITCH +AWS::EC2::NetworkAcl Ec2NetworkAclCfnProvisioner +AWS::EC2::NetworkAclEntry Ec2NetworkAclCfnProvisioner +AWS::EC2::Route LEGACY_SWITCH +AWS::EC2::RouteTable LEGACY_SWITCH +AWS::EC2::SecurityGroup LEGACY_SWITCH +AWS::EC2::SecurityGroupEgress Ec2SecurityGroupRuleCfnProvisioner +AWS::EC2::SecurityGroupIngress Ec2SecurityGroupRuleCfnProvisioner +AWS::EC2::Subnet LEGACY_SWITCH +AWS::EC2::SubnetNetworkAclAssociation Ec2NetworkAclCfnProvisioner +AWS::EC2::SubnetRouteTableAssociation LEGACY_SWITCH +AWS::EC2::VPC Ec2VpcCfnProvisioner +AWS::EC2::VPCEndpoint Ec2VpcEndpointCfnProvisioner +AWS::EC2::VPCGatewayAttachment Ec2VpcGatewayAttachmentCfnProvisioner +AWS::ECR::Repository LEGACY_SWITCH +AWS::ECS::CapacityProvider EcsCapacityCfnProvisioner +AWS::ECS::Cluster LEGACY_SWITCH +AWS::ECS::ClusterCapacityProviderAssociations EcsCapacityCfnProvisioner +AWS::ECS::Service LEGACY_SWITCH +AWS::ECS::TaskDefinition LEGACY_SWITCH +AWS::EKS::Cluster LEGACY_SWITCH +AWS::EKS::Nodegroup LEGACY_SWITCH +AWS::ElasticLoadBalancingV2::Listener LEGACY_SWITCH +AWS::ElasticLoadBalancingV2::ListenerRule LEGACY_SWITCH +AWS::ElasticLoadBalancingV2::LoadBalancer LEGACY_SWITCH +AWS::ElasticLoadBalancingV2::TargetGroup LEGACY_SWITCH +AWS::Events::EventBus LEGACY_SWITCH +AWS::Events::EventBusPolicy LEGACY_SWITCH +AWS::Events::Rule LEGACY_SWITCH +AWS::IAM::AccessKey LEGACY_SWITCH +AWS::IAM::InstanceProfile LEGACY_SWITCH +AWS::IAM::ManagedPolicy LEGACY_SWITCH +AWS::IAM::Policy LEGACY_SWITCH +AWS::IAM::Role IamRoleCfnProvisioner +AWS::IAM::User LEGACY_SWITCH +AWS::KMS::Alias LEGACY_SWITCH +AWS::KMS::Key LEGACY_SWITCH +AWS::Kinesis::Stream LEGACY_SWITCH +AWS::KinesisFirehose::DeliveryStream LEGACY_SWITCH +AWS::Lambda::Alias LambdaVersionAliasCfnProvisioner +AWS::Lambda::EventSourceMapping LEGACY_SWITCH +AWS::Lambda::Function LEGACY_SWITCH +AWS::Lambda::LayerVersion LEGACY_SWITCH +AWS::Lambda::MicrovmImage LambdaMicrovmsCfnProvisioner +AWS::Lambda::NetworkConnector LambdaMicrovmsCfnProvisioner +AWS::Lambda::Permission LambdaAddressingCfnProvisioner +AWS::Lambda::Version LambdaVersionAliasCfnProvisioner +AWS::Logs::LogGroup LEGACY_SWITCH +AWS::Organizations::Account OrganizationsCfnProvisioner +AWS::Organizations::Organization OrganizationsCfnProvisioner +AWS::Organizations::OrganizationalUnit OrganizationsCfnProvisioner +AWS::Organizations::Policy OrganizationsCfnProvisioner +AWS::Organizations::ResourcePolicy OrganizationsCfnProvisioner +AWS::Pipes::Pipe LEGACY_SWITCH +AWS::RDS::DBCluster LEGACY_SWITCH +AWS::RDS::DBClusterParameterGroup LEGACY_SWITCH +AWS::RDS::DBInstance LEGACY_SWITCH +AWS::RDS::DBParameterGroup LEGACY_SWITCH +AWS::RDS::DBProxy LEGACY_SWITCH +AWS::RDS::DBProxyTargetGroup LEGACY_SWITCH +AWS::RDS::DBSubnetGroup LEGACY_SWITCH +AWS::Route53::HostedZone LEGACY_SWITCH +AWS::Route53::RecordSet LEGACY_SWITCH +AWS::S3::Bucket LEGACY_SWITCH +AWS::S3::BucketPolicy LEGACY_SWITCH +AWS::SNS::Subscription LEGACY_SWITCH +AWS::SNS::Topic LEGACY_SWITCH +AWS::SQS::Queue SqsCfnProvisioner +AWS::SQS::QueuePolicy SqsCfnProvisioner +AWS::SSM::Parameter LEGACY_SWITCH +AWS::SecretsManager::Secret LEGACY_SWITCH +AWS::SecretsManager::SecretTargetAttachment LEGACY_SWITCH +AWS::StepFunctions::StateMachine LEGACY_SWITCH +AWS::WAFv2::WebACL WafV2CfnProvisioner +Custom::DynamoDBReplica LEGACY_SWITCH