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 c66e93224c..655b962f1c 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 @@ -29,7 +29,6 @@ import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex; import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement; import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex; import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition; -import io.github.hectorvent.floci.services.docdb.DocDbService; import io.github.hectorvent.floci.services.ecr.EcrService; import io.github.hectorvent.floci.services.ecr.model.Repository; import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService; @@ -53,13 +52,6 @@ import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair; import io.github.hectorvent.floci.services.firehose.FirehoseService; import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription; -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 io.github.hectorvent.floci.services.eks.EksService; import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest; import io.github.hectorvent.floci.services.eks.model.Nodegroup; @@ -74,7 +66,6 @@ import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion; import io.github.hectorvent.floci.services.pipes.PipesService; import io.github.hectorvent.floci.services.pipes.model.DesiredState; import io.github.hectorvent.floci.services.s3.S3Service; -import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService; import io.github.hectorvent.floci.services.sns.SnsService; import io.github.hectorvent.floci.services.sqs.SqsService; import io.github.hectorvent.floci.services.ssm.SsmService; @@ -134,13 +125,9 @@ public class CloudFormationResourceProvisioner { private static final String NAME_MODE_GENERATED = "generated"; private static final int GENERATED_NAME_SUFFIX_LENGTH = 12; private static final int STEP_FUNCTIONS_NAME_MAX_LENGTH = 80; - private static final String SECRET_TARGET_MANAGED_KEYS_ATTR = "__FlociSecretTargetManagedKeys"; - private static final String SECRET_TARGET_OWNER_ATTR = "__FlociSecretTargetOwner"; private static final String DDB_REPLICA_TABLE_NAME_ATTR = "TableName"; private static final String DDB_REPLICA_REGION_ATTR = "__FlociDynamoDbReplicaRegion"; private static final String DDB_REPLICA_SKIP_DELETION_ATTR = "__FlociDynamoDbReplicaSkipDeletion"; - private static final List SECRET_TARGET_CONNECTION_KEYS = List.of( - "engine", "host", "port", "dbname", "dbInstanceIdentifier", "dbClusterIdentifier"); private static final int LAMBDA_DEFAULT_TIMEOUT_SECONDS = 3; private static final int LAMBDA_DEFAULT_MEMORY_MB = 128; private static final int LAMBDA_DEFAULT_EPHEMERAL_STORAGE_MB = 512; @@ -176,7 +163,6 @@ public class CloudFormationResourceProvisioner { "AWS::EKS::Nodegroup", "AWS::IAM::ManagedPolicy", "AWS::IAM::Policy", - "AWS::SecretsManager::SecretTargetAttachment", "Custom::DynamoDBReplica"); static final Set LEGACY_SWITCH_TYPES = Set.of( @@ -209,8 +195,6 @@ public class CloudFormationResourceProvisioner { "AWS::Lambda::Function", "AWS::Lambda::LayerVersion", "AWS::Route53::RecordSet", - "AWS::SecretsManager::Secret", - "AWS::SecretsManager::SecretTargetAttachment", "AWS::StepFunctions::StateMachine", "Custom::DynamoDBReplica"); @@ -228,7 +212,6 @@ public class CloudFormationResourceProvisioner { private final DynamoDbService dynamoDbService; private final LambdaService lambdaService; private final IamService iamService; - private final SecretsManagerService secretsManagerService; private final ApiGatewayService apiGatewayService; private final ApiGatewayV2Service apiGatewayV2Service; private final LambdaLayerService lambdaLayerService; @@ -237,10 +220,8 @@ public class CloudFormationResourceProvisioner { private final ContainerReachableEndpoint reachableEndpoint; private final StepFunctionsService stepFunctionsService; private final Ec2Service ec2Service; - private final RdsService rdsService; private final EksService eksService; private final AutoScalingService autoScalingService; - private final DocDbService docDbService; private final CloudFrontService cloudFrontService; // Item 15 decomposition: extracted per-service provisioners are consulted before the switch // below. As types migrate, their switch cases and provisionXxx methods are removed here; the @@ -254,7 +235,6 @@ public class CloudFormationResourceProvisioner { SnsService snsService, DynamoDbService dynamoDbService, LambdaService lambdaService, IamService iamService, SsmService ssmService, KmsService kmsService, - SecretsManagerService secretsManagerService, ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service, EcrService ecrService, @@ -265,14 +245,12 @@ public class CloudFormationResourceProvisioner { ContainerReachableEndpoint reachableEndpoint, StepFunctionsService stepFunctionsService, Ec2Service ec2Service, - RdsService rdsService, EksService eksService, CloudWatchLogsService logsService, KinesisService kinesisService, CloudWatchMetricsService cloudWatchMetricsService, AutoScalingService autoScalingService, FirehoseService firehoseService, - DocDbService docDbService, CloudFrontService cloudFrontService, CloudFormationResourceRegistry resourceRegistry, CfnDynamicReferences dynamicReferences, @@ -282,7 +260,6 @@ public class CloudFormationResourceProvisioner { this.dynamoDbService = dynamoDbService; this.lambdaService = lambdaService; this.iamService = iamService; - this.secretsManagerService = secretsManagerService; this.apiGatewayService = apiGatewayService; this.apiGatewayV2Service = apiGatewayV2Service; this.lambdaLayerService = lambdaLayerService; @@ -291,10 +268,8 @@ public class CloudFormationResourceProvisioner { this.reachableEndpoint = reachableEndpoint; this.stepFunctionsService = stepFunctionsService; this.ec2Service = ec2Service; - this.rdsService = rdsService; this.eksService = eksService; this.autoScalingService = autoScalingService; - this.docDbService = docDbService; this.cloudFrontService = cloudFrontService; this.resourceRegistry = resourceRegistry; this.dynamicReferences = dynamicReferences; @@ -351,9 +326,6 @@ public class CloudFormationResourceProvisioner { case "AWS::IAM::ManagedPolicy" -> provisionIamManagedPolicy(resource, properties, engine, accountId, stackName); case "AWS::IAM::InstanceProfile" -> provisionInstanceProfile(resource, properties, engine, accountId, stackName); - case "AWS::SecretsManager::Secret" -> provisionSecret(resource, properties, engine, region, accountId, stackName); - case "AWS::SecretsManager::SecretTargetAttachment" -> - provisionSecretTargetAttachment(resource, properties, engine, region, stackName); case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine); case "AWS::ApiGateway::RestApi" -> provisionApiGatewayRestApi(resource, properties, engine, region, accountId, stackName); case "AWS::ApiGateway::Resource" -> provisionApiGatewayResource(resource, properties, engine, region); @@ -539,10 +511,6 @@ public class CloudFormationResourceProvisioner { deleteCustomResource(resource, region); return; } - if ("AWS::SecretsManager::SecretTargetAttachment".equals(resourceType)) { - deleteSecretTargetAttachment(resource, region); - return; - } // Nodegroup deletion needs both the cluster name (from a Fn::GetAtt attribute) and the // nodegroup name (the physical id), which the type/physicalId delete path can't provide. if ("AWS::EKS::Nodegroup".equals(resourceType)) { @@ -611,11 +579,6 @@ public class CloudFormationResourceProvisioner { case "AWS::IAM::Policy" -> { } case "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId); case "AWS::IAM::InstanceProfile" -> iamService.deleteInstanceProfile(physicalId); - case "AWS::SecretsManager::Secret" -> deleteSecretSafe(physicalId, region); - case "AWS::SecretsManager::SecretTargetAttachment" -> throw new AwsException( - "ValidationError", - "SecretTargetAttachment deletion requires the StackResource metadata that records its managed fields.", - 400); // No bus context on the type/physicalId path (e.g. CREATE-rollback); targets the default bus. case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId); case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId); @@ -2484,433 +2447,6 @@ public class CloudFormationResourceProvisioner { // ── KMS ─────────────────────────────────────────────────────────────────── - // ── Secrets Manager ─────────────────────────────────────────────────────── - - private void provisionSecret(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String accountId, String stackName) { - String name = resolveOptional(props, "Name", engine); - if (name == null || name.isBlank()) { - name = generatePhysicalName(stackName, r.getLogicalId(), 512, false); - } - String description = resolveOptional(props, "Description", engine); - String value = resolveSecretValue(props, engine); - var secret = secretsManagerService.createSecret(name, value, null, description, null, List.of(), region); - r.setPhysicalId(secret.getArn()); - r.getAttributes().put("Arn", secret.getArn()); - r.getAttributes().put("Name", name); - } - - /** Provisions an AWS-compatible Secrets Manager database target attachment. */ - private void provisionSecretTargetAttachment(StackResource r, JsonNode props, - CloudFormationTemplateEngine engine, String region, - String stackName) { - String secretId = requireSecretTargetProperty(props, "SecretId", engine); - String targetId = requireSecretTargetProperty(props, "TargetId", engine); - String targetType = requireSecretTargetProperty(props, "TargetType", engine); - validateSecretTargetType(targetType); - SecretTargetConnection connection = resolveSecretTargetConnection(targetType, targetId); - - String previousSecretId = r.getPhysicalId(); - String previousManagedKeys = r.getAttributes().get(SECRET_TARGET_MANAGED_KEYS_ATTR); - String attachmentOwner = r.getAttributes().getOrDefault( - SECRET_TARGET_OWNER_ATTR, stackName + "/" + r.getLogicalId()); - String secretArn = secretsManagerService.describeSecret(secretId, region).getArn(); - String previousSecretArn = canonicalExistingSecretArn(previousSecretId, secretArn, region); - boolean replacingSecret = previousSecretArn != null && !previousSecretArn.equals(secretArn); - boolean claimCreated = false; - boolean wroteNewSecret = false; - boolean detachedPreviousSecret = false; - ObjectNode currentSecretJson = null; - SecretTargetMutation previousDetach = null; - - try { - claimCreated = secretsManagerService.claimTargetAttachment( - secretArn, attachmentOwner, region); - - currentSecretJson = readSecretJsonObject(secretArn, region); - ObjectNode desiredSecretJson = currentSecretJson.deepCopy(); - SECRET_TARGET_CONNECTION_KEYS.forEach(desiredSecretJson::remove); - - List managedKeys = new ArrayList<>(); - addSecretTargetConnection(desiredSecretJson, managedKeys, connection); - - if (replacingSecret) { - previousDetach = prepareSecretTargetDetach(previousSecretArn, previousManagedKeys, region); - } - if (!desiredSecretJson.equals(currentSecretJson)) { - secretsManagerService.putSecretValue( - secretArn, desiredSecretJson.toString(), null, null, region, null); - wroteNewSecret = true; - } - if (previousDetach != null) { - putSecretTargetMutation(previousDetach, region); - detachedPreviousSecret = true; - } - if (replacingSecret) { - secretsManagerService.releaseTargetAttachment( - previousSecretArn, attachmentOwner, region); - } - - r.setPhysicalId(secretArn); - r.getAttributes().remove("Arn"); - r.getAttributes().put("Id", secretArn); - r.getAttributes().put(SECRET_TARGET_OWNER_ATTR, attachmentOwner); - r.getAttributes().put(SECRET_TARGET_MANAGED_KEYS_ATTR, String.join(",", managedKeys)); - } catch (RuntimeException failure) { - if (detachedPreviousSecret && previousDetach != null) { - ObjectNode previousValue = previousDetach.originalValue(); - attemptSecretTargetCleanup(failure, "restore previous secret " + previousSecretArn, - () -> secretsManagerService.putSecretValue( - previousSecretArn, previousValue.toString(), - null, null, region, null)); - } - if (wroteNewSecret && currentSecretJson != null) { - ObjectNode originalValue = currentSecretJson; - attemptSecretTargetCleanup(failure, "restore new secret " + secretArn, - () -> secretsManagerService.putSecretValue( - secretArn, originalValue.toString(), - null, null, region, null)); - } - if (claimCreated) { - attemptSecretTargetCleanup(failure, "release target attachment claim for " + secretArn, - () -> secretsManagerService.releaseTargetAttachment( - secretArn, attachmentOwner, region)); - } - throw failure; - } - } - - private static void validateSecretTargetType(String targetType) { - if (!Set.of( - "AWS::RDS::DBInstance", - "AWS::RDS::DBCluster", - "AWS::DocDB::DBInstance", - "AWS::DocDB::DBCluster").contains(targetType)) { - throw new AwsException("ValidationError", - "SecretTargetAttachment TargetType " + targetType - + " is not supported by Floci; supported values are AWS::RDS::DBInstance," - + " AWS::RDS::DBCluster, AWS::DocDB::DBInstance," - + " and AWS::DocDB::DBCluster.", 400); - } - } - - private String canonicalExistingSecretArn(String secretId, String newSecretArn, String region) { - if (secretId == null || secretId.isBlank() || secretId.equals(newSecretArn)) { - return secretId; - } - try { - return secretsManagerService.describeSecret(secretId, region).getArn(); - } catch (AwsException e) { - if ("ResourceNotFoundException".equals(e.getErrorCode())) { - return null; - } - throw e; - } - } - - private String requireSecretTargetProperty(JsonNode props, String name, - CloudFormationTemplateEngine engine) { - String value = resolveOptional(props, name, engine); - if (value == null || value.isBlank()) { - throw new AwsException("ValidationError", - "AWS::SecretsManager::SecretTargetAttachment requires " + name + ".", 400); - } - return value; - } - - private ObjectNode readSecretJsonObject(String secretId, String region) { - return tryReadSecretJsonObject(secretId, region) - .orElseThrow(CloudFormationResourceProvisioner::invalidSecretTargetValue); - } - - private Optional tryReadSecretJsonObject(String secretId, String region) { - String secretString = secretsManagerService - .getSecretValue(secretId, null, null, region) - .getSecretString(); - if (secretString == null) { - return Optional.empty(); - } - try { - JsonNode parsed = objectMapper.readTree(secretString); - if (parsed == null || !parsed.isObject()) { - return Optional.empty(); - } - return Optional.of(((ObjectNode) parsed).deepCopy()); - } catch (JsonProcessingException e) { - return Optional.empty(); - } - } - - private static AwsException invalidSecretTargetValue() { - return new AwsException("ValidationError", - "SecretString for AWS::SecretsManager::SecretTargetAttachment must be a JSON object.", 400); - } - - private SecretTargetConnection resolveSecretTargetConnection(String targetType, String targetId) { - return switch (targetType) { - case "AWS::RDS::DBInstance" -> dbInstanceConnection(targetId); - case "AWS::RDS::DBCluster" -> dbClusterConnection(targetId); - case "AWS::DocDB::DBInstance" -> docDbInstanceConnection(targetId); - case "AWS::DocDB::DBCluster" -> docDbClusterConnection(targetId); - default -> throw new IllegalStateException("Validated target type was not handled: " + targetType); - }; - } - - private SecretTargetConnection dbInstanceConnection(String targetId) { - var instance = rdsService.getDbInstance(targetId); - if (instance == null || instance.getEngine() == null || instance.getEndpoint() == null - || instance.getEndpoint().address() == null - || instance.getEndpoint().address().isBlank() - || instance.getEndpoint().port() <= 0 - || instance.getDbInstanceIdentifier() == null - || instance.getDbInstanceIdentifier().isBlank()) { - throw incompleteSecretTarget(targetId); - } - return new SecretTargetConnection( - instance.getEngine().name().toLowerCase(Locale.ROOT), - instance.getEndpoint().address(), - instance.getEndpoint().port(), - instance.getDbName(), - "dbInstanceIdentifier", - instance.getDbInstanceIdentifier()); - } - - private SecretTargetConnection dbClusterConnection(String targetId) { - var cluster = rdsService.getDbCluster(targetId); - if (cluster == null || cluster.getEngine() == null || cluster.getEndpoint() == null - || cluster.getEndpoint().address() == null - || cluster.getEndpoint().address().isBlank() - || cluster.getEndpoint().port() <= 0 - || cluster.getDbClusterIdentifier() == null - || cluster.getDbClusterIdentifier().isBlank()) { - throw incompleteSecretTarget(targetId); - } - return new SecretTargetConnection( - cluster.getEngine().name().toLowerCase(Locale.ROOT), - cluster.getEndpoint().address(), - cluster.getEndpoint().port(), - cluster.getDatabaseName(), - "dbClusterIdentifier", - cluster.getDbClusterIdentifier()); - } - - private SecretTargetConnection docDbInstanceConnection(String targetId) { - var instance = docDbService.getDbInstance(targetId); - if (instance == null || instance.getEndpoint() == null - || instance.getEndpoint().isBlank() - || instance.getPort() <= 0 - || instance.getDbInstanceIdentifier() == null - || instance.getDbInstanceIdentifier().isBlank()) { - throw incompleteSecretTarget(targetId); - } - return new SecretTargetConnection( - "mongo", - instance.getEndpoint(), - instance.getPort(), - null, - "dbInstanceIdentifier", - instance.getDbInstanceIdentifier()); - } - - private SecretTargetConnection docDbClusterConnection(String targetId) { - var cluster = docDbService.getDbCluster(targetId); - if (cluster == null || cluster.getEndpoint() == null - || cluster.getEndpoint().isBlank() - || cluster.getPort() <= 0 - || cluster.getDbClusterIdentifier() == null - || cluster.getDbClusterIdentifier().isBlank()) { - throw incompleteSecretTarget(targetId); - } - return new SecretTargetConnection( - "mongo", - cluster.getEndpoint(), - cluster.getPort(), - null, - "dbClusterIdentifier", - cluster.getDbClusterIdentifier()); - } - - private static void addSecretTargetConnection(ObjectNode secretJson, List managedKeys, - SecretTargetConnection connection) { - putSecretTargetField(secretJson, managedKeys, "engine", connection.engine()); - putSecretTargetField(secretJson, managedKeys, "host", connection.host()); - putSecretTargetField(secretJson, managedKeys, "port", connection.port()); - putOptionalSecretTargetField(secretJson, managedKeys, "dbname", connection.dbname()); - putSecretTargetField(secretJson, managedKeys, - connection.identifierKey(), connection.identifier()); - } - - private static AwsException incompleteSecretTarget(String targetId) { - return new AwsException("ValidationError", - "SecretTargetAttachment target " + targetId + " has incomplete connection information.", 400); - } - - private record SecretTargetConnection(String engine, String host, int port, String dbname, - String identifierKey, String identifier) { - } - - private record SecretTargetMutation(String secretId, ObjectNode originalValue, ObjectNode value) { - } - - private static void putSecretTargetField(ObjectNode secretJson, List managedKeys, - String name, String value) { - secretJson.put(name, value); - managedKeys.add(name); - } - - private static void putSecretTargetField(ObjectNode secretJson, List managedKeys, - String name, int value) { - secretJson.put(name, value); - managedKeys.add(name); - } - - private static void putOptionalSecretTargetField(ObjectNode secretJson, List managedKeys, - String name, String value) { - if (value != null && !value.isBlank()) { - putSecretTargetField(secretJson, managedKeys, name, value); - } - } - - private void deleteSecretTargetAttachment(StackResource resource, String region) { - String attachmentOwner = resource.getAttributes().get(SECRET_TARGET_OWNER_ATTR); - if (!secretsManagerService.canManageTargetAttachment( - resource.getPhysicalId(), attachmentOwner, region)) { - LOG.warnv("Skipping SecretTargetAttachment detach because secret {0}" - + " is owned by a different attachment", - resource.getPhysicalId()); - return; - } - detachSecretTarget(resource.getPhysicalId(), - resource.getAttributes().get(SECRET_TARGET_MANAGED_KEYS_ATTR), region); - secretsManagerService.releaseTargetAttachment( - resource.getPhysicalId(), attachmentOwner, region); - } - - private void detachSecretTarget(String secretId, String managedKeysAttribute, String region) { - SecretTargetMutation mutation = prepareSecretTargetDetach(secretId, managedKeysAttribute, region); - if (mutation != null) { - putSecretTargetMutation(mutation, region); - } - } - - private SecretTargetMutation prepareSecretTargetDetach(String secretId, - String managedKeysAttribute, - String region) { - try { - Optional parsedSecret = tryReadSecretJsonObject(secretId, region); - if (parsedSecret.isEmpty()) { - LOG.debugv("SecretTargetAttachment current secret value is no longer a JSON object;" - + " treating as already detached: {0}", secretId); - return null; - } - ObjectNode currentSecretJson = parsedSecret.get(); - ObjectNode detachedSecretJson = currentSecretJson.deepCopy(); - List managedKeys = managedSecretTargetKeys(managedKeysAttribute); - managedKeys.forEach(detachedSecretJson::remove); - return detachedSecretJson.equals(currentSecretJson) - ? null - : new SecretTargetMutation(secretId, currentSecretJson, detachedSecretJson); - } catch (AwsException e) { - if (!"ResourceNotFoundException".equals(e.getErrorCode())) { - throw e; - } - LOG.debugv("SecretTargetAttachment secret already gone, treating as detached: {0}", secretId); - return null; - } - } - - private void putSecretTargetMutation(SecretTargetMutation mutation, String region) { - secretsManagerService.putSecretValue( - mutation.secretId(), mutation.value().toString(), null, null, region, null); - } - - private void attemptSecretTargetCleanup(RuntimeException primaryFailure, - String description, - Runnable cleanup) { - try { - cleanup.run(); - } catch (RuntimeException cleanupFailure) { - primaryFailure.addSuppressed(cleanupFailure); - LOG.warnv("SecretTargetAttachment rollback cleanup failed while attempting to {0}: {1}", - description, cleanupFailure.getMessage()); - } - } - - private static List managedSecretTargetKeys(String attribute) { - if (attribute == null || attribute.isBlank()) { - return SECRET_TARGET_CONNECTION_KEYS; - } - List keys = Arrays.stream(attribute.split(",")) - .filter(SECRET_TARGET_CONNECTION_KEYS::contains) - .toList(); - return keys.isEmpty() ? SECRET_TARGET_CONNECTION_KEYS : keys; - } - - /** - * Resolves the secret value from CloudFormation properties. - * SecretString and GenerateSecretString are mutually exclusive per AWS spec. - * If GenerateSecretString is present, a random password is generated. - * If SecretStringTemplate and GenerateStringKey are specified inside - * GenerateSecretString, the generated password is embedded in the template JSON. - */ - private String resolveSecretValue(JsonNode props, CloudFormationTemplateEngine engine) { - if (props == null) { - return "{}"; - } - - // SecretString takes precedence when explicitly set - String secretString = resolveOptional(props, "SecretString", engine); - JsonNode genNode = props.get("GenerateSecretString"); - - if (secretString != null && genNode != null && !genNode.isNull()) { - throw new AwsException("ValidationError", - "You can't specify both SecretString and GenerateSecretString", 400); - } - - if (secretString != null) { - return secretString; - } - - if (genNode != null && !genNode.isNull()) { - return generateSecretString(genNode); - } - - return "{}"; - } - - private String generateSecretString(JsonNode genNode) { - String password = io.github.hectorvent.floci.services.secretsmanager - .RandomPasswordGenerator.generate(genNode); - - String template = null; - String key = null; - JsonNode templateNode = genNode.get("SecretStringTemplate"); - JsonNode keyNode = genNode.get("GenerateStringKey"); - - if (templateNode != null && !templateNode.isNull()) { - template = templateNode.asText(); - } - if (keyNode != null && !keyNode.isNull()) { - key = keyNode.asText(); - } - - if (template != null && key != null) { - // Insert the generated password into the template JSON - try { - var mapper = new com.fasterxml.jackson.databind.ObjectMapper(); - var tree = (com.fasterxml.jackson.databind.node.ObjectNode) mapper.readTree(template); - tree.put(key, password); - return mapper.writeValueAsString(tree); - } catch (Exception e) { - // If the template is not valid JSON, fall back to raw password - LOG.warnv("Failed to parse SecretStringTemplate: {0}", e.getMessage()); - return password; - } - } - - return password; - } - private void putResolvedText(ObjectNode req, String target, JsonNode props, String source, CloudFormationTemplateEngine engine) { @@ -5419,16 +4955,6 @@ public class CloudFormationResourceProvisioner { resource.getAttributes().remove(INLINE_CLEANUP_GROUP_TARGETS_ATTR); } - private void deleteSecretSafe(String secretId, String region) { - try { - secretsManagerService.deleteSecret(secretId, null, true, region); - } catch (AwsException e) { - if (!"ResourceNotFoundException".equals(e.getErrorCode())) { - throw e; - } - LOG.debugv("Secret already gone, treating as deleted: {0}", secretId); - } - } /** * Generate an AWS-like physical name: {stackName}-{logicalId}-{randomSuffix}. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java new file mode 100644 index 0000000000..67a2e91c03 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java @@ -0,0 +1,448 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.docdb.DocDbService; +import io.github.hectorvent.floci.services.docdb.model.DocDbCluster; +import io.github.hectorvent.floci.services.docdb.model.DocDbInstance; +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.DbInstance; +import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.Set; + +/** + * Provisions {@code AWS::SecretsManager::SecretTargetAttachment}. + * + *

Extracted from {@code CloudFormationResourceProvisioner}. Unlike most provisioners this one + * wraps three services rather than one: an attachment reads the endpoint of the RDS or DocumentDB + * instance or cluster it points at, so it can write the connection detail (engine, host, port, + * dbname, identifier) into the target secret. That dependency is inherent to the type, and it is + * the reason {@code RdsService} stayed in the monolith when the RDS types moved out. + * + *

This type deletes with the stored {@link StackResource}, not the physical id alone, so it + * overrides {@code delete(StackResource, String)}. The delete needs two create-time attributes + * that no physical id carries: which secret fields this attachment managed, so only those are + * stripped, and which attachment owns the secret, so a second attachment's fields are left alone. + * Registering that here is what lets the type leave the engine's + * {@code DELETE_NEEDS_STACK_RESOURCE} set; the two must change together or + * {@code CfnDeletePrecedenceTest} fails with both claiming it. + */ +@ApplicationScoped +public class SecretTargetAttachmentCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::SecretsManager::SecretTargetAttachment"; + + private static final Logger LOG = Logger.getLogger(SecretTargetAttachmentCfnProvisioner.class); + + private static final String SECRET_TARGET_MANAGED_KEYS_ATTR = "__FlociSecretTargetManagedKeys"; + private static final String SECRET_TARGET_OWNER_ATTR = "__FlociSecretTargetOwner"; + private static final List SECRET_TARGET_CONNECTION_KEYS = List.of( + "engine", "host", "port", "dbname", "dbInstanceIdentifier", "dbClusterIdentifier"); + + private final SecretsManagerService secretsManagerService; + private final RdsService rdsService; + private final DocDbService docDbService; + private final ObjectMapper objectMapper; + + @Inject + public SecretTargetAttachmentCfnProvisioner(SecretsManagerService secretsManagerService, + RdsService rdsService, + DocDbService docDbService, + ObjectMapper objectMapper) { + this.secretsManagerService = secretsManagerService; + this.rdsService = rdsService; + this.docDbService = docDbService; + this.objectMapper = objectMapper; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + requireSupported(r.getResourceType()); + provisionSecretTargetAttachment(r, props, ctx); + } + + @Override + public void delete(StackResource resource, String region) { + requireSupported(resource.getResourceType()); + deleteSecretTargetAttachment(resource, region); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + requireSupported(resourceType); + throw new AwsException("ValidationError", + "SecretTargetAttachment deletion requires the StackResource metadata that records " + + "its managed fields.", 400); + } + + private static void requireSupported(String resourceType) { + if (!TYPE.equals(resourceType)) { + throw new IllegalStateException( + "SecretTargetAttachmentCfnProvisioner received an unsupported type: " + resourceType); + } + } + + /** Provisions an AWS-compatible Secrets Manager database target attachment. */ + private void provisionSecretTargetAttachment(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); + String stackName = ctx.stackName(); + String secretId = requireSecretTargetProperty(props, "SecretId", ctx); + String targetId = requireSecretTargetProperty(props, "TargetId", ctx); + String targetType = requireSecretTargetProperty(props, "TargetType", ctx); + validateSecretTargetType(targetType); + SecretTargetConnection connection = resolveSecretTargetConnection(targetType, targetId); + + String previousSecretId = r.getPhysicalId(); + String previousManagedKeys = r.getAttributes().get(SECRET_TARGET_MANAGED_KEYS_ATTR); + String attachmentOwner = r.getAttributes().getOrDefault( + SECRET_TARGET_OWNER_ATTR, stackName + "/" + r.getLogicalId()); + String secretArn = secretsManagerService.describeSecret(secretId, region).getArn(); + String previousSecretArn = canonicalExistingSecretArn(previousSecretId, secretArn, region); + boolean replacingSecret = previousSecretArn != null && !previousSecretArn.equals(secretArn); + boolean claimCreated = false; + boolean wroteNewSecret = false; + boolean detachedPreviousSecret = false; + ObjectNode currentSecretJson = null; + SecretTargetMutation previousDetach = null; + + try { + claimCreated = secretsManagerService.claimTargetAttachment( + secretArn, attachmentOwner, region); + + currentSecretJson = readSecretJsonObject(secretArn, region); + ObjectNode desiredSecretJson = currentSecretJson.deepCopy(); + SECRET_TARGET_CONNECTION_KEYS.forEach(desiredSecretJson::remove); + + List managedKeys = new ArrayList<>(); + addSecretTargetConnection(desiredSecretJson, managedKeys, connection); + + if (replacingSecret) { + previousDetach = prepareSecretTargetDetach(previousSecretArn, previousManagedKeys, region); + } + if (!desiredSecretJson.equals(currentSecretJson)) { + secretsManagerService.putSecretValue( + secretArn, desiredSecretJson.toString(), null, null, region, null); + wroteNewSecret = true; + } + if (previousDetach != null) { + putSecretTargetMutation(previousDetach, region); + detachedPreviousSecret = true; + } + if (replacingSecret) { + secretsManagerService.releaseTargetAttachment( + previousSecretArn, attachmentOwner, region); + } + + r.setPhysicalId(secretArn); + r.getAttributes().remove("Arn"); + r.getAttributes().put("Id", secretArn); + r.getAttributes().put(SECRET_TARGET_OWNER_ATTR, attachmentOwner); + r.getAttributes().put(SECRET_TARGET_MANAGED_KEYS_ATTR, String.join(",", managedKeys)); + } catch (RuntimeException failure) { + if (detachedPreviousSecret && previousDetach != null) { + ObjectNode previousValue = previousDetach.originalValue(); + attemptSecretTargetCleanup(failure, "restore previous secret " + previousSecretArn, + () -> secretsManagerService.putSecretValue( + previousSecretArn, previousValue.toString(), + null, null, region, null)); + } + if (wroteNewSecret && currentSecretJson != null) { + ObjectNode originalValue = currentSecretJson; + attemptSecretTargetCleanup(failure, "restore new secret " + secretArn, + () -> secretsManagerService.putSecretValue( + secretArn, originalValue.toString(), + null, null, region, null)); + } + if (claimCreated) { + attemptSecretTargetCleanup(failure, "release target attachment claim for " + secretArn, + () -> secretsManagerService.releaseTargetAttachment( + secretArn, attachmentOwner, region)); + } + throw failure; + } + } + + private static void validateSecretTargetType(String targetType) { + if (!Set.of( + "AWS::RDS::DBInstance", + "AWS::RDS::DBCluster", + "AWS::DocDB::DBInstance", + "AWS::DocDB::DBCluster").contains(targetType)) { + throw new AwsException("ValidationError", + "SecretTargetAttachment TargetType " + targetType + + " is not supported by Floci; supported values are AWS::RDS::DBInstance," + + " AWS::RDS::DBCluster, AWS::DocDB::DBInstance," + + " and AWS::DocDB::DBCluster.", 400); + } + } + + private String canonicalExistingSecretArn(String secretId, String newSecretArn, String region) { + if (secretId == null || secretId.isBlank() || secretId.equals(newSecretArn)) { + return secretId; + } + try { + return secretsManagerService.describeSecret(secretId, region).getArn(); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + return null; + } + throw e; + } + } + + private String requireSecretTargetProperty(JsonNode props, String name, ProvisionContext ctx) { + String value = ctx.resolveOptional(props, name); + if (value == null || value.isBlank()) { + throw new AwsException("ValidationError", + "AWS::SecretsManager::SecretTargetAttachment requires " + name + ".", 400); + } + return value; + } + + private ObjectNode readSecretJsonObject(String secretId, String region) { + return tryReadSecretJsonObject(secretId, region) + .orElseThrow(SecretTargetAttachmentCfnProvisioner::invalidSecretTargetValue); + } + + private Optional tryReadSecretJsonObject(String secretId, String region) { + String secretString = secretsManagerService + .getSecretValue(secretId, null, null, region) + .getSecretString(); + if (secretString == null) { + return Optional.empty(); + } + try { + JsonNode parsed = objectMapper.readTree(secretString); + if (parsed == null || !parsed.isObject()) { + return Optional.empty(); + } + return Optional.of(((ObjectNode) parsed).deepCopy()); + } catch (JsonProcessingException e) { + return Optional.empty(); + } + } + + private static AwsException invalidSecretTargetValue() { + return new AwsException("ValidationError", + "SecretString for AWS::SecretsManager::SecretTargetAttachment must be a JSON object.", 400); + } + + private SecretTargetConnection resolveSecretTargetConnection(String targetType, String targetId) { + return switch (targetType) { + case "AWS::RDS::DBInstance" -> dbInstanceConnection(targetId); + case "AWS::RDS::DBCluster" -> dbClusterConnection(targetId); + case "AWS::DocDB::DBInstance" -> docDbInstanceConnection(targetId); + case "AWS::DocDB::DBCluster" -> docDbClusterConnection(targetId); + default -> throw new IllegalStateException("Validated target type was not handled: " + targetType); + }; + } + + private SecretTargetConnection dbInstanceConnection(String targetId) { + DbInstance instance = rdsService.getDbInstance(targetId); + if (instance == null || instance.getEngine() == null || instance.getEndpoint() == null + || instance.getEndpoint().address() == null + || instance.getEndpoint().address().isBlank() + || instance.getEndpoint().port() <= 0 + || instance.getDbInstanceIdentifier() == null + || instance.getDbInstanceIdentifier().isBlank()) { + throw incompleteSecretTarget(targetId); + } + return new SecretTargetConnection( + instance.getEngine().name().toLowerCase(Locale.ROOT), + instance.getEndpoint().address(), + instance.getEndpoint().port(), + instance.getDbName(), + "dbInstanceIdentifier", + instance.getDbInstanceIdentifier()); + } + + private SecretTargetConnection dbClusterConnection(String targetId) { + DbCluster cluster = rdsService.getDbCluster(targetId); + if (cluster == null || cluster.getEngine() == null || cluster.getEndpoint() == null + || cluster.getEndpoint().address() == null + || cluster.getEndpoint().address().isBlank() + || cluster.getEndpoint().port() <= 0 + || cluster.getDbClusterIdentifier() == null + || cluster.getDbClusterIdentifier().isBlank()) { + throw incompleteSecretTarget(targetId); + } + return new SecretTargetConnection( + cluster.getEngine().name().toLowerCase(Locale.ROOT), + cluster.getEndpoint().address(), + cluster.getEndpoint().port(), + cluster.getDatabaseName(), + "dbClusterIdentifier", + cluster.getDbClusterIdentifier()); + } + + private SecretTargetConnection docDbInstanceConnection(String targetId) { + DocDbInstance instance = docDbService.getDbInstance(targetId); + if (instance == null || instance.getEndpoint() == null + || instance.getEndpoint().isBlank() + || instance.getPort() <= 0 + || instance.getDbInstanceIdentifier() == null + || instance.getDbInstanceIdentifier().isBlank()) { + throw incompleteSecretTarget(targetId); + } + return new SecretTargetConnection( + "mongo", + instance.getEndpoint(), + instance.getPort(), + null, + "dbInstanceIdentifier", + instance.getDbInstanceIdentifier()); + } + + private SecretTargetConnection docDbClusterConnection(String targetId) { + DocDbCluster cluster = docDbService.getDbCluster(targetId); + if (cluster == null || cluster.getEndpoint() == null + || cluster.getEndpoint().isBlank() + || cluster.getPort() <= 0 + || cluster.getDbClusterIdentifier() == null + || cluster.getDbClusterIdentifier().isBlank()) { + throw incompleteSecretTarget(targetId); + } + return new SecretTargetConnection( + "mongo", + cluster.getEndpoint(), + cluster.getPort(), + null, + "dbClusterIdentifier", + cluster.getDbClusterIdentifier()); + } + + private static void addSecretTargetConnection(ObjectNode secretJson, List managedKeys, + SecretTargetConnection connection) { + putSecretTargetField(secretJson, managedKeys, "engine", connection.engine()); + putSecretTargetField(secretJson, managedKeys, "host", connection.host()); + putSecretTargetField(secretJson, managedKeys, "port", connection.port()); + putOptionalSecretTargetField(secretJson, managedKeys, "dbname", connection.dbname()); + putSecretTargetField(secretJson, managedKeys, + connection.identifierKey(), connection.identifier()); + } + + private static AwsException incompleteSecretTarget(String targetId) { + return new AwsException("ValidationError", + "SecretTargetAttachment target " + targetId + " has incomplete connection information.", 400); + } + + private record SecretTargetConnection(String engine, String host, int port, String dbname, + String identifierKey, String identifier) { + } + + private record SecretTargetMutation(String secretId, ObjectNode originalValue, ObjectNode value) { + } + + private static void putSecretTargetField(ObjectNode secretJson, List managedKeys, + String name, String value) { + secretJson.put(name, value); + managedKeys.add(name); + } + + private static void putSecretTargetField(ObjectNode secretJson, List managedKeys, + String name, int value) { + secretJson.put(name, value); + managedKeys.add(name); + } + + private static void putOptionalSecretTargetField(ObjectNode secretJson, List managedKeys, + String name, String value) { + if (value != null && !value.isBlank()) { + putSecretTargetField(secretJson, managedKeys, name, value); + } + } + + private void deleteSecretTargetAttachment(StackResource resource, String region) { + String attachmentOwner = resource.getAttributes().get(SECRET_TARGET_OWNER_ATTR); + if (!secretsManagerService.canManageTargetAttachment( + resource.getPhysicalId(), attachmentOwner, region)) { + LOG.warnv("Skipping SecretTargetAttachment detach because secret {0}" + + " is owned by a different attachment", + resource.getPhysicalId()); + return; + } + detachSecretTarget(resource.getPhysicalId(), + resource.getAttributes().get(SECRET_TARGET_MANAGED_KEYS_ATTR), region); + secretsManagerService.releaseTargetAttachment( + resource.getPhysicalId(), attachmentOwner, region); + } + + private void detachSecretTarget(String secretId, String managedKeysAttribute, String region) { + SecretTargetMutation mutation = prepareSecretTargetDetach(secretId, managedKeysAttribute, region); + if (mutation != null) { + putSecretTargetMutation(mutation, region); + } + } + + private SecretTargetMutation prepareSecretTargetDetach(String secretId, + String managedKeysAttribute, + String region) { + try { + Optional parsedSecret = tryReadSecretJsonObject(secretId, region); + if (parsedSecret.isEmpty()) { + LOG.debugv("SecretTargetAttachment current secret value is no longer a JSON object;" + + " treating as already detached: {0}", secretId); + return null; + } + ObjectNode currentSecretJson = parsedSecret.get(); + ObjectNode detachedSecretJson = currentSecretJson.deepCopy(); + List managedKeys = managedSecretTargetKeys(managedKeysAttribute); + managedKeys.forEach(detachedSecretJson::remove); + return detachedSecretJson.equals(currentSecretJson) + ? null + : new SecretTargetMutation(secretId, currentSecretJson, detachedSecretJson); + } catch (AwsException e) { + if (!"ResourceNotFoundException".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("SecretTargetAttachment secret already gone, treating as detached: {0}", secretId); + return null; + } + } + + private void putSecretTargetMutation(SecretTargetMutation mutation, String region) { + secretsManagerService.putSecretValue( + mutation.secretId(), mutation.value().toString(), null, null, region, null); + } + + private void attemptSecretTargetCleanup(RuntimeException primaryFailure, + String description, + Runnable cleanup) { + try { + cleanup.run(); + } catch (RuntimeException cleanupFailure) { + primaryFailure.addSuppressed(cleanupFailure); + LOG.warnv("SecretTargetAttachment rollback cleanup failed while attempting to {0}: {1}", + description, cleanupFailure.getMessage()); + } + } + + private static List managedSecretTargetKeys(String attribute) { + if (attribute == null || attribute.isBlank()) { + return SECRET_TARGET_CONNECTION_KEYS; + } + List keys = Arrays.stream(attribute.split(",")) + .filter(SECRET_TARGET_CONNECTION_KEYS::contains) + .toList(); + return keys.isEmpty() ? SECRET_TARGET_CONNECTION_KEYS : keys; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java new file mode 100644 index 0000000000..05966efb18 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SecretsManagerCfnProvisioner.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.secretsmanager.RandomPasswordGenerator; +import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService; +import io.github.hectorvent.floci.services.secretsmanager.model.Secret; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.List; +import java.util.Set; + +/** + * Provisions {@code AWS::SecretsManager::Secret}. + * + *

Extracted from {@code CloudFormationResourceProvisioner}. The sibling type + * {@code AWS::SecretsManager::SecretTargetAttachment} lives in + * {@link SecretTargetAttachmentCfnProvisioner} instead of here, because it has to read an RDS or + * DocumentDB endpoint to build the connection detail it writes into the secret, so it needs three + * services where this one needs only its own. + * + *

The secret deletes by physical id alone, so the id-only delete override serves it and it is + * not in the engine's {@code DELETE_NEEDS_STACK_RESOURCE} set. + */ +@ApplicationScoped +public class SecretsManagerCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::SecretsManager::Secret"; + + private static final Logger LOG = Logger.getLogger(SecretsManagerCfnProvisioner.class); + + private final SecretsManagerService secretsManagerService; + + @Inject + public SecretsManagerCfnProvisioner(SecretsManagerService secretsManagerService) { + this.secretsManagerService = secretsManagerService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + if (!TYPE.equals(r.getResourceType())) { + throw new IllegalStateException( + "SecretsManagerCfnProvisioner received an unsupported type: " + r.getResourceType()); + } + provisionSecret(r, props, ctx); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (!TYPE.equals(resourceType)) { + throw new IllegalStateException( + "SecretsManagerCfnProvisioner received an unsupported type: " + resourceType); + } + deleteSecretSafe(physicalId, region); + } + + private void provisionSecret(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); + String name = ctx.resolveOptional(props, "Name"); + if (name == null || name.isBlank()) { + name = ctx.generatePhysicalName(r.getLogicalId(), 512, false); + } + String description = ctx.resolveOptional(props, "Description"); + String value = resolveSecretValue(props, ctx); + Secret secret = secretsManagerService.createSecret(name, value, null, description, null, + List.of(), region); + r.setPhysicalId(secret.getArn()); + r.getAttributes().put("Arn", secret.getArn()); + r.getAttributes().put("Name", name); + } + + private void deleteSecretSafe(String secretId, String region) { + try { + secretsManagerService.deleteSecret(secretId, null, true, region); + } catch (AwsException e) { + if (!"ResourceNotFoundException".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("Secret already gone, treating as deleted: {0}", secretId); + } + } + + /** + * Resolves the secret value from CloudFormation properties. + * SecretString and GenerateSecretString are mutually exclusive per AWS spec. + * If GenerateSecretString is present, a random password is generated. + * If SecretStringTemplate and GenerateStringKey are specified inside + * GenerateSecretString, the generated password is embedded in the template JSON. + */ + private String resolveSecretValue(JsonNode props, ProvisionContext ctx) { + if (props == null) { + return "{}"; + } + + // SecretString takes precedence when explicitly set + String secretString = ctx.resolveOptional(props, "SecretString"); + JsonNode genNode = props.get("GenerateSecretString"); + + if (secretString != null && genNode != null && !genNode.isNull()) { + throw new AwsException("ValidationError", + "You can't specify both SecretString and GenerateSecretString", 400); + } + + if (secretString != null) { + return secretString; + } + + if (genNode != null && !genNode.isNull()) { + return generateSecretString(genNode); + } + + return "{}"; + } + + private String generateSecretString(JsonNode genNode) { + String password = RandomPasswordGenerator.generate(genNode); + + String template = null; + String key = null; + JsonNode templateNode = genNode.get("SecretStringTemplate"); + JsonNode keyNode = genNode.get("GenerateStringKey"); + + if (templateNode != null && !templateNode.isNull()) { + template = templateNode.asText(); + } + if (keyNode != null && !keyNode.isNull()) { + key = keyNode.asText(); + } + + if (template != null && key != null) { + // Insert the generated password into the template JSON + try { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode tree = (ObjectNode) mapper.readTree(template); + tree.put(key, password); + return mapper.writeValueAsString(tree); + } catch (Exception e) { + // If the template is not valid JSON, fall back to raw password + LOG.warnv("Failed to parse SecretStringTemplate: {0}", e.getMessage()); + return password; + } + } + + return password; + } +} 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 dd0057c384..33c9dee042 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 @@ -66,6 +66,8 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.RdsCfnPro 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; +import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretTargetAttachmentCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretsManagerCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.SnsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.SsmCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner; @@ -321,6 +323,11 @@ final class CfnProvisionerFixture { if (rdsService != null) { discovered.add(new RdsCfnProvisioner(rdsService, dynamicReferences)); } + if (secretsManagerService != null) { + discovered.add(new SecretsManagerCfnProvisioner(secretsManagerService)); + discovered.add(new SecretTargetAttachmentCfnProvisioner( + secretsManagerService, rdsService, docDbService, objectMapper)); + } if (wafV2Service != null) { discovered.add(new WafV2CfnProvisioner(wafV2Service)); } @@ -626,7 +633,6 @@ final class CfnProvisionerFixture { iamService, ssmService, kmsService, - secretsManagerService, apiGatewayService, apiGatewayV2Service, ecrService, @@ -637,14 +643,12 @@ final class CfnProvisionerFixture { reachableEndpoint, stepFunctionsService, ec2Service, - rdsService, eksService, logsService, kinesisService, cloudWatchMetricsService, autoScalingService, firehoseService, - docDbService, cloudFrontService, resourceRegistry, dynamicReferences, diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 9de34c48db..d73b485ed7 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -44,3 +44,4 @@ AWS::RDS::DBInstance ResumeFullAutomationModeTime RDS Custom automation mode is 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 +AWS::SecretsManager::Secret Id Fn::GetAtt Id on a secret is its ARN, which the provisioner already sets as the physical id and as Arn; closable, deferred to a follow-up PR to keep this one a pure move diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 9d43b527bf..c000f283ed 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -127,8 +127,8 @@ AWS::SQS::Queue SqsCfnProvisioner AWS::SQS::QueuePolicy SqsCfnProvisioner AWS::SSM::Parameter SsmCfnProvisioner AWS::Scheduler::ScheduleGroup SchedulerScheduleGroupCfnProvisioner -AWS::SecretsManager::Secret LEGACY_SWITCH -AWS::SecretsManager::SecretTargetAttachment LEGACY_SWITCH +AWS::SecretsManager::Secret SecretsManagerCfnProvisioner +AWS::SecretsManager::SecretTargetAttachment SecretTargetAttachmentCfnProvisioner AWS::StepFunctions::StateMachine LEGACY_SWITCH AWS::WAFv2::WebACL WafV2CfnProvisioner Custom::DynamoDBReplica LEGACY_SWITCH