The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
check pg grant statements rights (#74909)
Alexander Polyankinf6de634363f3
diff --git a/modules/drivers/redshift/src/metabase/driver/redshift.clj b/modules/drivers/redshift/src/metabase/driver/redshift.cljindex a28bda9897f..79691497779 100644--- a/modules/drivers/redshift/src/metabase/driver/redshift.clj+++ b/modules/drivers/redshift/src/metabase/driver/redshift.clj@@ -789,7 +789,10 @@qu (sql.u/quote-name :postgres :field username)source-schemas (set schemas)spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))]- ;; Pre-flight check (read-only) can run in its own transaction.+ ;; Pre-flight check (read-only) can run in its own transaction. Only the+ ;; PUBLIC-CREATE assert is needed on Redshift — its GRANT statements error+ ;; loudly at execute time when grant authority is missing, so the silent-+ ;; skip class of bug we catch on PostgreSQL doesn't reproduce.(jdbc/with-db-transaction [t-conn spec](doseq [s source-schemas](assert-no-public-create-grant! t-conn s)))diff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.cljindex 5d60aa72d2d..f5a573d11a8 100644--- a/src/metabase/driver/postgres.clj+++ b/src/metabase/driver/postgres.clj@@ -1478,6 +1478,125 @@(when (public-create-grant? conn schema-name)(raise-public-create-grant! schema-name)))+(defn schema-missing-usage-grant-option?+ "True when the current PostgreSQL user does not hold `USAGE WITH GRANT OPTION`+ on `schema-name`. Without it, our `GRANT USAGE ON SCHEMA … TO <user>` silently+ no-ops and the workspace user can't resolve table names at all."+ [conn schema-name]+ (let [row (first (jdbc/query+ conn+ ["SELECT has_schema_privilege(current_user, ?, 'USAGE WITH GRANT OPTION') AS can_grant"+ schema-name]))]+ (not (:can_grant row))))++(defn raise-missing-usage-grant-option!+ "Throw the standard ex-info for the schema-USAGE-grant-option pre-condition."+ [schema-name]+ (throw (ex-info (format (str "User lacks USAGE WITH GRANT OPTION on schema \"%s\"; workspace "+ "provisioning cannot grant USAGE to the workspace user. Have the "+ "schema owner run:\n\n"+ " GRANT USAGE ON SCHEMA \"%s\" TO CURRENT_USER WITH GRANT OPTION;\n\n"+ "then retry workspace provisioning.")+ schema-name schema-name)+ {:status-code 412+ :schema schema-name})))++(defn assert-has-usage-grant-option!+ "Throws when the current PostgreSQL user lacks `USAGE WITH GRANT OPTION` on+ `schema-name`. Called from `grant-workspace-read-access!` per input schema."+ [conn schema-name]+ (when (schema-missing-usage-grant-option? conn schema-name)+ (raise-missing-usage-grant-option! schema-name)))++(defn tables-missing-grant-option+ "Return objects in `schema-name` for which the current PostgreSQL user does+ *not* hold `SELECT WITH GRANT OPTION`. Probes tables, partitioned tables,+ views, materialized views, and foreign tables — the same `relkind`s touched+ by `GRANT SELECT ON ALL TABLES IN SCHEMA`. `GRANT` silently no-ops on objects+ the connection user can't re-grant, so we check up front to fail fast."+ [conn schema-name]+ (jdbc/query+ conn+ [(str "SELECT n.nspname AS schema, c.relname AS object "+ "FROM pg_class c "+ "JOIN pg_namespace n ON n.oid = c.relnamespace "+ "WHERE n.nspname = ? "+ " AND c.relkind IN ('r','p','v','m','f') "+ " AND NOT has_table_privilege(current_user, c.oid, 'SELECT WITH GRANT OPTION') "+ "ORDER BY c.relname")+ schema-name]))++(defn raise-missing-grant-option!+ "Throw the standard ex-info for the SELECT-WITH-GRANT-OPTION pre-condition,+ naming the objects the current user cannot re-grant SELECT on."+ [schema-name objects]+ (let [qualified (map #(format "\"%s\".\"%s\"" (:schema %) (:object %)) objects)]+ (throw (ex-info (format (str "User lacks SELECT WITH GRANT OPTION on %d object(s) in schema "+ "\"%s\": %s. Workspace provisioning cannot grant SELECT to the "+ "workspace user on these objects. Have the object owner run:\n\n"+ " GRANT SELECT ON ALL TABLES IN SCHEMA \"%s\" TO CURRENT_USER WITH GRANT OPTION;\n\n"+ "then retry workspace provisioning.")+ (count objects) schema-name (str/join ", " qualified) schema-name)+ {:status-code 412+ :schema schema-name+ :objects (vec qualified)}))))++(defn assert-has-grant-option!+ "Throws when the current PostgreSQL user lacks `SELECT WITH GRANT OPTION` on+ any table/view in `schema-name`. Called from `grant-workspace-read-access!`+ per input schema alongside [[assert-no-public-create-grant!]] — without the+ grant option, our `GRANT SELECT ON ALL TABLES IN SCHEMA` silently skips the+ objects and the workspace user can't read them."+ [conn schema-name]+ (when-let [missing (seq (tables-missing-grant-option conn schema-name))]+ (raise-missing-grant-option! schema-name missing)))++(defn unmemberable-owners-in-schema+ "Return distinct roles owning objects in `schema-name` that the current+ PostgreSQL user is *not* a member of. `ALTER DEFAULT PRIVILEGES` (without+ `FOR ROLE`) only affects future objects created by the connection user, so+ tables created by any of these owner roles won't receive the workspace+ user's default SELECT — even if the statement runs without error.++ PostgreSQL-only: the query relies on `pg_has_role`'s implicit overload+ resolution (`name, oid, text`), which Redshift's planner rejects."+ [conn schema-name]+ (jdbc/query+ conn+ [(str "SELECT DISTINCT pg_get_userbyid(c.relowner) AS owner "+ "FROM pg_class c "+ "JOIN pg_namespace n ON n.oid = c.relnamespace "+ "WHERE n.nspname = ? "+ " AND c.relkind IN ('r','p','v','m','f') "+ " AND NOT pg_has_role(current_user, c.relowner, 'MEMBER') "+ "ORDER BY owner")+ schema-name]))++(defn raise-unmemberable-default-priv-owners!+ "Throw the standard ex-info for the ALTER-DEFAULT-PRIVILEGES pre-condition,+ naming the owner roles we cannot target with `FOR ROLE`."+ [schema-name owners]+ (let [owner-names (map :owner owners)]+ (throw (ex-info (format (str "Current user is not a member of %d role(s) that own objects in "+ "schema \"%s\": %s. `ALTER DEFAULT PRIVILEGES IN SCHEMA \"%s\"` "+ "cannot cover future objects created by these roles, so the "+ "workspace user would lose access to new tables. Grant role "+ "membership to the current user (e.g. `GRANT \"<owner>\" TO "+ "CURRENT_USER`), then retry workspace provisioning.")+ (count owners) schema-name (str/join ", " owner-names) schema-name)+ {:status-code 412+ :schema schema-name+ :owners (vec owner-names)}))))++(defn assert-can-alter-default-privileges!+ "Throws when objects in `schema-name` are owned by roles the current user+ isn't a member of, since our `ALTER DEFAULT PRIVILEGES IN SCHEMA …` (without+ `FOR ROLE`) can't extend the workspace user's default SELECT to future+ objects created by those roles."+ [conn schema-name]+ (when-let [missing (seq (unmemberable-owners-in-schema conn schema-name))]+ (raise-unmemberable-default-priv-owners! schema-name missing)))+;;; Isolation limit, checked at grant time in [[grant-workspace-read-access!]] via;;; [[assert-no-public-create-grant!]]: PostgreSQL's permission model lets a user;;; receive privileges either directly or through PUBLIC (the implicit pseudo-role@@ -1562,7 +1681,10 @@;; never touches can keep their default ACLs._ (jdbc/with-db-transaction [check-conn (sql-jdbc.conn/db->pooled-connection-spec (:id database))](doseq [s source-schemas]- (assert-no-public-create-grant! check-conn s)))+ (assert-no-public-create-grant! check-conn s)+ (assert-has-usage-grant-option! check-conn s)+ (assert-has-grant-option! check-conn s)+ (assert-can-alter-default-privileges! check-conn s)))sqls (grant-workspace-read-access-sqls username schemas)](jdbc/with-db-transaction [t-conn (sql-jdbc.conn/db->pooled-connection-spec (:id database))](with-open [^Statement stmt (.createStatement ^Connection (:connection t-conn))]diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.cljindex d0fb2e7a0dd..bbf0645374f 100644--- a/test/metabase/driver/postgres_test.clj+++ b/test/metabase/driver/postgres_test.clj@@ -2357,3 +2357,113 @@(is (=? {:type :missing-column:name "xix"}(first (driver/validate-native-query-fields :postgres broken-query))))))))))++;;; ---------------------------------------- Workspace provisioning ----------------------------------------------++(defmacro ^:private with-drop-schema!+ "Run `body`, ensuring `schema` is dropped (CASCADE) on `admin-spec` afterward."+ [admin-spec schema & body]+ `(try+ ~@body+ (finally+ (jdbc/execute! ~admin-spec+ [(format "DROP SCHEMA IF EXISTS \"%s\" CASCADE" ~schema)]))))++(defmacro ^:private with-drop-role!+ "Run `body`, ensuring `role` is dropped on `admin-spec` afterward."+ [admin-spec role & body]+ `(try+ ~@body+ (finally+ (jdbc/execute! ~admin-spec+ [(format "DROP ROLE IF EXISTS \"%s\"" ~role)]))))++(deftest workspace-precondition-usage-grant-option-test+ (mt/test-driver :postgres+ (testing "assert-has-usage-grant-option! throws when current_user lacks USAGE WITH GRANT OPTION on the schema"+ (mt/with-empty-db+ (let [admin-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))+ role "ws_pre_usage_role"+ schema "ws_pre_usage_schema"+ password (str (random-uuid))]+ (with-drop-role! admin-spec role+ (with-drop-schema! admin-spec schema+ (jdbc/execute! admin-spec+ [(str "CREATE ROLE \"" role "\" WITH LOGIN PASSWORD '" password "'; "+ "CREATE SCHEMA \"" schema "\"; "+ ;; USAGE without WITH GRANT OPTION+ "GRANT USAGE ON SCHEMA \"" schema "\" TO \"" role "\";")])+ (sql-jdbc.conn/with-connection-spec-for-testing-connection+ [user-spec [:postgres (assoc (:details (mt/db)) :user role :password password)]]+ (testing "fails when grant option is missing"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"USAGE WITH GRANT OPTION"+ (postgres/assert-has-usage-grant-option! user-spec schema))))+ (testing "passes once WITH GRANT OPTION is granted"+ (jdbc/execute! admin-spec+ [(str "GRANT USAGE ON SCHEMA \"" schema "\" TO \"" role "\" WITH GRANT OPTION")])+ (is (nil? (postgres/assert-has-usage-grant-option! user-spec schema))))))))))))++(deftest workspace-precondition-table-grant-option-test+ (mt/test-driver :postgres+ (testing "assert-has-grant-option! throws when current_user lacks SELECT WITH GRANT OPTION on a schema table"+ (mt/with-empty-db+ (let [admin-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))+ role "ws_pre_table_role"+ schema "ws_pre_table_schema"+ table "ws_pre_table_t"+ password (str (random-uuid))]+ (with-drop-role! admin-spec role+ (with-drop-schema! admin-spec schema+ (jdbc/execute! admin-spec+ [(str "CREATE ROLE \"" role "\" WITH LOGIN PASSWORD '" password "'; "+ "CREATE SCHEMA \"" schema "\"; "+ "CREATE TABLE \"" schema "\".\"" table "\" (id INT); "+ ;; Pass the schema-USAGE precondition so we test the table check in isolation.+ "GRANT USAGE ON SCHEMA \"" schema "\" TO \"" role "\" WITH GRANT OPTION; "+ ;; SELECT *without* WITH GRANT OPTION+ "GRANT SELECT ON \"" schema "\".\"" table "\" TO \"" role "\";")])+ (sql-jdbc.conn/with-connection-spec-for-testing-connection+ [user-spec [:postgres (assoc (:details (mt/db)) :user role :password password)]]+ (testing "fails and names the offending table"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"SELECT WITH GRANT OPTION"+ (postgres/assert-has-grant-option! user-spec schema))))+ (testing "passes once SELECT WITH GRANT OPTION is granted"+ (jdbc/execute! admin-spec+ [(str "GRANT SELECT ON \"" schema "\".\"" table "\" TO \"" role "\" WITH GRANT OPTION")])+ (is (nil? (postgres/assert-has-grant-option! user-spec schema))))))))))))++(deftest workspace-precondition-alter-default-privileges-test+ (mt/test-driver :postgres+ (testing "assert-can-alter-default-privileges! throws when an object owner is not a role the current_user belongs to"+ (mt/with-empty-db+ (let [admin-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))+ role "ws_pre_adp_role"+ owner "ws_pre_adp_other_owner"+ schema "ws_pre_adp_schema"+ table "ws_pre_adp_t"+ password (str (random-uuid))]+ (with-drop-role! admin-spec role+ (with-drop-role! admin-spec owner+ (with-drop-schema! admin-spec schema+ (jdbc/execute! admin-spec+ [(str "CREATE ROLE \"" role "\" WITH LOGIN PASSWORD '" password "'; "+ "CREATE ROLE \"" owner "\"; "+ "CREATE SCHEMA \"" schema "\"; "+ "GRANT USAGE ON SCHEMA \"" schema "\" TO \"" role "\" WITH GRANT OPTION; "+ "CREATE TABLE \"" schema "\".\"" table "\" (id INT); "+ "ALTER TABLE \"" schema "\".\"" table "\" OWNER TO \"" owner "\";")])+ (sql-jdbc.conn/with-connection-spec-for-testing-connection+ [user-spec [:postgres (assoc (:details (mt/db)) :user role :password password)]]+ (testing "fails and names the unmemberable owner"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"ALTER DEFAULT PRIVILEGES"+ (postgres/assert-can-alter-default-privileges! user-spec schema))))+ (testing "passes once the current_user becomes a member of the owner role"+ (jdbc/execute! admin-spec+ [(str "GRANT \"" owner "\" TO \"" role "\"")])+ (is (nil? (postgres/assert-can-alter-default-privileges! user-spec schema)))))))))))))