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

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

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

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

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

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

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

No files matched your search

@@ -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.
*
* <p>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<String> 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<String> 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:<secret-id-or-arn>:SecretString:<json-key>:<stage>:<version>}}}
* and {@code {{resolve:ssm:<name>:<version>}}} / {@code {{resolve:ssm-secure:<name>:<version>}}},
* 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 = <secret-id-or-arn>:SecretString:<json-key>:<version-stage>:<version-id>. The
// secret id may be an ARN (which itself contains colons), so split on the ":SecretString"
// marker rather than on ":". AWS also accepts <secret-id-or-arn>:::: 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,
@@ -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.
*
* <p>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".
*
* <p>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<String> 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);
}
}
}
@@ -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.
*
* <p>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:<secret-id-or-arn>:SecretString:<json-key>:<stage>:<version>}}}
* and {@code {{resolve:ssm:<name>:<version>}}} / {@code {{resolve:ssm-secure:<name>:<version>}}},
* 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 = <secret-id-or-arn>:SecretString:<json-key>:<version-stage>:<version-id>. The
// secret id may be an ARN (which itself contains colons), so split on the ":SecretString"
// marker rather than on ":". AWS also accepts <secret-id-or-arn>:::: 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);
}
}
@@ -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<CfnResourceProvisioner> 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<String> 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);
}
}
@@ -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.
*
* <p>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.
*
* <p>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.
*
* <p>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<String, String> resolveTags(JsonNode props, String name) {
Map<String, String> 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) {