mirror of
https://github.com/floci-io/floci.git
synced 2026-11-30 00:45:17 -05:00
feat(dsql): map IAM roles to database roles with AWS IAM GRANT (#6143)
* feat(dsql): map IAM roles to database roles with AWS IAM GRANT A role other than admin now signs in to a cluster for the IAM role that AWS IAM GRANT mapped to it, as on DSQL: the token's principal (a Lambda function's execution role, an ECS task's role, an AssumeRole session) is looked up in sys.iam_pg_role_mappings, and an unmapped role is refused with DSQL's 28000. AWS IAM GRANT and REVOKE become calls to procedures in the cluster's sys schema, with DSQL's command tags and its refusals for a superuser and for a role the caller holds no ADMIN option on. sys.iam_session_user() and sys.current_session_id() answer the session's identity. Since the identity travels in dsql.* settings, the dsql prefix is reserved as DSQL reserves it, measured on AWS: SET, RESET, set_config, ALTER ROLE ... SET and a function's SET clause of a dsql. parameter answer 42602 with DSQL's detail. Errors lose their source location and the context lines of the sys functions, as DSQL's never show them. * fix(dsql): refuse dropping a mapped role and keep the session identity out of the session's reach DROP ROLE, USER and GROUP of a role an IAM identity is mapped to now answer DSQL's 2BP01, with one detail line per mapping in grant order, as measured on DSQL. The statement becomes a call to sys.drop_roles, which refuses a mapped role and otherwise drops the roles as the caller. A role dropped where Floci cannot see it, inside a function body, stops being listed in sys.iam_pg_role_mappings, and its mappings go with the next grant or revoke. The session identity no longer travels in dsql.* startup settings, which a set_config inside a DO block or a function body could overwrite. The endpoint writes it as the superuser into sys.session_identity, keyed by the backend's pid, before it forwards the first ReadyForQuery, and no role of the cluster can write that table. Catching every set_config of a dsql. parameter was rejected: only a PostgreSQL extension written in C can reserve a prefix, so the gap inside DO blocks and function bodies is documented as it is. Command tags are settled per batch: each Query, Sync and FunctionCall gets its own, and a Parse's tag, a Bind's statement, a Close and an Execute's result take effect when the database answers them, in its order. A pipelined batch no longer loses its tags to an earlier ReadyForQuery, and a Parse the database refuses leaves the statement it named as it was. Closed statements and portals are forgotten, and portals with their transaction. Also, as measured on DSQL: AWS IAM GRANT takes an IAM user's ARN, a repeated grant answers its notice whoever the grantor was, and a failed read of the mappings refuses the connection as 08006 with its cause logged, instead of as a role refused. An error's context drops everything a sys function ran, the statements it executed included.
This commit is contained in:
1 parent
fd37e109f8
commit
6e5b3c6c1d
10 files changed
+1402
-69
No files matched your search
@@ -125,7 +125,8 @@ public class DsqlDatabases {
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection superuser(Backend backend) throws SQLException {
|
||||
/** A superuser connection to the cluster's database, for what the endpoint checks itself. */
|
||||
public static Connection superuser(Backend backend) throws SQLException {
|
||||
return DriverManager.getConnection(backend.jdbcUrl(), "dbowner", "");
|
||||
}
|
||||
|
||||
|
||||
+77
-16
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.dsql.dataplane;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.PostgresWire;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
@@ -23,6 +25,10 @@ import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
@@ -38,8 +44,8 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
* sends picks the cluster. A connection is admitted as Aurora DSQL admits it (measured on AWS,
|
||||
* eu-west-1, 2026-10-16): the password is a SigV4 token for the endpoint's host, {@code admin}
|
||||
* signs {@code DbConnectAdmin} and every other role {@code DbConnect}, a token is taken up to 5
|
||||
* seconds past its expiry, and a role other than {@code admin} logs in only for an IAM role mapped
|
||||
* to it, which Floci does not map yet. Every refusal is the same {@code access denied}, with a hint
|
||||
* seconds past its expiry, and a role other than {@code admin} logs in only for an IAM role that
|
||||
* {@code AWS IAM GRANT} mapped to it. Every refusal is the same {@code access denied}, with a hint
|
||||
* only where DSQL gives one. DSQL lets clients in while a cluster is still CREATING; Floci's
|
||||
* clusters are CREATING only while their database starts, and serve once it answers.
|
||||
*/
|
||||
@@ -70,18 +76,17 @@ public class DsqlEndpoint {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a connection may go on, and to which cluster; when it may not, the SQLSTATE DSQL
|
||||
* answers ({@code 08006} for the token, {@code 28000} for the role it would log in as) and its
|
||||
* hint.
|
||||
* Whether a connection may go on, and as whom; when it may not, the SQLSTATE DSQL answers
|
||||
* ({@code 08006} for the token, {@code 28000} for the role it would log in as) and its hint.
|
||||
*/
|
||||
record Admission(boolean allowed, String state, String hint, Route route) {
|
||||
record Admission(boolean allowed, String state, String hint, Route route, String principalArn) {
|
||||
|
||||
static Admission refused(String hint) {
|
||||
return new Admission(false, "08006", hint, null);
|
||||
return new Admission(false, "08006", hint, null, null);
|
||||
}
|
||||
|
||||
static Admission unauthorized() {
|
||||
return new Admission(false, "28000", null, null);
|
||||
return new Admission(false, "28000", null, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,8 +182,7 @@ public class DsqlEndpoint {
|
||||
* Whether {@code token} lets {@code user} in, checked in the order DSQL reports: the cluster
|
||||
* the client asked for by name (or, without a name, the one the token is for), the action
|
||||
* the user needs, the token's expiry, then its signature and, for a role other than
|
||||
* {@code admin}, the IAM role mapped to it: DSQL refuses a role no IAM role is mapped to, and
|
||||
* Floci maps none yet, so only {@code admin} signs in.
|
||||
* {@code admin}, the IAM role mapped to it.
|
||||
*/
|
||||
Admission admit(String token, String user, String serverName) {
|
||||
URI uri;
|
||||
@@ -231,16 +235,31 @@ public class DsqlEndpoint {
|
||||
if (!route.accountId().equals(iamService.resolveAccountId(accessKeyId).orElse(route.accountId()))) {
|
||||
return Admission.refused(null);
|
||||
}
|
||||
// The endpoint runs outside any request: the caller's policies are read in the cluster's
|
||||
// account, as the enforcement filter reads them in the request's.
|
||||
if (enforcement && !RequestScopes.callAs(route.accountId(), route.region(),
|
||||
() -> allowedByIam(accessKeyId, "dsql:" + needed, route))) {
|
||||
// The endpoint runs outside any request: the caller's identity and policies are read in the
|
||||
// cluster's account, as the enforcement filter reads them in the request's.
|
||||
String principal = RequestScopes.callAs(route.accountId(), route.region(), () -> {
|
||||
if (enforcement && !allowedByIam(accessKeyId, "dsql:" + needed, route)) {
|
||||
return null;
|
||||
}
|
||||
return iamService.resolvePrincipalArn(accessKeyId).orElseGet(() -> AwsArnUtils.Arn.global(
|
||||
AwsRegions.partitionFor(route.region()), "iam", route.accountId(), "root").toString());
|
||||
});
|
||||
if (principal == null) {
|
||||
return Admission.refused(null);
|
||||
}
|
||||
if (!ADMIN.equals(user)) {
|
||||
return Admission.unauthorized();
|
||||
try {
|
||||
if (!mapped(route.backend(), principal, user)) {
|
||||
return Admission.unauthorized();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
// A database that cannot be asked says nothing about the role: the connection fails
|
||||
// as one the cluster cannot serve, not as a role refused.
|
||||
LOG.warn("Could not read the IAM role mappings of a DSQL cluster", e);
|
||||
return Admission.refused(null);
|
||||
}
|
||||
}
|
||||
return new Admission(true, null, null, route);
|
||||
return new Admission(true, null, null, route, principal);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,6 +308,48 @@ public class DsqlEndpoint {
|
||||
== IamPolicyEvaluator.SimulationDecision.ALLOWED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code AWS IAM GRANT} mapped the IAM role {@code principal} to {@code role}. A
|
||||
* superuser is never one, as DSQL never lets {@code dbowner} in.
|
||||
*/
|
||||
private static boolean mapped(DsqlDatabases.Backend backend, String principal, String role) throws SQLException {
|
||||
try (Connection connection = DsqlDatabases.superuser(backend);
|
||||
PreparedStatement query = connection.prepareStatement("SELECT 1 FROM sys.iam_pg_role_mappings m"
|
||||
+ " JOIN pg_roles r ON r.oid = m.pg_role_oid WHERE m.arn = ? AND m.pg_role_name = ?"
|
||||
+ " AND NOT r.rolsuper")) {
|
||||
query.setString(1, principal);
|
||||
query.setString(2, role);
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
return rows.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records who the session on backend process {@code pid} is, for {@code sys.iam_session_user()}
|
||||
* and {@code sys.current_session_id()}. The superuser writes it into a table no role of the
|
||||
* cluster can write, so nothing the session runs can change it, and drops the rows of sessions
|
||||
* that have ended. False, with the cause logged, when the database could not be written.
|
||||
*/
|
||||
boolean recordSession(DsqlDatabases.Backend backend, int pid, String principal, String sessionId) {
|
||||
try (Connection connection = DsqlDatabases.superuser(backend);
|
||||
PreparedStatement purge = connection.prepareStatement("DELETE FROM sys.session_identity"
|
||||
+ " WHERE pid NOT IN (SELECT pid FROM pg_stat_activity WHERE pid IS NOT NULL)");
|
||||
PreparedStatement record = connection.prepareStatement("INSERT INTO sys.session_identity"
|
||||
+ " (pid, iam_session_user, session_id) VALUES (?, ?, ?) ON CONFLICT (pid) DO UPDATE"
|
||||
+ " SET iam_session_user = EXCLUDED.iam_session_user, session_id = EXCLUDED.session_id")) {
|
||||
purge.executeUpdate();
|
||||
record.setInt(1, pid);
|
||||
record.setString(2, principal);
|
||||
record.setString(3, sessionId);
|
||||
record.executeUpdate();
|
||||
return true;
|
||||
} catch (SQLException e) {
|
||||
LOG.warn("Could not record the identity of a DSQL session", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String[] credentialScope(String rawQuery) {
|
||||
String credential = SigV4RequestValidator.queryParameter(rawQuery, "X-Amz-Credential");
|
||||
if (credential == null) {
|
||||
|
||||
+234
-28
@@ -17,19 +17,26 @@ import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* One client connection to a DSQL endpoint, as Aurora DSQL serves it (measured on AWS, eu-west-1,
|
||||
* 2026-10-16): TLS is mandatory, the password is an IAM token for the endpoint, the startup is read
|
||||
* as DSQL reads it, and a connection lives an hour.
|
||||
* as DSQL reads it, DSQL's own statements become the {@code sys} calls that implement them, their
|
||||
* errors come back without the source locations and {@code sys} lines DSQL never shows, and a
|
||||
* connection lives an hour.
|
||||
*/
|
||||
final class DsqlSession {
|
||||
|
||||
@@ -42,6 +49,17 @@ final class DsqlSession {
|
||||
private final Socket socket;
|
||||
private final DsqlEndpoint endpoint;
|
||||
private final String sessionId = DsqlIdentifiers.newId();
|
||||
// One batch per Query or Sync sent, oldest first, holding what the database's answers to it
|
||||
// settle, in the order it answers them. A batch goes with its ReadyForQuery, and with it what an
|
||||
// error left unanswered, so a later batch's are never touched.
|
||||
private final Deque<Batch> batches = new ArrayDeque<>();
|
||||
private Batch openBatch;
|
||||
// The prepared statements DSQL tags its own way, and the statement each portal runs, as the
|
||||
// database confirmed them. Only the thread relaying the database's answers touches them.
|
||||
private final Map<String, String> statementTags = new HashMap<>();
|
||||
private final Map<String, String> portalStatements = new HashMap<>();
|
||||
private volatile String principalArn;
|
||||
private volatile int backendPid;
|
||||
private volatile long cancelKey;
|
||||
|
||||
DsqlSession(Socket socket, DsqlEndpoint endpoint) {
|
||||
@@ -142,11 +160,12 @@ final class DsqlSession {
|
||||
backendStartup.put("options", backendOptions(optionSettings));
|
||||
}
|
||||
backendStartup.put("database", "postgres");
|
||||
principalArn = admission.principalArn();
|
||||
backendOut.write(PostgresWire.startupMessage(backendStartup));
|
||||
backendOut.flush();
|
||||
|
||||
Thread toClient = Thread.ofVirtual().name("dsql-backend-" + sessionId)
|
||||
.start(() -> relayToClient(backendIn, out, target, tls));
|
||||
.start(() -> relayToClient(backendIn, out, admission.route(), tls));
|
||||
Thread lifetime = Thread.ofVirtual().name("dsql-lifetime-" + sessionId).start(() -> {
|
||||
try {
|
||||
Thread.sleep(CONNECTION_LIFETIME.toMillis());
|
||||
@@ -171,13 +190,63 @@ final class DsqlSession {
|
||||
}
|
||||
}
|
||||
|
||||
private static void relayToBackend(InputStream in, OutputStream backendOut) throws IOException {
|
||||
private void relayToBackend(InputStream in, OutputStream backendOut) throws IOException {
|
||||
while (true) {
|
||||
PostgresWire.Message message = PostgresWire.read(in, MAX_MESSAGE, "message");
|
||||
PostgresWire.write(backendOut, message);
|
||||
if (message.type() == 'X') {
|
||||
backendOut.flush();
|
||||
return;
|
||||
switch (message.type()) {
|
||||
case 'Q' -> {
|
||||
String query = PostgresWire.cString(message.body(), 0).value();
|
||||
PostgresWire.write(backendOut, 'Q', PostgresWire.cStringBytes(rewriteSimpleQuery(query)));
|
||||
}
|
||||
case 'P' -> {
|
||||
PostgresWire.CString name = PostgresWire.cString(message.body(), 0);
|
||||
PostgresWire.CString query = PostgresWire.cString(message.body(), name.next());
|
||||
DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query.value());
|
||||
String tag = rewritten.overridesTags() && rewritten.commandTags().size() == 1
|
||||
? rewritten.commandTags().get(0) : null;
|
||||
synchronized (batches) {
|
||||
extendedBatch().parses.addLast(new Named(name.value(), tag));
|
||||
}
|
||||
PostgresWire.write(backendOut, 'P', PostgresWire.cStringBytes(name.value()),
|
||||
PostgresWire.cStringBytes(rewritten.sql()),
|
||||
Arrays.copyOfRange(message.body(), query.next(), message.body().length));
|
||||
}
|
||||
case 'B' -> {
|
||||
PostgresWire.CString portal = PostgresWire.cString(message.body(), 0);
|
||||
PostgresWire.CString statement = PostgresWire.cString(message.body(), portal.next());
|
||||
synchronized (batches) {
|
||||
extendedBatch().binds.addLast(new Named(portal.value(), statement.value()));
|
||||
}
|
||||
PostgresWire.write(backendOut, message);
|
||||
}
|
||||
case 'E' -> {
|
||||
String portal = PostgresWire.cString(message.body(), 0).value();
|
||||
synchronized (batches) {
|
||||
extendedBatch().results.addLast(new Named(portal, null));
|
||||
}
|
||||
PostgresWire.write(backendOut, message);
|
||||
}
|
||||
case 'C' -> {
|
||||
String kind = message.body()[0] == 'S' ? "S" : "P";
|
||||
synchronized (batches) {
|
||||
extendedBatch().closes.addLast(new Named(PostgresWire.cString(message.body(), 1).value(), kind));
|
||||
}
|
||||
PostgresWire.write(backendOut, message);
|
||||
}
|
||||
case 'S', 'F' -> {
|
||||
// A Sync, or a FunctionCall, is answered by a ReadyForQuery of its own.
|
||||
synchronized (batches) {
|
||||
extendedBatch();
|
||||
openBatch = null;
|
||||
}
|
||||
PostgresWire.write(backendOut, message);
|
||||
}
|
||||
case 'X' -> {
|
||||
PostgresWire.write(backendOut, message);
|
||||
backendOut.flush();
|
||||
return;
|
||||
}
|
||||
default -> PostgresWire.write(backendOut, message);
|
||||
}
|
||||
if (in.available() == 0) {
|
||||
backendOut.flush();
|
||||
@@ -185,6 +254,54 @@ final class DsqlSession {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple query as the database runs it. Its statements' command tags join the batch its
|
||||
* ReadyForQuery ends: the extended-protocol messages sent since the last Sync, if any.
|
||||
*/
|
||||
private String rewriteSimpleQuery(String query) {
|
||||
DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query);
|
||||
synchronized (batches) {
|
||||
Batch batch = extendedBatch();
|
||||
rewritten.commandTags().forEach(tag -> batch.results.addLast(new Named(null, tag)));
|
||||
openBatch = null;
|
||||
}
|
||||
return rewritten.sql();
|
||||
}
|
||||
|
||||
/** The batch the extended-protocol messages since the last Sync belong to. Called holding {@code batches}. */
|
||||
private Batch extendedBatch() {
|
||||
if (openBatch == null) {
|
||||
openBatch = new Batch();
|
||||
batches.addLast(openBatch);
|
||||
}
|
||||
return openBatch;
|
||||
}
|
||||
|
||||
/**
|
||||
* What one Query or Sync's messages wait for the database to settle, each kind in the order the
|
||||
* database answers it: the statements parsed and their tags, the portals bound and the statements
|
||||
* they run, the statements and portals closed, and the results, each a portal's or a simple
|
||||
* query statement's tag.
|
||||
*/
|
||||
private static final class Batch {
|
||||
final Deque<Named> parses = new ArrayDeque<>();
|
||||
final Deque<Named> binds = new ArrayDeque<>();
|
||||
final Deque<Named> closes = new ArrayDeque<>();
|
||||
final Deque<Named> results = new ArrayDeque<>();
|
||||
}
|
||||
|
||||
/** A statement or portal name, and what goes with it; a simple query's result has no name. */
|
||||
private record Named(String name, String value) {
|
||||
}
|
||||
|
||||
/** The answer of the oldest batch the database is answering, from {@code queue}. */
|
||||
private Named settle(Function<Batch, Deque<Named>> queue) {
|
||||
synchronized (batches) {
|
||||
Batch batch = batches.peekFirst();
|
||||
return batch == null ? null : queue.apply(batch).pollFirst();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings a client's startup {@code options} make, as DSQL reads them (measured, eu-west-1,
|
||||
* 2026-10-20): words split on white space, with no escapes, of which only {@code -c name=value}
|
||||
@@ -223,29 +340,87 @@ final class DsqlSession {
|
||||
return String.join(" ", words);
|
||||
}
|
||||
|
||||
private void relayToClient(InputStream backendIn, OutputStream out, DsqlDatabases.Backend backend, Socket client) {
|
||||
private void relayToClient(InputStream backendIn, OutputStream out, DsqlEndpoint.Route route, Socket client) {
|
||||
try {
|
||||
PostgresWire.Message authenticated = null;
|
||||
List<PostgresWire.Message> startup = new ArrayList<>();
|
||||
boolean started = false;
|
||||
while (true) {
|
||||
PostgresWire.Message message = PostgresWire.read(backendIn, MAX_MESSAGE, "message");
|
||||
if (!started) {
|
||||
// DSQL refuses a connection instead of authenticating it, so the database's
|
||||
// AuthenticationOk waits for what follows it, and a refusal takes its place.
|
||||
if (message.type() == 'R' && authenticated == null) {
|
||||
authenticated = message;
|
||||
continue;
|
||||
// DSQL refuses a connection instead of authenticating it, so what the database
|
||||
// answers the startup waits for its ReadyForQuery, and a refusal takes its place.
|
||||
switch (message.type()) {
|
||||
case 'E' -> {
|
||||
startup.clear();
|
||||
message = new PostgresWire.Message(message.type(), withSessionId(message.body()));
|
||||
}
|
||||
case 'Z' -> {
|
||||
// The session's identity is in place before the client's first statement.
|
||||
if (!endpoint.recordSession(route.backend(), backendPid, principalArn, sessionId)) {
|
||||
refuse(out, "08006", ACCESS_DENIED, null);
|
||||
closeQuietly(client);
|
||||
return;
|
||||
}
|
||||
for (PostgresWire.Message answer : startup) {
|
||||
PostgresWire.write(out, answer);
|
||||
}
|
||||
started = true;
|
||||
}
|
||||
case 'K' -> {
|
||||
cancelKey = endpoint.registerCancelKey(message.body(), route.backend());
|
||||
backendPid = PostgresWire.int32(message.body(), 0);
|
||||
startup.add(message);
|
||||
continue;
|
||||
}
|
||||
default -> {
|
||||
startup.add(message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (message.type() == 'E') {
|
||||
message = new PostgresWire.Message(message.type(), withSessionId(message.body()));
|
||||
} else if (authenticated != null) {
|
||||
PostgresWire.write(out, authenticated);
|
||||
}
|
||||
authenticated = null;
|
||||
started = message.type() == 'Z';
|
||||
}
|
||||
if (message.type() == 'K') {
|
||||
cancelKey = endpoint.registerCancelKey(message.body(), backend);
|
||||
switch (message.type()) {
|
||||
case 'C' -> {
|
||||
Named result = settle(batch -> batch.results);
|
||||
String override = result == null ? null : result.name() == null ? result.value()
|
||||
: statementTags.get(portalStatements.get(result.name()));
|
||||
if (override != null) {
|
||||
message = new PostgresWire.Message((byte) 'C', PostgresWire.cStringBytes(override));
|
||||
}
|
||||
}
|
||||
case 'I', 's' -> settle(batch -> batch.results);
|
||||
case '1' -> {
|
||||
Named parsed = settle(batch -> batch.parses);
|
||||
if (parsed != null && parsed.value() != null) {
|
||||
statementTags.put(parsed.name(), parsed.value());
|
||||
} else if (parsed != null) {
|
||||
statementTags.remove(parsed.name());
|
||||
}
|
||||
}
|
||||
case '2' -> {
|
||||
Named bound = settle(batch -> batch.binds);
|
||||
if (bound != null) {
|
||||
portalStatements.put(bound.name(), bound.value());
|
||||
}
|
||||
}
|
||||
case '3' -> {
|
||||
Named closed = settle(batch -> batch.closes);
|
||||
if (closed != null) {
|
||||
(closed.value().equals("S") ? statementTags : portalStatements).remove(closed.name());
|
||||
}
|
||||
}
|
||||
case 'E', 'N' -> message = new PostgresWire.Message(message.type(),
|
||||
inDsqlWords(message.type(), message.body()));
|
||||
case 'Z' -> {
|
||||
synchronized (batches) {
|
||||
batches.pollFirst();
|
||||
}
|
||||
if (message.body()[0] == 'I') {
|
||||
// Outside a transaction no portal outlives its Sync.
|
||||
portalStatements.clear();
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
PostgresWire.write(out, message);
|
||||
if (backendIn.available() == 0) {
|
||||
@@ -259,14 +434,45 @@ final class DsqlSession {
|
||||
}
|
||||
|
||||
/**
|
||||
* A refusal of the database's as DSQL words every one: the session's id as its detail, and no
|
||||
* source location.
|
||||
* An error or notice as DSQL words it (measured on AWS). An error carries no source location,
|
||||
* PostgreSQL's own included, while a notice keeps its location. The context keeps what the
|
||||
* client's SQL ran and drops what Floci's {@code sys} functions ran, as DSQL's context never
|
||||
* shows its own: the context lists the innermost call first, so everything up to the last
|
||||
* line of a {@code sys} function, the statements it ran included, is theirs.
|
||||
*/
|
||||
static byte[] inDsqlWords(byte type, byte[] body) {
|
||||
Map<Character, String> fields = PostgresWire.parseFields(body, 0);
|
||||
boolean changed = false;
|
||||
String where = fields.get('W');
|
||||
if (where != null) {
|
||||
List<String> lines = where.lines().toList();
|
||||
int ownLines = 0;
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
if (lines.get(i).contains("function sys.")) {
|
||||
ownLines = i + 1;
|
||||
}
|
||||
}
|
||||
String kept = String.join("\n", lines.subList(ownLines, lines.size()));
|
||||
if (!kept.equals(where)) {
|
||||
changed = true;
|
||||
if (kept.isEmpty()) {
|
||||
fields.remove('W');
|
||||
} else {
|
||||
fields.put('W', kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (type == 'E') {
|
||||
changed |= fields.remove('F') != null;
|
||||
changed |= fields.remove('L') != null;
|
||||
changed |= fields.remove('R') != null;
|
||||
}
|
||||
return changed ? PostgresWire.fields(fields) : body;
|
||||
}
|
||||
|
||||
/** A refusal of the database's as DSQL words every one: the session's id as its detail. */
|
||||
private byte[] withSessionId(byte[] body) {
|
||||
Map<Character, String> fields = PostgresWire.parseFields(body, 0);
|
||||
fields.remove('F');
|
||||
fields.remove('L');
|
||||
fields.remove('R');
|
||||
fields.putIfAbsent('D', "Session Id: " + sessionId);
|
||||
return PostgresWire.fields(fields);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
package io.github.hectorvent.floci.services.dsql.dataplane;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The statements of a query as Aurora DSQL reads them. DSQL's own syntax ({@code AWS IAM GRANT}
|
||||
* and {@code REVOKE}) becomes the calls into the cluster's {@code sys} schema that implement it,
|
||||
* and a statement DSQL refuses becomes a call to {@code sys._reject} with the SQLSTATE and message
|
||||
* DSQL answers (measured on AWS, eu-west-1, 2026-10-16 and 2026-10-20), so the database raises the
|
||||
* error and the transaction fails as DSQL's does.
|
||||
*/
|
||||
public final class DsqlStatements {
|
||||
|
||||
private static final String RESERVED_PREFIX = "dsql.";
|
||||
private static final Set<String> ROLE_SPECIFIERS = Set.of("CURRENT_ROLE", "CURRENT_USER", "SESSION_USER", "PUBLIC",
|
||||
"NONE");
|
||||
|
||||
private DsqlStatements() {
|
||||
}
|
||||
|
||||
/** One statement of a query, and the command tag a client should see for it when it differs. */
|
||||
public record Statement(String sql, String commandTag) {
|
||||
}
|
||||
|
||||
/** The statements of {@code query}, each rewritten as DSQL reads it, in order. */
|
||||
public static List<Statement> rewrite(String query) {
|
||||
List<Statement> statements = new ArrayList<>();
|
||||
for (List<Token> tokens : split(tokenize(query))) {
|
||||
if (tokens.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String text = query.substring(tokens.get(0).start(), tokens.get(tokens.size() - 1).end());
|
||||
statements.add(rewrite(text, tokens));
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
/**
|
||||
* A query as the database runs it, and the command tag each of its statements shows, null where
|
||||
* the database's own is right.
|
||||
*/
|
||||
public record Query(String sql, List<String> commandTags) {
|
||||
|
||||
/** Whether any statement shows a command tag other than the database's. */
|
||||
public boolean overridesTags() {
|
||||
return commandTags.stream().anyMatch(tag -> tag != null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole query as the database runs it: the statements rewritten and joined, or, when none
|
||||
* needed rewriting, the query exactly as the client sent it.
|
||||
*/
|
||||
public static Query rewriteQuery(String query) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
List<String> tags = new ArrayList<>();
|
||||
boolean changed = false;
|
||||
for (List<Token> tokens : split(tokenize(query))) {
|
||||
if (tokens.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String text = query.substring(tokens.get(0).start(), tokens.get(tokens.size() - 1).end());
|
||||
Statement statement = rewrite(text, tokens);
|
||||
changed |= statement.commandTag() != null || !statement.sql().equals(text);
|
||||
parts.add(statement.sql());
|
||||
tags.add(statement.commandTag());
|
||||
}
|
||||
return new Query(changed ? String.join(";\n", parts) : query, tags);
|
||||
}
|
||||
|
||||
/** {@code sys._reject} raising {@code state} with {@code message}, as a statement. */
|
||||
public static String reject(String state, String message, String detail) {
|
||||
return "SELECT sys._reject(" + literal(state) + ", " + literal(message)
|
||||
+ (detail == null ? "" : ", " + literal(detail)) + ")";
|
||||
}
|
||||
|
||||
private static Statement rewrite(String text, List<Token> tokens) {
|
||||
String first = word(tokens, 0);
|
||||
String second = word(tokens, 1);
|
||||
String third = word(tokens, 2);
|
||||
|
||||
if ("AWS".equals(first) && "IAM".equals(second) && ("GRANT".equals(third) || "REVOKE".equals(third))) {
|
||||
Statement iam = iamGrant(tokens, "GRANT".equals(third));
|
||||
if (iam != null) {
|
||||
return iam;
|
||||
}
|
||||
}
|
||||
if ("DROP".equals(first) && ("ROLE".equals(second) || "USER".equals(second) || "GROUP".equals(second))) {
|
||||
Statement drop = dropRoles(tokens);
|
||||
if (drop != null) {
|
||||
return drop;
|
||||
}
|
||||
}
|
||||
Statement setting = setting(tokens, first);
|
||||
if (setting != null) {
|
||||
return setting;
|
||||
}
|
||||
return new Statement(text, null);
|
||||
}
|
||||
|
||||
private static Statement iamGrant(List<Token> tokens, boolean grant) {
|
||||
if (tokens.size() != 6 || tokens.get(5).type() != Type.STRING) {
|
||||
return null;
|
||||
}
|
||||
String preposition = word(tokens, 4);
|
||||
if (!(grant ? "TO" : "FROM").equals(preposition)) {
|
||||
return null;
|
||||
}
|
||||
Token role = tokens.get(3);
|
||||
String roleName = switch (role.type()) {
|
||||
case WORD -> role.lower();
|
||||
case QUOTED_IDENTIFIER -> role.value();
|
||||
default -> null;
|
||||
};
|
||||
if (roleName == null) {
|
||||
return null;
|
||||
}
|
||||
String call = "CALL sys.aws_iam_" + (grant ? "grant" : "revoke") + "(" + literal(roleName) + ", "
|
||||
+ literal(tokens.get(5).value()) + ")";
|
||||
return new Statement(call, grant ? "AWS IAM GRANT" : "AWS IAM REVOKE");
|
||||
}
|
||||
|
||||
/**
|
||||
* DSQL reserves the {@code dsql} prefix as PostgreSQL reserves an extension's (measured,
|
||||
* eu-west-1, 2026-10-20): setting or resetting a {@code dsql.} parameter, with {@code SET} or
|
||||
* {@code RESET} in any statement or with {@code set_config}, is {@code 42602}, and showing one
|
||||
* {@code 42704}, as for a parameter that does not exist. {@code set_config} of any other dotted
|
||||
* parameter named in the statement is not supported, though {@code SET} of one is.
|
||||
*/
|
||||
private static Statement setting(List<Token> tokens, String first) {
|
||||
if ("SHOW".equals(first)) {
|
||||
String name = parameterName(tokens, 1);
|
||||
if (name.startsWith(RESERVED_PREFIX)) {
|
||||
return rejected("42704", "unrecognized configuration parameter \"" + name + "\"");
|
||||
}
|
||||
}
|
||||
for (int i = 0; i + 1 < tokens.size(); i++) {
|
||||
String word = word(tokens, i);
|
||||
if ("SET".equals(word) || "RESET".equals(word)) {
|
||||
int at = "SESSION".equals(word(tokens, i + 1)) || "LOCAL".equals(word(tokens, i + 1)) ? i + 2 : i + 1;
|
||||
String name = parameterName(tokens, at);
|
||||
if (name.startsWith(RESERVED_PREFIX)) {
|
||||
return reservedPrefix(name);
|
||||
}
|
||||
}
|
||||
boolean setConfig = "SET_CONFIG".equals(word) || tokens.get(i).type() == Type.QUOTED_IDENTIFIER
|
||||
&& "set_config".equals(tokens.get(i).value());
|
||||
if (setConfig && i + 2 < tokens.size() && "(".equals(tokens.get(i + 1).text())
|
||||
&& tokens.get(i + 2).type() == Type.STRING) {
|
||||
String name = tokens.get(i + 2).value();
|
||||
if (name.startsWith(RESERVED_PREFIX)) {
|
||||
return reservedPrefix(name);
|
||||
}
|
||||
if (name.contains(".")) {
|
||||
return rejected("0A000", "setting configuration parameter \"" + name + "\" not supported");
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code DROP ROLE|USER|GROUP [IF EXISTS] name, ...}: the call that refuses a role an IAM role or
|
||||
* user is mapped to, as DSQL does (measured), and otherwise drops them as the caller.
|
||||
*/
|
||||
private static Statement dropRoles(List<Token> tokens) {
|
||||
int at = 2;
|
||||
boolean ifExists = "IF".equals(word(tokens, at)) && "EXISTS".equals(word(tokens, at + 1));
|
||||
if (ifExists) {
|
||||
at += 2;
|
||||
}
|
||||
List<String> names = new ArrayList<>();
|
||||
for (int i = at; i < tokens.size(); i += 2) {
|
||||
Token name = tokens.get(i);
|
||||
// A role specifier PostgreSQL refuses here is left for PostgreSQL to refuse.
|
||||
boolean specifier = name.type() == Type.WORD && ROLE_SPECIFIERS.contains(name.upper());
|
||||
if (specifier || name.type() != Type.WORD && name.type() != Type.QUOTED_IDENTIFIER) {
|
||||
return null;
|
||||
}
|
||||
names.add(literal(identifier(name)));
|
||||
if (i + 1 < tokens.size() && !",".equals(tokens.get(i + 1).text())) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// Names and commas alternate, so a list that ends in a comma is left for PostgreSQL to refuse.
|
||||
if (names.isEmpty() || (tokens.size() - at) % 2 == 0) {
|
||||
return null;
|
||||
}
|
||||
return new Statement("CALL sys.drop_roles(ARRAY[" + String.join(", ", names) + "]::text[], " + ifExists + ")",
|
||||
"DROP ROLE");
|
||||
}
|
||||
|
||||
private static Statement reservedPrefix(String name) {
|
||||
return new Statement(reject("42602", "invalid configuration parameter name \"" + name + "\"",
|
||||
"\"dsql\" is a reserved prefix."), null);
|
||||
}
|
||||
|
||||
/** The parameter named from {@code at} on, its parts joined by dots, as PostgreSQL folds its case. */
|
||||
private static String parameterName(List<Token> tokens, int at) {
|
||||
StringBuilder name = new StringBuilder();
|
||||
for (int i = at; i < tokens.size(); i++) {
|
||||
Token token = tokens.get(i);
|
||||
if (token.type() == Type.WORD || token.type() == Type.QUOTED_IDENTIFIER) {
|
||||
name.append(identifier(token));
|
||||
} else if (".".equals(token.text()) && token.type() == Type.SYMBOL && name.length() > 0) {
|
||||
name.append('.');
|
||||
continue;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
if (i + 1 >= tokens.size() || !".".equals(tokens.get(i + 1).text())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return name.toString();
|
||||
}
|
||||
|
||||
private static Statement rejected(String state, String message) {
|
||||
return new Statement(reject(state, message, null), null);
|
||||
}
|
||||
|
||||
// ── Tokens ────────────────────────────────────────────────────────────────
|
||||
|
||||
enum Type { WORD, QUOTED_IDENTIFIER, STRING, NUMBER, SYMBOL }
|
||||
|
||||
record Token(Type type, String text, String value, int start, int end) {
|
||||
String upper() {
|
||||
return text.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
String lower() {
|
||||
return text.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
|
||||
static List<Token> tokenize(String sql) {
|
||||
List<Token> tokens = new ArrayList<>();
|
||||
int i = 0;
|
||||
int n = sql.length();
|
||||
while (i < n) {
|
||||
char c = sql.charAt(i);
|
||||
if (Character.isWhitespace(c)) {
|
||||
i++;
|
||||
} else if (c == '-' && i + 1 < n && sql.charAt(i + 1) == '-') {
|
||||
while (i < n && sql.charAt(i) != '\n') {
|
||||
i++;
|
||||
}
|
||||
} else if (c == '/' && i + 1 < n && sql.charAt(i + 1) == '*') {
|
||||
int depth = 1;
|
||||
i += 2;
|
||||
while (i < n && depth > 0) {
|
||||
if (sql.startsWith("/*", i)) {
|
||||
depth++;
|
||||
i += 2;
|
||||
} else if (sql.startsWith("*/", i)) {
|
||||
depth--;
|
||||
i += 2;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
} else if (c == '\'' || ((c == 'E' || c == 'e') && i + 1 < n && sql.charAt(i + 1) == '\'')) {
|
||||
boolean escapes = c != '\'';
|
||||
int start = i;
|
||||
i += escapes ? 2 : 1;
|
||||
StringBuilder value = new StringBuilder();
|
||||
while (i < n) {
|
||||
char d = sql.charAt(i);
|
||||
if (escapes && d == '\\' && i + 1 < n) {
|
||||
value.append(sql.charAt(i + 1));
|
||||
i += 2;
|
||||
} else if (d == '\'' && i + 1 < n && sql.charAt(i + 1) == '\'') {
|
||||
value.append('\'');
|
||||
i += 2;
|
||||
} else if (d == '\'') {
|
||||
i++;
|
||||
break;
|
||||
} else {
|
||||
value.append(d);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
tokens.add(new Token(Type.STRING, sql.substring(start, i), value.toString(), start, i));
|
||||
} else if (c == '"') {
|
||||
int start = i++;
|
||||
StringBuilder value = new StringBuilder();
|
||||
while (i < n) {
|
||||
char d = sql.charAt(i);
|
||||
if (d == '"' && i + 1 < n && sql.charAt(i + 1) == '"') {
|
||||
value.append('"');
|
||||
i += 2;
|
||||
} else if (d == '"') {
|
||||
i++;
|
||||
break;
|
||||
} else {
|
||||
value.append(d);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
tokens.add(new Token(Type.QUOTED_IDENTIFIER, sql.substring(start, i), value.toString(), start, i));
|
||||
} else if (c == '$' && dollarTagEnd(sql, i) > 0) {
|
||||
int tagEnd = dollarTagEnd(sql, i);
|
||||
String tag = sql.substring(i, tagEnd);
|
||||
int close = sql.indexOf(tag, tagEnd);
|
||||
int end = close < 0 ? n : close + tag.length();
|
||||
String value = sql.substring(tagEnd, close < 0 ? n : close);
|
||||
tokens.add(new Token(Type.STRING, sql.substring(i, end), value, i, end));
|
||||
i = end;
|
||||
} else if (Character.isLetter(c) || c == '_') {
|
||||
int start = i;
|
||||
while (i < n && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_' || sql.charAt(i) == '$')) {
|
||||
i++;
|
||||
}
|
||||
tokens.add(new Token(Type.WORD, sql.substring(start, i), null, start, i));
|
||||
} else if (Character.isDigit(c)) {
|
||||
int start = i;
|
||||
while (i < n && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '.')) {
|
||||
i++;
|
||||
}
|
||||
tokens.add(new Token(Type.NUMBER, sql.substring(start, i), null, start, i));
|
||||
} else {
|
||||
tokens.add(new Token(Type.SYMBOL, String.valueOf(c), null, i, i + 1));
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private static int dollarTagEnd(String sql, int at) {
|
||||
int i = at + 1;
|
||||
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_')) {
|
||||
if (i == at + 1 && Character.isDigit(sql.charAt(i))) {
|
||||
return -1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return i < sql.length() && sql.charAt(i) == '$' ? i + 1 : -1;
|
||||
}
|
||||
|
||||
static List<List<Token>> split(List<Token> tokens) {
|
||||
List<List<Token>> statements = new ArrayList<>();
|
||||
List<Token> current = new ArrayList<>();
|
||||
int depth = 0;
|
||||
for (Token token : tokens) {
|
||||
if ("(".equals(token.text()) && token.type() == Type.SYMBOL) {
|
||||
depth++;
|
||||
} else if (")".equals(token.text()) && token.type() == Type.SYMBOL) {
|
||||
depth = Math.max(0, depth - 1);
|
||||
}
|
||||
if (";".equals(token.text()) && token.type() == Type.SYMBOL && depth == 0) {
|
||||
statements.add(current);
|
||||
current = new ArrayList<>();
|
||||
} else {
|
||||
current.add(token);
|
||||
}
|
||||
}
|
||||
statements.add(current);
|
||||
return statements;
|
||||
}
|
||||
|
||||
private static String word(List<Token> tokens, int index) {
|
||||
if (index < 0 || index >= tokens.size() || tokens.get(index).type() != Type.WORD) {
|
||||
return "";
|
||||
}
|
||||
return tokens.get(index).upper();
|
||||
}
|
||||
|
||||
private static String identifier(Token token) {
|
||||
return switch (token.type()) {
|
||||
case QUOTED_IDENTIFIER -> token.value();
|
||||
case WORD -> token.lower();
|
||||
default -> token.text();
|
||||
};
|
||||
}
|
||||
|
||||
static String literal(String value) {
|
||||
return "'" + value.replace("'", "''") + "'";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user