mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(rds): rotate cluster managed credentials and secret versions together (#7003)
* fix(rds): rotate cluster managed credentials and secret versions together
* test(rds): load the PostgreSQL driver before the first DriverManager call
DriverManager only offers drivers the caller's class loader can see. After a
Quarkus restart, the first getConnection in
RdsPostgresStartupParametersIntegrationTest found none ("No suitable driver
found"), which has been failing CI shard 1 on main. Load PgJDBC through the
test's own loader first, as RdsBackendEndpointRefreshIntegrationTest already
does, and do the same in the new managed-password rotation Docker test.
---------
Co-authored-by: Priamo Germosen <priamo.germosen@starling.co>
This commit is contained in:
1 parent
955a935bad
commit
83ec0b82c3
8 files changed
+475
-9
No files matched your search
+91
@@ -0,0 +1,91 @@
|
||||
package io.github.hectorvent.floci.services.rds;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.rds.RdsClient;
|
||||
import software.amazon.awssdk.services.rds.model.DBCluster;
|
||||
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
|
||||
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
|
||||
|
||||
import java.net.URI;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.RdsRequests.assumeDocker;
|
||||
import static io.github.hectorvent.floci.testing.RdsRequests.rdsClient;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@QuarkusTest
|
||||
@Tag("docker")
|
||||
class RdsManagedPasswordRotationDockerIntegrationTest {
|
||||
|
||||
/**
|
||||
* DriverManager only hands out a driver the caller's class loader can see. After a Quarkus
|
||||
* restart the first connection would find none, so PgJDBC is loaded through this test's loader first.
|
||||
*/
|
||||
@BeforeEach
|
||||
void registerPostgresDriver() throws ClassNotFoundException {
|
||||
Class.forName("org.postgresql.Driver");
|
||||
}
|
||||
|
||||
@Test
|
||||
void freshPostgresConnectionsUseTheRotatedManagedSecret() throws Exception {
|
||||
assumeDocker();
|
||||
String id = "sql-rotate-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
try (RdsClient rds = rdsClient("us-east-1", "000000000000");
|
||||
SecretsManagerClient secrets = SecretsManagerClient.builder()
|
||||
.endpointOverride(URI.create("http://localhost:" + RestAssured.port))
|
||||
.region(Region.US_EAST_1).httpClientBuilder(UrlConnectionHttpClient.builder())
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
|
||||
.build()) {
|
||||
DBCluster cluster = rds.createDBCluster(request -> request.dbClusterIdentifier(id).engine("aurora-postgresql")
|
||||
.engineVersion("16.4").masterUsername("clusteradmin").databaseName("appdb")
|
||||
.manageMasterUserPassword(true)).dbCluster();
|
||||
try {
|
||||
rds.createDBInstance(request -> request.dbInstanceIdentifier(id + "-member").dbClusterIdentifier(id)
|
||||
.engine("aurora-postgresql").dbInstanceClass("db.r5.large"));
|
||||
try {
|
||||
String arn = cluster.masterUserSecret().secretArn();
|
||||
GetSecretValueResponse before = secrets.getSecretValue(request -> request.secretId(arn));
|
||||
String oldPassword = password(before);
|
||||
String url = "jdbc:postgresql://127.0.0.1:" + cluster.port()
|
||||
+ "/appdb?connectTimeout=5&socketTimeout=5";
|
||||
verifyLogin(url, oldPassword);
|
||||
rds.modifyDBCluster(request -> request.dbClusterIdentifier(id)
|
||||
.rotateMasterUserPassword(true).applyImmediately(true));
|
||||
GetSecretValueResponse after = secrets.getSecretValue(request -> request.secretId(arn));
|
||||
assertNotEquals(before.versionId(), after.versionId());
|
||||
verifyLogin(url, password(after));
|
||||
SQLException refused = assertThrows(SQLException.class, () -> verifyLogin(url, oldPassword));
|
||||
assertEquals("28P01", refused.getSQLState());
|
||||
} finally {
|
||||
rds.deleteDBInstance(request -> request.dbInstanceIdentifier(id + "-member").skipFinalSnapshot(true));
|
||||
}
|
||||
} finally {
|
||||
rds.deleteDBCluster(request -> request.dbClusterIdentifier(id).skipFinalSnapshot(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String password(GetSecretValueResponse response) throws Exception {
|
||||
return new ObjectMapper().readTree(response.secretString()).path("password").asText();
|
||||
}
|
||||
|
||||
private static void verifyLogin(String url, String password) throws SQLException {
|
||||
try (Connection connection = DriverManager.getConnection(url, "clusteradmin", password)) {
|
||||
assertEquals(1, connection.createStatement().executeQuery("select 1").getMetaData().getColumnCount());
|
||||
}
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package io.github.hectorvent.floci.services.rds;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.testing.RdsMockProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.rds.RdsClient;
|
||||
import software.amazon.awssdk.services.rds.model.DBCluster;
|
||||
import software.amazon.awssdk.services.rds.model.RdsException;
|
||||
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
|
||||
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.RdsRequests.rdsClient;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(RdsMockProfile.class)
|
||||
class RdsManagedPasswordRotationIntegrationTest {
|
||||
|
||||
@Inject
|
||||
RdsService service;
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"aurora-postgresql,us-east-1,771661000001", "aurora-mysql,eu-west-2,771661000002",
|
||||
"aurora-postgresql,cn-north-1,771661000003", "aurora-mysql,us-gov-west-1,771661000004"})
|
||||
void sdkRotationPublishesMatchingCurrentAndPreviousCredentials(String engine, String region, String account)
|
||||
throws Exception {
|
||||
String id = "rotate-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
try (RdsClient rds = rdsClient(region, account); SecretsManagerClient secrets = secrets(region, account)) {
|
||||
DBCluster created = rds.createDBCluster(request -> request.dbClusterIdentifier(id).engine(engine)
|
||||
.masterUsername("clusteradmin").manageMasterUserPassword(true)).dbCluster();
|
||||
String arn = created.masterUserSecret().secretArn();
|
||||
try {
|
||||
GetSecretValueResponse before = secrets.getSecretValue(request -> request.secretId(arn));
|
||||
rds.modifyDBCluster(request -> request.dbClusterIdentifier(id).rotateMasterUserPassword(false));
|
||||
assertEquals(before.versionId(), secrets.getSecretValue(request -> request.secretId(arn)).versionId());
|
||||
|
||||
rds.createDBInstance(request -> request.dbInstanceIdentifier(id + "-member").dbClusterIdentifier(id)
|
||||
.engine(engine).dbInstanceClass("db.r5.large"));
|
||||
try {
|
||||
DBCluster rotated = rds.modifyDBCluster(request -> request.dbClusterIdentifier(id)
|
||||
.rotateMasterUserPassword(true).applyImmediately(true)).dbCluster();
|
||||
assertEquals(arn, rotated.masterUserSecret().secretArn());
|
||||
assertEquals("active", rotated.masterUserSecret().secretStatus());
|
||||
GetSecretValueResponse after = secrets.getSecretValue(request -> request.secretId(arn));
|
||||
assertNotEquals(before.versionId(), after.versionId());
|
||||
JsonNode oldValue = new ObjectMapper().readTree(before.secretString());
|
||||
JsonNode newValue = new ObjectMapper().readTree(after.secretString());
|
||||
assertTrue(!oldValue.path("password").equals(newValue.path("password")), "password must change");
|
||||
assertEquals("clusteradmin", newValue.path("username").asText());
|
||||
assertEquals(before.versionId(), secrets.getSecretValue(request -> request.secretId(arn)
|
||||
.versionStage("AWSPREVIOUS")).versionId());
|
||||
String password = newValue.path("password").asText();
|
||||
RequestScopes.runAs(account, region, () -> {
|
||||
assertTrue(password.equals(service.getDbCluster(id, region).getMasterPassword()));
|
||||
assertTrue(password.equals(service.getDbInstance(id + "-member", region).getMasterPassword()));
|
||||
});
|
||||
RdsException deferred = assertThrows(RdsException.class, () -> rds.modifyDBCluster(request -> request
|
||||
.dbClusterIdentifier(id).rotateMasterUserPassword(true).applyImmediately(false)));
|
||||
assertEquals(400, deferred.statusCode());
|
||||
assertEquals(after.versionId(), secrets.getSecretValue(request -> request.secretId(arn)).versionId());
|
||||
} finally {
|
||||
rds.deleteDBInstance(request -> request.dbInstanceIdentifier(id + "-member").skipFinalSnapshot(true));
|
||||
}
|
||||
} finally {
|
||||
rds.deleteDBCluster(request -> request.dbClusterIdentifier(id).skipFinalSnapshot(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"true", "false"})
|
||||
void sdkRejectsRotationWithoutAnExistingManagedSecret(boolean enableManagement) {
|
||||
String id = "unmanaged-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
try (RdsClient rds = rdsClient("us-east-1", "771661000005")) {
|
||||
rds.createDBCluster(request -> request.dbClusterIdentifier(id).engine("aurora-postgresql")
|
||||
.masterUsername("clusteradmin").masterUserPassword("SyntheticPassword!"));
|
||||
try {
|
||||
RdsException error = assertThrows(RdsException.class, () -> rds.modifyDBCluster(request -> request
|
||||
.dbClusterIdentifier(id).rotateMasterUserPassword(true).applyImmediately(true)
|
||||
.manageMasterUserPassword(enableManagement ? true : null)));
|
||||
assertEquals(400, error.statusCode());
|
||||
} finally {
|
||||
rds.deleteDBCluster(request -> request.dbClusterIdentifier(id).skipFinalSnapshot(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static SecretsManagerClient secrets(String region, String account) {
|
||||
return SecretsManagerClient.builder().endpointOverride(URI.create("http://localhost:" + RestAssured.port))
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder()).region(Region.of(region))
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test")))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+9
@@ -39,6 +39,15 @@ class RdsPostgresStartupParametersIntegrationTest {
|
||||
assumeDocker();
|
||||
}
|
||||
|
||||
/**
|
||||
* DriverManager only hands out a driver the caller's class loader can see. After a Quarkus
|
||||
* restart the first connection would find none, so PgJDBC is loaded through this test's loader first.
|
||||
*/
|
||||
@BeforeEach
|
||||
void registerPostgresDriver() throws ClassNotFoundException {
|
||||
Class.forName("org.postgresql.Driver");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientStartupParametersApplyToTheSession() throws Exception {
|
||||
String dbId = "startup-params-" + Long.toString(System.nanoTime(), 36);
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package io.github.hectorvent.floci.services.secretsmanager;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
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.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ManagedSecretImmediateRotationServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void publicationFailureRestoresBackendVersionLabelsAndAllowsRetry() {
|
||||
FailingStore store = new FailingStore();
|
||||
SecretsManagerService service = service(store);
|
||||
try {
|
||||
Secret secret = create(service);
|
||||
String previous = secret.getCurrentVersionId();
|
||||
AtomicReference<String> backend = new AtomicReference<>("old");
|
||||
store.failNext = true;
|
||||
assertThrows(IllegalStateException.class, () -> service.rotateManagedSecretAfter(secret.getArn(), "rds",
|
||||
REGION, () -> { backend.set("new"); return "new"; }, () -> backend.set("old")));
|
||||
assertEquals("old", backend.get());
|
||||
assertEquals(previous, secret.getCurrentVersionId());
|
||||
assertEquals(List.of("AWSCURRENT"), secret.getVersions().get(previous).getVersionStages());
|
||||
assertEquals(1, secret.getVersions().size());
|
||||
assertNull(secret.getLastRotatedDate());
|
||||
|
||||
service.rotateManagedSecretAfter(secret.getArn(), "rds", REGION,
|
||||
() -> { backend.set("new"); return "new"; }, () -> backend.set("old"));
|
||||
assertEquals("new", backend.get());
|
||||
assertNotEquals(previous, secret.getCurrentVersionId());
|
||||
assertEquals(previous, service.getSecretValue(secret.getArn(), null, "AWSPREVIOUS", REGION).getVersionId());
|
||||
} finally {
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void backendFailureLeavesTheCurrentVersionUntouched() {
|
||||
SecretsManagerService service = service(new FailingStore());
|
||||
try {
|
||||
Secret secret = create(service);
|
||||
String previous = secret.getCurrentVersionId();
|
||||
assertThrows(IllegalStateException.class, () -> service.rotateManagedSecretAfter(secret.getArn(), "rds",
|
||||
REGION, () -> { throw new IllegalStateException("backend refused"); },
|
||||
() -> fail("backend did not accept a change")));
|
||||
assertEquals(previous, secret.getCurrentVersionId());
|
||||
assertEquals(1, secret.getVersions().size());
|
||||
assertDoesNotThrow(() -> service.putSecretValue(secret.getArn(), "retry", null, null, REGION, null));
|
||||
} finally {
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentWritesAreRefusedUntilTheOwnerPublishesItsCredential() throws Exception {
|
||||
SecretsManagerService service = service(new FailingStore());
|
||||
CountDownLatch changing = new CountDownLatch(1);
|
||||
CountDownLatch finish = new CountDownLatch(1);
|
||||
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
|
||||
Secret secret = create(service);
|
||||
Future<?> rotation = executor.submit(() -> service.rotateManagedSecretAfter(secret.getArn(), "rds",
|
||||
REGION, () -> {
|
||||
changing.countDown();
|
||||
try {
|
||||
assertTrue(finish.await(5, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(error);
|
||||
}
|
||||
return "new";
|
||||
}, () -> fail("unexpected rollback")));
|
||||
try {
|
||||
assertTrue(changing.await(5, TimeUnit.SECONDS));
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.putSecretValue(secret.getArn(), "racing", null, null, REGION, null));
|
||||
assertThrows(AwsException.class, () -> service.deleteSecret(secret.getArn(), null, true, REGION));
|
||||
assertThrows(AwsException.class, () -> service.rotateManagedSecretAfter(secret.getArn(), "rds", REGION,
|
||||
() -> "racing", () -> fail("racing operation must not run")));
|
||||
} finally {
|
||||
finish.countDown();
|
||||
}
|
||||
rotation.get(5, TimeUnit.SECONDS);
|
||||
assertEquals("new", service.getSecretValue(secret.getArn(), null, null, REGION).getSecretString());
|
||||
} finally {
|
||||
finish.countDown();
|
||||
service.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private static SecretsManagerService service(FailingStore store) {
|
||||
return new SecretsManagerService(store, 30, new RegionResolver(REGION, "000000000000"),
|
||||
null, new ObjectMapper(), null, List.of());
|
||||
}
|
||||
|
||||
private static Secret create(SecretsManagerService service) {
|
||||
return service.createSecret("managed", "old", null, null, null, null, "rds", REGION);
|
||||
}
|
||||
|
||||
private static final class FailingStore extends InMemoryStorage<String, Secret> {
|
||||
private boolean failNext;
|
||||
|
||||
@Override
|
||||
public synchronized void put(String key, Secret value) {
|
||||
if (failNext) {
|
||||
failNext = false;
|
||||
throw new IllegalStateException("publication failed");
|
||||
}
|
||||
super.put(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user