fix(rds): grant the MySQL/MariaDB master user RDS-master-equivalent privileges (#2679)

* fix(rds): grant the MySQL/MariaDB master user RDS-master-equivalent privileges

The stock mysql/mariadb images grant MYSQL_USER only ALL on MYSQL_DATABASE
plus USAGE, so a non-root master user cannot CREATE DATABASE, CREATE USER
or GRANT. Real RDS master users perform these routinely, and the terraform
and pulumi mysql providers run them right after connecting; against Floci
they failed with ERROR 1044.

After the DB container starts, exec a root GRANT ALL PRIVILEGES ON *.*
WITH GRANT OPTION for the master user, reusing the exec-with-retry
machinery the PostgreSQL rds_iam init already uses (extracted into a
shared execUntilSuccess). Real RDS withholds SUPER, FILE and SHUTDOWN
from its master grant list; the emulator grants ALL for simplicity,
mirroring how POSTGRES_USER is already a superuser. A root master is
skipped: the images create no separate user for it and root already
holds every privilege.

* fix(rds): deliver the master grant as a one-time init script and escape the username

Review follow-ups from #2679:

- Escape single quotes and backslashes in the GRANT statement. Floci does
  not enforce AWS's MasterUsername charset anywhere, so an unescaped name
  could break out of the string literal in SQL executed as root.
- Replace the post-start root exec with a /docker-entrypoint-initdb.d
  script installed between container create and start. The images run init
  scripts exactly once, against an empty data directory, as root, after
  creating the master user, so a reboot on a reused volume never re-runs
  the grant and never needs to re-authenticate as root. This removes the
  reboot-after-password-rotation failure: MYSQL_ROOT_PASSWORD only takes
  effect on first initialization, so the rotated password can never open
  a root session on a reused volume.
- The tar-and-copy shape follows CodeBuildRunner.copySourceToContainer.
This commit is contained in:
Matan Baruch authored and GitHub committed 2026-08-28 17:51:44 -04:00
1 parent be892864db
commit 6c96f47f73
2 files changed
+149 -3

No files matched your search

@@ -21,6 +21,8 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.model.Bind;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
@@ -54,6 +56,91 @@ class RdsContainerManagerTest {
assertTrue(sql.contains("CREATE ROLE rds_iam"));
}
@Test
void mysqlMasterGrantSqlGrantsGlobalPrivilegesWithGrantOption() {
String sql = RdsContainerManager.mysqlMasterGrantSql("admin");
assertTrue(sql.contains("GRANT ALL PRIVILEGES ON *.*"));
assertTrue(sql.contains("'admin'@'%'"));
assertTrue(sql.contains("WITH GRANT OPTION"));
}
@Test
void mysqlMasterGrantSqlEscapesQuotesAndBackslashes() {
// Floci does not enforce AWS's MasterUsername charset, so a quote must not be able to
// break out of the string literal in SQL executed as root.
assertEquals("GRANT ALL PRIVILEGES ON *.* TO 'we\\'ird\\\\'@'%' WITH GRANT OPTION;",
RdsContainerManager.mysqlMasterGrantSql("we'ird\\"));
}
@Test
void needsMasterGrantSkipsRootAndPostgres() {
assertTrue(RdsContainerManager.needsMasterGrant(DatabaseEngine.MYSQL, "admin"));
assertTrue(RdsContainerManager.needsMasterGrant(DatabaseEngine.MARIADB, "admin"));
assertFalse(RdsContainerManager.needsMasterGrant(DatabaseEngine.MYSQL, "root"));
assertFalse(RdsContainerManager.needsMasterGrant(DatabaseEngine.POSTGRES, "admin"));
assertFalse(RdsContainerManager.needsMasterGrant(DatabaseEngine.MYSQL, null));
}
@Test
void mysqlRootMasterStartDoesNotInstallAnInitScript() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
manager.start("db1", "vol1", DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
verify(lifecycleManager, never()).getDockerClient();
}
@Test
void mysqlNonRootMasterStartInstallsGrantInitScriptBeforeStart() throws Exception {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
DockerClient dockerClient = mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class);
when(dockerClient.copyArchiveToContainerCmd(any())).thenReturn(copyCmd);
when(copyCmd.withRemotePath(any())).thenReturn(copyCmd);
when(copyCmd.withTarInputStream(any())).thenReturn(copyCmd);
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
manager.start("db1", "vol1", DatabaseEngine.MYSQL, "mysql:8.0", "admin", "password", "db");
verify(copyCmd).withRemotePath("/docker-entrypoint-initdb.d");
var tarCaptor = org.mockito.ArgumentCaptor.forClass(java.io.InputStream.class);
verify(copyCmd).withTarInputStream(tarCaptor.capture());
try (var tar = new org.apache.commons.compress.archivers.tar.TarArchiveInputStream(tarCaptor.getValue())) {
var entry = tar.getNextEntry();
assertEquals("floci-master-grants.sql", entry.getName());
assertEquals(RdsContainerManager.mysqlMasterGrantSql("admin"),
new String(tar.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8));
}
// The script lands on the created container before it starts, so the entrypoint's
// one-time init phase is the thing that runs it.
var order = org.mockito.Mockito.inOrder(dockerClient, lifecycleManager);
order.verify(dockerClient).copyArchiveToContainerCmd("container-id");
order.verify(lifecycleManager).startCreated(org.mockito.ArgumentMatchers.eq("container-id"), any());
}
@Test
void postgres18UsesParentDataMount() {
assertEquals("/var/lib/postgresql",