Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

GHY-3709 fix Redshift workspace destroy on foreign-grantor default privs (#74919)

bryan2aeb34082261
diff --git a/modules/drivers/redshift/src/metabase/driver/redshift.clj b/modules/drivers/redshift/src/metabase/driver/redshift.clj
index f859c1da5ba..2dbb178b935 100644
--- a/modules/drivers/redshift/src/metabase/driver/redshift.clj
+++ b/modules/drivers/redshift/src/metabase/driver/redshift.clj
@@ -769,6 +769,83 @@
(when (public-create-grant? conn schema-name)
(driver.postgres/raise-public-create-grant! schema-name)))
+(defn- current-user-usesuper?
+ "True when `current_user` has `usesuper`. Superusers can ALTER DEFAULT
+ PRIVILEGES FOR USER <anyone>, so they bypass the membership check below.
+
+ Redshift's user-membership model differs from PostgreSQL's: there is no
+ `pg_has_role(name, name, text)` overload (the function doesn't exist on
+ Redshift at all on RA3 clusters), and `pg_group` is not generally populated.
+ The practical membership graph collapses to: you are `current_user`, or you
+ are a superuser. Anything else fails at REVOKE time."
+ [conn]
+ (boolean (:usesuper (first (jdbc/query conn ["SELECT usesuper FROM pg_user WHERE usename = current_user"])))))
+
+(defn- relation-owners-in-schema
+ "Distinct relation owners in `schema-name`. Caller filters out the ones
+ `current_user` can impersonate.
+
+ Why this matters: `ALTER DEFAULT PRIVILEGES IN SCHEMA <s>` (without
+ `FOR ROLE`) only affects future objects created by the connection user.
+ Tables created later by foreign owners skip the iso-user grant -- workspace
+ data goes stale silently.
+
+ `relkind` set matches the scope of `ALTER DEFAULT PRIVILEGES ... ON TABLES`:
+ ordinary tables (`r`), views (`v`), materialized views (`m`), partitioned
+ tables (`p`), and foreign tables (`f`). Spectrum external tables live in
+ `svv_external_tables` and are not covered by `pg_default_acl`, so they need
+ no entry here."
+ [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','v','m','p','f') "
+ "ORDER BY owner")
+ schema-name])
+ (keep :owner)))
+
+(defn- default-acl-grantors-in-schema
+ "Distinct grantors of pre-existing `pg_default_acl` entries in `schema-name`.
+ Caller filters out the ones `current_user` can impersonate.
+
+ Distinct from [[relation-owners-in-schema]]: that surfaces future-object
+ grantor risk; this surfaces pre-existing default-priv rows we will need to
+ REVOKE FOR USER <grantor> at destroy time. Both block the workspace
+ contract."
+ [conn schema-name]
+ (->> (jdbc/query conn
+ [(str "SELECT DISTINCT u.usename AS owner "
+ "FROM pg_catalog.pg_default_acl d "
+ "JOIN pg_catalog.pg_user u ON u.usesysid = d.defacluser "
+ "JOIN pg_catalog.pg_namespace n ON n.oid = d.defaclnamespace "
+ "WHERE n.nspname = ? "
+ " AND d.defaclobjtype = 'r' "
+ "ORDER BY owner")
+ schema-name])
+ (keep :owner)))
+
+(defn assert-can-alter-default-privileges!
+ "Throws when `schema-name` has relation-owners or pre-existing default-priv
+ grantors that `current_user` cannot impersonate via `FOR USER`. On Redshift
+ the impersonation graph collapses to: `owner == current_user`, or
+ `current_user` is a superuser.
+
+ Without this guarantee we can neither extend defaults to future objects of
+ foreign owners (silent data drift) nor REVOKE pre-existing default-priv
+ entries at destroy time (DROP USER fails -> GHY-3709)."
+ [conn schema-name]
+ (when-not (current-user-usesuper? conn)
+ (let [me (:me (first (jdbc/query conn ["SELECT current_user AS me"])))
+ owners (->> (concat (relation-owners-in-schema conn schema-name)
+ (default-acl-grantors-in-schema conn schema-name))
+ distinct
+ (remove #(= % me))
+ (map (fn [o] {:owner o})))]
+ (when (seq owners)
+ (driver.postgres/raise-unmemberable-default-priv-owners! schema-name owners)))))
+
(defmethod driver/init-workspace-isolation! :redshift
[_driver database workspace]
(let [schema-name (driver.u/workspace-isolation-namespace-name workspace)
@@ -800,13 +877,20 @@
quoted-user (quote-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. 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.
+ ;; Pre-flight check (read-only) can run in its own transaction. Redshift's
+ ;; GRANT statements error loudly when grant authority is missing, so PG's
+ ;; silent-skip USAGE/SELECT class doesn't reproduce here. But two ALTER
+ ;; DEFAULT PRIVILEGES failure modes do reproduce and need explicit checks:
+ ;;
+ ;; - Foreign relation-owners: tables created later by an owner the
+ ;; connection user can't impersonate skip our default-priv grant.
+ ;; - Foreign default-priv grantors: pre-existing `pg_default_acl` rows whose
+ ;; grantor we can't impersonate at destroy time -> `DROP USER` fails
+ ;; (GHY-3709).
(jdbc/with-db-transaction [t-conn spec]
(doseq [s source-schemas]
- (assert-no-public-create-grant! t-conn s)))
+ (assert-no-public-create-grant! t-conn s)
+ (assert-can-alter-default-privileges! t-conn s)))
;; Grants run as auto-commit per statement so privileges are immediately
;; observable to a subsequent describe-database from a different connection.
(doseq [s source-schemas
@@ -828,7 +912,9 @@
(seq (jdbc/query conn ["SELECT 1 FROM pg_namespace WHERE nspname = ?" schema-name])))
(defn- schemas-with-user-grants
- "Query Redshift to find schemas where the user has been granted privileges."
+ "Query Redshift to find schemas where the user has been granted relation-level privileges.
+ `svv_relation_privileges` only surfaces actual GRANTs on existing relations -- it does NOT
+ list ALTER DEFAULT PRIVILEGES entries. See [[default-acl-grants-for-user]] for those."
[conn username]
(->> (jdbc/query conn
["SELECT DISTINCT namespace_name FROM svv_relation_privileges
@@ -836,19 +922,82 @@
username])
(keep :namespace_name)))
+(defn- escape-like-pattern
+ "Escape PostgreSQL/Redshift LIKE metacharacters (`%`, `_`) and our chosen
+ escape char (`|`) in `s` so it matches literally. Used with `ESCAPE '|'` on
+ the LIKE clause -- `|` chosen over `\\` because Redshift's SQL parser treats
+ a literal `'\\'` as an unterminated string. Without this escaping, iso-user
+ names containing `_` (which they always do -- the generator produces
+ `mb__isolation_<id>` form) would match siblings via wildcard, and the
+ destroy could revoke default-priv rows belonging to unrelated users."
+ [^String s]
+ (-> s
+ (str/replace "|" "||")
+ (str/replace "%" "|%")
+ (str/replace "_" "|_")))
+
+(defn- default-acl-grants-for-user
+ "Enumerate `(grantor, schema)` pairs that have an ALTER DEFAULT PRIVILEGES entry referencing
+ `username` as a grantee. Returns a seq of `{:grantor :schema}` maps.
+
+ Redshift exposes `pg_default_acl` but rejects `aclitem`->`varchar` casts and does not
+ provide `aclexplode`. We use `array_to_string(defaclacl, ',')` (allowed on aclitem[]).
+ Verified live: Redshift's `array_to_string` strips the enclosing braces of an `aclitem[]`,
+ so each entry is comma-separated text of the form `grantee=privs/grantor`. To make the
+ grantee match unambiguous, we prepend a `,` to the haystack and search for `,<name>=` --
+ that way a row with only one grantee (no preceding entries) still matches.
+
+ LIKE metacharacters in `username` are escaped with `ESCAPE '|'` so `_` and `%` match
+ literally -- critical because the iso-user generator always produces `_`-containing
+ names. Pipe over backslash because Redshift's parser rejects a literal backslash escape
+ clause as an unterminated string.
+
+ Schema-less entries (`defaclnamespace = 0`, applies to any schema) are excluded -- our
+ provisioning only ever issues `ALTER DEFAULT PRIVILEGES IN SCHEMA`, never the no-schema
+ form, so those entries do not originate here."
+ [conn username]
+ (let [esc (escape-like-pattern username)]
+ (jdbc/query
+ conn
+ [(str "SELECT u.usename AS grantor, "
+ " n.nspname AS schema "
+ "FROM pg_catalog.pg_default_acl d "
+ "JOIN pg_catalog.pg_user u ON u.usesysid = d.defacluser "
+ "JOIN pg_catalog.pg_namespace n ON n.oid = d.defaclnamespace "
+ "WHERE d.defaclobjtype = 'r' "
+ " AND (',' || array_to_string(d.defaclacl, ',')) LIKE ? ESCAPE '|'")
+ (str "%," esc "=%")])))
+
(defmethod driver/destroy-workspace-isolation! :redshift
[_driver database workspace]
(let [schema-name (:schema workspace)
username (-> workspace :database_details :user)
quoted-user (quote-field username)
- quoted-schema (quote-schema schema-name)]
- (jdbc/with-db-transaction [t-conn (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
- (let [user-exists (user-exists? t-conn username)
- schema-exists (schema-exists? t-conn schema-name)
+ quoted-schema (quote-schema schema-name)
+ spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
+ ;; Foreign-grantor default-priv REVOKEs run first, each in its own autocommit
+ ;; statement. Redshift has no SAVEPOINT and aborts the entire transaction on
+ ;; the first error, so these cannot share a transaction with the main cleanup
+ ;; batch: one stale row (schema dropped between discovery and execution) would
+ ;; otherwise poison DROP USER. Autocommit + per-statement catch is what
+ ;; actually lets the rest proceed.
+ (when (user-exists? spec username)
+ (doseq [{:keys [grantor schema]} (default-acl-grants-for-user spec username)
+ :let [sql (format "ALTER DEFAULT PRIVILEGES FOR USER %s IN SCHEMA %s REVOKE ALL ON TABLES FROM %s"
+ (quote-field grantor) (quote-schema schema) quoted-user)]]
+ (try
+ (jdbc/execute! spec [sql])
+ (catch Throwable t
+ (log/warnf t "Failed to revoke default-priv (%s, %s) referencing iso-user %s; continuing"
+ grantor schema username)))))
+ ;; Main batch stays transactional: relation revokes, iso-schema bare REVOKE,
+ ;; DROP SCHEMA, DROP USER -- the cleanup we want atomic.
+ (jdbc/with-db-transaction [t-conn spec]
+ (let [user-exists (user-exists? t-conn username)
+ schema-exists (schema-exists? t-conn schema-name)
granted-schemas (when user-exists
(schemas-with-user-grants t-conn username))]
(with-open [^Statement stmt (.createStatement ^Connection (:connection t-conn))]
- ;; Only revoke if user exists
(when user-exists
(doseq [schema granted-schemas
:let [quoted-granted-schema (quote-schema schema)]]
@@ -857,17 +1006,11 @@
quoted-granted-schema quoted-user))
(.addBatch ^Statement stmt
^String (format "REVOKE ALL PRIVILEGES ON SCHEMA %s FROM %s"
- quoted-granted-schema quoted-user))
- ;; `grant-workspace-read-access!` issues `ALTER DEFAULT PRIVILEGES IN SCHEMA <s>
- ;; GRANT SELECT ON TABLES TO <iso-user>` on every input schema. Those default-priv
- ;; entries are owned by the granting role (metabase_ci) but reference the iso-user;
- ;; without an explicit REVOKE here, `DROP USER` fails with "cannot be dropped
- ;; because some objects depend on it / privileges for default privileges on new
- ;; relations belonging to user <grantor> in schema <input-schema>".
- (.addBatch ^Statement stmt
- ^String (format "ALTER DEFAULT PRIVILEGES IN SCHEMA %s REVOKE ALL ON TABLES FROM %s"
quoted-granted-schema quoted-user)))
- ;; Only revoke default privileges if both user and schema exist
+ ;; Iso-namespace default-priv was issued by the connection user at init time, so a
+ ;; no-FOR-USER REVOKE is correct here. Guarded on schema existence to avoid
+ ;; erroring on a schema that was dropped manually. Coverage for foreign-grantor
+ ;; default-priv rows is handled above by the per-grantor autocommit loop.
(when schema-exists
(.addBatch ^Statement stmt
^String (format "ALTER DEFAULT PRIVILEGES IN SCHEMA %s REVOKE ALL ON TABLES FROM %s"
diff --git a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj b/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
index d1306149bd2..793540b9583 100644
--- a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
+++ b/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
@@ -5,6 +5,7 @@
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.driver :as driver]
+ [metabase.driver.redshift :as redshift]
[metabase.driver.sql-jdbc :as driver.sql-jdbc]
[metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
@@ -723,3 +724,196 @@
;; None (special role in Postgres to revert back to login role; should not be quoted)
"none" "SET SESSION AUTHORIZATION none;"
"NONE" "SET SESSION AUTHORIZATION NONE;"))))))
+
+;;; ---------------------------------------- Workspace provisioning ----------------------------------------------
+
+(defn- try-execute!
+ "Run `sql` against `spec`, logging exceptions at warn level. For cleanup
+ paths where the object may not exist *or* where a residual catalog row
+ (the very class of bug GHY-3709 covers) might prevent a successful drop.
+ Logging instead of swallowing surfaces orphan-role accumulation on CI."
+ [spec sql]
+ (try (jdbc/execute! spec [sql])
+ (catch Throwable t
+ (log/warnf t "Test cleanup failed: %s" sql))))
+
+(deftest ^:synchronized workspace-precondition-alter-default-privileges-test
+ ;; Redshift mirror of `metabase.driver.postgres-test/workspace-precondition-alter-default-privileges-test`,
+ ;; covering GHY-3709. We simulate the prod failure mode by:
+ ;; - creating a non-superuser "tenant" role,
+ ;; - seeding a schema with a table whose owner is a different role,
+ ;; - connecting as the tenant role and running the pre-flight assert.
+ ;;
+ ;; The assert must throw with status 412, since the tenant role can neither
+ ;; impersonate the foreign owner nor flip to superuser at runtime. Once admin
+ ;; reassigns the table to the tenant role, the assert must pass.
+ ;;
+ ;; Note: Redshift's impersonation graph collapses to "current_user == owner
+ ;; OR current_user is superuser" -- there is no working `pg_has_role(...)`
+ ;; on RA3 clusters. The PG mirror grants role membership instead; here we
+ ;; ALTER OWNER to dodge the missing-overload problem.
+ (mt/test-driver :redshift
+ (let [admin-spec (sql-jdbc.conn/connection-details->spec :redshift (tx/dbdef->connection-details :redshift))
+ suffix (u/lower-case-en (mt/random-name))
+ tenant (str "ws_pre_adp_tenant_" suffix)
+ owner (str "ws_pre_adp_owner_" suffix)
+ schema (str "ws_pre_adp_schema_" suffix)
+ table (str "ws_pre_adp_t_" suffix)
+ password "Pwd_ws_pre_adp_1!"]
+ (try
+ (execute! (str
+ (format "CREATE USER \"%s\" WITH PASSWORD '%s';%n" tenant password)
+ (format "CREATE USER \"%s\" WITH PASSWORD '%s';%n" owner password)
+ (format "CREATE SCHEMA \"%s\";%n" schema)
+ (format "GRANT USAGE ON SCHEMA \"%s\" TO \"%s\";%n" schema tenant)
+ (format "CREATE TABLE \"%s\".\"%s\" (id INTEGER);%n" schema table)
+ ;; Reassign the table to a different role so tenant doesn't own it.
+ (format "ALTER TABLE \"%s\".\"%s\" OWNER TO \"%s\";%n" schema table owner)))
+ (sql-jdbc.conn/with-connection-spec-for-testing-connection
+ [tenant-spec [:redshift (assoc (tx/dbdef->connection-details :redshift)
+ :user tenant
+ :password password)]]
+ (testing "throws when a relation in the input schema is owned by an unmemberable role"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"not a member of \d+ role"
+ (redshift/assert-can-alter-default-privileges! tenant-spec schema))))
+ (testing "passes once the foreign-owned object is reassigned to the tenant"
+ (jdbc/execute! admin-spec
+ [(format "ALTER TABLE \"%s\".\"%s\" OWNER TO \"%s\""
+ schema table tenant)])
+ (is (nil? (redshift/assert-can-alter-default-privileges! tenant-spec schema)))))
+ (finally
+ (try-execute! admin-spec (format "DROP SCHEMA IF EXISTS \"%s\" CASCADE" schema))
+ (try-execute! admin-spec (format "DROP OWNED BY \"%s\"" owner))
+ (try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" tenant))
+ (try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" owner)))))))
+
+(deftest ^:synchronized workspace-precondition-foreign-default-acl-grantor-test
+ ;; The other half of GHY-3709: a `pg_default_acl` row owned by a role the
+ ;; tenant cannot impersonate must be caught at grant time. If we let
+ ;; provisioning through, destroy-time REVOKE has no way to drop that row
+ ;; and `DROP USER` fails -- which is exactly the production error reported
+ ;; on workspace 69.
+ (mt/test-driver :redshift
+ (let [admin-spec (sql-jdbc.conn/connection-details->spec :redshift (tx/dbdef->connection-details :redshift))
+ suffix (u/lower-case-en (mt/random-name))
+ tenant (str "ws_pre_facl_tenant_" suffix)
+ grantor (str "ws_pre_facl_grantor_" suffix)
+ schema (str "ws_pre_facl_schema_" suffix)
+ dummy (str "ws_pre_facl_dummy_" suffix)
+ password "Pwd_ws_pre_facl_1!"]
+ (try
+ (execute! (str
+ (format "CREATE USER \"%s\" WITH PASSWORD '%s';%n" tenant password)
+ (format "CREATE USER \"%s\" WITH PASSWORD '%s' CREATEUSER;%n" grantor password)
+ (format "CREATE USER \"%s\" WITH PASSWORD '%s';%n" dummy password)
+ (format "CREATE SCHEMA \"%s\" AUTHORIZATION \"%s\";%n" schema grantor)
+ (format "GRANT USAGE ON SCHEMA \"%s\" TO \"%s\";%n" schema tenant)))
+ ;; Connect as the foreign grantor to seed a pg_default_acl row owned by them.
+ (sql-jdbc.conn/with-connection-spec-for-testing-connection
+ [grantor-spec [:redshift (assoc (tx/dbdef->connection-details :redshift)
+ :user grantor
+ :password password)]]
+ (jdbc/execute! grantor-spec
+ [(format "ALTER DEFAULT PRIVILEGES IN SCHEMA \"%s\" GRANT SELECT ON TABLES TO \"%s\""
+ schema dummy)]))
+ (sql-jdbc.conn/with-connection-spec-for-testing-connection
+ [tenant-spec [:redshift (assoc (tx/dbdef->connection-details :redshift)
+ :user tenant
+ :password password)]]
+ (testing "throws when the schema carries a pre-existing default-priv row from a foreign grantor"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"not a member of \d+ role"
+ (redshift/assert-can-alter-default-privileges! tenant-spec schema)))))
+ (finally
+ ;; Revoke the seeded default-priv as the grantor (only they can).
+ (sql-jdbc.conn/with-connection-spec-for-testing-connection
+ [grantor-spec [:redshift (assoc (tx/dbdef->connection-details :redshift)
+ :user grantor
+ :password password)]]
+ (try-execute! grantor-spec
+ (format "ALTER DEFAULT PRIVILEGES IN SCHEMA \"%s\" REVOKE ALL ON TABLES FROM \"%s\""
+ schema dummy)))
+ (try-execute! admin-spec (format "DROP SCHEMA IF EXISTS \"%s\" CASCADE" schema))
+ ;; Flush any residual catalog rows referencing these test roles -- the
+ ;; whole point of this test is the case where DROP USER would fail on
+ ;; lingering default-priv entries, so cleanup must be belt-and-
+ ;; suspenders to keep CI re-runs from accumulating orphan roles.
+ (try-execute! admin-spec (format "DROP OWNED BY \"%s\"" grantor))
+ (try-execute! admin-spec (format "DROP OWNED BY \"%s\"" dummy))
+ (try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" tenant))
+ (try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" grantor))
+ (try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" dummy)))))))
+
+(deftest ^:synchronized workspace-destroy-survives-foreign-grantor-default-priv-test
+ ;; GHY-3709 destroy-path integration test (Redshift counterpart to the PG test
+ ;; of the same name). PG sidesteps this via `DROP OWNED BY <iso-user>`, which
+ ;; removes default-priv ACL entries where the iso-user is grantee regardless
+ ;; of grantor. Redshift has no equivalent, so destroy has to enumerate
+ ;; `pg_default_acl` and issue `ALTER DEFAULT PRIVILEGES FOR USER <grantor>
+ ;; REVOKE` per discovered (grantor, schema) pair before `DROP USER`.
+ ;;
+ ;; Repro shape:
+ ;; 1. Provision an iso-user via `init-workspace-isolation!`.
+ ;; 2. Connect as a foreign role (not the current connection user) and
+ ;; `ALTER DEFAULT PRIVILEGES IN SCHEMA <s> GRANT SELECT ON TABLES TO
+ ;; <iso-user>` -- catalog row is owned by that foreign grantor.
+ ;; 3. Run `destroy-workspace-isolation!`. Without the fix, `DROP USER`
+ ;; fails with "user cannot be dropped because some objects depend on
+ ;; it / privileges for default privileges on new relations belonging
+ ;; to user <grantor> in schema <s>". With the fix, destroy enumerates
+ ;; the row, REVOKEs it FOR USER the grantor, and DROP USER succeeds.
+ (mt/test-driver :redshift
+ (let [admin-spec (sql-jdbc.conn/connection-details->spec :redshift (tx/dbdef->connection-details :redshift))
+ suffix (u/lower-case-en (mt/random-name))
+ grantor (str "ws_dest_grantor_" suffix)
+ schema (str "ws_dest_schema_" suffix)
+ password "Pwd_ws_dest_1!"
+ workspace {:id (rand-int Integer/MAX_VALUE)
+ :name (str "wsd-dest-foreign-" suffix)}]
+ (try
+ (execute! (str
+ (format "CREATE USER \"%s\" WITH PASSWORD '%s' CREATEUSER;%n" grantor password)
+ (format "CREATE SCHEMA \"%s\" AUTHORIZATION \"%s\";%n" schema grantor)))
+ (let [init-result (driver/init-workspace-isolation! :redshift (mt/db) workspace)
+ iso-user (-> init-result :database_details :user)
+ workspace+det (merge workspace init-result)]
+ (try
+ ;; Seed the foreign-grantor default-priv: connect as the foreign role
+ ;; and issue ALTER DEFAULT PRIVILEGES so the resulting pg_default_acl
+ ;; row's grantor (defacluser) is the foreign role, not current_user.
+ ;; This is the exact production shape that reproduced GHY-3709.
+ (sql-jdbc.conn/with-connection-spec-for-testing-connection
+ [grantor-spec [:redshift (assoc (tx/dbdef->connection-details :redshift)
+ :user grantor
+ :password password)]]
+ (jdbc/execute! grantor-spec
+ [(format "ALTER DEFAULT PRIVILEGES IN SCHEMA \"%s\" GRANT SELECT ON TABLES TO \"%s\""
+ schema iso-user)]))
+ (testing "destroy completes without error despite foreign-grantor default-priv row"
+ (is (some? (driver/destroy-workspace-isolation! :redshift (mt/db) workspace+det))))
+ (testing "iso-user is gone from pg_user after destroy"
+ (is (empty? (jdbc/query admin-spec ["SELECT 1 FROM pg_user WHERE usename = ?" iso-user]))))
+ (finally
+ ;; Belt-and-suspenders: if destroy raised, the iso-user may still
+ ;; exist with the foreign-grantor row still pinned to it. Revoke
+ ;; as the grantor (only they can drop their own default-priv) and
+ ;; force-drop the iso-user so CI re-runs don't accumulate orphans.
+ (try
+ (sql-jdbc.conn/with-connection-spec-for-testing-connection
+ [grantor-spec [:redshift (assoc (tx/dbdef->connection-details :redshift)
+ :user grantor
+ :password password)]]
+ (try-execute! grantor-spec
+ (format "ALTER DEFAULT PRIVILEGES IN SCHEMA \"%s\" REVOKE ALL ON TABLES FROM \"%s\""
+ schema iso-user)))
+ (catch Throwable t
+ (log/warn t "Test cleanup: connecting as foreign grantor failed")))
+ (try-execute! admin-spec (format "DROP OWNED BY \"%s\"" iso-user))
+ (try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" iso-user)))))
+ (finally
+ (try-execute! admin-spec (format "DROP SCHEMA IF EXISTS \"%s\" CASCADE" schema))
+ (try-execute! admin-spec (format "DROP OWNED BY \"%s\"" grantor))
+ (try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" grantor)))))))
diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.clj
index c2d7747f4b7..d3a61818f20 100644
--- a/test/metabase/driver/postgres_test.clj
+++ b/test/metabase/driver/postgres_test.clj
@@ -2485,3 +2485,63 @@
(jdbc/execute! admin-spec
[(format "GRANT %s TO %s" qowner qrole)])
(is (nil? (postgres/assert-can-alter-default-privileges! user-spec schema))))))))))))))
+
+(deftest ^:synchronized workspace-destroy-survives-foreign-grantor-default-priv-test
+ ;; PostgreSQL counterpart to Redshift's GHY-3709 destroy fix. The Redshift
+ ;; driver had to grow explicit `pg_default_acl` discovery + per-grantor
+ ;; REVOKEs because Redshift's `DROP OWNED BY` semantics differ from PG. PG's
+ ;; destroy issues `DROP OWNED BY <iso-user>` which removes default-priv ACL
+ ;; entries where the iso-user appears as a grantee, regardless of who granted
+ ;; them. This test pins that contract: seed a foreign-grantor default-priv
+ ;; row targeting the iso-user and confirm `destroy-workspace-isolation!`
+ ;; still cleans up without raising "user cannot be dropped because some
+ ;; objects depend on it".
+ (mt/test-driver :postgres
+ (testing "destroy succeeds when a non-current_user grantor seeded a default-priv targeting the iso-user"
+ (mt/with-empty-db
+ (let [admin-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))
+ grantor "ws_destroy_foreign_grantor"
+ schema "ws_destroy_foreign_schema"
+ qgrantor (sql.u/quote-name :postgres :field grantor)
+ qschema (sql.u/quote-name :postgres :schema schema)
+ workspace {:id (rand-int Integer/MAX_VALUE)
+ :name "wsd-foreign-destroy"}]
+ (with-drop-role! admin-spec grantor
+ (with-drop-schema! admin-spec schema
+ (jdbc/execute! admin-spec
+ [(format (str "CREATE ROLE %s WITH LOGIN PASSWORD 'pwd'; "
+ "GRANT %s TO CURRENT_USER; "
+ "CREATE SCHEMA %s AUTHORIZATION %s;")
+ qgrantor qgrantor qschema qgrantor)])
+ (let [init-result (driver/init-workspace-isolation! :postgres (mt/db) workspace)
+ iso-user (-> init-result :database_details :user)
+ qiso (sql.u/quote-name :postgres :field iso-user)
+ workspace+det (merge workspace init-result)]
+ (try
+ ;; Seed the foreign-grantor default-priv: set the grantor role and
+ ;; issue ALTER DEFAULT PRIVILEGES so the resulting pg_default_acl
+ ;; row is owned by the grantor, not by current_user.
+ (jdbc/execute! admin-spec
+ [(format (str "SET ROLE %s; "
+ "ALTER DEFAULT PRIVILEGES IN SCHEMA %s "
+ "GRANT SELECT ON TABLES TO %s; "
+ "RESET ROLE;")
+ qgrantor qschema qiso)])
+ (testing "destroy completes without error"
+ (is (some? (driver/destroy-workspace-isolation! :postgres (mt/db) workspace+det))))
+ (testing "the iso-user has been dropped"
+ (is (empty? (jdbc/query admin-spec
+ ["SELECT 1 FROM pg_roles WHERE rolname = ?" iso-user]))))
+ (finally
+ ;; If destroy raised, the iso-user may still exist -- clean up so the
+ ;; with-drop-role!/with-drop-schema! frames don't fail on the schema.
+ ;; Log instead of swallowing so CI surfaces orphan-role accumulation
+ ;; rather than masking it behind a failed schema drop downstream.
+ (try (jdbc/execute! admin-spec
+ [(format "DROP OWNED BY %s CASCADE" qiso)])
+ (catch Throwable t
+ (log/warnf t "Test cleanup: DROP OWNED BY %s failed" qiso)))
+ (try (jdbc/execute! admin-spec
+ [(format "DROP USER IF EXISTS %s" qiso)])
+ (catch Throwable t
+ (log/warnf t "Test cleanup: DROP USER %s failed" qiso)))))))))))))