mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(rds): fix DBSubnetGroup shape, non-master auth pass-through, and volume lifecycle (#604)
* fix(rds): fix DBSubnetGroup shape, non-master auth pass-through, and volume lifecycle (#548, #503, #567) * fix(rds): fix wrong storage value and docs * fix(rds): fix master password check
This commit is contained in:
1 parent
c7987ad1de
commit
eeedfe09a2
17 files changed
+445
-63
No files matched your search
@@ -115,6 +115,7 @@ public interface EmulatorConfig {
|
||||
AppConfigStorageConfig appconfig();
|
||||
AppConfigDataStorageConfig appconfigdata();
|
||||
ElastiCacheStorageConfig elasticache();
|
||||
RdsStorageConfig rds();
|
||||
}
|
||||
|
||||
interface SsmStorageConfig {
|
||||
@@ -209,6 +210,10 @@ public interface EmulatorConfig {
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface RdsStorageConfig {
|
||||
Optional<String> mode();
|
||||
}
|
||||
|
||||
interface WalConfig {
|
||||
@WithDefault("30000")
|
||||
long compactionIntervalMs();
|
||||
|
||||
@@ -81,7 +81,8 @@ public class ResolvedServiceCatalog {
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
Set.of(), Set.of("elasticache"), Set.of(), Set.of()),
|
||||
descriptor("rds", "rds", config.services().rds().enabled(), true,
|
||||
null, null, 5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY,
|
||||
"rds", storageMode(config.storage().services().rds().mode(), config.storage().mode()),
|
||||
5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY,
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
Set.of(), Set.of("rds"), Set.of(), Set.of()),
|
||||
descriptor("events", "eventbridge", config.services().eventbridge().enabled(), true,
|
||||
|
||||
@@ -444,20 +444,7 @@ public class RdsQueryHandler {
|
||||
.elem("Status", "active")
|
||||
.end("VpcSecurityGroupMembership")
|
||||
.end("VpcSecurityGroups")
|
||||
.start("DBSubnetGroup")
|
||||
.elem("DBSubnetGroupName", "default")
|
||||
.elem("VpcId", "vpc-00000000")
|
||||
.elem("SubnetGroupStatus", "Complete")
|
||||
.start("Subnets")
|
||||
.start("member")
|
||||
.elem("SubnetIdentifier", "subnet-00000000")
|
||||
.start("SubnetAvailabilityZone")
|
||||
.elem("Name", config.defaultAvailabilityZone())
|
||||
.end("SubnetAvailabilityZone")
|
||||
.elem("SubnetStatus", "Active")
|
||||
.end("member")
|
||||
.end("Subnets")
|
||||
.end("DBSubnetGroup")
|
||||
.elem("DBSubnetGroup", "default")
|
||||
.elem("DbClusterResourceId", c.getDbClusterResourceId())
|
||||
.elem("DBClusterArn", c.getDbClusterArn())
|
||||
.start("DBClusterMembers");
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.rds;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle;
|
||||
@@ -41,17 +42,20 @@ public class RdsService {
|
||||
private final RdsProxyManager proxyManager;
|
||||
private final RegionResolver regionResolver;
|
||||
private final EmulatorConfig config;
|
||||
private final ServiceConfigAccess serviceConfigAccess;
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Inject
|
||||
public RdsService(RdsContainerManager containerManager,
|
||||
RdsProxyManager proxyManager,
|
||||
RegionResolver regionResolver,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config,
|
||||
ServiceConfigAccess serviceConfigAccess) {
|
||||
this.containerManager = containerManager;
|
||||
this.proxyManager = proxyManager;
|
||||
this.regionResolver = regionResolver;
|
||||
this.config = config;
|
||||
this.serviceConfigAccess = serviceConfigAccess;
|
||||
this.instances = new InMemoryStorage<>();
|
||||
this.clusters = new InMemoryStorage<>();
|
||||
this.parameterGroups = new InMemoryStorage<>();
|
||||
@@ -106,6 +110,9 @@ public class RdsService {
|
||||
instance.setContainerId(containerId);
|
||||
instance.setContainerHost(containerHost);
|
||||
instance.setContainerPort(containerPort);
|
||||
if (dbClusterIdentifier == null || dbClusterIdentifier.isBlank()) {
|
||||
instance.setDockerVolumeName(isInMemory() ? null : "floci-rds-" + id);
|
||||
}
|
||||
|
||||
String region = regionResolver.getDefaultRegion();
|
||||
instance.setDbiResourceId("db-" + java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 24).toUpperCase());
|
||||
@@ -211,10 +218,13 @@ public class RdsService {
|
||||
|
||||
String clusterId = instance.getDbClusterIdentifier();
|
||||
if (clusterId == null || clusterId.isBlank()) {
|
||||
// Standalone — stop its container
|
||||
// Standalone — stop its container and clean up its Docker volume
|
||||
if (instance.getContainerId() != null) {
|
||||
containerManager.stop(buildHandle(instance));
|
||||
}
|
||||
if (instance.getDockerVolumeName() != null) {
|
||||
containerManager.removeVolume(instance.getDbInstanceIdentifier());
|
||||
}
|
||||
} else {
|
||||
// Cluster member — remove from cluster's member list
|
||||
DbCluster cluster = clusters.get(clusterId).orElse(null);
|
||||
@@ -253,6 +263,7 @@ public class RdsService {
|
||||
cluster.setContainerId(handle.getContainerId());
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
cluster.setDockerVolumeName(isInMemory() ? null : "floci-rds-" + id);
|
||||
|
||||
String region = regionResolver.getDefaultRegion();
|
||||
cluster.setDbClusterResourceId("cluster-" + java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 24).toUpperCase());
|
||||
@@ -312,6 +323,9 @@ public class RdsService {
|
||||
if (cluster.getContainerId() != null) {
|
||||
containerManager.stop(buildClusterHandle(cluster));
|
||||
}
|
||||
if (cluster.getDockerVolumeName() != null) {
|
||||
containerManager.removeVolume(id);
|
||||
}
|
||||
|
||||
releaseProxyPort(cluster.getProxyPort());
|
||||
clusters.delete(id);
|
||||
@@ -368,6 +382,9 @@ public class RdsService {
|
||||
if (instance == null) {
|
||||
return false;
|
||||
}
|
||||
if (!instance.getMasterUsername().equals(clientUser)) {
|
||||
return true; // non-master user: backend is the authority
|
||||
}
|
||||
return password != null && password.equals(instance.getMasterPassword());
|
||||
}
|
||||
|
||||
@@ -376,11 +393,18 @@ public class RdsService {
|
||||
if (cluster == null) {
|
||||
return false;
|
||||
}
|
||||
if (!cluster.getMasterUsername().equals(clientUser)) {
|
||||
return true; // non-master user: backend is the authority
|
||||
}
|
||||
return password != null && password.equals(cluster.getMasterPassword());
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private boolean isInMemory() {
|
||||
return "memory".equals(serviceConfigAccess.storageMode("rds"));
|
||||
}
|
||||
|
||||
private DatabaseEngine resolveEngine(String engineParam) {
|
||||
if (engineParam == null) {
|
||||
return DatabaseEngine.POSTGRES;
|
||||
|
||||
+58
-24
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.rds.container;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
@@ -38,6 +39,7 @@ public class RdsContainerManager {
|
||||
private final ContainerDetector containerDetector;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ServiceConfigAccess serviceConfigAccess;
|
||||
private final Map<String, RdsContainerHandle> activeContainers = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
@@ -46,13 +48,15 @@ public class RdsContainerManager {
|
||||
ContainerLogStreamer logStreamer,
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config,
|
||||
RegionResolver regionResolver) {
|
||||
RegionResolver regionResolver,
|
||||
ServiceConfigAccess serviceConfigAccess) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
this.containerDetector = containerDetector;
|
||||
this.config = config;
|
||||
this.regionResolver = regionResolver;
|
||||
this.serviceConfigAccess = serviceConfigAccess;
|
||||
}
|
||||
|
||||
public RdsContainerHandle start(String instanceId, DatabaseEngine engine,
|
||||
@@ -140,36 +144,66 @@ public class RdsContainerManager {
|
||||
|
||||
private void addPersistenceMounts(ContainerBuilder.Builder specBuilder, String instanceId,
|
||||
DatabaseEngine engine, List<String> envVars) {
|
||||
if ("memory".equals(serviceConfigAccess.storageMode("rds"))) {
|
||||
return; // ephemeral mode — no mount needed
|
||||
}
|
||||
|
||||
String hostPersistentPath = config.storage().hostPersistentPath();
|
||||
boolean isVolume = !hostPersistentPath.startsWith("/") && !hostPersistentPath.startsWith(".");
|
||||
|
||||
if (isVolume) {
|
||||
// Named volume mode: mount the whole volume and tell the engine where to write
|
||||
if (!hostPersistentPath.startsWith("/") && !hostPersistentPath.startsWith(".")) {
|
||||
// Explicit Docker named volume (e.g. "floci-data"): mount the shared volume
|
||||
String internalMountPath = "/app/data";
|
||||
specBuilder.withBind(hostPersistentPath, internalMountPath);
|
||||
|
||||
specBuilder.withNamedVolume(hostPersistentPath, internalMountPath);
|
||||
String dataPath = internalMountPath + "/rds/" + instanceId;
|
||||
if (engine == DatabaseEngine.POSTGRES) {
|
||||
envVars.add("PGDATA=" + dataPath);
|
||||
} else {
|
||||
LOG.warnv("Volume-based persistence for RDS engine {0} is currently only optimized for POSTGRES. " +
|
||||
"Using default non-persistent path.", engine);
|
||||
}
|
||||
} else {
|
||||
// Directory mode: mount the specific subdirectory directly
|
||||
String dataPath = Path.of(config.storage().persistentPath(), "rds", instanceId)
|
||||
.toAbsolutePath().toString();
|
||||
applyEngineDataPath(specBuilder, engine, envVars, instanceId, dataPath);
|
||||
|
||||
} else if (hostPersistentPath.startsWith("/")) {
|
||||
// Absolute bind-mount path: user explicitly configured this host path
|
||||
String hostDataPath = Path.of(hostPersistentPath, "rds", instanceId).toString();
|
||||
try {
|
||||
Files.createDirectories(Path.of(dataPath));
|
||||
String hostDataPath = Path.of(hostPersistentPath, "rds", instanceId)
|
||||
.toAbsolutePath().toString();
|
||||
String target = (engine == DatabaseEngine.POSTGRES)
|
||||
? "/var/lib/postgresql/data"
|
||||
: "/var/lib/mysql";
|
||||
specBuilder.withBind(hostDataPath, target);
|
||||
Files.createDirectories(Path.of(hostDataPath));
|
||||
} catch (IOException e) {
|
||||
LOG.errorv("Failed to create RDS data directory: {0}", dataPath, e);
|
||||
LOG.errorv("Failed to create RDS data directory: {0}", hostDataPath, e);
|
||||
}
|
||||
specBuilder.withBind(hostDataPath, engineDefaultDataPath(engine));
|
||||
|
||||
} else {
|
||||
// Default (relative path like ./data): use a per-instance Docker named volume.
|
||||
// This works on all platforms including Docker Desktop on macOS, where
|
||||
// bind-mounting paths inside the Floci container is not allowed.
|
||||
String volumeName = "floci-rds-" + instanceId;
|
||||
specBuilder.withNamedVolume(volumeName, engineDefaultDataPath(engine));
|
||||
if (engine == DatabaseEngine.POSTGRES) {
|
||||
envVars.add("PGDATA=/var/lib/postgresql/data");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void applyEngineDataPath(ContainerBuilder.Builder specBuilder, DatabaseEngine engine,
|
||||
List<String> envVars, String instanceId, String dataPath) {
|
||||
if (engine == DatabaseEngine.POSTGRES) {
|
||||
envVars.add("PGDATA=" + dataPath);
|
||||
} else {
|
||||
// MySQL / MariaDB: use a dedicated per-instance named volume
|
||||
String volumeName = "floci-rds-" + instanceId;
|
||||
specBuilder.withNamedVolume(volumeName, engineDefaultDataPath(engine));
|
||||
}
|
||||
}
|
||||
|
||||
private static String engineDefaultDataPath(DatabaseEngine engine) {
|
||||
return switch (engine) {
|
||||
case POSTGRES -> "/var/lib/postgresql/data";
|
||||
case MYSQL, MARIADB -> "/var/lib/mysql";
|
||||
};
|
||||
}
|
||||
|
||||
public void removeVolume(String instanceId) {
|
||||
String volumeName = "floci-rds-" + instanceId;
|
||||
try {
|
||||
lifecycleManager.getDockerClient().removeVolumeCmd(volumeName).exec();
|
||||
LOG.infov("Removed Docker volume {0} for RDS instance {1}", volumeName, instanceId);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not remove Docker volume {0}: {1}", volumeName, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@ public class DbCluster {
|
||||
private Instant createdAt;
|
||||
private int proxyPort;
|
||||
|
||||
private String dockerVolumeName; // null in in-memory mode; "floci-rds-<id>" otherwise
|
||||
|
||||
// Transient — not persisted
|
||||
private transient String containerId;
|
||||
private transient String containerHost;
|
||||
@@ -104,6 +106,9 @@ public class DbCluster {
|
||||
public int getProxyPort() { return proxyPort; }
|
||||
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
|
||||
|
||||
public String getDockerVolumeName() { return dockerVolumeName; }
|
||||
public void setDockerVolumeName(String dockerVolumeName) { this.dockerVolumeName = dockerVolumeName; }
|
||||
|
||||
public String getContainerId() { return containerId; }
|
||||
public void setContainerId(String containerId) { this.containerId = containerId; }
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ public class DbInstance {
|
||||
private Instant createdAt;
|
||||
private int proxyPort;
|
||||
|
||||
private String dockerVolumeName; // null in in-memory mode; "floci-rds-<id>" otherwise
|
||||
|
||||
// Transient — not persisted; restored on startup by re-launching containers
|
||||
private transient String containerId;
|
||||
private transient String containerHost;
|
||||
@@ -108,6 +110,9 @@ public class DbInstance {
|
||||
public int getProxyPort() { return proxyPort; }
|
||||
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
|
||||
|
||||
public String getDockerVolumeName() { return dockerVolumeName; }
|
||||
public void setDockerVolumeName(String dockerVolumeName) { this.dockerVolumeName = dockerVolumeName; }
|
||||
|
||||
public String getContainerId() { return containerId; }
|
||||
public void setContainerId(String containerId) { this.containerId = containerId; }
|
||||
|
||||
|
||||
+11
-3
@@ -65,7 +65,10 @@ public class MySqlProtocolHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 4: Validate credentials against the backend nonce
|
||||
// Phase 4: Validate credentials against the backend nonce.
|
||||
// Master user: validate the scramble locally against the known master password.
|
||||
// Non-master users: pass through — the backend validates their scramble directly.
|
||||
// IAM tokens: validate SigV4, then connect to backend as master.
|
||||
byte[] clientPayload = Arrays.copyOfRange(clientResponseRaw, 4, clientResponseRaw.length);
|
||||
String[] parsed = parseHandshakeResponse(clientPayload);
|
||||
String clientUsername = parsed[0];
|
||||
@@ -74,8 +77,13 @@ public class MySqlProtocolHandler {
|
||||
|
||||
boolean valid;
|
||||
try {
|
||||
byte[] expected = scrambleNativePassword(masterPassword, backendNonce);
|
||||
valid = masterUsername.equals(clientUsername) && Arrays.equals(expected, clientAuthData);
|
||||
if (masterUsername.equals(clientUsername)) {
|
||||
byte[] expected = scrambleNativePassword(masterPassword, backendNonce);
|
||||
valid = Arrays.equals(expected, clientAuthData);
|
||||
} else {
|
||||
// Non-master user: defer to backend — it knows their password.
|
||||
valid = true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("MySQL auth error for instance: {0}", e.getMessage());
|
||||
valid = false;
|
||||
|
||||
+34
-18
@@ -68,32 +68,48 @@ public class PostgresProtocolHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 4: Validate credentials
|
||||
boolean valid;
|
||||
if (iamEnabled && clientPassword.contains("X-Amz-Signature")) {
|
||||
valid = sigV4.validate(clientPassword, clientUsername);
|
||||
} else {
|
||||
valid = passwordValidator.validate(clientUsername, clientPassword);
|
||||
// Phase 4: Validate credentials.
|
||||
// - IAM tokens: validated locally via SigV4.
|
||||
// - Master user (plain password): validated at the proxy via passwordValidator, which
|
||||
// reads from RdsService and therefore reflects modifyDBInstance password changes.
|
||||
// - Non-master users: pass through — the backend is the authority for their passwords.
|
||||
boolean isIam = iamEnabled && clientPassword.contains("X-Amz-Signature");
|
||||
boolean isMaster = masterUsername.equals(clientUsername);
|
||||
|
||||
if (isIam) {
|
||||
if (!sigV4.validate(clientPassword, clientUsername)) {
|
||||
sendErrorResponse(clientOut, "FATAL", "28P01",
|
||||
"password authentication failed for user \"" + clientUsername + "\"");
|
||||
clientOut.flush();
|
||||
closeQuietly(client);
|
||||
closeQuietly(backend);
|
||||
return;
|
||||
}
|
||||
} else if (isMaster) {
|
||||
if (!passwordValidator.validate(clientUsername, clientPassword)) {
|
||||
sendErrorResponse(clientOut, "FATAL", "28P01",
|
||||
"password authentication failed for user \"" + clientUsername + "\"");
|
||||
clientOut.flush();
|
||||
closeQuietly(client);
|
||||
closeQuietly(backend);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!valid) {
|
||||
sendErrorResponse(clientOut, "FATAL", "28P01",
|
||||
"password authentication failed for user \"" + clientUsername + "\"");
|
||||
clientOut.flush();
|
||||
closeQuietly(client);
|
||||
closeQuietly(backend);
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 5: Connect to backend PostgreSQL
|
||||
// Phase 5: Connect to backend PostgreSQL.
|
||||
// IAM and master: use master credentials — the backend has the original container password
|
||||
// and is never updated directly, so the proxy always authenticates as master.
|
||||
// Non-master: forward the client's own credentials so the backend enforces its own ACLs.
|
||||
InputStream backendIn = backend.getInputStream();
|
||||
OutputStream backendOut = backend.getOutputStream();
|
||||
|
||||
String effectiveDbName = (dbName != null && !dbName.isBlank()) ? dbName : "postgres";
|
||||
sendStartupToBackend(backendOut, masterUsername, effectiveDbName);
|
||||
String backendUser = (isIam || isMaster) ? masterUsername : clientUsername;
|
||||
String backendPass = (isIam || isMaster) ? masterPassword : clientPassword;
|
||||
sendStartupToBackend(backendOut, backendUser, effectiveDbName);
|
||||
backendOut.flush();
|
||||
|
||||
if (!authenticateWithBackend(backendIn, backendOut, masterUsername, masterPassword)) {
|
||||
if (!authenticateWithBackend(backendIn, backendOut, backendUser, backendPass)) {
|
||||
sendErrorResponse(clientOut, "FATAL", "08006",
|
||||
"Backend database authentication failed");
|
||||
clientOut.flush();
|
||||
|
||||
Reference in new issue
Block a user