diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index ee0c2613bd..7c0f05070f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java index 89bc609caf..94db342b20 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java @@ -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} diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java index eb65d20961..9f5a542982 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java @@ -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 { diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java index 12a44ac3e7..75eb0f0ae3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java @@ -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) { diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 95a1514605..18264fe734 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -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", diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java index 170a312a66..24f8c12c1d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java @@ -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")); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java index 72704cb603..e55b3342ea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java @@ -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);