Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment (#1804)
Alex Banna62a576c8d482
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex e6767b3d26..6d9180e035 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -57,7 +57,7 @@ cross-resource references.| IAM | `Role`, `User`, `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` || SSM | `Parameter` || KMS | `Key`, `Alias` |-| Secrets Manager | `Secret` |+| Secrets Manager | `Secret`, `SecretTargetAttachment` || ECR | `Repository` || ECS | `Cluster`, `TaskDefinition`, `Service` || EKS | `Cluster`, `Nodegroup` |@@ -84,6 +84,25 @@ All other resource types are accepted without error and assigned a synthetic phy`arn:aws:stub:::<logicalId>` ARN attribute), so templates with unsupported types still reach`CREATE_COMPLETE` rather than failing.+## Secrets Manager Target Attachments++`AWS::SecretsManager::SecretTargetAttachment` adds the target's database connection fields to the+referenced secret while preserving credentials and custom fields. `Ref` and `Fn::GetAtt Id` return+the complete secret ARN, only one attachment can own a secret, and deleting the attachment removes+only its managed connection fields.++Supported target types are:++- `AWS::RDS::DBInstance`+- `AWS::RDS::DBCluster`+- `AWS::DocDB::DBInstance`+- `AWS::DocDB::DBCluster`++Redshift clusters, Redshift Serverless namespaces, and DocumentDB Elastic clusters are not supported+because their backing services are not implemented. A `SecretId` change is applied in place rather+than reproducing CloudFormation's replacement event sequence; failed changes restore affected secret+data and attachment ownership.+## Lambda Stack Updates`AWS::Lambda::Function` resources are reconciled during `UpdateStack` in the same shape as CloudFormation/CDK deployments: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.javaindex 23b62ba4cb..5555e2f2ef 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@@ -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; skipcase "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.diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.javaindex c2e764d7e6..39a023eff7 100644--- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java@@ -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)diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/model/Secret.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/model/Secret.javaindex 3ca1878ba0..a49f9ac9b1 100644--- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/model/Secret.java+++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/model/Secret.java@@ -28,6 +28,7 @@ public class Secret {private RotationRules rotationRules;private Instant lastRotatedDate;private Instant nextRotationDate;+ private String targetAttachmentOwner;@RegisterForReflectionpublic 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;+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.javaindex 02e71fef3c..7b7cb7303f 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeleteIdempotencyTest.java@@ -36,6 +36,7 @@ class CloudFormationDeleteIdempotencyTest {new ObjectMapper(),null, null, null, null, null, null, null,null, null, null, null, null, null, null,+ null,new CloudFormationResourceRegistry(List.of()));}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.javaindex a7ab054b94..22051fa071 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java@@ -50,6 +50,7 @@ class CloudFormationIamAttachmentProvisionerTest {mapper,null, null, null, null, null, null, null,null, null, null, null, null, null, null,+ null,new CloudFormationResourceRegistry(List.of()));}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecretTargetAttachmentIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecretTargetAttachmentIntegrationTest.javanew file mode 100644index 0000000000..8d233a28a3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecretTargetAttachmentIntegrationTest.java@@ -0,0 +1,425 @@+package io.github.hectorvent.floci.services.cloudformation;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.XmlParser;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assertions.fail;++/** End-to-end coverage for attaching and detaching an external secret from an RDS target. */+@QuarkusTest+@TestProfile(CloudFormationSecretTargetAttachmentIntegrationTest.RdsMockProfile.class)+class CloudFormationSecretTargetAttachmentIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";+ private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final ObjectMapper MAPPER = new ObjectMapper();++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void attachmentAddsConnectionDataAndDetachPreservesTheSecret() throws Exception {+ String suffix = Long.toString(System.nanoTime(), 36);+ String secretName = "sta-secret-" + suffix;+ String databaseId = "sta-database-" + suffix;+ String stackName = "sta-stack-" + suffix;+ String secretArn = createSecret(secretName);+ boolean stackCreated = false;++ try {+ String template = """+ {+ "Resources": {+ "Database": {+ "Type": "AWS::RDS::DBInstance",+ "Properties": {+ "DBInstanceIdentifier": "%s",+ "Engine": "postgres",+ "MasterUsername": "dbadmin",+ "MasterUserPassword": "database-password",+ "DBName": "appdb",+ "DBInstanceClass": "db.t3.micro",+ "AllocatedStorage": 20+ }+ },+ "Attachment": {+ "Type": "AWS::SecretsManager::SecretTargetAttachment",+ "Properties": {+ "SecretId": "%s",+ "TargetType": "AWS::RDS::DBInstance",+ "TargetId": {"Ref": "Database"}+ }+ }+ },+ "Outputs": {+ "AttachmentRef": {"Value": {"Ref": "Attachment"}},+ "AttachmentId": {+ "Value": {"Fn::GetAtt": ["Attachment", "Id"]}+ }+ }+ }+ """.formatted(databaseId, secretName);++ createStack(stackName, template);+ stackCreated = true;+ String describeXml = describeStack(stackName);+ assertTrue(describeXml.contains("<StackStatus>CREATE_COMPLETE</StackStatus>"),+ "stack should be CREATE_COMPLETE: " + describeXml);+ assertEquals(secretArn, outputValue(describeXml, "AttachmentRef"));+ assertEquals(secretArn, outputValue(describeXml, "AttachmentId"));++ JsonNode attached = getSecretJson(secretName);+ assertEquals("admin", attached.path("username").asText());+ assertEquals("initial-password", attached.path("password").asText());+ assertEquals("keep", attached.path("custom").asText());+ assertEquals("postgres", attached.path("engine").asText());+ assertEquals("localhost", attached.path("host").asText());+ assertTrue(attached.path("port").asInt() > 0);+ assertEquals("appdb", attached.path("dbname").asText());+ assertEquals(databaseId, attached.path("dbInstanceIdentifier").asText());++ deleteStack(stackName);+ awaitStackDeleted(stackName);+ stackCreated = false;++ given()+ .header("X-Amz-Target", "secretsmanager.DescribeSecret")+ .contentType(SM_CONTENT_TYPE)+ .body("{\"SecretId\":\"" + secretName + "\"}")+ .when().post("/").then().statusCode(200);++ JsonNode detached = getSecretJson(secretName);+ assertEquals("admin", detached.path("username").asText());+ assertEquals("initial-password", detached.path("password").asText());+ assertEquals("keep", detached.path("custom").asText());+ assertFalse(detached.has("engine"));+ assertFalse(detached.has("host"));+ assertFalse(detached.has("port"));+ assertFalse(detached.has("dbname"));+ assertFalse(detached.has("dbInstanceIdentifier"));+ } finally {+ if (stackCreated) {+ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }+ forceDeleteSecret(secretName);+ }+ }++ @Test+ void deletionTreatsBinaryOverwriteAsAlreadyDetached() throws Exception {+ String suffix = Long.toString(System.nanoTime(), 36);+ String secretName = "sta-binary-secret-" + suffix;+ String databaseId = "sta-binary-database-" + suffix;+ String stackName = "sta-binary-stack-" + suffix;+ createSecret(secretName);+ boolean stackCreated = false;++ try {+ String template = """+ {+ "Resources": {+ "Database": {+ "Type": "AWS::RDS::DBInstance",+ "Properties": {+ "DBInstanceIdentifier": "%s",+ "Engine": "postgres",+ "MasterUsername": "dbadmin",+ "MasterUserPassword": "database-password"+ }+ },+ "Attachment": {+ "Type": "AWS::SecretsManager::SecretTargetAttachment",+ "Properties": {+ "SecretId": "%s",+ "TargetType": "AWS::RDS::DBInstance",+ "TargetId": {"Ref": "Database"}+ }+ }+ }+ }+ """.formatted(databaseId, secretName);++ createStack(stackName, template);+ stackCreated = true;+ String describeXml = describeStack(stackName);+ assertTrue(describeXml.contains("<StackStatus>CREATE_COMPLETE</StackStatus>"),+ "stack should be CREATE_COMPLETE: " + describeXml);++ putBinarySecret(secretName, "AQID");++ deleteStack(stackName);+ awaitStackDeleted(stackName);+ stackCreated = false;++ JsonNode value = getSecretValue(secretName);+ assertEquals("AQID", value.path("SecretBinary").asText());+ assertFalse(value.has("SecretString"));+ } finally {+ if (stackCreated) {+ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }+ forceDeleteSecret(secretName);+ }+ }++ @Test+ void createRollbackDetachesConnectionDataFromAnExternalSecret() throws Exception {+ String suffix = Long.toString(System.nanoTime(), 36);+ String secretName = "sta-rollback-secret-" + suffix;+ String databaseId = "sta-rollback-database-" + suffix;+ String stackName = "sta-rollback-stack-" + suffix;+ createSecret(secretName);+ boolean stackCreated = false;++ try {+ String template = """+ {+ "Resources": {+ "Database": {+ "Type": "AWS::RDS::DBInstance",+ "Properties": {+ "DBInstanceIdentifier": "%s",+ "Engine": "postgres",+ "MasterUsername": "dbadmin",+ "MasterUserPassword": "database-password",+ "DBName": "appdb",+ "DBInstanceClass": "db.t3.micro",+ "AllocatedStorage": 20+ }+ },+ "Attachment": {+ "Type": "AWS::SecretsManager::SecretTargetAttachment",+ "Properties": {+ "SecretId": "%s",+ "TargetType": "AWS::RDS::DBInstance",+ "TargetId": {"Ref": "Database"}+ }+ },+ "BrokenAttachment": {+ "Type": "AWS::SecretsManager::SecretTargetAttachment",+ "DependsOn": "Attachment",+ "Properties": {+ "SecretId": "missing-secret-%s",+ "TargetType": "AWS::RDS::DBInstance",+ "TargetId": {"Ref": "Database"}+ }+ }+ }+ }+ """.formatted(databaseId, secretName, suffix);++ createStack(stackName, template);+ stackCreated = true;+ String describeXml = describeStack(stackName);+ assertTrue(describeXml.contains("<StackStatus>ROLLBACK_COMPLETE</StackStatus>"),+ "stack should be ROLLBACK_COMPLETE: " + describeXml);++ JsonNode rolledBack = getSecretJson(secretName);+ assertEquals("admin", rolledBack.path("username").asText());+ assertEquals("initial-password", rolledBack.path("password").asText());+ assertEquals("keep", rolledBack.path("custom").asText());+ assertFalse(rolledBack.has("engine"));+ assertFalse(rolledBack.has("host"));+ assertFalse(rolledBack.has("port"));+ assertFalse(rolledBack.has("dbname"));+ assertFalse(rolledBack.has("dbInstanceIdentifier"));+ } finally {+ if (stackCreated) {+ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }+ forceDeleteSecret(secretName);+ }+ }++ @Test+ void duplicateAttachmentToTheSameSecretFailsAndRollsBackTheFirstAttachment() throws Exception {+ String suffix = Long.toString(System.nanoTime(), 36);+ String secretName = "sta-duplicate-secret-" + suffix;+ String databaseId = "sta-duplicate-database-" + suffix;+ String stackName = "sta-duplicate-stack-" + suffix;+ createSecret(secretName);+ boolean stackCreated = false;++ try {+ String template = """+ {+ "Resources": {+ "Database": {+ "Type": "AWS::RDS::DBInstance",+ "Properties": {+ "DBInstanceIdentifier": "%s",+ "Engine": "postgres",+ "MasterUsername": "dbadmin",+ "MasterUserPassword": "database-password"+ }+ },+ "FirstAttachment": {+ "Type": "AWS::SecretsManager::SecretTargetAttachment",+ "Properties": {+ "SecretId": "%s",+ "TargetType": "AWS::RDS::DBInstance",+ "TargetId": {"Ref": "Database"}+ }+ },+ "DuplicateAttachment": {+ "Type": "AWS::SecretsManager::SecretTargetAttachment",+ "DependsOn": "FirstAttachment",+ "Properties": {+ "SecretId": "%s",+ "TargetType": "AWS::RDS::DBInstance",+ "TargetId": {"Ref": "Database"}+ }+ }+ }+ }+ """.formatted(databaseId, secretName, secretName);++ createStack(stackName, template);+ stackCreated = true;+ String describeXml = describeStack(stackName);+ assertTrue(describeXml.contains("<StackStatus>ROLLBACK_COMPLETE</StackStatus>"),+ "stack should be ROLLBACK_COMPLETE: " + describeXml);+ assertTrue(describeXml.contains("already attached"),+ "stack should report the duplicate attachment: " + describeXml);++ JsonNode rolledBack = getSecretJson(secretName);+ assertEquals("admin", rolledBack.path("username").asText());+ assertEquals("initial-password", rolledBack.path("password").asText());+ assertEquals("keep", rolledBack.path("custom").asText());+ assertFalse(rolledBack.has("engine"));+ assertFalse(rolledBack.has("host"));+ assertFalse(rolledBack.has("port"));+ assertFalse(rolledBack.has("dbInstanceIdentifier"));+ } finally {+ if (stackCreated) {+ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }+ forceDeleteSecret(secretName);+ }+ }++ private static String createSecret(String secretName) throws Exception {+ String request = MAPPER.createObjectNode()+ .put("Name", secretName)+ .put("SecretString",+ "{\"username\":\"admin\",\"password\":\"initial-password\",\"custom\":\"keep\"}")+ .toString();+ String response = given()+ .header("X-Amz-Target", "secretsmanager.CreateSecret")+ .contentType(SM_CONTENT_TYPE)+ .body(request)+ .when().post("/").then().statusCode(200).extract().asString();+ return MAPPER.readTree(response).path("ARN").asText();+ }++ private static JsonNode getSecretJson(String secretName) throws Exception {+ return MAPPER.readTree(getSecretValue(secretName).path("SecretString").asText());+ }++ private static JsonNode getSecretValue(String secretName) throws Exception {+ String response = given()+ .header("X-Amz-Target", "secretsmanager.GetSecretValue")+ .contentType(SM_CONTENT_TYPE)+ .body("{\"SecretId\":\"" + secretName + "\"}")+ .when().post("/").then().statusCode(200).extract().asString();+ return MAPPER.readTree(response);+ }++ private static void putBinarySecret(String secretName, String value) {+ String request = MAPPER.createObjectNode()+ .put("SecretId", secretName)+ .put("SecretBinary", value)+ .toString();+ given()+ .header("X-Amz-Target", "secretsmanager.PutSecretValue")+ .contentType(SM_CONTENT_TYPE)+ .body(request)+ .when().post("/").then().statusCode(200);+ }++ private static void forceDeleteSecret(String secretName) {+ given()+ .header("X-Amz-Target", "secretsmanager.DeleteSecret")+ .contentType(SM_CONTENT_TYPE)+ .body("{\"SecretId\":\"" + secretName + "\",\"ForceDeleteWithoutRecovery\":true}")+ .when().post("/").then().statusCode(200);+ }++ private static void createStack(String stackName, String template) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when().post("/").then().statusCode(200);+ }++ private static String describeStack(String stackName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then().statusCode(200).extract().asString();+ }++ private static String outputValue(String xml, String key) {+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);+ }++ private static void deleteStack(String stackName) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when().post("/").then().statusCode(200);+ }++ private static void awaitStackDeleted(String stackName) throws InterruptedException {+ for (int i = 0; i < 100; i++) {+ String body = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then().extract().asString();+ if (body.contains("does not exist")) {+ return;+ }+ if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {+ fail("stack delete failed: " + body);+ }+ Thread.sleep(50);+ }+ fail("stack " + stackName + " was not deleted within the timeout");+ }++ public static final class RdsMockProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.rds.mock", "true");+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.javaindex d1d7944ca3..4423a00ebe 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java@@ -49,6 +49,7 @@ class CustomResourceProvisionerTest {provisioner = new CloudFormationResourceProvisioner(null, null, null, null, lambdaService, null, null, null, null, null,null, null, null, null, null, null, mapper, store, endpoint, null, null, null, null, null, null, null, null, null, null, null, null,+ null,new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()));}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.javaindex be11803e61..45cf8a084c 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java@@ -47,6 +47,7 @@ class RdsCfnProvisionerTest {mapper,null, null, null, null, null, null, null,rdsService, null, null, null, null, null, null,+ null,new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()));}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.javanew file mode 100644index 0000000000..b808b60ea8--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java@@ -0,0 +1,681 @@+package io.github.hectorvent.floci.services.cloudformation;++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.cloudformation.provisioners.CloudFormationResourceRegistry;+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.DatabaseEngine;+import io.github.hectorvent.floci.services.rds.model.DbCluster;+import io.github.hectorvent.floci.services.rds.model.DbEndpoint;+import io.github.hectorvent.floci.services.rds.model.DbInstance;+import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;+import io.github.hectorvent.floci.services.secretsmanager.model.Secret;+import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.ArgumentCaptor;++import java.util.List;+import java.util.Map;+import java.util.function.Function;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.ArgumentMatchers.isNull;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++class SecretTargetAttachmentCfnProvisionerTest {++ private static final String REGION = "us-east-1";+ private static final String SECRET_ID = "database-secret";+ private static final String SECRET_ARN =+ "arn:aws:secretsmanager:us-east-1:000000000000:secret:database-secret-a1b2c3";++ private final ObjectMapper mapper = new ObjectMapper();+ private SecretsManagerService secretsManagerService;+ private RdsService rdsService;+ private DocDbService docDbService;+ private CloudFormationResourceProvisioner provisioner;++ @BeforeEach+ void setUp() {+ secretsManagerService = mock(SecretsManagerService.class);+ rdsService = mock(RdsService.class);+ docDbService = mock(DocDbService.class);+ when(secretsManagerService.claimTargetAttachment(any(), any(), any())).thenReturn(true);+ when(secretsManagerService.canManageTargetAttachment(any(), any(), any())).thenReturn(true);+ provisioner = new CloudFormationResourceProvisioner(+ null, null, null, null, null, null, null, null, secretsManagerService, null,+ null, null, null, null, null, null,+ mapper,+ null, null, null, null, null, null, null,+ rdsService, null, null, null, null, null, null,+ docDbService,+ new CloudFormationResourceRegistry(List.of()));+ }++ @Test+ void dbInstanceAttachmentAddsAndThenRemovesOnlyConnectionFields() throws Exception {+ stubSecretValues(+ "{\"username\":\"admin\",\"password\":\"secret\",\"custom\":\"keep\","+ + "\"dbClusterIdentifier\":\"old-cluster\"}",+ "{\"username\":\"admin\",\"password\":\"secret\",\"custom\":\"keep\","+ + "\"engine\":\"postgres\",\"host\":\"db.local\",\"port\":5432,"+ + "\"dbname\":\"app\",\"dbInstanceIdentifier\":\"database\"}");+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());++ StackResource resource = provision(instanceProperties());+ assertEquals("CREATE_COMPLETE", resource.getStatus());+ assertEquals(SECRET_ARN, resource.getPhysicalId());+ assertFalse(resource.getAttributes().containsKey("Arn"));+ assertEquals(SECRET_ARN, resource.getAttributes().get("Id"));+ assertEquals("stack/Attachment",+ resource.getAttributes().get("__FlociSecretTargetOwner"));++ provisioner.delete(resource, REGION);++ ArgumentCaptor<String> values = ArgumentCaptor.forClass(String.class);+ verify(secretsManagerService, org.mockito.Mockito.times(2)).putSecretValue(+ eq(SECRET_ARN), values.capture(), isNull(), isNull(), eq(REGION), isNull());++ JsonNode attached = mapper.readTree(values.getAllValues().get(0));+ assertEquals("admin", attached.path("username").asText());+ assertEquals("secret", attached.path("password").asText());+ assertEquals("keep", attached.path("custom").asText());+ assertEquals("postgres", attached.path("engine").asText());+ assertEquals("db.local", attached.path("host").asText());+ assertEquals(5432, attached.path("port").asInt());+ assertEquals("app", attached.path("dbname").asText());+ assertEquals("database", attached.path("dbInstanceIdentifier").asText());+ assertFalse(attached.has("dbClusterIdentifier"));++ JsonNode detached = mapper.readTree(values.getAllValues().get(1));+ assertEquals("admin", detached.path("username").asText());+ assertEquals("secret", detached.path("password").asText());+ assertEquals("keep", detached.path("custom").asText());+ assertFalse(detached.has("engine"));+ assertFalse(detached.has("host"));+ assertFalse(detached.has("port"));+ assertFalse(detached.has("dbname"));+ assertFalse(detached.has("dbInstanceIdentifier"));+ verify(secretsManagerService).releaseTargetAttachment(+ SECRET_ARN, "stack/Attachment", REGION);+ }++ @Test+ void dbClusterAttachmentUsesClusterConnectionFields() throws Exception {+ stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\"}");+ DbCluster cluster = new DbCluster();+ cluster.setDbClusterIdentifier("cluster");+ cluster.setEngine(DatabaseEngine.MYSQL);+ cluster.setEndpoint(new DbEndpoint("cluster.local", 3306));+ cluster.setDatabaseName("orders");+ when(rdsService.getDbCluster("cluster")).thenReturn(cluster);++ StackResource resource = provision(properties("AWS::RDS::DBCluster", "cluster"));++ assertEquals("CREATE_COMPLETE", resource.getStatus());+ ArgumentCaptor<String> value = ArgumentCaptor.forClass(String.class);+ verify(secretsManagerService).putSecretValue(+ eq(SECRET_ARN), value.capture(), isNull(), isNull(), eq(REGION), isNull());+ JsonNode attached = mapper.readTree(value.getValue());+ assertEquals("mysql", attached.path("engine").asText());+ assertEquals("cluster.local", attached.path("host").asText());+ assertEquals(3306, attached.path("port").asInt());+ assertEquals("orders", attached.path("dbname").asText());+ assertEquals("cluster", attached.path("dbClusterIdentifier").asText());+ assertFalse(attached.has("dbInstanceIdentifier"));+ }++ @Test+ void docDbInstanceAttachmentUsesMongoConnectionFields() throws Exception {+ stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\",\"ssl\":true}");+ DocDbInstance instance = new DocDbInstance();+ instance.setDbInstanceIdentifier("document-instance");+ instance.setEndpoint("document.local");+ instance.setPort(27017);+ when(docDbService.getDbInstance("document-instance")).thenReturn(instance);++ StackResource resource = provision(+ properties("AWS::DocDB::DBInstance", "document-instance"));++ assertEquals("CREATE_COMPLETE", resource.getStatus());+ ArgumentCaptor<String> value = ArgumentCaptor.forClass(String.class);+ verify(secretsManagerService).putSecretValue(+ eq(SECRET_ARN), value.capture(), isNull(), isNull(), eq(REGION), isNull());+ JsonNode attached = mapper.readTree(value.getValue());+ assertEquals("mongo", attached.path("engine").asText());+ assertEquals("document.local", attached.path("host").asText());+ assertEquals(27017, attached.path("port").asInt());+ assertEquals("document-instance", attached.path("dbInstanceIdentifier").asText());+ assertTrue(attached.path("ssl").asBoolean());+ assertFalse(attached.has("dbClusterIdentifier"));+ }++ @Test+ void docDbClusterAttachmentUsesMongoConnectionFields() throws Exception {+ stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\",\"ssl\":true}");+ DocDbCluster cluster = new DocDbCluster();+ cluster.setDbClusterIdentifier("document-cluster");+ cluster.setEndpoint("document-cluster.local");+ cluster.setPort(27017);+ when(docDbService.getDbCluster("document-cluster")).thenReturn(cluster);++ StackResource resource = provision(+ properties("AWS::DocDB::DBCluster", "document-cluster"));++ assertEquals("CREATE_COMPLETE", resource.getStatus());+ ArgumentCaptor<String> value = ArgumentCaptor.forClass(String.class);+ verify(secretsManagerService).putSecretValue(+ eq(SECRET_ARN), value.capture(), isNull(), isNull(), eq(REGION), isNull());+ JsonNode attached = mapper.readTree(value.getValue());+ assertEquals("mongo", attached.path("engine").asText());+ assertEquals("document-cluster.local", attached.path("host").asText());+ assertEquals(27017, attached.path("port").asInt());+ assertEquals("document-cluster", attached.path("dbClusterIdentifier").asText());+ assertTrue(attached.path("ssl").asBoolean());+ assertFalse(attached.has("dbInstanceIdentifier"));+ }++ @ParameterizedTest+ @ValueSource(strings = {"SecretId", "TargetId", "TargetType"})+ void allRequiredPropertiesAreValidated(String missingProperty) {+ ObjectNode properties = instanceProperties();+ properties.remove(missingProperty);++ StackResource resource = provision(properties);++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("requires " + missingProperty));+ assertNull(resource.getPhysicalId());+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void missingSecretFailsInsteadOfUsingTheUnresolvedId() {+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());+ when(secretsManagerService.describeSecret(SECRET_ID, REGION))+ .thenThrow(new AwsException("ResourceNotFoundException", "missing", 400));++ StackResource resource = provision(instanceProperties());++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("missing"));+ assertNull(resource.getPhysicalId());+ verify(secretsManagerService).describeSecret(SECRET_ID, REGION);+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void unchangedAttachmentDoesNotCreateAnotherSecretVersion() {+ stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\","+ + "\"engine\":\"postgres\",\"host\":\"db.local\",\"port\":5432,"+ + "\"dbname\":\"app\",\"dbInstanceIdentifier\":\"database\"}");+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());++ StackResource resource = provision(instanceProperties());++ assertEquals("CREATE_COMPLETE", resource.getStatus());+ assertEquals(SECRET_ARN, resource.getPhysicalId());+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void changingTargetOnTheSameSecretUpdatesInPlace() throws Exception {+ stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\","+ + "\"engine\":\"postgres\",\"host\":\"db.local\",\"port\":5432,"+ + "\"dbname\":\"app\",\"dbInstanceIdentifier\":\"database\"}");+ DbCluster cluster = new DbCluster();+ cluster.setDbClusterIdentifier("replacement-cluster");+ cluster.setEngine(DatabaseEngine.POSTGRES);+ cluster.setEndpoint(new DbEndpoint("replacement.local", 6432));+ cluster.setDatabaseName("replacement");+ when(rdsService.getDbCluster("replacement-cluster")).thenReturn(cluster);++ StackResource resource = provision(+ properties("AWS::RDS::DBCluster", "replacement-cluster"),+ SECRET_ARN,+ Map.of(+ "__FlociSecretTargetManagedKeys",+ "engine,host,port,dbname,dbInstanceIdentifier",+ "__FlociSecretTargetOwner",+ "stack/Attachment"));++ assertEquals("CREATE_COMPLETE", resource.getStatus());+ assertEquals(SECRET_ARN, resource.getPhysicalId());+ ArgumentCaptor<String> value = ArgumentCaptor.forClass(String.class);+ verify(secretsManagerService).putSecretValue(+ eq(SECRET_ARN), value.capture(), isNull(), isNull(), eq(REGION), isNull());+ JsonNode updated = mapper.readTree(value.getValue());+ assertEquals("replacement.local", updated.path("host").asText());+ assertEquals(6432, updated.path("port").asInt());+ assertEquals("replacement", updated.path("dbname").asText());+ assertEquals("replacement-cluster",+ updated.path("dbClusterIdentifier").asText());+ assertFalse(updated.has("dbInstanceIdentifier"));+ verify(secretsManagerService, never()).releaseTargetAttachment(+ any(), any(), any());+ }++ @Test+ void legacyNamePhysicalIdResolvingToTheSameSecretIsNotDetached() {+ stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\","+ + "\"engine\":\"postgres\",\"host\":\"db.local\",\"port\":5432,"+ + "\"dbname\":\"app\",\"dbInstanceIdentifier\":\"database\"}");+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());++ StackResource resource = provision(instanceProperties(), SECRET_ID,+ Map.of("__FlociSecretTargetManagedKeys",+ "engine,host,port,dbname,dbInstanceIdentifier"));++ assertEquals("CREATE_COMPLETE", resource.getStatus());+ assertEquals(SECRET_ARN, resource.getPhysicalId());+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void failedLegacyUpdateReleasesTheClaimCreatedByThatAttempt() {+ stubSecretValues("not-json");+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());++ StackResource resource = provision(+ instanceProperties(),+ SECRET_ARN,+ Map.of("__FlociSecretTargetManagedKeys",+ "engine,host,port,dbname,dbInstanceIdentifier"));++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("must be a JSON object"));+ verify(secretsManagerService).releaseTargetAttachment(+ SECRET_ARN, "stack/Attachment", REGION);+ }++ @Test+ void missingTargetFailsBeforeReadingTheSecret() {+ when(rdsService.getDbInstance("database"))+ .thenThrow(new AwsException("DBInstanceNotFound", "database is missing", 404));++ StackResource resource = provision(instanceProperties());++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("database is missing"));+ verifyNoInteractions(secretsManagerService);+ }++ @Test+ void incompleteTargetFailsBeforeReadingTheSecret() {+ DbInstance instance = dbInstance();+ instance.setEndpoint(null);+ when(rdsService.getDbInstance("database")).thenReturn(instance);++ StackResource resource = provision(instanceProperties());++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("incomplete connection information"));+ verifyNoInteractions(secretsManagerService);+ }++ @Test+ void replacingTheSecretAttachesTheNewSecretBeforeDetachingTheOldSecret() throws Exception {+ String oldArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:old-a1b2c3";+ String newArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:new-d4e5f6";+ ObjectNode properties = instanceProperties();+ properties.put("SecretId", "new-secret");+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());+ when(secretsManagerService.describeSecret("new-secret", REGION)).thenReturn(secret(newArn));+ when(secretsManagerService.describeSecret(oldArn, REGION)).thenReturn(secret(oldArn));+ when(secretsManagerService.getSecretValue(newArn, null, null, REGION))+ .thenReturn(secretVersion("{\"username\":\"new-user\",\"password\":\"new-password\"}"));+ when(secretsManagerService.getSecretValue(oldArn, null, null, REGION))+ .thenReturn(secretVersion("{\"username\":\"old-user\",\"password\":\"old-password\","+ + "\"engine\":\"mysql\",\"host\":\"old.local\",\"port\":3306,"+ + "\"dbInstanceIdentifier\":\"old-database\"}"));++ StackResource resource = provision(properties, oldArn,+ Map.of("__FlociSecretTargetManagedKeys",+ "engine,host,port,dbInstanceIdentifier"));++ assertEquals("CREATE_COMPLETE", resource.getStatus());+ assertEquals(newArn, resource.getPhysicalId());+ ArgumentCaptor<String> ids = ArgumentCaptor.forClass(String.class);+ ArgumentCaptor<String> values = ArgumentCaptor.forClass(String.class);+ verify(secretsManagerService, times(2)).putSecretValue(+ ids.capture(), values.capture(), isNull(), isNull(), eq(REGION), isNull());+ assertEquals(List.of(newArn, oldArn), ids.getAllValues());++ JsonNode attached = mapper.readTree(values.getAllValues().get(0));+ assertEquals("new-user", attached.path("username").asText());+ assertEquals("postgres", attached.path("engine").asText());+ assertEquals("database", attached.path("dbInstanceIdentifier").asText());++ JsonNode detached = mapper.readTree(values.getAllValues().get(1));+ assertEquals("old-user", detached.path("username").asText());+ assertEquals("old-password", detached.path("password").asText());+ assertFalse(detached.has("engine"));+ assertFalse(detached.has("host"));+ assertFalse(detached.has("port"));+ assertFalse(detached.has("dbInstanceIdentifier"));+ }++ @Test+ void invalidOldSecretIsTreatedAsDetachedDuringReplacement() {+ String oldArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:old-a1b2c3";+ String newArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:new-d4e5f6";+ ObjectNode properties = instanceProperties();+ properties.put("SecretId", "new-secret");+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());+ when(secretsManagerService.describeSecret("new-secret", REGION)).thenReturn(secret(newArn));+ when(secretsManagerService.describeSecret(oldArn, REGION)).thenReturn(secret(oldArn));+ when(secretsManagerService.getSecretValue(newArn, null, null, REGION))+ .thenReturn(secretVersion("{\"username\":\"new-user\",\"password\":\"new-password\"}"));+ when(secretsManagerService.getSecretValue(oldArn, null, null, REGION))+ .thenReturn(secretVersion("not-json"));++ StackResource resource = provision(properties, oldArn,+ Map.of("__FlociSecretTargetManagedKeys", "engine,host,port"));++ assertEquals("CREATE_COMPLETE", resource.getStatus());+ assertEquals(newArn, resource.getPhysicalId());+ verify(secretsManagerService).putSecretValue(+ eq(newArn), any(), isNull(), isNull(), eq(REGION), isNull());+ verify(secretsManagerService, never()).putSecretValue(+ eq(oldArn), any(), any(), any(), any(), any());+ }++ @Test+ void failedPreviousDetachRestoresTheNewSecretAndReleasesItsClaim() throws Exception {+ String oldArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:old-a1b2c3";+ String newArn = "arn:aws:secretsmanager:us-east-1:000000000000:secret:new-d4e5f6";+ String newOriginal = "{\"username\":\"new-user\",\"password\":\"new-password\"}";+ ObjectNode properties = instanceProperties();+ properties.put("SecretId", "new-secret");+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());+ when(secretsManagerService.describeSecret("new-secret", REGION)).thenReturn(secret(newArn));+ when(secretsManagerService.describeSecret(oldArn, REGION)).thenReturn(secret(oldArn));+ when(secretsManagerService.getSecretValue(newArn, null, null, REGION))+ .thenReturn(secretVersion(newOriginal));+ when(secretsManagerService.getSecretValue(oldArn, null, null, REGION))+ .thenReturn(secretVersion("{\"username\":\"old-user\",\"password\":\"old-password\","+ + "\"engine\":\"mysql\",\"host\":\"old.local\",\"port\":3306,"+ + "\"dbInstanceIdentifier\":\"old-database\"}"));+ AwsException denied = new AwsException("AccessDeniedException", "detach denied", 403);+ when(secretsManagerService.putSecretValue(+ eq(oldArn), any(), isNull(), isNull(), eq(REGION), isNull()))+ .thenThrow(denied);++ StackResource resource = provision(properties, oldArn,+ Map.of(+ "__FlociSecretTargetManagedKeys",+ "engine,host,port,dbInstanceIdentifier",+ "__FlociSecretTargetOwner",+ "stack/Attachment"));++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertEquals("detach denied", resource.getStatusReason());+ assertEquals(oldArn, resource.getPhysicalId());+ ArgumentCaptor<String> newValues = ArgumentCaptor.forClass(String.class);+ verify(secretsManagerService, times(2)).putSecretValue(+ eq(newArn), newValues.capture(), isNull(), isNull(), eq(REGION), isNull());+ assertEquals("postgres",+ mapper.readTree(newValues.getAllValues().getFirst()).path("engine").asText());+ assertEquals(mapper.readTree(newOriginal),+ mapper.readTree(newValues.getAllValues().get(1)));+ verify(secretsManagerService).releaseTargetAttachment(+ newArn, "stack/Attachment", REGION);+ verify(secretsManagerService, never()).releaseTargetAttachment(+ oldArn, "stack/Attachment", REGION);+ }++ @Test+ void detachDoesNotCreateAnotherVersionWhenManagedFieldsAreAlreadyAbsent() {+ when(secretsManagerService.getSecretValue(SECRET_ARN, null, null, REGION))+ .thenReturn(secretVersion("{\"username\":\"admin\",\"custom\":\"keep\"}"));++ provisioner.delete(attachmentResource(), REGION);++ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void detachTreatsAnAlreadyDeletedSecretAsComplete() {+ when(secretsManagerService.getSecretValue(SECRET_ARN, null, null, REGION))+ .thenThrow(new AwsException("ResourceNotFoundException", "missing", 400));++ assertDoesNotThrow(() -> provisioner.delete(attachmentResource(), REGION));+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @ParameterizedTest+ @ValueSource(strings = {"not-json", "\"plain-text\"", "[]"})+ void detachTreatsMalformedOrNonObjectSecretAsAlreadyDetached(String secretString) {+ when(secretsManagerService.getSecretValue(SECRET_ARN, null, null, REGION))+ .thenReturn(secretVersion(secretString));++ assertDoesNotThrow(() -> provisioner.delete(attachmentResource(), REGION));++ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void detachTreatsBinarySecretAsAlreadyDetached() {+ SecretVersion binary = new SecretVersion();+ binary.setSecretBinary("AQID");+ when(secretsManagerService.getSecretValue(SECRET_ARN, null, null, REGION))+ .thenReturn(binary);++ assertDoesNotThrow(() -> provisioner.delete(attachmentResource(), REGION));++ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void detachStillPropagatesSecretReadFailures() {+ AwsException denied = new AwsException("AccessDeniedException", "denied", 403);+ when(secretsManagerService.getSecretValue(SECRET_ARN, null, null, REGION))+ .thenThrow(denied);++ AwsException thrown = assertThrows(+ AwsException.class, () -> provisioner.delete(attachmentResource(), REGION));++ assertSame(denied, thrown);+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void detachSkipsASecretClaimedByAnotherAttachment() {+ StackResource resource = attachmentResource();+ when(secretsManagerService.canManageTargetAttachment(+ SECRET_ARN, "stack/Attachment", REGION)).thenReturn(false);++ assertDoesNotThrow(() -> provisioner.delete(resource, REGION));++ verify(secretsManagerService, never()).getSecretValue(+ any(), any(), any(), any());+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ verify(secretsManagerService, never()).releaseTargetAttachment(+ any(), any(), any());+ }++ @Test+ void physicalIdOnlyDeleteRefusesToGuessWhichSecretFieldsWereManaged() {+ AwsException exception = assertThrows(AwsException.class, () -> provisioner.delete(+ "AWS::SecretsManager::SecretTargetAttachment", SECRET_ARN, REGION));++ assertEquals("ValidationError", exception.getErrorCode());+ assertTrue(exception.getMessage().contains("StackResource metadata"));+ verifyNoInteractions(secretsManagerService);+ }++ @ParameterizedTest+ @ValueSource(strings = {"not-json", "\"plain-text\"", "[]"})+ void secretValueMustBeAJsonObject(String secretString) {+ stubSecretValues(secretString);+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());++ StackResource resource = provision(instanceProperties());++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("must be a JSON object"));+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void binarySecretStillFailsProvisioning() {+ SecretVersion binary = new SecretVersion();+ binary.setSecretBinary("AQID");+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());+ when(secretsManagerService.describeSecret(SECRET_ID, REGION)).thenReturn(secret(SECRET_ARN));+ when(secretsManagerService.getSecretValue(SECRET_ARN, null, null, REGION))+ .thenReturn(binary);++ StackResource resource = provision(instanceProperties());++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("must be a JSON object"));+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @ParameterizedTest+ @ValueSource(strings = {+ "AWS::Redshift::Cluster",+ "AWS::RedshiftServerless::Namespace",+ "AWS::DocDBElastic::Cluster"+ })+ void targetTypesWithoutBackingServicesFailExplicitly(String targetType) {+ stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\"}");++ StackResource resource = provision(properties(targetType, "database"));++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("not supported by Floci"));+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ @Test+ void aSecondAttachmentToTheSameSecretFailsBeforeReadingOrWritingItsValue() {+ when(rdsService.getDbInstance("database")).thenReturn(dbInstance());+ when(secretsManagerService.describeSecret(SECRET_ID, REGION)).thenReturn(secret(SECRET_ARN));+ when(secretsManagerService.claimTargetAttachment(+ SECRET_ARN, "stack/Attachment", REGION))+ .thenThrow(new AwsException(+ "ResourceExistsException",+ "A target is already attached to secret " + SECRET_ARN + ".",+ 400));++ StackResource resource = provision(instanceProperties());++ assertEquals("CREATE_FAILED", resource.getStatus());+ assertTrue(resource.getStatusReason().contains("already attached"));+ verify(secretsManagerService, never()).getSecretValue(+ any(), any(), any(), any());+ verify(secretsManagerService, never()).putSecretValue(+ any(), any(), any(), any(), any(), any());+ }++ private StackResource provision(JsonNode properties) {+ return provision(properties, null, Map.of());+ }++ private StackResource provision(JsonNode properties, String existingPhysicalId,+ Map<String, String> existingAttributes) {+ return provisioner.provision(+ "Attachment", "AWS::SecretsManager::SecretTargetAttachment", properties,+ engine(), REGION, "000000000000", "stack",+ existingPhysicalId, existingAttributes);+ }++ private ObjectNode instanceProperties() {+ return properties("AWS::RDS::DBInstance", "database");+ }++ private ObjectNode properties(String targetType, String targetId) {+ ObjectNode properties = mapper.createObjectNode();+ properties.put("SecretId", SECRET_ID);+ properties.put("TargetId", targetId);+ properties.put("TargetType", targetType);+ return properties;+ }++ private DbInstance dbInstance() {+ DbInstance instance = new DbInstance();+ instance.setDbInstanceIdentifier("database");+ instance.setEngine(DatabaseEngine.POSTGRES);+ instance.setEndpoint(new DbEndpoint("db.local", 5432));+ instance.setDbName("app");+ return instance;+ }++ private void stubSecretValues(String... values) {+ when(secretsManagerService.describeSecret(SECRET_ID, REGION)).thenReturn(secret(SECRET_ARN));+ SecretVersion[] versions = java.util.Arrays.stream(values)+ .map(this::secretVersion)+ .toArray(SecretVersion[]::new);+ when(secretsManagerService.getSecretValue(SECRET_ARN, null, null, REGION))+ .thenReturn(versions[0], java.util.Arrays.copyOfRange(versions, 1, versions.length));+ }++ private Secret secret(String arn) {+ Secret secret = new Secret();+ secret.setArn(arn);+ return secret;+ }++ private SecretVersion secretVersion(String value) {+ SecretVersion version = new SecretVersion();+ version.setSecretString(value);+ return version;+ }++ private StackResource attachmentResource() {+ StackResource resource = new StackResource();+ resource.setLogicalId("Attachment");+ resource.setResourceType("AWS::SecretsManager::SecretTargetAttachment");+ resource.setPhysicalId(SECRET_ARN);+ resource.setAttributes(new java.util.HashMap<>(Map.of(+ "__FlociSecretTargetManagedKeys",+ "engine,host,port,dbname,dbInstanceIdentifier",+ "__FlociSecretTargetOwner",+ "stack/Attachment")));+ return resource;+ }++ private CloudFormationTemplateEngine engine() {+ return new CloudFormationTemplateEngine(+ "000000000000", REGION, "stack", "stack/id",+ Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,+ (Function<String, String>) name -> null);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.javaindex 5aa709d44d..b4ef4e9c7d 100644--- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandlerTest.java@@ -16,11 +16,12 @@ class SecretsManagerJsonHandlerTest {private static final String REGION = "us-east-1";private static final ObjectMapper MAPPER = new ObjectMapper();+ private SecretsManagerService service;private SecretsManagerJsonHandler handler;@BeforeEachvoid setUp() {- SecretsManagerService service = new SecretsManagerService(new InMemoryStorage<>(), 30);+ service = new SecretsManagerService(new InMemoryStorage<>(), 30);handler = new SecretsManagerJsonHandler(service, MAPPER);}@@ -142,6 +143,30 @@ class SecretsManagerJsonHandlerTest {assertThat(body.get("KmsKeyId").asText(), is("my-kms-key"));}+ @Test+ void targetAttachmentOwnershipIsNotExposedByPublicResponses() {+ ObjectNode createReq = MAPPER.createObjectNode();+ createReq.put("Name", "attached-secret");+ handler.handle("CreateSecret", createReq, REGION);+ service.claimTargetAttachment("attached-secret", "stack/Attachment", REGION);++ ObjectNode describeReq = MAPPER.createObjectNode();+ describeReq.put("SecretId", "attached-secret");+ ObjectNode described = (ObjectNode) handler+ .handle("DescribeSecret", describeReq, REGION)+ .getEntity();+ ObjectNode listed = (ObjectNode) ((ObjectNode) handler+ .handle("ListSecrets", MAPPER.createObjectNode(), REGION)+ .getEntity())+ .path("SecretList")+ .path(0);++ assertThat(described.has("targetAttachmentOwner"), is(false));+ assertThat(described.has("TargetAttachmentOwner"), is(false));+ assertThat(listed.has("targetAttachmentOwner"), is(false));+ assertThat(listed.has("TargetAttachmentOwner"), is(false));+ }+@Testvoid listSecretsResponseIncludesKmsKeyId() {ObjectNode createReq = MAPPER.createObjectNode();diff --git a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.javaindex d10d5a4e64..8b59428f95 100644--- a/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerServiceTest.java@@ -161,6 +161,34 @@ class SecretsManagerServiceTest {assertEquals("desc", described.getDescription());}+ @Test+ void targetAttachmentClaimIsExclusiveAndIdempotentForItsOwner() {+ service.createSecret("my-secret", "value", null, null, null, null, REGION);++ assertTrue(service.claimTargetAttachment("my-secret", "stack/First", REGION));+ assertFalse(service.claimTargetAttachment("my-secret", "stack/First", REGION));+ AwsException duplicate = assertThrows(AwsException.class,+ () -> service.claimTargetAttachment("my-secret", "stack/Second", REGION));++ assertEquals("ResourceExistsException", duplicate.getErrorCode());+ assertTrue(duplicate.getMessage().contains("already attached"));+ assertTrue(service.canManageTargetAttachment("my-secret", "stack/First", REGION));+ assertFalse(service.canManageTargetAttachment("my-secret", "stack/Second", REGION));+ }++ @Test+ void targetAttachmentClaimCanOnlyBeReleasedByItsOwner() {+ service.createSecret("my-secret", "value", null, null, null, null, REGION);+ service.claimTargetAttachment("my-secret", "stack/First", REGION);++ service.releaseTargetAttachment("my-secret", "stack/Second", REGION);+ assertThrows(AwsException.class,+ () -> service.claimTargetAttachment("my-secret", "stack/Second", REGION));++ service.releaseTargetAttachment("my-secret", "stack/First", REGION);+ assertTrue(service.claimTargetAttachment("my-secret", "stack/Second", REGION));+ }+@Testvoid updateSecret() {service.createSecret("my-secret", "value", null, "old desc", null, null, REGION);