feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment (#1804)

* feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment

AWS::SecretsManager::SecretTargetAttachment previously fell through the
default branch, so its Ref yielded a generated placeholder rather than the
secret ARN. Per the CloudFormation resource reference, this resource's Ref
returns the ARN of the secret named in SecretId, and consumers such as
Secret.fromSecretCompleteArn(...) require the complete ARN (with the
trailing -6char suffix).

Resolve SecretId (a Ref to the Secret, a friendly name, or a raw ARN) to
the canonical complete ARN via describeSecret and expose it as the
resource's physical id / Arn attribute, falling back to SecretId as-given
if the lookup fails. Deleting the attachment is a detach no-op — it must
not delete the underlying secret.

* fix(cloudformation): require SecretId on SecretTargetAttachment

SecretId is a required property of AWS::SecretsManager::SecretTargetAttachment.
Resolving it as optional let a template omit it and still create (falling back to
the logical id); reject a missing SecretId instead. Adds a regression test.

* fix(cloudformation): complete secret target attachment lifecycle

* fix(cloudformation): require attachment metadata on delete

* fix(cloudformation): tolerate detached secret overwrites

* fix(cloudformation): align secret target attachment behavior

* docs(cloudformation): document secret target attachments

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>
This commit is contained in:
Alex Bannaandabanna authored and GitHub committed 2026-08-05 17:11:25 -05:00
1 parent 42d94c62ee
commit 62a576c8d4
12 files changed
+1637 -2

No files matched your search

@@ -20,6 +20,7 @@ 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;
@@ -82,6 +83,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -119,6 +121,10 @@ public class CloudFormationResourceProvisioner {
private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets";
private static final String LAMBDA_NAME_MODE_EXPLICIT = "explicit";
private static final String LAMBDA_NAME_MODE_GENERATED = "generated";
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 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;
@@ -165,6 +171,7 @@ public class CloudFormationResourceProvisioner {
private final CloudWatchMetricsService cloudWatchMetricsService;
private final AutoScalingService autoScalingService;
private final FirehoseService firehoseService;
private final DocDbService docDbService;
// 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
// now-dead service deps above are cleared in the final cleanup once the switch is empty.
@@ -198,6 +205,7 @@ public class CloudFormationResourceProvisioner {
CloudWatchMetricsService cloudWatchMetricsService,
AutoScalingService autoScalingService,
FirehoseService firehoseService,
DocDbService docDbService,
CloudFormationResourceRegistry resourceRegistry) {
this.s3Service = s3Service;
this.sqsService = sqsService;
@@ -230,6 +238,7 @@ public class CloudFormationResourceProvisioner {
this.cloudWatchMetricsService = cloudWatchMetricsService;
this.autoScalingService = autoScalingService;
this.firehoseService = firehoseService;
this.docDbService = docDbService;
this.resourceRegistry = resourceRegistry;
}
@@ -288,6 +297,8 @@ public class CloudFormationResourceProvisioner {
case "AWS::KMS::Key" -> provisionKmsKey(resource, properties, engine, region, accountId);
case "AWS::KMS::Alias" -> provisionKmsAlias(resource, properties, engine, region);
case "AWS::SecretsManager::Secret" -> provisionSecret(resource, properties, engine, region, accountId, stackName);
case "AWS::SecretsManager::SecretTargetAttachment" ->
provisionSecretTargetAttachment(resource, properties, engine, region, stackName);
case "AWS::CDK::Metadata" -> provisionCdkMetadata(resource);
case "AWS::S3::BucketPolicy" -> provisionS3BucketPolicy(resource, properties, engine);
case "AWS::ECR::Repository" -> provisionEcrRepository(resource, properties, engine, stackName, region);
@@ -400,6 +411,10 @@ 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)) {
@@ -468,6 +483,10 @@ public class CloudFormationResourceProvisioner {
} // KMS keys can't be immediately deleted; skip
case "AWS::KMS::Alias" -> kmsService.deleteAlias(physicalId, region);
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);
case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, null, region);
case "AWS::Events::EventBus" -> deleteEventBusSafe(physicalId, region);
case "AWS::Events::EventBusPolicy" -> removeEventBusPolicySafe(physicalId, region);
@@ -2301,6 +2320,352 @@ public class CloudFormationResourceProvisioner {
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.
@@ -287,6 +287,85 @@ public class SecretsManagerService {
return secret;
}
/**
* Claims the single Secrets Manager target-attachment slot for a CloudFormation resource.
*
* @return {@code true} when this call created the claim, or {@code false} when the same
* resource already owned it.
*/
public boolean claimTargetAttachment(String secretId, String attachmentOwner, String region) {
Secret resolved = resolveSecret(secretId, region);
synchronized (lockFor(resolved.getArn())) {
Secret secret = resolveSecret(resolved.getArn(), region);
if (secret.getDeletedDate() != null) {
throw new AwsException("ResourceNotFoundException",
"Secrets Manager can't find the specified secret.", 400);
}
String existingOwner = secret.getTargetAttachmentOwner();
if (existingOwner != null && !existingOwner.equals(attachmentOwner)) {
throw new AwsException("ResourceExistsException",
"A target is already attached to secret " + secret.getArn() + ".", 400);
}
if (existingOwner != null) {
return false;
}
secret.setTargetAttachmentOwner(attachmentOwner);
store.put(regionKey(region, secret.getName()), secret);
return true;
}
}
/**
* Returns whether an attachment may mutate this secret. Unclaimed secrets remain manageable
* so target attachments persisted before ownership tracking was introduced can still detach.
*/
public boolean canManageTargetAttachment(String secretId, String attachmentOwner, String region) {
Secret resolved;
try {
resolved = resolveSecret(secretId, region);
} catch (AwsException e) {
if ("ResourceNotFoundException".equals(e.getErrorCode())) {
return true;
}
throw e;
}
synchronized (lockFor(resolved.getArn())) {
Secret secret = resolveSecret(resolved.getArn(), region);
String existingOwner = secret.getTargetAttachmentOwner();
return existingOwner == null
|| attachmentOwner != null && attachmentOwner.equals(existingOwner);
}
}
/** Releases a target-attachment claim only when it is still owned by the caller. */
public void releaseTargetAttachment(String secretId, String attachmentOwner, String region) {
if (attachmentOwner == null || attachmentOwner.isBlank()) {
return;
}
Secret resolved;
try {
resolved = resolveSecret(secretId, region);
} catch (AwsException e) {
if ("ResourceNotFoundException".equals(e.getErrorCode())) {
return;
}
throw e;
}
synchronized (lockFor(resolved.getArn())) {
Secret secret = resolveSecret(resolved.getArn(), region);
if (!attachmentOwner.equals(secret.getTargetAttachmentOwner())) {
return;
}
secret.setTargetAttachmentOwner(null);
store.put(regionKey(region, secret.getName()), secret);
}
}
public List<Secret> listSecrets(String region) {
String prefix = region + "::";
return store.scan(key -> key.startsWith(prefix) && store.get(key)
@@ -28,6 +28,7 @@ public class Secret {
private RotationRules rotationRules;
private Instant lastRotatedDate;
private Instant nextRotationDate;
private String targetAttachmentOwner;
@RegisterForReflection
public record RotationRules(
@@ -172,4 +173,12 @@ public class Secret {
public void setNextRotationDate(Instant nextRotationDate) {
this.nextRotationDate = nextRotationDate;
}
public String getTargetAttachmentOwner() {
return targetAttachmentOwner;
}
public void setTargetAttachmentOwner(String targetAttachmentOwner) {
this.targetAttachmentOwner = targetAttachmentOwner;
}
}