mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(dsql): translate role names and record each cluster's roles (#8631)
This commit is contained in:
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();
|
||||
|
||||
@@ -18,6 +18,24 @@ ALTER DATABASE {{database}} SET default_transaction_isolation TO 'repeatable rea
|
||||
CREATE SCHEMA IF NOT EXISTS sys AUTHORIZATION {{owner}};
|
||||
GRANT USAGE ON SCHEMA sys TO PUBLIC;
|
||||
|
||||
-- On a server Floci shares between clusters ({{external}} is true), PUBLIC may not connect to the
|
||||
-- cluster's database, which PostgreSQL lets every role do by default. The NOLOGIN role
|
||||
-- {{connect_role_literal}} holds CONNECT on it instead, and each role recorded as the cluster's
|
||||
-- is a member of it (see sys._record_backend_roles), with no ADMIN option: no client can take a
|
||||
-- recorded role's CONNECT away, and a membership does not keep DROP ROLE from dropping a role. Its
|
||||
-- name is outside the cluster's prefix, so no name a client gives maps onto it.
|
||||
DO $$
|
||||
BEGIN
|
||||
IF {{external}} THEN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = {{connect_role_literal}}) THEN
|
||||
EXECUTE format('CREATE ROLE %I NOLOGIN', {{connect_role_literal}});
|
||||
END IF;
|
||||
EXECUTE format('REVOKE CONNECT ON DATABASE %I FROM PUBLIC', current_database());
|
||||
EXECUTE format('GRANT CONNECT ON DATABASE %I TO %I', current_database(), {{connect_role_literal}});
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
|
||||
-- ── Identifiers: a UUID as 26 characters of lowercase base32 ──────────────────
|
||||
|
||||
CREATE OR REPLACE FUNCTION sys.uuid_to_base32_str(u uuid) RETURNS text
|
||||
@@ -104,13 +122,122 @@ LANGUAGE sql IMMUTABLE AS $$ SELECT 10995116277760::bigint $$;
|
||||
CREATE OR REPLACE FUNCTION sys.cluster_size() RETURNS bigint
|
||||
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ SELECT pg_database_size(current_database()) $$;
|
||||
|
||||
-- ── The cluster's roles, and the names a client knows them by ─────────────────
|
||||
|
||||
-- The backend roles this cluster owns: its admin, its owner unless that is a superuser, and every role
|
||||
-- a recorded role holds the ADMIN option on, which PostgreSQL gives a role's creator. On a server
|
||||
-- Floci shares between clusters ({{external}} is true) each backend name is the client's name after
|
||||
-- the prefix {{role_prefix}}, and only a role with that prefix is recorded through the ADMIN option;
|
||||
-- in a cluster's own container the prefix is empty. On a shared server the role holding the cluster's
|
||||
-- CONNECT, {{connect_role_literal}}, is recorded too, like the owner, and like it is no client's role.
|
||||
-- Deleting the cluster drops what is recorded here.
|
||||
CREATE TABLE IF NOT EXISTS sys.backend_roles (
|
||||
role_oid oid PRIMARY KEY,
|
||||
backend_name name NOT NULL,
|
||||
logical_name text NOT NULL
|
||||
);
|
||||
REVOKE ALL ON sys.backend_roles FROM PUBLIC;
|
||||
|
||||
-- A backend role's name without the cluster's prefix; any other name itself.
|
||||
CREATE OR REPLACE FUNCTION sys._strip_role_prefix(role_name text) RETURNS text
|
||||
LANGUAGE plpgsql IMMUTABLE STRICT AS $$
|
||||
DECLARE
|
||||
prefix constant text := {{role_prefix}};
|
||||
BEGIN
|
||||
IF starts_with(role_name, prefix) THEN
|
||||
RETURN substr(role_name, length(prefix) + 1);
|
||||
END IF;
|
||||
RETURN role_name;
|
||||
END
|
||||
$$;
|
||||
|
||||
-- The name a client knows a backend role by: the recorded one, else the name without the prefix.
|
||||
-- With no prefix it is the name itself.
|
||||
CREATE OR REPLACE FUNCTION sys._logical_role(role_name name) RETURNS text
|
||||
LANGUAGE sql STABLE STRICT SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||
SELECT coalesce((SELECT b.logical_name FROM sys.backend_roles b WHERE b.backend_name = role_name LIMIT 1),
|
||||
sys._strip_role_prefix(role_name))
|
||||
$$;
|
||||
|
||||
-- Brings sys.backend_roles up to date. The cluster's roles are its admin, its owner unless that is a
|
||||
-- superuser, and every role reached from the admin or a role already recorded through the ADMIN option
|
||||
-- that, on a shared server, also carries the cluster's prefix: a role another cluster's admin was
|
||||
-- granted WITH ADMIN OPTION stays that cluster's. On a shared server the ADMIN option counts only when
|
||||
-- it is the one PostgreSQL 16 gives a role's creator, which the bootstrap superuser (oid 10) grants,
|
||||
-- or one this cluster's admin or recorded roles granted: a role another cluster's admin creates under
|
||||
-- this cluster's prefix and grants to this cluster's roles is not taken for this cluster's. A recorded
|
||||
-- role that is no longer one of them, or no longer exists, is forgotten; a renamed one is followed. On a
|
||||
-- shared server each role recorded, but the owner and {{connect_role_literal}} itself, is made a member of
|
||||
-- {{connect_role_literal}}, so it may connect to the cluster's database, and a role forgotten is no longer
|
||||
-- one. The memberships are granted by this procedure's owner, so the cluster's roles hold no ADMIN
|
||||
-- option on {{connect_role_literal}} and cannot revoke them.
|
||||
CREATE OR REPLACE PROCEDURE sys._record_backend_roles()
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||
DECLARE
|
||||
cluster_roles oid[];
|
||||
entry record;
|
||||
BEGIN
|
||||
WITH RECURSIVE owned (oid) AS (
|
||||
SELECT a.oid FROM pg_authid a WHERE a.rolname = {{admin_literal}}
|
||||
UNION
|
||||
SELECT a.oid FROM sys.backend_roles b JOIN pg_authid a ON a.oid = b.role_oid
|
||||
WHERE a.rolname <> {{owner_literal}} AND (NOT {{external}} OR starts_with(a.rolname, {{role_prefix}}))
|
||||
UNION
|
||||
SELECT m.roleid FROM pg_auth_members m JOIN owned o ON m.member = o.oid JOIN pg_authid r ON r.oid = m.roleid
|
||||
WHERE m.admin_option
|
||||
AND (NOT {{external}}
|
||||
OR (starts_with(r.rolname, {{role_prefix}})
|
||||
AND (m.grantor = 10::oid
|
||||
OR m.grantor IN (SELECT a.oid FROM pg_authid a WHERE a.rolname = {{admin_literal}})
|
||||
OR m.grantor IN (SELECT b.role_oid FROM sys.backend_roles b))))
|
||||
)
|
||||
SELECT coalesce(array_agg(a.oid), '{}') INTO cluster_roles FROM pg_authid a
|
||||
WHERE (a.oid IN (SELECT oid FROM owned) OR a.rolname = {{owner_literal}}
|
||||
OR ({{external}} AND a.rolname = {{connect_role_literal}}))
|
||||
AND NOT a.rolsuper;
|
||||
|
||||
FOR entry IN SELECT b.role_oid, a.rolname FROM sys.backend_roles b LEFT JOIN pg_authid a ON a.oid = b.role_oid
|
||||
WHERE NOT (b.role_oid = ANY (cluster_roles)) LOOP
|
||||
DELETE FROM sys.backend_roles WHERE role_oid = entry.role_oid;
|
||||
IF {{external}} AND entry.rolname IS NOT NULL
|
||||
AND EXISTS (SELECT 1 FROM pg_auth_members m JOIN pg_authid g ON g.oid = m.roleid
|
||||
WHERE g.rolname = {{connect_role_literal}} AND m.member = entry.role_oid) THEN
|
||||
EXECUTE format('REVOKE %I FROM %I', {{connect_role_literal}}, entry.rolname);
|
||||
END IF;
|
||||
END LOOP;
|
||||
UPDATE sys.backend_roles b SET backend_name = a.rolname, logical_name = sys._strip_role_prefix(a.rolname)
|
||||
FROM pg_authid a WHERE a.oid = b.role_oid AND a.rolname <> b.backend_name;
|
||||
FOR entry IN SELECT a.oid, a.rolname FROM pg_authid a
|
||||
WHERE a.oid = ANY (cluster_roles)
|
||||
AND NOT EXISTS (SELECT 1 FROM sys.backend_roles b WHERE b.role_oid = a.oid)
|
||||
ORDER BY a.oid LOOP
|
||||
INSERT INTO sys.backend_roles VALUES (entry.oid, entry.rolname, sys._strip_role_prefix(entry.rolname));
|
||||
END LOOP;
|
||||
IF {{external}} THEN
|
||||
-- WITH INHERIT TRUE, so a role created NOINHERIT holds the CONNECT all the same.
|
||||
FOR entry IN SELECT a.rolname FROM sys.backend_roles b JOIN pg_authid a ON a.oid = b.role_oid
|
||||
WHERE a.rolname NOT IN ({{owner_literal}}, {{connect_role_literal}})
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_auth_members m JOIN pg_authid g ON g.oid = m.roleid
|
||||
WHERE g.rolname = {{connect_role_literal}} AND m.member = a.oid
|
||||
AND m.inherit_option)
|
||||
ORDER BY a.oid LOOP
|
||||
EXECUTE format('GRANT %I TO %I WITH INHERIT TRUE, SET FALSE', {{connect_role_literal}}, entry.rolname);
|
||||
END LOOP;
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
|
||||
-- On a shared server, only the cluster's roles, by the names its clients know, and not its owner or
|
||||
-- the role holding its CONNECT, which are Floci's own.
|
||||
CREATE OR REPLACE VIEW sys.roles AS
|
||||
SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication,
|
||||
rolconnlimit, '********'::text AS rolpassword, rolvaliduntil, rolbypassrls,
|
||||
SELECT sys._logical_role(rolname)::name AS rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb,
|
||||
rolcanlogin, rolreplication, rolconnlimit, '********'::text AS rolpassword, rolvaliduntil, rolbypassrls,
|
||||
s.setconfig AS rolconfig, pg_authid.oid
|
||||
FROM pg_authid
|
||||
LEFT JOIN pg_db_role_setting s ON pg_authid.oid = s.setrole AND s.setdatabase = 0::oid
|
||||
WHERE pg_authid.rolname !~~ 'pg_%';
|
||||
WHERE pg_authid.rolname !~~ 'pg_%'
|
||||
AND (NOT {{external}} OR (pg_authid.oid IN (SELECT role_oid FROM sys.backend_roles)
|
||||
AND pg_authid.rolname NOT IN ({{owner_literal}}, {{connect_role_literal}})));
|
||||
GRANT SELECT ON sys.roles TO PUBLIC;
|
||||
|
||||
-- ── A transaction's limits: one DDL statement, no DDL with DML, 3,000 rows ────
|
||||
@@ -479,8 +606,8 @@ CREATE TABLE IF NOT EXISTS sys.iam_auth_member (
|
||||
);
|
||||
|
||||
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
|
||||
SELECT i.oid::oid AS iam_oid, i.arn, m.roleid AS pg_role_oid, sys._logical_role(a.rolname)::name AS pg_role_name,
|
||||
m.grantor AS grantor_pg_role_oid, sys._logical_role(b.rolname)::name 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
|
||||
@@ -489,7 +616,7 @@ 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.
|
||||
-- included. Its messages name the role as the client knows it.
|
||||
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
|
||||
@@ -498,17 +625,18 @@ DECLARE
|
||||
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);
|
||||
RAISE EXCEPTION USING ERRCODE = '42704', MESSAGE = format('role "%s" does not exist', sys._logical_role(role_name));
|
||||
END IF;
|
||||
IF superuser THEN
|
||||
RAISE EXCEPTION USING ERRCODE = '0LP01', MESSAGE = format('cannot establish trust with role "%s"', role_name),
|
||||
RAISE EXCEPTION USING ERRCODE = '0LP01',
|
||||
MESSAGE = format('cannot establish trust with role "%s"', sys._logical_role(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),
|
||||
MESSAGE = format('permission denied to %s IAM trust with role "%s"', verb, sys._logical_role(role_name)),
|
||||
DETAIL = format('Only roles with the ADMIN option on role "%s" may %s IAM trust %s this role.',
|
||||
role_name, verb, preposition);
|
||||
sys._logical_role(role_name), verb, preposition);
|
||||
END IF;
|
||||
RETURN role_oid;
|
||||
END
|
||||
@@ -538,11 +666,11 @@ BEGIN
|
||||
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
|
||||
SELECT coalesce(sys._logical_role(b.rolname), 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;
|
||||
iam_arn, sys._logical_role(role_name), granted_by;
|
||||
RETURN;
|
||||
END IF;
|
||||
INSERT INTO sys.iam_auth_member (member, roleid, grantor)
|
||||
@@ -574,7 +702,8 @@ $$;
|
||||
-- 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),
|
||||
SELECT string_agg(format('privileges for trust relationship of role %s with arn %s', sys._logical_role(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
|
||||
@@ -584,7 +713,8 @@ $$;
|
||||
|
||||
-- A statement on roles, which DSQL counts as DDL (measured) though PostgreSQL fires no event trigger
|
||||
-- for one: CREATE or ALTER ROLE, USER or GROUP, and GRANT or REVOKE of a role, which Floci's
|
||||
-- endpoint hands here, counted, then run as the caller. Anything else is not one of them.
|
||||
-- endpoint hands here, counted, then run as the caller. Anything else is not one of them. A role it
|
||||
-- creates is then recorded as the cluster's.
|
||||
CREATE OR REPLACE PROCEDURE sys.run_role_ddl(statement text)
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
@@ -593,11 +723,12 @@ BEGIN
|
||||
END IF;
|
||||
PERFORM sys._count_ddl();
|
||||
EXECUTE statement;
|
||||
CALL sys._record_backend_roles();
|
||||
END
|
||||
$$;
|
||||
|
||||
-- DROP ROLE, USER or GROUP, which Floci's endpoint hands here: refused for a mapped role, otherwise
|
||||
-- counted as DDL and run as the caller.
|
||||
-- counted as DDL and run as the caller, and the roles dropped are no longer recorded as the cluster's.
|
||||
CREATE OR REPLACE PROCEDURE sys.drop_roles(role_names text[], missing_ok boolean)
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
@@ -609,12 +740,14 @@ BEGIN
|
||||
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),
|
||||
MESSAGE = format('role "%s" cannot be dropped because some objects depend on it',
|
||||
sys._logical_role(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));
|
||||
CALL sys._record_backend_roles();
|
||||
END
|
||||
$$;
|
||||
|
||||
@@ -634,4 +767,8 @@ BEGIN
|
||||
END LOOP;
|
||||
END
|
||||
$$;
|
||||
|
||||
-- The admin, the owner, the role holding the cluster's CONNECT and the roles the admin made, recorded
|
||||
-- as the cluster's.
|
||||
CALL sys._record_backend_roles();
|
||||
RESET session_replication_role;
|
||||
@@ -0,0 +1,134 @@
|
||||
package io.floci.aws.services.dsql;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.exception.DockerException;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
import com.github.dockerjava.api.model.PortBinding;
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import io.floci.aws.services.dsql.dataplane.DockerDsqlBackend;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.TestDockerClients;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* A throwaway PostgreSQL 16 in Docker for the external DSQL backend's tests, bound to a free port
|
||||
* on 127.0.0.1, whose superuser is {@code postgres}. {@link #close()} removes the container and
|
||||
* always closes the Docker client.
|
||||
*/
|
||||
public final class ExternalPostgresServer implements AutoCloseable {
|
||||
|
||||
public static final String IMAGE = "postgres:16-alpine";
|
||||
private static final Duration READY_TIMEOUT = Duration.ofSeconds(60);
|
||||
|
||||
private final DockerClient dockerClient;
|
||||
private final String containerId;
|
||||
private final int port;
|
||||
|
||||
private ExternalPostgresServer(DockerClient dockerClient, String containerId, int port) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.containerId = containerId;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
/** Docker, or the image, is not there; a test skips rather than fails. Its cause says why. */
|
||||
public static final class DockerUnavailableException extends Exception {
|
||||
DockerUnavailableException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a container named {@code name} plus a random suffix, with {@code env} besides
|
||||
* {@code POSTGRES_USER=postgres}, and waits until {@code postgres} logs in with
|
||||
* {@code password} (empty where the server trusts its connections), through the readiness loop
|
||||
* the Docker backend waits for a cluster's database with.
|
||||
*/
|
||||
public static ExternalPostgresServer start(String name, String password, String... env)
|
||||
throws DockerUnavailableException, SQLException, InterruptedException {
|
||||
DockerClient dockerClient = TestDockerClients.local();
|
||||
String containerId = null;
|
||||
try {
|
||||
if (!DockerAvailability.answers(dockerClient)) {
|
||||
throw new DockerUnavailableException("Docker does not answer", null);
|
||||
}
|
||||
try {
|
||||
dockerClient.pullImageCmd(IMAGE).start().awaitCompletion(120, TimeUnit.SECONDS);
|
||||
} catch (RuntimeException e) {
|
||||
throw new DockerUnavailableException("Docker or " + IMAGE + " is not available: " + e.getMessage(), e);
|
||||
}
|
||||
List<String> environment = new ArrayList<>(List.of("POSTGRES_USER=postgres"));
|
||||
environment.addAll(List.of(env));
|
||||
ExposedPort exposed = ExposedPort.tcp(5432);
|
||||
containerId = dockerClient.createContainerCmd(IMAGE)
|
||||
.withName(name + "-" + UUID.randomUUID())
|
||||
.withEnv(environment)
|
||||
.withExposedPorts(exposed)
|
||||
.withHostConfig(HostConfig.newHostConfig()
|
||||
.withPortBindings(new PortBinding(Ports.Binding.bindIp("127.0.0.1"), exposed)))
|
||||
.exec().getId();
|
||||
dockerClient.startContainerCmd(containerId).exec();
|
||||
InspectContainerResponse inspected = dockerClient.inspectContainerCmd(containerId).exec();
|
||||
int port = Integer.parseInt(
|
||||
inspected.getNetworkSettings().getPorts().getBindings().get(exposed)[0].getHostPortSpec());
|
||||
DockerDsqlBackend.awaitReady(() -> DriverManager.getConnection(jdbcUrl(port, "postgres"), "postgres",
|
||||
password), READY_TIMEOUT);
|
||||
return new ExternalPostgresServer(dockerClient, containerId, port);
|
||||
} catch (DockerUnavailableException | SQLException | InterruptedException | RuntimeException e) {
|
||||
close(dockerClient, containerId, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public int port() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public String jdbcUrl(String database) {
|
||||
return jdbcUrl(port, database);
|
||||
}
|
||||
|
||||
private static String jdbcUrl(int port, String database) {
|
||||
return "jdbc:postgresql://127.0.0.1:" + port + "/" + database;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
close(dockerClient, containerId, null);
|
||||
}
|
||||
|
||||
/** Removes the container, if any, then closes the client whatever the removal did. */
|
||||
private static void close(DockerClient dockerClient, String containerId, Exception failure) {
|
||||
try {
|
||||
if (containerId != null) {
|
||||
dockerClient.removeContainerCmd(containerId).withForce(true).withRemoveVolumes(true).exec();
|
||||
}
|
||||
} catch (DockerException e) {
|
||||
// The container is a throwaway; Docker reaps what it could not remove here.
|
||||
report(failure, "Could not remove " + containerId, e);
|
||||
} finally {
|
||||
try {
|
||||
dockerClient.close();
|
||||
} catch (IOException e) {
|
||||
report(failure, "Could not close the Docker client", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void report(Exception failure, String what, Exception e) {
|
||||
if (failure != null) {
|
||||
failure.addSuppressed(e);
|
||||
} else {
|
||||
System.err.println(what + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
package io.floci.aws.services.dsql.dataplane;
|
||||
|
||||
import io.floci.aws.services.dsql.ExternalPostgresServer;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.opentest4j.TestAbortedException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Runs the bootstrap script rendered for the external backend against a throwaway PostgreSQL 16,
|
||||
* set up as a shared server holds one cluster: its own database, owner role and prefixed roles.
|
||||
*/
|
||||
@Tag("docker")
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class DsqlBootstrapExternalIntegrationTest {
|
||||
|
||||
private static final String DATABASE = "dsql_abc";
|
||||
private static final String OWNER = "dsqlowner_abc";
|
||||
private static final String ADMIN = "dabc_admin";
|
||||
private static final String PREFIX = "dabc_";
|
||||
private static final String CONNECT = "dsqlconnect_abc";
|
||||
private static final String OTHER_DATABASE = "dsql_xyz";
|
||||
private static final String OTHER_OWNER = "dsqlowner_xyz";
|
||||
private static final String OTHER_ADMIN = "dxyz_admin";
|
||||
private static final String OTHER_PREFIX = "dxyz_";
|
||||
private static final String OTHER_CONNECT = "dsqlconnect_xyz";
|
||||
private static final String ARN = "arn:aws:iam::123456789012:role/app";
|
||||
|
||||
private ExternalPostgresServer server;
|
||||
|
||||
@BeforeAll
|
||||
void startServerAndBootstrapTwice() throws Exception {
|
||||
try {
|
||||
server = ExternalPostgresServer.start("floci-dsql-bootstrap", "", "POSTGRES_HOST_AUTH_METHOD=trust");
|
||||
} catch (ExternalPostgresServer.DockerUnavailableException e) {
|
||||
throw new TestAbortedException(e.getMessage(), e);
|
||||
}
|
||||
|
||||
createClusterDatabase(DATABASE, OWNER);
|
||||
createClusterDatabase(OTHER_DATABASE, OTHER_OWNER);
|
||||
String script = DsqlBootstrap.render(DATABASE, OWNER, ADMIN, CONNECT, PREFIX, true);
|
||||
for (int run = 0; run < 2; run++) {
|
||||
try (Connection connection = connect(DATABASE, "postgres"); Statement statement = connection.createStatement()) {
|
||||
statement.execute(script);
|
||||
}
|
||||
}
|
||||
try (Connection connection = connect(OTHER_DATABASE, "postgres"); Statement statement = connection.createStatement()) {
|
||||
statement.execute(DsqlBootstrap.render(OTHER_DATABASE, OTHER_OWNER, OTHER_ADMIN, OTHER_CONNECT,
|
||||
OTHER_PREFIX, true));
|
||||
}
|
||||
}
|
||||
|
||||
private void createClusterDatabase(String database, String owner) throws SQLException {
|
||||
try (Connection connection = connect("postgres", "postgres"); Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE ROLE " + owner + " NOLOGIN");
|
||||
statement.execute("CREATE DATABASE " + database + " OWNER " + owner);
|
||||
}
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
void removeServer() {
|
||||
if (server != null) {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void bootstrapRecordsTheAdminAndOwnerAndRolesTheirChildrenCreate() throws SQLException {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.run_role_ddl($$CREATE ROLE " + PREFIX + "b WITH LOGIN CREATEROLE$$)");
|
||||
}
|
||||
try (Connection b = connect(DATABASE, PREFIX + "b"); Statement statement = b.createStatement()) {
|
||||
statement.execute("CALL sys.run_role_ddl($$CREATE ROLE " + PREFIX + "c$$)");
|
||||
}
|
||||
|
||||
Map<String, String> recorded = backendRoles();
|
||||
assertEquals(PREFIX + "b", recorded.get("b"));
|
||||
assertEquals(PREFIX + "c", recorded.get("c"));
|
||||
assertEquals(ADMIN, recorded.get("admin"));
|
||||
assertEquals(OWNER, recorded.get(OWNER));
|
||||
assertEquals(CONNECT, recorded.get(CONNECT), "the role holding the cluster's CONNECT is recorded");
|
||||
assertTrue(hasConnect(PREFIX + "c"), "a recorded role may connect to its cluster's database");
|
||||
|
||||
List<String> visible = query(ADMIN, "SELECT rolname FROM sys.roles ORDER BY rolname");
|
||||
assertEquals(List.of("admin", "b", "c"), visible, "sys.roles lists the cluster's roles, not its owner");
|
||||
|
||||
try (Connection b = connect(DATABASE, PREFIX + "b"); Statement statement = b.createStatement()) {
|
||||
statement.execute("CALL sys.drop_roles(ARRAY['" + PREFIX + "c']::text[], false)");
|
||||
}
|
||||
assertFalse(backendRoles().containsKey("c"));
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.drop_roles(ARRAY['" + PREFIX + "b']::text[], false)");
|
||||
}
|
||||
assertFalse(backendRoles().containsKey("b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamMessagesAndMappingsNameRolesLogically() throws SQLException {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
SQLException missing = assertThrows(SQLException.class, () ->
|
||||
statement.execute("CALL sys.aws_iam_grant('" + PREFIX + "nope', '" + ARN + "')"));
|
||||
assertTrue(missing.getMessage().contains("role \"nope\" does not exist"), missing.getMessage());
|
||||
|
||||
statement.execute("CALL sys.run_role_ddl($$CREATE ROLE " + PREFIX + "app$$)");
|
||||
statement.execute("CALL sys.aws_iam_grant('" + PREFIX + "app', '" + ARN + "')");
|
||||
SQLException mapped = assertThrows(SQLException.class, () ->
|
||||
statement.execute("CALL sys.drop_roles(ARRAY['" + PREFIX + "app']::text[], false)"));
|
||||
assertTrue(mapped.getMessage().contains("role \"app\" cannot be dropped because some objects depend on it"),
|
||||
mapped.getMessage());
|
||||
assertTrue(mapped.getMessage().contains("privileges for trust relationship of role app with arn " + ARN),
|
||||
mapped.getMessage());
|
||||
}
|
||||
assertEquals(List.of("app|admin"),
|
||||
query(ADMIN, "SELECT pg_role_name || '|' || grantor_pg_role_name FROM sys.iam_pg_role_mappings"));
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.aws_iam_revoke('" + PREFIX + "app', '" + ARN + "')");
|
||||
statement.execute("CALL sys.drop_roles(ARRAY['" + PREFIX + "app']::text[], false)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoleGrantedToAnotherClustersAdminStaysItsOwnClusters() throws SQLException {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.run_role_ddl($$CREATE ROLE " + PREFIX + "x$$)");
|
||||
statement.execute("CALL sys.run_role_ddl($$GRANT " + PREFIX + "x TO " + OTHER_ADMIN + " WITH ADMIN OPTION$$)");
|
||||
}
|
||||
try (Connection superuser = connect(OTHER_DATABASE, "postgres"); Statement statement = superuser.createStatement()) {
|
||||
statement.execute("CALL sys._record_backend_roles()");
|
||||
assertFalse(backendRoles(OTHER_DATABASE).containsValue(PREFIX + "x"),
|
||||
"another cluster's role is not recorded through its admin's ADMIN option");
|
||||
assertEquals(List.of("admin"), query(OTHER_DATABASE, OTHER_ADMIN, "SELECT rolname FROM sys.roles"));
|
||||
|
||||
// A role recorded before the prefix was required is forgotten, and loses its CONNECT.
|
||||
statement.execute("INSERT INTO sys.backend_roles SELECT oid, rolname, rolname FROM pg_roles WHERE rolname = '"
|
||||
+ PREFIX + "x'");
|
||||
statement.execute("GRANT " + OTHER_CONNECT + " TO " + PREFIX + "x");
|
||||
statement.execute("CALL sys._record_backend_roles()");
|
||||
assertFalse(backendRoles(OTHER_DATABASE).containsValue(PREFIX + "x"));
|
||||
assertEquals(List.of("false"), query(OTHER_DATABASE, "postgres",
|
||||
"SELECT has_database_privilege('" + PREFIX + "x', '" + OTHER_DATABASE + "', 'CONNECT')::text"));
|
||||
}
|
||||
assertEquals(PREFIX + "x", backendRoles().get("x"), "the role stays recorded by its own cluster");
|
||||
assertEquals(OTHER_OWNER, backendRoles(OTHER_DATABASE).get(OTHER_OWNER), "the owner stays recorded");
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.drop_roles(ARRAY['" + PREFIX + "x']::text[], false)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRolePlantedUnderThisClustersPrefixByAnotherClusterIsNotRecorded() throws SQLException {
|
||||
String planted = PREFIX + "planted";
|
||||
// Another cluster's admin, on the server itself, where Floci translates no name.
|
||||
try (Connection other = connect(OTHER_DATABASE, OTHER_ADMIN); Statement statement = other.createStatement()) {
|
||||
statement.execute("CREATE ROLE " + planted);
|
||||
statement.execute("GRANT " + planted + " TO " + ADMIN + " WITH ADMIN OPTION");
|
||||
statement.execute("CREATE TABLE planted_in_other(x int)");
|
||||
statement.execute("GRANT SELECT ON planted_in_other TO " + planted);
|
||||
}
|
||||
try {
|
||||
assertEquals(List.of("true"), query("postgres", "SELECT pg_has_role('" + ADMIN + "', '" + planted
|
||||
+ "', 'MEMBER WITH ADMIN OPTION')::text"), "this cluster's admin holds the ADMIN option on it");
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.run_role_ddl($$CREATE ROLE " + PREFIX + "own$$)");
|
||||
}
|
||||
|
||||
Map<String, String> recorded = backendRoles();
|
||||
assertFalse(recorded.containsValue(planted), "a role the other cluster's admin granted in is not recorded");
|
||||
assertEquals(PREFIX + "own", recorded.get("own"), "a role this cluster's admin created is");
|
||||
assertFalse(hasConnect(planted));
|
||||
} finally {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.drop_roles(ARRAY['" + PREFIX + "own']::text[], false)");
|
||||
}
|
||||
try (Connection superuser = connect(DATABASE, "postgres"); Statement statement = superuser.createStatement()) {
|
||||
// Undoes what a recording of the planted role would have done.
|
||||
statement.execute("DELETE FROM sys.backend_roles WHERE backend_name = '" + planted + "'");
|
||||
}
|
||||
try (Connection other = connect(OTHER_DATABASE, OTHER_ADMIN); Statement statement = other.createStatement()) {
|
||||
statement.execute("DROP TABLE planted_in_other");
|
||||
statement.execute("DROP ROLE " + planted);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBootstrapTakesConnectFromPublic() throws SQLException {
|
||||
String database = "dsql_fresh";
|
||||
String owner = "dsqlowner_fresh";
|
||||
createClusterDatabase(database, owner);
|
||||
try (Connection connection = connect("postgres", "postgres"); Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE ROLE stranger LOGIN");
|
||||
}
|
||||
assertEquals(List.of("true"), query(database, "postgres",
|
||||
"SELECT has_database_privilege('public', current_database(), 'CONNECT')::text"),
|
||||
"a database PostgreSQL creates lets PUBLIC connect");
|
||||
try (Connection stranger = connect(database, "stranger")) {
|
||||
assertTrue(stranger.isValid(1));
|
||||
}
|
||||
|
||||
try (Connection connection = connect(database, "postgres"); Statement statement = connection.createStatement()) {
|
||||
statement.execute(DsqlBootstrap.render(database, owner, "dfresh_admin", "dsqlconnect_fresh", "dfresh_", true));
|
||||
}
|
||||
|
||||
assertEquals(List.of("false"), query(database, "postgres",
|
||||
"SELECT has_database_privilege('public', current_database(), 'CONNECT')::text"));
|
||||
SQLException refused = assertThrows(SQLException.class, () -> connect(database, "stranger").close());
|
||||
assertEquals("42501", refused.getSQLState(), refused.getMessage());
|
||||
try (Connection admin = connect(database, "dfresh_admin")) {
|
||||
assertTrue(admin.isValid(1), "the cluster's admin, a recorded role, still connects");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void noRoleOfTheClusterCanTakeAwayARecordedRolesConnect() throws SQLException {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.run_role_ddl($$CREATE ROLE " + PREFIX + "held WITH LOGIN NOINHERIT$$)");
|
||||
}
|
||||
try {
|
||||
assertTrue(hasConnect(PREFIX + "held"), "a NOINHERIT role connects through its membership all the same");
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
// The admin holds the ADMIN option on the role it created, and none on the connect role.
|
||||
SQLException revoke = assertThrows(SQLException.class,
|
||||
() -> statement.execute("REVOKE " + CONNECT + " FROM " + PREFIX + "held"));
|
||||
assertEquals("42501", revoke.getSQLState(), revoke.getMessage());
|
||||
statement.execute("REVOKE CONNECT ON DATABASE " + DATABASE + " FROM " + PREFIX + "held");
|
||||
SQLException release = assertThrows(SQLException.class,
|
||||
() -> statement.execute("CALL sys._release_backend_roles(ARRAY['" + PREFIX + "held'])"));
|
||||
assertEquals("42883", release.getSQLState(), release.getMessage());
|
||||
}
|
||||
assertTrue(hasConnect(PREFIX + "held"));
|
||||
try (Connection held = connect(DATABASE, PREFIX + "held"); Statement statement = held.createStatement()) {
|
||||
statement.execute("SELECT 1");
|
||||
}
|
||||
assertEquals(List.of("false"), query("postgres", "SELECT pg_has_role('" + ADMIN + "', '" + CONNECT
|
||||
+ "', 'MEMBER WITH ADMIN OPTION')::text"), "the cluster's admin cannot grant the connect role");
|
||||
} finally {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.drop_roles(ARRAY['" + PREFIX + "held']::text[], false)");
|
||||
}
|
||||
}
|
||||
assertFalse(backendRoles().containsKey("held"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void translatedRevocationsOfAGrantsOptionsReachTheClustersRoles() throws SQLException {
|
||||
RoleNames names = new PrefixedRoleNames("abc");
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute(DsqlStatements.rewriteQuery("CREATE ROLE granted", names).sql());
|
||||
statement.execute(DsqlStatements.rewriteQuery("CREATE ROLE holder", names).sql());
|
||||
statement.execute(DsqlStatements.rewriteQuery(
|
||||
"GRANT granted TO holder WITH ADMIN TRUE, INHERIT TRUE, SET TRUE", names).sql());
|
||||
for (String option : List.of("ADMIN", "INHERIT", "SET")) {
|
||||
statement.execute(DsqlStatements.rewriteQuery(
|
||||
"REVOKE " + option + " OPTION FOR granted FROM holder", names).sql());
|
||||
}
|
||||
}
|
||||
try {
|
||||
assertEquals(List.of("false|false|false"), query("postgres", "SELECT m.admin_option || '|' || m.inherit_option"
|
||||
+ " || '|' || m.set_option FROM pg_auth_members m WHERE m.roleid = '" + PREFIX + "granted'::regrole"
|
||||
+ " AND m.member = '" + PREFIX + "holder'::regrole"));
|
||||
} finally {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute(DsqlStatements.rewriteQuery("DROP ROLE holder, granted", names).sql());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnquotedNonAsciiNameAndItsQuotedSpellingNameOneRole() throws SQLException {
|
||||
RoleNames names = new PrefixedRoleNames("abc");
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute(DsqlStatements.rewriteQuery("CREATE ROLE \u00c9MILE", names).sql());
|
||||
assertEquals(List.of(PREFIX + "\u00c9mile"), query("postgres", "SELECT rolname FROM pg_roles WHERE rolname LIKE '"
|
||||
+ PREFIX + "%mile'"));
|
||||
statement.execute(DsqlStatements.rewriteQuery("DROP ROLE \"\u00c9mile\"", names).sql());
|
||||
}
|
||||
assertFalse(backendRoles().containsValue(PREFIX + "\u00c9mile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theImplicitGrantOfARoleToItsCreatorIsMadeByTheBootstrapSuperuser() throws SQLException {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.run_role_ddl($$CREATE ROLE " + PREFIX + "made$$)");
|
||||
}
|
||||
try {
|
||||
// What sys._record_backend_roles matches: PostgreSQL 16 records BOOTSTRAP_SUPERUSERID (10).
|
||||
assertEquals(List.of("10"), query("postgres", "SELECT m.grantor::text FROM pg_auth_members m"
|
||||
+ " WHERE m.roleid = '" + PREFIX + "made'::regrole AND m.member = '" + ADMIN + "'::regrole"
|
||||
+ " AND m.admin_option"));
|
||||
} finally {
|
||||
try (Connection admin = connect(DATABASE, ADMIN); Statement statement = admin.createStatement()) {
|
||||
statement.execute("CALL sys.drop_roles(ARRAY['" + PREFIX + "made']::text[], false)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> backendRoles() throws SQLException {
|
||||
return backendRoles(DATABASE);
|
||||
}
|
||||
|
||||
private Map<String, String> backendRoles(String database) throws SQLException {
|
||||
Map<String, String> roles = new TreeMap<>();
|
||||
try (Connection connection = connect(database, "postgres"); Statement statement = connection.createStatement();
|
||||
ResultSet rows = statement.executeQuery("SELECT logical_name, backend_name FROM sys.backend_roles")) {
|
||||
while (rows.next()) {
|
||||
roles.put(rows.getString(1), rows.getString(2));
|
||||
}
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
private boolean hasConnect(String role) throws SQLException {
|
||||
return query("postgres", "SELECT has_database_privilege('" + role + "', '" + DATABASE + "', 'CONNECT')::text")
|
||||
.equals(List.of("true"));
|
||||
}
|
||||
|
||||
private List<String> query(String user, String sql) throws SQLException {
|
||||
return query(DATABASE, user, sql);
|
||||
}
|
||||
|
||||
private List<String> query(String database, String user, String sql) throws SQLException {
|
||||
List<String> values = new ArrayList<>();
|
||||
try (Connection connection = connect(database, user); Statement statement = connection.createStatement();
|
||||
ResultSet rows = statement.executeQuery(sql)) {
|
||||
while (rows.next()) {
|
||||
values.add(rows.getString(1));
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private Connection connect(String database, String user) throws SQLException {
|
||||
return DriverManager.getConnection(server.jdbcUrl(database), user, "");
|
||||
}
|
||||
}
|
||||
@@ -3,19 +3,24 @@ package io.floci.aws.services.dsql.dataplane;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class DsqlBootstrapTest {
|
||||
|
||||
private static String docker() {
|
||||
return DsqlBootstrap.render("postgres", "dbowner", "admin");
|
||||
return DsqlBootstrap.render("postgres", "dbowner", "admin", "", "", false);
|
||||
}
|
||||
|
||||
private static String external() {
|
||||
return DsqlBootstrap.render("dsql_abc", "dsqlowner_abc", "dabc_admin", "dsqlconnect_abc", "dabc_", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noRenderingLeavesAPlaceholderBehind() {
|
||||
assertFalse(docker().contains("{{"));
|
||||
assertFalse(DsqlBootstrap.render("dsql_abc", "dsqlowner_abc", "dabc_admin").contains("{{"));
|
||||
assertFalse(DsqlBootstrap.render("My-Db", "o\"w", "it's").contains("{{"));
|
||||
assertFalse(external().contains("{{"));
|
||||
assertFalse(DsqlBootstrap.render("My-Db", "o\"w", "it's", "c'n", "p'x_", true).contains("{{"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -30,8 +35,50 @@ class DsqlBootstrapTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherRenderingNamesItsOwnDatabaseAndRoles() {
|
||||
String script = DsqlBootstrap.render("dsql_abc", "dsqlowner_abc", "dabc_admin");
|
||||
void dockerRenderingUsesNoPrefixAndStaysInDockerMode() {
|
||||
String script = docker();
|
||||
assertTrue(script.contains("sys.backend_roles"));
|
||||
assertTrue(script.contains("prefix constant text := '';"));
|
||||
assertTrue(script.contains("IF false THEN"));
|
||||
assertTrue(script.contains("NOT false OR"));
|
||||
assertFalse(script.contains("'dabc_'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void externalRenderingRecordsTheClustersRolesUnderItsPrefix() {
|
||||
String script = external();
|
||||
assertTrue(script.contains("CREATE TABLE IF NOT EXISTS sys.backend_roles"));
|
||||
assertTrue(script.contains("prefix constant text := 'dabc_';"));
|
||||
assertTrue(script.contains("IF true THEN"));
|
||||
assertTrue(script.contains("NOT true OR"));
|
||||
assertTrue(script.contains("rolname = 'dsqlowner_abc'"));
|
||||
assertTrue(script.contains("rolname = 'dsqlconnect_abc'"));
|
||||
assertTrue(script.contains("GRANT %I TO %I WITH INHERIT TRUE, SET FALSE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void externalRenderingNeedsAConnectRoleOutsideThePrefix() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> DsqlBootstrap.render("dsql_abc", "dsqlowner_abc", "dabc_admin", "", "dabc_", true));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> DsqlBootstrap.render("dsql_abc", "dsqlowner_abc", "dabc_admin", "dabc_connect", "dabc_", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noClientCallableProcedureRevokesARolesConnect() {
|
||||
assertFalse(external().contains("_release_backend_roles"));
|
||||
assertFalse(external().contains("REVOKE CONNECT ON DATABASE %I FROM %I"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void externalRenderingTakesConnectFromPublic() {
|
||||
assertTrue(external().contains("REVOKE CONNECT ON DATABASE %I FROM PUBLIC"));
|
||||
assertTrue(docker().contains("IF false THEN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '')"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void externalRenderingNamesTheClustersObjects() {
|
||||
String script = external();
|
||||
assertTrue(script.contains("GRANT CREATE ON DATABASE \"dsql_abc\" TO \"dabc_admin\""));
|
||||
assertTrue(script.contains("AUTHORIZATION \"dsqlowner_abc\""));
|
||||
assertFalse(script.contains("'admin'"));
|
||||
@@ -40,11 +87,14 @@ class DsqlBootstrapTest {
|
||||
|
||||
@Test
|
||||
void everyIdentifierIsQuotedAndLiteralsEscaped() {
|
||||
String script = DsqlBootstrap.render("My-Db", "o\"w", "it's");
|
||||
String script = DsqlBootstrap.render("My-Db", "o\"w", "it's", "c'n", "p'x_", true);
|
||||
assertTrue(script.contains("GRANT CREATE ON DATABASE \"My-Db\" TO \"it's\""));
|
||||
assertTrue(script.contains("AUTHORIZATION \"o\"\"w\""));
|
||||
assertTrue(script.contains("rolname = 'it''s'"));
|
||||
assertTrue(DsqlBootstrap.render("user", "table", "select")
|
||||
assertTrue(script.contains("rolname = 'o\"w'"));
|
||||
assertTrue(script.contains("prefix constant text := 'p''x_';"));
|
||||
assertTrue(script.contains("rolname = 'c''n'"));
|
||||
assertTrue(DsqlBootstrap.render("user", "table", "select", "", "", false)
|
||||
.contains("GRANT CREATE ON DATABASE \"user\" TO \"select\""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package io.floci.aws.services.dsql.dataplane;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class DsqlRoleNamesTest {
|
||||
|
||||
private static final RoleNames NAMES = new PrefixedRoleNames("x");
|
||||
private static final String ARN = "'arn:aws:iam::123456789012:role/r'";
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', quoteCharacter = '`', value = {
|
||||
"CREATE ROLE app WITH LOGIN|CALL sys.run_role_ddl($dsql$CREATE ROLE dx_app WITH LOGIN$dsql$)",
|
||||
"GRANT app TO reader|CALL sys.run_role_ddl($dsql$GRANT dx_app TO dx_reader$dsql$)",
|
||||
"GRANT SELECT ON t TO app, PUBLIC|GRANT SELECT ON t TO dx_app, PUBLIC",
|
||||
"REVOKE ALL ON t FROM app|REVOKE ALL ON t FROM dx_app",
|
||||
"ALTER TABLE t OWNER TO app|ALTER TABLE t OWNER TO dx_app",
|
||||
"SET ROLE app|SET ROLE dx_app",
|
||||
"CREATE SCHEMA s AUTHORIZATION app|CREATE SCHEMA s AUTHORIZATION dx_app",
|
||||
"CREATE POLICY p ON t TO app|CREATE POLICY p ON t TO dx_app",
|
||||
"ALTER DEFAULT PRIVILEGES FOR ROLE app GRANT SELECT ON TABLES TO reader"
|
||||
+ "|ALTER DEFAULT PRIVILEGES FOR ROLE dx_app GRANT SELECT ON TABLES TO dx_reader",
|
||||
"REASSIGN OWNED BY app TO reader|REASSIGN OWNED BY dx_app TO dx_reader",
|
||||
"DROP OWNED BY app|DROP OWNED BY dx_app",
|
||||
"DROP ROLE app, reader|CALL sys.drop_roles(ARRAY['dx_app', 'dx_reader']::text[], false)",
|
||||
"AWS IAM GRANT app TO " + ARN + "|CALL sys.aws_iam_grant('dx_app', " + ARN + ")",
|
||||
"CREATE ROLE \"App\"|CALL sys.run_role_ddl($dsql$CREATE ROLE \"dx_App\"$dsql$)",
|
||||
"SELECT 'app'|SELECT 'app'",
|
||||
"GRANT pg_read_all_data TO app|CALL sys.run_role_ddl($dsql$GRANT pg_read_all_data TO dx_app$dsql$)",
|
||||
"SET ROLE NONE|SET ROLE NONE",
|
||||
// Beyond the brief's rows: the other positions the grammar names a role in.
|
||||
"GRANT \"app\" TO r|CALL sys.run_role_ddl($dsql$GRANT \"dx_app\" TO dx_r$dsql$)",
|
||||
"CREATE ROLE App|CALL sys.run_role_ddl($dsql$CREATE ROLE dx_app$dsql$)",
|
||||
"CREATE ROLE a IN ROLE b, c ROLE d ADMIN e USER f"
|
||||
+ "|CALL sys.run_role_ddl($dsql$CREATE ROLE dx_a IN ROLE dx_b, dx_c ROLE dx_d ADMIN dx_e USER dx_f$dsql$)",
|
||||
"CREATE USER u IN GROUP g PASSWORD 'p'|CALL sys.run_role_ddl($dsql$CREATE USER dx_u IN GROUP dx_g PASSWORD 'p'$dsql$)",
|
||||
"ALTER ROLE app RENAME TO other|CALL sys.run_role_ddl($dsql$ALTER ROLE dx_app RENAME TO dx_other$dsql$)",
|
||||
"ALTER ROLE app SET role TO 'x'|CALL sys.run_role_ddl($dsql$ALTER ROLE dx_app SET role TO 'x'$dsql$)",
|
||||
"ALTER ROLE ALL SET work_mem = '1MB'|CALL sys.run_role_ddl($dsql$ALTER ROLE ALL SET work_mem = '1MB'$dsql$)",
|
||||
"ALTER GROUP g ADD USER a, b|CALL sys.run_role_ddl($dsql$ALTER GROUP dx_g ADD USER dx_a, dx_b$dsql$)",
|
||||
"ALTER ROLE CURRENT_USER WITH NOLOGIN|CALL sys.run_role_ddl($dsql$ALTER ROLE CURRENT_USER WITH NOLOGIN$dsql$)",
|
||||
"GRANT a, b TO c WITH ADMIN OPTION GRANTED BY d"
|
||||
+ "|CALL sys.run_role_ddl($dsql$GRANT dx_a, dx_b TO dx_c WITH ADMIN OPTION GRANTED BY dx_d$dsql$)",
|
||||
"REVOKE ADMIN OPTION FOR app FROM reader CASCADE"
|
||||
+ "|CALL sys.run_role_ddl($dsql$REVOKE ADMIN OPTION FOR dx_app FROM dx_reader CASCADE$dsql$)",
|
||||
"REVOKE INHERIT OPTION FOR app FROM reader"
|
||||
+ "|CALL sys.run_role_ddl($dsql$REVOKE INHERIT OPTION FOR dx_app FROM dx_reader$dsql$)",
|
||||
"REVOKE SET OPTION FOR app, other FROM reader GRANTED BY admin RESTRICT"
|
||||
+ "|CALL sys.run_role_ddl($dsql$REVOKE SET OPTION FOR dx_app, dx_other FROM dx_reader GRANTED BY dx_admin"
|
||||
+ " RESTRICT$dsql$)",
|
||||
"revoke inherit option for app from GROUP reader"
|
||||
+ "|CALL sys.run_role_ddl($dsql$revoke inherit option for dx_app from GROUP dx_reader$dsql$)",
|
||||
"REVOKE app FROM reader|CALL sys.run_role_ddl($dsql$REVOKE dx_app FROM dx_reader$dsql$)",
|
||||
"GRANT SELECT ON t TO GROUP g, CURRENT_USER WITH GRANT OPTION"
|
||||
+ "|GRANT SELECT ON t TO GROUP dx_g, CURRENT_USER WITH GRANT OPTION",
|
||||
"SET SESSION ROLE app|SET SESSION ROLE dx_app",
|
||||
"SET SESSION AUTHORIZATION app|SET SESSION AUTHORIZATION dx_app",
|
||||
"SET SESSION AUTHORIZATION DEFAULT|SET SESSION AUTHORIZATION DEFAULT",
|
||||
"SET ROLE 'app'|SET ROLE \"dx_app\"",
|
||||
"SET role = 'app'|SET role = \"dx_app\"",
|
||||
"SET role TO 'App'|SET role TO \"dx_App\"",
|
||||
"SET LOCAL ROLE 'app'|SET LOCAL ROLE \"dx_app\"",
|
||||
"SET SESSION AUTHORIZATION 'app'|SET SESSION AUTHORIZATION \"dx_app\"",
|
||||
"SET LOCAL SESSION AUTHORIZATION 'app'|SET LOCAL SESSION AUTHORIZATION \"dx_app\"",
|
||||
"SET ROLE E'it\\'s'|SET ROLE \"dx_it's\"",
|
||||
"SET ROLE 'it''s'|SET ROLE \"dx_it's\"",
|
||||
"SET ROLE $$app$$|SET ROLE \"dx_app\"",
|
||||
// A backslash in the name cannot break a literal while standard_conforming_strings is off.
|
||||
"SET ROLE 'a\\b'|SET ROLE \"dx_a\\b\"",
|
||||
"SET SESSION AUTHORIZATION 'q\"t'|SET SESSION AUTHORIZATION \"dx_q\"\"t\"",
|
||||
"SET ROLE 'none'|SET ROLE 'none'",
|
||||
// PostgreSQL 16 takes a role named none, however written, for NONE (checked), and reserves the name.
|
||||
"SET ROLE \"none\"|SET ROLE \"none\"",
|
||||
"SET ROLE 'NONE'|SET ROLE \"dx_NONE\"",
|
||||
"SET ROLE 'public'|SET ROLE \"dx_public\"",
|
||||
"SET ROLE 'default'|SET ROLE \"dx_default\"",
|
||||
"SET role TO DEFAULT|SET role TO DEFAULT",
|
||||
"CREATE SCHEMA IF NOT EXISTS AUTHORIZATION app|CREATE SCHEMA IF NOT EXISTS AUTHORIZATION dx_app",
|
||||
"ALTER POLICY p ON t TO a, PUBLIC USING (n > 0)|ALTER POLICY p ON t TO dx_a, PUBLIC USING (n > 0)",
|
||||
"ALTER POLICY p ON t RENAME TO q|ALTER POLICY p ON t RENAME TO q",
|
||||
"ALTER DEFAULT PRIVILEGES FOR USER a, b IN SCHEMA s REVOKE ALL ON TABLES FROM c"
|
||||
+ "|ALTER DEFAULT PRIVILEGES FOR USER dx_a, dx_b IN SCHEMA s REVOKE ALL ON TABLES FROM dx_c",
|
||||
"DROP OWNED BY a, b CASCADE|DROP OWNED BY dx_a, dx_b CASCADE",
|
||||
"ALTER SCHEMA s OWNER TO CURRENT_USER|ALTER SCHEMA s OWNER TO CURRENT_USER",
|
||||
// Not role positions: a column, constraint or attribute called owner, renamed.
|
||||
"ALTER TABLE t RENAME COLUMN owner TO x|ALTER TABLE t RENAME COLUMN owner TO x",
|
||||
"ALTER TABLE t RENAME owner TO x|ALTER TABLE t RENAME owner TO x",
|
||||
"ALTER TABLE t RENAME CONSTRAINT owner TO c|ALTER TABLE t RENAME CONSTRAINT owner TO c",
|
||||
"ALTER TYPE ty RENAME ATTRIBUTE owner TO y|ALTER TYPE ty RENAME ATTRIBUTE owner TO y",
|
||||
"ALTER TABLE owner OWNER TO app|ALTER TABLE owner OWNER TO dx_app",
|
||||
})
|
||||
void roleNamesAreTranslatedWhereSqlNamesARole(String sql, String expected) {
|
||||
assertEquals(expected, DsqlStatements.rewriteQuery(sql, NAMES).sql());
|
||||
assertEquals(DsqlStatements.rewriteQuery(sql).sql(), DsqlStatements.rewriteQuery(sql, RoleNames.IDENTITY).sql());
|
||||
assertEquals(DsqlStatements.rewriteQuery(sql).commandTags(),
|
||||
DsqlStatements.rewriteQuery(sql, NAMES).commandTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachStatementOfAQueryIsTranslated() {
|
||||
DsqlStatements.Query query = DsqlStatements.rewriteQuery("SELECT 'app'; SET ROLE app; DROP ROLE reader", NAMES);
|
||||
|
||||
assertEquals("SELECT 'app';\nSET ROLE dx_app;\nCALL sys.drop_roles(ARRAY['dx_reader']::text[], false)",
|
||||
query.sql());
|
||||
assertEquals(Arrays.asList(null, null, "DROP ROLE"), query.commandTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOneArgumentRewriteStillAnswersWhatItDid() {
|
||||
List<DsqlStatements.Statement> statements = DsqlStatements.rewrite("DROP ROLE app", NAMES);
|
||||
|
||||
assertEquals("CALL sys.drop_roles(ARRAY['dx_app']::text[], false)", statements.get(0).sql());
|
||||
assertEquals(DsqlStatements.rewrite("DROP ROLE app"), DsqlStatements.rewrite("DROP ROLE app", RoleNames.IDENTITY));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"CREATE ROLE abcdefghijabcdefghijabcdefghijabcdef",
|
||||
"GRANT SELECT ON t TO ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEF",
|
||||
})
|
||||
void overlongRoleNameIsRefused(String sql) {
|
||||
DsqlStatements.Statement statement = DsqlStatements.rewrite(sql, NAMES).get(0);
|
||||
|
||||
assertEquals(DsqlStatements.reject("42602", "role name \"abcdefghijabcdefghijabcdefghijabcdef\" is too long"
|
||||
+ " for Floci's external backend (max 35 bytes)", null), statement.sql());
|
||||
assertNull(statement.commandTag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMultibyteNameOfFewerCharactersThanTheLimitButMoreBytesIsRefused() {
|
||||
String name = "\u00e9".repeat(18);
|
||||
assertEquals(18, name.length());
|
||||
|
||||
DsqlStatements.Statement statement = DsqlStatements.rewrite("CREATE ROLE \"" + name + "\"", NAMES).get(0);
|
||||
|
||||
assertEquals(DsqlStatements.reject("42602", "role name \"" + name + "\" is too long for Floci's external"
|
||||
+ " backend (max 35 bytes)", null), statement.sql());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMultibyteNameOfExactlyThirtyFiveBytesIsAccepted() {
|
||||
String name = "\u00e9".repeat(17) + "a";
|
||||
assertEquals(35, name.getBytes(StandardCharsets.UTF_8).length);
|
||||
|
||||
assertEquals("CALL sys.run_role_ddl($dsql$CREATE ROLE \"dx_" + name + "\"$dsql$)",
|
||||
DsqlStatements.rewriteQuery("CREATE ROLE \"" + name + "\"", NAMES).sql());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aThirtyFiveByteNameFillsTheIdentifierOfARealClusterId() {
|
||||
RoleNames longPrefix = new PrefixedRoleNames("abcdefghijklmnopqrstuvwxyz");
|
||||
String name = "r".repeat(35);
|
||||
assertEquals("CALL sys.run_role_ddl($dsql$CREATE ROLE dabcdefghijklmnopqrstuvwxyz_" + name + "$dsql$)",
|
||||
DsqlStatements.rewriteQuery("CREATE ROLE " + name, longPrefix).sql());
|
||||
assertEquals(63, longPrefix.toBackend(name).getBytes(StandardCharsets.UTF_8).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void thirtyFiveCharactersAreAccepted() {
|
||||
String sql = DsqlStatements.rewriteQuery("SET ROLE abcdefghijabcdefghijabcdefghijabcde", NAMES).sql();
|
||||
|
||||
assertEquals("SET ROLE dx_abcdefghijabcdefghijabcdefghijabcde", sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void longNamesAreOnlyCheckedWhenNamesAreTranslated() {
|
||||
String sql = "CREATE ROLE abcdefghijabcdefghijabcdefghijabcdef";
|
||||
|
||||
assertEquals(DsqlStatements.rewriteQuery(sql).sql(), DsqlStatements.rewriteQuery(sql, RoleNames.IDENTITY).sql());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', quoteCharacter = '`', value = {
|
||||
"CALL sys.run_role_ddl('CREATE ROLE \"dother_x\"')|procedure sys.run_role_ddl(text) does not exist",
|
||||
"call SYS.Run_Role_Ddl($$GRANT a TO b$$)|procedure sys.run_role_ddl(text) does not exist",
|
||||
"CALL \"sys\".\"drop_roles\"(ARRAY['x'], true)|procedure sys.drop_roles(text[], boolean) does not exist",
|
||||
"CALL sys.aws_iam_grant('x', 'arn')|procedure sys.aws_iam_grant(text, text) does not exist",
|
||||
"CALL sys.aws_iam_revoke ( 'x', 'arn' )|procedure sys.aws_iam_revoke(text, text) does not exist",
|
||||
"SELECT sys._reject('42000', 'm')|function sys._reject(unknown, unknown) does not exist",
|
||||
"SELECT 1; CALL sys._record_backend_roles()|procedure sys._record_backend_roles() does not exist",
|
||||
"SELECT sys._strip_role_prefix(f(1, 2))|function sys._strip_role_prefix(unknown) does not exist",
|
||||
"CREATE PROCEDURE p() LANGUAGE sql BEGIN ATOMIC CALL sys.run_role_ddl('x')"
|
||||
+ "|procedure sys.run_role_ddl(text) does not exist",
|
||||
"CALL sys.U&\"run\\005frole\\005fddl\"('x')|procedure sys.run_role_ddl(text) does not exist",
|
||||
"CALL u&\"\\0073ys\".drop_roles(ARRAY['x'], true)|procedure sys.drop_roles(text[], boolean) does not exist",
|
||||
"CALL sys.U&\"run!005frole!+00005fddl\" UESCAPE '!'('x')|procedure sys.run_role_ddl(text) does not exist",
|
||||
"CALL sys.U&\"aws_iam_grant\" /* c */ UESCAPE '%' ('x', 'a')"
|
||||
+ "|procedure sys.aws_iam_grant(text, text) does not exist",
|
||||
"SELECT sys.U&\"\\005freject\"('1', 'm')|function sys._reject(unknown, unknown) does not exist",
|
||||
})
|
||||
void clientCallsOfFlocisInternalRoutinesAreRefusedOnASharedServer(String sql, String message) {
|
||||
List<DsqlStatements.Statement> statements = DsqlStatements.rewrite(sql, NAMES);
|
||||
DsqlStatements.Statement statement = statements.get(statements.size() - 1);
|
||||
|
||||
assertEquals(DsqlStatements.reject("42883", message, null), statement.sql());
|
||||
assertNull(statement.commandTag());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"CALL sys.run_role_ddl('CREATE ROLE x')",
|
||||
"SELECT sys._reject('42000', 'm')",
|
||||
})
|
||||
void internalRoutinesAreLeftAsTheyAreWithTheClustersOwnDatabase(String sql) {
|
||||
assertEquals(sql, DsqlStatements.rewriteQuery(sql, RoleNames.IDENTITY).sql());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"SELECT sys.iam_session_user()",
|
||||
"CALL sys.wait_for_job('abc')",
|
||||
"SELECT public.run_role_ddl('x')",
|
||||
"SELECT run_role_ddl FROM t",
|
||||
"SELECT 'sys.run_role_ddl(''x'')'",
|
||||
"SELECT sys.current_session_id(), my._helper()",
|
||||
"CREATE TABLE run_role_ddl (id int)",
|
||||
"INSERT INTO drop_roles (a) VALUES (1)",
|
||||
"CALL run_role_ddl('a client procedure of that name')",
|
||||
"SELECT aws_iam_grant(1, 2), _private(3)",
|
||||
})
|
||||
void otherRoutinesAndMentionsAreNotRefused(String sql) {
|
||||
assertEquals(sql, DsqlStatements.rewriteQuery(sql, NAMES).sql());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnquotedNameFoldsOnlyItsAsciiLettersAsPostgresqlDoes() {
|
||||
String created = DsqlStatements.rewriteQuery("CREATE ROLE \u00c9MILE", NAMES).sql();
|
||||
String quoted = DsqlStatements.rewriteQuery("DROP ROLE \"\u00c9mile\"", NAMES).sql();
|
||||
String unquoted = DsqlStatements.rewriteQuery("SET ROLE \u00c9mile", NAMES).sql();
|
||||
|
||||
assertEquals("CALL sys.run_role_ddl($dsql$CREATE ROLE \"dx_\u00c9mile\"$dsql$)", created);
|
||||
assertEquals("CALL sys.drop_roles(ARRAY['dx_\u00c9mile']::text[], false)", quoted);
|
||||
assertEquals("SET ROLE \"dx_\u00c9mile\"", unquoted);
|
||||
assertEquals("SET ROLE \"dx_\u00e9mile\"", DsqlStatements.rewriteQuery("SET ROLE \u00e9MILE", NAMES).sql());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', quoteCharacter = '`', value = {
|
||||
"SET ROLE U&\"\\0061pp\"|SET ROLE \"dx_app\"",
|
||||
"CREATE ROLE U&\"d!0061t\" UESCAPE '!'|CALL sys.run_role_ddl($dsql$CREATE ROLE \"dx_dat\"$dsql$)",
|
||||
"SET ROLE U&'\\0061pp'|SET ROLE \"dx_app\"",
|
||||
"GRANT SELECT ON t TO U&\"a\\\\b\"|GRANT SELECT ON t TO \"dx_a\\b\"",
|
||||
})
|
||||
void unicodeEscapedNamesAreTranslatedByWhatTheyDecodeTo(String sql, String expected) {
|
||||
assertEquals(expected, DsqlStatements.rewriteQuery(sql, NAMES).sql());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', quoteCharacter = '`', value = {
|
||||
"\\zz|\\",
|
||||
"x\\|\\",
|
||||
"a\\0000|\\",
|
||||
"a\\+110000|\\",
|
||||
"\\D83D|\\",
|
||||
"\\D83Dx|\\",
|
||||
"\\DE00\\D83D|\\",
|
||||
"\\D83D\\D83D\\DE00|\\",
|
||||
"a|a",
|
||||
"a|+",
|
||||
"a|'",
|
||||
"a|\"",
|
||||
"a|` `",
|
||||
})
|
||||
void whatPostgresqlRefusesIsFlaggedMalformed(String raw, String escape) {
|
||||
assertTrue(DsqlStatements.unicodeUnescaped(raw, escape.charAt(0)).malformed(), raw + " UESCAPE " + escape);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', quoteCharacter = '`', value = {
|
||||
"SET ROLE U&\"\\zz\"",
|
||||
"SET ROLE U&\"a\\0000\"",
|
||||
"SET ROLE U&\"\\D83D\"",
|
||||
"SET ROLE U&\"a\" UESCAPE 'a'",
|
||||
"SET ROLE U&\"a\" UESCAPE '+'",
|
||||
"SET ROLE U&'\\zz'",
|
||||
"CREATE ROLE U&\"x\\",
|
||||
"GRANT SELECT ON t TO U&\"\\+110000\"",
|
||||
})
|
||||
void aMalformedUnicodeEscapedNameIsLeftForPostgresqlToRefuse(String sql) {
|
||||
String rewritten = DsqlStatements.rewriteQuery(sql, NAMES).sql();
|
||||
|
||||
assertFalse(rewritten.contains("dx_"), rewritten);
|
||||
assertTrue(rewritten.contains(sql.substring(sql.indexOf("U&"))), rewritten);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unicodeEscapesDecodeAsPostgresqlDecodesThem() {
|
||||
assertEquals(new DsqlStatements.Unescaped("d\u00e4t", false), DsqlStatements.unicodeUnescaped("d\\00e4t", '\\'));
|
||||
assertEquals(new DsqlStatements.Unescaped("\ud83d\ude00", false),
|
||||
DsqlStatements.unicodeUnescaped("\\+01F600", '\\'));
|
||||
assertEquals(new DsqlStatements.Unescaped("\ud83d\ude00", false),
|
||||
DsqlStatements.unicodeUnescaped("\\D83D\\DE00", '\\'));
|
||||
assertEquals(new DsqlStatements.Unescaped("a!b", false), DsqlStatements.unicodeUnescaped("a!!b", '!'));
|
||||
assertEquals(new DsqlStatements.Unescaped("x\\0061", false), DsqlStatements.unicodeUnescaped("x\\0061", '!'));
|
||||
assertEquals(new DsqlStatements.Unescaped("\\zz", true), DsqlStatements.unicodeUnescaped("\\zz", '\\'),
|
||||
"a malformed escape is kept, and flagged");
|
||||
List<DsqlStatements.Token> tokens = DsqlStatements.tokenize("SELECT U&\"a\"\"b\" UESCAPE '!', 1");
|
||||
assertEquals("a\"b", tokens.get(1).value());
|
||||
assertEquals("U&\"a\"\"b\" UESCAPE '!'", tokens.get(1).text());
|
||||
assertEquals(",", tokens.get(2).text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void prefixedNamesRoundTrip() {
|
||||
assertEquals("App", NAMES.toLogical(NAMES.toBackend("App")));
|
||||
assertEquals("dx_app", NAMES.toBackend("app"));
|
||||
assertEquals("admin", NAMES.toLogical("admin"));
|
||||
assertFalse(NAMES.isIdentity());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"public", "current_user", "current_role", "session_user", "none", "default",
|
||||
"pg_read_all_data"})
|
||||
void specifiersAndReservedNamesAreNotPrefixed(String name) {
|
||||
assertEquals(name, NAMES.toBackend(name, false));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"public", "current_user", "current_role", "session_user", "none", "default"})
|
||||
void aQuotedOrExactSpecifierNameIsARoleAndIsPrefixed(String name) {
|
||||
assertEquals("dx_" + name, NAMES.toBackend(name, true));
|
||||
assertEquals("dx_" + name, NAMES.toBackend(name), "a login's user name is a role's exact name");
|
||||
assertEquals("CALL sys.run_role_ddl($dsql$CREATE ROLE \"dx_" + name + "\"$dsql$)",
|
||||
DsqlStatements.rewriteQuery("CREATE ROLE \"" + name + "\"", NAMES).sql());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', quoteCharacter = '`', value = {
|
||||
"GRANT SELECT ON t TO \"public\", PUBLIC|GRANT SELECT ON t TO \"dx_public\", PUBLIC",
|
||||
"SET SESSION AUTHORIZATION \"none\"|SET SESSION AUTHORIZATION \"dx_none\"",
|
||||
"ALTER TABLE t OWNER TO \"current_user\"|ALTER TABLE t OWNER TO \"dx_current_user\"",
|
||||
"DROP ROLE \"default\"|CALL sys.drop_roles(ARRAY['dx_default']::text[], false)",
|
||||
"CREATE ROLE \"pg_x\"|CALL sys.run_role_ddl($dsql$CREATE ROLE \"pg_x\"$dsql$)",
|
||||
"GRANT pg_read_all_data TO \"public\"|CALL sys.run_role_ddl($dsql$GRANT pg_read_all_data TO \"dx_public\"$dsql$)",
|
||||
})
|
||||
void onlyUnquotedSpecifiersKeepTheirNames(String sql, String expected) {
|
||||
assertEquals(expected, DsqlStatements.rewriteQuery(sql, NAMES).sql());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLongestLogicalNameFitsInPostgresqlsLimit() {
|
||||
assertEquals(35, PrefixedRoleNames.MAX_LOGICAL);
|
||||
}
|
||||
}
|
||||
@@ -143,6 +143,8 @@ class DsqlStatementsTest {
|
||||
"SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",
|
||||
"SET search_path TO probe",
|
||||
"DROP ROLE CURRENT_USER",
|
||||
"DROP ROLE session_user",
|
||||
"DROP ROLE DEFAULT",
|
||||
"DROP ROLE IF EXISTS",
|
||||
"DROP ROLE a b",
|
||||
"DROP ROLE a,",
|
||||
@@ -219,4 +221,40 @@ class DsqlStatementsTest {
|
||||
assertEquals("SELECT $f$ ; $f$", statements.get(1).sql());
|
||||
assertEquals("SELECT \"x;y\"", statements.get(2).sql());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"a /* x /* y */ z */ b|a@0-1,b@20-21",
|
||||
"a /* x /* y */ b|a@0-1",
|
||||
"a /* never closed|a@0-1",
|
||||
"a /*|a@0-1",
|
||||
"a -- to the end|a@0-1",
|
||||
"a --|a@0-1",
|
||||
"a - b|a@0-1,-@2-3,b@4-5",
|
||||
"a / b|a@0-1,/@2-3,b@4-5",
|
||||
"a/**/b|a@0-1,b@5-6",
|
||||
"a/*/ b*/c|a@0-1,c@8-9",
|
||||
})
|
||||
void tokenizeSkipsWhitespaceAndCommentsAndKeepsTheTokenPositions(String sql, String expected) {
|
||||
StringBuilder actual = new StringBuilder();
|
||||
for (DsqlStatements.Token token : DsqlStatements.tokenize(sql)) {
|
||||
if (actual.length() > 0) {
|
||||
actual.append(',');
|
||||
}
|
||||
actual.append(token.text()).append('@').append(token.start()).append('-').append(token.end());
|
||||
}
|
||||
|
||||
assertEquals(expected, actual.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenizeEndsALineCommentAtEitherLineBreak() {
|
||||
List<DsqlStatements.Token> lineFeed = DsqlStatements.tokenize("a --\nb");
|
||||
List<DsqlStatements.Token> carriageReturn = DsqlStatements.tokenize("a --\rb");
|
||||
|
||||
assertEquals(2, lineFeed.size());
|
||||
assertEquals(5, lineFeed.get(1).start());
|
||||
assertEquals(2, carriageReturn.size());
|
||||
assertEquals(5, carriageReturn.get(1).start());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user