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

@@ -34,6 +34,10 @@ public final class CfnRollback {
*/
public static final String UPDATE_ROLLBACK_FAILURE_ATTR = "__FlociUpdateRollbackFailure";
/** The namespace, credentials, secret and attributes overwritten by a Serverless namespace update. */
public static final String REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR =
"__FlociRedshiftServerlessNamespaceUpdateSnapshot";
/**
* Holds the configuration a pipe carried before the update in flight mutated it, so a failed
* stack update can put it back. Written by {@code PipesCfnProvisioner} before its first
@@ -4,9 +4,11 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
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.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;
@@ -21,6 +23,8 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback.REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR;
/**
* Provisions {@code AWS::RedshiftServerless::Namespace} and {@code AWS::RedshiftServerless::Workgroup}.
* Both types use their name as the physical id, which is what {@code Ref} returns.
@@ -35,7 +39,7 @@ public class RedshiftServerlessCfnProvisioner implements CfnResourceProvisioner
private static final Logger LOG = Logger.getLogger(RedshiftServerlessCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();
private static final String NAMESPACE = "AWS::RedshiftServerless::Namespace";
private static final String WORKGROUP = "AWS::RedshiftServerless::Workgroup";
private static final int NAME_MAX_LENGTH = 64;
@@ -90,16 +94,40 @@ public class RedshiftServerlessCfnProvisioner implements CfnResourceProvisioner
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
if (resource.getAttributes().containsKey(REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR)
&& !ReplacementCleanup.hasReplacement(resource)) {
return new UpdateCleanupResult(true, true, null, 0, null);
}
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
}
@Override
public boolean retainsFailedUpdateState(StackResource resource) {
return resource.getAttributes().containsKey(REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
String raw = resource.getAttributes().get(REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR);
if (raw != null) {
try {
JsonNode snapshot = MAPPER.readTree(raw);
service.restoreNamespaceUpdate(MAPPER.treeToValue(snapshot.path("state"), NamespaceUpdateSnapshot.class),
snapshot.path("region").asText());
resource.getAttributes().clear();
snapshot.path("attributes").fields().forEachRemaining(entry ->
resource.getAttributes().put(entry.getKey(), entry.getValue().asText()));
return true;
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the Redshift Serverless namespace update snapshot", e);
}
}
return ReplacementCleanup.rollback(resource, this::delete);
}
@@ -108,6 +136,10 @@ public class RedshiftServerlessCfnProvisioner implements CfnResourceProvisioner
r.getLogicalId(), NAME_MAX_LENGTH, true);
String adminUsername = ctx.resolveOptional(props, "AdminUsername");
String adminUserPassword = ctx.resolveOptional(props, "AdminUserPassword");
String manageAdminPasswordProperty = ctx.resolveOptional(props, "ManageAdminPassword");
Boolean manageAdminPassword = manageAdminPasswordProperty == null
? null : Boolean.parseBoolean(manageAdminPasswordProperty);
String adminPasswordSecretKmsKeyId = ctx.resolveOptional(props, "AdminPasswordSecretKmsKeyId");
String kmsKeyId = ctx.resolveOptional(props, "KmsKeyId");
String defaultIamRoleArn = ctx.resolveOptional(props, "DefaultIamRoleArn");
List<String> iamRoles = ctx.resolveStringList(props, "IamRoles");
@@ -124,13 +156,21 @@ public class RedshiftServerlessCfnProvisioner implements CfnResourceProvisioner
+ "remove the namespace from the template and add it back",
400);
}
if (r.getAttributes().containsKey(REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR)) {
throw new AwsException("ConflictException", "Namespace update rollback is still pending.", 400);
}
ObjectNode snapshot = MAPPER.createObjectNode().put("region", ctx.region());
snapshot.set("attributes", MAPPER.valueToTree(r.getAttributes()));
snapshot.set("state", MAPPER.valueToTree(service.snapshotNamespaceUpdate(name, ctx.region())));
r.getAttributes().put(REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
namespace = service.reconcileNamespace(name, adminUsername, adminUserPassword, kmsKeyId,
defaultIamRoleArn, iamRoles, logExports, ctx.region());
defaultIamRoleArn, iamRoles, logExports, Boolean.TRUE.equals(manageAdminPassword),
adminPasswordSecretKmsKeyId, ctx.region());
reconcileTags(namespace.getNamespaceArn(), tags, ctx);
} else {
namespace = service.createNamespace(name, adminUsername, adminUserPassword,
ctx.resolveOptional(props, "DbName"), kmsKeyId, defaultIamRoleArn, iamRoles, logExports, tags,
ctx.region());
ctx.resolveOptional(props, "DbName"), kmsKeyId, defaultIamRoleArn, iamRoles, logExports,
tags, manageAdminPassword, adminPasswordSecretKmsKeyId, ctx.region());
}
r.setPhysicalId(name);
@@ -50,6 +50,17 @@ public class RedshiftServerlessAdminSecrets {
}
}
Secret snapshot(Namespace namespace, String region) {
if (namespace.getAdminPasswordSecretArn() == null) {
return null;
}
return mapper.convertValue(secrets.describeSecret(namespace.getAdminPasswordSecretArn(), region), Secret.class);
}
void restore(Secret snapshot, String region) {
secrets.restoreManagedSecret(mapper.convertValue(snapshot, Secret.class), region);
}
private String value(Namespace namespace) {
return mapper.createObjectNode().put("engine", "redshift")
.put("username", namespace.getAdminUsername())
@@ -283,7 +283,9 @@ public class RedshiftServerlessJsonHandler {
private Response handleRestoreFromSnapshot(JsonNode request, String region) {
RedshiftServerlessService.RestoreResult result = service.restoreFromSnapshot(
ServerlessSupport.text(request, "namespaceName"), ServerlessSupport.text(request, "workgroupName"),
snapshotNameOf(request, region), ServerlessSupport.text(request, "ownerAccount"), region);
snapshotNameOf(request, region), ServerlessSupport.text(request, "ownerAccount"),
ServerlessSupport.bool(request, "manageAdminPassword"),
ServerlessSupport.text(request, "adminPasswordSecretKmsKeyId"), region);
ObjectNode response = objectMapper.createObjectNode();
response.set("namespace", namespaceNode(result.namespace()));
response.put("ownerAccount", result.snapshot().getOwnerAccount());
@@ -99,6 +99,12 @@ public class RedshiftServerlessRuntime {
*/
public void restoreSnapshot(String accountId, String region, String workgroupName, String masterUsername,
String dbName, Path dumpFile) {
restoreSnapshot(accountId, region, workgroupName, masterUsername, dbName, dumpFile, () -> { });
}
/** Keeps the safety dump until the namespace's credentials and metadata have also committed. */
public void restoreSnapshot(String accountId, String region, String workgroupName, String masterUsername,
String dbName, Path dumpFile, Runnable afterRestore) {
String backendId = backendId(region, workgroupName);
Path safety;
try {
@@ -112,6 +118,7 @@ public class RedshiftServerlessRuntime {
try {
containerManager.resetUserSchemas(accountId, backendId, masterUsername, dbName);
containerManager.restoreSnapshot(accountId, backendId, masterUsername, dbName, dumpFile, true);
afterRestore.run();
} catch (RuntimeException e) {
rollBackRestore(accountId, backendId, masterUsername, dbName, safety, e);
throw e;
@@ -15,7 +15,9 @@ import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.redshiftserverless.model.PricePerformanceTarget;
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import io.github.hectorvent.floci.services.redshiftserverless.model.Workgroup;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.quarkus.runtime.StartupEvent;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
@@ -300,7 +302,7 @@ public class RedshiftServerlessService implements Resettable {
String defaultIamRoleArn, List<String> iamRoles,
List<String> logExports, String region) {
return applyNamespaceUpdate(namespaceName, adminUsername, adminUserPassword, kmsKeyId,
defaultIamRoleArn, iamRoles, logExports, null, null, region, false);
defaultIamRoleArn, iamRoles, logExports, null, null, region, false, false);
}
public synchronized Namespace updateNamespace(String namespaceName, String adminUsername,
@@ -309,7 +311,8 @@ public class RedshiftServerlessService implements Resettable {
List<String> logExports, Boolean manageAdminPassword,
String adminPasswordSecretKmsKeyId, String region) {
return applyNamespaceUpdate(namespaceName, adminUsername, adminUserPassword, kmsKeyId,
defaultIamRoleArn, iamRoles, logExports, manageAdminPassword, adminPasswordSecretKmsKeyId, region, false);
defaultIamRoleArn, iamRoles, logExports, manageAdminPassword, adminPasswordSecretKmsKeyId, region, false,
false);
}
/**
@@ -322,7 +325,17 @@ public class RedshiftServerlessService implements Resettable {
String defaultIamRoleArn, List<String> iamRoles,
List<String> logExports, String region) {
return applyNamespaceUpdate(namespaceName, adminUsername, adminUserPassword, kmsKeyId,
defaultIamRoleArn, iamRoles, logExports, null, null, region, true);
defaultIamRoleArn, iamRoles, logExports, null, null, region, true, false);
}
public synchronized Namespace reconcileNamespace(String namespaceName, String adminUsername,
String adminUserPassword, String kmsKeyId,
String defaultIamRoleArn, List<String> iamRoles,
List<String> logExports, Boolean manageAdminPassword,
String adminPasswordSecretKmsKeyId, String region) {
return applyNamespaceUpdate(namespaceName, adminUsername, adminUserPassword, kmsKeyId,
defaultIamRoleArn, iamRoles, logExports, manageAdminPassword, adminPasswordSecretKmsKeyId, region, true,
false);
}
/**
@@ -334,7 +347,8 @@ public class RedshiftServerlessService implements Resettable {
String adminUserPassword, String kmsKeyId,
String defaultIamRoleArn, List<String> iamRoles,
List<String> logExports, Boolean manageAdminPassword,
String adminPasswordSecretKmsKeyId, String region, boolean resetOmitted) {
String adminPasswordSecretKmsKeyId, String region, boolean resetOmitted,
boolean forceManagedPasswordRotation) {
validateManagedPassword(manageAdminPassword, adminUserPassword, adminPasswordSecretKmsKeyId);
String key = storageKey(region, namespaceName);
Namespace current = getNamespace(namespaceName, region);
@@ -366,7 +380,7 @@ public class RedshiftServerlessService implements Resettable {
}
if (managed) {
updated.setAdminUsername(adminUserOf(updated));
if (!wasManaged) {
if (!wasManaged || forceManagedPasswordRotation) {
updated.setAdminUserPassword(runtime.generatePassword());
}
if (adminPasswordSecretKmsKeyId != null) {
@@ -382,7 +396,8 @@ public class RedshiftServerlessService implements Resettable {
boolean rotated = !Objects.equals(current.getAdminUserPassword(), updated.getAdminUserPassword());
boolean secretUpdated = managed && wasManaged
&& (!Objects.equals(current.getAdminUsername(), updated.getAdminUsername())
|| !Objects.equals(current.getAdminPasswordSecretKmsKeyId(), updated.getAdminPasswordSecretKmsKeyId()));
|| !Objects.equals(current.getAdminPasswordSecretKmsKeyId(), updated.getAdminPasswordSecretKmsKeyId())
|| !Objects.equals(current.getAdminUserPassword(), updated.getAdminUserPassword()));
boolean backendChanged = false;
boolean storeAttempted = false;
try {
@@ -417,6 +432,42 @@ public class RedshiftServerlessService implements Resettable {
return updated;
}
@RegisterForReflection
public record NamespaceUpdateSnapshot(Namespace namespace, Secret secret) {}
public synchronized NamespaceUpdateSnapshot snapshotNamespaceUpdate(String namespaceName, String region) {
Namespace current = new Namespace(getNamespace(namespaceName, region));
Secret secret = current.getAdminPasswordSecretArn() == null ? null
: requireAdminSecrets().snapshot(current, region);
return new NamespaceUpdateSnapshot(current, secret);
}
/** Restores a CloudFormation update's credentials without generating a new password or secret ARN. */
public synchronized void restoreNamespaceUpdate(NamespaceUpdateSnapshot snapshot, String region) {
Namespace previous = new Namespace(snapshot.namespace());
Namespace current = getNamespace(previous.getNamespaceName(), region);
if (snapshot.secret() != null) {
requireAdminSecrets().restore(snapshot.secret(), region);
}
boolean passwordChanged = !Objects.equals(current.getAdminUserPassword(), previous.getAdminUserPassword());
if (passwordChanged) {
applyNewAdminPassword(current, previous.getAdminUserPassword(), region);
}
if (current.getAdminPasswordSecretArn() != null
&& !Objects.equals(current.getAdminPasswordSecretArn(), previous.getAdminPasswordSecretArn())) {
try {
requireAdminSecrets().delete(current, region);
} catch (RuntimeException failure) {
if (passwordChanged) {
compensate(() -> restoreAdminPassword(current, region), failure,
"restore current backend admin password after blocked rollback");
}
throw failure;
}
}
namespaces.put(storageKey(region, previous.getNamespaceName()), previous);
}
public synchronized Namespace deleteNamespace(String namespaceName, String region) {
Namespace current = getNamespace(namespaceName, region);
Namespace deleted = new Namespace(current);
@@ -467,6 +518,7 @@ public class RedshiftServerlessService implements Resettable {
snapshot.setStatus("AVAILABLE");
snapshot.setSnapshotCreateTime(Instant.now());
snapshot.setAdminUsername(adminUserOf(namespace));
snapshot.setAdminUserPassword(namespace.getAdminUserPassword());
snapshot.setKmsKeyId(namespace.getKmsKeyId());
snapshot.setRetentionPeriod(retentionDays);
snapshot.setTags(tags);
@@ -641,6 +693,14 @@ public class RedshiftServerlessService implements Resettable {
public synchronized RestoreResult restoreFromSnapshot(String namespaceName, String workgroupName,
String snapshotName, String ownerAccount,
String region) {
return restoreFromSnapshot(namespaceName, workgroupName, snapshotName, ownerAccount, null, null, region);
}
public synchronized RestoreResult restoreFromSnapshot(String namespaceName, String workgroupName,
String snapshotName, String ownerAccount,
Boolean manageAdminPassword,
String adminPasswordSecretKmsKeyId, String region) {
validateManagedPassword(manageAdminPassword, null, adminPasswordSecretKmsKeyId);
validateNamespaceName(namespaceName);
RedshiftServerlessSnapshot snapshot = getSnapshot(snapshotName, region);
if (ownerAccount != null && !ownerAccount.isBlank() && !ownerAccount.equals(snapshot.getOwnerAccount())) {
@@ -652,17 +712,34 @@ public class RedshiftServerlessService implements Resettable {
+ namespaceName + ".");
}
Namespace namespace = getNamespace(namespaceName, region);
Runnable restoreCredentials = () -> restoreSnapshotCredentials(namespace, snapshot, manageAdminPassword,
adminPasswordSecretKmsKeyId, region);
if (snapshot.getSqlDump() != null && hasLiveRuntime(workgroup)) {
Path dump = trustedDump(snapshot, region).filter(Files::exists).orElseThrow(() -> new AwsException(
"InternalServerException", "The data of snapshot " + snapshotName + " is no longer available.",
500));
runtime.restoreSnapshot(workgroups.accountId(), region, workgroupName, workgroup.getMasterUsername(),
namespace.getDbName(), dump);
namespace.getDbName(), dump, restoreCredentials);
} else {
restoreCredentials.run();
}
return new RestoreResult(getNamespace(namespaceName, region), snapshot);
}
private void restoreSnapshotCredentials(Namespace namespace, RedshiftServerlessSnapshot snapshot,
Boolean manageAdminPassword, String adminPasswordSecretKmsKeyId,
String region) {
if (Boolean.TRUE.equals(manageAdminPassword)) {
applyNamespaceUpdate(namespace.getNamespaceName(), null, null, null, null, null, null,
true, adminPasswordSecretKmsKeyId, region, false, true);
} else if (snapshot.getAdminUserPassword() != null) {
applyNamespaceUpdate(namespace.getNamespaceName(), snapshot.getAdminUsername(), snapshot.getAdminUserPassword(),
null, null, null, null, false, null, region, false, false);
} else {
Namespace restored = new Namespace(namespace);
restored.setStatus("AVAILABLE");
namespaces.put(storageKey(region, namespace.getNamespaceName()), restored);
}
Namespace restored = new Namespace(namespace);
restored.setStatus("AVAILABLE");
namespaces.put(storageKey(region, namespaceName), restored);
return new RestoreResult(restored, snapshot);
}
public record RestoreResult(Namespace namespace, RedshiftServerlessSnapshot snapshot) {}
@@ -27,6 +27,7 @@ public class RedshiftServerlessSnapshot {
private String status = "AVAILABLE";
private Instant snapshotCreateTime;
private String adminUsername;
private String adminUserPassword;
private String kmsKeyId;
private Integer retentionPeriod;
private String sqlDump;
@@ -46,6 +47,7 @@ public class RedshiftServerlessSnapshot {
this.status = other.status;
this.snapshotCreateTime = other.snapshotCreateTime;
this.adminUsername = other.adminUsername;
this.adminUserPassword = other.adminUserPassword;
this.kmsKeyId = other.kmsKeyId;
this.retentionPeriod = other.retentionPeriod;
this.sqlDump = other.sqlDump;
@@ -132,6 +134,14 @@ public class RedshiftServerlessSnapshot {
this.adminUsername = adminUsername;
}
public String getAdminUserPassword() {
return adminUserPassword;
}
public void setAdminUserPassword(String adminUserPassword) {
this.adminUserPassword = adminUserPassword;
}
public String getKmsKeyId() {
return kmsKeyId;
}
@@ -82,6 +82,9 @@ public class SecretsManagerService implements ResourceProvider {
// stripe only contend; no lock is held while a rotation Lambda runs.
private static final int ROTATION_LOCK_STRIPE_COUNT = 32;
private final Object[] rotationLockStripes = newLockStripes(ROTATION_LOCK_STRIPE_COUNT);
// Names outlive ARNs across deletion and recreation. Hold these after any ARN lock, never before it.
private static final int NAME_LOCK_STRIPE_COUNT = 32;
private final Object[] nameLockStripes = newLockStripes(NAME_LOCK_STRIPE_COUNT);
// Entries exist only while a service owner changes backend credentials outside the stripe.
private final Set<String> managedReleases = ConcurrentHashMap.newKeySet();
@@ -98,6 +101,11 @@ public class SecretsManagerService implements ResourceProvider {
return rotationLockStripes[index];
}
private Object nameLockFor(String accountId, String region, String name) {
int index = Math.floorMod(Objects.hash(accountId, region, name), nameLockStripes.length);
return nameLockStripes[index];
}
/** Names rotation threads for diagnostics. */
private static final class RotationThreadFactory implements ThreadFactory {
private final AtomicInteger nextId = new AtomicInteger(1);
@@ -184,6 +192,17 @@ public class SecretsManagerService implements ResourceProvider {
throwIfBothSecretValues(secretString, secretBinary);
validateKmsKey(kmsKeyId, region);
String accountId = store instanceof AccountAwareStorageBackend<Secret> aware
? aware.accountId() : regionResolver.getAccountId();
synchronized (nameLockFor(accountId, region, name)) {
return createSecretLocked(name, secretString, secretBinary, description, kmsKeyId, tags,
owningService, clientRequestToken, region);
}
}
private Secret createSecretLocked(String name, String secretString, String secretBinary,
String description, String kmsKeyId, List<Secret.Tag> tags,
String owningService, String clientRequestToken, String region) {
String storageKey = regionKey(region, name);
Secret existing = store.get(storageKey).orElse(null);
@@ -1188,6 +1207,26 @@ public class SecretsManagerService implements ResourceProvider {
}
}
/** Restores the exact service-owned secret, including its ARN and version labels, during rollback. */
public void restoreManagedSecret(Secret snapshot, String region) {
if (snapshot.getOwningService() == null) {
throw new IllegalArgumentException("A managed secret snapshot must have an owning service");
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(snapshot.getArn());
synchronized (lockFor(snapshot.getArn())) {
synchronized (nameLockFor(arn.accountId(), region, snapshot.getName())) {
throwIfManagedRelease(snapshot.getArn());
String currentArn = findArnByName(arn.accountId(), snapshot.getName(), region).orElse(null);
if (currentArn != null && !snapshot.getArn().equals(currentArn)) {
throw new AwsException("ResourceExistsException",
"Cannot restore managed secret " + snapshot.getArn()
+ " because another secret already uses the name " + snapshot.getName() + ".", 400);
}
persist(snapshot, region);
}
}
}
public Secret restoreSecret(String secretId, String region) {
Secret secret = resolveSecret(secretId, region);
String storageKey = regionKey(region, secret.getName());