mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
refactor(cloudformation): move the SecretsManager types into per-service provisioners (#3530)
Moves AWS::SecretsManager::Secret and AWS::SecretsManager::SecretTargetAttachment out of the monolith switch. The logic is carried over intact. What differs is the plumbing, plus the style the new files have to meet as new files: locals that were var now name their types, which matters most where an RDS and a DocumentDB lookup sit side by side returning different shapes, the inline fully-qualified ObjectMapper, ObjectNode and RandomPasswordGenerator are imported, and neither file keeps a private copy of resolveOptional now that ProvisionContext already offers the identical method the other 46 migrated provisioners call. Monolith 5,461 to 4,987 lines, legacy types 33 to 31. Two classes rather than one, because the two types do not want the same dependencies. The secret needs only SecretsManagerService. The attachment reads an RDS or DocumentDB endpoint to build the connection detail it writes into the target secret, so it needs three services and an ObjectMapper. Splitting keeps AGENTS.md's "inject only the service it wraps" true for the common case and confines the wide dependency to the type that genuinely has it. The repo already anticipated the split: SecretTargetAttachmentCfnProvisionerTest has existed for some time, named for a class that did not. This is the batch that finally takes RdsService out of the monolith. Batch 7 could not: dbInstanceConnection and dbClusterConnection were the last two rdsService call sites and both belong to the attachment. Three service fields leave with this change, SecretsManagerService, RdsService and DocDbService, along with their constructor parameters and imports, plus six RDS model imports that batch 7 left behind unused. SecretTargetAttachment is the first extracted type to leave DELETE_NEEDS_STACK_RESOURCE, which drops from 7 entries to 6. Its delete needs two create-time attributes no physical id carries: which secret fields the attachment managed, so only those are stripped, and which attachment owns the secret, so a second attachment's fields survive. That logic moves into the provisioner's delete(StackResource, String) override, and the set entry goes in the same commit because the registry is consulted first and leaving both claiming the type is exactly what CfnDeletePrecedenceTest exists to catch. The id-only delete keeps refusing the attachment with the same message, which a test asserts. The 34 SecretTargetAttachmentCfnProvisionerTest tests and the 5 attachment integration tests pass unchanged, which is the guard that the move preserved behaviour: both build through CfnProvisionerFixture, so they exercise the new provisioners without knowing they exist. Making the types provisioner-owned rather than LEGACY_SWITCH puts them under CfnSchemaCoverageTest for the first time, since it skips switch-owned types. One attribute surfaces: Fn::GetAtt Id on a secret is its ARN, which the provisioner already sets as the physical id and as Arn. It is recorded as a gap rather than set, to keep this commit a pure move.
This commit is contained in:
1 parent
7d96799c5a
commit
d90cb23c23
6 files changed
+614
-479
No files matched your search
-474
@@ -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<String> 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<String> 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<String> 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<ObjectNode> 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<String> 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<String> managedKeys,
|
||||
String name, String value) {
|
||||
secretJson.put(name, value);
|
||||
managedKeys.add(name);
|
||||
}
|
||||
|
||||
private static void putSecretTargetField(ObjectNode secretJson, List<String> managedKeys,
|
||||
String name, int value) {
|
||||
secretJson.put(name, value);
|
||||
managedKeys.add(name);
|
||||
}
|
||||
|
||||
private static void putOptionalSecretTargetField(ObjectNode secretJson, List<String> 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<ObjectNode> 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<String> 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<String> managedSecretTargetKeys(String attribute) {
|
||||
if (attribute == null || attribute.isBlank()) {
|
||||
return SECRET_TARGET_CONNECTION_KEYS;
|
||||
}
|
||||
List<String> 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}.
|
||||
|
||||
+448
@@ -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}.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String> 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<String> 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<String> 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<ObjectNode> 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<String> 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<String> managedKeys,
|
||||
String name, String value) {
|
||||
secretJson.put(name, value);
|
||||
managedKeys.add(name);
|
||||
}
|
||||
|
||||
private static void putSecretTargetField(ObjectNode secretJson, List<String> managedKeys,
|
||||
String name, int value) {
|
||||
secretJson.put(name, value);
|
||||
managedKeys.add(name);
|
||||
}
|
||||
|
||||
private static void putOptionalSecretTargetField(ObjectNode secretJson, List<String> 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<ObjectNode> 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<String> 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<String> managedSecretTargetKeys(String attribute) {
|
||||
if (attribute == null || attribute.isBlank()) {
|
||||
return SECRET_TARGET_CONNECTION_KEYS;
|
||||
}
|
||||
List<String> keys = Arrays.stream(attribute.split(","))
|
||||
.filter(SECRET_TARGET_CONNECTION_KEYS::contains)
|
||||
.toList();
|
||||
return keys.isEmpty() ? SECRET_TARGET_CONNECTION_KEYS : keys;
|
||||
}
|
||||
}
|
||||
+156
@@ -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}.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String> 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user