fix(rds): inherit cluster IAM settings for new members (#5653)

* fix(rds): inherit cluster IAM settings for new members

* fix(rds): keep new member authentication in step with cluster changes

* fix(rds): allow metadata reads during member creation

* fix(rds): keep member creation consistent with lifecycle changes

* fix(rds): preserve metadata access during instance reboot

* fix(rds): use one cluster state for member creation

* test(rds): check IAM authentication consistently
This commit is contained in:
David Phillips authored and GitHub committed 2026-10-14 13:36:57 -04:00
1 parent 9f224e5760
commit 12c8f969af
5 files changed
+654 -85

No files matched your search

@@ -0,0 +1,49 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DBInstance;
import static org.assertj.core.api.Assertions.assertThat;
class RdsClusterMemberIamStateTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
@DisplayName("New Aurora members inherit cluster IAM authentication")
void newMembersInheritClusterIamAuthentication(boolean enabled) {
String clusterId = TestFixtures.uniqueName("sdk-iam-cluster");
try (RdsClient rds = TestFixtures.rdsClient()) {
boolean clusterCreated = false;
try {
rds.createDBCluster(request -> request.dbClusterIdentifier(clusterId)
.engine("aurora-postgresql").masterUsername("admin")
.masterUserPassword("Secret12345").enableIAMDatabaseAuthentication(enabled));
clusterCreated = true;
for (Boolean requested : new Boolean[]{null, false, true}) {
String memberId = TestFixtures.uniqueName("sdk-iam-member");
boolean memberCreated = false;
try {
DBInstance member = rds.createDBInstance(request -> request.dbInstanceIdentifier(memberId)
.dbClusterIdentifier(clusterId).dbInstanceClass("db.r5.large")
.engine("aurora-postgresql").enableIAMDatabaseAuthentication(requested)).dbInstance();
memberCreated = true;
assertThat(member.iamDatabaseAuthenticationEnabled()).isEqualTo(enabled);
assertThat(rds.describeDBInstances(request -> request.dbInstanceIdentifier(memberId))
.dbInstances().get(0).iamDatabaseAuthenticationEnabled()).isEqualTo(enabled);
} finally {
if (memberCreated) {
rds.deleteDBInstance(request -> request.dbInstanceIdentifier(memberId).skipFinalSnapshot(true));
}
}
}
} finally {
if (clusterCreated) {
rds.deleteDBCluster(request -> request.dbClusterIdentifier(clusterId).skipFinalSnapshot(true));
}
}
}
}
}
+6
View File
@@ -748,6 +748,12 @@ The RDS auth proxy validates the master username and password at the proxy layer
IAM database authentication is also supported. Set `--enable-iam-database-authentication` at instance creation time and use `aws rds generate-db-auth-token` to obtain a token.
New Aurora members inherit IAM database authentication from their cluster.
`EnableIAMDatabaseAuthentication` on `CreateDBInstance` does not override the
cluster setting, including when the instance parameter is omitted.
Member IAM connections currently require the cluster master username and password
to be supplied when creating the member; those credentials are not yet inherited.
Changing `EnableIAMDatabaseAuthentication` with `ModifyDBCluster` updates existing
Aurora members and applies to new connections through the cluster and member
endpoints. Omitting the flag preserves the current setting. Existing connections
@@ -88,6 +88,7 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -743,6 +744,7 @@ public class RdsService implements Resettable, ResourceProvider {
String instanceDockerVolumeName = null;
String instanceStorageResourceId = dbiResourceId;
PlacementResolution placement;
DbCluster publicationCluster = null;
String engineIdentifier = engineParam != null && !engineParam.isBlank()
? engineParam.toLowerCase() : null;
@@ -757,6 +759,7 @@ public class RdsService implements Resettable, ResourceProvider {
if (engineIdentifier == null && cluster.getEngineIdentifier() != null) {
engineIdentifier = cluster.getEngineIdentifier().toLowerCase();
}
publicationCluster = cluster;
backendHost = cluster.getContainerHost();
backendPort = cluster.getContainerPort();
containerId = cluster.getContainerId();
@@ -831,50 +834,72 @@ public class RdsService implements Resettable, ResourceProvider {
instance.setDbiResourceId(dbiResourceId);
instance.setDbInstanceArn(dbInstanceArn);
if (manageMasterUserPassword) {
attachManagedMasterUserSecret(instance, effectiveRegion, masterUserSecretKmsKeyId, effectiveSecretKmsKeyId);
}
String accountId = accountIdFromArn(instance.getDbInstanceArn());
putInstanceForScope(accountId, effectiveRegion, id, instance);
// The canonical cluster owns member publication and cluster changes. Standalone
// publication and slow relay/storage work do not hold the service-wide monitor.
synchronized (publicationCluster != null ? publicationCluster : instance) {
DbCluster currentCluster = null;
if (dbClusterIdentifier != null && !dbClusterIdentifier.isBlank()) {
currentCluster = findClusterForScope(accountId, effectiveRegion, dbClusterIdentifier);
if (currentCluster != publicationCluster) {
releaseProxyPort(proxyPort);
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster changed during member creation.", 400);
}
if (currentCluster != null) {
if (currentCluster.getStatus() != null
&& currentCluster.getStatus() != DbInstanceStatus.AVAILABLE) {
releaseProxyPort(proxyPort);
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster is not available for member creation.", 400);
}
backendHost = currentCluster.getContainerHost();
backendPort = currentCluster.getContainerPort();
instance.setContainerId(currentCluster.getContainerId());
instance.setContainerHost(backendHost);
instance.setContainerPort(backendPort);
iamEnabled = currentCluster.isIamDatabaseAuthenticationEnabled();
instance.setIamDatabaseAuthenticationEnabled(iamEnabled);
}
}
if (manageMasterUserPassword) {
attachManagedMasterUserSecret(instance, effectiveRegion, masterUserSecretKmsKeyId, effectiveSecretKmsKeyId);
}
putInstanceForScope(accountId, effectiveRegion, id, instance);
if (!mock && hasBackend(backendHost, backendPort)) {
final String instanceRegion = regionFromArn(instance.getDbInstanceArn());
try {
proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id),
engine, iamEnabled, proxyPort, backendHost, backendPort,
instance.getEndpoint().address(),
masterUsername, masterPassword, dbName,
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion, id, user, pw),
proxyBinding(engine, instance.getEndpoint().address(), instance.getEndpoint().port(),
instanceRegion, accountId, dbUserResourceId(instance)));
} catch (RuntimeException | Error e) {
if (!mock && hasBackend(backendHost, backendPort)) {
final String instanceRegion = regionFromArn(instance.getDbInstanceArn());
try {
deleteInstanceForScope(accountId, effectiveRegion, id);
} catch (RuntimeException rollbackFailure) {
e.addSuppressed(rollbackFailure);
proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id),
engine, iamEnabled, proxyPort, backendHost, backendPort,
instance.getEndpoint().address(),
masterUsername, masterPassword, dbName,
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion, id, user, pw),
proxyBinding(engine, instance.getEndpoint().address(), instance.getEndpoint().port(),
instanceRegion, accountId, dbUserResourceId(instance)));
} catch (RuntimeException | Error e) {
try {
deleteInstanceForScope(accountId, effectiveRegion, id);
} catch (RuntimeException rollbackFailure) {
e.addSuppressed(rollbackFailure);
}
throw e;
}
throw e;
}
}
if (dbClusterIdentifier != null && !dbClusterIdentifier.isBlank()) {
DbCluster cluster = findClusterForScope(
currentAccountId(), effectiveRegion, dbClusterIdentifier);
if (cluster != null) {
cluster.getDbClusterMembers().add(id);
if (cluster.resolveWriterIdentifier() == null
|| !cluster.getDbClusterMembers().contains(cluster.getClusterWriterIdentifier())) {
cluster.setClusterWriterIdentifier(cluster.resolveWriterIdentifier());
if (currentCluster != null) {
currentCluster.getDbClusterMembers().add(id);
if (currentCluster.resolveWriterIdentifier() == null
|| !currentCluster.getDbClusterMembers().contains(currentCluster.getClusterWriterIdentifier())) {
currentCluster.setClusterWriterIdentifier(currentCluster.resolveWriterIdentifier());
}
putClusterForScope(currentAccountId(), effectiveRegion,
dbClusterIdentifier, cluster);
putClusterForScope(accountId, effectiveRegion, dbClusterIdentifier, currentCluster);
}
}
instance.setStatus(DbInstanceStatus.AVAILABLE);
putInstanceForScope(accountId, effectiveRegion, id, instance);
instance.setStatus(DbInstanceStatus.AVAILABLE);
putInstanceForScope(accountId, effectiveRegion, id, instance);
}
LOG.infov("DB instance {0} created, engine={1}, endpoint={2}:{3}",
id, engine, endpoint.address(), String.valueOf(endpoint.port()));
return instance;
@@ -1572,7 +1597,7 @@ public class RdsService implements Resettable, ResourceProvider {
replica.setPreferredBackupWindow(backupWindow);
}
putInstanceForScope(accountIdFromArn(replica.getDbInstanceArn()), effectiveRegion, id, replica);
DbInstance promoted = rebootDbInstance(id, effectiveRegion);
DbInstance promoted = doRebootDbInstance(id, effectiveRegion);
LOG.infov("Read replica {0} promoted to a standalone DB instance", id);
return promoted;
}
@@ -2909,7 +2934,7 @@ public class RdsService implements Resettable, ResourceProvider {
// synchronized like the tag and delete paths: an unguarded read-modify-write here could
// write an instance back after deleteDbInstance removed it
public synchronized DbInstance modifyDbInstance(
public DbInstance modifyDbInstance(
String id, String newPassword, Boolean iamEnabled,
String dbSubnetGroupName, List<String> vpcSecurityGroupIds,
String optionGroupName, String region, Boolean autoMinorVersionUpgrade,
@@ -2920,7 +2945,19 @@ public class RdsService implements Resettable, ResourceProvider {
settings, publiclyAccessible, scaling, null);
}
public synchronized DbInstance modifyDbInstance(
public DbInstance modifyDbInstance(
String id, String newPassword, Boolean iamEnabled,
String dbSubnetGroupName, List<String> vpcSecurityGroupIds,
String optionGroupName, String region, Boolean autoMinorVersionUpgrade,
DbInstanceSettings settings, Boolean publiclyAccessible,
DbInstanceScalingChanges scaling, Boolean deletionProtection) {
return withInstancePublication(id, region, () -> doModifyDbInstance(
id, newPassword, iamEnabled, dbSubnetGroupName, vpcSecurityGroupIds,
optionGroupName, region, autoMinorVersionUpgrade,
settings, publiclyAccessible, scaling, deletionProtection));
}
private synchronized DbInstance doModifyDbInstance(
String id, String newPassword, Boolean iamEnabled,
String dbSubnetGroupName, List<String> vpcSecurityGroupIds,
String optionGroupName, String region, Boolean autoMinorVersionUpgrade,
@@ -3337,7 +3374,7 @@ public class RdsService implements Resettable, ResourceProvider {
private void startStandaloneInstanceBackend(DbInstance instance, String id, String effectiveRegion) {
if (instance.getEndpoint() == null) {
try {
ensureInstanceBackend(id, effectiveRegion);
doEnsureInstanceBackend(id, effectiveRegion);
} catch (RuntimeException | Error e) {
instance.setStatus(DbInstanceStatus.FAILED);
putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
@@ -3385,7 +3422,11 @@ public class RdsService implements Resettable, ResourceProvider {
* Stops an available cluster and its members: the cluster's proxy and container go away,
* every member's proxy with them, and all of them report "stopped" until StartDBCluster.
*/
public synchronized DbCluster stopDbCluster(String id, String region) {
public DbCluster stopDbCluster(String id, String region) {
return withClusterPublication(id, region, () -> doStopDbCluster(id, region));
}
private DbCluster doStopDbCluster(String id, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
DbCluster cluster = getDbCluster(id, effectiveRegion);
@@ -3433,7 +3474,11 @@ public class RdsService implements Resettable, ResourceProvider {
}
/** Starts a stopped cluster and its members on the cluster's kept volume. */
public synchronized DbCluster startDbCluster(String id, String region) {
public DbCluster startDbCluster(String id, String region) {
return withClusterPublication(id, region, () -> doStartDbCluster(id, region));
}
private DbCluster doStartDbCluster(String id, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
DbCluster cluster = getDbCluster(id, effectiveRegion);
@@ -3456,7 +3501,11 @@ public class RdsService implements Resettable, ResourceProvider {
}
/** Reboots a cluster: its container and proxies go down and come back on the same volume. */
public synchronized DbCluster rebootDbCluster(String id, String region) {
public DbCluster rebootDbCluster(String id, String region) {
return withClusterPublication(id, region, () -> doRebootDbCluster(id, region));
}
private DbCluster doRebootDbCluster(String id, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
DbCluster cluster = getDbCluster(id, effectiveRegion);
@@ -3554,6 +3603,10 @@ public class RdsService implements Resettable, ResourceProvider {
}
public DbInstance rebootDbInstance(String id, String region) {
return withInstancePublication(id, region, () -> doRebootDbInstance(id, region));
}
private DbInstance doRebootDbInstance(String id, String region) {
String effectiveRegion = effectiveRegion(region);
DbInstance instance = getDbInstance(id, effectiveRegion);
@@ -3614,7 +3667,7 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getEndpoint().port(), instanceRegion, accountId, dbUserResourceId(instance)));
} else {
// No backing container: created or last rebooted while no daemon was reachable.
instance = ensureInstanceBackend(id, effectiveRegion);
instance = doEnsureInstanceBackend(id, effectiveRegion);
}
}
@@ -3674,7 +3727,11 @@ public class RdsService implements Resettable, ResourceProvider {
*
* @return the instance, with its container fields populated when a backend became available
*/
public synchronized DbInstance ensureInstanceBackend(String id, String region) {
public DbInstance ensureInstanceBackend(String id, String region) {
return withInstancePublication(id, region, () -> doEnsureInstanceBackend(id, region));
}
private synchronized DbInstance doEnsureInstanceBackend(String id, String region) {
String effectiveRegion = effectiveRegion(region);
DbInstance instance = getDbInstance(id, effectiveRegion);
if (config.services().rds().mock()) {
@@ -3762,7 +3819,11 @@ public class RdsService implements Resettable, ResourceProvider {
*
* @return the cluster, with its container fields populated when a backend became available
*/
public synchronized DbCluster ensureClusterBackend(String id, String region) {
public DbCluster ensureClusterBackend(String id, String region) {
return withClusterPublication(id, region, () -> doEnsureClusterBackend(id, region));
}
private DbCluster doEnsureClusterBackend(String id, String region) {
return ensureClusterBackend(id, region, true);
}
@@ -3872,7 +3933,7 @@ public class RdsService implements Resettable, ResourceProvider {
member.setContainerPort(0);
}
// Member retry must not recurse into the cluster's other members.
ensureInstanceBackend(memberId, region);
doEnsureInstanceBackend(memberId, region);
} else if (restart) {
member.setContainerId(cluster.getContainerId());
member.setContainerHost(cluster.getContainerHost());
@@ -3931,11 +3992,55 @@ public class RdsService implements Resettable, ResourceProvider {
return config.services().rds().mock() || containerManager.isDockerReachable();
}
public synchronized void deleteDbInstance(String id) {
private <T> T withClusterPublication(String id, String region, Supplier<T> operation) {
String accountId = currentAccountId();
String scopeRegion = effectiveRegion(region);
while (true) {
DbCluster cluster = getDbCluster(id, scopeRegion);
synchronized (cluster) {
synchronized (this) {
if (findClusterForScope(accountId, scopeRegion, id) != cluster) {
continue;
}
return operation.get();
}
}
}
}
private <T> T withInstancePublication(String id, String region, Supplier<T> operation) {
String accountId = currentAccountId();
String scopeRegion = effectiveRegion(region);
while (true) {
DbInstance instance = getDbInstance(id, scopeRegion);
String clusterId = instance.getDbClusterIdentifier();
DbCluster cluster = clusterId == null || clusterId.isBlank() ? null
: findClusterForScope(accountId, scopeRegion, clusterId);
synchronized (cluster != null ? cluster : instance) {
synchronized (this) {
if (findInstanceForScope(accountId, scopeRegion, id) != instance
|| (clusterId != null && !clusterId.isBlank()
&& findClusterForScope(accountId, scopeRegion, clusterId) != cluster)) {
continue;
}
}
return operation.get();
}
}
}
public void deleteDbInstance(String id) {
deleteDbInstance(id, regionResolver.getDefaultRegion());
}
public synchronized void deleteDbInstance(String id, String region) {
public void deleteDbInstance(String id, String region) {
withInstancePublication(id, region, () -> {
doDeleteDbInstance(id, region);
return null;
});
}
private synchronized void doDeleteDbInstance(String id, String region) {
String effectiveRegion = effectiveRegion(region);
DbInstance instance = Optional.ofNullable(
findInstanceForScope(currentAccountId(), effectiveRegion, id))
@@ -4567,7 +4672,29 @@ public class RdsService implements Resettable, ResourceProvider {
serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause, null, null, region);
}
public synchronized DbCluster modifyDbCluster(String id, String newPassword, Boolean iamEnabled,
public DbCluster modifyDbCluster(String id, String newPassword, Boolean iamEnabled,
Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
Integer serverlessV2SecondsUntilAutoPause,
Boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String region) {
String effectiveRegion = effectiveRegion(region);
while (true) {
DbCluster cluster = getDbCluster(id, effectiveRegion);
// Wait for same-cluster publication before entering the global mutation monitor.
synchronized (cluster) {
synchronized (this) {
if (findClusterForScope(currentAccountId(), effectiveRegion, id) != cluster) {
continue;
}
return doModifyDbCluster(id, newPassword, iamEnabled, serverlessV2MinCapacity,
serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, region);
}
}
}
}
private DbCluster doModifyDbCluster(String id, String newPassword, Boolean iamEnabled,
Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
Integer serverlessV2SecondsUntilAutoPause,
Boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
@@ -4694,11 +4821,27 @@ public class RdsService implements Resettable, ResourceProvider {
}
}
public synchronized void deleteDbCluster(String id) {
public void deleteDbCluster(String id) {
deleteDbCluster(id, regionResolver.getDefaultRegion());
}
public synchronized void deleteDbCluster(String id, String region) {
public void deleteDbCluster(String id, String region) {
String effectiveRegion = effectiveRegion(region);
while (true) {
DbCluster cluster = getDbCluster(id, effectiveRegion);
synchronized (cluster) {
synchronized (this) {
if (findClusterForScope(currentAccountId(), effectiveRegion, id) != cluster) {
continue;
}
doDeleteDbCluster(id, region);
return;
}
}
}
}
private void doDeleteDbCluster(String id, String region) {
String effectiveRegion = effectiveRegion(region);
DbCluster cluster = Optional.ofNullable(
findClusterForScope(currentAccountId(), effectiveRegion, id))
@@ -5106,7 +5249,11 @@ public class RdsService implements Resettable, ResourceProvider {
* Forces a failover inside a DB cluster: the named member, or the first reader when none is
* named, becomes the writer. A cluster without a reader has nothing to fail over to.
*/
public synchronized DbCluster failoverDbCluster(String id, String targetDbInstanceIdentifier, String region) {
public DbCluster failoverDbCluster(String id, String targetDbInstanceIdentifier, String region) {
return withClusterPublication(id, region, () -> doFailoverDbCluster(id, targetDbInstanceIdentifier, region));
}
private DbCluster doFailoverDbCluster(String id, String targetDbInstanceIdentifier, String region) {
String effectiveRegion = effectiveRegion(region);
DbCluster cluster = getDbCluster(id, effectiveRegion);
String writer = cluster.resolveWriterIdentifier();
@@ -8,6 +8,8 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.sql.Connection;
import java.sql.DriverManager;
@@ -81,20 +83,9 @@ class RdsIamAuthLambdaSessionIntegrationTest {
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
iamService.registerLambdaExecutionRoleSession(ACCOUNT_ID, accessKeyId, SESSION_SECRET, SESSION_TOKEN,
"arn:aws:iam::" + ACCOUNT_ID + ":role/connect-with-iam");
await().atMost(Duration.ofSeconds(60)).ignoreExceptions().until(() -> {
try (Connection connection = connect(port, MASTER_PASSWORD)) {
return connection.isValid(5);
}
});
awaitPasswordReady(port);
String token = SigV4TokenTestHelper.createRdsToken("127.0.0.1", port, MASTER_USER,
accessKeyId, SESSION_SECRET, Instant.now().minusSeconds(60), 900, SESSION_TOKEN);
try (Connection connection = connect(port, token);
Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT current_user")) {
assertTrue(rows.next());
assertEquals(MASTER_USER, rows.getString(1));
}
assertIamAuthentication(port, accessKeyId, true);
String anotherSession = SigV4TokenTestHelper.createRdsToken("127.0.0.1", port, MASTER_USER,
accessKeyId, SESSION_SECRET, Instant.now().minusSeconds(60), 900,
@@ -142,14 +133,8 @@ class RdsIamAuthLambdaSessionIntegrationTest {
iamService.registerLambdaExecutionRoleSession(ACCOUNT_ID, accessKeyId, SESSION_SECRET, SESSION_TOKEN,
"arn:aws:iam::" + ACCOUNT_ID + ":role/cluster-connect-with-iam");
for (int port : new int[]{clusterPort, memberPort}) {
await().atMost(Duration.ofSeconds(60)).ignoreExceptions().until(() -> {
try (Connection connection = connect(port, MASTER_PASSWORD)) {
return connection.isValid(5);
}
});
String token = SigV4TokenTestHelper.createRdsToken("127.0.0.1", port, MASTER_USER,
accessKeyId, SESSION_SECRET, Instant.now().minusSeconds(60), 900, SESSION_TOKEN);
assertThrows(SQLException.class, () -> connect(port, token).close());
awaitPasswordReady(port);
assertIamAuthentication(port, accessKeyId, false);
}
for (boolean enabled : new boolean[]{true, false}) {
rds("ModifyDBCluster")
@@ -157,18 +142,7 @@ class RdsIamAuthLambdaSessionIntegrationTest {
.formParam("EnableIAMDatabaseAuthentication", Boolean.toString(enabled))
.when().post("/").then().statusCode(200);
for (int port : new int[]{clusterPort, memberPort}) {
String token = SigV4TokenTestHelper.createRdsToken("127.0.0.1", port, MASTER_USER,
accessKeyId, SESSION_SECRET, Instant.now().minusSeconds(60), 900, SESSION_TOKEN);
if (enabled) {
try (Connection connection = connect(port, token);
Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT current_user")) {
assertTrue(rows.next());
assertEquals(MASTER_USER, rows.getString(1));
}
} else {
assertThrows(SQLException.class, () -> connect(port, token).close());
}
assertIamAuthentication(port, accessKeyId, enabled);
try (Connection connection = connect(port, MASTER_PASSWORD)) {
assertTrue(connection.isValid(5));
}
@@ -183,6 +157,70 @@ class RdsIamAuthLambdaSessionIntegrationTest {
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void newClusterMemberUsesClusterIamAuthentication(boolean enabled) throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String clusterId = "inherit-cluster-" + suffix;
String memberId = "inherit-member-" + suffix;
String accessKeyId = "ASIA" + suffix.toUpperCase();
try {
rds("CreateDBCluster")
.formParam("DBClusterIdentifier", clusterId)
.formParam("Engine", "aurora-postgresql")
.formParam("MasterUsername", MASTER_USER)
.formParam("MasterUserPassword", MASTER_PASSWORD)
.formParam("DatabaseName", DATABASE)
.formParam("EnableIAMDatabaseAuthentication", Boolean.toString(enabled))
.when().post("/").then().statusCode(200);
int port = rds("CreateDBInstance")
.formParam("DBInstanceIdentifier", memberId)
.formParam("DBClusterIdentifier", clusterId)
.formParam("DBInstanceClass", "db.r5.large")
.formParam("Engine", "aurora-postgresql")
.formParam("MasterUsername", MASTER_USER)
.formParam("MasterUserPassword", MASTER_PASSWORD)
.formParam("DBName", DATABASE)
.formParam("EnableIAMDatabaseAuthentication", Boolean.toString(!enabled))
.when().post("/").then().statusCode(200)
.extract().xmlPath()
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
iamService.registerLambdaExecutionRoleSession(ACCOUNT_ID, accessKeyId, SESSION_SECRET, SESSION_TOKEN,
"arn:aws:iam::" + ACCOUNT_ID + ":role/member-connect-with-iam");
awaitPasswordReady(port);
assertIamAuthentication(port, accessKeyId, enabled);
} finally {
iamService.unregisterSession(ACCOUNT_ID, accessKeyId);
rds("DeleteDBInstance").formParam("DBInstanceIdentifier", memberId)
.formParam("SkipFinalSnapshot", "true").when().post("/");
rds("DeleteDBCluster").formParam("DBClusterIdentifier", clusterId)
.formParam("SkipFinalSnapshot", "true").when().post("/");
}
}
private static void awaitPasswordReady(int port) {
await().atMost(Duration.ofSeconds(60)).ignoreExceptions().until(() -> {
try (Connection connection = connect(port, MASTER_PASSWORD)) {
return connection.isValid(5);
}
});
}
private static void assertIamAuthentication(int port, String accessKeyId, boolean enabled) throws Exception {
String token = SigV4TokenTestHelper.createRdsToken("127.0.0.1", port, MASTER_USER,
accessKeyId, SESSION_SECRET, Instant.now().minusSeconds(60), 900, SESSION_TOKEN);
if (enabled) {
try (Connection connection = connect(port, token);
Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT current_user")) {
assertTrue(rows.next());
assertEquals(MASTER_USER, rows.getString(1));
}
} else {
assertThrows(SQLException.class, () -> connect(port, token).close());
}
}
private static Connection connect(int port, String password) throws SQLException {
Properties properties = new Properties();
properties.setProperty("user", MASTER_USER);
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.ec2.model.VpcIpv6CidrBlockAssociation
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import io.github.hectorvent.floci.services.rds.container.AutoPauseListener;
import io.github.hectorvent.floci.services.rds.container.RdsBackendGate;
import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
@@ -47,6 +48,8 @@ import io.github.hectorvent.floci.services.rds.model.ReadReplicaRequest;
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyBinding;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.github.hectorvent.floci.testutil.LogCapture;
@@ -54,9 +57,11 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.lang.reflect.Field;
import java.net.ServerSocket;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
@@ -66,14 +71,17 @@ import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.LogRecord;
import java.util.stream.Collectors;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@@ -455,6 +463,327 @@ class RdsServiceTest {
}
}
@Test
void replacedClusterCannotReceiveAnOldMemberPublicationAndRetryReusesThePort() throws Exception {
when(rdsConfig.mock()).thenReturn(false);
rdsService.createDbCluster("replaced-cluster", "aurora-postgresql", "16.3",
"admin", "password", "dbname", false, null);
CountDownLatch endpoint = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicBoolean first = new AtomicBoolean(true);
when(rdsConfig.endpointHost()).thenAnswer(call -> {
if (first.compareAndSet(true, false)) {
endpoint.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
}
return Optional.empty();
});
ExecutorService worker = Executors.newSingleThreadExecutor();
try {
Future<DbInstance> creation = worker.submit(() -> rdsService.createDbInstance("replacement-member",
"aurora-postgresql", "16.3", "admin", "password", "dbname", "db.r5.large", 20,
true, null, null, "replaced-cluster", null, false, false, null,
Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults()));
assertTrue(endpoint.await(5, TimeUnit.SECONDS));
rdsService.deleteDbCluster("replaced-cluster");
rdsService.createDbCluster("replaced-cluster", "aurora-postgresql", "16.3",
"admin", "password", "dbname", true, null);
release.countDown();
ExecutionException failed = assertThrows(ExecutionException.class, () -> creation.get(5, TimeUnit.SECONDS));
AwsException cause = assertInstanceOf(AwsException.class, failed.getCause());
assertEquals("InvalidDBClusterStateFault", cause.getErrorCode());
assertEquals("DBInstanceNotFound", assertThrows(AwsException.class,
() -> rdsService.getDbInstance("replacement-member")).getErrorCode());
assertTrue(rdsService.getDbCluster("replaced-cluster").getDbClusterMembers().isEmpty());
DbInstance retry = rdsService.createDbInstance("replacement-member", "aurora-postgresql", "16.3",
"admin", "password", "dbname", "db.r5.large", 20, false, null, null, "replaced-cluster",
null, false, false, null, Map.of(), List.of(), null, null, true,
DbInstanceSettings.defaults(), true, 7001, false);
assertEquals(7001, retry.getProxyPort());
assertTrue(retry.isIamDatabaseAuthenticationEnabled());
} finally {
release.countDown();
worker.shutdownNow();
assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void standaloneCertificatePreparationDoesNotBlockUnrelatedMetadata() throws Exception {
int port;
try (ServerSocket reservation = new ServerSocket(0)) {
port = reservation.getLocalPort();
}
when(rdsConfig.proxyBasePort()).thenReturn(port);
when(rdsConfig.proxyMaxPort()).thenReturn(port);
RdsProxyTlsCertificates certificates = mock(RdsProxyTlsCertificates.class);
CountDownLatch preparing = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(call -> {
preparing.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return null;
}).when(certificates).ensureHost(anyString());
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class), certificates,
config, RdsBackendGate.OPEN);
RdsService service = newService(containerManager, manager, new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
service.createGlobalCluster("unrelated-global", null, "aurora-postgresql", "16.3",
"dbname", false, false, Map.of(), "us-east-1");
ExecutorService workers = Executors.newFixedThreadPool(2);
try {
Future<DbInstance> creation = workers.submit(() -> service.createDbInstance("standalone",
"postgres", "16.3", "admin", "password", "dbname", "db.r5.large", 20,
false, null, null, null, null, false, false, null,
Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults()));
assertTrue(preparing.await(5, TimeUnit.SECONDS));
Future<GlobalCluster> unrelated = workers.submit(() -> service.describeGlobalCluster("unrelated-global"));
assertEquals("unrelated-global", unrelated.get(1, TimeUnit.SECONDS).getGlobalClusterIdentifier());
release.countDown();
assertEquals(DbInstanceStatus.AVAILABLE, creation.get(5, TimeUnit.SECONDS).getStatus());
} finally {
release.countDown();
workers.shutdownNow();
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
manager.stopAll();
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void memberPublicationAndClusterIamToggleKeepProxyStateConsistent(boolean initiallyEnabled) throws Exception {
InMemoryStorage<String, DbInstance> instances = spy(new InMemoryStorage<>());
RdsService service = newService(containerManager, proxyManager, instances, new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
service.createDbCluster("race-cluster", "aurora-postgresql", "16.3",
"admin", "password", "dbname", initiallyEnabled, null);
service.createGlobalCluster("unrelated-global", null, "aurora-postgresql", "16.3",
"dbname", false, false, Map.of(), "us-east-1");
CountDownLatch published = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicBoolean firstPublication = new AtomicBoolean(true);
AtomicBoolean installed = new AtomicBoolean(false);
AtomicBoolean proxyIam = new AtomicBoolean(initiallyEnabled);
doAnswer(call -> {
Object result = call.callRealMethod();
DbInstance value = call.getArgument(1);
if ("race-member".equals(value.getDbInstanceIdentifier()) && firstPublication.compareAndSet(true, false)) {
published.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
}
return result;
}).when(instances).put(any(), any());
doAnswer(call -> {
proxyIam.set(call.getArgument(2));
installed.set(true);
return null;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
any(), any(), any(), any(), any(), any());
doAnswer(call -> {
String key = call.getArgument(0);
if (key.endsWith(":db:race-member") && installed.get()) {
proxyIam.set(call.getArgument(1));
}
return null;
}).when(proxyManager).updateIamEnabled(any(), anyBoolean());
ExecutorService workers = Executors.newFixedThreadPool(4);
AtomicReference<Thread> modifierThread = new AtomicReference<>();
AtomicReference<Thread> deletionThread = new AtomicReference<>();
try {
Future<DbInstance> creation = workers.submit(() -> service.createDbInstance("race-member",
"aurora-postgresql", "16.3", "admin", "password", "dbname", "db.r5.large", 20,
!initiallyEnabled, null, null, "race-cluster", null, false, false, null,
Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults()));
assertTrue(published.await(5, TimeUnit.SECONDS));
Future<DbCluster> modification = workers.submit(() -> {
modifierThread.set(Thread.currentThread());
return service.modifyDbCluster("race-cluster", null, !initiallyEnabled);
});
await().atMost(Duration.ofSeconds(5)).until(() -> modification.isDone()
|| (modifierThread.get() != null && modifierThread.get().getState() == Thread.State.BLOCKED));
Future<AwsException> deletion = workers.submit(() -> {
deletionThread.set(Thread.currentThread());
return assertThrows(AwsException.class, () -> service.deleteDbCluster("race-cluster"));
});
await().atMost(Duration.ofSeconds(5)).until(() -> deletion.isDone()
|| (deletionThread.get() != null && deletionThread.get().getState() == Thread.State.BLOCKED));
Future<GlobalCluster> unrelated = workers.submit(() -> service.describeGlobalCluster("unrelated-global"));
assertEquals("unrelated-global", unrelated.get(1, TimeUnit.SECONDS).getGlobalClusterIdentifier());
release.countDown();
creation.get(5, TimeUnit.SECONDS);
modification.get(5, TimeUnit.SECONDS);
assertEquals("InvalidDBClusterStateFault", deletion.get(5, TimeUnit.SECONDS).getErrorCode());
assertTrue(installed.get());
assertEquals(!initiallyEnabled, service.getDbCluster("race-cluster").isIamDatabaseAuthenticationEnabled());
assertEquals(!initiallyEnabled, service.getDbInstance("race-member").isIamDatabaseAuthenticationEnabled());
assertEquals(!initiallyEnabled, proxyIam.get());
} finally {
release.countDown();
workers.shutdownNow();
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void standaloneRebootDoesNotBlockUnrelatedMetadataDuringBackendStop() throws Exception {
rdsService.createGlobalCluster("reboot-unrelated", null, "aurora-postgresql", "16.3",
"dbname", false, false, Map.of(), "us-east-1");
rdsService.createDbInstance("reboot-progress", "postgres", "16.3",
"admin", "password", "dbname", "db.t3.micro", 20,
false, null, null, null, null, false);
CountDownLatch stopping = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(call -> {
stopping.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return null;
}).when(containerManager).stop(any());
ExecutorService workers = Executors.newFixedThreadPool(2);
try {
Future<DbInstance> reboot = workers.submit(() -> rdsService.rebootDbInstance("reboot-progress"));
assertTrue(stopping.await(5, TimeUnit.SECONDS));
Future<GlobalCluster> unrelated = workers.submit(() -> rdsService.describeGlobalCluster("reboot-unrelated"));
assertEquals("reboot-unrelated", unrelated.get(1, TimeUnit.SECONDS).getGlobalClusterIdentifier());
release.countDown();
assertEquals(DbInstanceStatus.AVAILABLE, reboot.get(5, TimeUnit.SECONDS).getStatus());
assertEquals("localhost", rdsService.getDbInstance("reboot-progress").getContainerHost());
} finally {
release.countDown();
workers.shutdownNow();
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
}
}
@ParameterizedTest
@ValueSource(strings = {"delete", "modify", "stop", "reboot"})
void memberLifecycleWaitsForPublicationWithoutBlockingMetadata(String operation) throws Exception {
InMemoryStorage<String, DbInstance> instances = spy(new InMemoryStorage<>());
RdsService service = newService(containerManager, proxyManager, instances, new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
service.createDbCluster("race-cluster", "aurora-postgresql", "16.3",
"admin", "password", "dbname", false, null);
service.createGlobalCluster("unrelated-global", null, "aurora-postgresql", "16.3",
"dbname", false, false, Map.of(), "us-east-1");
CountDownLatch published = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicBoolean firstPublication = new AtomicBoolean(true);
AtomicBoolean installed = new AtomicBoolean(false);
AtomicBoolean proxyIam = new AtomicBoolean(false);
AtomicReference<String> memberBackend = new AtomicReference<>();
doAnswer(call -> {
Object result = call.callRealMethod();
DbInstance value = call.getArgument(1);
if ("race-member".equals(value.getDbInstanceIdentifier()) && firstPublication.compareAndSet(true, false)) {
published.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
}
return result;
}).when(instances).put(any(), any());
doAnswer(call -> {
if (((String) call.getArgument(0)).endsWith(":db:race-member")) {
memberBackend.set(call.getArgument(4));
}
proxyIam.set(call.getArgument(2));
installed.set(true);
return null;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
any(), any(), any(), any(), any(), any());
doAnswer(call -> {
String key = call.getArgument(0);
if (key.endsWith(":db:race-member") && installed.get()) {
proxyIam.set(call.getArgument(1));
}
return null;
}).when(proxyManager).updateIamEnabled(any(), anyBoolean());
doAnswer(call -> {
installed.set(false);
return null;
}).when(proxyManager).stopProxy(any());
ExecutorService workers = Executors.newFixedThreadPool(4);
AtomicReference<Thread> modifierThread = new AtomicReference<>();
try {
Future<DbInstance> creation = workers.submit(() -> service.createDbInstance("race-member",
"aurora-postgresql", "16.3", "admin", "password", "dbname", "db.r5.large", 20,
true, null, null, "race-cluster", null, false, false, null,
Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults()));
assertTrue(published.await(5, TimeUnit.SECONDS));
if ("reboot".equals(operation)) {
when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new RdsContainerHandle("replacement-container", "race-cluster", "new-backend", 6543));
}
Future<?> modification = workers.submit(() -> {
modifierThread.set(Thread.currentThread());
switch (operation) {
case "delete" -> service.deleteDbInstance("race-member");
case "modify" -> service.modifyDbInstance("race-member", null, true, null);
case "stop" -> service.stopDbCluster("race-cluster", "us-east-1");
case "reboot" -> service.rebootDbCluster("race-cluster", "us-east-1");
default -> throw new AssertionError(operation);
}
});
await().atMost(Duration.ofSeconds(5)).until(() -> modification.isDone()
|| (modifierThread.get() != null && modifierThread.get().getState() == Thread.State.BLOCKED));
Future<GlobalCluster> unrelated = workers.submit(() -> service.describeGlobalCluster("unrelated-global"));
assertEquals("unrelated-global", unrelated.get(1, TimeUnit.SECONDS).getGlobalClusterIdentifier());
release.countDown();
creation.get(5, TimeUnit.SECONDS);
modification.get(5, TimeUnit.SECONDS);
if ("delete".equals(operation)) {
assertEquals("DBInstanceNotFound", assertThrows(AwsException.class,
() -> service.getDbInstance("race-member")).getErrorCode());
assertFalse(installed.get());
assertFalse(service.getDbCluster("race-cluster").getDbClusterMembers().contains("race-member"));
} else if ("modify".equals(operation)) {
assertTrue(installed.get());
assertTrue(service.getDbInstance("race-member").isIamDatabaseAuthenticationEnabled());
assertTrue(proxyIam.get());
} else if ("stop".equals(operation)) {
assertEquals(DbInstanceStatus.STOPPED, service.getDbCluster("race-cluster").getStatus());
assertEquals(DbInstanceStatus.STOPPED, service.getDbInstance("race-member").getStatus());
assertFalse(installed.get());
assertTrue(service.getDbCluster("race-cluster").getDbClusterMembers().contains("race-member"));
} else {
assertEquals(DbInstanceStatus.AVAILABLE, service.getDbInstance("race-member").getStatus());
assertEquals("new-backend", service.getDbCluster("race-cluster").getContainerHost());
assertEquals("new-backend", service.getDbInstance("race-member").getContainerHost());
assertEquals("new-backend", memberBackend.get());
assertTrue(installed.get());
}
} finally {
release.countDown();
workers.shutdownNow();
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
}
}
@ParameterizedTest
@CsvSource({"aurora-postgresql,16.3,false,false", "aurora-postgresql,16.3,true,false",
"aurora-mysql,8.0,false,false", "aurora-mysql,8.0,true,false",
"aurora-postgresql,16.3,false,true", "aurora-postgresql,16.3,true,true",
"aurora-mysql,8.0,false,true", "aurora-mysql,8.0,true,true"})
void newClusterMembersInheritIamAuthentication(String engine, String version,
boolean clusterEnabled, boolean mockMode) {
when(rdsConfig.mock()).thenReturn(mockMode);
rdsService.createDbCluster("iam-cluster", engine, version,
"admin", "password", "dbname", clusterEnabled, null);
clearInvocations(proxyManager);
DbInstance member = rdsService.createDbInstance("iam-member", engine, version,
"admin", "password", "dbname", "db.r5.large", 20, !clusterEnabled,
null, null, "iam-cluster", null, false, false, null,
Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults());
assertEquals(clusterEnabled, member.isIamDatabaseAuthenticationEnabled());
assertEquals(clusterEnabled, rdsService.getDbInstance("iam-member").isIamDatabaseAuthenticationEnabled());
if (mockMode) {
verifyNoInteractions(proxyManager);
} else {
verify(proxyManager).startProxy(eq("rds-resource:" + member.getDbInstanceArn()), any(),
eq(clusterEnabled), anyInt(), any(), anyInt(), any(), any(), any(), any(), any(), any());
}
}
@Test
void createDbInstanceLeavesPostgresIamTokensUnboundWhenTheBindingIsTurnedOff() {
when(rdsConfig.iamTokenEndpointBinding()).thenReturn(false);