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
@@ -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