From b08f1aebe2790643f1256a95eb7b8ffe5ef01f8a Mon Sep 17 00:00:00 2001 From: Stefan Bischof Date: Wed, 2 Dec 2026 20:36:18 +0100 Subject: [PATCH] metadata: SQL Server, MySQL and MariaDB read in either scope SQL Server shows a user only the metadata of what it owns or holds a right on; a connection reads in DATABASE where it holds VIEW DEFINITION on the database. In USER the schemas are those that hold an object the user sees. Grants on routines and sequences are read as object privileges, no longer as grants on tables. MySQL and MariaDB read in DATABASE where the session holds, on every object, the rights with which information_schema shows the whole structure: SELECT, SHOW VIEW and TRIGGER, on MariaDB EXECUTE besides, as it opens a view to find its columns. SHOW GRANTS of the session decides, granted to the account or to an active role; the grant tables of the schema mysql must be readable too. DATABASE reads every grant on a table, a column and a routine from those grant tables. USER reads the user and its roles from APPLICABLE_ROLES, its grants from information_schema and SHOW GRANTS of its own account, and the grants of its active roles as each database shows them. Grantees and grantors are named without their host. MariaDB reads the keys of a table from KEY_COLUMN_USAGE, which shows them to a reader that may only select. H2 and DuckDB read their catalog one way only, the same in both scopes, and every connection may read in the scope it asks for. They keep the scope they are made for, so a snapshot names the scope asked for. The contract runs on SQL Server, MySQL and MariaDB in a container too, and the tests of each database add what it shows differently; on MySQL and MariaDB a reader holding exactly the requirement, directly or through an active role, reads what the administrator reads, and a reader of the grant tables alone falls back. Unit tests cover the lines of SHOW GRANTS and the scope of the provider of each product, and a snapshot read with the provider of H2 names the scope asked for. The README of the metadata providers says which provider serves which product, how a scope is asked for, and for each database what each scope reads, the right DATABASE needs, and where a database shows a user less or more than one might expect. Signed-off-by: Stefan Bischof --- jdbc/impl/pom.xml | 24 + .../DatabaseServiceReadsInOneScopeH2Test.java | 11 + .../impl/scope/MariaDbMetadataScopeTest.java | 289 ++++++++++++ .../impl/scope/MetadataScopeContract.java | 127 ++++++ .../impl/scope/MsSqlMetadataScopeTest.java | 133 ++++++ .../impl/scope/MySqlMetadataScopeTest.java | 251 ++++++++++ jdbc/metadata/README.md | 199 ++++++++ .../jdbc/metadata/DuckDbMetadataProvider.java | 25 + .../daanse/sql/jdbc/metadata/GrantLine.java | 177 ++++++++ .../sql/jdbc/metadata/H2MetadataProvider.java | 25 + .../metadata/MariaDbMetadataProvider.java | 193 +++++++- .../MicrosoftSqlServerMetadataProvider.java | 107 ++++- .../daanse/sql/jdbc/metadata/MySqlGrants.java | 427 ++++++++++++++++++ .../jdbc/metadata/MySqlMetadataProvider.java | 208 +++++++++ .../sql/jdbc/metadata/GrantLineTest.java | 112 +++++ .../metadata/MetadataScopeDefaultsTest.java | 4 +- .../sql/jdbc/metadata/MySqlGrantsTest.java | 127 ++++++ 17 files changed, 2418 insertions(+), 21 deletions(-) create mode 100644 jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MariaDbMetadataScopeTest.java create mode 100644 jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MsSqlMetadataScopeTest.java create mode 100644 jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MySqlMetadataScopeTest.java create mode 100644 jdbc/metadata/README.md create mode 100644 jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/GrantLine.java create mode 100644 jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlGrants.java create mode 100644 jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/GrantLineTest.java create mode 100644 jdbc/metadata/src/test/java/org/eclipse/daanse/sql/jdbc/metadata/MySqlGrantsTest.java diff --git a/jdbc/impl/pom.xml b/jdbc/impl/pom.xml index 14f028d6..49e66f45 100644 --- a/jdbc/impl/pom.xml +++ b/jdbc/impl/pom.xml @@ -89,6 +89,12 @@ 1.21.4 test + + org.testcontainers + mssqlserver + 1.21.4 + test + com.oracle.database.jdbc ojdbc11 @@ -101,6 +107,24 @@ 42.7.12 test + + com.microsoft.sqlserver + mssql-jdbc + 12.6.5.jre11 + test + + + com.mysql + mysql-connector-j + 8.4.0 + test + + + org.mariadb.jdbc + mariadb-java-client + 3.5.11 + test + org.junit.jupiter diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsInOneScopeH2Test.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsInOneScopeH2Test.java index a6b26553..7bbfef81 100644 --- a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsInOneScopeH2Test.java +++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/DatabaseServiceReadsInOneScopeH2Test.java @@ -26,6 +26,7 @@ import org.eclipse.daanse.sql.jdbc.api.MetadataScopeException; import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo; import org.eclipse.daanse.sql.jdbc.api.schema.TableDefinition; +import org.eclipse.daanse.sql.jdbc.metadata.H2MetadataProvider; import org.eclipse.daanse.sql.jdbc.record.schema.TableDefinitionRecord; import org.eclipse.daanse.sql.jdbc.record.schema.TableMetaDataRecord; import org.eclipse.daanse.sql.model.schema.SchemaReference; @@ -122,6 +123,16 @@ void theUserScopeAskedForIsReadInIt() throws SQLException { assertThat(structure.tables()).extracting(t -> t.table().name()).containsExactly("ORDERS"); } + @Test + void aDatabaseThatReadsOneWayOnlyReportsTheScopeAskedFor() throws SQLException { + StructureInfo structure = new DatabaseServiceImpl() + .createMetaInfo(connection, new H2MetadataProvider(MetadataScope.USER), true).structureInfo(); + + assertThat(structure.requestedScope()).isEqualTo(MetadataScope.USER); + assertThat(structure.scope()).isEqualTo(MetadataScope.USER); + assertThat(structure.tables()).extracting(t -> t.table().name()).contains("ORDERS", "SECRET"); + } + /** * Reads {@code VISIBLE} and {@code HIDDEN} in {@code DATABASE}, {@code VISIBLE} in {@code USER}; * counts what it reads. diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MariaDbMetadataScopeTest.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MariaDbMetadataScopeTest.java new file mode 100644 index 00000000..2b54bdff --- /dev/null +++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MariaDbMetadataScopeTest.java @@ -0,0 +1,289 @@ +/* +* Copyright (c) 2026 Contributors to the Eclipse Foundation. +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*/ +package org.eclipse.daanse.sql.jdbc.impl.scope; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Duration; +import java.util.List; + +import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; +import org.eclipse.daanse.sql.jdbc.api.MetadataScope; +import org.eclipse.daanse.sql.jdbc.api.MetadataScopeException; +import org.eclipse.daanse.sql.jdbc.api.meta.MetaInfo; +import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo; +import org.eclipse.daanse.sql.jdbc.metadata.MariaDbMetadataProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; + +/** + * The scopes on MariaDB, in a container. A schema is a database. {@code root} creates the objects + * and reads in {@link MetadataScope#DATABASE}; {@code clerk} may not read the grant tables of the + * schema {@code mysql} and reads in {@link MetadataScope#USER} what its default role, active in each + * of its sessions, lets it see. {@code information_schema} shows no grant to a role; the grants of + * the role are read from {@code SHOW GRANTS FOR} it. A reader that holds the rights the provider + * names, {@code SELECT, SHOW VIEW, TRIGGER, EXECUTE ON *.*}, and no other, reads in + * {@link MetadataScope#DATABASE} what {@code root} reads; one that may read the grant tables alone + * may not. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MariaDbMetadataScopeTest extends MetadataScopeContract { + + private static final String PASSWORD = "scope"; + + @SuppressWarnings("resource") + private final GenericContainer container = new GenericContainer<>("mariadb:11.4") + .withEnv("MARIADB_ROOT_PASSWORD", PASSWORD).withExposedPorts(3306) + .waitingFor(Wait.forLogMessage(".*ready for connections.*\\n", 2) + .withStartupTimeout(Duration.ofMinutes(3))); + + @Override + protected void start() { + container.start(); + } + + @Override + protected void stop() { + container.stop(); + } + + private String url() { + return "jdbc:mariadb://" + container.getHost() + ":" + container.getMappedPort(3306) + "/"; + } + + @Override + protected Connection admin() throws SQLException { + return DriverManager.getConnection(url(), "root", PASSWORD); + } + + @Override + protected Connection clerk() throws SQLException { + return DriverManager.getConnection(url(), "clerk", "clerk"); + } + + /** A new connection of {@code user}, whose password is its name. */ + private Connection connect(String user) throws SQLException { + return DriverManager.getConnection(url(), user, user); + } + + @Override + protected List fixture() { + return List.of("CREATE DATABASE shop", "CREATE DATABASE stock", "CREATE DATABASE hidden", + "CREATE TABLE shop.orders (id INT PRIMARY KEY, qty INT)", + "CREATE TABLE stock.product (id INT PRIMARY KEY)", + "CREATE TABLE stock.secret (id INT PRIMARY KEY)", + "CREATE TABLE hidden.t (id INT PRIMARY KEY)", + "CREATE FUNCTION stock.f() RETURNS INT DETERMINISTIC RETURN 1", + "CREATE ROLE r_reader", "CREATE ROLE r_other", + "GRANT SELECT ON shop.orders TO r_reader", "GRANT SELECT ON stock.product TO r_reader", + "GRANT SELECT ON stock.secret TO r_other", + "CREATE USER clerk IDENTIFIED BY 'clerk'", "GRANT r_reader TO clerk", + "SET DEFAULT ROLE r_reader FOR clerk", "GRANT UPDATE (qty) ON shop.orders TO clerk", + "GRANT EXECUTE ON FUNCTION stock.f TO clerk", + "CREATE USER other IDENTIFIED BY 'other'", "GRANT r_other TO other", + "SET DEFAULT ROLE r_other FOR other"); + } + + @Override + protected List grantTheHiddenTable() { + return List.of("GRANT SELECT ON hidden.t TO clerk"); + } + + @Override + protected List revokeTheHiddenTable() { + return List.of("REVOKE SELECT ON hidden.t FROM clerk"); + } + + @Override + protected MetadataProvider provider(MetadataScope scope) { + return new MariaDbMetadataProvider(scope); + } + + @Override + protected List catalogOfTheAdministrator() { + return List.of("MYSQL."); + } + + /** + * A role granted to the role of the user is active too, and so are its grants; the user may not + * run {@code SHOW GRANTS FOR} it, so they are read from {@code SHOW GRANTS FOR} the role of the + * user. + */ + @Test + void theGrantsOfARoleGrantedToTheActiveRoleAreRead() throws SQLException { + run(List.of("CREATE TABLE shop.lines (id INT PRIMARY KEY)", "CREATE ROLE r_base", + "GRANT SELECT ON shop.lines TO r_base", "GRANT r_base TO r_reader")); + try (Connection clerk = clerk()) { + StructureInfo structure = snapshot(clerk, MetadataScope.USER); + + assertThat(tables(structure)).contains("shop.lines"); + assertThat(tableGrants(structure)).contains("r_base select shop.lines", "r_reader select shop.orders"); + assertThat(memberships(structure)).contains("clerk > r_reader", "r_reader > r_base"); + } finally { + run(List.of("DROP ROLE r_base", "DROP TABLE shop.lines")); + } + } + + /** + * The keys of a table the user may only read: {@code TABLE_CONSTRAINTS} shows them only to a + * holder of more than {@code SELECT}, {@code KEY_COLUMN_USAGE} to every holder of a right. + */ + @Test + void theKeysOfATableTheUserMayOnlyReadAreRead() throws SQLException { + run(List.of("CREATE TABLE stock.part (id INT, code INT, CONSTRAINT pk_part PRIMARY KEY (id)," + + " CONSTRAINT uq_part_code UNIQUE (code))", "GRANT SELECT ON stock.part TO r_reader")); + try (Connection clerk = clerk()) { + StructureInfo structure = snapshot(clerk, MetadataScope.USER); + + assertThat(structure.primaryKeys()).filteredOn(pk -> pk.table().name().equals("part")) + .flatExtracting(pk -> pk.columns()).extracting(column -> column.name()).containsExactly("id"); + assertThat(structure.uniqueConstraints()).filteredOn(uc -> uc.table().name().equals("part")) + .extracting(uc -> uc.name()).containsExactly("uq_part_code"); + } finally { + run(List.of("DROP TABLE stock.part")); + } + } + + /** The grants of a role, with the columns a privilege holds for, read from {@code SHOW GRANTS FOR} it. */ + @Test + void theGrantsOfTheActiveRoleAreReadFromShowGrants() throws SQLException { + run(List.of("GRANT INSERT (id, qty) ON shop.orders TO r_reader")); + try (Connection clerk = clerk()) { + StructureInfo structure = snapshot(clerk, MetadataScope.USER); + + assertThat(columnGrants(structure)).contains("r_reader insert shop.orders.id", + "r_reader insert shop.orders.qty", "clerk update shop.orders.qty"); + assertThat(tableGrants(structure)).noneMatch(grant -> grant.contains(" insert ")); + } finally { + run(List.of("REVOKE INSERT (id, qty) ON shop.orders FROM r_reader")); + } + } + + /** + * A schema none of the readers below holds a right on, with an object of each kind the provider + * reads, and grants on them to {@code other}. + */ + private static List vault() { + return List.of("CREATE DATABASE vault", + "CREATE TABLE vault.parent (id INT PRIMARY KEY, code INT, qty INT," + + " CONSTRAINT uq_parent_code UNIQUE (code), CONSTRAINT ck_parent_qty CHECK (qty > 0))", + "CREATE TABLE vault.child (id INT PRIMARY KEY, parent_id INT," + + " CONSTRAINT fk_child_parent FOREIGN KEY (parent_id) REFERENCES vault.parent (id))", + "CREATE INDEX idx_child_parent ON vault.child (parent_id)", + "CREATE TABLE vault.part (id INT PRIMARY KEY) PARTITION BY HASH (id) PARTITIONS 2", + "CREATE SEQUENCE vault.seq START WITH 10 INCREMENT BY 5", + "CREATE FUNCTION vault.f_next(p INT) RETURNS INT DETERMINISTIC RETURN p + 1", + "CREATE VIEW vault.v_parent AS SELECT id, qty FROM vault.parent WHERE qty > 1", + "CREATE VIEW vault.v_next AS SELECT id, vault.f_next(qty) AS next_qty FROM vault.parent", + "CREATE TRIGGER vault.trg_child_inserted AFTER INSERT ON vault.child FOR EACH ROW" + + " SET @last_child = NEW.id", + "CREATE PROCEDURE vault.p_double(IN a INT, OUT b INT) SET b = a * 2", + "GRANT SELECT ON vault.parent TO other", "GRANT UPDATE (parent_id) ON vault.child TO other", + "GRANT EXECUTE ON PROCEDURE vault.p_double TO other"); + } + + private static List dropTheVault() { + return List.of("REVOKE SELECT ON vault.parent FROM other", "REVOKE UPDATE (parent_id) ON vault.child FROM other", + "REVOKE EXECUTE ON PROCEDURE vault.p_double FROM other", "DROP DATABASE vault"); + } + + /** What the administrator reads of the vault, each body among it. */ + private static final List VAULT = List.of("table child", "table parent", "table part", "view v_next", "view v_parent", + "column v_next.id", "column v_next.next_qty", "column v_parent.id", "column v_parent.qty", + "sequence seq", "primary key child [id]", "primary key parent [id]", "unique parent.uq_parent_code [code]", + "check parent.ck_parent_qty", "foreign key child.parent_id -> parent.id", + "index child.idx_child_parent parent_id", "query of v_next body", "query of v_parent body", + "trigger child.trg_child_inserted body", "function f_next [, p] body", "procedure p_double [a, b] body", + "grant select on parent to other", "grant update on child.parent_id to other", + "grant execute on p_double to other"); + + /** + * {@code SELECT} on the grant tables alone shows a reader the grants but not the schemas it holds + * no other right on: asked for {@link MetadataScope#DATABASE}, it reads in + * {@link MetadataScope#USER}, and strictly not at all. + */ + @Test + void theGrantTablesAloneAreNotTheWholeDatabase() throws SQLException { + run(List.of("CREATE USER grant_reader IDENTIFIED BY 'grant_reader'", + "GRANT SELECT ON mysql.user TO grant_reader", "GRANT SELECT ON mysql.roles_mapping TO grant_reader", + "GRANT SELECT ON mysql.tables_priv TO grant_reader", "GRANT SELECT ON mysql.columns_priv TO grant_reader", + "GRANT SELECT ON mysql.procs_priv TO grant_reader")); + MetadataProvider provider = provider(MetadataScope.DATABASE); + try (Connection reader = connect("grant_reader")) { + StructureInfo structure = snapshot(reader, MetadataScope.DATABASE); + + assertThat(structure.requestedScope()).isEqualTo(MetadataScope.DATABASE); + assertThat(structure.scope()).isEqualTo(MetadataScope.USER); + assertThat(tables(structure)).isEmpty(); + assertThatThrownBy(() -> metaInfo(reader, MetadataScope.DATABASE, true)) + .isInstanceOfSatisfying(MetadataScopeException.class, e -> { + assertThat(e.available()).isEqualTo(MetadataScope.USER); + assertThat(e.requirement()).isEqualTo(provider.scopeRequirement()) + .isEqualTo("SELECT, SHOW VIEW, TRIGGER, EXECUTE ON *.*"); + }); + } finally { + run(List.of("DROP USER grant_reader")); + } + } + + /** + * A reader granted the rights the provider names, as a {@code GRANT}, and no other, reads in + * {@link MetadataScope#DATABASE}, strictly, what {@code root} reads: the whole vault, each body + * and query, every grant, and everything else. MariaDB shows the columns of a view that calls a + * function, {@code v_next}, only to a reader that may execute the function. + */ + @Test + void aReaderHoldingTheRequirementReadsWhatTheAdministratorReads() throws SQLException { + run(vault()); + run(List.of("CREATE USER catalog_reader IDENTIFIED BY 'catalog_reader'", + "GRANT " + provider(MetadataScope.DATABASE).scopeRequirement() + " TO catalog_reader")); + try (Connection admin = admin(); Connection reader = connect("catalog_reader")) { + MetaInfo expected = metaInfo(admin, MetadataScope.DATABASE, true); + MetaInfo actual = metaInfo(reader, MetadataScope.DATABASE, true); + + assertThat(actual.structureInfo().scope()).isEqualTo(MetadataScope.DATABASE); + assertThat(inventory(expected, "vault")).containsAll(VAULT); + assertThat(inventory(actual, "vault")).isEqualTo(inventory(expected, "vault")); + assertSameMetadata(expected, actual); + } finally { + run(List.of("DROP USER catalog_reader")); + run(dropTheVault()); + } + } + + /** + * The rights count where a role active in the session holds them, also through a role granted + * to that role: not where the role is granted but not active. + */ + @Test + void theRequirementHeldThroughAnActiveRole() throws SQLException { + run(List.of("CREATE ROLE catalog_role", "CREATE ROLE catalog_outer", + "GRANT " + provider(MetadataScope.DATABASE).scopeRequirement() + " TO catalog_role", + "GRANT catalog_role TO catalog_outer", "CREATE USER role_reader IDENTIFIED BY 'role_reader'", + "GRANT catalog_outer TO role_reader")); + try { + try (Connection reader = connect("role_reader")) { + assertThat(provider(MetadataScope.DATABASE).effectiveScope(reader)).isEqualTo(MetadataScope.USER); + } + run(List.of("SET DEFAULT ROLE catalog_outer FOR role_reader")); + try (Connection reader = connect("role_reader")) { + assertThat(provider(MetadataScope.DATABASE).effectiveScope(reader)).isEqualTo(MetadataScope.DATABASE); + } + } finally { + run(List.of("DROP USER role_reader", "DROP ROLE catalog_outer", "DROP ROLE catalog_role")); + } + } +} diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MetadataScopeContract.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MetadataScopeContract.java index 9e8d3eab..54c7ac73 100644 --- a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MetadataScopeContract.java +++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MetadataScopeContract.java @@ -31,9 +31,12 @@ import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; import org.eclipse.daanse.sql.jdbc.api.MetadataScope; import org.eclipse.daanse.sql.jdbc.api.MetadataScopeException; +import org.eclipse.daanse.sql.jdbc.api.meta.MetaInfo; import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo; import org.eclipse.daanse.sql.jdbc.impl.DatabaseServiceImpl; import org.eclipse.daanse.sql.model.schema.CatalogReference; +import org.eclipse.daanse.sql.model.schema.ColumnReference; +import org.eclipse.daanse.sql.model.schema.Named; import org.eclipse.daanse.sql.model.schema.SchemaReference; import org.eclipse.daanse.sql.model.schema.TableReference; import org.junit.jupiter.api.AfterAll; @@ -241,6 +244,130 @@ protected StructureInfo snapshot(Connection connection, MetadataScope scope) thr return new DatabaseServiceImpl().createMetaInfo(connection, provider(scope)).structureInfo(); } + /** The snapshot of {@code connection} with its indexes, asked for in {@code scope}, strictly or not. */ + protected MetaInfo metaInfo(Connection connection, MetadataScope scope, boolean strict) throws SQLException { + return new DatabaseServiceImpl().createMetaInfo(connection, provider(scope), strict); + } + + /** + * Asserts that {@code actual} holds what {@code expected} holds, all of it: the catalogs, schemas, + * tables, columns, keys, constraints, indexes, views with their queries, triggers, sequences, + * partitions, functions and procedures with their parameters and bodies, the principals, the + * memberships and every grant. + */ + protected static void assertSameMetadata(MetaInfo expected, MetaInfo actual) { + StructureInfo e = expected.structureInfo(); + StructureInfo a = actual.structureInfo(); + assertThat(a.catalogs()).as("catalogs").containsExactlyInAnyOrderElementsOf(e.catalogs()); + assertThat(a.schemas()).as("schemas").containsExactlyInAnyOrderElementsOf(e.schemas()); + assertThat(a.tables()).as("tables").containsExactlyInAnyOrderElementsOf(e.tables()); + assertThat(a.columns()).as("columns").containsExactlyInAnyOrderElementsOf(e.columns()); + assertThat(a.primaryKeys()).as("primary keys").containsExactlyInAnyOrderElementsOf(e.primaryKeys()); + assertThat(a.importedKeys()).as("foreign keys").containsExactlyInAnyOrderElementsOf(e.importedKeys()); + assertThat(a.uniqueConstraints()).as("unique constraints") + .containsExactlyInAnyOrderElementsOf(e.uniqueConstraints()); + assertThat(a.checkConstraints()).as("checks").containsExactlyInAnyOrderElementsOf(e.checkConstraints()); + assertThat(actual.indexInfos()).as("indexes").containsExactlyInAnyOrderElementsOf(expected.indexInfos()); + assertThat(a.viewDefinitions()).as("views").containsExactlyInAnyOrderElementsOf(e.viewDefinitions()); + assertThat(a.triggers()).as("triggers").containsExactlyInAnyOrderElementsOf(e.triggers()); + assertThat(a.sequences()).as("sequences").containsExactlyInAnyOrderElementsOf(e.sequences()); + assertThat(a.partitions()).as("partitions").containsExactlyInAnyOrderElementsOf(e.partitions()); + assertThat(a.functions()).as("functions").containsExactlyInAnyOrderElementsOf(e.functions()); + assertThat(a.procedures()).as("procedures").containsExactlyInAnyOrderElementsOf(e.procedures()); + assertThat(a.principals()).as("principals").containsExactlyInAnyOrderElementsOf(e.principals()); + assertThat(a.roleMemberships()).as("memberships").containsExactlyInAnyOrderElementsOf(e.roleMemberships()); + assertThat(a.tablePrivileges()).as("grants on tables") + .containsExactlyInAnyOrderElementsOf(e.tablePrivileges()); + assertThat(a.columnPrivileges()).as("grants on columns") + .containsExactlyInAnyOrderElementsOf(e.columnPrivileges()); + assertThat(a.objectPrivileges()).as("grants on routines") + .containsExactlyInAnyOrderElementsOf(e.objectPrivileges()); + } + + /** + * What a snapshot holds in {@code schema}, one line for each object, as + * {@code kind table.name detail}: the tables and views with their columns, the keys, constraints + * and indexes, the query of each view, the triggers, functions and procedures with their + * parameters, each body as {@code body} where the snapshot holds it, the sequences and the grants. + * Names in lower case. + */ + protected static Set inventory(MetaInfo info, String schema) { + StructureInfo s = info.structureInfo(); + Set lines = new TreeSet<>(); + for (var table : s.tables()) { + if (isIn(table.table().schema(), schema)) { + lines.add(lower(table.table().type()) + " " + lower(table.table().name())); + } + } + for (var column : s.columns()) { + TableReference table = column.column().table().orElseThrow(); + if (isIn(table.schema(), schema)) { + lines.add("column " + lower(table.name()) + "." + lower(column.column().name())); + } + } + s.primaryKeys().stream().filter(pk -> isIn(pk.table().schema(), schema)) + .forEach(pk -> lines.add("primary key " + lower(pk.table().name()) + " " + names(pk.columns()))); + s.uniqueConstraints().stream().filter(uc -> isIn(uc.table().schema(), schema)) + .forEach(uc -> lines.add("unique " + lower(uc.table().name()) + "." + lower(uc.name()) + " " + + names(uc.columns()))); + s.checkConstraints().stream().filter(cc -> isIn(cc.table().schema(), schema)) + .forEach(cc -> lines.add("check " + lower(cc.table().name()) + "." + lower(cc.name()))); + for (var key : s.importedKeys()) { + TableReference table = key.foreignKeyColumn().table().orElseThrow(); + if (isIn(table.schema(), schema)) { + lines.add("foreign key " + lower(table.name()) + "." + lower(key.foreignKeyColumn().name()) + " -> " + + lower(key.primaryKeyColumn().table().orElseThrow().name()) + "." + + lower(key.primaryKeyColumn().name())); + } + } + for (var index : info.indexInfos()) { + if (isIn(index.tableReference().schema(), schema)) { + index.indexInfoItems().forEach(item -> lines.add("index " + lower(index.tableReference().name()) + "." + + lower(item.indexName().orElse("")) + " " + + lower(item.column().map(ColumnReference::name).orElse("")))); + } + } + s.viewDefinitions().stream().filter(v -> isIn(v.view().schema(), schema)) + .forEach(v -> lines.add("query of " + lower(v.view().name()) + body(v.viewBody()))); + s.triggers().stream().filter(t -> isIn(t.reference().table().schema(), schema)) + .forEach(t -> lines.add("trigger " + lower(t.reference().table().name()) + "." + + lower(t.reference().name()) + body(t.body()))); + s.functions().stream().filter(f -> isIn(f.reference().schema(), schema)) + .forEach(f -> lines.add("function " + lower(f.reference().name()) + " " + names(f.columns()) + + body(f.body()))); + s.procedures().stream().filter(p -> isIn(p.reference().schema(), schema)) + .forEach(p -> lines.add("procedure " + lower(p.reference().name()) + " " + names(p.columns()) + + body(p.body()))); + s.sequences().stream().filter(q -> isIn(q.reference().schema(), schema)) + .forEach(q -> lines.add("sequence " + lower(q.reference().name()))); + s.tablePrivileges().stream().filter(p -> isIn(p.table().schema(), schema)) + .forEach(p -> lines.add("grant " + lower(p.privilege()) + " on " + lower(p.table().name()) + " to " + + lower(p.grantee()))); + for (var p : s.columnPrivileges()) { + TableReference table = p.column().table().orElseThrow(); + if (isIn(table.schema(), schema)) { + lines.add("grant " + lower(p.privilege()) + " on " + lower(table.name()) + "." + + lower(p.column().name()) + " to " + lower(p.grantee())); + } + } + s.objectPrivileges().stream().filter(p -> p.schemaName().map(n -> lower(n).equals(schema)).orElse(false)) + .forEach(p -> lines.add("grant " + lower(p.privilege()) + " on " + lower(p.objectName()) + " to " + + lower(p.grantee()))); + return lines; + } + + private static boolean isIn(Optional reference, String schema) { + return reference.map(s -> lower(s.name()).equals(schema)).orElse(false); + } + + private static String names(List named) { + return named.stream().map(n -> lower(n.name())).toList().toString(); + } + + private static String body(Optional body) { + return body.filter(b -> !b.isBlank()).isPresent() ? " body" : ""; + } + /** Runs {@code statements} as the administrator. */ protected void run(List statements) throws SQLException { try (Connection admin = admin(); Statement statement = admin.createStatement()) { diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MsSqlMetadataScopeTest.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MsSqlMetadataScopeTest.java new file mode 100644 index 00000000..aea85e20 --- /dev/null +++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MsSqlMetadataScopeTest.java @@ -0,0 +1,133 @@ +/* +* Copyright (c) 2026 Contributors to the Eclipse Foundation. +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*/ +package org.eclipse.daanse.sql.jdbc.impl.scope; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; +import org.eclipse.daanse.sql.jdbc.api.MetadataScope; +import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo; +import org.eclipse.daanse.sql.jdbc.metadata.MicrosoftSqlServerMetadataProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.testcontainers.containers.MSSQLServerContainer; + +/** + * The scopes on SQL Server, in a container, in a database of their own. {@code sa} creates the + * objects and reads in {@link MetadataScope#DATABASE}; the database shows {@code clerk} only what + * it owns or holds a right on. {@code viewer}, which holds {@code VIEW DEFINITION} on the database + * and nothing else, reads the whole database too. A password must not hold the name of its login. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MsSqlMetadataScopeTest extends MetadataScopeContract { + + @SuppressWarnings("resource") + private final MSSQLServerContainer container = new MSSQLServerContainer<>( + "mcr.microsoft.com/mssql/server:2022-latest").acceptLicense(); + + @Override + protected void start() throws SQLException { + container.start(); + try (Connection master = DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(), + container.getPassword()); Statement statement = master.createStatement()) { + statement.execute("CREATE DATABASE scope"); + } + } + + @Override + protected void stop() { + container.stop(); + } + + private String url() { + return container.getJdbcUrl() + ";databaseName=scope"; + } + + @Override + protected Connection admin() throws SQLException { + return DriverManager.getConnection(url(), container.getUsername(), container.getPassword()); + } + + @Override + protected Connection clerk() throws SQLException { + return DriverManager.getConnection(url(), "clerk", "Kontor!Pass123"); + } + + @Override + protected List fixture() { + return List.of("CREATE SCHEMA shop", "CREATE SCHEMA stock", "CREATE SCHEMA hidden", + "CREATE TABLE shop.orders (id INT PRIMARY KEY, qty INT)", + "CREATE TABLE stock.product (id INT PRIMARY KEY)", + "CREATE TABLE stock.secret (id INT PRIMARY KEY)", + "CREATE TABLE hidden.t (id INT PRIMARY KEY)", + "CREATE FUNCTION stock.f() RETURNS INT AS BEGIN RETURN 1 END", + "CREATE ROLE r_reader", "CREATE ROLE r_other", + "GRANT SELECT ON shop.orders TO r_reader", "GRANT SELECT ON stock.product TO r_reader", + "GRANT SELECT ON stock.secret TO r_other", + "CREATE LOGIN clerk WITH PASSWORD = 'Kontor!Pass123', CHECK_POLICY = OFF", + "CREATE USER clerk FOR LOGIN clerk", "ALTER ROLE r_reader ADD MEMBER clerk", + "GRANT UPDATE (qty) ON shop.orders TO clerk", "GRANT EXECUTE ON stock.f TO clerk", + "CREATE LOGIN other WITH PASSWORD = 'Fremd!Pass123', CHECK_POLICY = OFF", + "CREATE USER other FOR LOGIN other", "ALTER ROLE r_other ADD MEMBER other", + "CREATE LOGIN viewer WITH PASSWORD = 'Schauen!Pass123', CHECK_POLICY = OFF", + "CREATE USER viewer FOR LOGIN viewer", "GRANT VIEW DEFINITION TO viewer"); + } + + @Override + protected List grantTheHiddenTable() { + return List.of("GRANT SELECT ON hidden.t TO clerk"); + } + + @Override + protected List revokeTheHiddenTable() { + return List.of("REVOKE SELECT ON hidden.t FROM clerk"); + } + + @Override + protected MetadataProvider provider(MetadataScope scope) { + return new MicrosoftSqlServerMetadataProvider(scope); + } + + /** + * A user that holds {@code VIEW DEFINITION} on the database and no right on any object reads + * every object, principal, membership and grant. + */ + @Test + void databaseScopeWithViewDefinition() throws SQLException { + try (Connection viewer = DriverManager.getConnection(url(), "viewer", "Schauen!Pass123")) { + StructureInfo structure = snapshot(viewer, MetadataScope.DATABASE); + + assertThat(structure.scope()).isEqualTo(MetadataScope.DATABASE); + assertThat(tables(structure)).containsExactlyInAnyOrder("shop.orders", "stock.product", "stock.secret", + "hidden.t"); + assertThat(schemas(structure)).contains("shop", "stock", "hidden"); + assertThat(principals(structure)).contains("r_reader", "r_other", "clerk", "other"); + assertThat(memberships(structure)).contains("clerk > r_reader", "other > r_other"); + assertThat(tableGrants(structure)).contains("r_other select stock.secret"); + assertThat(columnGrants(structure)).contains("clerk update shop.orders.qty"); + assertThat(routineGrants(structure)).contains("clerk execute stock.f"); + } + } + + @Test + void aGrantOnARoutineIsNoTableGrant() throws SQLException { + try (Connection admin = admin()) { + StructureInfo structure = snapshot(admin, MetadataScope.DATABASE); + + assertThat(tableGrants(structure)).noneMatch(grant -> grant.endsWith("stock.f")); + } + } +} diff --git a/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MySqlMetadataScopeTest.java b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MySqlMetadataScopeTest.java new file mode 100644 index 00000000..436515b9 --- /dev/null +++ b/jdbc/impl/src/test/java/org/eclipse/daanse/sql/jdbc/impl/scope/MySqlMetadataScopeTest.java @@ -0,0 +1,251 @@ +/* +* Copyright (c) 2026 Contributors to the Eclipse Foundation. +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*/ +package org.eclipse.daanse.sql.jdbc.impl.scope; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Duration; +import java.util.List; + +import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; +import org.eclipse.daanse.sql.jdbc.api.MetadataScope; +import org.eclipse.daanse.sql.jdbc.api.MetadataScopeException; +import org.eclipse.daanse.sql.jdbc.api.meta.MetaInfo; +import org.eclipse.daanse.sql.jdbc.api.meta.StructureInfo; +import org.eclipse.daanse.sql.jdbc.metadata.MySqlMetadataProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; + +/** + * The scopes on MySQL, in a container. A schema is a database. {@code root} creates the objects and + * reads in {@link MetadataScope#DATABASE}; {@code clerk} may not read the grant tables of the schema + * {@code mysql} and reads in {@link MetadataScope#USER} what its active roles let it see: its role + * is its default role, active in each of its sessions. A reader that holds the rights the provider + * names, {@code SELECT, SHOW VIEW, TRIGGER ON *.*}, and no other, reads in + * {@link MetadataScope#DATABASE} what {@code root} reads; one that may read the grant tables alone + * may not. + */ +@EnabledIfSystemProperty(named = "integration.docker", matches = "true") +class MySqlMetadataScopeTest extends MetadataScopeContract { + + private static final String PASSWORD = "scope"; + + @SuppressWarnings("resource") + private final GenericContainer container = new GenericContainer<>("mysql:8.4") + .withEnv("MYSQL_ROOT_PASSWORD", PASSWORD).withExposedPorts(3306) + .waitingFor(Wait.forLogMessage(".*ready for connections.*port: 3306.*", 1) + .withStartupTimeout(Duration.ofMinutes(3))); + + @Override + protected void start() { + container.start(); + } + + @Override + protected void stop() { + container.stop(); + } + + private String url() { + return "jdbc:mysql://" + container.getHost() + ":" + container.getMappedPort(3306) + + "/?allowPublicKeyRetrieval=true&useSSL=false"; + } + + @Override + protected Connection admin() throws SQLException { + return DriverManager.getConnection(url(), "root", PASSWORD); + } + + @Override + protected Connection clerk() throws SQLException { + return DriverManager.getConnection(url(), "clerk", "clerk"); + } + + /** A new connection of {@code user}, whose password is its name. */ + private Connection connect(String user) throws SQLException { + return DriverManager.getConnection(url(), user, user); + } + + @Override + protected List fixture() { + return List.of("CREATE DATABASE shop", "CREATE DATABASE stock", "CREATE DATABASE hidden", + "CREATE TABLE shop.orders (id INT PRIMARY KEY, qty INT)", + "CREATE TABLE stock.product (id INT PRIMARY KEY)", + "CREATE TABLE stock.secret (id INT PRIMARY KEY)", + "CREATE TABLE hidden.t (id INT PRIMARY KEY)", + "CREATE FUNCTION stock.f() RETURNS INT DETERMINISTIC RETURN 1", + "CREATE ROLE r_reader, r_other", + "GRANT SELECT ON shop.orders TO r_reader", "GRANT SELECT ON stock.product TO r_reader", + "GRANT SELECT ON stock.secret TO r_other", + "CREATE USER clerk IDENTIFIED BY 'clerk'", "GRANT r_reader TO clerk", + "SET DEFAULT ROLE r_reader TO clerk", "GRANT UPDATE (qty) ON shop.orders TO clerk", + "GRANT EXECUTE ON FUNCTION stock.f TO clerk", + "CREATE USER other IDENTIFIED BY 'other'", "GRANT r_other TO other", + "SET DEFAULT ROLE r_other TO other"); + } + + @Override + protected List grantTheHiddenTable() { + return List.of("GRANT SELECT ON hidden.t TO clerk"); + } + + @Override + protected List revokeTheHiddenTable() { + return List.of("REVOKE SELECT ON hidden.t FROM clerk"); + } + + @Override + protected MetadataProvider provider(MetadataScope scope) { + return new MySqlMetadataProvider(scope); + } + + @Override + protected List catalogOfTheAdministrator() { + return List.of("MYSQL."); + } + + /** + * A session sees what its active roles let it see: without its default role {@code clerk} sees + * only the orders, through its right on one of their columns, and none of the grants of the role. + */ + @Test + void userScopeFollowsTheActiveRoles() throws SQLException { + run(List.of("SET DEFAULT ROLE NONE TO clerk")); + try (Connection clerk = clerk()) { + StructureInfo structure = snapshot(clerk, MetadataScope.USER); + + assertThat(tables(structure)).containsExactly("shop.orders"); + assertThat(tableGrants(structure)).isEmpty(); + assertThat(columnGrants(structure)).containsExactly("clerk update shop.orders.qty"); + assertThat(memberships(structure)).containsExactly("clerk > r_reader"); + } finally { + run(List.of("SET DEFAULT ROLE r_reader TO clerk")); + } + } + + /** + * A schema none of the readers below holds a right on, with an object of each kind the provider + * reads, and grants on them to {@code other}. + */ + private static List vault() { + return List.of("CREATE DATABASE vault", + "CREATE TABLE vault.parent (id INT PRIMARY KEY, code INT, qty INT," + + " CONSTRAINT uq_parent_code UNIQUE (code), CONSTRAINT ck_parent_qty CHECK (qty > 0))", + "CREATE TABLE vault.child (id INT PRIMARY KEY, parent_id INT," + + " CONSTRAINT fk_child_parent FOREIGN KEY (parent_id) REFERENCES vault.parent (id))", + "CREATE INDEX idx_child_parent ON vault.child (parent_id)", + "CREATE TABLE vault.part (id INT PRIMARY KEY) PARTITION BY HASH (id) PARTITIONS 2", + "CREATE FUNCTION vault.f_next(p INT) RETURNS INT DETERMINISTIC RETURN p + 1", + "CREATE VIEW vault.v_parent AS SELECT id, qty FROM vault.parent WHERE qty > 1", + "CREATE VIEW vault.v_next AS SELECT id, vault.f_next(qty) AS next_qty FROM vault.parent", + "CREATE TRIGGER vault.trg_child_inserted AFTER INSERT ON vault.child FOR EACH ROW" + + " SET @last_child = NEW.id", + "CREATE PROCEDURE vault.p_double(IN a INT, OUT b INT) SET b = a * 2", + "GRANT SELECT ON vault.parent TO other", "GRANT UPDATE (parent_id) ON vault.child TO other", + "GRANT EXECUTE ON PROCEDURE vault.p_double TO other"); + } + + private static List dropTheVault() { + return List.of("REVOKE SELECT ON vault.parent FROM other", "REVOKE UPDATE (parent_id) ON vault.child FROM other", + "REVOKE EXECUTE ON PROCEDURE vault.p_double FROM other", "DROP DATABASE vault"); + } + + /** What the administrator reads of the vault, each body among it. */ + private static final List VAULT = List.of("table child", "table parent", "table part", "view v_next", "view v_parent", + "column v_next.id", "column v_next.next_qty", "column v_parent.id", "column v_parent.qty", + "primary key child [id]", "primary key parent [id]", "unique parent.uq_parent_code [code]", + "check parent.ck_parent_qty", "foreign key child.parent_id -> parent.id", + "index child.idx_child_parent parent_id", "query of v_next body", "query of v_parent body", + "trigger child.trg_child_inserted body", "function f_next [, p] body", "procedure p_double [a, b] body", + "grant select on parent to other", "grant update on child.parent_id to other", + "grant execute on p_double to other"); + + /** + * {@code SELECT} on the grant tables alone shows a reader the grants but not the schemas it holds + * no other right on: asked for {@link MetadataScope#DATABASE}, it reads in + * {@link MetadataScope#USER}, and strictly not at all. + */ + @Test + void theGrantTablesAloneAreNotTheWholeDatabase() throws SQLException { + run(List.of("CREATE USER grant_reader IDENTIFIED BY 'grant_reader'", + "GRANT SELECT ON mysql.user TO grant_reader", "GRANT SELECT ON mysql.role_edges TO grant_reader", + "GRANT SELECT ON mysql.tables_priv TO grant_reader", "GRANT SELECT ON mysql.columns_priv TO grant_reader", + "GRANT SELECT ON mysql.procs_priv TO grant_reader")); + MetadataProvider provider = provider(MetadataScope.DATABASE); + try (Connection reader = connect("grant_reader")) { + StructureInfo structure = snapshot(reader, MetadataScope.DATABASE); + + assertThat(structure.requestedScope()).isEqualTo(MetadataScope.DATABASE); + assertThat(structure.scope()).isEqualTo(MetadataScope.USER); + assertThat(tables(structure)).isEmpty(); + assertThatThrownBy(() -> metaInfo(reader, MetadataScope.DATABASE, true)) + .isInstanceOfSatisfying(MetadataScopeException.class, e -> { + assertThat(e.available()).isEqualTo(MetadataScope.USER); + assertThat(e.requirement()).isEqualTo(provider.scopeRequirement()) + .isEqualTo("SELECT, SHOW VIEW, TRIGGER ON *.*"); + }); + } finally { + run(List.of("DROP USER grant_reader")); + } + } + + /** + * A reader granted the rights the provider names, as a {@code GRANT}, and no other, reads in + * {@link MetadataScope#DATABASE}, strictly, what {@code root} reads: the whole vault, each body + * and query, every grant, and everything else. + */ + @Test + void aReaderHoldingTheRequirementReadsWhatTheAdministratorReads() throws SQLException { + run(vault()); + run(List.of("CREATE USER catalog_reader IDENTIFIED BY 'catalog_reader'", + "GRANT " + provider(MetadataScope.DATABASE).scopeRequirement() + " TO catalog_reader")); + try (Connection admin = admin(); Connection reader = connect("catalog_reader")) { + MetaInfo expected = metaInfo(admin, MetadataScope.DATABASE, true); + MetaInfo actual = metaInfo(reader, MetadataScope.DATABASE, true); + + assertThat(actual.structureInfo().scope()).isEqualTo(MetadataScope.DATABASE); + assertThat(inventory(expected, "vault")).containsAll(VAULT); + assertThat(inventory(actual, "vault")).isEqualTo(inventory(expected, "vault")); + assertSameMetadata(expected, actual); + } finally { + run(List.of("DROP USER catalog_reader")); + run(dropTheVault()); + } + } + + /** + * The rights count where a role active in the session holds them, also through a role granted + * to that role: not where the role is granted but not active. + */ + @Test + void theRequirementHeldThroughAnActiveRole() throws SQLException { + run(List.of("CREATE ROLE catalog_role, catalog_outer", + "GRANT " + provider(MetadataScope.DATABASE).scopeRequirement() + " TO catalog_role", + "GRANT catalog_role TO catalog_outer", "CREATE USER role_reader IDENTIFIED BY 'role_reader'", + "GRANT catalog_outer TO role_reader")); + try { + try (Connection reader = connect("role_reader")) { + assertThat(provider(MetadataScope.DATABASE).effectiveScope(reader)).isEqualTo(MetadataScope.USER); + } + run(List.of("SET DEFAULT ROLE catalog_outer TO role_reader")); + try (Connection reader = connect("role_reader")) { + assertThat(provider(MetadataScope.DATABASE).effectiveScope(reader)).isEqualTo(MetadataScope.DATABASE); + } + } finally { + run(List.of("DROP USER role_reader", "DROP ROLE catalog_outer, catalog_role")); + } + } +} diff --git a/jdbc/metadata/README.md b/jdbc/metadata/README.md new file mode 100644 index 00000000..befb2a3f --- /dev/null +++ b/jdbc/metadata/README.md @@ -0,0 +1,199 @@ +# Daanse SQL JDBC Metadata + +One `MetadataProvider` per database reads what the JDBC driver does not report, or reports +incompletely: keys, constraints, indexes, triggers, sequences, synonyms, partitions, routines with +their parameters and bodies, comments, users and roles, memberships and grants. `MetadataProviders` +picks the provider for a connection or a database product name; `DatabaseServiceImpl` +(`jdbc/impl`) reads a whole snapshot with it. + +| Product | Provider | +| --- | --- | +| Oracle | `OracleMetadataProvider` | +| PostgreSQL | `PostgreSqlMetadataProvider` | +| Microsoft SQL Server | `MicrosoftSqlServerMetadataProvider` | +| MySQL | `MySqlMetadataProvider` | +| MariaDB | `MariaDbMetadataProvider` | +| H2 | `H2MetadataProvider` | +| DuckDB | `DuckDbMetadataProvider` | + +## Two scopes: the whole database, or what the user may see + +A snapshot is read in one of two scopes, `MetadataScope`: + +- **`DATABASE`** — the whole database: every schema with all its tables, views, keys, constraints, + indexes, triggers, functions and procedures; every user and role, every membership, every grant. +- **`USER`** — the database as the connected user sees it: the schemas and objects it holds a right + on, also in schemas of others; the roles it holds, its memberships, the grants that concern it. + What it may not see is missing, without an error. + +The scope is a property of the provider. One call with one parameter reads a database in a scope; +both scopes are two calls and two snapshots. + +```java +MetadataProvider provider = MetadataProviders.forConnection(connection, MetadataScope.USER).orElseThrow(); +MetaInfo info = new DatabaseServiceImpl().createMetaInfo(connection, provider, /* strict */ false); +info.structureInfo().requestedScope(); // USER +info.structureInfo().scope(); // USER +``` + +`MetadataProviders.forConnection(connection)` and `forProductName(name)` without a scope, and every +provider made with its constructor without arguments, read in `DATABASE`. + +### A connection that may not read the whole database + +Reading in `DATABASE` needs a right on most databases. A connection that lacks it and asks for +`DATABASE` gets the whole snapshot in `USER`, never a mix of both, and the snapshot says so: + +```java +MetaInfo info = new DatabaseServiceImpl().createMetaInfo(connection, + MetadataProviders.forConnection(connection).orElseThrow()); +info.structureInfo().requestedScope(); // DATABASE +info.structureInfo().scope(); // USER, where the connection lacks the right +``` + +Asked to be strict, the snapshot is not read at all; a `MetadataScopeException` names the product, +both scopes and the right that is missing: + +```java +try { + new DatabaseServiceImpl().createMetaInfo(connection, provider, /* strict */ true); +} catch (MetadataScopeException e) { + e.product(); // "Oracle" + e.requested(); // DATABASE + e.available(); // USER + e.requirement(); // "SELECT_CATALOG_ROLE or SELECT ANY DICTIONARY" +} +``` + +`MetadataProvider.effectiveScope(connection)` tells the scope a connection may read in, once per +snapshot; `scopeRequirement()` names the right `DATABASE` needs. + +## Each database + +| Database | `DATABASE` reads | `USER` reads | `DATABASE` needs | +| --- | --- | --- | --- | +| Oracle | the `DBA_` views, for every structure, user, role, membership and grant | the `ALL_` views; the roles from `USER_ROLE_PRIVS` and `ROLE_ROLE_PRIVS` | `SELECT_CATALOG_ROLE` or `SELECT ANY DICTIONARY` | +| PostgreSQL | the system catalog; the grants from the access control lists | the same catalog, under the conditions `information_schema` applies | nothing: every user may read the whole catalog | +| SQL Server | the catalog views | the same views, which show the user only what it may see | `VIEW DEFINITION` on the database | +| MySQL | `information_schema`; users, roles, memberships and grants from the schema `mysql` | `information_schema`, `APPLICABLE_ROLES`, `ROLE_*_GRANTS`, `SHOW GRANTS` | `SELECT, SHOW VIEW, TRIGGER ON *.*` | +| MariaDB | `information_schema`; users, roles, memberships and grants from the schema `mysql` | `information_schema`, `APPLICABLE_ROLES`, `SHOW GRANTS`, `SHOW GRANTS FOR` each active role | `SELECT, SHOW VIEW, TRIGGER, EXECUTE ON *.*` | +| H2, DuckDB | the catalog | the same | nothing | + +Both rights on Oracle and the right on SQL Server only let a reader read metadata, no data. The +rights on MySQL and MariaDB let it read every row of every table as well, and on MariaDB run every +function and procedure: neither has a right that shows a reader the whole structure without them +(see [below](#the-rights-to-read-the-whole-database-on-mysql-and-mariadb)). A grant on a schema, a +database or the whole server is not read; on PostgreSQL the access control list of the database is +read as an object privilege. + +### Oracle + +A schema is a user. The `ALL_` views show a reader the objects it holds a right on; a reader that +may read the dictionary, and has no right on a table, sees nothing of the schemas of others there. +So `DATABASE` reads every structure from the `DBA_` views, not only the grants, and reads the tables +itself instead of through the JDBC driver, which reads `ALL_OBJECTS`. A `PUBLIC` synonym is no +table of a schema. A connection reads in `DATABASE` where every `DBA_` view the provider reads +answers; else in `USER`. + +Every user may read `ALL_USERS`, which names every user: the schemas of `USER` are every user, as +in `DATABASE`, and those the user sees no object in hold nothing. The memberships of `USER` are +those of the user and of the roles it holds; Oracle shows no one, not even the owner of a role, the +memberships of other users. + +The whole database is large: `SYS` alone owns thousands of tables and views, and a snapshot in +`DATABASE` of an otherwise empty Oracle Database Free reads about eleven thousand of them. + +### PostgreSQL + +The system catalog shows every schema, relation, routine, role and access control list to every +user, so every connection reads in the scope it asks for. Both scopes read the grants from the +access control lists of tables, columns, routines, sequences and the database, not from +`information_schema`, which shows only grants to or by a role of the reader, repeats a grant on a +table for every column, and lists the rights an owner has without a grant. A relation without an +access control list has the default one, on which only its owner holds rights: no grant is read for +it. The sequences are read from `pg_sequence`, as `information_schema.sequences` shows only those +the reader holds a right on. + +`USER` reads the same catalog under the conditions of `information_schema`: a schema the user may +use (`USAGE`); in it the relations it owns, through a role or itself, or holds a right on; their +columns, keys, constraints, indexes, triggers and partitions; a foreign key only where both its +tables are visible; the routines it owns or may execute, the sequences and types it may use; the +grants to `PUBLIC` or to or by a role it has; its memberships and those of the roles it has; these +roles and the user. `PUBLIC` may execute a routine unless that was revoked, so every such routine +of a schema the user may use is visible. + +### SQL Server + +The database shows a user only the metadata of the objects it owns or holds a right on (metadata +visibility); the catalog views read the same in both scopes. `VIEW DEFINITION` on the database, +granted alone, shows every object, principal, membership and grant. Every user sees the name of +every schema: in `USER` the schemas are those holding an object the user sees. A `DENY` is read as +the privilege `DENY `. The grants on routines and sequences are object privileges. + +### MySQL + +A schema is a database, which the JDBC driver reports as a catalog. `information_schema` shows a +user the objects it holds a right on, through itself or through a role **active in its session**; +the provider does not change the session. A role becomes active in each session as the user's +default role (`SET DEFAULT ROLE`); without it, `USER` shows only what the user's own grants let it +see. The memberships of `USER` are all roles granted to the user, active or not. + +`information_schema` lists no grant on a routine to the user; `USER` reads them from +`SHOW GRANTS FOR` the user's own account, which, unlike `SHOW GRANTS` without an account, does not +mix in the grants of its active roles. Those come from `ROLE_TABLE_GRANTS`, `ROLE_COLUMN_GRANTS` and +`ROLE_ROUTINE_GRANTS`. A grantee or grantor is named without its host, as the principals are. + +### MariaDB + +As MySQL, with two differences. `information_schema` shows no grant to a role, and MariaDB has no +`ROLE_*_GRANTS` views. `USER` reads the grants of the active roles from `SHOW GRANTS FOR` each +active role granted to the user, which its holder may run and which shows the grants of the roles +granted to it as well; for a role granted to that role in turn, which is active too, the user may +not run it. For these grants a line of `SHOW GRANTS` is read only where it grants rights on one +table or routine; a grant on every object, on every object of a schema, of a role or of a proxy is +passed over. + +And `information_schema` shows the constraints of a table, `TABLE_CONSTRAINTS` and +`REFERENTIAL_CONSTRAINTS`, only to a user holding more than `SELECT` on it, and a check, +`CHECK_CONSTRAINTS`, only to a user holding a right on the whole schema. The primary keys and +unique constraints are read from `KEY_COLUMN_USAGE`, which shows them to every user holding a right +on the table; in `USER`, the foreign keys of a table the user may only select from, and the checks +of a schema it holds no right on as a whole, are missing. + +### The rights to read the whole database on MySQL and MariaDB + +`information_schema` shows a reader only the objects it holds a right on, and of these only part, +so the grant tables of the schema `mysql` alone are not the whole database: a reader that may read +them, and nothing else, sees every grant but no schema it holds no other right on. A connection +reads in `DATABASE` where it holds these rights on every object, `ON *.*`, which a DBA grants as + +```sql +GRANT SELECT, SHOW VIEW, TRIGGER ON *.* TO catalog_reader; -- MySQL +GRANT SELECT, SHOW VIEW, TRIGGER, EXECUTE ON *.* TO catalog_reader; -- MariaDB +``` + +and as `scopeRequirement()` names them. With these, and no other right, a reader reads what `root` +reads. Without one of them it would read less: + +| Right | Without it, `information_schema` shows the reader | +| --- | --- | +| `SELECT` | no column; no query of a view, which needs `SELECT` on the view as well as `SHOW VIEW`; on MySQL no key column, so no key; no function or procedure, which `SHOW_ROUTINE` on MySQL and `SHOW CREATE ROUTINE` on MariaDB 11.3 and later would show, but no column; on MariaDB no sequence, which is read by selecting from it. `SELECT` on every object covers the five grant tables. | +| `SHOW VIEW` | every view, but without its query | +| `TRIGGER` | no trigger | +| `EXECUTE`, MariaDB only | no column of a view that calls a stored function, also of many views of the schema `sys`: MariaDB finds the columns of a view by opening it. MySQL keeps them in its data dictionary. | + +So no set of rights without `SELECT` shows the whole structure. On MariaDB a reader holding `SELECT` +alone sees no constraint in `TABLE_CONSTRAINTS`, so no foreign key and no check; `SHOW VIEW` or +`TRIGGER` shows them. `SHOW DATABASES` is not needed: a right on every object shows every schema, +an empty one too. + +The rights count where they are granted to the account, to a role active in the session or to a +role granted to that role; the provider reads them from `SHOW GRANTS`, which shows all of them for +the session, and tries each of the five grant tables once besides. A role granted but not active +does not count. `ALL PRIVILEGES ON *.*` holds them all. On MySQL with `partial_revokes` on, a right +on every object revoked on a schema hides that schema from the reader: `SHOW GRANTS` shows the +revoke, and the connection reads in `USER`. + +The rights are the same on MySQL 8.0, 8.4 and 9.7 and on MariaDB 10.4, 10.6, 10.11, 11.3, 11.4, +11.8 and 12.3, and each of them exists on every version of both. MySQL 5.7 keeps no +`mysql.role_edges`, so a connection to it reads in `USER` whatever rights it holds. diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/DuckDbMetadataProvider.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/DuckDbMetadataProvider.java index baeebb2f..36d57975 100644 --- a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/DuckDbMetadataProvider.java +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/DuckDbMetadataProvider.java @@ -22,11 +22,13 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.daanse.sql.jdbc.api.MetadataProvider; +import org.eclipse.daanse.sql.jdbc.api.MetadataScope; import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfo; import org.eclipse.daanse.sql.jdbc.api.meta.IndexInfoItem; import org.eclipse.daanse.sql.jdbc.api.schema.CheckConstraint; @@ -56,9 +58,32 @@ *

DuckDB does not keep the name a constraint was given; it names each constraint after its table * and columns. A foreign key refers to a table of its own schema, as DuckDB has no other. Its * referential action is always {@code NO ACTION}.

+ * + *

DuckDB knows no users and no rights: both scopes read the same, and every connection may read + * in the scope it asks for. The snapshot names the scope asked for.

*/ public class DuckDbMetadataProvider implements MetadataProvider { + private final MetadataScope scope; + + public DuckDbMetadataProvider() { + this(MetadataScope.DATABASE); + } + + public DuckDbMetadataProvider(MetadataScope scope) { + this.scope = Objects.requireNonNull(scope, "scope"); + } + + @Override + public MetadataProvider withScope(MetadataScope other) { + return other == scope ? this : new DuckDbMetadataProvider(other); + } + + @Override + public MetadataScope scope() { + return scope; + } + private static final String CONSTRAINTS = """ SELECT table_name, constraint_name, constraint_column_names, expression, referenced_table, referenced_column_names diff --git a/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/GrantLine.java b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/GrantLine.java new file mode 100644 index 00000000..9096c672 --- /dev/null +++ b/jdbc/metadata/src/main/java/org/eclipse/daanse/sql/jdbc/metadata/GrantLine.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena - initial + * Stefan Bischof (bipolis.org) - initial + */ +package org.eclipse.daanse.sql.jdbc.metadata; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * A line of {@code SHOW GRANTS} on MySQL and MariaDB that grants rights on one table or one + * routine, read with a strict pattern: + * + *
+ * GRANT SELECT, UPDATE (`qty`) ON `shop`.`orders` TO `clerk`@`%` WITH GRANT OPTION
+ * GRANT EXECUTE ON FUNCTION `stock`.`f` TO `r_reader`
+ * 
+ * + * Each privilege may name the columns it holds for. Every other line is no such grant: a grant on + * every object ({@code ON *.*}) or every object of a schema ({@code ON `shop`.*}), of a role, of a + * proxy, {@code SET DEFAULT ROLE}, and any line the pattern does not hold. The privileges a line + * grants on every object, and those it revokes, are read apart: {@link #onEveryObject}, + * {@link #revoked}. + */ +final class GrantLine { + + /** What a line grants rights on. */ + enum Kind { + TABLE, FUNCTION, PROCEDURE + } + + /** A privilege, with the columns it holds for; none for the whole object. */ + record Privilege(String name, List columns) { + } + + /** The rights a line grants on one object. */ + record Grant(Kind kind, String schema, String object, List privileges, String grantee, + boolean grantable) { + } + + private static final String IDENTIFIER = "`(?:[^`]|``)+`"; + + private static final Pattern LINE = Pattern.compile("GRANT (?.+?) ON (?:(?FUNCTION|PROCEDURE) )?" + + "(?" + IDENTIFIER + ")\\.(?" + IDENTIFIER + ") TO (?" + IDENTIFIER + + ")(?:@" + IDENTIFIER + ")?(?