diff --git a/README.md b/README.md index f1b314f417..70d418cbbe 100644 --- a/README.md +++ b/README.md @@ -337,7 +337,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | CloudWatch OAM | In-process | Full 15-operation sink, policy, cross-account link, and tagging API | | ElastiCache | Real Docker | Redis / Valkey protocol, IAM auth, SigV4 validation | | MemoryDB | Real Docker | Redis / Valkey protocol via real containers; JSON 1.1 control plane; reuses ElastiCache RESP proxy | -| Aurora DSQL | Real Docker, mock mode available | PostgreSQL 16 per cluster behind a TLS endpoint with IAM token auth for `admin`; no DSQL dialect yet | +| Aurora DSQL | Real Docker, mock mode available | PostgreSQL 16 per cluster behind a TLS endpoint with IAM token auth, `AWS IAM GRANT` role mappings; not yet DSQL's limits and async indexes | | RDS | Real Docker | PostgreSQL, MySQL, MariaDB, IAM auth, JDBC-compatible engines | | Timestream for InfluxDB | Real Docker, mock mode available | InfluxDB 2.x DB instances and read replica clusters via `influxdb:2.7`; initial auth secret in Secrets Manager; backups and restore through the influx CLI | | RDS Data API | REST JSON over real RDS containers | Raw SQL execution and transactions for local MySQL / MariaDB RDS resources | diff --git a/docs/services/dsql.md b/docs/services/dsql.md index 32af425c3f..e4e6fa2203 100644 --- a/docs/services/dsql.md +++ b/docs/services/dsql.md @@ -67,8 +67,10 @@ When Floci runs in Docker, publish `5432` alongside `4566`. wrong action is refused with the hint `Wrong user to action mapping. user: , action: `. - A token is accepted up to 5 seconds past its expiry, as DSQL accepts it; after that the hint is `Signature expired: ...`. -- Only `admin` signs in. DSQL lets another role in only for an IAM role that `AWS IAM GRANT` mapped - to it, which Floci does not support yet, so every other role is refused as an unmapped one is. +- A role other than `admin` signs in only for an IAM role or user that `AWS IAM GRANT` mapped to + it. The token's principal is the identity behind its credentials (a Lambda function's execution + role, an ECS task's role with `FLOCI_SERVICES_ECS_TASK_ROLE_CREDENTIALS_ENABLED`, an `AssumeRole` + session, an IAM user's key), its ARN with its path. - The signature is verified like any other Floci IAM token: the `test` key, or a key or session Floci issued. With `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED`, the principal also needs `dsql:DbConnectAdmin` or `dsql:DbConnect` on the cluster ARN. @@ -84,11 +86,31 @@ The database is PostgreSQL 16 at `REPEATABLE READ`, as DSQL's is, with the role the `public` schema and can create roles and databases. A connection closes after an hour, as DSQL closes it. +- `AWS IAM GRANT TO ''` and `AWS IAM REVOKE FROM ''`, for an IAM role or + user, with `sys.iam_pg_role_mappings`. A superuser role cannot be mapped, only a role holding the + `ADMIN` option on a role can map it (`admin` maps the roles it created), and a mapped role cannot + be dropped until its mappings are revoked. +- `sys.iam_session_user()` answers the connection's IAM principal and `sys.current_session_id()` + its session id, as on DSQL. +- `dsql` is a reserved prefix, as on DSQL: `SET`, `RESET`, `set_config`, `ALTER ROLE ... SET` and a + function's `SET` clause of a `dsql.` parameter fail with `42602` and `"dsql" is a reserved + prefix.`, and `SHOW` of one with `42704`. `set_config` of another dotted parameter is `0A000`, though + `SET` of one works. +- Errors carry no source location, as DSQL's carry none, and no line of Floci's `sys` functions in + their context; notices keep their location. + ### Differences from AWS -- DSQL's SQL dialect is not applied: what DSQL adds to PostgreSQL (`CREATE INDEX ASYNC`, `AWS IAM - GRANT`, the `sys` functions) is refused as PostgreSQL refuses it, what DSQL refuses works, and - DSQL's transaction limits (one DDL statement, 3,000 rows, 300 seconds) do not apply. +- The rest of DSQL's SQL dialect is not applied yet: `CREATE INDEX ASYNC` and its jobs are refused + as PostgreSQL refuses them, what DSQL refuses works, and DSQL's transaction limits (one DDL + statement, 3,000 rows, 300 seconds) do not apply. +- `sys` also holds the tables behind Floci's IAM mappings. +- Floci checks the statements a client sends, not what a `DO` block or a function body runs. In + one, `SET`, `RESET` and `set_config` of a `dsql.` parameter set it where DSQL refuses it, since + only a PostgreSQL extension written in C can reserve a prefix, and so does `set_config` of a name + built at run time, as in `set_config(chr(100) || 'sql.x', ...)`. Nothing Floci reads lives in such + a parameter. Likewise a `DROP ROLE` in one drops a mapped role: `sys.iam_pg_role_mappings` no + longer lists its mappings, and the next `AWS IAM GRANT` or `REVOKE` removes them. - DSQL is optimistic: conflicting transactions both run and the second to commit fails with `40001`. Floci's database is PostgreSQL, so a write that conflicts waits for the other transaction, then fails with PostgreSQL's `40001`. diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlDatabases.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlDatabases.java index 091cae4a3e..37a87e037a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlDatabases.java +++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlDatabases.java @@ -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", ""); } diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java index f243d38d00..7f19fba629 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java +++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java @@ -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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java index 6189afbe36..28fb381ee3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java +++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java @@ -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 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 statementTags = new HashMap<>(); + private final Map 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 parses = new ArrayDeque<>(); + final Deque binds = new ArrayDeque<>(); + final Deque closes = new ArrayDeque<>(); + final Deque 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> 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 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 fields = PostgresWire.parseFields(body, 0); + boolean changed = false; + String where = fields.get('W'); + if (where != null) { + List 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 fields = PostgresWire.parseFields(body, 0); - fields.remove('F'); - fields.remove('L'); - fields.remove('R'); fields.putIfAbsent('D', "Session Id: " + sessionId); return PostgresWire.fields(fields); } diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatements.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatements.java new file mode 100644 index 0000000000..9616ed1a66 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatements.java @@ -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 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 rewrite(String query) { + List statements = new ArrayList<>(); + for (List 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 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 parts = new ArrayList<>(); + List tags = new ArrayList<>(); + boolean changed = false; + for (List 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 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 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 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 tokens) { + int at = 2; + boolean ifExists = "IF".equals(word(tokens, at)) && "EXISTS".equals(word(tokens, at + 1)); + if (ifExists) { + at += 2; + } + List 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 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 tokenize(String sql) { + List 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> split(List tokens) { + List> statements = new ArrayList<>(); + List 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 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("'", "''") + "'"; + } +} diff --git a/src/main/resources/dsql/bootstrap.sql b/src/main/resources/dsql/bootstrap.sql index e94e529891..d39dd25bd7 100644 --- a/src/main/resources/dsql/bootstrap.sql +++ b/src/main/resources/dsql/bootstrap.sql @@ -1,7 +1,7 @@ -- What a cluster's PostgreSQL is before any client connects, as Aurora DSQL's database is (measured --- on AWS, eu-west-1, 2026-10-16): the role admin, which owns the public schema, and repeatable read. --- Installed by Floci as the superuser dbowner every time the database starts; every statement is --- idempotent. +-- on AWS, eu-west-1, 2026-10-16): the role admin, which owns the public schema, repeatable read, and +-- the sys schema with the session's identity and AWS IAM GRANT. Installed by Floci as the superuser +-- dbowner every time the database starts; every statement is idempotent. DO $$ BEGIN @@ -13,3 +13,178 @@ $$; GRANT CREATE ON DATABASE postgres TO admin; ALTER SCHEMA public OWNER TO admin; ALTER DATABASE postgres SET default_transaction_isolation TO 'repeatable read'; + +CREATE SCHEMA IF NOT EXISTS sys AUTHORIZATION dbowner; +GRANT USAGE ON SCHEMA sys TO PUBLIC; + +-- ── The session ─────────────────────────────────────────────────────────────── + +-- Each connection's IAM principal and session id, written by Floci's endpoint before the client's +-- first statement, keyed by the backend serving it. Only the definer functions read it, so a client +-- cannot change what its session reports. +CREATE TABLE IF NOT EXISTS sys.session_identity ( + pid integer PRIMARY KEY, + iam_session_user text NOT NULL, + session_id text NOT NULL +); +REVOKE ALL ON sys.session_identity FROM PUBLIC; + +-- name, as DSQL's answers it (measured: an ARN past 63 bytes is cut there). +CREATE OR REPLACE FUNCTION sys.iam_session_user() RETURNS name +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS +$$ SELECT iam_session_user::name FROM sys.session_identity WHERE pid = pg_backend_pid() $$; + +CREATE OR REPLACE FUNCTION sys.current_session_id() RETURNS text +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS +$$ SELECT session_id FROM sys.session_identity WHERE pid = pg_backend_pid() $$; + +-- A statement DSQL refuses, raised with DSQL's SQLSTATE and message. +CREATE OR REPLACE FUNCTION sys._reject(state text, message text, detail text DEFAULT NULL) RETURNS void +LANGUAGE plpgsql AS $$ +BEGIN + IF detail IS NULL THEN + RAISE EXCEPTION USING ERRCODE = state, MESSAGE = message; + END IF; + RAISE EXCEPTION USING ERRCODE = state, MESSAGE = message, DETAIL = detail; +END +$$; + +-- ── AWS IAM GRANT and REVOKE: which IAM role may log in as which database role ─ + +CREATE TABLE IF NOT EXISTS sys.iam_identity ( + oid bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + arn text COLLATE "C" NOT NULL UNIQUE +); +CREATE TABLE IF NOT EXISTS sys.iam_auth_member ( + member bigint NOT NULL REFERENCES sys.iam_identity (oid) ON DELETE CASCADE, + roleid oid NOT NULL, + grantor oid NOT NULL, + PRIMARY KEY (member, roleid) +); + +CREATE OR REPLACE VIEW sys.iam_pg_role_mappings AS +SELECT i.oid::oid AS iam_oid, i.arn, m.roleid AS pg_role_oid, a.rolname AS pg_role_name, + m.grantor AS grantor_pg_role_oid, b.rolname AS grantor_pg_role_name +FROM sys.iam_identity i +JOIN sys.iam_auth_member m ON i.oid = m.member +JOIN pg_authid a ON a.oid = m.roleid +LEFT JOIN pg_authid b ON b.oid = m.grantor; +GRANT SELECT ON sys.iam_pg_role_mappings TO PUBLIC; + +-- The role an IAM role may be trusted with: one that exists, is no superuser, and on which the caller +-- holds the ADMIN option, which admin holds on every role it created and on none other, itself +-- included. +CREATE OR REPLACE FUNCTION sys._trusted_role(role_name text, verb text, preposition text) RETURNS oid +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + role_oid oid; + superuser boolean; +BEGIN + SELECT oid, rolsuper INTO role_oid, superuser FROM pg_roles WHERE rolname = role_name; + IF role_oid IS NULL THEN + RAISE EXCEPTION USING ERRCODE = '42704', MESSAGE = format('role "%s" does not exist', role_name); + END IF; + IF superuser THEN + RAISE EXCEPTION USING ERRCODE = '0LP01', MESSAGE = format('cannot establish trust with role "%s"', role_name), + DETAIL = 'cannot GRANT/REVOKE IAM for roles with the SUPERUSER attribute'; + END IF; + IF NOT pg_has_role(session_user, role_oid, 'MEMBER WITH ADMIN OPTION') THEN + RAISE EXCEPTION USING ERRCODE = '42501', + MESSAGE = format('permission denied to %s IAM trust with role "%s"', verb, role_name), + DETAIL = format('Only roles with the ADMIN option on role "%s" may %s IAM trust %s this role.', + role_name, verb, preposition); + END IF; + RETURN role_oid; +END +$$; + +-- The mappings of a role dropped where Floci could not refuse it (a DO block or a function body), +-- and the identities left with no mapping, go with the next grant or revoke. +CREATE OR REPLACE PROCEDURE sys._forget_dropped_roles() +LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ + DELETE FROM sys.iam_auth_member m WHERE NOT EXISTS (SELECT 1 FROM pg_authid a WHERE a.oid = m.roleid); + DELETE FROM sys.iam_identity i WHERE NOT EXISTS (SELECT 1 FROM sys.iam_auth_member m WHERE m.member = i.oid); +$$; + +CREATE OR REPLACE PROCEDURE sys.aws_iam_grant(role_name text, iam_arn text) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + role_oid oid; + identity bigint; + granted_by text; +BEGIN + IF iam_arn !~ '^arn:aws[a-z-]*:iam::[0-9]{12}:(role|user)/.+' THEN + RAISE EXCEPTION USING ERRCODE = '0P000', MESSAGE = 'IAM role must look like an IAM ARN'; + END IF; + role_oid := sys._trusted_role(role_name, 'grant', 'to'); + CALL sys._forget_dropped_roles(); + INSERT INTO sys.iam_identity (arn) VALUES (iam_arn) ON CONFLICT (arn) DO NOTHING; + SELECT oid INTO identity FROM sys.iam_identity WHERE arn = iam_arn; + IF EXISTS (SELECT 1 FROM sys.iam_auth_member m WHERE m.member = identity AND m.roleid = role_oid) THEN + SELECT coalesce(b.rolname::text, m.grantor::text) INTO granted_by FROM sys.iam_auth_member m + LEFT JOIN pg_authid b ON b.oid = m.grantor + WHERE m.member = identity AND m.roleid = role_oid; + RAISE NOTICE 'IAM role "%" has already been granted access to role "%" by role "%"', + iam_arn, role_name, granted_by; + RETURN; + END IF; + INSERT INTO sys.iam_auth_member (member, roleid, grantor) + VALUES (identity, role_oid, (SELECT oid FROM pg_roles WHERE rolname = session_user)); +END +$$; + +CREATE OR REPLACE PROCEDURE sys.aws_iam_revoke(role_name text, iam_arn text) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + role_oid oid; + identity bigint; +BEGIN + IF iam_arn !~ '^arn:aws[a-z-]*:iam::[0-9]{12}:(role|user)/.+' THEN + RAISE EXCEPTION USING ERRCODE = '0P000', MESSAGE = 'IAM role must look like an IAM ARN'; + END IF; + role_oid := sys._trusted_role(role_name, 'revoke', 'from'); + SELECT oid INTO identity FROM sys.iam_identity WHERE arn = iam_arn; + IF identity IS NULL OR NOT EXISTS (SELECT 1 FROM sys.iam_auth_member WHERE member = identity AND roleid = role_oid) THEN + RAISE EXCEPTION USING ERRCODE = '42704', MESSAGE = format('IAM role "%s" does not exist', iam_arn); + END IF; + DELETE FROM sys.iam_auth_member WHERE member = identity AND roleid = role_oid; + CALL sys._forget_dropped_roles(); +END +$$; + +-- A role an IAM role or user is mapped to cannot be dropped, as on DSQL (measured): one detail line +-- per mapping, in the order they were granted. +CREATE OR REPLACE FUNCTION sys._trust_relationships(role_name text) RETURNS text +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ + SELECT string_agg(format('privileges for trust relationship of role %s with arn %s', role_name, i.arn), + E'\n' ORDER BY i.oid) + FROM sys.iam_auth_member m + JOIN sys.iam_identity i ON i.oid = m.member + JOIN pg_roles r ON r.oid = m.roleid + WHERE r.rolname = role_name +$$; + +-- DROP ROLE, USER or GROUP, which Floci's endpoint hands here: refused for a mapped role, otherwise +-- run as the caller. +CREATE OR REPLACE PROCEDURE sys.drop_roles(role_names text[], missing_ok boolean) +LANGUAGE plpgsql AS $$ +DECLARE + role_name text; + trust text; +BEGIN + FOREACH role_name IN ARRAY role_names LOOP + trust := sys._trust_relationships(role_name); + IF trust IS NOT NULL THEN + RAISE EXCEPTION USING ERRCODE = '2BP01', + MESSAGE = format('role "%s" cannot be dropped because some objects depend on it', role_name), + DETAIL = trust; + END IF; + END LOOP; + EXECUTE format('DROP ROLE %s%s', CASE WHEN missing_ok THEN 'IF EXISTS ' ELSE '' END, + (SELECT string_agg(quote_ident(name), ', ') FROM unnest(role_names) AS name)); +END +$$; + +REVOKE ALL ON sys.iam_identity, sys.iam_auth_member FROM PUBLIC; +REVOKE EXECUTE ON FUNCTION sys._trusted_role(text, text, text) FROM PUBLIC; +REVOKE EXECUTE ON PROCEDURE sys._forget_dropped_roles() FROM PUBLIC; diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlaneIntegrationTest.java index a2c7a77c5f..3e1b0760e1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlaneIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlaneIntegrationTest.java @@ -1,7 +1,9 @@ package io.github.hectorvent.floci.services.dsql; import com.github.dockerjava.api.DockerClient; +import io.github.hectorvent.floci.core.common.PostgresWire; import io.github.hectorvent.floci.services.dsql.dataplane.DsqlEndpoint; +import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.testing.EnforcementFixtures; import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper; @@ -16,8 +18,16 @@ 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.ssl.NonValidatingFactory; import org.postgresql.util.PSQLException; +import org.postgresql.util.PSQLWarning; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; @@ -25,6 +35,8 @@ import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; @@ -32,6 +44,7 @@ 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.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -48,6 +61,7 @@ class DsqlDataPlaneIntegrationTest { private static final String ACCOUNT = "111122223333"; private static final String REGION = "eu-west-1"; + private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT + ":role/service/app-role"; private static final String AUTH = "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261016/" + REGION + "/dsql/aws4_request, SignedHeaders=host, Signature=abc"; @@ -57,6 +71,9 @@ class DsqlDataPlaneIntegrationTest { @Inject DsqlEndpoint endpoint; + @Inject + IamService iamService; + @ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0") int httpPort; @@ -94,11 +111,14 @@ class DsqlDataPlaneIntegrationTest { 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')")) { + + " (SELECT nspowner::regrole::text FROM pg_namespace WHERE nspname = 'public')," + + " sys.iam_session_user(), length(sys.current_session_id())")) { assertTrue(row.next()); assertEquals("admin", row.getString(1)); assertEquals("repeatable read", row.getString(2)); assertEquals("admin", row.getString(3)); + assertEquals("arn:aws:iam::" + ACCOUNT + ":root", row.getString(4)); + assertEquals(26, row.getInt(5)); } } @@ -141,24 +161,197 @@ class DsqlDataPlaneIntegrationTest { 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 { + void aRoleLogsInOnlyForTheIamRoleMappedToIt() throws Exception { + String accessKeyId = "ASIA" + Long.toString(System.nanoTime(), 36).toUpperCase(); + String secret = "app+session/secret=key"; + String sessionToken = "IQoJb3JpZ2luX2VjEJr+app/role+session=="; + iamService.registerLambdaExecutionRoleSession(ACCOUNT, accessKeyId, secret, sessionToken, ROLE_ARN); 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", accessKeyId, secret, Instant.now(), 900, sessionToken)).close()); + assertEquals("unable to accept connection, access denied", unmapped.getServerErrorMessage().getMessage()); + assertEquals("28000", unmapped.getSQLState()); + + statement.execute("AWS IAM GRANT app_role TO '" + ROLE_ARN + "'"); + try (Connection app = connect("app_role", token("DbConnect", accessKeyId, secret, Instant.now(), 900, + sessionToken)); + Statement query = app.createStatement()) { + try (ResultSet row = query.executeQuery("SELECT current_user, sys.iam_session_user()")) { + assertTrue(row.next()); + assertEquals("app_role", row.getString(1)); + assertEquals(ROLE_ARN, row.getString(2)); + } + } + + statement.execute("AWS IAM GRANT app_role TO '" + ROLE_ARN + "'"); + assertEquals("IAM role \"" + ROLE_ARN + "\" has already been granted access to role \"app_role\" by role" + + " \"admin\"", ((PSQLWarning) statement.getWarnings()).getServerErrorMessage().getMessage()); + PSQLException mapped = assertThrows(PSQLException.class, () -> statement.execute("DROP ROLE app_role")); + assertEquals("2BP01", mapped.getSQLState()); + assertEquals("role \"app_role\" cannot be dropped because some objects depend on it", + mapped.getServerErrorMessage().getMessage()); + assertEquals("privileges for trust relationship of role app_role with arn " + ROLE_ARN, + mapped.getServerErrorMessage().getDetail()); + assertNull(mapped.getServerErrorMessage().getWhere()); + + PSQLException adminAction = assertThrows(PSQLException.class, () -> connect("app_role", + token("DbConnectAdmin", accessKeyId, secret, Instant.now(), 900, sessionToken)).close()); + assertEquals("Wrong user to action mapping. user: app_role, action: DbConnectAdmin", + adminAction.getServerErrorMessage().getHint()); + + PSQLException superuser = assertThrows(PSQLException.class, () -> + statement.execute("AWS IAM GRANT dbowner TO '" + ROLE_ARN + "'")); + assertEquals("0LP01", superuser.getSQLState()); + assertEquals("cannot establish trust with role \"dbowner\"", superuser.getServerErrorMessage().getMessage()); + PSQLException itself = assertThrows(PSQLException.class, () -> + statement.execute("AWS IAM GRANT admin TO '" + ROLE_ARN + "'")); + assertEquals("42501", itself.getSQLState()); + assertEquals("Only roles with the ADMIN option on role \"admin\" may grant IAM trust to this role.", + itself.getServerErrorMessage().getDetail()); + assertThrows(PSQLException.class, () -> connect("dbowner", + token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken)).close()); + + statement.execute("AWS IAM REVOKE app_role FROM '" + ROLE_ARN + "'"); + assertThrows(PSQLException.class, () -> connect("app_role", + token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken)).close()); + statement.execute("DROP ROLE app_role"); + } finally { + iamService.unregisterSession(ACCOUNT, accessKeyId); } + } - 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: ")); + @Test + void anIamUserLogsInForTheRoleMappedToIt() throws Exception { + String userName = "dsql-" + System.nanoTime(); + EnforcementFixtures.UserCredentials user = EnforcementFixtures.createUser(cleanup, httpPort, + EnforcementFixtures.auth(ACCOUNT, "iam"), userName); + String userArn = "arn:aws:iam::" + ACCOUNT + ":user/" + userName; + try (Connection admin = connect("admin", adminToken()); Statement statement = admin.createStatement()) { + statement.execute("CREATE ROLE user_role WITH LOGIN"); + statement.execute("AWS IAM GRANT user_role TO '" + userArn + "'"); + try (Connection app = connect("user_role", token("DbConnect", user.accessKeyId(), user.secretAccessKey(), + Instant.now(), 900, null)); + Statement query = app.createStatement(); + ResultSet row = query.executeQuery("SELECT current_user, sys.iam_session_user()")) { + assertTrue(row.next()); + assertEquals("user_role", row.getString(1)); + assertEquals(userArn, row.getString(2)); + } - 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()); + PSQLException group = assertThrows(PSQLException.class, () -> + statement.execute("AWS IAM GRANT user_role TO 'arn:aws:iam::" + ACCOUNT + ":group/g'")); + assertEquals("0P000", group.getSQLState()); + statement.execute("AWS IAM REVOKE user_role FROM '" + userArn + "'"); + statement.execute("DROP ROLE user_role"); + } + } + + @Test + void nothingASessionRunsChangesWhoItIs() throws Exception { + try (Connection connection = connect("admin", adminToken()); Statement statement = connection.createStatement()) { + statement.execute("CREATE FUNCTION spoof() RETURNS text LANGUAGE sql AS" + + " $$ SELECT set_config('dsql.iam_session_user', 'spoofed', false) $$"); + statement.execute("SELECT spoof()"); + try (ResultSet row = statement.executeQuery("SELECT sys.iam_session_user()")) { + assertTrue(row.next()); + assertEquals("arn:aws:iam::" + ACCOUNT + ":root", row.getString(1)); + } + PSQLException written = assertThrows(PSQLException.class, () -> + statement.execute("UPDATE sys.session_identity SET iam_session_user = 'spoofed'")); + assertEquals("42501", written.getSQLState()); + statement.execute("DROP FUNCTION spoof()"); + } + } + + @Test + void aRoleDroppedInsideAFunctionTakesItsMappingsWithIt() throws Exception { + try (Connection connection = connect("admin", adminToken()); Statement statement = connection.createStatement()) { + statement.execute("CREATE ROLE dropped_role"); + statement.execute("AWS IAM GRANT dropped_role TO '" + ROLE_ARN + "'"); + statement.execute("CREATE FUNCTION drop_it() RETURNS void LANGUAGE sql AS 'DROP ROLE dropped_role'"); + statement.execute("SELECT drop_it()"); + statement.execute("CREATE ROLE dropped_role"); + + String mappings = "SELECT count(*) FROM sys.iam_pg_role_mappings WHERE arn = '" + ROLE_ARN + "'" + + " AND pg_role_name = 'dropped_role'"; + try (ResultSet row = statement.executeQuery(mappings)) { + assertTrue(row.next()); + assertEquals(0, row.getInt(1)); + } + PSQLException none = assertThrows(PSQLException.class, () -> + statement.execute("AWS IAM REVOKE dropped_role FROM '" + ROLE_ARN + "'")); + assertEquals("42704", none.getSQLState()); + statement.execute("AWS IAM GRANT dropped_role TO '" + ROLE_ARN + "'"); + try (ResultSet row = statement.executeQuery(mappings)) { + assertTrue(row.next()); + assertEquals(1, row.getInt(1)); + } + statement.execute("AWS IAM REVOKE dropped_role FROM '" + ROLE_ARN + "'"); + statement.execute("DROP ROLE dropped_role"); + statement.execute("DROP FUNCTION drop_it()"); + } + } + + /** + * What a pipelining client sends before reading any answer: each statement shows its own command + * tag, and a Parse the database refuses leaves the statement it named as it was. + */ + @Test + void pipelinedStatementsShowTheirOwnCommandTags() throws Exception { + try (Connection admin = connect("admin", adminToken()); Statement statement = admin.createStatement()) { + statement.execute("CREATE ROLE pipelined_role"); + } + String grant = "AWS IAM GRANT pipelined_role TO '" + ROLE_ARN + "'"; + String revoke = "AWS IAM REVOKE pipelined_role FROM '" + ROLE_ARN + "'"; + try (WireClient client = new WireClient("admin", adminToken())) { + client.send(query("SELECT 1"), query(grant), query(revoke + "; SELECT 2")); + assertEquals(List.of("SELECT 1"), client.untilReady()); + assertEquals(List.of("AWS IAM GRANT"), client.untilReady()); + assertEquals(List.of("AWS IAM REVOKE", "SELECT 1"), client.untilReady()); + + client.send(parse("s1", "SELECT 1"), sync(), parse("s1", grant), sync(), + bind("s1"), execute(), sync()); + assertEquals(List.of(), client.untilReady()); + assertEquals(List.of("ERROR 42P05"), client.untilReady()); + assertEquals(List.of("SELECT 1"), client.untilReady()); + + client.send(close("s1"), parse("s1", grant), bind("s1"), execute(), parse("s2", revoke), bind("s2"), + execute(), sync(), query("SELECT 3")); + assertEquals(List.of("AWS IAM GRANT", "AWS IAM REVOKE"), client.untilReady()); + assertEquals(List.of("SELECT 1"), client.untilReady()); + } + try (Connection admin = connect("admin", adminToken()); Statement statement = admin.createStatement()) { + statement.execute("DROP ROLE pipelined_role"); + } + } + + @Test + void dsqlsParametersAreReservedAsDsqlReservesThem() throws Exception { + try (Connection connection = connect("admin", adminToken()); Statement statement = connection.createStatement()) { + for (String sql : List.of("SET dsql.x = 1", "RESET dsql.x", "SELECT set_config('dsql.x', '1', false)", + "ALTER ROLE admin SET dsql.x = 1", + "CREATE FUNCTION reserved() RETURNS int LANGUAGE sql SET dsql.x = 1 AS 'SELECT 1'")) { + PSQLException reserved = assertThrows(PSQLException.class, () -> statement.execute(sql), sql); + assertEquals("42602", reserved.getSQLState(), sql); + assertEquals("invalid configuration parameter name \"dsql.x\"", + reserved.getServerErrorMessage().getMessage(), sql); + assertEquals("\"dsql\" is a reserved prefix.", reserved.getServerErrorMessage().getDetail(), sql); + } + PSQLException shown = assertThrows(PSQLException.class, () -> statement.execute("SHOW dsql.session_id")); + assertEquals("42704", shown.getSQLState()); + assertEquals("unrecognized configuration parameter \"dsql.session_id\"", + shown.getServerErrorMessage().getMessage()); + + PSQLException custom = assertThrows(PSQLException.class, () -> + statement.execute("SELECT set_config('myapp.foo', 'x', false)")); + assertEquals("0A000", custom.getSQLState()); + assertEquals("setting configuration parameter \"myapp.foo\" not supported", + custom.getServerErrorMessage().getMessage()); + statement.execute("SET myapp.foo = 'x'"); + } } @Test @@ -185,12 +378,14 @@ class DsqlDataPlaneIntegrationTest { assertEquals(null, fromTheDatabase.getServerErrorMessage().getFile()); Properties ignored = properties("admin", adminToken()); - ignored.setProperty("options", "--search_path=elsewhere -c search_path=first -c search_path=second"); + ignored.setProperty("options", "--dsql.iam_session_user=spoofed --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')")) { + ResultSet row = statement.executeQuery("SELECT current_setting('search_path'), sys.iam_session_user()")) { assertTrue(row.next()); assertEquals("first", row.getString(1)); + assertEquals("arn:aws:iam::" + ACCOUNT + ":root", row.getString(2)); } } @@ -211,6 +406,91 @@ class DsqlDataPlaneIntegrationTest { assertEquals("unable to accept connection, access denied", foreign.getServerErrorMessage().getMessage()); } + /** A client that writes the wire protocol itself, to send what JDBC sends one message at a time. */ + private final class WireClient implements AutoCloseable { + + private final Socket socket; + private final InputStream in; + private final OutputStream out; + + WireClient(String user, String password) throws Exception { + Socket plain = new Socket("127.0.0.1", endpoint.port()); + plain.getOutputStream().write(PostgresWire.int32(8)); + plain.getOutputStream().write(PostgresWire.int32(PostgresWire.SSL_REQUEST)); + assertEquals('S', plain.getInputStream().read()); + socket = new NonValidatingFactory(null).createSocket(plain, host, endpoint.port(), true); + in = new BufferedInputStream(socket.getInputStream()); + out = socket.getOutputStream(); + Map startup = new LinkedHashMap<>(); + startup.put("user", user); + startup.put("database", "postgres"); + out.write(PostgresWire.startupMessage(startup)); + assertEquals('R', PostgresWire.read(in, Integer.MAX_VALUE, "message").type()); + send(message('p', PostgresWire.cStringBytes(password))); + untilReady(); + } + + void send(byte[]... messages) throws IOException { + for (byte[] message : messages) { + out.write(message); + } + out.flush(); + } + + /** The command tags, and the SQLSTATE of an error, up to the next ReadyForQuery. */ + List untilReady() throws IOException { + List answers = new ArrayList<>(); + while (true) { + PostgresWire.Message message = PostgresWire.read(in, Integer.MAX_VALUE, "message"); + switch (message.type()) { + case 'C' -> answers.add(PostgresWire.cString(message.body(), 0).value()); + case 'E' -> answers.add("ERROR " + PostgresWire.parseFields(message.body(), 0).get('C')); + case 'Z' -> { + return answers; + } + default -> { + } + } + } + } + + @Override + public void close() throws IOException { + socket.close(); + } + } + + private static byte[] query(String sql) throws IOException { + return message('Q', PostgresWire.cStringBytes(sql)); + } + + private static byte[] parse(String statement, String sql) throws IOException { + return message('P', PostgresWire.cStringBytes(statement), PostgresWire.cStringBytes(sql), new byte[2]); + } + + /** The unnamed portal for {@code statement}, with no parameters and text results. */ + private static byte[] bind(String statement) throws IOException { + return message('B', PostgresWire.cStringBytes(""), PostgresWire.cStringBytes(statement), new byte[6]); + } + + private static byte[] execute() throws IOException { + return message('E', PostgresWire.cStringBytes(""), PostgresWire.int32(0)); + } + + private static byte[] close(String statement) throws IOException { + return message('C', new byte[] {'S'}, PostgresWire.cStringBytes(statement)); + } + + private static byte[] sync() throws IOException { + return message('S'); + } + + private static byte[] message(int type, byte[]... parts) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + PostgresWire.write(bytes, type, parts); + return bytes.toByteArray(); + } + /** 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"), diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSessionTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSessionTest.java index e189d79ef2..f52535e49e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSessionTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSessionTest.java @@ -1,11 +1,16 @@ package io.github.hectorvent.floci.services.dsql.dataplane; +import io.github.hectorvent.floci.core.common.PostgresWire; import org.junit.jupiter.api.Test; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; class DsqlSessionTest { @@ -37,4 +42,87 @@ class DsqlSessionTest { assertEquals(null, DsqlSession.customParameter(Map.of("search_path", "public"), Map.of("user", "admin", "options", "-c search_path=public"))); } + + @Test + void anErrorRaisedInsideSysCarriesNeitherContextNorLocation() { + byte[] postgres = error(Map.of('C', "0A000", 'M', "unsupported statement: Truncate", + 'W', "PL/pgSQL function sys._reject(text,text,text) line 4 at RAISE", + 'F', "pl_exec.c", 'L', "3926", 'R', "exec_stmt_raise")); + + Map fields = PostgresWire.parseFields(DsqlSession.inDsqlWords((byte) 'E', postgres), 0); + + assertEquals("unsupported statement: Truncate", fields.get('M')); + assertFalse(fields.containsKey('W')); + assertFalse(fields.containsKey('F')); + assertFalse(fields.containsKey('L')); + assertFalse(fields.containsKey('R')); + } + + @Test + void aNoticeRaisedInsideSysKeepsItsLocationAsWaitForJobsDoesOnDsql() { + byte[] postgres = error(Map.of('S', "NOTICE", 'C', "00000", 'M', "Job execution succeeded for job with id x", + 'W', "PL/pgSQL function sys.wait_for_job(text,boolean) line 7 at RAISE", + 'F', "pl_exec.c", 'L', "3926", 'R', "exec_stmt_raise")); + + Map fields = PostgresWire.parseFields(DsqlSession.inDsqlWords((byte) 'N', postgres), 0); + + assertFalse(fields.containsKey('W')); + assertTrue(fields.containsKey('F')); + assertEquals("exec_stmt_raise", fields.get('R')); + } + + @Test + void whatASysFunctionRanLeavesTheContextWithIt() { + byte[] postgres = error(Map.of('C', "42704", 'M', "role \"nosuch\" does not exist", + 'W', "SQL statement \"DROP ROLE nosuch\"\nPL/pgSQL function sys.drop_roles(text[],boolean) line 13" + + " at EXECUTE")); + + Map fields = PostgresWire.parseFields(DsqlSession.inDsqlWords((byte) 'E', postgres), 0); + + assertFalse(fields.containsKey('W')); + } + + @Test + void theClientsOwnFramesAroundASysCallStay() { + byte[] postgres = error(Map.of('C', "22012", 'M', "division by zero", + 'W', "SQL statement \"SELECT\n 1 / 0\"\nPL/pgSQL function sys.probe() line 3 at PERFORM\n" + + "SQL function \"f\" statement 1")); + + Map fields = PostgresWire.parseFields(DsqlSession.inDsqlWords((byte) 'E', postgres), 0); + + assertEquals("SQL function \"f\" statement 1", fields.get('W')); + } + + @Test + void anErrorFromTheClientsOwnSqlIsLeftAlone() { + byte[] postgres = error(Map.of('C', "23505", 'M', "duplicate key value violates unique constraint \"t_u\"", + 'W', "SQL function \"f\" statement 1")); + + assertArrayEquals(postgres, DsqlSession.inDsqlWords((byte) 'E', postgres)); + } + + @Test + void postgresqlsOwnErrorLosesItsSourceLocationAsOnDsql() { + byte[] postgres = error(Map.of('C', "23503", 'M', "insert or update on table \"child\" violates foreign key" + + " constraint \"child_parent_id_fkey\"", 'F', "ri_triggers.c", 'L', "2608", 'R', "ri_ReportViolation")); + + Map fields = PostgresWire.parseFields(DsqlSession.inDsqlWords((byte) 'E', postgres), 0); + + assertEquals("23503", fields.get('C')); + assertFalse(fields.containsKey('F')); + assertFalse(fields.containsKey('L')); + assertFalse(fields.containsKey('R')); + } + + private static byte[] error(Map fields) { + Map ordered = new LinkedHashMap<>(); + ordered.put('S', fields.getOrDefault('S', "ERROR")); + ordered.put('V', fields.getOrDefault('S', "ERROR")); + fields.forEach((code, value) -> { + if (code != 'S') { + ordered.put(code, value); + } + }); + return PostgresWire.fields(ordered); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatementsTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatementsTest.java new file mode 100644 index 0000000000..30dac8b657 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatementsTest.java @@ -0,0 +1,118 @@ +package io.github.hectorvent.floci.services.dsql.dataplane; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class DsqlStatementsTest { + + @Test + void awsIamGrantAndRevokeBecomeCallsWithDsqlsCommandTags() { + List statements = DsqlStatements.rewrite( + "AWS IAM GRANT App_Role TO 'arn:aws:iam::123456789012:role/app';" + + " aws iam revoke \"Mixed\" from 'arn:aws:iam::123456789012:role/o''x'"); + + assertEquals("CALL sys.aws_iam_grant('app_role', 'arn:aws:iam::123456789012:role/app')", + statements.get(0).sql()); + assertEquals("AWS IAM GRANT", statements.get(0).commandTag()); + assertEquals("CALL sys.aws_iam_revoke('Mixed', 'arn:aws:iam::123456789012:role/o''x')", + statements.get(1).sql()); + assertEquals("AWS IAM REVOKE", statements.get(1).commandTag()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "SET dsql.x = 1|dsql.x", + "SET LOCAL dsql.row_count TO 0|dsql.row_count", + "RESET dsql.x|dsql.x", + "SELECT set_config('dsql.internal', 'on', false)|dsql.internal", + "SELECT 1, set_config('dsql.x', '1', true) FROM t|dsql.x", + "ALTER ROLE admin SET dsql.x = 1|dsql.x", + "ALTER ROLE admin IN DATABASE postgres RESET dsql.x|dsql.x", + "CREATE FUNCTION f() RETURNS int LANGUAGE sql SET dsql.x = 1 AS 'SELECT 1'|dsql.x", + "SET \"dsql\".x = 1|dsql.x", + "SELECT \"set_config\"('dsql.x', '1', false)|dsql.x", + }) + void theDsqlPrefixIsReservedOnEveryChannel(String sql, String name) { + assertEquals(DsqlStatements.reject("42602", "invalid configuration parameter name \"" + name + "\"", + "\"dsql\" is a reserved prefix."), DsqlStatements.rewrite(sql).get(0).sql()); + } + + @Test + void showingADsqlParameterFindsNone() { + assertEquals(DsqlStatements.reject("42704", "unrecognized configuration parameter \"dsql.session_id\"", null), + DsqlStatements.rewrite("SHOW dsql.session_id").get(0).sql()); + } + + @Test + void setConfigOfAnotherDottedParameterIsNotSupportedThoughSetIs() { + assertEquals(DsqlStatements.reject("0A000", "setting configuration parameter \"myapp.foo\" not supported", null), + DsqlStatements.rewrite("SELECT set_config('myapp.foo', 'x', false)").get(0).sql()); + assertEquals("SET myapp.foo = 'x'", DsqlStatements.rewrite("SET myapp.foo = 'x'").get(0).sql()); + assertEquals("SELECT set_config('search_path', 'public', false)", + DsqlStatements.rewrite("SELECT set_config('search_path', 'public', false)").get(0).sql()); + } + + @Test + void dropRoleBecomesTheCallThatRefusesAMappedRole() { + assertEquals("CALL sys.drop_roles(ARRAY['app_role', 'Mixed']::text[], false)", + DsqlStatements.rewrite("DROP ROLE App_Role, \"Mixed\"").get(0).sql()); + DsqlStatements.Statement user = DsqlStatements.rewrite("drop user if exists u").get(0); + assertEquals("CALL sys.drop_roles(ARRAY['u']::text[], true)", user.sql()); + assertEquals("DROP ROLE", user.commandTag()); + assertEquals("DROP ROLE", DsqlStatements.rewrite("DROP GROUP g").get(0).commandTag()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "SET search_path TO probe", + "DROP ROLE CURRENT_USER", + "DROP ROLE IF EXISTS", + "DROP ROLE a b", + "DROP ROLE a,", + "SELECT 'AWS IAM GRANT a TO b' AS text", + "CREATE INDEX ON t (n)", + "TRUNCATE t", + }) + void whatIsNotDsqlsOwnSyntaxPassesUnchanged(String sql) { + assertEquals(sql, DsqlStatements.rewrite(sql).get(0).sql()); + } + + @Test + void aQueryWithNothingToRewriteGoesToTheDatabaseExactlyAsSent() { + String query = "-- comment\nSELECT 1;\n/* two */ SELECT 'a;b';"; + + DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query); + + assertEquals(query, rewritten.sql()); + assertEquals(false, rewritten.overridesTags()); + } + + @Test + void aQueryWithDsqlSyntaxIsRewrittenStatementByStatementWithItsTags() { + DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery( + "SELECT 1; AWS IAM GRANT app TO 'arn:aws:iam::123456789012:role/app'"); + + assertEquals("SELECT 1;\nCALL sys.aws_iam_grant('app', 'arn:aws:iam::123456789012:role/app')", + rewritten.sql()); + assertEquals(Arrays.asList(null, "AWS IAM GRANT"), rewritten.commandTags()); + assertEquals(true, rewritten.overridesTags()); + } + + @Test + void statementsAreSplitOutsideStringsCommentsAndDollarQuotes() { + List statements = DsqlStatements.rewrite( + "SELECT 'a;b'; /* ; */ SELECT $f$ ; $f$ -- ;\n; SELECT \"x;y\""); + + assertEquals(3, statements.size()); + assertEquals("SELECT 'a;b'", statements.get(0).sql()); + assertEquals("SELECT $f$ ; $f$", statements.get(1).sql()); + assertEquals("SELECT \"x;y\"", statements.get(2).sql()); + } +}