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 0700e3e4ea..770aac56b3 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 @@ -207,13 +207,6 @@ public class CloudFormationResourceProvisioner { "AWS::IAM::Policy", "AWS::Lambda::Function", "AWS::Lambda::LayerVersion", - "AWS::RDS::DBCluster", - "AWS::RDS::DBClusterParameterGroup", - "AWS::RDS::DBInstance", - "AWS::RDS::DBParameterGroup", - "AWS::RDS::DBProxy", - "AWS::RDS::DBProxyTargetGroup", - "AWS::RDS::DBSubnetGroup", "AWS::Route53::RecordSet", "AWS::SecretsManager::Secret", "AWS::SecretsManager::SecretTargetAttachment", @@ -389,18 +382,6 @@ public class CloudFormationResourceProvisioner { // fake physical id. Topological ordering guarantees parents are provisioned first. case "AWS::EC2::SecurityGroup" -> provisionSecurityGroup(resource, properties, engine, region, stackName); case "AWS::EC2::Instance" -> provisionEc2Instance(resource, properties, engine, region); - // RDS. DBInstance/DBCluster start real RDS containers (same as the direct API). - case "AWS::RDS::DBSubnetGroup" -> provisionDbSubnetGroup(resource, properties, engine, stackName, region); - case "AWS::RDS::DBParameterGroup" -> - provisionDbParameterGroup(resource, properties, engine, stackName, region); - case "AWS::RDS::DBClusterParameterGroup" -> - provisionDbClusterParameterGroup( - resource, properties, engine, stackName, region); - case "AWS::RDS::DBInstance" -> provisionDbInstance(resource, properties, engine, stackName, region); - case "AWS::RDS::DBCluster" -> provisionDbCluster(resource, properties, engine, stackName, region); - case "AWS::RDS::DBProxy" -> provisionDbProxy(resource, properties, engine, region); - case "AWS::RDS::DBProxyTargetGroup" -> - provisionDbProxyTargetGroup(resource, properties, engine, region); case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName); case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName); case "AWS::AutoScaling::LaunchConfiguration" -> @@ -641,16 +622,6 @@ public class CloudFormationResourceProvisioner { case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region); case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId); case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId)); - case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId, region); - case "AWS::RDS::DBCluster" -> rdsService.deleteDbCluster(physicalId, region); - case "AWS::RDS::DBProxy" -> deleteDbProxySafe(physicalId, region); - case "AWS::RDS::DBProxyTargetGroup" -> clearDbProxyTargetGroupSafe(physicalId, region); - case "AWS::RDS::DBSubnetGroup" -> - rdsService.deleteDbSubnetGroup(physicalId, region); - case "AWS::RDS::DBParameterGroup" -> - rdsService.deleteDbParameterGroup(physicalId, region); - case "AWS::RDS::DBClusterParameterGroup" -> - rdsService.deleteDbClusterParameterGroup(physicalId, region); case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId); case "AWS::AutoScaling::LaunchConfiguration" -> autoScalingService.deleteLaunchConfiguration(region, physicalId); @@ -1110,110 +1081,6 @@ public class CloudFormationResourceProvisioner { } } - // ── RDS ───────────────────────────────────────────────────────────────────── - - private void provisionDbSubnetGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String stackName, String region) { - String explicitName = resolveOptional(props, "DBSubnetGroupName", engine); - String priorPhysicalId = r.getPhysicalId(); - String name; - if (explicitName != null && !explicitName.isBlank()) { - name = explicitName; - } else if (priorPhysicalId != null) { - // No explicit name: keep the name RDS already has on file instead of generating a fresh - // one on every update, which would otherwise orphan the previously provisioned group. - name = priorPhysicalId; - } else { - name = generatePhysicalName(stackName, r.getLogicalId(), 60, true); - } - String description = firstNonBlank(resolveOptional(props, "DBSubnetGroupDescription", engine), - "Managed by CloudFormation"); - // SubnetIds may be a literal array, or a list-valued intrinsic — e.g. CDK's - // Fn::Split over a cross-stack Fn::ImportValue when the source VPC exports its - // subnet ids as one comma-joined value (issue #2937). - List subnetIds = props != null && props.has("SubnetIds") - ? engine.resolveStringList(props.get("SubnetIds")) - : new ArrayList<>(); - - // On UpdateStack, provision() is re-invoked for every resource regardless of whether its - // properties actually changed, so a same-named group already on file must be reconciled in - // place rather than re-created (createDbSubnetGroup throws DBSubnetGroupAlreadyExists). - DbSubnetGroup existing = sameNameExistingResource(priorPhysicalId, name, n -> rdsService.getDbSubnetGroup(n, region)); - DbSubnetGroup group; - if (existing != null) { - group = rdsService.modifyDbSubnetGroup(name, subnetIds, region); - } else { - group = rdsService.createDbSubnetGroup(name, description, subnetIds, region); - deleteRenamedResource(priorPhysicalId, name, id -> rdsService.deleteDbSubnetGroup(id), "DB subnet group"); - } - r.setPhysicalId(group.getDbSubnetGroupName()); - r.getAttributes().put("DBSubnetGroupName", group.getDbSubnetGroupName()); - } - - private void provisionDbParameterGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String stackName, String region) { - String explicitName = resolveOptional(props, "DBParameterGroupName", engine); - String priorPhysicalId = r.getPhysicalId(); - String name; - if (explicitName != null && !explicitName.isBlank()) { - name = explicitName; - } else if (priorPhysicalId != null) { - name = priorPhysicalId; - } else { - name = generatePhysicalName(stackName, r.getLogicalId(), 60, true); - } - String family = resolveOptional(props, "Family", engine); - String description = firstNonBlank(resolveOptional(props, "Description", engine), - "Managed by CloudFormation"); - - // DBParameterGroupName, Family and Description are all immutable on real AWS (any change - // replaces the resource), so a same-named group already on file is a no-op, not a re-create. - DbParameterGroup existing = sameNameExistingResource(priorPhysicalId, name, - n -> rdsService.getDbParameterGroup(n, region)); - DbParameterGroup group; - if (existing != null) { - group = existing; - } else { - group = rdsService.createDbParameterGroup(name, family, description, region); - deleteRenamedResource(priorPhysicalId, name, id -> rdsService.deleteDbParameterGroup(id, region), - "DB parameter group"); - } - r.setPhysicalId(group.getDbParameterGroupName()); - r.getAttributes().put("DBParameterGroupName", group.getDbParameterGroupName()); - } - - private void provisionDbClusterParameterGroup(StackResource r, JsonNode props, - CloudFormationTemplateEngine engine, - String stackName, String region) { - String explicitName = resolveOptional(props, "DBClusterParameterGroupName", engine); - String priorPhysicalId = r.getPhysicalId(); - String name; - if (explicitName != null && !explicitName.isBlank()) { - name = explicitName; - } else if (priorPhysicalId != null) { - name = priorPhysicalId; - } else { - name = generatePhysicalName(stackName, r.getLogicalId(), 60, true); - } - String family = resolveOptional(props, "Family", engine); - String description = firstNonBlank(resolveOptional(props, "Description", engine), - "Managed by CloudFormation"); - - // Same immutability rationale as provisionDbParameterGroup above. - DbClusterParameterGroup existing = sameNameExistingResource(priorPhysicalId, name, - n -> rdsService.getDbClusterParameterGroup(n, region)); - DbClusterParameterGroup group; - if (existing != null) { - group = existing; - } else { - group = rdsService.createDbClusterParameterGroup(name, family, description, region); - deleteRenamedResource(priorPhysicalId, name, id -> rdsService.deleteDbClusterParameterGroup(id, region), - "DB cluster parameter group"); - } - r.setPhysicalId(group.getDbClusterParameterGroupName()); - r.getAttributes().put("DBClusterParameterGroupName", group.getDbClusterParameterGroupName()); - } - /** The VPC a security group would land in for this template value: the default when omitted. */ private String effectiveVpcId(String vpcId, String region) { return vpcId != null && !vpcId.isEmpty() ? vpcId : String.valueOf(ec2Service.resolveDefaultVpcId(region)); @@ -1369,350 +1236,6 @@ public class CloudFormationResourceProvisioner { } } - private void provisionDbInstance(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String stackName, String region) { - String explicitId = resolveOptional(props, "DBInstanceIdentifier", engine); - String priorPhysicalId = r.getPhysicalId(); - String id; - if (explicitId != null && !explicitId.isBlank()) { - id = explicitId; - } else if (priorPhysicalId != null) { - id = priorPhysicalId; - } else { - id = generatePhysicalName(stackName, r.getLogicalId(), 60, true); - } - - // provision() is re-invoked on every UpdateStack for every resource, so a same-id instance - // already on file must be reconciled rather than re-created (createDbInstance throws - // DBInstanceAlreadyExists). Only the properties RdsService.modifyDbInstance actually supports - // (password, IAM auth, subnet group) are reconciled here; other property changes (engine, - // instance class, allocated storage, ...) are a pre-existing gap in that method, not addressed - // by this fix. - DbInstance instance = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbInstance); - if (instance != null) { - instance = rdsService.modifyDbInstance( - id, - resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true), - parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine), - resolveOptional(props, "DBSubnetGroupName", engine)); - } else { - instance = rdsService.createDbInstance( - id, - resolveOptional(props, "Engine", engine), - resolveOptional(props, "EngineVersion", engine), - resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUsername", engine), region, false), - resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true), - resolveOptional(props, "DBName", engine), - firstNonBlank(resolveOptional(props, "DBInstanceClass", engine), "db.t3.micro"), - parseIntProp(props, "AllocatedStorage", engine, 20), - parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine), - resolveOptional(props, "DBParameterGroupName", engine), - resolveOptional(props, "DBSubnetGroupName", engine), - resolveOptional(props, "DBClusterIdentifier", engine), - null, false, false, null, Map.of(), region); - deleteRenamedResource(priorPhysicalId, id, rdsService::deleteDbInstance, "DB instance"); - } - r.setPhysicalId(instance.getDbInstanceIdentifier()); - r.getAttributes().put("DBInstanceIdentifier", instance.getDbInstanceIdentifier()); - if (instance.getEndpoint() != null) { - r.getAttributes().put("Endpoint.Address", instance.getEndpoint().address()); - r.getAttributes().put("Endpoint.Port", String.valueOf(instance.getEndpoint().port())); - } - if (instance.getDbInstanceArn() != null) { - r.getAttributes().put("DBInstanceArn", instance.getDbInstanceArn()); - } - } - - private void provisionDbCluster(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String stackName, String region) { - String explicitId = resolveOptional(props, "DBClusterIdentifier", engine); - String priorPhysicalId = r.getPhysicalId(); - String id; - if (explicitId != null && !explicitId.isBlank()) { - id = explicitId; - } else if (priorPhysicalId != null) { - id = priorPhysicalId; - } else { - id = generatePhysicalName(stackName, r.getLogicalId(), 60, true); - } - - // Same re-invocation rationale as provisionDbInstance above; modifyDbCluster only reconciles - // password and IAM auth, mirroring that method's existing scope. - DbCluster cluster = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbCluster); - if (cluster != null) { - cluster = rdsService.modifyDbCluster( - id, - resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true), - parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine), - parseServerlessV2Capacity(props, "MinCapacity", engine), - parseServerlessV2Capacity(props, "MaxCapacity", engine), - parseServerlessV2SecondsUntilAutoPause(props, engine), region); - } else { - Double serverlessV2MinCapacity = parseServerlessV2Capacity(props, "MinCapacity", engine); - Double serverlessV2MaxCapacity = parseServerlessV2Capacity(props, "MaxCapacity", engine); - Integer serverlessV2SecondsUntilAutoPause = - parseServerlessV2SecondsUntilAutoPause(props, engine); - String engineName = resolveOptional(props, "Engine", engine); - String engineVersion = resolveOptional(props, "EngineVersion", engine); - String masterUsername = resolveDynamicReferences( - resolveOptionalWithoutDynamicReferences(props, "MasterUsername", engine), region, false); - String masterPassword = resolveDynamicReferences( - resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true); - String databaseName = resolveOptional(props, "DatabaseName", engine); - boolean iamEnabled = parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine); - String parameterGroup = resolveOptional(props, "DBClusterParameterGroupName", engine); - String engineMode = resolveOptional(props, "EngineMode", engine); - boolean storageEncrypted = parseBoolProp(props, "StorageEncrypted", engine); - if (engineMode == null && !storageEncrypted) { - if (serverlessV2MinCapacity == null && serverlessV2MaxCapacity == null - && serverlessV2SecondsUntilAutoPause == null) { - cluster = rdsService.createDbCluster(id, engineName, engineVersion, masterUsername, - masterPassword, databaseName, iamEnabled, parameterGroup, null, null, false, region); - } else { - cluster = rdsService.createDbCluster(id, engineName, engineVersion, masterUsername, - masterPassword, databaseName, iamEnabled, parameterGroup, null, null, false, region, - serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause); - } - } else { - cluster = rdsService.createDbCluster(id, engineName, engineVersion, masterUsername, - masterPassword, databaseName, iamEnabled, parameterGroup, null, null, false, region, - serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause, - false, null, engineMode, storageEncrypted); - } - deleteRenamedResource(priorPhysicalId, id, rdsService::deleteDbCluster, "DB cluster"); - } - r.setPhysicalId(cluster.getDbClusterIdentifier()); - r.getAttributes().put("DBClusterIdentifier", cluster.getDbClusterIdentifier()); - if (cluster.getEndpoint() != null) { - r.getAttributes().put("Endpoint.Address", cluster.getEndpoint().address()); - r.getAttributes().put("Endpoint.Port", String.valueOf(cluster.getEndpoint().port())); - } - if (cluster.getReaderEndpoint() != null) { - r.getAttributes().put("ReadEndpoint.Address", cluster.getReaderEndpoint().address()); - } - if (cluster.getDbClusterArn() != null) { - r.getAttributes().put("DBClusterArn", cluster.getDbClusterArn()); - } - } - - private Double parseServerlessV2Capacity(JsonNode props, String field, - CloudFormationTemplateEngine engine) { - JsonNode config = props.get("ServerlessV2ScalingConfiguration"); - if (config == null || config.isNull()) { - return null; - } - String resolved = resolveOptional(config, field, engine); - if (resolved == null || resolved.isBlank()) { - return null; - } - try { - return Double.valueOf(resolved.trim()); - } catch (NumberFormatException e) { - throw new AwsException("ValidationError", - "ServerlessV2ScalingConfiguration " + field + " must be a number.", 400); - } - } - - private Integer parseServerlessV2SecondsUntilAutoPause( - JsonNode props, CloudFormationTemplateEngine engine) { - JsonNode config = props.get("ServerlessV2ScalingConfiguration"); - if (config == null || config.isNull()) { - return null; - } - String resolved = resolveOptional(config, "SecondsUntilAutoPause", engine); - if (resolved == null || resolved.isBlank()) { - return null; - } - try { - return Integer.valueOf(resolved.trim()); - } catch (NumberFormatException e) { - throw new AwsException("ValidationError", - "ServerlessV2ScalingConfiguration SecondsUntilAutoPause must be an integer.", 400); - } - } - - private void provisionDbProxy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region) { - String name = resolveOptional(props, "DBProxyName", engine); - String engineFamily = resolveOptional(props, "EngineFamily", engine); - String defaultAuthScheme = resolveOptional(props, "DefaultAuthScheme", engine); - if (defaultAuthScheme == null) { - defaultAuthScheme = "NONE"; - } else if (defaultAuthScheme.isBlank()) { - throw new AwsException("InvalidParameterValue", - "DefaultAuthScheme must be NONE or IAM_AUTH.", 400); - } - String endpointNetworkType = resolveOptional(props, "EndpointNetworkType", engine); - String targetConnectionNetworkType = resolveOptional( - props, "TargetConnectionNetworkType", engine); - validateIpv4DbProxyNetworkType(endpointNetworkType, - "EndpointNetworkType", true, "IPV4, IPV6, or DUAL"); - validateIpv4DbProxyNetworkType(targetConnectionNetworkType, - "TargetConnectionNetworkType", false, "IPV4 or IPV6"); - boolean requireTls = parseBoolProp(props, "RequireTLS", engine); - boolean debugLogging = parseBoolProp(props, "DebugLogging", engine); - Integer configuredIdleClientTimeout = parseOptionalIntProp(props, "IdleClientTimeout", engine); - int idleClientTimeout = configuredIdleClientTimeout != null ? configuredIdleClientTimeout : 1800; - String roleArn = resolveOptional(props, "RoleArn", engine); - List subnetIds = resolveStringList(props, "VpcSubnetIds", engine); - if (subnetIds.stream().distinct().count() < 2) { - throw new AwsException("InvalidParameterValue", - "AWS::RDS::DBProxy VpcSubnetIds must contain at least two distinct subnet IDs.", 400); - } - List sgIds = resolveStringList(props, "VpcSecurityGroupIds", engine); - List auth = parseProxyAuth(props, engine); - boolean iamAuth = "IAM_AUTH".equalsIgnoreCase(defaultAuthScheme) - || auth.stream().anyMatch(a -> - "REQUIRED".equalsIgnoreCase(a.getIamAuth()) - || "ENABLED".equalsIgnoreCase(a.getIamAuth())); - Map tags = parseCfnTags(props != null ? props.get("Tags") : null, engine); - var proxy = r.getPhysicalId() == null - ? rdsService.createDbProxy(name, engineFamily, requireTls, iamAuth, - defaultAuthScheme, roleArn, subnetIds, sgIds, auth, idleClientTimeout, - debugLogging, tags, region) - : updateDbProxy(r, name, engineFamily, defaultAuthScheme, requireTls, - idleClientTimeout, debugLogging, roleArn, subnetIds, sgIds, auth, tags, region); - r.setPhysicalId(proxy.getDbProxyName()); // Ref -> DBProxyName - r.getAttributes().put("Endpoint", proxy.getEndpoint()); // GetAtt "Endpoint" (bare host) - r.getAttributes().put("DBProxyArn", proxy.getDbProxyArn()); - if (proxy.getVpcId() != null) { - r.getAttributes().put("VpcId", proxy.getVpcId()); - } - } - - private io.github.hectorvent.floci.services.rds.model.DbProxy updateDbProxy( - StackResource resource, String name, String engineFamily, String defaultAuthScheme, - boolean requireTls, int idleClientTimeout, boolean debugLogging, String roleArn, - List subnetIds, List securityGroupIds, List auth, - Map tags, String region) { - var existing = rdsService.getDbProxy(resource.getPhysicalId(), region); - if (!Objects.equals(existing.getDbProxyName(), name) - || engineFamily == null - || !existing.getEngineFamily().equalsIgnoreCase(engineFamily) - || !Set.copyOf(existing.getVpcSubnetIds()).equals(Set.copyOf(subnetIds))) { - throw new AwsException("UnsupportedOperation", - "Changing DBProxyName, EngineFamily, or VpcSubnetIds requires CloudFormation " - + "replacement, which is not yet supported by Floci.", 400); - } - return rdsService.modifyDbProxy(existing.getDbProxyName(), defaultAuthScheme, auth, - requireTls, idleClientTimeout, debugLogging, roleArn, - securityGroupIds, tags, region); - } - - private void provisionDbProxyTargetGroup(StackResource r, JsonNode props, - CloudFormationTemplateEngine engine, String region) { - String dbProxyName = resolveOptional(props, "DBProxyName", engine); - String targetGroupName = resolveOptional(props, "TargetGroupName", engine); - if (!"default".equals(targetGroupName)) { - throw new AwsException("InvalidParameterValue", - "AWS::RDS::DBProxyTargetGroup TargetGroupName must be default.", 400); - } - List clusterIds = resolveStringList(props, "DBClusterIdentifiers", engine); - List instanceIds = resolveStringList(props, "DBInstanceIdentifiers", engine); - Integer maxConn = null; - Integer maxIdle = null; - Integer connectionBorrowTimeout = null; - String initQuery = null; - List sessionPinningFilters = List.of(); - if (props != null && props.has("ConnectionPoolConfigurationInfo")) { - JsonNode cpc = props.get("ConnectionPoolConfigurationInfo"); - maxConn = parseOptionalIntProp(cpc, "MaxConnectionsPercent", engine); - maxIdle = parseOptionalIntProp(cpc, "MaxIdleConnectionsPercent", engine); - connectionBorrowTimeout = parseOptionalIntProp(cpc, "ConnectionBorrowTimeout", engine); - initQuery = resolveOptional(cpc, "InitQuery", engine); - sessionPinningFilters = resolveStringList(cpc, "SessionPinningFilters", engine); - } - if (maxIdle != null && maxConn == null) { - throw new AwsException("InvalidParameterValue", - "MaxConnectionsPercent is required when MaxIdleConnectionsPercent is specified.", - 400); - } - if (r.getPhysicalId() != null) { - var existing = rdsService.getDbProxyTargetGroupByArn(r.getPhysicalId(), region); - if (!Objects.equals(existing.getDbProxyName(), dbProxyName) - || !Objects.equals(existing.getTargetGroupName(), targetGroupName)) { - throw new AwsException("UnsupportedOperation", - "Changing DBProxyName or TargetGroupName requires CloudFormation replacement.", - 400); - } - } - var proxy = rdsService.getDbProxy(dbProxyName, region); - int effectiveMaxConnections = maxConn != null ? maxConn - : ("SQLSERVER".equals(proxy.getEngineFamily()) ? 10 : 100); - int effectiveMaxIdle = maxIdle != null ? maxIdle : effectiveMaxConnections / 2; - int effectiveBorrowTimeout = connectionBorrowTimeout != null ? connectionBorrowTimeout : 120; - var tg = rdsService.reconcileDbProxyTargetGroup( - dbProxyName, targetGroupName, clusterIds, instanceIds, - effectiveMaxConnections, effectiveMaxIdle, effectiveBorrowTimeout, - initQuery, sessionPinningFilters, region); - r.setPhysicalId(tg.getTargetGroupArn()); // Ref -> TargetGroupArn - r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn()); - r.getAttributes().put("DBProxyName", tg.getDbProxyName()); - } - - private List parseProxyAuth(JsonNode props, CloudFormationTemplateEngine engine) { - List auth = new ArrayList<>(); - if (props != null && props.has("Auth") && props.get("Auth").isArray()) { - for (JsonNode a : props.get("Auth")) { - DbProxyAuth entry = new DbProxyAuth(); - entry.setAuthScheme(resolveOptional(a, "AuthScheme", engine)); - entry.setSecretArn(resolveOptional(a, "SecretArn", engine)); - entry.setIamAuth(resolveOptional(a, "IAMAuth", engine)); - entry.setClientPasswordAuthType(resolveOptional(a, "ClientPasswordAuthType", engine)); - entry.setDescription(resolveOptional(a, "Description", engine)); - entry.setUserName(resolveOptional(a, "UserName", engine)); - auth.add(entry); - } - } - return auth; - } - - private void validateIpv4DbProxyNetworkType( - String value, String propertyName, boolean dualAllowed, String validValues) { - if (value == null) { - return; - } - if ("IPV4".equalsIgnoreCase(value)) { - return; - } - boolean supportedAwsValue = "IPV6".equalsIgnoreCase(value) - || (dualAllowed && "DUAL".equalsIgnoreCase(value)); - if (value.isBlank() || !supportedAwsValue) { - throw new AwsException("InvalidParameterValue", - propertyName + " must be " + validValues + ".", 400); - } - throw new AwsException("UnsupportedOperation", - propertyName + " " + value.toUpperCase() - + " is not supported because Floci currently exposes IPv4 proxy networking only.", - 400); - } - - private void deleteDbProxySafe(String name, String region) { - try { - rdsService.deleteDbProxy(name, region); - } catch (AwsException e) { - if (!"DBProxyNotFoundFault".equals(e.getErrorCode())) { - throw e; - } - LOG.debugv("DB proxy already gone, treating as deleted: {0}", name); - } - } - - private void clearDbProxyTargetGroupSafe(String targetGroupArn, String region) { - try { - rdsService.clearDbProxyTargetGroupByArn(targetGroupArn, region); - } catch (AwsException e) { - if (!"DBProxyTargetGroupNotFoundFault".equals(e.getErrorCode())) { - throw e; - } - LOG.debugv("DB proxy target group already gone, treating as deleted: {0}", targetGroupArn); - } - } - - private static String firstNonBlank(String value, String fallback) { - return (value == null || value.isBlank()) ? fallback : value; - } - private int parseIntProp(JsonNode props, String name, CloudFormationTemplateEngine engine, int fallback) { String value = resolveOptional(props, name, engine); if (value == null || value.isBlank()) { @@ -1725,22 +1248,6 @@ public class CloudFormationResourceProvisioner { } } - private Integer parseOptionalIntProp(JsonNode props, String name, CloudFormationTemplateEngine engine) { - String value = resolveOptional(props, name, engine); - if (value == null || value.isBlank()) { - return null; - } - try { - return Integer.valueOf(value.trim()); - } catch (NumberFormatException e) { - throw new AwsException("InvalidParameterValue", name + " must be an integer.", 400); - } - } - - private boolean parseBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) { - return Boolean.parseBoolean(resolveOptional(props, name, engine)); - } - // ── EKS ───────────────────────────────────────────────────────────────────── private void provisionEksCluster(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java new file mode 100644 index 0000000000..58ee4407d9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java @@ -0,0 +1,652 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.rds.RdsService; +import io.github.hectorvent.floci.services.rds.model.DbCluster; +import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup; +import io.github.hectorvent.floci.services.rds.model.DbInstance; +import io.github.hectorvent.floci.services.rds.model.DbParameterGroup; +import io.github.hectorvent.floci.services.rds.model.DbProxyAuth; +import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * CloudFormation provisioning for RDS: the two parameter-group types, {@code DBSubnetGroup}, + * {@code DBInstance}, {@code DBCluster}, {@code DBProxy} and {@code DBProxyTargetGroup}. + * Extracted from {@code CloudFormationResourceProvisioner}. + * + *

Every type here deletes by physical id alone, so the id-only + * {@link #delete(String, String, String)} serves all seven and none of them appears in the + * engine's {@code DELETE_NEEDS_STACK_RESOURCE} set. + * + *

Unlike most extractions this one does not take {@code RdsService} out of the monolith. + * {@code AWS::SecretsManager::SecretTargetAttachment} is still served there and reads an + * instance's or cluster's endpoint to build its connection detail, so the monolith keeps its own + * reference to the service. + */ +@ApplicationScoped +public class RdsCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(RdsCfnProvisioner.class); + + private final RdsService rdsService; + private final CfnDynamicReferences dynamicReferences; + + @Inject + public RdsCfnProvisioner(RdsService rdsService, CfnDynamicReferences dynamicReferences) { + this.rdsService = rdsService; + this.dynamicReferences = dynamicReferences; + } + + @Override + public Set resourceTypes() { + return Set.of( + "AWS::RDS::DBSubnetGroup", + "AWS::RDS::DBParameterGroup", + "AWS::RDS::DBClusterParameterGroup", + "AWS::RDS::DBInstance", + "AWS::RDS::DBCluster", + "AWS::RDS::DBProxy", + "AWS::RDS::DBProxyTargetGroup"); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + CloudFormationTemplateEngine engine = ctx.engine(); + String region = ctx.region(); + switch (r.getResourceType()) { + case "AWS::RDS::DBSubnetGroup" -> provisionDbSubnetGroup(r, props, engine, ctx, region); + case "AWS::RDS::DBParameterGroup" -> provisionDbParameterGroup(r, props, engine, ctx, region); + case "AWS::RDS::DBClusterParameterGroup" -> + provisionDbClusterParameterGroup(r, props, engine, ctx, region); + case "AWS::RDS::DBInstance" -> provisionDbInstance(r, props, engine, ctx, region); + case "AWS::RDS::DBCluster" -> provisionDbCluster(r, props, engine, ctx, region); + case "AWS::RDS::DBProxy" -> provisionDbProxy(r, props, engine, region); + case "AWS::RDS::DBProxyTargetGroup" -> provisionDbProxyTargetGroup(r, props, engine, region); + default -> throw new IllegalStateException( + "RdsCfnProvisioner received an unsupported type: " + r.getResourceType()); + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + switch (resourceType) { + case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId, region); + case "AWS::RDS::DBCluster" -> rdsService.deleteDbCluster(physicalId, region); + case "AWS::RDS::DBProxy" -> deleteDbProxySafe(physicalId, region); + case "AWS::RDS::DBProxyTargetGroup" -> clearDbProxyTargetGroupSafe(physicalId, region); + case "AWS::RDS::DBSubnetGroup" -> rdsService.deleteDbSubnetGroup(physicalId, region); + case "AWS::RDS::DBParameterGroup" -> rdsService.deleteDbParameterGroup(physicalId, region); + case "AWS::RDS::DBClusterParameterGroup" -> + rdsService.deleteDbClusterParameterGroup(physicalId, region); + default -> throw new IllegalStateException( + "RdsCfnProvisioner received an unsupported type: " + resourceType); + } + } + + private void provisionDbSubnetGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + ProvisionContext ctx, String region) { + String explicitName = resolveOptional(props, "DBSubnetGroupName", engine); + String priorPhysicalId = r.getPhysicalId(); + String name; + if (explicitName != null && !explicitName.isBlank()) { + name = explicitName; + } else if (priorPhysicalId != null) { + // No explicit name: keep the name RDS already has on file instead of generating a fresh + // one on every update, which would otherwise orphan the previously provisioned group. + name = priorPhysicalId; + } else { + name = ctx.generatePhysicalName(r.getLogicalId(), 60, true); + } + String description = firstNonBlank(resolveOptional(props, "DBSubnetGroupDescription", engine), + "Managed by CloudFormation"); + // SubnetIds may be a literal array, or a list-valued intrinsic such as CDK's + // Fn::Split over a cross-stack Fn::ImportValue when the source VPC exports its + // subnet ids as one comma-joined value (issue #2937). + List subnetIds = props != null && props.has("SubnetIds") + ? engine.resolveStringList(props.get("SubnetIds")) + : new ArrayList<>(); + + // On UpdateStack, provision() is re-invoked for every resource regardless of whether its + // properties actually changed, so a same-named group already on file must be reconciled in + // place rather than re-created (createDbSubnetGroup throws DBSubnetGroupAlreadyExists). + DbSubnetGroup existing = sameNameExistingResource(priorPhysicalId, name, n -> rdsService.getDbSubnetGroup(n, region)); + DbSubnetGroup group; + if (existing != null) { + group = rdsService.modifyDbSubnetGroup(name, subnetIds, region); + } else { + group = rdsService.createDbSubnetGroup(name, description, subnetIds, region); + deleteRenamedResource(priorPhysicalId, name, id -> rdsService.deleteDbSubnetGroup(id), "DB subnet group"); + } + r.setPhysicalId(group.getDbSubnetGroupName()); + r.getAttributes().put("DBSubnetGroupName", group.getDbSubnetGroupName()); + } + + private void provisionDbParameterGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + ProvisionContext ctx, String region) { + String explicitName = resolveOptional(props, "DBParameterGroupName", engine); + String priorPhysicalId = r.getPhysicalId(); + String name; + if (explicitName != null && !explicitName.isBlank()) { + name = explicitName; + } else if (priorPhysicalId != null) { + name = priorPhysicalId; + } else { + name = ctx.generatePhysicalName(r.getLogicalId(), 60, true); + } + String family = resolveOptional(props, "Family", engine); + String description = firstNonBlank(resolveOptional(props, "Description", engine), + "Managed by CloudFormation"); + + // DBParameterGroupName, Family and Description are all immutable on real AWS (any change + // replaces the resource), so a same-named group already on file is a no-op, not a re-create. + DbParameterGroup existing = sameNameExistingResource(priorPhysicalId, name, + n -> rdsService.getDbParameterGroup(n, region)); + DbParameterGroup group; + if (existing != null) { + group = existing; + } else { + group = rdsService.createDbParameterGroup(name, family, description, region); + deleteRenamedResource(priorPhysicalId, name, id -> rdsService.deleteDbParameterGroup(id, region), + "DB parameter group"); + } + r.setPhysicalId(group.getDbParameterGroupName()); + r.getAttributes().put("DBParameterGroupName", group.getDbParameterGroupName()); + } + + private void provisionDbClusterParameterGroup(StackResource r, JsonNode props, + CloudFormationTemplateEngine engine, + ProvisionContext ctx, String region) { + String explicitName = resolveOptional(props, "DBClusterParameterGroupName", engine); + String priorPhysicalId = r.getPhysicalId(); + String name; + if (explicitName != null && !explicitName.isBlank()) { + name = explicitName; + } else if (priorPhysicalId != null) { + name = priorPhysicalId; + } else { + name = ctx.generatePhysicalName(r.getLogicalId(), 60, true); + } + String family = resolveOptional(props, "Family", engine); + String description = firstNonBlank(resolveOptional(props, "Description", engine), + "Managed by CloudFormation"); + + // Same immutability rationale as provisionDbParameterGroup above. + DbClusterParameterGroup existing = sameNameExistingResource(priorPhysicalId, name, + n -> rdsService.getDbClusterParameterGroup(n, region)); + DbClusterParameterGroup group; + if (existing != null) { + group = existing; + } else { + group = rdsService.createDbClusterParameterGroup(name, family, description, region); + deleteRenamedResource(priorPhysicalId, name, id -> rdsService.deleteDbClusterParameterGroup(id, region), + "DB cluster parameter group"); + } + r.setPhysicalId(group.getDbClusterParameterGroupName()); + r.getAttributes().put("DBClusterParameterGroupName", group.getDbClusterParameterGroupName()); + } + + private void provisionDbInstance(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + ProvisionContext ctx, String region) { + String explicitId = resolveOptional(props, "DBInstanceIdentifier", engine); + String priorPhysicalId = r.getPhysicalId(); + String id; + if (explicitId != null && !explicitId.isBlank()) { + id = explicitId; + } else if (priorPhysicalId != null) { + id = priorPhysicalId; + } else { + id = ctx.generatePhysicalName(r.getLogicalId(), 60, true); + } + + // provision() is re-invoked on every UpdateStack for every resource, so a same-id instance + // already on file must be reconciled rather than re-created (createDbInstance throws + // DBInstanceAlreadyExists). Only the properties RdsService.modifyDbInstance actually supports + // (password, IAM auth, subnet group) are reconciled here; other property changes (engine, + // instance class, allocated storage, ...) are a pre-existing gap in that method, not addressed + // by this fix. + DbInstance instance = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbInstance); + if (instance != null) { + instance = rdsService.modifyDbInstance( + id, + resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true), + parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine), + resolveOptional(props, "DBSubnetGroupName", engine)); + } else { + instance = rdsService.createDbInstance( + id, + resolveOptional(props, "Engine", engine), + resolveOptional(props, "EngineVersion", engine), + resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUsername", engine), region, false), + resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true), + resolveOptional(props, "DBName", engine), + firstNonBlank(resolveOptional(props, "DBInstanceClass", engine), "db.t3.micro"), + parseIntProp(props, "AllocatedStorage", engine, 20), + parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine), + resolveOptional(props, "DBParameterGroupName", engine), + resolveOptional(props, "DBSubnetGroupName", engine), + resolveOptional(props, "DBClusterIdentifier", engine), + null, false, false, null, Map.of(), region); + deleteRenamedResource(priorPhysicalId, id, rdsService::deleteDbInstance, "DB instance"); + } + r.setPhysicalId(instance.getDbInstanceIdentifier()); + r.getAttributes().put("DBInstanceIdentifier", instance.getDbInstanceIdentifier()); + if (instance.getEndpoint() != null) { + r.getAttributes().put("Endpoint.Address", instance.getEndpoint().address()); + r.getAttributes().put("Endpoint.Port", String.valueOf(instance.getEndpoint().port())); + } + if (instance.getDbInstanceArn() != null) { + r.getAttributes().put("DBInstanceArn", instance.getDbInstanceArn()); + } + } + + private void provisionDbCluster(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + ProvisionContext ctx, String region) { + String explicitId = resolveOptional(props, "DBClusterIdentifier", engine); + String priorPhysicalId = r.getPhysicalId(); + String id; + if (explicitId != null && !explicitId.isBlank()) { + id = explicitId; + } else if (priorPhysicalId != null) { + id = priorPhysicalId; + } else { + id = ctx.generatePhysicalName(r.getLogicalId(), 60, true); + } + + // Same re-invocation rationale as provisionDbInstance above; modifyDbCluster only reconciles + // password and IAM auth, mirroring that method's existing scope. + DbCluster cluster = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbCluster); + if (cluster != null) { + cluster = rdsService.modifyDbCluster( + id, + resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true), + parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine), + parseServerlessV2Capacity(props, "MinCapacity", engine), + parseServerlessV2Capacity(props, "MaxCapacity", engine), + parseServerlessV2SecondsUntilAutoPause(props, engine), region); + } else { + Double serverlessV2MinCapacity = parseServerlessV2Capacity(props, "MinCapacity", engine); + Double serverlessV2MaxCapacity = parseServerlessV2Capacity(props, "MaxCapacity", engine); + Integer serverlessV2SecondsUntilAutoPause = + parseServerlessV2SecondsUntilAutoPause(props, engine); + String engineName = resolveOptional(props, "Engine", engine); + String engineVersion = resolveOptional(props, "EngineVersion", engine); + String masterUsername = resolveDynamicReferences( + resolveOptionalWithoutDynamicReferences(props, "MasterUsername", engine), region, false); + String masterPassword = resolveDynamicReferences( + resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true); + String databaseName = resolveOptional(props, "DatabaseName", engine); + boolean iamEnabled = parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine); + String parameterGroup = resolveOptional(props, "DBClusterParameterGroupName", engine); + String engineMode = resolveOptional(props, "EngineMode", engine); + boolean storageEncrypted = parseBoolProp(props, "StorageEncrypted", engine); + if (engineMode == null && !storageEncrypted) { + if (serverlessV2MinCapacity == null && serverlessV2MaxCapacity == null + && serverlessV2SecondsUntilAutoPause == null) { + cluster = rdsService.createDbCluster(id, engineName, engineVersion, masterUsername, + masterPassword, databaseName, iamEnabled, parameterGroup, null, null, false, region); + } else { + cluster = rdsService.createDbCluster(id, engineName, engineVersion, masterUsername, + masterPassword, databaseName, iamEnabled, parameterGroup, null, null, false, region, + serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause); + } + } else { + cluster = rdsService.createDbCluster(id, engineName, engineVersion, masterUsername, + masterPassword, databaseName, iamEnabled, parameterGroup, null, null, false, region, + serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause, + false, null, engineMode, storageEncrypted); + } + deleteRenamedResource(priorPhysicalId, id, rdsService::deleteDbCluster, "DB cluster"); + } + r.setPhysicalId(cluster.getDbClusterIdentifier()); + r.getAttributes().put("DBClusterIdentifier", cluster.getDbClusterIdentifier()); + if (cluster.getEndpoint() != null) { + r.getAttributes().put("Endpoint.Address", cluster.getEndpoint().address()); + r.getAttributes().put("Endpoint.Port", String.valueOf(cluster.getEndpoint().port())); + } + if (cluster.getReaderEndpoint() != null) { + r.getAttributes().put("ReadEndpoint.Address", cluster.getReaderEndpoint().address()); + } + if (cluster.getDbClusterArn() != null) { + r.getAttributes().put("DBClusterArn", cluster.getDbClusterArn()); + } + } + + private Double parseServerlessV2Capacity(JsonNode props, String field, + CloudFormationTemplateEngine engine) { + JsonNode config = props.get("ServerlessV2ScalingConfiguration"); + if (config == null || config.isNull()) { + return null; + } + String resolved = resolveOptional(config, field, engine); + if (resolved == null || resolved.isBlank()) { + return null; + } + try { + return Double.valueOf(resolved.trim()); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", + "ServerlessV2ScalingConfiguration " + field + " must be a number.", 400); + } + } + + private Integer parseServerlessV2SecondsUntilAutoPause( + JsonNode props, CloudFormationTemplateEngine engine) { + JsonNode config = props.get("ServerlessV2ScalingConfiguration"); + if (config == null || config.isNull()) { + return null; + } + String resolved = resolveOptional(config, "SecondsUntilAutoPause", engine); + if (resolved == null || resolved.isBlank()) { + return null; + } + try { + return Integer.valueOf(resolved.trim()); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", + "ServerlessV2ScalingConfiguration SecondsUntilAutoPause must be an integer.", 400); + } + } + + private void provisionDbProxy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + String region) { + String name = resolveOptional(props, "DBProxyName", engine); + String engineFamily = resolveOptional(props, "EngineFamily", engine); + String defaultAuthScheme = resolveOptional(props, "DefaultAuthScheme", engine); + if (defaultAuthScheme == null) { + defaultAuthScheme = "NONE"; + } else if (defaultAuthScheme.isBlank()) { + throw new AwsException("InvalidParameterValue", + "DefaultAuthScheme must be NONE or IAM_AUTH.", 400); + } + String endpointNetworkType = resolveOptional(props, "EndpointNetworkType", engine); + String targetConnectionNetworkType = resolveOptional( + props, "TargetConnectionNetworkType", engine); + validateIpv4DbProxyNetworkType(endpointNetworkType, + "EndpointNetworkType", true, "IPV4, IPV6, or DUAL"); + validateIpv4DbProxyNetworkType(targetConnectionNetworkType, + "TargetConnectionNetworkType", false, "IPV4 or IPV6"); + boolean requireTls = parseBoolProp(props, "RequireTLS", engine); + boolean debugLogging = parseBoolProp(props, "DebugLogging", engine); + Integer configuredIdleClientTimeout = parseOptionalIntProp(props, "IdleClientTimeout", engine); + int idleClientTimeout = configuredIdleClientTimeout != null ? configuredIdleClientTimeout : 1800; + String roleArn = resolveOptional(props, "RoleArn", engine); + List subnetIds = resolveStringList(props, "VpcSubnetIds", engine); + if (subnetIds.stream().distinct().count() < 2) { + throw new AwsException("InvalidParameterValue", + "AWS::RDS::DBProxy VpcSubnetIds must contain at least two distinct subnet IDs.", 400); + } + List sgIds = resolveStringList(props, "VpcSecurityGroupIds", engine); + List auth = parseProxyAuth(props, engine); + boolean iamAuth = "IAM_AUTH".equalsIgnoreCase(defaultAuthScheme) + || auth.stream().anyMatch(a -> + "REQUIRED".equalsIgnoreCase(a.getIamAuth()) + || "ENABLED".equalsIgnoreCase(a.getIamAuth())); + Map tags = parseCfnTags(props != null ? props.get("Tags") : null, engine); + var proxy = r.getPhysicalId() == null + ? rdsService.createDbProxy(name, engineFamily, requireTls, iamAuth, + defaultAuthScheme, roleArn, subnetIds, sgIds, auth, idleClientTimeout, + debugLogging, tags, region) + : updateDbProxy(r, name, engineFamily, defaultAuthScheme, requireTls, + idleClientTimeout, debugLogging, roleArn, subnetIds, sgIds, auth, tags, region); + r.setPhysicalId(proxy.getDbProxyName()); // Ref -> DBProxyName + r.getAttributes().put("Endpoint", proxy.getEndpoint()); // GetAtt "Endpoint" (bare host) + r.getAttributes().put("DBProxyArn", proxy.getDbProxyArn()); + if (proxy.getVpcId() != null) { + r.getAttributes().put("VpcId", proxy.getVpcId()); + } + } + + private io.github.hectorvent.floci.services.rds.model.DbProxy updateDbProxy( + StackResource resource, String name, String engineFamily, String defaultAuthScheme, + boolean requireTls, int idleClientTimeout, boolean debugLogging, String roleArn, + List subnetIds, List securityGroupIds, List auth, + Map tags, String region) { + var existing = rdsService.getDbProxy(resource.getPhysicalId(), region); + if (!Objects.equals(existing.getDbProxyName(), name) + || engineFamily == null + || !existing.getEngineFamily().equalsIgnoreCase(engineFamily) + || !Set.copyOf(existing.getVpcSubnetIds()).equals(Set.copyOf(subnetIds))) { + throw new AwsException("UnsupportedOperation", + "Changing DBProxyName, EngineFamily, or VpcSubnetIds requires CloudFormation " + + "replacement, which is not yet supported by Floci.", 400); + } + return rdsService.modifyDbProxy(existing.getDbProxyName(), defaultAuthScheme, auth, + requireTls, idleClientTimeout, debugLogging, roleArn, + securityGroupIds, tags, region); + } + + private void provisionDbProxyTargetGroup(StackResource r, JsonNode props, + CloudFormationTemplateEngine engine, String region) { + String dbProxyName = resolveOptional(props, "DBProxyName", engine); + String targetGroupName = resolveOptional(props, "TargetGroupName", engine); + if (!"default".equals(targetGroupName)) { + throw new AwsException("InvalidParameterValue", + "AWS::RDS::DBProxyTargetGroup TargetGroupName must be default.", 400); + } + List clusterIds = resolveStringList(props, "DBClusterIdentifiers", engine); + List instanceIds = resolveStringList(props, "DBInstanceIdentifiers", engine); + Integer maxConn = null; + Integer maxIdle = null; + Integer connectionBorrowTimeout = null; + String initQuery = null; + List sessionPinningFilters = List.of(); + if (props != null && props.has("ConnectionPoolConfigurationInfo")) { + JsonNode cpc = props.get("ConnectionPoolConfigurationInfo"); + maxConn = parseOptionalIntProp(cpc, "MaxConnectionsPercent", engine); + maxIdle = parseOptionalIntProp(cpc, "MaxIdleConnectionsPercent", engine); + connectionBorrowTimeout = parseOptionalIntProp(cpc, "ConnectionBorrowTimeout", engine); + initQuery = resolveOptional(cpc, "InitQuery", engine); + sessionPinningFilters = resolveStringList(cpc, "SessionPinningFilters", engine); + } + if (maxIdle != null && maxConn == null) { + throw new AwsException("InvalidParameterValue", + "MaxConnectionsPercent is required when MaxIdleConnectionsPercent is specified.", + 400); + } + if (r.getPhysicalId() != null) { + var existing = rdsService.getDbProxyTargetGroupByArn(r.getPhysicalId(), region); + if (!Objects.equals(existing.getDbProxyName(), dbProxyName) + || !Objects.equals(existing.getTargetGroupName(), targetGroupName)) { + throw new AwsException("UnsupportedOperation", + "Changing DBProxyName or TargetGroupName requires CloudFormation replacement.", + 400); + } + } + var proxy = rdsService.getDbProxy(dbProxyName, region); + int effectiveMaxConnections = maxConn != null ? maxConn + : ("SQLSERVER".equals(proxy.getEngineFamily()) ? 10 : 100); + int effectiveMaxIdle = maxIdle != null ? maxIdle : effectiveMaxConnections / 2; + int effectiveBorrowTimeout = connectionBorrowTimeout != null ? connectionBorrowTimeout : 120; + var tg = rdsService.reconcileDbProxyTargetGroup( + dbProxyName, targetGroupName, clusterIds, instanceIds, + effectiveMaxConnections, effectiveMaxIdle, effectiveBorrowTimeout, + initQuery, sessionPinningFilters, region); + r.setPhysicalId(tg.getTargetGroupArn()); // Ref -> TargetGroupArn + r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn()); + r.getAttributes().put("DBProxyName", tg.getDbProxyName()); + } + + private List parseProxyAuth(JsonNode props, CloudFormationTemplateEngine engine) { + List auth = new ArrayList<>(); + if (props != null && props.has("Auth") && props.get("Auth").isArray()) { + for (JsonNode a : props.get("Auth")) { + DbProxyAuth entry = new DbProxyAuth(); + entry.setAuthScheme(resolveOptional(a, "AuthScheme", engine)); + entry.setSecretArn(resolveOptional(a, "SecretArn", engine)); + entry.setIamAuth(resolveOptional(a, "IAMAuth", engine)); + entry.setClientPasswordAuthType(resolveOptional(a, "ClientPasswordAuthType", engine)); + entry.setDescription(resolveOptional(a, "Description", engine)); + entry.setUserName(resolveOptional(a, "UserName", engine)); + auth.add(entry); + } + } + return auth; + } + + private void validateIpv4DbProxyNetworkType( + String value, String propertyName, boolean dualAllowed, String validValues) { + if (value == null) { + return; + } + if ("IPV4".equalsIgnoreCase(value)) { + return; + } + boolean supportedAwsValue = "IPV6".equalsIgnoreCase(value) + || (dualAllowed && "DUAL".equalsIgnoreCase(value)); + if (value.isBlank() || !supportedAwsValue) { + throw new AwsException("InvalidParameterValue", + propertyName + " must be " + validValues + ".", 400); + } + throw new AwsException("UnsupportedOperation", + propertyName + " " + value.toUpperCase() + + " is not supported because Floci currently exposes IPv4 proxy networking only.", + 400); + } + + private void deleteDbProxySafe(String name, String region) { + try { + rdsService.deleteDbProxy(name, region); + } catch (AwsException e) { + if (!"DBProxyNotFoundFault".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("DB proxy already gone, treating as deleted: {0}", name); + } + } + + private void clearDbProxyTargetGroupSafe(String targetGroupArn, String region) { + try { + rdsService.clearDbProxyTargetGroupByArn(targetGroupArn, region); + } catch (AwsException e) { + if (!"DBProxyTargetGroupNotFoundFault".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("DB proxy target group already gone, treating as deleted: {0}", targetGroupArn); + } + } + + private static String firstNonBlank(String value, String fallback) { + return (value == null || value.isBlank()) ? fallback : value; + } + + private Integer parseOptionalIntProp(JsonNode props, String name, CloudFormationTemplateEngine engine) { + String value = resolveOptional(props, name, engine); + if (value == null || value.isBlank()) { + return null; + } + try { + return Integer.valueOf(value.trim()); + } catch (NumberFormatException e) { + throw new AwsException("InvalidParameterValue", name + " must be an integer.", 400); + } + } + + private boolean parseBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) { + return Boolean.parseBoolean(resolveOptional(props, name, engine)); + } + + // ── helpers copied from the monolith, which keeps its own copies for the types still there ── + + private String resolveOptional(JsonNode props, String name, CloudFormationTemplateEngine engine) { + if (props == null || !props.has(name) || props.get(name).isNull()) { + return null; + } + return engine.resolve(props.get(name)); + } + + private List resolveStringList(JsonNode props, String field, CloudFormationTemplateEngine engine) { + if (props == null || !props.has(field)) { + return new ArrayList<>(); + } + return new ArrayList<>(engine.resolveStringList(props.get(field))); + } + + /** + * Resolves a property without the engine's general dynamic-reference stage, for the two RDS + * master-credential properties that resolve their own references with {@code ssm-secure} + * allowed. The general stage rejects {@code ssm-secure}, so running it first would fail the + * one case AWS permits it. Mirrors the monolith helper of the same name. + */ + private String resolveOptionalWithoutDynamicReferences(JsonNode props, String name, + CloudFormationTemplateEngine engine) { + if (props == null || !props.has(name) || props.get(name).isNull()) { + return null; + } + return engine.resolveWithoutDynamicReferences(props.get(name)); + } + + private String resolveDynamicReferences(String value, String region, boolean allowSsmSecure) { + return dynamicReferences.resolveDynamicReferences(value, region, allowSsmSecure); + } + + private Map parseCfnTags(JsonNode tagsNode, CloudFormationTemplateEngine engine) { + tagsNode = engine.resolveNode(tagsNode); + Map out = new HashMap<>(); + if (tagsNode == null || tagsNode.isNull() || !tagsNode.isArray()) { + return out; + } + for (JsonNode entry : tagsNode) { + JsonNode resolved = engine.resolveNode(entry); + String key = resolved.path("Key").asText(null); + String value = resolved.path("Value").asText(""); + if (key != null) { + out.put(key, value); + } + } + return out; + } + + private T sameNameExistingResource(String priorPhysicalId, String name, + java.util.function.Function lookup) { + if (priorPhysicalId == null || !priorPhysicalId.equals(name)) { + return null; + } + try { + return lookup.apply(name); + } catch (AwsException notFound) { + // Expected when the resource was deleted out of band since the prior update; the + // caller falls back to creating it fresh under the same name. + LOG.debugv(notFound, "No existing {0} found on file, falling back to create", name); + return null; + } + } + + private void deleteRenamedResource(String priorPhysicalId, String newName, + java.util.function.Consumer delete, String resourceKind) { + if (priorPhysicalId == null || priorPhysicalId.equals(newName)) { + return; + } + try { + delete.accept(priorPhysicalId); + } catch (RuntimeException e) { + LOG.warnv(e, "Failed to delete renamed {0} {1} after replacement by {2}", + resourceKind, priorPhysicalId, newName); + } + } + + private int parseIntProp(JsonNode props, String name, CloudFormationTemplateEngine engine, int fallback) { + String value = resolveOptional(props, name, engine); + if (value == null || value.isBlank()) { + return fallback; + } + try { + return Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + LOG.debugv(e, "Non-numeric {0} value {1}; falling back to {2}", name, value, fallback); + return fallback; + } + } +} 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 index 90732492d2..dd0057c384 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -62,6 +62,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEve import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaVersionAliasCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.PipesCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.RdsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Route53CfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.S3CfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.SchedulerScheduleGroupCfnProvisioner; @@ -215,6 +216,7 @@ final class CfnProvisionerFixture { * behind silently. */ private List inferredProvisioners() { + ensureDynamicReferences(); List discovered = new ArrayList<>(); discovered.add(new CdkMetadataCfnProvisioner()); if (s3Service != null) { @@ -316,6 +318,9 @@ final class CfnProvisionerFixture { if (batchService != null) { discovered.add(new BatchCfnProvisioner(batchService)); } + if (rdsService != null) { + discovered.add(new RdsCfnProvisioner(rdsService, dynamicReferences)); + } if (wafV2Service != null) { discovered.add(new WafV2CfnProvisioner(wafV2Service)); } @@ -586,6 +591,21 @@ final class CfnProvisionerFixture { return this; } + /** + * Wires {@link CfnDynamicReferences} from the services already named, the way CDI does in + * production, so a test resolving {{@code resolve:ssm:...}} does not have to know that + * resolution moved out of the provisioner. + * + *

Called before the registry is built, not only from {@link #build()}: RdsCfnProvisioner + * takes it as a constructor argument, so inferring the provisioners needs it in hand. + */ + private void ensureDynamicReferences() { + if (dynamicReferences == null) { + dynamicReferences = new CfnDynamicReferences( + secretsManagerService, ssmService, objectMapper); + } + } + /** The registry {@link #build()} would use: explicit if the test chose one, else inferred. */ CloudFormationResourceRegistry buildRegistry() { return registryChosenByTest @@ -597,13 +617,7 @@ final class CfnProvisionerFixture { if (!registryChosenByTest) { resourceRegistry = buildRegistry(); } - 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); - } + ensureDynamicReferences(); return new CloudFormationResourceProvisioner( s3Service, snsService, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsDynamicReferenceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsDynamicReferenceIntegrationTest.java new file mode 100644 index 0000000000..437618f616 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsDynamicReferenceIntegrationTest.java @@ -0,0 +1,200 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * RDS master credentials are the only properties where {@code {{resolve:ssm-secure:...}}} is + * legal. Every other property resolves dynamic references through the template engine's general + * stage, which rejects {@code ssm-secure} outright, so the two RDS credential properties opt out + * of that stage and resolve their own references with the elevated permission. + * + *

That opt-out is invisible to the rest of the suite. {@code RdsCfnProvisionerTest} builds its + * engine without a dynamic-reference resolver, so the general stage is disabled there and its + * assertions hold whether or not the opt-out survives. + * {@code CloudFormationDynamicReferenceIntegrationTest} covers the general path and the + * {@code ssm-secure} rejection, but has no RDS case. Without the tests below, dropping the opt-out + * leaves the whole suite green and breaks {@code ssm-secure} on the one resource that accepts it. + */ +@QuarkusTest +@TestProfile(CloudFormationRdsDynamicReferenceIntegrationTest.RdsMockProfile.class) +class CloudFormationRdsDynamicReferenceIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + /** + * The regression gate. A master password reading from an SSM {@code SecureString} must reach + * {@code CREATE_COMPLETE}. If the credential properties stop opting out of the general stage, + * that stage rejects the reference and the stack rolls back instead. + */ + @Test + void createStack_rdsMasterPasswordResolvesSsmSecureDynamicReference() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String parameterName = "/cfn-rds-dynref/secure-password-" + suffix; + String stackName = "cfn-rds-dynref-secure-stack-" + suffix; + String databaseId = "cfn-rds-dynref-secure-db-" + suffix; + putParameter(parameterName, "s3cret-from-ssm", "SecureString"); + boolean stackCreated = false; + + try { + createStack(stackName, template(databaseId, + "{{resolve:ssm-secure:" + parameterName + "}}")); + stackCreated = true; + + String describeXml = describeStack(stackName); + assertTrue(describeXml.contains("CREATE_COMPLETE"), + "an ssm-secure master password is legal on RDS and must provision: " + describeXml); + } finally { + if (stackCreated) { + deleteStack(stackName); + awaitStackDeleted(stackName); + } + deleteParameter(parameterName); + } + } + + /** + * The other direction. Opting out of the general stage must not cost the credential properties + * the ordinary {@code ssm} reference, which they resolve themselves. + */ + @Test + void createStack_rdsMasterPasswordResolvesPlainSsmDynamicReference() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String parameterName = "/cfn-rds-dynref/plain-password-" + suffix; + String stackName = "cfn-rds-dynref-plain-stack-" + suffix; + String databaseId = "cfn-rds-dynref-plain-db-" + suffix; + putParameter(parameterName, "plain-from-ssm", "String"); + boolean stackCreated = false; + + try { + createStack(stackName, template(databaseId, + "{{resolve:ssm:" + parameterName + "}}")); + stackCreated = true; + + String describeXml = describeStack(stackName); + assertTrue(describeXml.contains("CREATE_COMPLETE"), + "a plain ssm master password must still resolve: " + describeXml); + } finally { + if (stackCreated) { + deleteStack(stackName); + awaitStackDeleted(stackName); + } + deleteParameter(parameterName); + } + } + + private static String template(String databaseId, String masterPassword) { + return """ + { + "Resources": { + "Database": { + "Type": "AWS::RDS::DBInstance", + "Properties": { + "DBInstanceIdentifier": "%s", + "Engine": "postgres", + "MasterUsername": "dbadmin", + "MasterUserPassword": "%s", + "DBName": "appdb", + "DBInstanceClass": "db.t3.micro", + "AllocatedStorage": 20 + } + } + } + } + """.formatted(databaseId, masterPassword); + } + + private static void putParameter(String name, String value, String type) { + given() + .header("X-Amz-Target", "AmazonSSM.PutParameter") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "%s", + "Value": "%s", + "Type": "%s", + "Overwrite": true + } + """.formatted(name, value, type)) + .when().post("/").then().statusCode(200); + } + + private static void deleteParameter(String name) { + given() + .header("X-Amz-Target", "AmazonSSM.DeleteParameter") + .contentType(SSM_CONTENT_TYPE) + .body("{\"Name\":\"" + name + "\"}") + .when().post("/"); + } + + private static void createStack(String stackName, String template) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200); + } + + private static String describeStack(String stackName) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200).extract().asString(); + } + + private static void deleteStack(String stackName) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200); + } + + private static void awaitStackDeleted(String stackName) throws InterruptedException { + for (int i = 0; i < 100; i++) { + String body = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when().post("/").then().extract().asString(); + if (body.contains("does not exist")) { + return; + } + if (body.contains("DELETE_FAILED")) { + fail("stack delete failed: " + body); + } + Thread.sleep(50); + } + fail("stack " + stackName + " was not deleted within the timeout"); + } + + public static final class RdsMockProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.rds.mock", "true"); + } + } +} diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 8304e40b0c..9d32245c59 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -26,4 +26,23 @@ AWS::Pipes::Pipe CreationTime pipe lifecycle timestamps are not tracked AWS::Pipes::Pipe CurrentState pipe state transitions are not modelled AWS::Pipes::Pipe LastModifiedTime pipe lifecycle timestamps are not tracked AWS::Pipes::Pipe StateReason pipe state transitions are not modelled +AWS::RDS::DBCluster DBClusterResourceId not set by the legacy switch; closable, deferred to a follow-up PR to keep this one a pure move +AWS::RDS::DBCluster Endpoint the dotted Endpoint.Address and Endpoint.Port are set instead, which is the form AWS's GetAtt actually exposes +AWS::RDS::DBCluster ReadEndpoint ReadEndpoint.Address is set instead, the form AWS's GetAtt exposes +AWS::RDS::DBCluster StorageEncryptionType cluster storage encryption is not emulated +AWS::RDS::DBCluster StorageThroughput provisioned storage throughput is not emulated +AWS::RDS::DBInstance AutomaticRestartTime instance restart scheduling is not emulated +AWS::RDS::DBInstance CertificateDetails per-instance CA certificate metadata is not emulated +AWS::RDS::DBInstance DBInstanceStatus the model carries no lifecycle status; instances reach available synchronously +AWS::RDS::DBInstance DbiResourceId not set by the legacy switch; closable, deferred to a follow-up PR to keep this one a pure move +AWS::RDS::DBInstance InstanceCreateTime creation timestamps are not recorded on the instance +AWS::RDS::DBInstance IsStorageConfigUpgradeAvailable storage configuration upgrades are not emulated +AWS::RDS::DBInstance LatestRestorableTime point-in-time restore windows are not emulated +AWS::RDS::DBInstance ListenerEndpoint the SQL Server listener endpoint is not emulated +AWS::RDS::DBInstance PercentProgress no asynchronous progress to report; instances reach available synchronously +AWS::RDS::DBInstance ReadReplicaDBClusterIdentifiers read replicas are not emulated +AWS::RDS::DBInstance ReadReplicaDBInstanceIdentifiers read replicas are not emulated +AWS::RDS::DBInstance ResumeFullAutomationModeTime RDS Custom automation mode is not emulated +AWS::RDS::DBInstance SecondaryAvailabilityZone multi-AZ secondary placement is not emulated +AWS::RDS::DBInstance StatusInfos read-replica status detail is not emulated AWS::SQS::QueuePolicy Id schema gives no description; the policy has no backing entity to take an id from diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index bae1f45baf..9d43b527bf 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -109,13 +109,13 @@ AWS::Organizations::OrganizationalUnit OrganizationsCfnProvisioner AWS::Organizations::Policy OrganizationsCfnProvisioner AWS::Organizations::ResourcePolicy OrganizationsCfnProvisioner AWS::Pipes::Pipe PipesCfnProvisioner -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::RDS::DBCluster RdsCfnProvisioner +AWS::RDS::DBClusterParameterGroup RdsCfnProvisioner +AWS::RDS::DBInstance RdsCfnProvisioner +AWS::RDS::DBParameterGroup RdsCfnProvisioner +AWS::RDS::DBProxy RdsCfnProvisioner +AWS::RDS::DBProxyTargetGroup RdsCfnProvisioner +AWS::RDS::DBSubnetGroup RdsCfnProvisioner AWS::Route53::HostedZone Route53CfnProvisioner AWS::Route53::RecordSet LEGACY_SWITCH AWS::S3::Bucket S3CfnProvisioner