feat(dsql): translate role names and record each cluster's roles (#8631)

This commit is contained in:
Joaquín Gamboa authored and GitHub committed 2026-11-16 19:22:41 -04:00
1 parent 98b66319a9
commit 3007534104
11 files changed
+1800 -63

No files matched your search

@@ -123,10 +123,25 @@ public class DockerDsqlBackend implements DsqlBackend {
}
private static void awaitReady(DsqlDatabases.Backend backend) throws SQLException {
Instant deadline = Instant.now().plus(READY_TIMEOUT);
awaitReady(() -> DsqlDatabases.superuser(backend), READY_TIMEOUT);
}
/** Opens a connection to the database {@link #awaitReady(Connector, Duration)} waits for. */
@FunctionalInterface
public interface Connector {
Connection open() throws SQLException;
}
/**
* Runs {@code SELECT 1} through a connection from {@code connector} every 250 ms until it
* succeeds or {@code timeout} has passed, as a PostgreSQL that is still starting refuses
* connections. Public for the tests' throwaway PostgreSQL servers, which wait the same way.
*/
public static void awaitReady(Connector connector, Duration timeout) throws SQLException {
Instant deadline = Instant.now().plus(timeout);
SQLException last = null;
while (Instant.now().isBefore(deadline)) {
try (Connection connection = DsqlDatabases.superuser(backend); Statement statement = connection.createStatement()) {
try (Connection connection = connector.open(); Statement statement = connection.createStatement()) {
statement.execute("SELECT 1");
return;
} catch (SQLException e) {
@@ -139,11 +154,11 @@ public class DockerDsqlBackend implements DsqlBackend {
}
}
}
throw new SQLException("The database did not start within " + READY_TIMEOUT.toSeconds() + " s", last);
throw new SQLException("The database did not start within " + timeout.toSeconds() + " s", last);
}
private static void bootstrap(DsqlDatabases.Backend backend) throws SQLException {
String script = DsqlBootstrap.render(DATABASE, SUPERUSER, DsqlEndpoint.ADMIN);
String script = DsqlBootstrap.render(DATABASE, SUPERUSER, DsqlEndpoint.ADMIN, "", "", false);
try (Connection connection = DsqlDatabases.superuser(backend); Statement statement = connection.createStatement()) {
statement.execute(script);
}
@@ -8,8 +8,10 @@ import java.nio.charset.StandardCharsets;
/**
* Renders the DSQL bootstrap script for the database, owner role and admin role of one cluster.
* The script's placeholders: {@code {{database}}}, {@code {{owner}}} and {@code {{admin}}} as
* identifiers, always quoted; {@code {{owner_literal}}} and {@code {{admin_literal}}}
* as SQL string literals.
* identifiers, always quoted; {@code {{owner_literal}}}, {@code {{admin_literal}}},
* {@code {{connect_role_literal}}} and {@code {{role_prefix}}} as SQL string literals
* ({@code 'dabc_'}, or {@code ''} for no prefix); {@code {{external}}} as the SQL boolean
* {@code true} or {@code false}.
*/
final class DsqlBootstrap {
@@ -18,14 +20,28 @@ final class DsqlBootstrap {
private DsqlBootstrap() {
}
/** The script for one cluster's database. */
static String render(String database, String owner, String admin) {
/**
* The script for one cluster's database. {@code rolePrefix} is what the cluster's backend role
* names start with (empty in Docker mode), and {@code external} says whether the database is one
* of many on a shared server, whose roles are not all the cluster's. There, {@code connectRole}
* names the NOLOGIN role through which the cluster's roles may connect to its database, which
* PUBLIC may not; it must not start with {@code rolePrefix}. In Docker mode it is unused and empty.
*/
static String render(String database, String owner, String admin, String connectRole, String rolePrefix,
boolean external) {
if (external && (connectRole.isEmpty() || connectRole.startsWith(rolePrefix))) {
throw new IllegalArgumentException("The external bootstrap needs a connect role outside the prefix "
+ rolePrefix + ", not \"" + connectRole + "\"");
}
return template()
.replace("{{database}}", identifier(database))
.replace("{{owner_literal}}", literal(owner))
.replace("{{owner}}", identifier(owner))
.replace("{{admin_literal}}", literal(admin))
.replace("{{admin}}", identifier(admin));
.replace("{{admin}}", identifier(admin))
.replace("{{connect_role_literal}}", literal(connectRole))
.replace("{{role_prefix}}", literal(rolePrefix))
.replace("{{external}}", Boolean.toString(external));
}
private static String template() {
@@ -1,9 +1,13 @@
package io.floci.aws.services.dsql.dataplane;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
/**
* The statements of a query as Aurora DSQL reads them. DSQL's own syntax ({@code CREATE INDEX
@@ -28,8 +32,19 @@ public final class DsqlStatements {
private static final String RESERVED_PREFIX = "dsql.";
private static final Set<String> ISOLATION_PARAMETERS = Set.of("default_transaction_isolation", "transaction_isolation");
private static final Set<String> ROLE_KINDS = Set.of("ROLE", "USER", "GROUP");
private static final Set<String> ROLE_SPECIFIERS = Set.of("CURRENT_ROLE", "CURRENT_USER", "SESSION_USER", "PUBLIC",
"NONE");
/** What PostgreSQL 16 lets {@code REVOKE <option> OPTION FOR} take back of a role's grant. */
private static final Set<String> ROLE_GRANT_OPTIONS = Set.of("ADMIN", "INHERIT", "SET");
private static final Set<String> RENAME_TARGETS = Set.of("RENAME", "COLUMN", "CONSTRAINT", "ATTRIBUTE");
private static final Pattern SIMPLE_IDENTIFIER = Pattern.compile("[a-z_][a-z0-9_$]*");
/**
* The role procedures Floci itself calls, with their signatures: on a shared server a client's
* own call would hand role DDL to the database without its names translated.
*/
private static final Map<String, String> INTERNAL_ROUTINES = Map.of(
"run_role_ddl", "text",
"drop_roles", "text[], boolean",
"aws_iam_grant", "text, text",
"aws_iam_revoke", "text, text");
private DsqlStatements() {
}
@@ -40,13 +55,21 @@ public final class DsqlStatements {
/** The statements of {@code query}, each rewritten as DSQL reads it, in order. */
public static List<Statement> rewrite(String query) {
return rewrite(query, RoleNames.IDENTITY);
}
/**
* The statements of {@code query}, each rewritten as DSQL reads it, in order, with the roles
* it names as {@code names} has them in the database.
*/
public static List<Statement> rewrite(String query, RoleNames names) {
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));
statements.add(rewrite(text, tokens, names));
}
return statements;
}
@@ -68,6 +91,14 @@ public final class DsqlStatements {
* needed rewriting, the query exactly as the client sent it.
*/
public static Query rewriteQuery(String query) {
return rewriteQuery(query, RoleNames.IDENTITY);
}
/**
* The whole query as the database runs it, with the roles it names as {@code names} has them
* in the database. With {@link RoleNames#IDENTITY} it is {@link #rewriteQuery(String)}.
*/
public static Query rewriteQuery(String query, RoleNames names) {
List<String> parts = new ArrayList<>();
List<String> tags = new ArrayList<>();
boolean changed = false;
@@ -76,7 +107,7 @@ public final class DsqlStatements {
continue;
}
String text = query.substring(tokens.get(0).start(), tokens.get(tokens.size() - 1).end());
Statement statement = rewrite(text, tokens);
Statement statement = rewrite(text, tokens, names);
changed |= statement.commandTag() != null || !statement.sql().equals(text);
parts.add(statement.sql());
tags.add(statement.commandTag());
@@ -90,6 +121,114 @@ public final class DsqlStatements {
+ (detail == null ? "" : ", " + literal(detail)) + ")";
}
/**
* The statement with each role it names as {@code names} has it in the database, then rewritten
* as DSQL reads it. A name too long to carry the backend's prefix within PostgreSQL's 63-byte
* identifier, counted in UTF-8 bytes, refuses the statement.
*/
private static Statement rewrite(String text, List<Token> tokens, RoleNames names) {
if (names.isIdentity()) {
return rewrite(text, tokens);
}
Statement internal = internalRoutineCall(tokens);
if (internal != null) {
return internal;
}
int base = tokens.get(0).start();
StringBuilder translated = new StringBuilder();
int copied = 0;
boolean changed = false;
for (int index : roleNamePositions(tokens)) {
Token token = tokens.get(index);
if (token.malformed()) {
// Left as written, so PostgreSQL refuses it as it would without Floci.
continue;
}
boolean string = token.type() == Type.STRING;
String logical = string ? token.value() : identifier(token);
// A string constant names a role exactly, as a quoted identifier does.
String backend = names.toBackend(logical, string || token.type() == Type.QUOTED_IDENTIFIER);
if (backend.equals(logical)) {
continue;
}
// PostgreSQL would truncate a longer name, and a login by the full name would not find it.
if (logical.getBytes(StandardCharsets.UTF_8).length > PrefixedRoleNames.MAX_LOGICAL
|| backend.getBytes(StandardCharsets.UTF_8).length > PrefixedRoleNames.MAX_IDENTIFIER_BYTES) {
return rejected("42602", "role name \"" + logical + "\" is too long for Floci's external backend (max "
+ PrefixedRoleNames.MAX_LOGICAL + " bytes)");
}
// A string constant goes back as a quoted identifier, which SET ROLE and SET SESSION
// AUTHORIZATION read alike, and whose quoting, unlike a string's, does not depend on
// standard_conforming_strings. The prefixed name is never none.
translated.append(text, copied, token.start() - base)
.append(roleIdentifier(backend, string || token.type() == Type.QUOTED_IDENTIFIER));
copied = token.end() - base;
changed = true;
}
if (!changed) {
return rewrite(text, tokens);
}
String sql = translated.append(text, copied, text.length()).toString();
return rewrite(sql, tokenize(sql));
}
/**
* A call the client wrote to one of Floci's internal routines, refused as PostgreSQL refuses a
* routine that does not exist: {@code sys.run_role_ddl}, {@code sys.drop_roles},
* {@code sys.aws_iam_grant} and {@code sys.aws_iam_revoke}, and any {@code sys._*} routine,
* each qualified with {@code sys}: an unqualified name may be the client's own table or function. Read from the client's tokens, before Floci adds calls of its own.
* A name spelled with {@code U&} escapes is read as it decodes. An unqualified call PostgreSQL
* resolves through a {@code search_path} naming {@code sys}, or a call built inside a routine
* body, is not seen here; what untranslated role DDL can do there is bounded by PostgreSQL 16's
* CREATEROLE and by what {@code sys._record_backend_roles} records: only roles under the
* cluster's prefix, reached through ADMIN options its own roles were given.
*/
private static Statement internalRoutineCall(List<Token> tokens) {
for (int i = 0; i + 1 < tokens.size(); i++) {
if (!isName(tokens, i) || !"(".equals(tokens.get(i + 1).text()) || tokens.get(i + 1).type() != Type.SYMBOL) {
continue;
}
String routine = identifier(tokens.get(i));
boolean qualified = i >= 2 && ".".equals(tokens.get(i - 1).text()) && tokens.get(i - 1).type() == Type.SYMBOL;
boolean inSys = qualified && isName(tokens, i - 2) && "sys".equals(identifier(tokens.get(i - 2)));
boolean internal = inSys && (INTERNAL_ROUTINES.containsKey(routine) || routine.startsWith("_"));
if (internal) {
String kind = "CALL".equals(word(tokens, qualified ? i - 3 : i - 1)) ? "procedure" : "function";
String signature = INTERNAL_ROUTINES.getOrDefault(routine, argumentTypes(tokens, i + 1));
return rejected("42883", kind + " sys." + routine + "(" + signature + ") does not exist");
}
}
return null;
}
/** The arguments of the call whose parenthesis is at {@code open}, each of an unknown type. */
private static String argumentTypes(List<Token> tokens, int open) {
List<String> types = new ArrayList<>();
int depth = 0;
boolean argument = false;
for (int i = open + 1; i < tokens.size(); i++) {
Token token = tokens.get(i);
boolean symbol = token.type() == Type.SYMBOL;
if (symbol && "(".equals(token.text())) {
depth++;
} else if (symbol && ")".equals(token.text())) {
if (depth == 0) {
break;
}
depth--;
} else if (symbol && ",".equals(token.text()) && depth == 0) {
types.add("unknown");
argument = false;
continue;
}
argument = true;
}
if (argument) {
types.add("unknown");
}
return String.join(", ", types);
}
private static Statement rewrite(String text, List<Token> tokens) {
String first = word(tokens, 0);
String second = word(tokens, 1);
@@ -202,7 +341,7 @@ public final class DsqlStatements {
}
Token role = tokens.get(3);
String roleName = switch (role.type()) {
case WORD -> role.lower();
case WORD -> role.folded();
case QUOTED_IDENTIFIER -> role.value();
default -> null;
};
@@ -371,7 +510,7 @@ public final class DsqlStatements {
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());
boolean specifier = name.type() == Type.WORD && PrefixedRoleNames.SPECIFIERS.contains(name.folded());
if (specifier || name.type() != Type.WORD && name.type() != Type.QUOTED_IDENTIFIER) {
return null;
}
@@ -472,17 +611,289 @@ public final class DsqlStatements {
return new Statement(reject(state, message, null), null);
}
// ── Role names ────────────────────────────────────────────────────────────
/**
* The indexes of the tokens that name a role where the statement's grammar places one: role
* DDL and the role lists of {@code GRANT} and {@code REVOKE}, ownership ({@code OWNER TO},
* {@code REASSIGN} and {@code DROP OWNED}), {@code SET ROLE}, {@code SET SESSION AUTHORIZATION},
* {@code CREATE SCHEMA ... AUTHORIZATION}, policies, default privileges, {@code DROP ROLE} and
* {@code AWS IAM GRANT|REVOKE}. Specifiers are included; the caller leaves what
* {@link RoleNames} keeps as it is.
*/
private static Set<Integer> roleNamePositions(List<Token> tokens) {
Set<Integer> at = new TreeSet<>();
String first = word(tokens, 0);
String second = word(tokens, 1);
switch (first) {
case "CREATE", "ALTER" -> {
boolean alter = "ALTER".equals(first);
if (ROLE_KINDS.contains(second) && !"MAPPING".equals(word(tokens, 2))) {
roleDdlNames(tokens, alter, at);
} else if ("POLICY".equals(second)) {
policyRoles(tokens, at);
} else if (!alter && "SCHEMA".equals(second)) {
for (int i = 2; i <= 6 && i < tokens.size(); i++) {
if ("AUTHORIZATION".equals(word(tokens, i))) {
addName(tokens, i + 1, at);
break;
}
}
} else if (alter && "DEFAULT".equals(second) && "PRIVILEGES".equals(word(tokens, 2))) {
int i = 3;
if ("FOR".equals(word(tokens, i)) && ("ROLE".equals(word(tokens, i + 1))
|| "USER".equals(word(tokens, i + 1)))) {
i = roleList(tokens, i + 2, false, at);
}
while (i < tokens.size() && !"GRANT".equals(word(tokens, i)) && !"REVOKE".equals(word(tokens, i))) {
i++;
}
grantRoles(tokens, i, at);
}
if (alter) {
for (int i = 2; i + 2 < tokens.size(); i++) {
// A column, constraint or attribute called owner, renamed, is not the OWNER TO clause.
boolean renamed = RENAME_TARGETS.contains(word(tokens, i - 1));
if (!renamed && "OWNER".equals(word(tokens, i)) && "TO".equals(word(tokens, i + 1))) {
addName(tokens, i + 2, at);
}
}
}
}
case "GRANT", "REVOKE" -> grantRoles(tokens, 0, at);
case "SET" -> setRole(tokens, at);
case "DROP" -> {
if (ROLE_KINDS.contains(second)) {
int i = 2;
if ("IF".equals(word(tokens, i)) && "EXISTS".equals(word(tokens, i + 1))) {
i += 2;
}
roleList(tokens, i, false, at);
} else if ("OWNED".equals(second) && "BY".equals(word(tokens, 2))) {
roleList(tokens, 3, false, at);
}
}
case "REASSIGN" -> {
if ("OWNED".equals(second) && "BY".equals(word(tokens, 2))) {
int i = roleList(tokens, 3, false, at);
if ("TO".equals(word(tokens, i))) {
addName(tokens, i + 1, at);
}
}
}
case "AWS" -> {
String third = word(tokens, 2);
if ("IAM".equals(second) && ("GRANT".equals(third) || "REVOKE".equals(third))) {
addName(tokens, 3, at);
}
}
default -> {
}
}
return at;
}
/**
* {@code CREATE|ALTER ROLE|USER|GROUP name}: the role, the role lists of its options
* ({@code IN ROLE}, {@code IN GROUP}, {@code ROLE}, {@code ADMIN}, {@code USER}) and a new name
* after {@code RENAME TO}. What follows {@code SET} or {@code RESET} names a parameter, not a role.
*/
private static void roleDdlNames(List<Token> tokens, boolean alter, Set<Integer> at) {
if (!(alter && "ALL".equals(word(tokens, 2)))) {
addName(tokens, 2, at);
}
int i = 3;
while (i < tokens.size()) {
String word = word(tokens, i);
if ("SET".equals(word) || "RESET".equals(word)) {
return;
}
if ("RENAME".equals(word) && "TO".equals(word(tokens, i + 1))) {
addName(tokens, i + 2, at);
return;
}
if ("IN".equals(word) && ("ROLE".equals(word(tokens, i + 1)) || "GROUP".equals(word(tokens, i + 1)))) {
i = roleList(tokens, i + 2, false, at);
} else if ("ROLE".equals(word) || "ADMIN".equals(word) || "USER".equals(word)) {
i = roleList(tokens, i + 1, false, at);
} else {
i++;
}
}
}
/**
* {@code GRANT} or {@code REVOKE} from {@code g}: of a role, the roles granted and the grantees,
* after {@code ADMIN|INHERIT|SET OPTION FOR} in a {@code REVOKE}; of privileges {@code ON} an
* object, the grantees; and the role after {@code GRANTED BY}.
*/
private static void grantRoles(List<Token> tokens, int g, Set<Integer> at) {
boolean grant = "GRANT".equals(word(tokens, g));
if (!grant && !"REVOKE".equals(word(tokens, g))) {
return;
}
String preposition = grant ? "TO" : "FROM";
int on = -1;
for (int i = g + 1; i < tokens.size() && on < 0; i++) {
if ("ON".equals(word(tokens, i))) {
on = i;
}
}
Set<Integer> found = new TreeSet<>();
int i;
if (on < 0) {
i = g + 1;
if (!grant && ROLE_GRANT_OPTIONS.contains(word(tokens, i)) && "OPTION".equals(word(tokens, i + 1))
&& "FOR".equals(word(tokens, i + 2))) {
i += 3;
}
i = roleList(tokens, i, false, found);
} else {
i = on + 1;
while (i < tokens.size() && !preposition.equals(word(tokens, i))) {
i++;
}
}
if (!preposition.equals(word(tokens, i))) {
return;
}
i = roleList(tokens, i + 1, true, found);
for (; i + 1 < tokens.size(); i++) {
if ("GRANTED".equals(word(tokens, i)) && "BY".equals(word(tokens, i + 1))) {
addName(tokens, i + 2, found);
break;
}
}
at.addAll(found);
}
/** {@code CREATE|ALTER POLICY name ON table ... TO role, ...}, but not {@code RENAME TO}. */
private static void policyRoles(List<Token> tokens, Set<Integer> at) {
for (int i = 3; i < tokens.size(); i++) {
String word = word(tokens, i);
if ("USING".equals(word) || "WITH".equals(word) || "RENAME".equals(word) || "(".equals(tokens.get(i).text())) {
return;
}
if ("TO".equals(word)) {
roleList(tokens, i + 1, false, at);
return;
}
}
}
/**
* {@code SET [SESSION|LOCAL] ROLE name} (or {@code TO} or {@code =} name) and
* {@code SET [SESSION|LOCAL] SESSION AUTHORIZATION name}, where the name may also be a string
* constant, written back as a quoted identifier. PostgreSQL takes a role named {@code none},
* however it is written, for
* {@code SET ROLE NONE}, so that one is left as it is.
*/
private static void setRole(List<Token> tokens, Set<Integer> at) {
int i = 1;
String scope = word(tokens, i);
if (("SESSION".equals(scope) || "LOCAL".equals(scope)) && !"AUTHORIZATION".equals(word(tokens, i + 1))) {
i++;
}
if ("ROLE".equals(word(tokens, i))) {
int value = i + 1;
if ("TO".equals(word(tokens, value)) || value < tokens.size() && "=".equals(tokens.get(value).text())
&& tokens.get(value).type() == Type.SYMBOL) {
value++;
}
if (isNameOrString(tokens, value) && !"none".equals(settingValue(tokens.get(value)))) {
at.add(value);
}
} else if ("SESSION".equals(word(tokens, i)) && "AUTHORIZATION".equals(word(tokens, i + 1))
&& isNameOrString(tokens, i + 2)) {
at.add(i + 2);
}
}
/**
* The names from {@code from} on, separated by commas, each preceded by {@code GROUP} where
* {@code grantees} allows it; the index after the list.
*/
private static int roleList(List<Token> tokens, int from, boolean grantees, Set<Integer> at) {
int i = from;
while (i < tokens.size()) {
if (grantees && "GROUP".equals(word(tokens, i))) {
i++;
}
if (!isName(tokens, i)) {
return i;
}
at.add(i);
i++;
Token next = i < tokens.size() ? tokens.get(i) : null;
if (next == null || next.type() != Type.SYMBOL || !",".equals(next.text())) {
return i;
}
i++;
}
return i;
}
private static void addName(List<Token> tokens, int index, Set<Integer> at) {
if (isName(tokens, index)) {
at.add(index);
}
}
private static boolean isNameOrString(List<Token> tokens, int index) {
return isName(tokens, index) || index >= 0 && index < tokens.size() && tokens.get(index).type() == Type.STRING;
}
/** The value a {@code SET} sees in a name or string constant. */
private static String settingValue(Token token) {
return token.type() == Type.STRING ? token.value() : identifier(token);
}
private static boolean isName(List<Token> tokens, int index) {
if (index < 0 || index >= tokens.size()) {
return false;
}
Type type = tokens.get(index).type();
return type == Type.WORD || type == Type.QUOTED_IDENTIFIER;
}
/** {@code name} as an identifier: quoted when it was or when PostgreSQL would fold it otherwise. */
private static String roleIdentifier(String name, boolean quoted) {
if (!quoted && SIMPLE_IDENTIFIER.matcher(name).matches()) {
return name;
}
return "\"" + name.replace("\"", "\"\"") + "\"";
}
// ── Tokens ────────────────────────────────────────────────────────────────
enum Type { WORD, QUOTED_IDENTIFIER, STRING, NUMBER, SYMBOL }
record Token(Type type, String text, String value, int start, int end) {
/**
* One token. {@code malformed} marks a {@code U&} identifier or string PostgreSQL refuses (a bad
* escape, code point or {@code UESCAPE} character, or a missing closing quote), whose
* {@code value} is only a best-effort decoding.
*/
record Token(Type type, String text, String value, int start, int end, boolean malformed) {
Token(Type type, String text, String value, int start, int end) {
this(type, text, value, start, end, false);
}
String upper() {
return text.toUpperCase(Locale.ROOT);
}
String lower() {
return text.toLowerCase(Locale.ROOT);
/**
* The word as PostgreSQL folds an unquoted identifier in a UTF-8 database: only the ASCII
* letters {@code A}-{@code Z} are lowered, so {@code Émile} stays {@code Émile}, the same
* name as the quoted {@code "Émile"}.
*/
String folded() {
StringBuilder folded = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
folded.append(c >= 'A' && c <= 'Z' ? (char) (c + ('a' - 'A')) : c);
}
return folded.toString();
}
}
@@ -491,28 +902,14 @@ public final class DsqlStatements {
int i = 0;
int n = sql.length();
while (i < n) {
i = skipSpaceAndComments(sql, i);
if (i >= n) {
break;
}
char c = sql.charAt(i);
if (Character.isWhitespace(c)) {
i++;
} else if (c == '-' && i + 1 < n && sql.charAt(i + 1) == '-') {
// PostgreSQL ends the comment at either line break.
while (i < n && sql.charAt(i) != '\n' && sql.charAt(i) != '\r') {
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++;
}
}
if ((c == 'U' || c == 'u') && i + 2 < n && sql.charAt(i + 1) == '&'
&& (sql.charAt(i + 2) == '"' || sql.charAt(i + 2) == '\'')) {
i = unicodeEscaped(sql, i, tokens);
} else if (c == '\'' || ((c == 'E' || c == 'e') && i + 1 < n && sql.charAt(i + 1) == '\'')) {
boolean escapes = c != '\'';
int start = i;
@@ -580,6 +977,180 @@ public final class DsqlStatements {
return tokens;
}
/**
* The {@code U&"..."} identifier or {@code U&'...'} string at {@code start}, with the
* {@code UESCAPE 'c'} clause that may follow it, added to {@code tokens} as one token whose value
* has its escapes decoded, as PostgreSQL decodes them: so {@code sys.U&"run\005frole\005fddl"}
* names {@code sys.run_role_ddl}. A token PostgreSQL would refuse is marked malformed. The index
* after the token.
*/
private static int unicodeEscaped(String sql, int start, List<Token> tokens) {
char quote = sql.charAt(start + 2);
int i = start + 3;
StringBuilder raw = new StringBuilder();
boolean closed = false;
while (i < sql.length()) {
char d = sql.charAt(i);
if (d == quote && i + 1 < sql.length() && sql.charAt(i + 1) == quote) {
raw.append(quote);
i += 2;
} else if (d == quote) {
i++;
closed = true;
break;
} else {
raw.append(d);
i++;
}
}
char escape = '\\';
int clauseEnd = uescapeEnd(sql, i);
if (clauseEnd > 0) {
escape = sql.charAt(clauseEnd - 2);
i = clauseEnd;
}
Unescaped decoded = unicodeUnescaped(raw.toString(), escape);
Type type = quote == '"' ? Type.QUOTED_IDENTIFIER : Type.STRING;
tokens.add(new Token(type, sql.substring(start, i), decoded.value(), start, i,
!closed || decoded.malformed()));
return i;
}
/** The index after a {@code UESCAPE 'c'} clause starting at or after {@code from}, or -1 if none does. */
private static int uescapeEnd(String sql, int from) {
int i = skipSpaceAndComments(sql, from);
String keyword = "UESCAPE";
if (!sql.regionMatches(true, i, keyword, 0, keyword.length())) {
return -1;
}
i += keyword.length();
if (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_')) {
return -1;
}
i = skipSpaceAndComments(sql, i);
if (i + 2 < sql.length() && sql.charAt(i) == '\'' && sql.charAt(i + 1) != '\'' && sql.charAt(i + 2) == '\'') {
return i + 3;
}
return -1;
}
private static int skipSpaceAndComments(String sql, int from) {
int i = from;
while (i < sql.length()) {
if (Character.isWhitespace(sql.charAt(i))) {
i++;
} else if (sql.startsWith("--", i)) {
// PostgreSQL ends the comment at either line break.
while (i < sql.length() && sql.charAt(i) != '\n' && sql.charAt(i) != '\r') {
i++;
}
} else if (sql.startsWith("/*", i)) {
int depth = 1;
i += 2;
while (i < sql.length() && depth > 0) {
if (sql.startsWith("/*", i)) {
depth++;
i += 2;
} else if (sql.startsWith("*/", i)) {
depth--;
i += 2;
} else {
i++;
}
}
} else {
return i;
}
}
return i;
}
/** A {@code U&} body decoded, and whether PostgreSQL would refuse it. */
record Unescaped(String value, boolean malformed) {
}
/**
* {@code raw} with {@code escape} followed by four hex digits, or by {@code +} and six, read as
* that code point, and a doubled {@code escape} as itself, as PostgreSQL decodes it. What
* PostgreSQL refuses makes the result malformed: an escape character that is a hex digit,
* {@code +}, a quote or white space; an escape followed by anything else; code point 0 or one
* past U+10FFFF; and a UTF-16 surrogate not in a high-low pair. The value then keeps such an
* escape as written, a best effort that only the guard against internal routine calls reads.
*/
static Unescaped unicodeUnescaped(String raw, char escape) {
boolean malformed = (escape < 128 && Character.digit(escape, 16) >= 0) || escape == '+' || escape == '\''
|| escape == '"' || Character.isWhitespace(escape);
StringBuilder value = new StringBuilder(raw.length());
int pendingHigh = -1;
int i = 0;
while (i < raw.length()) {
char c = raw.charAt(i);
int codePoint = -1;
int length = 1;
if (c == escape && i + 1 < raw.length() && raw.charAt(i + 1) == escape) {
value.append(escape);
i += 2;
malformed |= pendingHigh >= 0;
pendingHigh = -1;
continue;
} else if (c == escape && i + 1 < raw.length() && raw.charAt(i + 1) == '+') {
codePoint = hexCodePoint(raw, i + 2, 6);
length = 8;
} else if (c == escape) {
codePoint = hexCodePoint(raw, i + 1, 4);
length = 5;
} else {
value.append(c);
i++;
malformed |= pendingHigh >= 0;
pendingHigh = -1;
continue;
}
if (codePoint <= 0) {
malformed = true;
value.append(c);
i++;
pendingHigh = -1;
continue;
}
if (codePoint <= Character.MAX_VALUE && Character.isHighSurrogate((char) codePoint)) {
malformed |= pendingHigh >= 0;
pendingHigh = codePoint;
} else if (codePoint <= Character.MAX_VALUE && Character.isLowSurrogate((char) codePoint)) {
if (pendingHigh < 0) {
malformed = true;
} else {
value.appendCodePoint(Character.toCodePoint((char) pendingHigh, (char) codePoint));
}
pendingHigh = -1;
} else {
malformed |= pendingHigh >= 0;
pendingHigh = -1;
value.appendCodePoint(codePoint);
}
i += length;
}
malformed |= pendingHigh >= 0;
return new Unescaped(value.toString(), malformed);
}
/** The code point written as {@code digits} hex digits at {@code from}, or -1 if they are not that. */
private static int hexCodePoint(String raw, int from, int digits) {
if (from + digits > raw.length()) {
return -1;
}
int codePoint = 0;
for (int i = from; i < from + digits; i++) {
char d = raw.charAt(i);
int digit = d < 128 ? Character.digit(d, 16) : -1;
if (digit < 0) {
return -1;
}
codePoint = codePoint * 16 + digit;
}
return Character.isValidCodePoint(codePoint) ? codePoint : -1;
}
private static int dollarTagEnd(String sql, int at) {
int i = at + 1;
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_')) {
@@ -640,7 +1211,7 @@ public final class DsqlStatements {
private static String identifier(Token token) {
return switch (token.type()) {
case QUOTED_IDENTIFIER -> token.value();
case WORD -> token.lower();
case WORD -> token.folded();
default -> token.text();
};
}
@@ -0,0 +1,60 @@
package io.floci.aws.services.dsql.dataplane;
import java.util.Set;
/**
* Role names of a cluster that shares its PostgreSQL server with others: each backend role
* carries the cluster's prefix, {@code d<clusterid>_}, so clusters' roles do not collide. Role
* specifiers, written as unquoted keywords, and PostgreSQL's reserved {@code pg_} roles keep their
* names; a quoted {@code "public"} names a role like any other, and is prefixed.
*/
public final class PrefixedRoleNames implements RoleNames {
/** PostgreSQL's longest identifier, in bytes (NAMEDATALEN - 1); a longer one is truncated. */
static final int MAX_IDENTIFIER_BYTES = 63;
/**
* The longest logical name, in UTF-8 bytes, whose prefixed form fits in PostgreSQL's 63-byte
* identifier, with the 28-byte prefix of a 26-character cluster id ({@code d} + id + {@code _}).
*/
static final int MAX_LOGICAL = 35;
/**
* The role specifiers PostgreSQL reads as keywords where a role name goes, folded to lower
* case; {@link DsqlStatements} reads the same set.
*/
static final Set<String> SPECIFIERS = Set.of(
"public", "current_user", "current_role", "session_user", "none", "default");
private final String prefix;
public PrefixedRoleNames(String clusterId) {
this.prefix = "d" + clusterId + "_";
}
@Override
public String toBackend(String logical) {
if (logical.startsWith("pg_")) {
return logical;
}
return prefix + logical;
}
@Override
public String toBackend(String logical, boolean quoted) {
if (!quoted && SPECIFIERS.contains(logical)) {
return logical;
}
return toBackend(logical);
}
@Override
public String toLogical(String backend) {
return backend.startsWith(prefix) ? backend.substring(prefix.length()) : backend;
}
@Override
public boolean isIdentity() {
return false;
}
}
@@ -24,6 +24,15 @@ public interface RoleNames {
/** The backend name of the role called {@code logical}: a role's exact name, never a specifier. */
String toBackend(String logical);
/**
* The backend name of a role named in SQL. Only an unquoted keyword is a role specifier
* ({@code PUBLIC}, {@code CURRENT_USER} and the like); a {@code quoted} identifier always names
* a role, as PostgreSQL reads it.
*/
default String toBackend(String logical, boolean quoted) {
return toBackend(logical);
}
String toLogical(String backend);
boolean isIdentity();