feat(redshift-serverless): rotate the managed admin password of a namespace (#8393)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-15 09:32:38 -04:00
1 parent 2688ed5180
commit 0de78cafb1
10 files changed
+377 -38

No files matched your search

@@ -61,7 +61,7 @@ public class RedshiftServerlessAdminSecrets {
secrets.restoreManagedSecret(mapper.convertValue(snapshot, Secret.class), region);
}
private String value(Namespace namespace) {
String value(Namespace namespace) {
return mapper.createObjectNode().put("engine", "redshift")
.put("username", namespace.getAdminUsername())
.put("password", namespace.getAdminUserPassword())
@@ -161,9 +161,10 @@ public class RedshiftServerlessRuntime {
}
/**
* Applies a new master password to the PostgreSQL role and to the proxy's backend leg. When the
* proxy step fails the role is put back to {@code oldPassword}, so the backend never requires a
* password the stored namespace does not hold.
* Applies a master password to the PostgreSQL role and to the proxy's backend leg. When the
* proxy step fails the role is put back to {@code oldPassword} when one is given, so the backend
* never requires a password the stored namespace does not hold. Putting a previous password back
* is the same change with the two passwords the other way round.
*/
public void changeMasterPassword(String accountId, String region, String workgroupName,
String masterUsername, String dbName, String oldPassword,
@@ -184,18 +185,6 @@ public class RedshiftServerlessRuntime {
}
}
/**
* Puts the role and the proxy back to {@code password} after a rotation the caller could not
* store. The proxy is only reset once the role is, so a failed role restore never leaves the two
* disagreeing; the failure propagates instead.
*/
public void restoreMasterPassword(String accountId, String region, String workgroupName,
String masterUsername, String dbName, String password) {
String backendId = backendId(region, workgroupName);
containerManager.alterUserPassword(accountId, backendId, masterUsername, password, dbName);
proxyManager.updateMasterPassword(relayKey(accountId, backendId), password);
}
public TempCredential issueCredential(String accountId, String region, String workgroupName,
String dbUser, int durationSeconds) {
return credentialBroker.issue(accountId, backendId(region, workgroupName), dbUser, List.of(),
@@ -20,6 +20,7 @@ import io.floci.aws.services.redshiftserverless.model.Namespace;
import io.floci.aws.services.redshiftserverless.model.PricePerformanceTarget;
import io.floci.aws.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import io.floci.aws.services.redshiftserverless.model.Workgroup;
import io.floci.aws.services.secretsmanager.ManagedSecretRotator;
import io.floci.aws.services.secretsmanager.model.Secret;
import io.quarkus.runtime.StartupEvent;
import io.quarkus.runtime.annotations.RegisterForReflection;
@@ -46,6 +47,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
@@ -54,7 +56,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public class RedshiftServerlessService implements Resettable, StoredResourceArns {
public class RedshiftServerlessService implements Resettable, StoredResourceArns, ManagedSecretRotator {
private static final Logger LOG = Logger.getLogger(RedshiftServerlessService.class);
public static final String DEFAULT_DB_NAME = "dev";
@@ -122,6 +124,7 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns
private final RedshiftServerlessRuntime runtime;
private final EmulatorConfig config;
private final RedshiftServerlessAdminSecrets adminSecrets;
private final Map<String, String> rotationReservations = new ConcurrentHashMap<>();
/** Looked up lazily: the endpoint service is built on this one. */
@Inject
Instance<RedshiftServerlessEndpointAccessService> endpointAccess;
@@ -1495,8 +1498,86 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns
|| previous.getAdminUserPassword() == null) {
return;
}
runtime.restoreMasterPassword(workgroups.accountId(), region, attached.get().getWorkgroupName(),
attached.get().getMasterUsername(), previous.getDbName(), previous.getAdminUserPassword());
runtime.changeMasterPassword(workgroups.accountId(), region, attached.get().getWorkgroupName(),
attached.get().getMasterUsername(), previous.getDbName(), null, previous.getAdminUserPassword());
}
@Override
public boolean supports(String secretArn, String region) {
return managedNamespaceOf(secretArn, region).isPresent();
}
@Override
public synchronized void reserve(String secretArn, String region) {
AccountAwareStorageBackend.AccountEntry<Namespace> entry = requireManagedNamespace(secretArn, region);
requireLiveWorkgroup(entry, region);
if (rotationReservations.putIfAbsent(secretArn, entry.key()) != null) {
throw new AwsException("InvalidRequestException",
"The namespace's managed admin password is already being rotated.", 400);
}
}
@Override
public void release(String secretArn, String region) {
rotationReservations.remove(secretArn);
}
/**
* The backend role and proxy, the stored namespace and the secret value change as one rotation:
* the secret is written last by the caller, and a failure anywhere puts the backend and the
* namespace back. A namespace with no running workgroup has nothing to change the password of,
* so it is refused rather than reported as rotated. This runs on a rotation thread with no request,
* so every lookup names the account of the namespace instead of the request's.
*/
@Override
public synchronized void rotate(String secretArn, String region, ManagedSecretRotator.Rotation rotation) {
AccountAwareStorageBackend.AccountEntry<Namespace> entry = requireManagedNamespace(secretArn, region);
Workgroup workgroup = requireLiveWorkgroup(entry, region);
String accountId = entry.accountId();
Namespace current = entry.value();
Namespace rotated = new Namespace(current);
rotated.setAdminUserPassword(runtime.generatePassword());
rotation.commit(() -> {
runtime.changeMasterPassword(accountId, region, workgroup.getWorkgroupName(),
workgroup.getMasterUsername(), current.getDbName(), current.getAdminUserPassword(),
rotated.getAdminUserPassword());
namespaces.putForAccount(accountId, entry.key(), rotated);
return requireAdminSecrets().value(rotated);
}, () -> {
runtime.changeMasterPassword(accountId, region, workgroup.getWorkgroupName(),
workgroup.getMasterUsername(), current.getDbName(), rotated.getAdminUserPassword(),
current.getAdminUserPassword());
namespaces.putForAccount(accountId, entry.key(), current);
});
}
private Optional<AccountAwareStorageBackend.AccountEntry<Namespace>> managedNamespaceOf(String secretArn,
String region) {
if (!AwsArnUtils.isArn(secretArn) || !region.equals(AwsArnUtils.parse(secretArn).region())) {
return Optional.empty();
}
return namespaces.scanAllAccountEntries(key -> key.startsWith(region + "::")).stream()
.filter(entry -> secretArn.equals(entry.value().getAdminPasswordSecretArn()))
.findFirst();
}
private AccountAwareStorageBackend.AccountEntry<Namespace> requireManagedNamespace(String secretArn,
String region) {
return managedNamespaceOf(secretArn, region)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The Redshift Serverless namespace for this managed secret no longer exists.", 400));
}
private Workgroup requireLiveWorkgroup(AccountAwareStorageBackend.AccountEntry<Namespace> entry, String region) {
String namespaceName = entry.value().getNamespaceName();
return workgroups.scanAllAccountEntries(key -> key.startsWith(region + "::")).stream()
.filter(candidate -> entry.accountId().equals(candidate.accountId()))
.map(AccountAwareStorageBackend.AccountEntry::value)
.filter(workgroup -> namespaceName.equals(workgroup.getNamespaceName()))
.filter(workgroup -> "AVAILABLE".equals(workgroup.getStatus()) && hasLiveRuntime(workgroup))
.findFirst()
.orElseThrow(() -> new AwsException("InvalidRequestException",
"The namespace must have an available workgroup to rotate its admin password.", 400));
}
private static String blankToNull(String value) {
@@ -48,7 +48,9 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
@@ -1643,6 +1645,8 @@ public class SecretsManagerService implements ResourceProvider, StoredResourceAr
private void executeManagedRotation(String secretArn, String token, String region,
ManagedSecretRotator rotator) {
AtomicReference<String> pendingValue = new AtomicReference<>();
AtomicBoolean rollbackFailed = new AtomicBoolean();
try {
AtomicInteger committed = new AtomicInteger();
rotator.rotate(secretArn, region, new ManagedSecretRotator.Rotation() {
@@ -1650,6 +1654,7 @@ public class SecretsManagerService implements ResourceProvider, StoredResourceAr
public void commit(Supplier<String> changeBackend, Runnable rollbackBackend) {
try {
String newValue = changeBackend.get();
pendingValue.set(newValue);
synchronized (lockFor(secretArn)) {
Secret current = resolveSecret(secretArn, region);
putManagedRotationVersion(current, token, current.getCurrentVersionId(), newValue);
@@ -1659,7 +1664,13 @@ public class SecretsManagerService implements ResourceProvider, StoredResourceAr
}
committed.set(1);
} catch (RuntimeException e) {
rollbackBackend.run();
try {
rollbackBackend.run();
} catch (RuntimeException rollbackError) {
rollbackError.addSuppressed(e);
rollbackFailed.set(true);
throw rollbackError;
}
throw e;
}
}
@@ -1671,13 +1682,28 @@ public class SecretsManagerService implements ResourceProvider, StoredResourceAr
LOG.errorv(e, "Managed rotation failed for secret {0}", secretArn);
synchronized (lockFor(secretArn)) {
Secret current = resolveSecret(secretArn, region);
if (current.getVersions() != null) {
if (rollbackFailed.get() && pendingValue.get() != null) {
// Backend rollback failed after the backend password changed: keep AWSPENDING with the
// rotated value so the new credential is not lost while AWSCURRENT stays unchanged.
if (current.getVersions() == null) {
current.setVersions(new HashMap<>());
}
SecretVersion pending = current.getVersions().get(token);
if (pending == null) {
pending = new SecretVersion();
pending.setVersionId(token);
pending.setVersionStages(List.of("AWSPENDING"));
pending.setCreatedDate(Instant.now());
current.getVersions().put(token, pending);
}
pending.setSecretString(pendingValue.get());
persist(current, region);
} else if (current.getVersions() != null) {
SecretVersion pending = current.getVersions().remove(token);
if (pending != null) {
persist(current, region);
}
}
persist(current, region);
}
} finally {
clearManagedRotation(secretArn, token);