mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(rds): load the token role's ALTER ROLE defaults into IAM sessions (#5344)
* fix(rds): load the token role's ALTER ROLE defaults into IAM sessions * fix(rds): open IAM sessions with the role's defaults as startup options so RESET keeps them
This commit is contained in:
1 parent
1230aec424
commit
e61b66fb22
4 files changed
+729
-32
No files matched your search
+336
-4
@@ -32,6 +32,7 @@ import java.security.KeyStore;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -712,8 +713,9 @@ class PostgresProtocolHandlerTest {
|
||||
assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
|
||||
}
|
||||
|
||||
assertEquals(List.of("user", "database"), List.copyOf(backendStartup.get().keySet()),
|
||||
assertEquals(List.of("user", "database", "client_encoding"), List.copyOf(backendStartup.get().keySet()),
|
||||
"client startup parameters are not applied to the master session");
|
||||
assertEquals("UTF8", backendStartup.get().get("client_encoding"));
|
||||
assertEquals("SELECT pg_catalog.set_config(E'search_path', E'app', false), "
|
||||
+ "pg_catalog.set_config(E'statement_timeout', E'5s', false), "
|
||||
+ "pg_catalog.set_config(E'application_name', E'svc', false)",
|
||||
@@ -880,6 +882,203 @@ class PostgresProtocolHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamSessionReopensTheBackendWithTheRoleDefaultsAsStartupOptions() throws Exception {
|
||||
List<String> tried = new ArrayList<>();
|
||||
AtomicReference<Map<String, String>> reopenedStartup = new AtomicReference<>();
|
||||
AtomicReference<String> handover = new AtomicReference<>();
|
||||
List<String> afterHandover = new ArrayList<>();
|
||||
|
||||
try (ServerSocket lookupServer = new ServerSocket(0);
|
||||
ServerSocket backendServer = new ServerSocket(0);
|
||||
ServerSocket clientServer = new ServerSocket(0)) {
|
||||
|
||||
Thread lookupThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
mockBackendRoleDefaultsLookup(lookupServer, List.of(
|
||||
new String[] {"temp_file_limit", "1GB"},
|
||||
new String[] {"no_such_parameter", "on"},
|
||||
new String[] {"role", "reader"},
|
||||
new String[] {"session_authorization", "dbadmin"},
|
||||
new String[] {"client_encoding", "LATIN1"},
|
||||
new String[] {"search_path", "app, public"}), tried);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
Thread backendThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
mockBackendRoleSwitch(backendServer, reopenedStartup, handover, "approle", true, (in, out) -> {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
afterHandover.add(readSimpleQuery(in));
|
||||
writeCommandComplete(out, "SELECT 1");
|
||||
writeReadyForQuery(out);
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
Socket proxyClient;
|
||||
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
|
||||
ourClient.setSoTimeout(5_000);
|
||||
proxyClient = clientServer.accept();
|
||||
List<Socket> backends = new ArrayList<>(List.of(
|
||||
new Socket("localhost", lookupServer.getLocalPort()),
|
||||
new Socket("localhost", backendServer.getLocalPort())));
|
||||
|
||||
Thread authThread = startIamAuth(proxyClient, () -> backends.remove(0));
|
||||
|
||||
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
|
||||
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
|
||||
|
||||
Map<String, String> clientStartup = new LinkedHashMap<>();
|
||||
clientStartup.put("user", "approle");
|
||||
clientStartup.put("database", "postgres");
|
||||
clientStartup.put("application_name", "svc");
|
||||
writeStartup(clientOut, clientStartup);
|
||||
readCleartextPasswordChallenge(clientIn);
|
||||
writePassword(clientOut, rdsToken("approle"));
|
||||
readAuthenticationOk(clientIn);
|
||||
|
||||
List<Map<Character, String>> notices = new ArrayList<>();
|
||||
Map<String, String> params = readParametersAndNoticesUntilReadyForQuery(clientIn, notices);
|
||||
assertEquals("approle", params.get("session_authorization"));
|
||||
assertEquals(1, notices.size(), notices.toString());
|
||||
assertEquals("WARNING", notices.get(0).get('S'));
|
||||
assertEquals("42704", notices.get(0).get('C'));
|
||||
assertEquals("unrecognized configuration parameter \"no_such_parameter\"", notices.get(0).get('M'));
|
||||
|
||||
ourClient.close();
|
||||
proxyClient.close();
|
||||
authThread.join(5_000);
|
||||
lookupThread.join(5_000);
|
||||
backendThread.join(5_000);
|
||||
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
|
||||
assertEquals(false, lookupThread.isAlive(), "lookupThread did not terminate");
|
||||
assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(List.of(
|
||||
"SELECT pg_catalog.set_config(E'temp_file_limit', E'1GB', false)",
|
||||
"SELECT pg_catalog.set_config(E'no_such_parameter', E'on', false)",
|
||||
"SELECT pg_catalog.set_config(E'search_path', E'app, public', false)"),
|
||||
tried, "each default is tried on the lookup session; role, client_encoding and session_authorization are not");
|
||||
assertEquals("dbadmin", reopenedStartup.get().get("user"));
|
||||
assertEquals("-c temp_file_limit=1GB -c search_path=app,\\ public", reopenedStartup.get().get("options"),
|
||||
"the accepted defaults become startup options, the refused one is left out");
|
||||
assertEquals("UTF8", reopenedStartup.get().get("client_encoding"));
|
||||
assertEquals("SET SESSION AUTHORIZATION \"approle\"", handover.get());
|
||||
assertEquals(List.of(
|
||||
"SELECT pg_catalog.set_config(E'role', E'reader', false)",
|
||||
"SELECT pg_catalog.set_config(E'application_name', E'svc', false)",
|
||||
"SELECT pg_catalog.set_config(E'client_encoding', E'LATIN1', false)"),
|
||||
afterHandover, "role as the role, then the client's settings, then the role's encoding once no proxy SQL follows");
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamSessionFailsWhenARoleDefaultHitsAnErrorOtherThanARefusal() throws Exception {
|
||||
try (ServerSocket lookupServer = new ServerSocket(0);
|
||||
ServerSocket clientServer = new ServerSocket(0)) {
|
||||
|
||||
Thread lookupThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
mockBackendRoleDefaultsLookup(lookupServer,
|
||||
List.<String[]>of(new String[] {"broken_default", "on"}), new ArrayList<>());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
Socket proxyClient;
|
||||
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
|
||||
ourClient.setSoTimeout(5_000);
|
||||
proxyClient = clientServer.accept();
|
||||
Socket backend = new Socket("localhost", lookupServer.getLocalPort());
|
||||
|
||||
Thread authThread = startIamAuth(proxyClient, backend);
|
||||
|
||||
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
|
||||
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
|
||||
|
||||
writeStartup(clientOut, "approle", "postgres");
|
||||
readCleartextPasswordChallenge(clientIn);
|
||||
writePassword(clientOut, rdsToken("approle"));
|
||||
|
||||
Map<Character, String> error = readErrorResponse(clientIn);
|
||||
assertEquals("FATAL", error.get('S'));
|
||||
assertEquals("XX000", error.get('C'));
|
||||
assertEquals("could not read block 0", error.get('M'));
|
||||
assertEquals(-1, clientIn.read(), "the login must fail");
|
||||
|
||||
authThread.join(5_000);
|
||||
lookupThread.join(5_000);
|
||||
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
|
||||
assertEquals(false, lookupThread.isAlive(), "lookupThread did not terminate");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupOptionsEscapeWhatPgSplitOptsSplitsOn() throws Exception {
|
||||
String options = PostgresProtocolHandler.startupOptions(List.of(
|
||||
new PostgresProtocolHandler.SessionSetting("search_path", "app, public"),
|
||||
new PostgresProtocolHandler.SessionSetting("application_name", "a\\b\tc")));
|
||||
assertEquals("-c search_path=app,\\ public -c application_name=a\\\\b\\\tc", options);
|
||||
assertEquals(List.of(
|
||||
new PostgresProtocolHandler.SessionSetting("search_path", "app, public"),
|
||||
new PostgresProtocolHandler.SessionSetting("application_name", "a\\b\tc")),
|
||||
PostgresProtocolHandler.parseOptions(options), "PostgreSQL reads back what was escaped");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"client_encoding|UTF8|true",
|
||||
"CLIENT_ENCODING|UTF8|true",
|
||||
"options|-c client_encoding=LATIN1|true",
|
||||
"options|--client-encoding=LATIN1|true",
|
||||
"options|-c search_path=app|false",
|
||||
"application_name|svc|false"
|
||||
})
|
||||
void clientChoseEncodingSeesEveryWayAClientCanAskForOne(String name, String value, boolean expected) {
|
||||
assertEquals(expected, PostgresProtocolHandler.clientChoseEncoding(Map.of("user", "approle", name, value)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleDefaultsQueryReadsTheRoleWideDefaultsBeforeTheDatabaseSpecificOnes() {
|
||||
String sql = PostgresProtocolHandler.roleDefaultsQuery("o'brien");
|
||||
assertEquals(true, sql.contains("r.rolname = E'o''brien'"), sql);
|
||||
assertEquals(true, sql.endsWith("ORDER BY s.setdatabase = 0 DESC, c.n"), sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsFromDataRowsReadsNameValueRowsAndSkipsEverythingElse() throws Exception {
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
DataOutputStream out = new DataOutputStream(buffer);
|
||||
writeDataRow(out, "search_path", "app, public");
|
||||
writeCommandComplete(out, "SELECT 1");
|
||||
writeDataRow(out, "work_mem", "");
|
||||
DataInputStream in = new DataInputStream(new ByteArrayInputStream(buffer.toByteArray()));
|
||||
List<byte[]> messages = new ArrayList<>();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int type = in.readByte();
|
||||
int length = in.readInt();
|
||||
ByteArrayOutputStream message = new ByteArrayOutputStream();
|
||||
DataOutputStream messageOut = new DataOutputStream(message);
|
||||
messageOut.writeByte(type);
|
||||
messageOut.writeInt(length);
|
||||
messageOut.write(in.readNBytes(length - 4));
|
||||
messages.add(message.toByteArray());
|
||||
}
|
||||
|
||||
assertEquals(List.of(
|
||||
new PostgresProtocolHandler.SessionSetting("search_path", "app, public"),
|
||||
new PostgresProtocolHandler.SessionSetting("work_mem", "")),
|
||||
PostgresProtocolHandler.settingsFromDataRows(messages));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionSettingsApplyOptionsFirstThenTheOtherParametersInOrder() throws Exception {
|
||||
Map<String, String> startup = new LinkedHashMap<>();
|
||||
@@ -1329,6 +1528,24 @@ class PostgresProtocolHandlerTest {
|
||||
return startIamAuth(proxyClient, backend, true, true);
|
||||
}
|
||||
|
||||
private Thread startIamAuth(Socket proxyClient, PostgresProtocolHandler.BackendConnector connector) {
|
||||
return Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
PostgresProtocolHandler.AuthenticatedSession session =
|
||||
PostgresProtocolHandler.authenticate(
|
||||
proxyClient, connector,
|
||||
"dbadmin", "adminpass", "postgres",
|
||||
true, testSigV4Validator(), testBinding(), testTlsCertificates(),
|
||||
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000, true);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Thread startIamAuth(Socket proxyClient, Socket backend,
|
||||
boolean iamEnabled, boolean forwardStartupParameters) {
|
||||
return Thread.ofVirtual().start(() -> {
|
||||
@@ -1444,9 +1661,14 @@ class PostgresProtocolHandlerTest {
|
||||
writeBackendKeyData(out);
|
||||
writeReadyForQuery(out);
|
||||
|
||||
assertEquals('Q', in.readByte());
|
||||
byte[] query = in.readNBytes(in.readInt() - 4);
|
||||
backendQuery.set(new String(query, 0, query.length - 1, StandardCharsets.UTF_8));
|
||||
String query = readSimpleQuery(in);
|
||||
if (query.contains("pg_db_role_setting")) {
|
||||
// A role with no defaults: the proxy carries on with this session.
|
||||
writeCommandComplete(out, "SELECT 0");
|
||||
writeReadyForQuery(out);
|
||||
query = readSimpleQuery(in);
|
||||
}
|
||||
backendQuery.set(query);
|
||||
|
||||
if (!roleExists) {
|
||||
writeErrorResponse(out, "ERROR", "42704", "role \"" + role + "\" does not exist");
|
||||
@@ -1465,6 +1687,101 @@ class PostgresProtocolHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The master session the proxy reads the role's defaults on: answers the lookup with
|
||||
* {@code roleDefaults}, then each default the proxy tries, recording them in {@code tried},
|
||||
* until the proxy terminates the session. {@code no_such_parameter} is refused as PostgreSQL
|
||||
* refuses an unknown parameter; {@code broken_default} fails with an internal error.
|
||||
*/
|
||||
private static void mockBackendRoleDefaultsLookup(ServerSocket server, List<String[]> roleDefaults,
|
||||
List<String> tried) throws IOException {
|
||||
try (Socket socket = server.accept()) {
|
||||
DataInputStream in = new DataInputStream(socket.getInputStream());
|
||||
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
|
||||
|
||||
int length = in.readInt();
|
||||
assertEquals(STARTUP_PROTOCOL_VERSION, in.readInt());
|
||||
in.readNBytes(length - 8);
|
||||
out.writeByte('R');
|
||||
out.writeInt(8);
|
||||
out.writeInt(3);
|
||||
out.flush();
|
||||
assertEquals('p', in.readByte());
|
||||
in.readNBytes(in.readInt() - 4);
|
||||
out.writeByte('R');
|
||||
out.writeInt(8);
|
||||
out.writeInt(0);
|
||||
writeParameterStatus(out, "session_authorization", "dbadmin");
|
||||
writeBackendKeyData(out);
|
||||
writeReadyForQuery(out);
|
||||
|
||||
assertEquals(true, readSimpleQuery(in).contains("pg_db_role_setting"));
|
||||
for (String[] setting : roleDefaults) {
|
||||
writeDataRow(out, setting[0], setting[1]);
|
||||
}
|
||||
writeCommandComplete(out, "SELECT " + roleDefaults.size());
|
||||
writeReadyForQuery(out);
|
||||
|
||||
while (true) {
|
||||
int type = in.read();
|
||||
if (type < 0 || type == 'X') {
|
||||
return;
|
||||
}
|
||||
assertEquals('Q', type);
|
||||
byte[] body = in.readNBytes(in.readInt() - 4);
|
||||
String query = new String(body, 0, body.length - 1, StandardCharsets.UTF_8);
|
||||
tried.add(query);
|
||||
if (query.contains("no_such_parameter")) {
|
||||
writeErrorResponse(out, "ERROR", "42704",
|
||||
"unrecognized configuration parameter \"no_such_parameter\"");
|
||||
} else if (query.contains("broken_default")) {
|
||||
writeErrorResponse(out, "ERROR", "XX000", "could not read block 0");
|
||||
} else {
|
||||
writeCommandComplete(out, "SELECT 1");
|
||||
}
|
||||
writeReadyForQuery(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> readParametersAndNoticesUntilReadyForQuery(
|
||||
DataInputStream in, List<Map<Character, String>> notices) throws IOException {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
while (true) {
|
||||
int type = in.readByte();
|
||||
byte[] payload = in.readNBytes(in.readInt() - 4);
|
||||
if (type == 'Z') {
|
||||
return params;
|
||||
}
|
||||
if (type == 'N') {
|
||||
Map<Character, String> fields = new HashMap<>();
|
||||
int i = 0;
|
||||
while (i < payload.length && payload[i] != 0) {
|
||||
char field = (char) payload[i++];
|
||||
int start = i;
|
||||
while (payload[i] != 0) {
|
||||
i++;
|
||||
}
|
||||
fields.put(field, new String(payload, start, i - start, StandardCharsets.UTF_8));
|
||||
i++;
|
||||
}
|
||||
notices.add(fields);
|
||||
}
|
||||
if (type == 'S') {
|
||||
int nameEnd = 0;
|
||||
while (payload[nameEnd] != 0) {
|
||||
nameEnd++;
|
||||
}
|
||||
int valueEnd = nameEnd + 1;
|
||||
while (payload[valueEnd] != 0) {
|
||||
valueEnd++;
|
||||
}
|
||||
params.put(new String(payload, 0, nameEnd, StandardCharsets.UTF_8),
|
||||
new String(payload, nameEnd + 1, valueEnd - nameEnd - 1, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Drives the backend side of a bridged session, once the client is past authentication. */
|
||||
@FunctionalInterface
|
||||
private interface BackendScript {
|
||||
@@ -1534,6 +1851,21 @@ class PostgresProtocolHandlerTest {
|
||||
out.flush();
|
||||
}
|
||||
|
||||
private static void writeDataRow(DataOutputStream out, String... values) throws IOException {
|
||||
ByteArrayOutputStream row = new ByteArrayOutputStream();
|
||||
DataOutputStream rowOut = new DataOutputStream(row);
|
||||
rowOut.writeShort(values.length);
|
||||
for (String value : values) {
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
rowOut.writeInt(bytes.length);
|
||||
rowOut.write(bytes);
|
||||
}
|
||||
out.writeByte('D');
|
||||
out.writeInt(4 + row.size());
|
||||
row.writeTo(out);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
private static void writeCommandComplete(DataOutputStream out, String tag) throws IOException {
|
||||
byte[] tagBytes = tag.getBytes(StandardCharsets.UTF_8);
|
||||
out.writeByte('C');
|
||||
|
||||
+44
@@ -134,6 +134,50 @@ class RdsPostgresStartupParametersIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIamSessionLoadsTheTokenRolesOwnDefaultsBeneathTheClientsParameters() throws Exception {
|
||||
String dbId = "startup-params-iam-defaults-" + Long.toString(System.nanoTime(), 36);
|
||||
int port = createIamInstance(dbId);
|
||||
try {
|
||||
asMaster(port,
|
||||
"CREATE ROLE reader NOLOGIN",
|
||||
"CREATE ROLE app_user LOGIN",
|
||||
"GRANT reader TO app_user",
|
||||
"ALTER ROLE app_user SET work_mem = '32MB'",
|
||||
"ALTER ROLE app_user IN DATABASE appdb SET work_mem = '48MB'",
|
||||
"ALTER ROLE app_user SET statement_timeout = '7s'",
|
||||
// Superuser-only: applies at login although app_user could not set it itself.
|
||||
"ALTER ROLE app_user SET log_min_duration_statement = '1s'",
|
||||
"ALTER ROLE app_user SET role = 'reader'",
|
||||
// Read on a session whose encoding the master's default would otherwise set.
|
||||
"ALTER ROLE app_user SET floci.note = 'café'",
|
||||
"ALTER ROLE " + MASTER_USER + " SET client_encoding = 'LATIN1'");
|
||||
|
||||
Properties iam = iamLogin(port, "app_user");
|
||||
iam.setProperty("options", "-c statement_timeout=9s");
|
||||
|
||||
try (Connection connection = DriverManager.getConnection(jdbcUrl(port), iam)) {
|
||||
assertThat(show(connection, "work_mem"), equalTo("48MB"));
|
||||
assertThat(show(connection, "statement_timeout"), equalTo("9s"));
|
||||
assertThat(show(connection, "log_min_duration_statement"), equalTo("1s"));
|
||||
assertThat(show(connection, "role"), equalTo("reader"));
|
||||
assertThat(show(connection, "session_authorization"), equalTo("app_user"));
|
||||
assertThat(show(connection, "floci.note"), equalTo("café"));
|
||||
|
||||
// As at login, the role's defaults are what RESET returns to, so the role cannot
|
||||
// shed a superuser-only one its administrator set.
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.execute("RESET ALL");
|
||||
}
|
||||
assertThat(show(connection, "work_mem"), equalTo("48MB"));
|
||||
assertThat(show(connection, "log_min_duration_statement"), equalTo("1s"));
|
||||
assertThat(show(connection, "statement_timeout"), equalTo("7s"));
|
||||
}
|
||||
} finally {
|
||||
deleteInstance(dbId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates a PostgreSQL instance with IAM database authentication and returns its proxy port. */
|
||||
private static int createIamInstance(String dbId) {
|
||||
return rds("CreateDBInstance")
|
||||
|
||||
Reference in new issue
Block a user