feat: support managed credentials in Redshift restore (#6515)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-25 21:43:14 -04:00
1 parent 7f5f1b554d
commit 2a5f734777
19 files changed
+849 -40

No files matched your search

@@ -3,12 +3,17 @@ package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessRuntime;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -52,7 +57,7 @@ class RedshiftServerlessCfnIntegrationTest {
"Properties": {
"NamespaceName": "%s",
"AdminUsername": "admin",
"AdminUserPassword": "Secret123!",
"ManageAdminPassword": true,
"DbName": "analytics",
"LogExports": ["userlog"],
"Tags": [{"Key": "env", "Value": "dev"}]
@@ -99,6 +104,12 @@ class RedshiftServerlessCfnIntegrationTest {
@InjectMock
RedshiftServerlessRuntime runtime;
@Inject
RedshiftServerlessService serverless;
@Inject
SecretsManagerService secrets;
@BeforeEach
void stubRuntime() {
when(runtime.generatePassword()).thenReturn("Generated123");
@@ -107,6 +118,37 @@ class RedshiftServerlessCfnIntegrationTest {
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
}
@Test
void failedStackUpdateRestoresManagedCredentialsAndOriginalSecret() {
cloudFormation("CreateStack", "32");
describeStacks("CREATE_COMPLETE");
Namespace original = serverless.getNamespace(NAMESPACE, "us-east-1");
String arn = original.getAdminPasswordSecretArn();
Secret originalSecret = secrets.describeSecret(arn, "us-east-1");
String originalVersion = originalSecret.getCurrentVersionId();
String originalValue = secrets.getSecretValue(arn, null, null, "us-east-1").getSecretString();
try {
String update = TEMPLATE.replace("\"ManageAdminPassword\": true",
"\"ManageAdminPassword\": false, \"AdminUserPassword\": \"Changed123!\"");
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", STACK)
.formParam("TemplateBody", update)
.formParam("Parameters.member.1.ParameterKey", "Capacity")
.formParam("Parameters.member.1.ParameterValue", "0")
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStatus(STACK, "UPDATE_ROLLBACK_COMPLETE");
Namespace restored = serverless.getNamespace(NAMESPACE, "us-east-1");
assertEquals(arn, restored.getAdminPasswordSecretArn());
assertEquals(original.getAdminUserPassword(), restored.getAdminUserPassword());
assertEquals(originalVersion, secrets.describeSecret(arn, "us-east-1").getCurrentVersionId());
assertEquals(originalValue, secrets.getSecretValue(arn, null, null, "us-east-1").getSecretString());
} finally {
cloudFormation("DeleteStack", null);
CfnStackWaits.awaitStackDeleted(STACK);
}
}
@Test
void createUpdateAndDeleteANamespaceAndWorkgroup() {
cloudFormation("CreateStack", "32");
@@ -116,6 +158,8 @@ class RedshiftServerlessCfnIntegrationTest {
assertEquals(WORKGROUP, outputValue(created, "WgRef"));
assertEquals("analytics", outputValue(created, "NsDb"));
assertEquals("AVAILABLE", outputValue(created, "NsStatus"));
String secretArn = serverless.getNamespace(NAMESPACE, "us-east-1").getAdminPasswordSecretArn();
assertTrue(secretArn.startsWith("arn:aws:secretsmanager:"));
assertEquals("AVAILABLE", outputValue(created, "WgStatus"));
assertEquals(NAMESPACE, outputValue(created, "WgNamespace"));
assertEquals("32", outputValue(created, "WgBase"));
@@ -128,6 +172,7 @@ class RedshiftServerlessCfnIntegrationTest {
.statusCode(200)
.body("namespace.namespaceArn", equalTo(outputValue(created, "NsArn")))
.body("namespace.namespaceId", equalTo(outputValue(created, "NsId")))
.body("namespace.adminPasswordSecretArn", equalTo(secretArn))
.body("namespace.logExports", hasItem("userlog"));
call("GetWorkgroup", "{\"workgroupName\":\"" + WORKGROUP + "\"}")
.statusCode(200)
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService.NamespaceUpdateSnapshot;
import io.github.hectorvent.floci.services.redshiftserverless.WorkgroupSettings;
import io.github.hectorvent.floci.services.redshiftserverless.model.ConfigParameter;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
@@ -32,9 +33,11 @@ import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
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.when;
@@ -46,6 +49,9 @@ class RedshiftServerlessCfnProvisionerTest {
private static final String WORKGROUP_TYPE = "AWS::RedshiftServerless::Workgroup";
private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:000000000000:namespace/ns-id";
private static final String WORKGROUP_ARN = "arn:aws:redshift-serverless:us-east-1:000000000000:workgroup/wg-id";
private static final String ADMIN_SECRET_ARN =
"arn:aws:secretsmanager:us-east-1:000000000000:secret:admin-abcdef";
private static final String ADMIN_SECRET_KEY = "arn:aws:kms:us-east-1:000000000000:key/admin-key";
private final RedshiftServerlessService service = mock(RedshiftServerlessService.class);
private final RedshiftServerlessCfnProvisioner provisioner = new RedshiftServerlessCfnProvisioner(service);
@@ -104,7 +110,8 @@ class RedshiftServerlessCfnProvisionerTest {
@Test
void createNamespaceSendsPropertiesAndRecordsEveryDottedAttribute() {
when(service.createNamespace(eq("my-ns"), eq("admin"), eq("Secret123"), eq("analytics"), isNull(),
isNull(), anyList(), anyList(), anyMap(), eq(REGION))).thenReturn(namespace("my-ns"));
isNull(), anyList(), anyList(), anyMap(), isNull(), isNull(), eq(REGION)))
.thenReturn(namespace("my-ns"));
ObjectNode props = mapper.createObjectNode();
props.put("NamespaceName", "my-ns");
props.put("AdminUsername", "admin");
@@ -131,14 +138,123 @@ class RedshiftServerlessCfnProvisionerTest {
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> tags = ArgumentCaptor.forClass(Map.class);
verify(service).createNamespace(eq("my-ns"), eq("admin"), eq("Secret123"), eq("analytics"), isNull(),
isNull(), anyList(), anyList(), tags.capture(), eq(REGION));
isNull(), anyList(), anyList(), tags.capture(), isNull(), isNull(), eq(REGION));
assertEquals(Map.of("env", "dev"), tags.getValue());
}
@Test
void namespaceRollbackRetainsSnapshotOnFailureAndRestoresAttributesOnRetry() throws Exception {
Namespace previous = namespace("existing-ns");
previous.setAdminUserPassword("Original123!");
previous.setAdminPasswordSecretArn(ADMIN_SECRET_ARN);
NamespaceUpdateSnapshot snapshot = new NamespaceUpdateSnapshot(previous, null);
when(service.getNamespace("existing-ns", REGION)).thenReturn(previous);
when(service.snapshotNamespaceUpdate("existing-ns", REGION)).thenReturn(snapshot);
when(service.reconcileNamespace(eq("existing-ns"), any(), any(), any(), any(), anyList(), anyList(),
eq(false), any(), eq(REGION))).thenReturn(namespace("existing-ns"));
StackResource resource = resource(NAMESPACE_TYPE, "existing-ns");
resource.getAttributes().put("Namespace.NamespaceArn", NAMESPACE_ARN);
Map<String, String> previousAttributes = Map.copyOf(resource.getAttributes());
provisioner.provision(resource, mapper.readTree("""
{"NamespaceName":"existing-ns", "AdminUserPassword":"Changed123!", "ManageAdminPassword":false}
"""), ctx("existing-ns"));
assertTrue(provisioner.retainsFailedUpdateState(resource));
doThrow(new IllegalStateException("Backend unavailable")).when(service).restoreNamespaceUpdate(any(), eq(REGION));
assertThrows(IllegalStateException.class, () -> provisioner.rollbackUpdate(resource));
assertTrue(provisioner.retainsFailedUpdateState(resource));
doNothing().when(service).restoreNamespaceUpdate(any(), eq(REGION));
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals(previousAttributes, resource.getAttributes());
assertFalse(provisioner.retainsFailedUpdateState(resource));
ArgumentCaptor<NamespaceUpdateSnapshot> restored = ArgumentCaptor.forClass(NamespaceUpdateSnapshot.class);
verify(service, times(2)).restoreNamespaceUpdate(restored.capture(), eq(REGION));
assertEquals("Original123!", restored.getValue().namespace().getAdminUserPassword());
assertEquals(ADMIN_SECRET_ARN, restored.getValue().namespace().getAdminPasswordSecretArn());
}
@Test
void committedNamespaceUpdateClearsRollbackSnapshot() throws Exception {
Namespace previous = namespace("existing-ns");
when(service.getNamespace("existing-ns", REGION)).thenReturn(previous);
when(service.snapshotNamespaceUpdate("existing-ns", REGION))
.thenReturn(new NamespaceUpdateSnapshot(previous, null));
when(service.reconcileNamespace(eq("existing-ns"), any(), any(), any(), any(), anyList(), anyList(),
eq(false), any(), eq(REGION))).thenReturn(previous);
StackResource resource = resource(NAMESPACE_TYPE, "existing-ns");
provisioner.provision(resource, mapper.readTree("{\"NamespaceName\":\"existing-ns\"}"), ctx("existing-ns"));
assertTrue(provisioner.completeUpdate(resource).complete());
provisioner.clearUpdate(resource);
assertFalse(provisioner.retainsFailedUpdateState(resource));
assertFalse(provisioner.rollbackUpdate(resource));
}
@Test
void createNamespacePassesManagedCredentialPropertiesWithoutExposingSecretAttributes() {
Namespace namespace = namespace("managed-ns");
namespace.setAdminPasswordSecretArn(ADMIN_SECRET_ARN);
namespace.setAdminPasswordSecretKmsKeyId(ADMIN_SECRET_KEY);
when(service.createNamespace(eq("managed-ns"), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
anyList(), anyMap(), eq(true), eq(ADMIN_SECRET_KEY), eq(REGION))).thenReturn(namespace);
ObjectNode props = mapper.createObjectNode();
props.put("NamespaceName", "managed-ns");
props.put("ManageAdminPassword", true);
props.put("AdminPasswordSecretKmsKeyId", ADMIN_SECRET_KEY);
StackResource resource = resource(NAMESPACE_TYPE, null);
provisioner.provision(resource, props, ctx(null));
verify(service).createNamespace(eq("managed-ns"), isNull(), isNull(), isNull(), isNull(), isNull(), anyList(),
anyList(), anyMap(), eq(true), eq(ADMIN_SECRET_KEY), eq(REGION));
assertFalse(resource.getAttributes().containsKey("Namespace.AdminPasswordSecretArn"));
assertFalse(resource.getAttributes().containsKey("Namespace.AdminPasswordSecretKmsKeyId"));
}
@Test
void updateNamespacePassesManagedCredentialPropertiesWithoutExposingSecretAttributes() {
Namespace namespace = namespace("managed-ns");
namespace.setAdminPasswordSecretArn(ADMIN_SECRET_ARN);
namespace.setAdminPasswordSecretKmsKeyId(ADMIN_SECRET_KEY);
when(service.getNamespace("managed-ns", REGION)).thenReturn(namespace);
when(service.reconcileNamespace(eq("managed-ns"), isNull(), isNull(), isNull(), isNull(), anyList(),
anyList(), eq(true), eq(ADMIN_SECRET_KEY), eq(REGION))).thenReturn(namespace);
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of());
ObjectNode props = mapper.createObjectNode();
props.put("NamespaceName", "managed-ns");
props.put("ManageAdminPassword", true);
props.put("AdminPasswordSecretKmsKeyId", ADMIN_SECRET_KEY);
StackResource resource = resource(NAMESPACE_TYPE, "managed-ns");
provisioner.provision(resource, props, ctx("managed-ns"));
verify(service).reconcileNamespace(eq("managed-ns"), isNull(), isNull(), isNull(), isNull(), anyList(),
anyList(), eq(true), eq(ADMIN_SECRET_KEY), eq(REGION));
assertFalse(resource.getAttributes().containsKey("Namespace.AdminPasswordSecretArn"));
assertFalse(resource.getAttributes().containsKey("Namespace.AdminPasswordSecretKmsKeyId"));
}
@Test
void updateNamespaceDisablesManagementWithoutExposingSecretAttributes() {
Namespace namespace = namespace("managed-ns");
when(service.getNamespace("managed-ns", REGION)).thenReturn(namespace);
when(service.reconcileNamespace(eq("managed-ns"), isNull(), isNull(), isNull(), isNull(), anyList(),
anyList(), eq(false), isNull(), eq(REGION))).thenReturn(namespace);
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of());
StackResource resource = resource(NAMESPACE_TYPE, "managed-ns");
provisioner.provision(resource, mapper.createObjectNode(), ctx("managed-ns"));
assertFalse(resource.getAttributes().containsKey("Namespace.AdminPasswordSecretArn"));
assertFalse(resource.getAttributes().containsKey("Namespace.AdminPasswordSecretKmsKeyId"));
}
@Test
void anUnnamedNamespaceGetsALowercaseGeneratedNameThatIsStableAcrossUpdates() {
when(service.createNamespace(any(), any(), any(), any(), any(), any(), anyList(), anyList(), anyMap(),
eq(REGION)))
isNull(), isNull(), eq(REGION)))
.thenAnswer(inv -> namespace(inv.getArgument(0)));
StackResource created = resource(NAMESPACE_TYPE, null);
@@ -149,7 +265,8 @@ class RedshiftServerlessCfnProvisionerTest {
assertEquals(generated, generated.toLowerCase());
when(service.getNamespace(generated, REGION)).thenReturn(namespace(generated));
when(service.reconcileNamespace(eq(generated), any(), any(), any(), any(), anyList(), anyList(), eq(REGION)))
when(service.reconcileNamespace(eq(generated), any(), any(), any(), any(), anyList(), anyList(), eq(false),
isNull(), eq(REGION)))
.thenReturn(namespace(generated));
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of());
StackResource updated = resource(NAMESPACE_TYPE, generated);
@@ -157,14 +274,15 @@ class RedshiftServerlessCfnProvisionerTest {
provisioner.provision(updated, mapper.createObjectNode(), ctx(generated));
assertEquals(generated, updated.getPhysicalId());
verify(service).reconcileNamespace(eq(generated), any(), any(), any(), any(), anyList(), anyList(), eq(REGION));
verify(service).reconcileNamespace(eq(generated), any(), any(), any(), any(), anyList(), anyList(), eq(false),
isNull(), eq(REGION));
}
@Test
void updateNamespaceUpdatesInPlaceAndRemovesTagsTheTemplateDropped() {
when(service.getNamespace("my-ns", REGION)).thenReturn(namespace("my-ns"));
when(service.reconcileNamespace(eq("my-ns"), isNull(), isNull(), eq("custom-key"), isNull(), anyList(),
anyList(), eq(REGION))).thenReturn(namespace("my-ns"));
anyList(), eq(false), isNull(), eq(REGION))).thenReturn(namespace("my-ns"));
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of("old", "1", "keep", "2"));
ObjectNode props = mapper.createObjectNode();
props.put("NamespaceName", "my-ns");
@@ -175,7 +293,7 @@ class RedshiftServerlessCfnProvisionerTest {
provisioner.provision(r, props, ctx("my-ns"));
verify(service, never()).createNamespace(any(), any(), any(), any(), any(), any(), anyList(), anyList(),
anyMap(), any());
anyMap(), any(), any(), any());
verify(service).untagResource(NAMESPACE_ARN, List.of("old"), REGION);
verify(service).tagResource(NAMESPACE_ARN, Map.of("keep", "2"), REGION);
assertEquals("my-ns", r.getPhysicalId());
@@ -192,14 +310,14 @@ class RedshiftServerlessCfnProvisionerTest {
AwsException rejected = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx("my-ns")));
assertEquals("ValidationException", rejected.getErrorCode());
verify(service, never()).reconcileNamespace(any(), any(), any(), any(), any(), any(), any(), any());
verify(service, never()).reconcileNamespace(any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void updateNamespaceSendsOmittedKmsKeyAndDefaultRoleAsNullSoTheServiceResetsThem() {
when(service.getNamespace("my-ns", REGION)).thenReturn(namespace("my-ns"));
when(service.reconcileNamespace(eq("my-ns"), isNull(), isNull(), isNull(), isNull(), anyList(), anyList(),
eq(REGION))).thenReturn(namespace("my-ns"));
eq(false), isNull(), eq(REGION))).thenReturn(namespace("my-ns"));
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of());
ObjectNode props = mapper.createObjectNode();
props.put("NamespaceName", "my-ns");
@@ -209,14 +327,14 @@ class RedshiftServerlessCfnProvisionerTest {
provisioner.provision(r, props, ctx("my-ns"));
verify(service).reconcileNamespace(eq("my-ns"), isNull(), isNull(), isNull(), isNull(), anyList(),
anyList(), eq(REGION));
anyList(), eq(false), isNull(), eq(REGION));
}
@Test
void updateNamespaceDropsTheDefaultRoleAttributeWhenTheTemplateNoLongerDeclaresIt() {
when(service.getNamespace("my-ns", REGION)).thenReturn(namespace("my-ns"));
when(service.reconcileNamespace(eq("my-ns"), isNull(), isNull(), isNull(), isNull(), anyList(), anyList(),
eq(REGION))).thenReturn(namespace("my-ns"));
eq(false), isNull(), eq(REGION))).thenReturn(namespace("my-ns"));
when(service.listTagsForResource(NAMESPACE_ARN, REGION)).thenReturn(Map.of());
ObjectNode props = mapper.createObjectNode();
props.put("NamespaceName", "my-ns");
@@ -8,16 +8,24 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -29,6 +37,8 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -54,11 +64,18 @@ class RedshiftServerlessAdminSecretsServiceTest {
private RedshiftServerlessRuntime runtime;
private SecretsManagerService secrets;
private ObjectMapper mapper;
private StorageFactory storageFactory;
private RegionResolver regions;
private RedshiftServerlessEndpoints endpoints;
private EmulatorConfig config;
@TempDir
Path tempDir;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setup() {
StorageFactory storageFactory = mock(StorageFactory.class);
storageFactory = mock(StorageFactory.class);
namespaces = spy(AccountAwareStorageBackend.inMemory(ACCOUNT));
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-namespaces.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) namespaces);
@@ -66,12 +83,12 @@ class RedshiftServerlessAdminSecretsServiceTest {
any(TypeReference.class))).thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT));
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-snapshots.json"),
any(TypeReference.class))).thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT));
RegionResolver regions = mock(RegionResolver.class);
regions = mock(RegionResolver.class);
when(regions.getAccountId()).thenReturn(ACCOUNT);
when(regions.buildArn(eq("redshift-serverless"), eq(REGION), any(String.class)))
.thenAnswer(invocation -> "arn:aws:redshift-serverless:" + REGION + ":" + ACCOUNT + ":"
+ invocation.getArgument(2, String.class));
RedshiftServerlessEndpoints endpoints = mock(RedshiftServerlessEndpoints.class);
endpoints = mock(RedshiftServerlessEndpoints.class);
when(endpoints.allocate()).thenReturn(new Endpoint("localhost", 7100));
runtime = mock(RedshiftServerlessRuntime.class);
when(runtime.generatePassword()).thenReturn(GENERATED_PASSWORD);
@@ -82,10 +99,13 @@ class RedshiftServerlessAdminSecretsServiceTest {
Secret secret = new Secret();
secret.setArn(SECRET_ARN);
secret.setKmsKeyId(SECRET_KEY);
secret.setOwningService("redshift");
when(secrets.describeSecret(SECRET_ARN, REGION)).thenReturn(secret);
when(secrets.createSecret(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(secret);
when(secrets.createSecret(any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(secret);
mapper = new ObjectMapper().findAndRegisterModules();
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
service = new RedshiftServerlessService(storageFactory, regions, endpoints, runtime, config,
new RedshiftServerlessAdminSecrets(secrets, mapper));
}
@@ -231,6 +251,186 @@ class RedshiftServerlessAdminSecretsServiceTest {
assertEquals(SECRET_KEY, copy.getAdminPasswordSecretKmsKeyId());
}
@Test
void namespaceRollbackRestoresDeletedManagedSecretAndBackendPassword() {
Namespace previous = createManaged();
attachWorkgroup();
RedshiftServerlessService.NamespaceUpdateSnapshot snapshot = service.snapshotNamespaceUpdate(NAME, REGION);
update(null, ORIGINAL_PASSWORD, false);
clearInvocations(runtime, secrets);
service.restoreNamespaceUpdate(snapshot, REGION);
assertEquals(previous.getAdminPasswordSecretArn(), service.getNamespace(NAME, REGION).getAdminPasswordSecretArn());
assertEquals(GENERATED_PASSWORD, service.getNamespace(NAME, REGION).getAdminUserPassword());
verify(runtime).changeMasterPassword(ACCOUNT, REGION, WORKGROUP, "admin", "analytics",
ORIGINAL_PASSWORD, GENERATED_PASSWORD);
ArgumentCaptor<Secret> restored = ArgumentCaptor.forClass(Secret.class);
verify(secrets).restoreManagedSecret(restored.capture(), eq(REGION));
assertEquals(SECRET_ARN, restored.getValue().getArn());
assertEquals(SECRET_KEY, restored.getValue().getKmsKeyId());
}
@Test
void namespaceRollbackLeavesCredentialsUnchangedWhenSecretRestoreConflicts() {
createManaged();
attachWorkgroup();
RedshiftServerlessService.NamespaceUpdateSnapshot snapshot = service.snapshotNamespaceUpdate(NAME, REGION);
Namespace current = update(null, ORIGINAL_PASSWORD, false);
clearInvocations(runtime, secrets);
AwsException conflict = new AwsException("ResourceExistsException", "Secret name has been reused", 400);
doThrow(conflict).when(secrets).restoreManagedSecret(any(Secret.class), eq(REGION));
assertSame(conflict, assertThrows(AwsException.class, () -> service.restoreNamespaceUpdate(snapshot, REGION)));
assertSame(current, service.getNamespace(NAME, REGION));
assertEquals(ORIGINAL_PASSWORD, current.getAdminUserPassword());
assertNull(current.getAdminPasswordSecretArn());
verify(runtime, never()).changeMasterPassword(any(), any(), any(), any(), any(), any(), any());
verify(runtime, never()).restoreMasterPassword(any(), any(), any(), any(), any(), any());
verify(secrets, never()).deleteSecret(any(), any(), anyBoolean(), any());
}
@Test
void namespaceRollbackRemovesNewManagedSecretAndRestoresUnmanagedPassword() {
createUnmanaged();
attachWorkgroup();
RedshiftServerlessService.NamespaceUpdateSnapshot snapshot = service.snapshotNamespaceUpdate(NAME, REGION);
update(null, null, true);
clearInvocations(runtime, secrets);
service.restoreNamespaceUpdate(snapshot, REGION);
assertNull(service.getNamespace(NAME, REGION).getAdminPasswordSecretArn());
assertEquals(ORIGINAL_PASSWORD, service.getNamespace(NAME, REGION).getAdminUserPassword());
verify(runtime).changeMasterPassword(ACCOUNT, REGION, WORKGROUP, "admin", "analytics",
GENERATED_PASSWORD, ORIGINAL_PASSWORD);
verify(secrets).deleteSecret(SECRET_ARN, null, true, REGION);
}
@Test
void blockedRollbackSecretDeletionRestoresCurrentBackendPasswordAndCanRetry() {
createUnmanaged();
attachWorkgroup();
RedshiftServerlessService.NamespaceUpdateSnapshot snapshot = service.snapshotNamespaceUpdate(NAME, REGION);
Namespace managed = update(null, null, true);
AtomicReference<String> backendPassword = new AtomicReference<>(GENERATED_PASSWORD);
doAnswer(invocation -> {
backendPassword.set(invocation.getArgument(6, String.class));
return null;
}).when(runtime).changeMasterPassword(any(), any(), any(), any(), any(), any(), any());
doAnswer(invocation -> {
backendPassword.set(invocation.getArgument(5, String.class));
return null;
}).when(runtime).restoreMasterPassword(any(), any(), any(), any(), any(), any());
AwsException failure = new AwsException("InvalidRequestException", "Secret has replicas", 400);
doThrow(failure).when(secrets).deleteSecret(SECRET_ARN, null, true, REGION);
assertSame(failure, assertThrows(AwsException.class, () -> service.restoreNamespaceUpdate(snapshot, REGION)));
assertEquals(GENERATED_PASSWORD, backendPassword.get());
assertSame(managed, service.getNamespace(NAME, REGION));
assertEquals(SECRET_ARN, managed.getAdminPasswordSecretArn());
assertEquals(managed.getAdminUserPassword(), backendPassword.get());
doReturn(null).when(secrets).deleteSecret(SECRET_ARN, null, true, REGION);
service.restoreNamespaceUpdate(snapshot, REGION);
assertEquals(ORIGINAL_PASSWORD, backendPassword.get());
assertEquals(ORIGINAL_PASSWORD, service.getNamespace(NAME, REGION).getAdminUserPassword());
assertNull(service.getNamespace(NAME, REGION).getAdminPasswordSecretArn());
}
@Test
void failedCredentialRestorePutsBackLiveDatabaseContents() throws Exception {
createUnmanaged();
RedshiftServerlessSnapshot snapshot = service.createSnapshot("failed-restore", NAME, null, null, REGION);
Path dump = tempDir.resolve("redshift-serverless-dumps").resolve(ACCOUNT).resolve(REGION)
.resolve("failed-restore.sql");
Files.createDirectories(dump.getParent());
Files.writeString(dump, "snapshot-data");
snapshot.setSqlDump(dump.toString());
attachWorkgroup();
Namespace previous = update(null, null, true);
AtomicReference<String> contents = new AtomicReference<>("live-data");
RedshiftContainerManager containers = mock(RedshiftContainerManager.class);
doAnswer(invocation -> {
Files.writeString(invocation.getArgument(4, Path.class), contents.get());
return null;
}).when(containers).takeSnapshot(any(), any(), any(), any(), any(), eq(true));
doAnswer(invocation -> {
contents.set("");
return null;
}).when(containers).resetUserSchemas(any(), any(), any(), any());
doAnswer(invocation -> {
contents.set(Files.readString(invocation.getArgument(4, Path.class)));
return null;
}).when(containers).restoreSnapshot(any(), any(), any(), any(), any(), eq(true));
RedshiftServerlessRuntime realRuntime = new RedshiftServerlessRuntime(containers,
mock(RedshiftProxyManager.class), mock(RedshiftCredentialBroker.class));
service = new RedshiftServerlessService(storageFactory, regions, endpoints, realRuntime, config,
new RedshiftServerlessAdminSecrets(secrets, mapper));
AwsException failure = new AwsException("InvalidRequestException", "Secret has replicas", 400);
doThrow(failure).when(secrets).deleteSecret(SECRET_ARN, null, true, REGION);
assertSame(failure, assertThrows(AwsException.class,
() -> service.restoreFromSnapshot(NAME, WORKGROUP, "failed-restore", null, REGION)));
assertEquals("live-data", contents.get());
assertSame(previous, service.getNamespace(NAME, REGION));
assertEquals(GENERATED_PASSWORD, service.getNamespace(NAME, REGION).getAdminUserPassword());
}
@Test
void restoreWithoutManagedCredentialsRestoresSnapshotPasswordAndRemovesManagedSecret() {
createUnmanaged();
service.createSnapshot("managed-restore-snap", NAME, null, null, REGION);
attachWorkgroup();
update(null, null, true);
clearInvocations(secrets, runtime);
Namespace restored = service.restoreFromSnapshot(NAME, WORKGROUP, "managed-restore-snap", null, REGION)
.namespace();
assertEquals(ORIGINAL_PASSWORD, restored.getAdminUserPassword());
assertNull(restored.getAdminPasswordSecretArn());
verify(runtime).changeMasterPassword(ACCOUNT, REGION, WORKGROUP, "admin", "analytics",
GENERATED_PASSWORD, ORIGINAL_PASSWORD);
verify(secrets).deleteSecret(SECRET_ARN, null, true, REGION);
}
@Test
void restoreWithManagedCredentialsRefreshesPasswordAndExistingSecret() throws Exception {
when(runtime.generatePassword()).thenReturn(GENERATED_PASSWORD, "Restored456!");
createManaged();
service.createSnapshot("refresh-managed-snap", NAME, null, null, REGION);
attachWorkgroup();
clearInvocations(secrets, runtime);
Namespace restored = service.restoreFromSnapshot(NAME, WORKGROUP, "refresh-managed-snap", null,
true, SECRET_KEY, REGION).namespace();
assertEquals("Restored456!", restored.getAdminUserPassword());
assertEquals(SECRET_ARN, restored.getAdminPasswordSecretArn());
verify(runtime).changeMasterPassword(ACCOUNT, REGION, WORKGROUP, "admin", "analytics",
GENERATED_PASSWORD, "Restored456!");
ArgumentCaptor<String> secretValue = ArgumentCaptor.forClass(String.class);
verify(secrets).putSecretValue(eq(SECRET_ARN), secretValue.capture(), isNull(), isNull(), eq(REGION), any());
assertEquals("Restored456!", mapper.readTree(secretValue.getValue()).path("password").asText());
}
@Test
void restoreFromSnapshotWithoutStoredPasswordKeepsCurrentCredentials() {
createUnmanaged();
service.createSnapshot("legacy-snap", NAME, null, null, REGION).setAdminUserPassword(null);
service.updateNamespace(NAME, null, "Changed123!", null, null, null, null, REGION);
attachWorkgroup();
Namespace restored = service.restoreFromSnapshot(NAME, WORKGROUP, "legacy-snap", null, REGION).namespace();
assertEquals("Changed123!", restored.getAdminUserPassword());
}
private Namespace createManaged() {
return service.createNamespace(NAME, "admin", null, "analytics", null, null, List.of(), List.of(), Map.of(),
true, SECRET_KEY, REGION);
@@ -256,6 +256,10 @@ class RedshiftServerlessIntegrationTest {
@Test
void snapshotLifecycleIsVisibleThroughSeparateReads() {
doAnswer(invocation -> {
invocation.getArgument(6, Runnable.class).run();
return null;
}).when(runtime).restoreSnapshot(any(), any(), any(), any(), any(), any(), any());
doAnswer(invocation -> {
Files.writeString(invocation.getArgument(5, Path.class), "-- dump");
return null;
@@ -330,10 +334,11 @@ class RedshiftServerlessIntegrationTest {
.body("snapshots", hasSize(0));
call("RestoreFromSnapshot", "{\"namespaceName\":\"snap-life-ns\",\"workgroupName\":\"snap-life-wg\","
+ "\"snapshotArn\":\"" + snapshotArn + "\"}")
+ "\"snapshotArn\":\"" + snapshotArn + "\",\"manageAdminPassword\":true}")
.statusCode(200)
.body("snapshotName", equalTo("snap-life"))
.body("namespace.namespaceName", equalTo("snap-life-ns"))
.body("namespace.adminPasswordSecretArn", notNullValue())
.body("namespace.status", equalTo("AVAILABLE"))
.body("ownerAccount", matchesPattern("\\d{12}"));
call("RestoreFromSnapshot", "{\"workgroupName\":\"snap-life-wg\",\"snapshotName\":\"snap-life\"}")
@@ -50,6 +50,27 @@ class RedshiftServerlessJsonHandlerTest {
assertTrue(response.path("namespace").path("adminPasswordSecretArn").isTextual(), response.toString());
}
@Test
void restoreFromSnapshotEnablesManagedCredentialsWhenRequested() {
body(handler.handle("CreateNamespace", parse(
"{\"namespaceName\":\"restore-managed-ns\",\"adminUsername\":\"admin\","
+ "\"adminUserPassword\":\"Initial123\"}"), REGION));
body(handler.handle("CreateSnapshot", parse(
"{\"snapshotName\":\"restore-managed-snap\",\"namespaceName\":\"restore-managed-ns\"}"), REGION));
body(handler.handle("CreateWorkgroup", parse(
"{\"workgroupName\":\"restore-managed-wg\",\"namespaceName\":\"restore-managed-ns\"}"), REGION));
JsonNode restored = body(handler.handle("RestoreFromSnapshot", parse(
"{\"namespaceName\":\"restore-managed-ns\",\"workgroupName\":\"restore-managed-wg\","
+ "\"snapshotName\":\"restore-managed-snap\",\"manageAdminPassword\":true,"
+ "\"adminPasswordSecretKmsKeyId\":\"arn:aws:kms:us-east-1:123456789012:key/managed\"}"),
REGION));
assertTrue(restored.path("namespace").path("adminPasswordSecretArn").isTextual(), restored.toString());
assertEquals("arn:aws:kms:us-east-1:123456789012:key/managed",
restored.path("namespace").path("adminPasswordSecretKmsKeyId").textValue());
}
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "123456789012";
@@ -12,17 +12,22 @@ import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
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.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -108,6 +113,30 @@ class RedshiftServerlessRuntimeTest {
any(Path.class), eq(true));
}
@Test
void credentialFailureKeepsSafetyDumpUntilDataIsRestored() {
Path dump = Path.of("/tmp/dump.sql");
AtomicReference<Path> safety = new AtomicReference<>();
doAnswer(invocation -> {
safety.set(invocation.getArgument(4, Path.class));
return null;
}).when(containers).takeSnapshot(any(), any(), any(), any(), any(), eq(true));
AwsException failure = new AwsException("InvalidRequestException", "Secret has replicas", 400);
assertSame(failure, assertThrows(AwsException.class, () -> runtime.restoreSnapshot(
ACCOUNT, REGION, "my-wg", "root", "analytics", dump, () -> {
assertTrue(Files.exists(safety.get()));
throw failure;
})));
InOrder order = inOrder(containers);
order.verify(containers).resetUserSchemas(ACCOUNT, BACKEND_ID, "root", "analytics");
order.verify(containers).restoreSnapshot(ACCOUNT, BACKEND_ID, "root", "analytics", dump, true);
order.verify(containers).resetUserSchemas(ACCOUNT, BACKEND_ID, "root", "analytics");
order.verify(containers).restoreSnapshot(ACCOUNT, BACKEND_ID, "root", "analytics", safety.get(), true);
assertFalse(Files.exists(safety.get()));
}
@Test
void failedAdoptedProxyUsesRecoveryRollback() {
when(containers.adoptOrStart(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics", "serverless")).thenReturn(handle());
@@ -90,6 +90,10 @@ class RedshiftServerlessServiceTest {
endpoints = mock(RedshiftServerlessEndpoints.class);
when(endpoints.allocate()).thenAnswer(invocation -> new Endpoint("localhost", nextPort++));
runtime = mock(RedshiftServerlessRuntime.class);
doAnswer(invocation -> {
invocation.getArgument(6, Runnable.class).run();
return null;
}).when(runtime).restoreSnapshot(any(), any(), any(), any(), any(), any(), any());
when(runtime.generatePassword()).thenReturn("Generated123");
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
@@ -925,7 +929,7 @@ class RedshiftServerlessServiceTest {
assertTrue(Files.exists(Path.of(snapshot.getSqlDump())));
service.restoreFromSnapshot("dump-ns", "dump-wg", "dump-snap", null, REGION);
verify(runtime).restoreSnapshot(eq(ACCOUNT_ID), eq(REGION), eq("dump-wg"), any(), eq("dev"),
eq(Path.of(snapshot.getSqlDump())));
eq(Path.of(snapshot.getSqlDump())), any(Runnable.class));
service.deleteSnapshot("dump-snap", REGION);
assertFalse(Files.exists(Path.of(snapshot.getSqlDump())));
@@ -945,7 +949,7 @@ class RedshiftServerlessServiceTest {
AwsException missing = assertThrows(AwsException.class,
() -> service.restoreFromSnapshot("gone-ns", "gone-wg", "gone-snap", null, REGION));
assertEquals("InternalServerException", missing.getErrorCode());
verify(runtime, never()).restoreSnapshot(any(), any(), any(), any(), any(), any());
verify(runtime, never()).restoreSnapshot(any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -962,7 +966,7 @@ class RedshiftServerlessServiceTest {
assertNull(snapshot.getSqlDump());
verify(runtime, never()).takeSnapshot(any(), any(), any(), any(), any(), any());
verify(runtime, never()).restoreSnapshot(any(), any(), any(), any(), any(), any());
verify(runtime, never()).restoreSnapshot(any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -0,0 +1,197 @@
package io.github.hectorvent.floci.services.secretsmanager;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SecretsManagerManagedSecretRestoreTest {
private static final String REGION = "us-east-1";
private static final String NAME = "redshift-serverless/namespace-id";
private final SecretsManagerService service = new SecretsManagerService(new InMemoryStorage<>(), 30);
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
@ParameterizedTest
@CsvSource({"true,000000000000", "false,000000000000", "true,111122223333", "false,111122223333"})
void createAndRollbackCannotOverwriteEachOther(boolean restoreFirst, String accountId) throws Exception {
ParkingStorage storage = new ParkingStorage();
AccountAwareStorageBackend<Secret> accountStore = new AccountAwareStorageBackend<>(storage, null, accountId);
SecretsManagerService concurrentService = new SecretsManagerService(accountStore, 30,
new RegionResolver(REGION, accountId), null, mapper);
Secret original = concurrentService.createSecret(NAME, "original", null, null, null, null, "redshift", REGION);
Secret snapshot = mapper.convertValue(original, Secret.class);
concurrentService.deleteSecret(original.getArn(), null, true, REGION);
AtomicReference<Secret> replacement = new AtomicReference<>();
Runnable create = () -> {
Secret created = concurrentService.createSecret(NAME, "replacement-v1", null, null, null, null, REGION);
concurrentService.putSecretValue(created.getArn(), "replacement-v2", null, null, REGION,
List.of("AWSCURRENT", "custom-stage"));
replacement.set(created);
};
Runnable restore = () -> concurrentService.restoreManagedSecret(snapshot, REGION);
storage.parkNextWrite.set(true);
Watched winner = new Watched(restoreFirst ? restore : create);
Watched loser = new Watched(() -> {
AwsException conflict = assertThrows(AwsException.class, restoreFirst ? create::run : restore::run);
assertEquals("ResourceExistsException", conflict.getErrorCode());
});
winner.thread.start();
try {
assertTrue(storage.entered.await(5, TimeUnit.SECONDS));
loser.thread.start();
assertTrue(loser.awaitBlocked(), "The competing operation must wait for the name's pending write");
} finally {
storage.released.countDown();
winner.awaitSuccess();
loser.awaitSuccess();
}
Secret expected = restoreFirst ? snapshot : replacement.get();
assertEquals(mapper.valueToTree(expected), mapper.valueToTree(concurrentService.describeSecret(NAME, REGION)));
}
@Test
void rollbackRefusesAReusedNameAndPreservesTheReplacementSecret() {
Secret original = service.createSecret(NAME, "original", null, null, null, null,
"redshift-serverless", REGION);
Secret snapshot = mapper.convertValue(original, Secret.class);
service.deleteSecret(original.getArn(), null, true, REGION);
Secret replacement = service.createSecret(NAME, "replacement-v1", null, null, null, null,
"redshift-serverless", REGION);
service.putSecretValue(replacement.getArn(), "replacement-v2", null, null, REGION,
List.of("AWSCURRENT", "custom-stage"));
Secret replacementBefore = mapper.convertValue(replacement, Secret.class);
assertNotEquals(snapshot.getArn(), replacement.getArn());
AwsException conflict = assertThrows(AwsException.class,
() -> service.restoreManagedSecret(snapshot, REGION));
assertEquals("ResourceExistsException", conflict.getErrorCode());
assertEquals(mapper.valueToTree(replacementBefore),
mapper.valueToTree(service.describeSecret(NAME, REGION)));
}
@Test
void rollbackChecksTheAccountNamedInTheSnapshotArn() {
AccountAwareStorageBackend<Secret> store = AccountAwareStorageBackend.inMemory("000000000000");
SecretsManagerService accountService = new SecretsManagerService(store, 30);
Secret snapshot = accountService.createSecret(NAME, "original", null, null, null, null,
"redshift", REGION);
Secret replacement = mapper.convertValue(snapshot, Secret.class);
replacement.setArn("arn:aws:secretsmanager:us-east-1:111122223333:secret:" + NAME + "-AbCdEf");
store.putForAccount("111122223333", REGION + "::" + NAME, replacement);
Secret foreignSnapshot = mapper.convertValue(snapshot, Secret.class);
foreignSnapshot.setArn("arn:aws:secretsmanager:us-east-1:111122223333:secret:" + NAME + "-GhIjKl");
AwsException conflict = assertThrows(AwsException.class,
() -> accountService.restoreManagedSecret(foreignSnapshot, REGION));
assertEquals("ResourceExistsException", conflict.getErrorCode());
assertEquals(replacement.getArn(), store.getForAccount("111122223333", REGION + "::" + NAME)
.orElseThrow().getArn());
assertEquals(snapshot.getArn(), accountService.describeSecret(NAME, REGION).getArn());
}
@Test
void rollbackRestoresADeletedSecretWithItsOriginalArnAndVersions() {
Secret original = service.createSecret(NAME, "original-v1", null, null, null, null,
"redshift-serverless", REGION);
service.putSecretValue(original.getArn(), "original-v2", null, null, REGION, null);
Secret snapshot = mapper.convertValue(original, Secret.class);
service.deleteSecret(original.getArn(), null, true, REGION);
service.restoreManagedSecret(snapshot, REGION);
assertEquals(mapper.valueToTree(snapshot), mapper.valueToTree(service.describeSecret(NAME, REGION)));
}
@Test
void rollbackRestoresTheSnapshotWhenTheCurrentArnMatches() {
Secret original = service.createSecret(NAME, "original", null, null, null, null,
"redshift-serverless", REGION);
Secret snapshot = mapper.convertValue(original, Secret.class);
SecretVersion changed = service.putSecretValue(original.getArn(), "changed", null, null, REGION, null);
assertNotEquals(snapshot.getCurrentVersionId(), changed.getVersionId());
service.restoreManagedSecret(snapshot, REGION);
assertEquals(mapper.valueToTree(snapshot), mapper.valueToTree(service.describeSecret(NAME, REGION)));
}
private static final class ParkingStorage extends InMemoryStorage<String, Secret> {
private final AtomicBoolean parkNextWrite = new AtomicBoolean();
private final CountDownLatch entered = new CountDownLatch(1);
private final CountDownLatch released = new CountDownLatch(1);
@Override
public void put(String key, Secret value) {
if (parkNextWrite.compareAndSet(true, false)) {
entered.countDown();
try {
assertTrue(released.await(10, TimeUnit.SECONDS), "Pending write was not released");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError(e);
}
}
super.put(key, value);
}
}
private static final class Watched {
private final Thread thread;
private final AtomicReference<Throwable> failure = new AtomicReference<>();
Watched(Runnable action) {
thread = new Thread(() -> {
try {
action.run();
} catch (Throwable t) {
failure.set(t);
}
});
thread.setDaemon(true);
}
boolean awaitBlocked() throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime() < deadline) {
if (thread.getState() == Thread.State.BLOCKED) {
return true;
}
if (!thread.isAlive()) {
return false;
}
Thread.sleep(5);
}
return false;
}
void awaitSuccess() throws InterruptedException {
thread.join(TimeUnit.SECONDS.toMillis(5));
assertTrue(!thread.isAlive(), "Secret operation did not finish");
assertNull(failure.get(), () -> "Secret operation failed: " + failure.get());
}
}
}