fix(rds): propagate ModifyDBInstance master-password rotations to the backend and proxy (#2709)

* fix(rds): propagate ModifyDBInstance master-password rotations to the backend and proxy

Rotating the master password only updated Floci's stored state. The
backend DB container kept the original credential and the running auth
proxy kept validating the master scramble against the password it was
started with, so after a rotation no client could connect at all: the
old password failed the proxy's (rotated) validator and the new one
failed against the backend.

On rotation, while the old credential is still known:
- exec into the DB container and change the password there. MySQL and
  MariaDB run SET PASSWORD as the master user itself with the old
  password (changing your own password needs no privileges, and root's
  password is the creation-time one, unknown after earlier rotations).
  PostgreSQL runs ALTER ROLE over the trusted local socket.
- restart the auth proxy on the rotated credential, the same stop/start
  the reboot path uses.

Mock mode, cluster members and instances without a running container
are unaffected.

* fix(rds): swap the proxy password snapshot in place instead of restarting it

An immediate stop/start of the auth proxy races the listener rebind: closing
the server socket defers the port release while relay connections are still
draining, so the restart failed with EADDRINUSE and ModifyDBInstance threw
(caught by the sdk-test-java RdsJdbcCompatTest). Updating the snapshot on the
running proxy avoids the race entirely and keeps live connections open, which
is also what rotation should do.
This commit is contained in:
Matan Baruch authored and GitHub committed 2026-08-29 14:43:07 -04:00
1 parent 88bf0a2931
commit 09a05c2d77
7 files changed
+195 -1

No files matched your search

@@ -1078,7 +1078,20 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getEngineVersion(), effectiveRegion);
instance.setOptionGroupName(optionGroupName);
}
boolean passwordRotated = false;
if (newPassword != null && !newPassword.isBlank()) {
String oldPassword = instance.getMasterPassword();
boolean backendRunning = !config.services().rds().mock()
&& instance.getDbClusterIdentifier() == null && instance.getContainerId() != null;
passwordRotated = backendRunning && !newPassword.equals(oldPassword);
// Propagate the rotation into the running backend DB before overwriting the stored
// password — this is the last moment the old credential (which the backend still
// holds) is known. Without it every later connection fails: the proxy dials the
// backend with the rotated password against a database still holding the original.
if (passwordRotated) {
containerManager.rotateMasterPassword(id, instance.getContainerId(),
instance.getEngine(), instance.getMasterUsername(), oldPassword, newPassword);
}
instance.setMasterPassword(newPassword);
}
if (iamEnabled != null) {
@@ -1096,6 +1109,15 @@ public class RdsService implements Resettable, ResourceProvider {
}
effective.applyTo(instance);
putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
// The running auth proxy holds a password snapshot from start time, so swap it in place
// (a stop/start here races the listener rebind while relay connections are still open,
// and would drop live connections rotation shouldn't touch).
if (passwordRotated) {
proxyManager.updateMasterPassword(
rdsResourceRelayKey(instance.getDbInstanceArn(), id), instance.getMasterPassword());
}
LOG.infov("DB instance {0} modified", id);
return instance;
}
@@ -407,6 +407,52 @@ public class RdsContainerManager {
execUntilSuccess(containerName, containerId, cmd, "PostgreSQL IAM role");
}
/**
* Propagates a ModifyDBInstance master-password rotation into the running DB container, so
* the backend's stored credential matches what clients (and the auth proxy) use from now on.
* For MySQL/MariaDB this runs as the master user itself with the old password — changing your
* own password needs no extra privileges, and the container's root password is the
* creation-time one, not reliably known after earlier rotations. PostgreSQL's official image
* trusts local socket connections, so psql needs no password at all.
*/
public void rotateMasterPassword(String instanceId, String containerId, DatabaseEngine engine,
String masterUsername, String oldPassword, String newPassword) {
execUntilSuccess(instanceId, containerId,
passwordRotationCommand(engine, masterUsername, oldPassword, newPassword),
"master-password rotation");
}
static String[] passwordRotationCommand(DatabaseEngine engine, String masterUsername,
String oldPassword, String newPassword) {
if (engine == DatabaseEngine.POSTGRES) {
String effectiveUser = (masterUsername != null && !masterUsername.isBlank())
? masterUsername : "postgres";
return new String[]{"psql", "-v", "ON_ERROR_STOP=1", "-U", effectiveUser, "-d", "postgres",
"-c", postgresPasswordRotationSql(effectiveUser, newPassword)};
}
String effectiveUser = (masterUsername != null && !masterUsername.isBlank())
? masterUsername : "root";
// MariaDB images ≥10.4 (Floci's floor is 10.11) ship only the `mariadb` client binary.
String client = engine == DatabaseEngine.MARIADB ? "mariadb" : "mysql";
return new String[]{client, "-u" + effectiveUser, "-p" + oldPassword,
"-e", mysqlPasswordRotationSql(engine, newPassword)};
}
static String mysqlPasswordRotationSql(DatabaseEngine engine, String newPassword) {
String escaped = newPassword.replace("\\", "\\\\").replace("'", "\\'");
// MariaDB only accepts the PASSWORD() form; MySQL 8 only the plain literal.
return engine == DatabaseEngine.MARIADB
? "SET PASSWORD = PASSWORD('" + escaped + "');"
: "SET PASSWORD = '" + escaped + "';";
}
static String postgresPasswordRotationSql(String masterUsername, String newPassword) {
// Identifier quoted with doubled double-quotes, literal with doubled single-quotes.
String role = masterUsername.replace("\"", "\"\"");
String password = newPassword.replace("'", "''");
return "ALTER ROLE \"" + role + "\" WITH PASSWORD '" + password + "';";
}
/**
* The stock mysql/mariadb images grant {@code MYSQL_USER} only {@code ALL} on
* {@code MYSQL_DATABASE}, so a master user cannot {@code CREATE DATABASE}, {@code CREATE USER}
@@ -22,7 +22,7 @@ public class RdsAuthProxy {
private final String instanceId;
private final String backendHost;
private final String masterUsername;
private final String masterPassword;
private volatile String masterPassword;
private final String dbName;
private final DatabaseEngine engine;
private final RdsSigV4Validator sigV4;
@@ -60,6 +60,11 @@ public class RdsAuthProxy {
instanceId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
}
/** Swap the master-password snapshot after a rotation; new connections authenticate against it. */
public void updateMasterPassword(String newPassword) {
this.masterPassword = newPassword;
}
public void stop() {
running = false;
try {
@@ -73,6 +73,14 @@ public class RdsProxyManager {
}
}
public synchronized void updateMasterPassword(String instanceId, String newPassword) {
RdsAuthProxy proxy = proxies.get(instanceId);
if (proxy != null) {
proxy.updateMasterPassword(newPassword);
LOG.infov("Updated RDS proxy master password for instance {0}", instanceId);
}
}
public synchronized void stopProxy(String instanceId) {
RdsAuthProxy proxy = proxies.get(instanceId);
if (proxy != null) {
@@ -58,6 +58,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
@@ -738,6 +739,56 @@ class RdsServiceTest {
assertFalse(modified.isIamDatabaseAuthenticationEnabled());
}
@Test
void modifyDbInstancePasswordRotationPropagatesToBackendAndProxy() {
DbInstance instance = rdsService.createDbInstance("mydb", "mysql", "8.0",
"admin", "original-password", "dbname", "db.t3.micro",
20, false, null, null, null, null, false);
instance.setContainerId("container-1");
instance.setContainerHost("10.0.0.5");
instance.setContainerPort(3306);
DbInstance modified = rdsService.modifyDbInstance("mydb", "rotated-password", null, null);
assertEquals("rotated-password", modified.getMasterPassword());
// The backend learns the new credential while the old one is still known...
verify(containerManager).rotateMasterPassword("mydb", "container-1",
DatabaseEngine.MYSQL, "admin", "original-password", "rotated-password");
// ...and the running proxy's password snapshot is swapped in place, without a restart
// (a stop/start would race the listener rebind and drop live connections).
verify(proxyManager).updateMasterPassword(anyString(), eq("rotated-password"));
verify(proxyManager, never()).stopProxy(anyString());
}
@Test
void modifyDbInstanceSamePasswordDoesNotTouchBackendOrProxy() {
DbInstance instance = rdsService.createDbInstance("mydb", "mysql", "8.0",
"admin", "original-password", "dbname", "db.t3.micro",
20, false, null, null, null, null, false);
instance.setContainerId("container-1");
rdsService.modifyDbInstance("mydb", "original-password", null, null);
verify(containerManager, never()).rotateMasterPassword(
anyString(), anyString(), any(), anyString(), anyString(), anyString());
verify(proxyManager, never()).updateMasterPassword(anyString(), anyString());
}
@Test
void modifyDbInstancePasswordRotationSkipsBackendInMockMode() {
when(config.services().rds().mock()).thenReturn(true);
rdsService.createDbInstance("mydb", "mysql", "8.0",
"admin", "original-password", "dbname", "db.t3.micro",
20, false, null, null, null, null, false);
DbInstance modified = rdsService.modifyDbInstance("mydb", "rotated-password", null, null);
assertEquals("rotated-password", modified.getMasterPassword());
verify(containerManager, never()).rotateMasterPassword(
anyString(), anyString(), any(), anyString(), anyString(), anyString());
verify(proxyManager, never()).updateMasterPassword(anyString(), anyString());
}
@Test
void modifyDbInstanceCanToggleIamWithoutChangingPassword() {
rdsService.createDbInstance("mydb", "postgres", "13",
@@ -73,6 +73,36 @@ class RdsContainerManagerTest {
RdsContainerManager.mysqlMasterGrantSql("we'ird\\"));
}
@Test
void passwordRotationCommandRunsAsTheMasterUserWithTheOldPassword() {
String[] mysql = RdsContainerManager.passwordRotationCommand(
DatabaseEngine.MYSQL, "admin", "old-pass", "new-pass");
assertEquals("mysql", mysql[0]);
assertEquals("-uadmin", mysql[1]);
assertEquals("-pold-pass", mysql[2]);
assertEquals("SET PASSWORD = 'new-pass';", mysql[4]);
assertEquals("mariadb", RdsContainerManager.passwordRotationCommand(
DatabaseEngine.MARIADB, "admin", "old-pass", "new-pass")[0]);
// PostgreSQL: local socket connections are trusted, so no old password appears at all.
String[] postgres = RdsContainerManager.passwordRotationCommand(
DatabaseEngine.POSTGRES, "admin", "old-pass", "new-pass");
assertEquals("psql", postgres[0]);
assertEquals("ALTER ROLE \"admin\" WITH PASSWORD 'new-pass';", postgres[postgres.length - 1]);
}
@Test
void passwordRotationSqlUsesEngineSyntaxAndEscapes() {
assertEquals("SET PASSWORD = 'a\\'b';",
RdsContainerManager.mysqlPasswordRotationSql(DatabaseEngine.MYSQL, "a'b"));
// MariaDB only accepts the PASSWORD() form.
assertEquals("SET PASSWORD = PASSWORD('a\\'b');",
RdsContainerManager.mysqlPasswordRotationSql(DatabaseEngine.MARIADB, "a'b"));
assertEquals("ALTER ROLE \"we\"\"ird\" WITH PASSWORD 'a''b';",
RdsContainerManager.postgresPasswordRotationSql("we\"ird", "a'b"));
}
@Test
void needsMasterGrantSkipsRootAndPostgres() {
assertTrue(RdsContainerManager.needsMasterGrant(DatabaseEngine.MYSQL, "admin"));
@@ -10,6 +10,7 @@ import java.net.ServerSocket;
import java.util.concurrent.ConcurrentHashMap;
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.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -74,6 +75,31 @@ class RdsProxyManagerTest {
}
}
@Test
void updateMasterPasswordSwapsTheRunningProxySnapshotWithoutARestart() throws Exception {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
int proxyPort = availablePort();
try {
start(manager, "proxy", proxyPort);
manager.updateMasterPassword("proxy", "rotated");
assertEquals("rotated", masterPassword(registry(manager).get("proxy")));
assertPortUnavailable(proxyPort);
} finally {
manager.stopAll();
}
}
@Test
void updateMasterPasswordForUnknownInstanceIsANoOp() {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
assertDoesNotThrow(() -> manager.updateMasterPassword("missing", "rotated"));
}
@Test
void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException {
RdsProxyManager manager = new RdsProxyManager(
@@ -159,6 +185,12 @@ class RdsProxyManagerTest {
mock(RdsProxyTlsCertificates.class), (user, password) -> true);
}
private static String masterPassword(RdsAuthProxy proxy) throws Exception {
Field field = RdsAuthProxy.class.getDeclaredField("masterPassword");
field.setAccessible(true);
return (String) field.get(proxy);
}
private static void setServerSocket(RdsAuthProxy proxy, ServerSocket socket) throws Exception {
Field field = RdsAuthProxy.class.getDeclaredField("serverSocket");
field.setAccessible(true);