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

@@ -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()));
}
@@ -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()));
}
@@ -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");
}
}
}
@@ -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()));
}
@@ -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()));
}
@@ -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);
}
}
@@ -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;
@BeforeEach
void 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));
}
@Test
void listSecretsResponseIncludesKmsKeyId() {
ObjectNode createReq = MAPPER.createObjectNode();
@@ -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));
}
@Test
void updateSecret() {
service.createSecret("my-secret", "value", null, "old desc", null, null, REGION);