mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(dsql): serve each cluster's database on the DSQL endpoint (#6102)
* feat(dsql): serve each cluster's database on the DSQL endpoint Each Aurora DSQL cluster gets a PostgreSQL 16 database in a Docker container, set up as DSQL's (the role admin owning public, repeatable read), and every cluster is served on one TLS endpoint where the server name picks the cluster. A connection is admitted as DSQL admits it, measured on AWS: an IAM token for the endpoint, DbConnectAdmin for admin, 5 seconds of grace past expiry, a long-term key only in its own account, IAM enforcement with the account's SCPs, and DSQL's SQLSTATE, text and hint for every refusal. A role other than admin is refused as an unmapped one, since role mappings come with AWS IAM GRANT in the next part. The startup is read as DSQL reads it: a dotted parameter is refused, and of options only -c name=value counts, the first for a name. The cluster is CREATING until its database answers; a multi-Region peer is ACTIVE after peering only once its database answers. A start that fails after the container exists removes it, a deletion Docker cannot finish leaves the cluster DELETING for the next start, and whether a cluster is wanted and its route change under one lock, so a deletion racing a start leaves no route. The data plane was first one PR; it is split by layer at the maintainer's request: this part (transport and admin), then AWS IAM GRANT and the other roles, then DSQL's dialect and limits. * refactor(postgres): speak PostgreSQL's wire protocol through one shared helper The DSQL endpoint brought a third copy of the startup parsing, message framing and ErrorResponse building that the RDS proxy's PostgresProtocolHandler and Redshift's PostgresWireDecoder each carried. They now go through core.common.PostgresWire: the startup packet and its parameters, reading and writing a message with its checked length, and the fields of an ErrorResponse or NoticeResponse. The length refusals keep the RDS proxy's wording, which its tests assert; Redshift's oversized-message refusal now reads the same way. Also from the review: the DSQL integration test makes its IAM users with EnforcementFixtures.createUser, which removes them after the test; the service test shares one ready-at-once provision stub; and every exception the endpoint and session swallow is named ignored, with the reason it is safe.
This commit is contained in:
1 parent
d2ee9f46a0
commit
f2b62fbbec
28 files changed
+2172
-324
No files matched your search
@@ -0,0 +1,109 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class PostgresWireTest {
|
||||
|
||||
@Test
|
||||
void aMessageIsFramedWithALengthThatCountsItself() throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
PostgresWire.write(out, 'Q', PostgresWire.cStringBytes("SELECT 1"));
|
||||
|
||||
byte[] framed = out.toByteArray();
|
||||
assertArrayEquals(PostgresWire.frame('Q', PostgresWire.cStringBytes("SELECT 1")), framed);
|
||||
assertEquals('Q', framed[0]);
|
||||
assertEquals(4 + 9, PostgresWire.int32(framed, 1));
|
||||
|
||||
PostgresWire.Message read = PostgresWire.read(new ByteArrayInputStream(framed), 1024, "message");
|
||||
assertEquals('Q', read.type());
|
||||
assertEquals("SELECT 1", PostgresWire.cString(read.body(), 0).value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMessageIsWrittenFromItsPartsInOrder() throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
PostgresWire.write(out, 'p', "secret".getBytes(), new byte[]{0});
|
||||
|
||||
assertArrayEquals(PostgresWire.frame('p', PostgresWire.cStringBytes("secret")), out.toByteArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLengthOutsideItsBoundsIsRefusedNamingThePacket() {
|
||||
IOException low = assertThrows(IOException.class, () -> PostgresWire.checkedLength(3, 4, 10, "backend message"));
|
||||
assertEquals("PostgreSQL backend message length is below the 4 byte minimum: 3", low.getMessage());
|
||||
IOException high = assertThrows(IOException.class, () -> PostgresWire.checkedLength(11, 4, 10, "backend message"));
|
||||
assertEquals("PostgreSQL backend message length exceeds the 10 byte limit: 11", high.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStreamThatEndsMidMessageIsAnEof() {
|
||||
byte[] truncated = {'Q', 0, 0, 0, 9, 'S'};
|
||||
|
||||
assertThrows(EOFException.class, () ->
|
||||
PostgresWire.read(new ByteArrayInputStream(truncated), 1024, "message"));
|
||||
assertThrows(EOFException.class, () ->
|
||||
PostgresWire.read(new ByteArrayInputStream(new byte[0]), 1024, "message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStartupMessageCarriesItsParametersInOrderAndReadsBack() throws IOException {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("user", "admin");
|
||||
parameters.put("database", "postgres");
|
||||
parameters.put("options", "-c search_path=public");
|
||||
|
||||
byte[] packet = PostgresWire.startupMessage(parameters);
|
||||
PostgresWire.Startup startup = PostgresWire.readStartup(new ByteArrayInputStream(packet), 10_000,
|
||||
"startup message");
|
||||
|
||||
assertEquals(PostgresWire.PROTOCOL_3, startup.code());
|
||||
Map<String, String> read = PostgresWire.startupParameters(startup.body());
|
||||
assertEquals(parameters, read);
|
||||
assertEquals(List.of("user", "database", "options"), List.copyOf(read.keySet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anSslRequestIsAStartupPacketWithNoBody() throws IOException {
|
||||
byte[] request = {0, 0, 0, 8, 4, (byte) 0xD2, 0x16, 0x2F};
|
||||
|
||||
PostgresWire.Startup startup = PostgresWire.readStartup(new ByteArrayInputStream(request), 10_000,
|
||||
"startup message");
|
||||
|
||||
assertEquals(PostgresWire.SSL_REQUEST, startup.code());
|
||||
assertEquals(0, startup.body().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupParametersStopAtTheEmptyNameOrAnUnterminatedOne() {
|
||||
byte[] body = {'u', 's', 'e', 'r', 0, 'a', 0, 0, 'x', 0, 'y', 0};
|
||||
byte[] unterminated = {'u', 's', 'e', 'r', 0, 'a', 0, 'd', 'b'};
|
||||
|
||||
assertEquals(Map.of("user", "a"), PostgresWire.startupParameters(body));
|
||||
assertEquals(Map.of("user", "a"), PostgresWire.startupParameters(unterminated));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anErrorResponseKeepsItsFieldsInOrder() {
|
||||
Map<Character, String> fields = new LinkedHashMap<>();
|
||||
fields.put('S', "FATAL");
|
||||
fields.put('C', "28000");
|
||||
fields.put('M', "access denied");
|
||||
|
||||
byte[] framed = PostgresWire.frame('E', PostgresWire.fields(fields));
|
||||
|
||||
assertEquals(fields, PostgresWire.parseFields(framed, 5));
|
||||
assertEquals(List.of('S', 'C', 'M'), List.copyOf(PostgresWire.parseFields(framed, 5).keySet()));
|
||||
}
|
||||
}
|
||||
+17
@@ -10,6 +10,7 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -153,6 +154,22 @@ class SigV4RequestValidatorTest {
|
||||
assertFalse(validate(iamService, token.replace("DBUser=app%20user", "DBUser=app%2Buser")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateTakesAnExpiredTokenOnlyWithinTheGraceItIsGiven() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDDSQL", "secret-dsql");
|
||||
String token = SigV4TokenTestHelper.createDsqlToken("abc.dsql.eu-west-1.localhost.floci.io", "eu-west-1",
|
||||
"DbConnectAdmin", "AKIDDSQL", "secret-dsql", Instant.now().minusSeconds(63), 60, null);
|
||||
String rawQuery = token.substring(token.indexOf('?') + 1);
|
||||
SigV4RequestValidator validator = new SigV4RequestValidator(iamService);
|
||||
|
||||
assertTrue(validator.validate(rawQuery, "abc.dsql.eu-west-1.localhost.floci.io", "DbConnectAdmin", "DBUser",
|
||||
false, null, "DSQL IAM token", null, Duration.ofSeconds(5)));
|
||||
assertFalse(validator.validate(rawQuery, "abc.dsql.eu-west-1.localhost.floci.io", "DbConnectAdmin", "DBUser",
|
||||
false, null, "DSQL IAM token", null, Duration.ZERO));
|
||||
assertFalse(validator.validate(rawQuery, "abc.dsql.eu-west-1.localhost.floci.io", "DbConnect", "DBUser",
|
||||
false, null, "DSQL IAM token", null, Duration.ofSeconds(5)));
|
||||
}
|
||||
|
||||
private static boolean validate(IamService iamService, String token) {
|
||||
String rawQuery = token.substring(token.indexOf('?') + 1);
|
||||
return new SigV4RequestValidator(iamService).validate(
|
||||
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
package io.github.hectorvent.floci.services.dsql;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.github.hectorvent.floci.services.dsql.dataplane.DsqlEndpoint;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.postgresql.util.PSQLException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* Aurora DSQL's data plane against a real PostgreSQL container: a client connects to the cluster
|
||||
* endpoint with TLS and an IAM token, with the refusals measured on AWS (eu-west-1, 2026-10-16).
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(DsqlDatabasesProfile.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
@Tag("docker")
|
||||
class DsqlDataPlaneIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111122223333";
|
||||
private static final String REGION = "eu-west-1";
|
||||
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
|
||||
+ "/20261016/" + REGION + "/dsql/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
DsqlEndpoint endpoint;
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0")
|
||||
int httpPort;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
private String identifier;
|
||||
private String host;
|
||||
|
||||
@BeforeAll
|
||||
void createCluster() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
} catch (Exception e) {
|
||||
assumeTrue(false, "Docker is not available: " + e.getMessage());
|
||||
}
|
||||
identifier = dsql().body(Map.of("deletionProtectionEnabled", false))
|
||||
.post("/cluster").then().statusCode(200).extract().path("identifier");
|
||||
host = identifier + ".dsql." + REGION + ".localhost.floci.io";
|
||||
await().atMost(Duration.ofMinutes(3)).pollInterval(Duration.ofMillis(500)).until(() ->
|
||||
"ACTIVE".equals(dsql().get("/cluster/" + identifier).then().extract().path("status")));
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
void deleteCluster() {
|
||||
if (identifier != null) {
|
||||
dsql().delete("/cluster/" + identifier);
|
||||
await().atMost(Duration.ofMinutes(1)).until(() ->
|
||||
dsql().get("/cluster/" + identifier).then().extract().statusCode() == 404);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminConnectsWithAnAdminTokenToDsqlsDatabase() throws Exception {
|
||||
try (Connection connection = connect("admin", adminToken());
|
||||
Statement statement = connection.createStatement();
|
||||
ResultSet row = statement.executeQuery("SELECT current_user, current_setting('transaction_isolation'),"
|
||||
+ " (SELECT nspowner::regrole::text FROM pg_namespace WHERE nspname = 'public')")) {
|
||||
assertTrue(row.next());
|
||||
assertEquals("admin", row.getString(1));
|
||||
assertEquals("repeatable read", row.getString(2));
|
||||
assertEquals("admin", row.getString(3));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConnectionIsRefusedAsDsqlRefusesIt() throws Exception {
|
||||
PSQLException plain = assertThrows(PSQLException.class, () -> {
|
||||
Properties properties = properties("admin", adminToken());
|
||||
properties.setProperty("sslmode", "disable");
|
||||
DriverManager.getConnection(url(), properties).close();
|
||||
});
|
||||
assertEquals("unable to accept connection, SSL is mandatory. AWS Authentication is required.",
|
||||
plain.getServerErrorMessage().getMessage());
|
||||
assertEquals("08P01", plain.getSQLState());
|
||||
assertTrue(plain.getServerErrorMessage().getDetail().startsWith("Session Id: "));
|
||||
|
||||
PSQLException wrongAction = assertThrows(PSQLException.class, () ->
|
||||
connect("admin", token("DbConnect", "test", "test", Instant.now(), 900, null)).close());
|
||||
assertEquals("unable to accept connection, access denied", wrongAction.getServerErrorMessage().getMessage());
|
||||
assertEquals("08006", wrongAction.getSQLState());
|
||||
assertTrue(wrongAction.getServerErrorMessage().getDetail().startsWith("Session Id: "));
|
||||
assertEquals("Wrong user to action mapping. user: admin, action: DbConnect",
|
||||
wrongAction.getServerErrorMessage().getHint());
|
||||
|
||||
PSQLException expired = assertThrows(PSQLException.class, () -> connect("admin",
|
||||
token("DbConnectAdmin", "test", "test", Instant.now().minusSeconds(120), 60, null)).close());
|
||||
assertTrue(expired.getServerErrorMessage().getHint().startsWith("Signature expired: "),
|
||||
expired.getServerErrorMessage().getHint());
|
||||
|
||||
PSQLException garbage = assertThrows(PSQLException.class, () -> connect("admin", "not-a-token").close());
|
||||
assertEquals("unable to accept connection, access denied", garbage.getServerErrorMessage().getMessage());
|
||||
assertEquals(null, garbage.getServerErrorMessage().getHint());
|
||||
|
||||
PSQLException otherDatabase = assertThrows(PSQLException.class, () -> {
|
||||
Properties properties = properties("admin", adminToken());
|
||||
DriverManager.getConnection("jdbc:postgresql://127.0.0.1:" + endpoint.port() + "/other", properties)
|
||||
.close();
|
||||
});
|
||||
assertEquals("database \"other\" is not currently accepting connections",
|
||||
otherDatabase.getServerErrorMessage().getMessage());
|
||||
assertEquals("55000", otherDatabase.getSQLState());
|
||||
}
|
||||
|
||||
/** A role other than {@code admin} signs in only for an IAM role mapped to it, and none is. */
|
||||
@Test
|
||||
void aRoleOtherThanAdminIsRefusedAsAnUnmappedRole() throws Exception {
|
||||
try (Connection admin = connect("admin", adminToken()); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CREATE ROLE app_role WITH LOGIN");
|
||||
}
|
||||
|
||||
PSQLException unmapped = assertThrows(PSQLException.class, () ->
|
||||
connect("app_role", token("DbConnect", "test", "test", Instant.now(), 900, null)).close());
|
||||
assertEquals("28000", unmapped.getSQLState());
|
||||
assertEquals("unable to accept connection, access denied", unmapped.getServerErrorMessage().getMessage());
|
||||
assertTrue(unmapped.getServerErrorMessage().getDetail().startsWith("Session Id: "));
|
||||
|
||||
PSQLException adminAction = assertThrows(PSQLException.class, () ->
|
||||
connect("app_role", token("DbConnectAdmin", "test", "test", Instant.now(), 900, null)).close());
|
||||
assertEquals("08006", adminAction.getSQLState());
|
||||
assertEquals("Wrong user to action mapping. user: app_role, action: DbConnectAdmin",
|
||||
adminAction.getServerErrorMessage().getHint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStartupSettingIsReadAsDsqlReadsIt() throws Exception {
|
||||
for (String name : List.of("dsql.iam_session_user", "myapp.foo")) {
|
||||
Properties custom = properties("admin", adminToken());
|
||||
custom.setProperty("options", "-c " + name + "=x");
|
||||
PSQLException refused = assertThrows(PSQLException.class, () ->
|
||||
DriverManager.getConnection(url(), custom).close());
|
||||
assertEquals("42704", refused.getSQLState());
|
||||
assertEquals("unrecognized configuration parameter \"" + name + "\"",
|
||||
refused.getServerErrorMessage().getMessage());
|
||||
assertTrue(refused.getServerErrorMessage().getDetail().startsWith("Session Id: "));
|
||||
}
|
||||
|
||||
Properties unknown = properties("admin", adminToken());
|
||||
unknown.setProperty("options", "-c nosuch_parameter=1");
|
||||
PSQLException fromTheDatabase = assertThrows(PSQLException.class, () ->
|
||||
DriverManager.getConnection(url(), unknown).close());
|
||||
assertEquals("42704", fromTheDatabase.getSQLState());
|
||||
assertEquals("unrecognized configuration parameter \"nosuch_parameter\"",
|
||||
fromTheDatabase.getServerErrorMessage().getMessage());
|
||||
assertTrue(fromTheDatabase.getServerErrorMessage().getDetail().startsWith("Session Id: "));
|
||||
assertEquals(null, fromTheDatabase.getServerErrorMessage().getFile());
|
||||
|
||||
Properties ignored = properties("admin", adminToken());
|
||||
ignored.setProperty("options", "--search_path=elsewhere -c search_path=first -c search_path=second");
|
||||
try (Connection connection = DriverManager.getConnection(url(), ignored);
|
||||
Statement statement = connection.createStatement();
|
||||
ResultSet row = statement.executeQuery("SELECT current_setting('search_path')")) {
|
||||
assertTrue(row.next());
|
||||
assertEquals("first", row.getString(1));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A long-term key signs in to its own account's clusters and to no other account's, whichever
|
||||
* account is Floci's default: the cluster here is not in the default one.
|
||||
*/
|
||||
@Test
|
||||
void aLongTermKeySignsInOnlyToItsOwnAccountsClusters() throws Exception {
|
||||
EnforcementFixtures.UserCredentials own = accessKey(ACCOUNT);
|
||||
EnforcementFixtures.UserCredentials other = accessKey("000000000000");
|
||||
|
||||
connect("admin", token("DbConnectAdmin", own.accessKeyId(), own.secretAccessKey(), Instant.now(), 900,
|
||||
null)).close();
|
||||
PSQLException foreign = assertThrows(PSQLException.class, () -> connect("admin", token("DbConnectAdmin",
|
||||
other.accessKeyId(), other.secretAccessKey(), Instant.now(), 900, null)).close());
|
||||
assertEquals("08006", foreign.getSQLState());
|
||||
assertEquals("unable to accept connection, access denied", foreign.getServerErrorMessage().getMessage());
|
||||
}
|
||||
|
||||
/** A new IAM user's access key in {@code account}, removed with the user after the test. */
|
||||
private EnforcementFixtures.UserCredentials accessKey(String account) {
|
||||
return EnforcementFixtures.createUser(cleanup, httpPort, EnforcementFixtures.auth(account, "iam"),
|
||||
"dsql-" + System.nanoTime());
|
||||
}
|
||||
|
||||
private Connection connect(String user, String password) throws SQLException {
|
||||
return DriverManager.getConnection(url(), properties(user, password));
|
||||
}
|
||||
|
||||
private String url() {
|
||||
return "jdbc:postgresql://127.0.0.1:" + endpoint.port() + "/postgres";
|
||||
}
|
||||
|
||||
private static Properties properties(String user, String password) {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", user);
|
||||
properties.setProperty("password", password);
|
||||
properties.setProperty("sslmode", "require");
|
||||
properties.setProperty("sslfactory", "org.postgresql.ssl.NonValidatingFactory");
|
||||
return properties;
|
||||
}
|
||||
|
||||
private String adminToken() throws Exception {
|
||||
return token("DbConnectAdmin", "test", "test", Instant.now(), 900, null);
|
||||
}
|
||||
|
||||
private String token(String action, String accessKeyId, String secret, Instant at, int expires,
|
||||
String sessionToken) throws Exception {
|
||||
return SigV4TokenTestHelper.createDsqlToken(host, REGION, action, accessKeyId, secret, at, expires,
|
||||
sessionToken);
|
||||
}
|
||||
|
||||
private RequestSpecification dsql() {
|
||||
return given().port(httpPort).header("Authorization", AUTH).contentType("application/json");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.dsql;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Clusters with a real database in Docker, served on an ephemeral port. */
|
||||
public final class DsqlDatabasesProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.dsql.mock", "false", "floci.services.dsql.port", "0");
|
||||
}
|
||||
}
|
||||
@@ -12,15 +12,21 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -35,14 +41,21 @@ class DsqlServiceTest {
|
||||
private static final String ROOT = "arn:aws:iam::" + ACCOUNT + ":root";
|
||||
|
||||
private final DsqlPrincipals principals = mock(DsqlPrincipals.class);
|
||||
private final DsqlDataPlane dataPlane = mock(DsqlDataPlane.class);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final DsqlService service = new DsqlService(
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT),
|
||||
new RegionResolver(REGION, ACCOUNT), "localhost.floci.io", new DsqlDataPlane(), principals,
|
||||
new IamPolicyEvaluator(mapper), mapper);
|
||||
new RegionResolver(REGION, ACCOUNT), "localhost.floci.io", dataPlane, principals,
|
||||
new IamPolicyEvaluator(mapper), mapper, true);
|
||||
|
||||
@BeforeEach
|
||||
void caller() {
|
||||
// A database that is ready at once and gone at once, as with floci.services.dsql.mock.
|
||||
readyAtOnce(dataPlane);
|
||||
doAnswer(call -> {
|
||||
call.<Runnable>getArgument(1).run();
|
||||
return null;
|
||||
}).when(dataPlane).deprovision(any(), any());
|
||||
when(principals.caller()).thenReturn(CallerArns.accountRoot(ROOT, ACCOUNT));
|
||||
when(principals.exists(anyString())).thenAnswer(call -> call.getArgument(0, String.class).endsWith(":root"));
|
||||
}
|
||||
@@ -161,6 +174,37 @@ class DsqlServiceTest {
|
||||
service.getCluster("eu-west-3", second.getIdentifier()).getLinkedClusterArns());
|
||||
}
|
||||
|
||||
/**
|
||||
* Peering makes a cluster ACTIVE only once its database answers: until then it is CREATING, and
|
||||
* one whose database failed is FAILED, not left waiting.
|
||||
*/
|
||||
@Test
|
||||
void aPeerIsActiveOnlyOnceItsDatabaseAnswers() {
|
||||
DsqlDataPlane slow = mock(DsqlDataPlane.class);
|
||||
Map<String, Consumer<Boolean>> starting = new HashMap<>();
|
||||
doAnswer(call -> {
|
||||
starting.put(call.<DsqlCluster>getArgument(0).getIdentifier(), call.getArgument(1));
|
||||
return null;
|
||||
}).when(slow).provision(any(), any());
|
||||
DsqlService peers = service(new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT), slow);
|
||||
DsqlCluster first = peers.createCluster(REGION, false, null, null, null, "eu-west-2", null, null, false);
|
||||
DsqlCluster second = peers.createCluster("eu-west-3", false, null, null, null, "eu-west-2", null, null, false);
|
||||
DsqlCluster failing = peers.createCluster(REGION, false, null, null, null, "eu-west-2", null, null, false);
|
||||
|
||||
starting.get(first.getIdentifier()).accept(true);
|
||||
starting.get(failing.getIdentifier()).accept(false);
|
||||
assertEquals(DsqlService.PENDING_SETUP, peers.getCluster(REGION, first.getIdentifier()).getStatus());
|
||||
assertEquals(DsqlService.FAILED, peers.getCluster(REGION, failing.getIdentifier()).getStatus());
|
||||
|
||||
peers.updateCluster(REGION, first.getIdentifier(), null, null, null, List.of(second.getArn()));
|
||||
peers.updateCluster("eu-west-3", second.getIdentifier(), null, null, null, List.of(first.getArn()));
|
||||
assertEquals(DsqlService.ACTIVE, peers.getCluster(REGION, first.getIdentifier()).getStatus());
|
||||
assertEquals(DsqlService.CREATING, peers.getCluster("eu-west-3", second.getIdentifier()).getStatus());
|
||||
|
||||
starting.get(second.getIdentifier()).accept(true);
|
||||
assertEquals(DsqlService.ACTIVE, peers.getCluster("eu-west-3", second.getIdentifier()).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateLeavesWhatItDoesNotNameAsItWas() {
|
||||
DsqlCluster cluster = service.createCluster(REGION, false, "arn:aws:kms:eu-west-1:" + ACCOUNT + ":key/k",
|
||||
@@ -198,6 +242,44 @@ class DsqlServiceTest {
|
||||
assertNull(tooMany.getExtendedData());
|
||||
}
|
||||
|
||||
/**
|
||||
* A restart over the same storage starts every cluster's database again, and finishes a
|
||||
* deletion the stop interrupted.
|
||||
*/
|
||||
@Test
|
||||
void aRestartBringsEveryClusterBackAndFinishesAnInterruptedDeletion() {
|
||||
AccountAwareStorageBackend<DsqlCluster> storage =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT);
|
||||
DsqlDataPlane stopping = mock(DsqlDataPlane.class);
|
||||
readyAtOnce(stopping);
|
||||
DsqlService before = service(storage, stopping);
|
||||
DsqlCluster kept = before.createCluster(REGION, false, null, null, null, null, null, null, false);
|
||||
DsqlCluster deleting = before.createCluster(REGION, false, null, null, null, null, null, null, false);
|
||||
// The stop comes before the database is gone, so the cluster stays DELETING.
|
||||
before.deleteCluster(REGION, deleting.getIdentifier());
|
||||
|
||||
DsqlService after = service(storage, dataPlane);
|
||||
after.onStart(null);
|
||||
|
||||
verify(dataPlane).provision(argThat(cluster -> kept.getIdentifier().equals(cluster.getIdentifier())), any());
|
||||
verify(dataPlane).deprovision(argThat(cluster -> deleting.getIdentifier().equals(cluster.getIdentifier())), any());
|
||||
assertEquals(DsqlService.ACTIVE, after.getCluster(REGION, kept.getIdentifier()).getStatus());
|
||||
assertThrows(AwsException.class, () -> after.getCluster(REGION, deleting.getIdentifier()));
|
||||
}
|
||||
|
||||
/** Makes {@code plane} start every cluster's database at once. */
|
||||
private static void readyAtOnce(DsqlDataPlane plane) {
|
||||
doAnswer(call -> {
|
||||
call.<Consumer<Boolean>>getArgument(1).accept(true);
|
||||
return null;
|
||||
}).when(plane).provision(any(), any());
|
||||
}
|
||||
|
||||
private DsqlService service(AccountAwareStorageBackend<DsqlCluster> storage, DsqlDataPlane plane) {
|
||||
return new DsqlService(storage, new RegionResolver(REGION, ACCOUNT), "localhost.floci.io", plane, principals,
|
||||
new IamPolicyEvaluator(mapper), mapper, true);
|
||||
}
|
||||
|
||||
private DsqlCluster cluster() {
|
||||
return service.createCluster(REGION, false, null, null, null, null, null, null, false);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package io.github.hectorvent.floci.services.dsql.dataplane;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class DsqlSessionTest {
|
||||
|
||||
@Test
|
||||
void startupOptionsCountOnlyTheirFirstDashCSettingForEachName() {
|
||||
Map<String, String> settings = DsqlSession.optionSettings(
|
||||
"--dsql.iam_session_user=spoofed -c search_path=first -csearch_path=x -c Search_Path=second"
|
||||
+ " -c TimeZone=UTC -B 100 garbage -c application_name -c");
|
||||
|
||||
assertEquals(Map.of("search_path", "first", "TimeZone", "UTC"), settings);
|
||||
assertEquals(List.of("search_path", "TimeZone"), List.copyOf(settings.keySet()));
|
||||
assertEquals(Map.of(), DsqlSession.optionSettings(null));
|
||||
assertEquals(Map.of(), DsqlSession.optionSettings(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupOptionsTakeNoEscapesAndReachTheDatabaseEscaped() {
|
||||
Map<String, String> settings = DsqlSession.optionSettings("-c search_path=a\\ b");
|
||||
|
||||
assertEquals(Map.of("search_path", "a\\"), settings);
|
||||
assertEquals("-c search_path=a\\\\", DsqlSession.backendOptions(settings));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCustomParameterInTheStartupIsTheOneRefused() {
|
||||
assertEquals("myapp.foo", DsqlSession.customParameter(Map.of("myapp.foo", "x"), Map.of("user", "admin")));
|
||||
assertEquals("dsql.iam_session_user", DsqlSession.customParameter(Map.of(),
|
||||
Map.of("user", "admin", "dsql.iam_session_user", "spoofed")));
|
||||
assertEquals(null, DsqlSession.customParameter(Map.of("search_path", "public"),
|
||||
Map.of("user", "admin", "options", "-c search_path=public")));
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
|
||||
import io.github.hectorvent.floci.core.common.PostgresWire;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
|
||||
@@ -1771,7 +1772,7 @@ class PostgresProtocolHandlerTest {
|
||||
int length = in.readInt();
|
||||
assertEquals(STARTUP_PROTOCOL_VERSION, in.readInt());
|
||||
byte[] payload = in.readNBytes(length - 8);
|
||||
backendStartup.set(PostgresProtocolHandler.parseStartupParams(payload));
|
||||
backendStartup.set(PostgresWire.startupParameters(payload));
|
||||
|
||||
out.writeByte('R');
|
||||
out.writeInt(8);
|
||||
@@ -2137,7 +2138,7 @@ class PostgresProtocolHandlerTest {
|
||||
int proto = in.readInt();
|
||||
assertEquals(STARTUP_PROTOCOL_VERSION, proto);
|
||||
byte[] payload = in.readNBytes(length - 8);
|
||||
backendStartup.set(PostgresProtocolHandler.parseStartupParams(payload));
|
||||
backendStartup.set(PostgresWire.startupParameters(payload));
|
||||
backendDatabase.set(backendStartup.get().get("database"));
|
||||
|
||||
out.writeByte('R');
|
||||
|
||||
+2
-1
@@ -229,7 +229,8 @@ class PostgresWireDecoderTest {
|
||||
byte[] hostile = new byte[]{'Q', 0x7F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
|
||||
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(hostile));
|
||||
IOException ex = assertThrows(IOException.class, decoder::nextMessage);
|
||||
assertTrue(ex.getMessage().contains("Refusing"), ex.getMessage());
|
||||
assertTrue(ex.getMessage().contains("exceeds the " + PostgresWireDecoder.MAX_MESSAGE_BYTES + " byte limit"),
|
||||
ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -116,6 +116,29 @@ public final class SigV4TokenTestHelper {
|
||||
"rds-db", timestamp, expiresSeconds, params, Map.of("host", host + ":" + port));
|
||||
}
|
||||
|
||||
/**
|
||||
* An Aurora DSQL token, shaped as the SDKs' DSQL signers shape it:
|
||||
* {@code <endpoint>/?Action=DbConnectAdmin&...}, signing the endpoint's host without a port.
|
||||
*/
|
||||
public static String createDsqlToken(
|
||||
String endpoint,
|
||||
String region,
|
||||
String action,
|
||||
String accessKeyId,
|
||||
String secretKey,
|
||||
Instant timestamp,
|
||||
int expiresSeconds,
|
||||
String sessionToken
|
||||
) throws Exception {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("Action", action);
|
||||
if (sessionToken != null) {
|
||||
params.put("X-Amz-Security-Token", sessionToken);
|
||||
}
|
||||
return signToken(endpoint, null, accessKeyId, secretKey, region, "dsql", timestamp, expiresSeconds,
|
||||
params, Map.of("host", endpoint));
|
||||
}
|
||||
|
||||
/**
|
||||
* An RDS token that carries the signer's credential under a percent-encoded parameter name
|
||||
* ({@code X-Amz%2DCredential}) and, after it, a second {@code X-Amz-Credential} naming
|
||||
|
||||
Reference in new issue
Block a user