diff --git a/CLAUDE.md b/CLAUDE.md index e63db0d..0848140 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,13 +13,17 @@ alone to have picked it up in that case. never hardcodes a schema for any permanent object — the one `CREATE SCHEMA __extension_drop` is transient scaffolding, created and dropped within the same install script, not where anything permanent -lives. Its permanent functions pin their resolution via -`SET search_path FROM CURRENT` at creation time rather than -`@extschema@`-qualifying every reference; either technique gets to the -same schema-independence property. It's genuinely schema-flexible. See -`../ai/CLAUDE.md`'s "Schema-flexibility testing" section for the general -methodology (why `schema=` and not `relocatable=` is what matters, and how -to actually prove search_path-independence). +lives. Every permanent function sets `search_path = pg_catalog, pg_temp` +(so a role with CREATE on the extension's schema can't hijack operators or +functions) and refers to its own objects through `@extension_schema@`, which +the install and update scripts substitute with the quoted schema name. +Registered SQL runs under the event trigger's own pinned +`pg_catalog, pg_temp`, restored after each registration; the extension's +schema and dependency schemas (e.g. cat_tools) are not on that path, so +registered SQL must qualify everything. The extension itself is genuinely +schema-flexible. See `../ai/CLAUDE.md`'s "Schema-flexibility testing" +section for the general methodology (why `schema=` and not `relocatable=` +is what matters, and how to actually prove search_path-independence). `test/install/load.sql` implements this by installing into a freshly created, randomly named schema (a constant, quote-forcing prefix plus a @@ -31,7 +35,10 @@ schema per test-file session (it never adds it to `search_path`, and never assumes a naming convention beyond what it queries from `pg_extension`/`pg_namespace` directly); `test/finish.sql` asserts at the end of every test file that the schema was never reachable via -`search_path` regardless. +`search_path` regardless. It emits one assertion with the same label in +every mode; in existing mode (installed by an external pg_upgrade, placement +not ours to assert) that assertion is `pass()` and checks nothing, so a +single expected output serves all modes. `https://github.com/Postgres-Extensions/pg_count_nulls/pull/55` is the reference this was adapted from (not ported wholesale — see that PR, and diff --git a/HISTORY.asc b/HISTORY.asc index 7e6369e..7a5d458 100644 --- a/HISTORY.asc +++ b/HISTORY.asc @@ -1,11 +1,37 @@ STABLE ------ +== BREAKING: registered SQL now runs with `search_path = pg_catalog, pg_temp` +Existing registrations may break: SQL registered with `extension_drop__add()` +or `extension_drop__update()` can no longer rely on unqualified names. It +must schema-qualify everything it uses (for example cat_tools and +extension_drop's functions), or the `DROP` fails. Re-register (with +`extension_drop__update()`) any SQL that doesn't. See README.md. + == Drop support for PostgreSQL versions before 12 extension_drop depends on cat_tools, which already requires PostgreSQL 12+. A fresh install of extension_drop was already broken below that too (a cat_tools function it calls needs PG11+ internally) -- this just makes the declared floor honest. +== Require USAGE for PUBLIC on the extension's schema +`CREATE EXTENSION` and `ALTER EXTENSION ... UPDATE` now fail unless `PUBLIC` +has USAGE on the schema extension_drop is installed in, and new event +triggers protect that USAGE afterwards. See README.md for details. + +== Run drop commands when `DROP SCHEMA ... CASCADE` or `DROP OWNED BY` drops an extension +The event trigger now fires for `DROP SCHEMA` and `DROP OWNED` as well as +`DROP EXTENSION`. Previously the other two commands left a stale registration +that made every later `DROP EXTENSION` fail with `XD001`; remove any with +`extension_drop__repair()`. Any role that can drop an extension can do so +without privileges on extension_drop's table; the registered SQL runs as that +role. +`extension_drop__sanity_assert()` now runs inside `_extension_drop__dropping()`, +before the registered SQL. See README.md. + +== Fix `extension_drop__update()` and `extension_drop__remove()` with several registrations +With more than one extension registered, they changed every registration +instead of only the named one. + == Remove redundant client_min_messages handling from install script `CREATE EXTENSION` already raises `client_min_messages` to `WARNING` for the install script (only-raising, so a stricter caller is respected) and diff --git a/README.md b/README.md index 13aecec..91ae482 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,37 @@ # extension_drop -Run custom commands when an extension is dropped. By default, `DROP -EXTENSION` simply drops all the objects the extension owns; this lets you -register additional SQL to run when a given extension is dropped. +Register SQL that runs when a given extension is dropped, whether by `DROP +EXTENSION`, `DROP SCHEMA ... CASCADE` or `DROP OWNED BY`. The registration is +removed with the extension. Requires [cat_tools](https://pgxn.org/dist/cat_tools/) >= 0.3.0. +`PUBLIC` must have USAGE on the schema extension_drop is installed in. The +event trigger runs as whichever role drops an extension, and calls +`_extension_drop__dropping()` in that schema. The leading underscore marks +it as internal, not for external callers (the extension has no internal +schema); it is documented under [How it works](#how-it-works). + +`CREATE EXTENSION` and `ALTER EXTENSION ... UPDATE` fail unless `PUBLIC` has +USAGE. The error's HINT gives the exact `GRANT USAGE ON SCHEMA ... TO PUBLIC` +to run first. + +Two event triggers on `REVOKE` and `DROP OWNED` protect it afterwards: + +- `extension_drop__usage_guard` (`ddl_command_end`) fails any command that + would remove USAGE, and the command has no effect. +- `extension_drop__usage_guard_start` (`ddl_command_start`) fails any such + command while `PUBLIC` already lacks USAGE. That happens if a superuser + bypassed the triggers, they were disabled or dropped, or the ACL arrived + through a restore. + +Only the `extension_drop__usage_guard_start` error has the `GRANT` HINT for +recovering; run it. + +Granting USAGE to `PUBLIC` also exposes every other object in that schema +that has `PUBLIC` privileges (functions are executable by `PUBLIC` by +default), so be careful about what schema you install it to. + ## Functions None of these are granted to `PUBLIC` except where noted, since @@ -13,10 +39,13 @@ None of these are granted to `PUBLIC` except where noted, since arbitrary SQL to run later. Grant them to specific roles as needed. - `extension_drop__add(extension_name name, sql text) RETURNS void` - Register `sql` to run when `extension_name` is dropped. + Register `sql` to run when `extension_name` is dropped. `sql` runs with + `search_path = pg_catalog, pg_temp`: schema-qualify everything it uses (see + [How it works](#how-it-works)). - `extension_drop__update(extension_name name, sql text) RETURNS void` - Replace the SQL registered for `extension_name`. + Replace the SQL registered for `extension_name`. The same `search_path` + rule applies. - `extension_drop__remove(extension_name name) RETURNS void` Remove the SQL registered for `extension_name`. @@ -34,6 +63,8 @@ arbitrary SQL to run later. Grant them to specific roles as needed. - `extension_drop__sanity_assert(ignore name DEFAULT NULL) RETURNS void` Raises an error if `extension_drop__sanity_check()` (called with the same `ignore` argument) isn't empty. Granted to `PUBLIC` by default. + `_extension_drop__dropping` calls it, as its owner, so it runs with the + owner's rights. - `extension_drop__repair() RETURNS void` Deletes any stale rows found by `extension_drop__sanity_check()`. This @@ -42,6 +73,120 @@ arbitrary SQL to run later. Grant them to specific roles as needed. ## How it works An event trigger (`extension_drop`, on `sql_drop`) fires whenever an -extension is dropped, runs any SQL registered for it via -`extension_drop__add`/`extension_drop__update`, and removes the registration -afterward. +extension is dropped -- by `DROP EXTENSION`, `DROP SCHEMA ... CASCADE` or +`DROP OWNED BY` -- removes its registration from `extension_drop__commands` +and runs the SQL registered for it via +`extension_drop__add`/`extension_drop__update`. Those commands fire the +trigger for every drop, but it returns immediately unless an extension is +among the dropped objects. + +Every extension_drop function pins `search_path = pg_catalog, pg_temp`, and +so does the registered SQL: it runs, as the dropping role, under the event +trigger's own pinned path. **Registered SQL must schema-qualify everything it +uses**: tables and functions in any schema (including cat_tools and +extension_drop's own functions). extension_drop's schema is whatever it was +installed into, so when registering, look it up and interpolate it with `%s` +(not `%I`: `regnamespace` output is already quoted): + + SELECT extension_drop__add('my_extension', + format('SELECT %s.extension_drop__get(%L)', + extnamespace::regnamespace, 'my_extension')) + FROM pg_extension WHERE extname = 'extension_drop'; + +Nothing but `pg_catalog` and `pg_temp` is on the registered SQL's path, so a +role with CREATE on any schema can't plant objects that it resolves. +Registered SQL runs in no particular order when one command drops several +extensions. + +Dropping an extension, registered or not, needs no privileges on +`extension_drop__commands`; the trigger gets the registered SQL from +`_extension_drop__dropping()`, which deletes the registration with its owner's +rights. The SQL itself runs as the dropping role, which may need further +privileges. A stale registration still fails the drop with `XD001`. + +`_extension_drop__dropping() RETURNS TABLE(extension_name name, sql text)` is +internal; only the event trigger can use it. It deletes the registrations of +the extensions being dropped and returns them, in no particular order, and +errors when called outside a `sql_drop` trigger, so a direct call can't remove +the registration of a live extension. It is `SECURITY DEFINER` (with +`search_path = pg_catalog, pg_temp` and schema-qualified references), runs +`extension_drop__sanity_assert()` as its owner after the delete, and never +executes the SQL. Granted to `PUBLIC`. Its owner is the role that ran +`CREATE EXTENSION` (or the `ALTER EXTENSION ... UPDATE` that first created +it). + +## Known issues + +Restoring a `pg_dump` of a database that uses extension_drop has two +problems, tracked in +[#56](https://github.com/Postgres-Extensions/extension_tools/issues/56). The +commands below name the schema `xd` and the target database `newdb`; change +them to match (`xd` also appears inside the `grep` and `sed` patterns). +Schema names that need quoting are untested: `pg_restore -l` prints them +unquoted, but the `sed` pattern and the `GRANT` need them quoted. + +### Restore into a schema other than `public` fails + +**Create the schema and grant `USAGE` to `PUBLIC` before restoring the +rest.** Otherwise `CREATE EXTENSION` fails with `cannot install +extension_drop in schema "xd"`: pg_dump writes the `GRANT` only after all +extensions are created, and `pg_dump -x` never writes it. Installs into +`public` are not affected. Pre-creating the schema and then restoring the whole +dump only works without `-1`, and logs `schema "xd" already exists`. + +Use this for `pg_restore`; it leaves out the commands data, so re-register +what is missing afterwards, as +[the next issue](#restore-fails-with-a-duplicate-key-on-extension_drop__commands) +describes: + + pg_restore -l db.dump > all.list + grep -E '^[0-9]+; [0-9]+ [0-9]+ SCHEMA - xd ' all.list > schema.list + grep -v -E '^[0-9]+; [0-9]+ [0-9]+ SCHEMA - xd |TABLE DATA xd extension_drop__commands ' \ + all.list > rest.list + pg_restore -1 -L schema.list -d newdb db.dump + psql -d newdb -c 'GRANT USAGE ON SCHEMA xd TO PUBLIC' + pg_restore -1 -L rest.list -d newdb db.dump + +The last command also works with `-j 2` in place of `-1`, or with neither. + +Use this for a plain SQL dump made without `--inserts`; it also leaves out +the commands data, so re-register afterwards: + + psql -d newdb -c 'CREATE SCHEMA xd; GRANT USAGE ON SCHEMA xd TO PUBLIC' + sed '/^CREATE SCHEMA xd;$/d' db.sql \ + | awk '/^COPY .*extension_drop__commands/{s=1} + !s{print} + s&&/^\\\.$/{s=0}' \ + | psql -1 -v ON_ERROR_STOP=1 -d newdb + +### Restore fails with a duplicate key on `extension_drop__commands` + +For a schema other than `public`, use the recipes under +[Restore into a schema other than `public` fails](#restore-into-a-schema-other-than-public-fails), +which already leave this data out. The recipes below apply when extension_drop +is in `public`; replace `xd` with `public` in them. + +**Leave the data of `extension_drop__commands` out of the restore, then +re-register what your extensions' install scripts don't register.** When an +extension registers drop SQL in its install script, `CREATE EXTENSION` +re-registers it during the restore and the dump's `COPY` then inserts the same +row, failing with `duplicate key value violates unique constraint +"extension_drop__commands_pkey"`. The failed `COPY` inserts none of its rows, +so a restore that continues past it (`psql -f`, `pg_restore` without `-1`, with +or without `-j`) also loses registrations made by direct +`extension_drop__add()` calls. A `-1` restore, or `psql -1`, aborts and +restores nothing. + +List the registrations in the source database before dumping, to know which +ones to re-register: + + SELECT * FROM xd.extension_drop__commands; + +Leave the data out when dumping (the pattern must be schema-qualified; an +unqualified name silently excludes nothing): + + pg_dump -Fc --exclude-table-data='xd.extension_drop__commands' -f db.dump db + +Then, for each registration the restored database lacks: + + SELECT xd.extension_drop__add('my_extension', 'SELECT 1'); diff --git a/sql/extension_drop--0.1.1--stable.sql b/sql/extension_drop--0.1.1--stable.sql index b011c62..b6d035c 100644 --- a/sql/extension_drop--0.1.1--stable.sql +++ b/sql/extension_drop--0.1.1--stable.sql @@ -1,28 +1,432 @@ -CREATE OR REPLACE FUNCTION extension_drop__event_trigger( -) RETURNS event_trigger LANGUAGE plpgsql SET search_path FROM CURRENT AS +/* + * Every function is re-created: every body changed, and each one's pinned search_path goes from + * , cat_tools, pg_temp to pg_catalog, pg_temp. The calls below are the same as in extension_drop.sql. + */ +DO $do$ +DECLARE + ns oid := (SELECT e.extnamespace FROM pg_catalog.pg_extension e WHERE e.extname = 'extension_drop'); + nsname name := (SELECT n.nspname FROM pg_catalog.pg_namespace n WHERE n.oid = ns); + ext_schema text := pg_catalog.quote_ident(nsname); +BEGIN + IF NOT pg_catalog.has_schema_privilege('public', ns, 'USAGE') THEN + RAISE EXCEPTION 'cannot update extension_drop in schema "%"', pg_catalog.replace(nsname, '"', '""') + USING ERRCODE = 'object_not_in_prerequisite_state' + , DETAIL = 'extension_drop requires PUBLIC to have USAGE on the schema it is installed in.' + , HINT = pg_catalog.format( + 'Run GRANT USAGE ON SCHEMA %s TO PUBLIC (creating the schema first if needed), then retry.' + , ext_schema + ); + END IF; +END +$do$; + +/* + * NOTE: All pg_temp objects must be dropped at the end of the script! + * Otherwise the eventual DROP CASCADE of pg_temp when the session ends will + * also drop the extension! Instead of risking problems, create our own + * "temporary" schema instead. + */ +CREATE SCHEMA __extension_drop; + +CREATE FUNCTION __extension_drop.exec( + sql text +) RETURNS void LANGUAGE plpgsql AS $body$ +BEGIN + RAISE DEBUG 'sql = %', sql; + EXECUTE sql; +END +$body$; + +CREATE FUNCTION __extension_drop.create_function( + function_name text + , args text + , options text + , body text + , comment text + , grants text DEFAULT NULL +) RETURNS void LANGUAGE plpgsql AS $body$ +DECLARE + c_clean_args text := cat_tools.routine__parse_arg_types_text(args); + + ext_schema text := COALESCE( + ( + SELECT pg_catalog.quote_ident(n.nspname) + FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace + WHERE e.extname = 'extension_drop' + ) + -- Not running as an extension script (e.g. the build smoke test) + , pg_catalog.quote_ident(pg_catalog.current_schema()) + ); + + /* + * Every permanent function is pinned to pg_catalog, pg_temp so nothing a caller can create in a schema + * they control is ever resolved. Bodies refer to our own objects through @extension_schema@. + */ + create_template CONSTANT text := $template$ +CREATE OR REPLACE FUNCTION %s( +%s +) RETURNS %s SET search_path = pg_catalog, pg_temp AS +%L +$template$ + ; + + revoke_template CONSTANT text := $template$ +REVOKE ALL ON FUNCTION %s( +%s +) FROM public; +$template$ + ; + + grant_template CONSTANT text := $template$ +GRANT EXECUTE ON FUNCTION %s( +%s +) TO %s; +$template$ + ; + + comment_template CONSTANT text := $template$ +COMMENT ON FUNCTION %s( +%s +) IS %L; +$template$ + ; + +BEGIN + PERFORM __extension_drop.exec( format( + create_template + , function_name + , args + , options + , pg_catalog.replace(body, '@extension_schema@', ext_schema) + ) ) + ; + + IF grants IS NOT NULL THEN + PERFORM __extension_drop.exec( format( + revoke_template + , function_name + , c_clean_args + ) ) + ; + IF grants <> '' THEN + PERFORM __extension_drop.exec( format( + grant_template + , function_name + , c_clean_args + , grants + ) ) + ; + END IF; + END IF; + + IF comment IS NOT NULL THEN + PERFORM __extension_drop.exec( format( + comment_template + , function_name + , c_clean_args + , comment + ) ) + ; + END IF; +END +$body$; + +/* + * ============================================================================ + * WARNING: DEFINER-SAFE CODE ONLY + * + * This function runs with its OWNER's rights whenever _extension_drop__dropping() + * (SECURITY DEFINER) calls it through extension_drop__sanity_assert(). + * Keep it definer-safe: + * + * - pinned search_path (done by create_function); every reference to our objects goes through + * @extension_schema@ + * - no dynamic SQL, and the only argument is compared against data, never interpolated + * - it only reads + * ============================================================================ + */ +SELECT __extension_drop.create_function( + 'extension_drop__sanity_check' + , 'ignore name DEFAULT NULL' + , 'name[] LANGUAGE sql STABLE' + , $body$ +SELECT array( + SELECT extension_name + FROM @extension_schema@.extension_drop__commands c + WHERE NOT EXISTS(SELECT 1 FROM pg_extension e WHERE e.extname = c.extension_name) + AND extension_name IS DISTINCT FROM ignore + ) +$body$ + , $$Returns an array of extensions that have drop commands but do not exist. This array should always be empty!$$ +); + +/* + * ============================================================================ + * WARNING: DEFINER-SAFE CODE ONLY + * + * This function runs with its OWNER's rights whenever _extension_drop__dropping() + * (SECURITY DEFINER) calls it. Keep it definer-safe: + * + * - pinned search_path (done by create_function); every reference to our objects goes through + * @extension_schema@ + * - no dynamic SQL; the only argument reaches sanity_check as a comparison value + * - the only text it raises is built from table contents, which are data, never executed + * ============================================================================ + */ +SELECT __extension_drop.create_function( + 'extension_drop__sanity_assert' + , 'ignore name DEFAULT NULL' + , 'void LANGUAGE plpgsql STABLE' + , $body$ +DECLARE + bad name[] := @extension_schema@.extension_drop__sanity_check(ignore); +BEGIN + IF array_length(bad, 1) IS NOT NULL THEN + RAISE EXCEPTION 'unexpected drop commands' USING ERRCODE = 'XD001' + , DETAIL = format( + '%s not exist: %s' + , CASE WHEN array_length(bad, 1) = 1 THEN 'This extension does' ELSE 'These extensions do' END + , array_to_string(bad, ', ') + ) + , HINT = $$This should not happen unless someone manually inserted into "extension_drop__commands" or messed with the "extension_drop" event trigger. + Use SELECT extension_drop__repair() to fix this.$$ + ; + END IF; +END +$body$ + , $$Throws an error if the "extension_drop__commands" table is not in a sane state.$$ +); + +/* + * REPAIR + */ +SELECT __extension_drop.create_function( + 'extension_drop__repair' + , '' + , 'void LANGUAGE sql' + , $body$ +DELETE FROM @extension_schema@.extension_drop__commands + WHERE extension_name = ANY( @extension_schema@.extension_drop__sanity_check() ) +$body$ + , 'Repairs the "extension_drop__commands" table. THIS FUNCTION SHOULD NEVER BE NEEDED.' + , '' -- Just revoke all access +); + +/* + * GET + */ +SELECT __extension_drop.create_function( + 'extension_drop__get' + , $$ + extension_name extension_drop__commands.extension_name%TYPE +$$ + , 'extension_drop__commands STABLE LANGUAGE plpgsql' + , $body$ +DECLARE + ret @extension_schema@.extension_drop__commands; +BEGIN + PERFORM @extension_schema@.extension_drop__sanity_assert(NULL::name); + SELECT INTO STRICT ret + * + FROM @extension_schema@.extension_drop__commands d + WHERE d.extension_name = extension_drop__get.extension_name + ; + + RETURN ret; + +EXCEPTION WHEN no_data_found THEN + RAISE 'no drop commands for extension "%"', extension_name + USING errcode = 'no_data_found' + ; +END +$body$ + , $$Get info about a set of commands to be run when an extension is dropped.$$ +); + +/* + * ADD + */ +SELECT __extension_drop.create_function( + 'extension_drop__add' + , $$ + extension_name extension_drop__commands.extension_name%TYPE + , sql extension_drop__commands.sql%TYPE +$$ + , 'void LANGUAGE plpgsql' + , $body$ +BEGIN + INSERT INTO @extension_schema@.extension_drop__commands VALUES(extension_name, sql); + PERFORM @extension_schema@.extension_drop__sanity_assert(NULL::name); +END $body$ + , $$Adds a set of commands to be run when an extension is dropped. The sql runs with search_path = pg_catalog, pg_temp: schema-qualify everything it uses.$$ + , '' -- Just revoke all access +); + +/* + * REMOVE + */ +SELECT __extension_drop.create_function( + 'extension_drop__remove' + , $$ + extension_name extension_drop__commands.extension_name%TYPE +$$ + , 'void LANGUAGE sql' + , $body$ +DELETE FROM @extension_schema@.extension_drop__commands d + -- extension_drop__get() runs sanity checks for us + WHERE d.extension_name = (@extension_schema@.extension_drop__get(extension_drop__remove.extension_name)).extension_name +$body$ + , $$Remove a set of commands to be run when an extension is dropped.$$ + , '' -- Just revoke all access +); + +/* + * UPDATE + */ +SELECT __extension_drop.create_function( + 'extension_drop__update' + , $$ + extension_name extension_drop__commands.extension_name%TYPE + , sql extension_drop__commands.sql%TYPE +$$ + , 'void LANGUAGE sql' + , $body$ +UPDATE @extension_schema@.extension_drop__commands d + SET sql = extension_drop__update.sql + -- extension_drop__get() runs sanity checks for us + WHERE d.extension_name = (@extension_schema@.extension_drop__get(extension_drop__update.extension_name)).extension_name +$body$ + , $$Update the set of commands to be run when an extension is dropped. The sql runs with search_path = pg_catalog, pg_temp: schema-qualify everything it uses.$$ + , '' -- Just revoke all access +); + +/* + * DROPPING: SECURITY DEFINER so a role that can drop an extension needs no privileges on + * extension_drop__commands. It only deletes and returns the registrations of extensions the current + * sql_drop command is dropping (outside a sql_drop trigger pg_event_trigger_dropped_objects() errors, so + * a direct call deletes nothing), then runs sanity_assert as the owner. It never runs the returned SQL: + * the event trigger does that as the dropping role. + */ +SELECT __extension_drop.create_function( + '_extension_drop__dropping' + , '' + , 'TABLE(extension_name name, sql text) LANGUAGE plpgsql SECURITY DEFINER' + , $body$ +BEGIN + RETURN QUERY + DELETE FROM @extension_schema@.extension_drop__commands c + USING pg_event_trigger_dropped_objects() d + WHERE c.extension_name = d.object_name AND d.object_type = 'extension' + RETURNING c.extension_name, c.sql + ; + + PERFORM @extension_schema@.extension_drop__sanity_assert(NULL::name); +END +$body$ + , $$Deletes and returns the registrations (extension_name, sql) of the extensions being dropped, after asserting the table is sane. Only works inside the extension_drop event trigger.$$ + , 'public' +); + +/* + * TRIGGER FUNCTION + */ +SELECT __extension_drop.create_function( + 'extension_drop__event_trigger' + , '' + , 'event_trigger LANGUAGE plpgsql' + , $body$ DECLARE - r extension_drop__commands; + r record; + saved_path text := current_setting('search_path'); BEGIN RAISE DEBUG 'extension_drop event trigger entry: tg_event %, tg_tag %', tg_event, tg_tag; - FOR r IN - SELECT c.* - FROM extension_drop__commands c - JOIN pg_event_trigger_dropped_objects() d - ON c.extension_name = d.object_name - AND d.object_type = 'extension' - LOOP + + -- Most drops involve no extension; don't call the dropping function (and its assert) for them. + IF NOT EXISTS (SELECT 1 FROM pg_event_trigger_dropped_objects() WHERE object_type = 'extension') THEN + RETURN; + END IF; + + FOR r IN SELECT * FROM @extension_schema@._extension_drop__dropping() LOOP RAISE DEBUG E'extension "%" is being dropped; executing SQL:\n%', r.extension_name, r.sql; EXECUTE r.sql; - DELETE FROM extension_drop__commands WHERE extension_name = r.extension_name; + -- Registered SQL may change search_path; don't let it leak into the next registration + PERFORM pg_catalog.set_config('search_path', saved_path, true); END LOOP; +END +$body$ + , 'Event trigger function that does the actual work for extension_drop.' +); - /* - * Need to do this after the fact since the extensions being dropped have - * already been removed from the catalog by the time this function is called. - */ - PERFORM extension_drop__sanity_assert(); +-- ALTER EVENT TRIGGER can't change WHEN +DROP EVENT TRIGGER extension_drop; +CREATE EVENT TRIGGER extension_drop + ON sql_drop + -- DROP SCHEMA CASCADE and DROP OWNED BY also drop extensions. + WHEN tag IN( 'DROP EXTENSION', 'DROP SCHEMA', 'DROP OWNED' ) -- NOTE! This MUST be IN + EXECUTE PROCEDURE extension_drop__event_trigger() +; + +/* + * USAGE GUARD: the start trigger refuses any REVOKE / DROP OWNED while PUBLIC already lacks USAGE (the + * only error that gives the GRANT); the end trigger refuses a command that just removed it. + */ +SELECT __extension_drop.create_function( + 'extension_drop__usage_guard' + , '' + , 'event_trigger LANGUAGE plpgsql' + , $body$ +DECLARE + ns oid := (SELECT e.extnamespace FROM pg_extension e WHERE e.extname = 'extension_drop'); + nsname text; + detail text := 'extension_drop requires PUBLIC to have USAGE on the schema it is installed in. DDL command: ' || tg_tag; +BEGIN + -- Not installed any more (e.g. DROP OWNED dropped it): nothing to protect. + IF ns IS NOT NULL AND NOT has_schema_privilege('public', ns, 'USAGE') THEN + nsname := (SELECT n.nspname FROM pg_namespace n WHERE n.oid = ns); + IF tg_event = 'ddl_command_start' THEN + RAISE EXCEPTION 'PUBLIC lacks USAGE on schema "%"', replace(nsname, '"', '""') + USING ERRCODE = 'object_not_in_prerequisite_state' + , DETAIL = detail + , HINT = format('Run GRANT USAGE ON SCHEMA %s TO PUBLIC.', quote_ident(nsname)) + ; + END IF; + RAISE EXCEPTION 'cannot remove USAGE on schema "%" from PUBLIC', replace(nsname, '"', '""') + USING ERRCODE = 'object_not_in_prerequisite_state' + , DETAIL = detail + ; + END IF; END -$body$; +$body$ + , 'Event trigger function that stops PUBLIC losing USAGE on the schema extension_drop is installed in.' +); + +CREATE EVENT TRIGGER extension_drop__usage_guard_start + ON ddl_command_start + WHEN tag IN( 'REVOKE', 'DROP OWNED' ) -- NOTE! This MUST be IN + EXECUTE PROCEDURE extension_drop__usage_guard() +; + +CREATE EVENT TRIGGER extension_drop__usage_guard + ON ddl_command_end + WHEN tag IN( 'REVOKE', 'DROP OWNED' ) -- NOTE! This MUST be IN + EXECUTE PROCEDURE extension_drop__usage_guard() +; + +/* + * Drop "temporary" objects + */ +DROP FUNCTION __extension_drop.create_function( + function_name text + , args text + , options text + , body text + , comment text + , grants text +); +DROP FUNCTION __extension_drop.exec( + sql text +); +DROP SCHEMA __extension_drop; -- vim: sw=2 ts=2 expandtab diff --git a/sql/extension_drop.sql b/sql/extension_drop.sql index 75319be..4229790 100644 --- a/sql/extension_drop.sql +++ b/sql/extension_drop.sql @@ -37,10 +37,24 @@ CREATE FUNCTION __extension_drop.create_function( DECLARE c_clean_args text := cat_tools.routine__parse_arg_types_text(args); + ext_schema text := COALESCE( + ( + SELECT pg_catalog.quote_ident(n.nspname) + FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace + WHERE e.extname = 'extension_drop' + ) + -- Not running as an extension script (e.g. the build smoke test) + , pg_catalog.quote_ident(pg_catalog.current_schema()) + ); + + /* + * Every permanent function is pinned to pg_catalog, pg_temp so nothing a caller can create in a schema + * they control is ever resolved. Bodies refer to our own objects through @extension_schema@. + */ create_template CONSTANT text := $template$ CREATE OR REPLACE FUNCTION %s( %s -) RETURNS %s SET search_path FROM CURRENT AS +) RETURNS %s SET search_path = pg_catalog, pg_temp AS %L $template$ ; @@ -71,8 +85,8 @@ BEGIN create_template , function_name , args - , options -- TODO: Force search_path if options ~* 'definer' - , body + , options + , pg_catalog.replace(body, '@extension_schema@', ext_schema) ) ) ; @@ -106,12 +120,51 @@ BEGIN END $body$; +/* + * Fail now rather than leave an install that can't drop extensions: the event trigger calls + * _extension_drop__dropping() as the dropping role, which needs USAGE on our schema. + */ +DO $do$ +DECLARE + ns oid := COALESCE( + (SELECT e.extnamespace FROM pg_catalog.pg_extension e WHERE e.extname = 'extension_drop') + -- Not running as an extension script (e.g. the build smoke test) + , (SELECT n.oid FROM pg_catalog.pg_namespace n WHERE n.nspname = pg_catalog.current_schema()) + ); + nsname name := (SELECT n.nspname FROM pg_catalog.pg_namespace n WHERE n.oid = ns); +BEGIN + IF NOT pg_catalog.has_schema_privilege('public', ns, 'USAGE') THEN + RAISE EXCEPTION 'cannot install extension_drop in schema "%"', pg_catalog.replace(nsname, '"', '""') + USING ERRCODE = 'object_not_in_prerequisite_state' + , DETAIL = 'extension_drop requires PUBLIC to have USAGE on the schema it is installed in.' + , HINT = pg_catalog.format( + 'Run GRANT USAGE ON SCHEMA %s TO PUBLIC (creating the schema first if needed), then retry.' + , pg_catalog.quote_ident(nsname) + ); + END IF; +END +$do$; + CREATE TABLE extension_drop__commands( extension_name name PRIMARY KEY , sql text NOT NULL ); SELECT __extension_drop.safe_dump('extension_drop__commands', ''); +/* + * ============================================================================ + * WARNING: DEFINER-SAFE CODE ONLY + * + * This function runs with its OWNER's rights whenever _extension_drop__dropping() + * (SECURITY DEFINER) calls it through extension_drop__sanity_assert(). + * Keep it definer-safe: + * + * - pinned search_path (done by create_function); every reference to our objects goes through + * @extension_schema@ + * - no dynamic SQL, and the only argument is compared against data, never interpolated + * - it only reads + * ============================================================================ + */ SELECT __extension_drop.create_function( 'extension_drop__sanity_check' , 'ignore name DEFAULT NULL' @@ -119,33 +172,45 @@ SELECT __extension_drop.create_function( , $body$ SELECT array( SELECT extension_name - FROM extension_drop__commands c - WHERE NOT EXISTS(SELECT 1 FROM pg_catalog.pg_extension e WHERE e.extname = c.extension_name) + FROM @extension_schema@.extension_drop__commands c + WHERE NOT EXISTS(SELECT 1 FROM pg_extension e WHERE e.extname = c.extension_name) AND extension_name IS DISTINCT FROM ignore ) $body$ , $$Returns an array of extensions that have drop commands but do not exist. This array should always be empty!$$ ); +/* + * ============================================================================ + * WARNING: DEFINER-SAFE CODE ONLY + * + * This function runs with its OWNER's rights whenever _extension_drop__dropping() + * (SECURITY DEFINER) calls it. Keep it definer-safe: + * + * - pinned search_path (done by create_function); every reference to our objects goes through + * @extension_schema@ + * - no dynamic SQL; the only argument reaches sanity_check as a comparison value + * - the only text it raises is built from table contents, which are data, never executed + * ============================================================================ + */ SELECT __extension_drop.create_function( 'extension_drop__sanity_assert' , 'ignore name DEFAULT NULL' , 'void LANGUAGE plpgsql STABLE' , $body$ DECLARE - bad name[] := extension_drop__sanity_check(ignore); + bad name[] := @extension_schema@.extension_drop__sanity_check(ignore); BEGIN - IF bad != '{}'::name[] THEN - RAISE 'unexpected drop commands' - USING ERRCODE = 'XD001' - , HINT = $$This should not happen unless someone manually inserted into "extension_drop__commands" or messed with the "extension_drop" event trigger. + IF array_length(bad, 1) IS NOT NULL THEN + RAISE EXCEPTION 'unexpected drop commands' USING ERRCODE = 'XD001' + , DETAIL = format( + '%s not exist: %s' + , CASE WHEN array_length(bad, 1) = 1 THEN 'This extension does' ELSE 'These extensions do' END + , array_to_string(bad, ', ') + ) + , HINT = $$This should not happen unless someone manually inserted into "extension_drop__commands" or messed with the "extension_drop" event trigger. Use SELECT extension_drop__repair() to fix this.$$ - , DETAIL = format( - '%s not exist: %s' - , CASE WHEN array_length(bad, 1) = 1 THEN 'This extension does' ELSE 'These extensions do' END - , array_to_string(bad, ', ') - ) - ; + ; END IF; END $body$ @@ -160,7 +225,8 @@ SELECT __extension_drop.create_function( , '' , 'void LANGUAGE sql' , $body$ -DELETE FROM extension_drop__commands WHERE extension_name = ANY( extension_drop__sanity_check() ) +DELETE FROM @extension_schema@.extension_drop__commands + WHERE extension_name = ANY( @extension_schema@.extension_drop__sanity_check() ) $body$ , 'Repairs the "extension_drop__commands" table. THIS FUNCTION SHOULD NEVER BE NEEDED.' , '' -- Just revoke all access @@ -177,12 +243,12 @@ $$ , 'extension_drop__commands STABLE LANGUAGE plpgsql' , $body$ DECLARE - ret extension_drop__commands; + ret @extension_schema@.extension_drop__commands; BEGIN - PERFORM extension_drop__sanity_assert(); + PERFORM @extension_schema@.extension_drop__sanity_assert(NULL::name); SELECT INTO STRICT ret * - FROM extension_drop__commands d + FROM @extension_schema@.extension_drop__commands d WHERE d.extension_name = extension_drop__get.extension_name ; @@ -209,11 +275,11 @@ $$ , 'void LANGUAGE plpgsql' , $body$ BEGIN - INSERT INTO extension_drop__commands VALUES(extension_name, sql); - PERFORM extension_drop__sanity_assert(); + INSERT INTO @extension_schema@.extension_drop__commands VALUES(extension_name, sql); + PERFORM @extension_schema@.extension_drop__sanity_assert(NULL::name); END $body$ - , $$Adds a set of commands to be run when an extension is dropped.$$ + , $$Adds a set of commands to be run when an extension is dropped. The sql runs with search_path = pg_catalog, pg_temp: schema-qualify everything it uses.$$ , '' -- Just revoke all access ); @@ -227,9 +293,9 @@ SELECT __extension_drop.create_function( $$ , 'void LANGUAGE sql' , $body$ -DELETE FROM extension_drop__commands d +DELETE FROM @extension_schema@.extension_drop__commands d -- extension_drop__get() runs sanity checks for us - WHERE d.extension_name = (extension_drop__get(extension_name)).extension_name + WHERE d.extension_name = (@extension_schema@.extension_drop__get(extension_drop__remove.extension_name)).extension_name $body$ , $$Remove a set of commands to be run when an extension is dropped.$$ , '' -- Just revoke all access @@ -246,15 +312,42 @@ SELECT __extension_drop.create_function( $$ , 'void LANGUAGE sql' , $body$ -UPDATE extension_drop__commands d +UPDATE @extension_schema@.extension_drop__commands d SET sql = extension_drop__update.sql -- extension_drop__get() runs sanity checks for us - WHERE d.extension_name = (extension_drop__get(extension_name)).extension_name + WHERE d.extension_name = (@extension_schema@.extension_drop__get(extension_drop__update.extension_name)).extension_name $body$ - , $$Update the set of commands to be run when an extension is dropped.$$ + , $$Update the set of commands to be run when an extension is dropped. The sql runs with search_path = pg_catalog, pg_temp: schema-qualify everything it uses.$$ , '' -- Just revoke all access ); +/* + * DROPPING: SECURITY DEFINER so a role that can drop an extension needs no privileges on + * extension_drop__commands. It only deletes and returns the registrations of extensions the current + * sql_drop command is dropping (outside a sql_drop trigger pg_event_trigger_dropped_objects() errors, so + * a direct call deletes nothing), then runs sanity_assert as the owner. It never runs the returned SQL: + * the event trigger does that as the dropping role. + */ +SELECT __extension_drop.create_function( + '_extension_drop__dropping' + , '' + , 'TABLE(extension_name name, sql text) LANGUAGE plpgsql SECURITY DEFINER' + , $body$ +BEGIN + RETURN QUERY + DELETE FROM @extension_schema@.extension_drop__commands c + USING pg_event_trigger_dropped_objects() d + WHERE c.extension_name = d.object_name AND d.object_type = 'extension' + RETURNING c.extension_name, c.sql + ; + + PERFORM @extension_schema@.extension_drop__sanity_assert(NULL::name); +END +$body$ + , $$Deletes and returns the registrations (extension_name, sql) of the extensions being dropped, after asserting the table is sane. Only works inside the extension_drop event trigger.$$ + , 'public' +); + /* * TRIGGER FUNCTION */ @@ -264,26 +357,22 @@ SELECT __extension_drop.create_function( , 'event_trigger LANGUAGE plpgsql' , $body$ DECLARE - r extension_drop__commands; + r record; + saved_path text := current_setting('search_path'); BEGIN RAISE DEBUG 'extension_drop event trigger entry: tg_event %, tg_tag %', tg_event, tg_tag; - FOR r IN - SELECT c.* - FROM extension_drop__commands c - JOIN pg_event_trigger_dropped_objects() d - ON c.extension_name = d.object_name - AND d.object_type = 'extension' - LOOP + + -- Most drops involve no extension; don't call the dropping function (and its assert) for them. + IF NOT EXISTS (SELECT 1 FROM pg_event_trigger_dropped_objects() WHERE object_type = 'extension') THEN + RETURN; + END IF; + + FOR r IN SELECT * FROM @extension_schema@._extension_drop__dropping() LOOP RAISE DEBUG E'extension "%" is being dropped; executing SQL:\n%', r.extension_name, r.sql; EXECUTE r.sql; - DELETE FROM extension_drop__commands WHERE extension_name = r.extension_name; + -- Registered SQL may change search_path; don't let it leak into the next registration + PERFORM pg_catalog.set_config('search_path', saved_path, true); END LOOP; - - /* - * Need to do this after the fact since the extensions being dropped have - * already been removed from the catalog by the time this function is called. - */ - PERFORM extension_drop__sanity_assert(); END $body$ , 'Event trigger function that does the actual work for extension_drop.' @@ -291,10 +380,57 @@ $body$ CREATE EVENT TRIGGER extension_drop ON sql_drop - WHEN tag IN( 'DROP EXTENSION' ) -- NOTE! This MUST be IN + -- DROP SCHEMA CASCADE and DROP OWNED BY also drop extensions. + WHEN tag IN( 'DROP EXTENSION', 'DROP SCHEMA', 'DROP OWNED' ) -- NOTE! This MUST be IN EXECUTE PROCEDURE extension_drop__event_trigger() ; +/* + * USAGE GUARD: the start trigger refuses any REVOKE / DROP OWNED while PUBLIC already lacks USAGE (the + * only error that gives the GRANT); the end trigger refuses a command that just removed it. + */ +SELECT __extension_drop.create_function( + 'extension_drop__usage_guard' + , '' + , 'event_trigger LANGUAGE plpgsql' + , $body$ +DECLARE + ns oid := (SELECT e.extnamespace FROM pg_extension e WHERE e.extname = 'extension_drop'); + nsname text; + detail text := 'extension_drop requires PUBLIC to have USAGE on the schema it is installed in. DDL command: ' || tg_tag; +BEGIN + -- Not installed any more (e.g. DROP OWNED dropped it): nothing to protect. + IF ns IS NOT NULL AND NOT has_schema_privilege('public', ns, 'USAGE') THEN + nsname := (SELECT n.nspname FROM pg_namespace n WHERE n.oid = ns); + IF tg_event = 'ddl_command_start' THEN + RAISE EXCEPTION 'PUBLIC lacks USAGE on schema "%"', replace(nsname, '"', '""') + USING ERRCODE = 'object_not_in_prerequisite_state' + , DETAIL = detail + , HINT = format('Run GRANT USAGE ON SCHEMA %s TO PUBLIC.', quote_ident(nsname)) + ; + END IF; + RAISE EXCEPTION 'cannot remove USAGE on schema "%" from PUBLIC', replace(nsname, '"', '""') + USING ERRCODE = 'object_not_in_prerequisite_state' + , DETAIL = detail + ; + END IF; +END +$body$ + , 'Event trigger function that stops PUBLIC losing USAGE on the schema extension_drop is installed in.' +); + +CREATE EVENT TRIGGER extension_drop__usage_guard_start + ON ddl_command_start + WHEN tag IN( 'REVOKE', 'DROP OWNED' ) -- NOTE! This MUST be IN + EXECUTE PROCEDURE extension_drop__usage_guard() +; + +CREATE EVENT TRIGGER extension_drop__usage_guard + ON ddl_command_end + WHEN tag IN( 'REVOKE', 'DROP OWNED' ) -- NOTE! This MUST be IN + EXECUTE PROCEDURE extension_drop__usage_guard() +; + /* * Drop "temporary" objects */ diff --git a/test/build/expected/build.out b/test/build/expected/build.out index 44215eb..9828ae2 100644 --- a/test/build/expected/build.out +++ b/test/build/expected/build.out @@ -17,6 +17,10 @@ INSTALL + + + + # TRANSACTION INTENTIONALLY LEFT OPEN diff --git a/test/deps.sql b/test/deps.sql index 769930b..319f859 100644 --- a/test/deps.sql +++ b/test/deps.sql @@ -39,4 +39,31 @@ WHERE x.extname = 'extension_drop' \set TT extension_drop_test_table CREATE TEMP TABLE :TT (i int); +/* + * Runs sql and returns the message, DETAIL and HINT of the error it raises when that error's SQLSTATE is + * `state`; returns no rows if it raises nothing. Any other error propagates. + */ +CREATE FUNCTION pg_temp.xd_capture(sql text, state text) +RETURNS TABLE(message text, detail text, hint text) LANGUAGE plpgsql AS $f$ +BEGIN + EXECUTE sql; +EXCEPTION WHEN OTHERS THEN + IF SQLSTATE <> state THEN + RAISE; + END IF; + GET STACKED DIAGNOSTICS message = MESSAGE_TEXT, detail = PG_EXCEPTION_DETAIL, hint = PG_EXCEPTION_HINT; + RETURN NEXT; +END $f$; + +/* + * Runs sql as role, then resets the role. On error the role reverts when the enclosing subtransaction + * is rolled back. + */ +CREATE FUNCTION pg_temp.xd_as(role name, sql text) RETURNS void LANGUAGE plpgsql AS $f$ +BEGIN + EXECUTE format('SET LOCAL ROLE %I', role); + EXECUTE sql; + RESET ROLE; +END $f$; + -- vi: expandtab ts=2 sw=2 diff --git a/test/expected/dependency_guard_1.out b/test/expected/dependency_guard_1.out deleted file mode 100644 index 0f29080..0000000 --- a/test/expected/dependency_guard_1.out +++ /dev/null @@ -1,7 +0,0 @@ -\set ECHO none -1..4 -ok 1 - Non-CASCADE DROP EXTENSION extension_drop is blocked by the dependency guard -ok 2 - extension_drop is still installed after the blocked drop attempt -ok 3 - Dependency guard view is still present after the blocked drop attempt -ok 4 # SKIP existing mode: extension_drop's placement is outside this suite's control -# TRANSACTION INTENTIONALLY LEFT OPEN! diff --git a/test/expected/drop_denied.out b/test/expected/drop_denied.out new file mode 100644 index 0000000..9ebef37 --- /dev/null +++ b/test/expected/drop_denied.out @@ -0,0 +1,35 @@ +\set ECHO none +1..32 +ok 1 - The role has no privileges on extension_drop__commands +ok 2 - Registered: DROP SCHEMA CASCADE with no table privileges +ok 3 - Registered: DROP SCHEMA CASCADE with no table privileges: effects +ok 4 - Registered: DROP OWNED BY with no table privileges +ok 5 - Registered: DROP OWNED BY with no table privileges: effects +ok 6 - Unregistered: DROP SCHEMA CASCADE with no table privileges +ok 7 - Unregistered: DROP OWNED BY with no table privileges +ok 8 - Registered SQL's own privilege error surfaces unchanged +ok 9 - Registered: DROP SCHEMA CASCADE with a stale registration present +ok 10 - Unregistered: DROP SCHEMA CASCADE with a stale registration present +ok 11 - sanity_assert raises XD001 with the expected message, DETAIL and HINT +ok 12 - The event trigger raises the same message, DETAIL and HINT +ok 13 - Plural DETAIL names both stale extensions +ok 14 - A role with a temp table of the same name drops a registered extension +ok 15 - A role with a temp table of the same name drops a registered extension: effects +ok 16 - _extension_drop__dropping outside the event trigger fails for a plain role +ok 17 - Registered: DROP SCHEMA CASCADE by the role with the operators planted +ok 18 - Registered: DROP SCHEMA CASCADE by the role with the operators planted: effects +ok 19 - DROP SCHEMA CASCADE with a stale registration and the operators planted +ok 20 - DROP SCHEMA CASCADE with a stale registration and the operators planted: effects +ok 21 - Superuser extension_drop__get and drop of a registered extension with the operators planted +ok 22 - Superuser extension_drop__get and drop of a registered extension with the operators planted: effects +ok 23 - extension_drop's member functions are exactly these, and only _extension_drop__dropping is SECURITY DEFINER +ok 24 - Every extension_drop function pins search_path to pg_catalog, pg_temp +ok 25 - Registered: DROP EXTENSION by the extension's non-superuser owner with no table privileges +ok 26 - Registered: DROP EXTENSION by the extension's non-superuser owner with no table privileges: effects +ok 27 - Unregistered: DROP EXTENSION by the extension's non-superuser owner with no table privileges +ok 28 - Stale registration is present +ok 29 - Non-superuser DROP SCHEMA CASCADE of a schema with no extension +ok 30 - Non-superuser DROP OWNED BY with no extension +ok 31 - Superuser DROP SCHEMA with stale registration +ok 32 - extension_drop's schema should not be reachable via search_path +# TRANSACTION INTENTIONALLY LEFT OPEN! diff --git a/test/expected/public_usage.out b/test/expected/public_usage.out new file mode 100644 index 0000000..899dff1 --- /dev/null +++ b/test/expected/public_usage.out @@ -0,0 +1,33 @@ +\set ECHO none +1..22 +ok 1 - Create role +ok 2 - REVOKE USAGE ON SCHEMA ... FROM PUBLIC is rejected +ok 3 - PUBLIC still has USAGE +ok 4 - REVOKE ALL ON SCHEMA ... FROM PUBLIC is rejected +ok 5 - HINT is empty and DETAIL explains the requirement and names the command +ok 6 - REVOKE from a role other than PUBLIC is allowed +ok 7 - PUBLIC keeps USAGE through the grantor's own grant +ok 8 - DROP OWNED BY the grantor of PUBLIC's only USAGE is rejected +ok 9 - DROP OWNED BY the grantor is allowed once PUBLIC has USAGE from the owner +ok 10 - Remove PUBLIC's USAGE with event triggers bypassed +ok 11 - An unrelated REVOKE reports the missing USAGE +ok 12 - HINT gives the GRANT; DETAIL explains the requirement and names the command +ok 13 - DROP OWNED reports the missing USAGE +ok 14 - The GRANT in the HINT recovers +ok 15 - Drop extension_drop +ok 16 - Install into a schema without PUBLIC USAGE fails +ok 17 - HINT gives the exact GRANT; DETAIL explains the requirement +WARNING: function__arg_types_text() is deprecated, use routine__parse_arg_types_text instead +WARNING: function__arg_types_text() is deprecated, use routine__parse_arg_types_text instead +WARNING: function__arg_types_text() is deprecated, use routine__parse_arg_types_text instead +WARNING: function__arg_types_text() is deprecated, use routine__parse_arg_types_text instead +WARNING: function__arg_types_text() is deprecated, use routine__parse_arg_types_text instead +WARNING: function__arg_types_text() is deprecated, use routine__parse_arg_types_text instead +WARNING: function__arg_types_text() is deprecated, use routine__parse_arg_types_text instead +WARNING: function__arg_types_text() is deprecated, use routine__parse_arg_types_text instead +ok 18 - Update of an install without PUBLIC USAGE fails +ok 19 - HINT gives the exact GRANT; DETAIL explains the requirement +ok 20 - Update succeeds once PUBLIC has USAGE, in a schema named x$body$y +ok 21 - Updated to the current version +ok 22 - extension_drop's schema should not be reachable via search_path +# TRANSACTION INTENTIONALLY LEFT OPEN! diff --git a/test/expected/sanity_assert_overload.out b/test/expected/sanity_assert_overload.out new file mode 100644 index 0000000..261938f --- /dev/null +++ b/test/expected/sanity_assert_overload.out @@ -0,0 +1,11 @@ +\set ECHO none +1..8 +ok 1 - Create a role with CREATE on extension_drop's schema +ok 2 - Plant a zero-argument extension_drop__sanity_assert() +ok 3 - CREATE EXTENSION of an extension that registers drop commands +ok 4 - extension_drop__get +ok 5 - DROP EXTENSION runs the event trigger +ok 6 - Unregister it +ok 7 - DROP EXTENSION of an unregistered extension +ok 8 - extension_drop's schema should not be reachable via search_path +# TRANSACTION INTENTIONALLY LEFT OPEN! diff --git a/test/expected/simple.out b/test/expected/simple.out index c1e3693..469de46 100644 --- a/test/expected/simple.out +++ b/test/expected/simple.out @@ -1,15 +1,56 @@ \set ECHO none -1..12 +1..53 ok 1 - Insert into extension_drop_test_table ok 2 - Create test extension -ok 3 - Verify extension_drop__get() -ok 4 - Drop test extension -ok 5 - extension_drop_test_table is empty -ok 6 - Create test extension again -ok 7 - Drop extension command -ok 8 - Add extension command -ok 9 - Dropping extension with bad command should fail -ok 10 - Drop extension command -ok 11 - Drop test extension -ok 12 - extension_drop's schema should not be reachable via search_path +ok 3 - Create second test extension +ok 4 - Verify extension_drop__get() +ok 5 - Drop both test extensions with one command +ok 6 - extension_drop_test_table is empty +ok 7 - Create test extension again +ok 8 - Drop extension command +ok 9 - Add extension command +ok 10 - Dropping extension with bad command should fail +ok 11 - Drop extension command +ok 12 - Drop test extension +ok 13 - Create role +ok 14 - Create schema +ok 15 - Insert into extension_drop_test_table +ok 16 - Create test extension as role +ok 17 - Verify extension_drop__get() +ok 18 - Drop owned +ok 19 - Test extension does not exist +ok 20 - extension_drop_test_table is empty +ok 21 - No stale registration +ok 22 - Create test extension +ok 23 - Test extension exists +ok 24 - Drop test extension +ok 25 - Test extension does not exist +ok 26 - Insert into extension_drop_test_table +ok 27 - Create test extension in schema +ok 28 - Verify extension_drop__get() +ok 29 - Drop schema cascade +ok 30 - Test extension does not exist +ok 31 - extension_drop_test_table is empty +ok 32 - No stale registration +ok 33 - Create test extension +ok 34 - Test extension exists +ok 35 - Drop test extension +ok 36 - Test extension does not exist +ok 37 - Create recording table +ok 38 - Create extension_drop_test_b +ok 39 - Create extension_drop_test +ok 40 - Register recording SQL for extension_drop_test_b +ok 41 - Register recording SQL for extension_drop_test +ok 42 - Drop both extensions with one command +ok 43 - Every registered SQL ran, each starting under the pinned search_path +ok 44 - Registrations removed +ok 45 - Register SQL that calls _extension_drop__dropping() +ok 46 - Drop extension_drop_test only +ok 47 - The nested dropping call returned no rows, under the pinned search_path +ok 48 - The surviving extension keeps its registration +ok 49 - Update extension_drop_test registration +ok 50 - Update left the other registration unchanged +ok 51 - Remove extension_drop_test registration +ok 52 - Remove left the other registration in place +ok 53 - extension_drop's schema should not be reachable via search_path # TRANSACTION INTENTIONALLY LEFT OPEN! diff --git a/test/expected/simple_1.out b/test/expected/simple_1.out deleted file mode 100644 index b9ce264..0000000 --- a/test/expected/simple_1.out +++ /dev/null @@ -1,15 +0,0 @@ -\set ECHO none -1..12 -ok 1 - Insert into extension_drop_test_table -ok 2 - Create test extension -ok 3 - Verify extension_drop__get() -ok 4 - Drop test extension -ok 5 - extension_drop_test_table is empty -ok 6 - Create test extension again -ok 7 - Drop extension command -ok 8 - Add extension command -ok 9 - Dropping extension with bad command should fail -ok 10 - Drop extension command -ok 11 - Drop test extension -ok 12 # SKIP existing mode: extension_drop's placement is outside this suite's control -# TRANSACTION INTENTIONALLY LEFT OPEN! diff --git a/test/extension/extension_drop_test--0.0.1.sql b/test/extension/extension_drop_test--0.0.1.sql index 5aabd64..6bea36b 100644 --- a/test/extension/extension_drop_test--0.0.1.sql +++ b/test/extension/extension_drop_test--0.0.1.sql @@ -1,3 +1,3 @@ -SELECT extension_drop__add('extension_drop_test', 'DELETE FROM extension_drop_test_table'); +SELECT extension_drop__add('extension_drop_test', 'DELETE FROM pg_temp.extension_drop_test_table'); -- vi: expandtab sw=2 ts=2 diff --git a/test/extension/extension_drop_test_b--0.0.1.sql b/test/extension/extension_drop_test_b--0.0.1.sql new file mode 100644 index 0000000..bc8a2b8 --- /dev/null +++ b/test/extension/extension_drop_test_b--0.0.1.sql @@ -0,0 +1,3 @@ +SELECT extension_drop__add('extension_drop_test_b', 'DELETE FROM pg_temp.extension_drop_test_table'); + +-- vi: expandtab sw=2 ts=2 diff --git a/test/extension/extension_drop_test_b.control b/test/extension/extension_drop_test_b.control new file mode 100644 index 0000000..61ec5d0 --- /dev/null +++ b/test/extension/extension_drop_test_b.control @@ -0,0 +1,2 @@ +default_version = '0.0.1' +requires = 'extension_drop' diff --git a/test/finish.sql b/test/finish.sql index 4b35225..611fa4b 100644 --- a/test/finish.sql +++ b/test/finish.sql @@ -13,19 +13,16 @@ * schema mid-run, so the value set at the top of the session is still * accurate here. * - * existing mode is the one exception: there, extension_drop was installed - * by a real pg_upgrade external to this suite (see test/install/load.sql), - * landing wherever THAT process's own ambient defaults put it -- typically - * public, which stays on search_path by default. We have no control over - * or guarantee about that placement, so there's nothing to assert here in - * that mode; skip() still counts as one test, so no plan() changes needed - * either way. + * existing mode is the one exception: there, extension_drop was installed by a real pg_upgrade external to this + * suite (see test/install/load.sql), landing wherever THAT process's ambient defaults put it -- typically + * public, which stays on search_path by default -- so nothing can be asserted. It emits the same single test + * with the same label as pass(), which checks nothing; that keeps one expected output for every mode. */ SELECT current_setting('extension_drop.test_load_mode') = 'existing' AS extension_drop_existing_mode \gset \if :extension_drop_existing_mode -SELECT skip('existing mode: extension_drop''s placement is outside this suite''s control'); +SELECT pass('extension_drop''s schema should not be reachable via search_path'); \else SELECT is( current_schemas(true) @> array[:'extension_drop_schema'::name] diff --git a/test/helpers/test_ext__verify_dropped.sql b/test/helpers/test_ext__verify_dropped.sql new file mode 100644 index 0000000..a86f134 --- /dev/null +++ b/test/helpers/test_ext__verify_dropped.sql @@ -0,0 +1,11 @@ +SELECT hasnt_extension('extension_drop_test', 'Test extension does not exist'); +SELECT is_empty( + $$SELECT * FROM $$ || :'TT' + , :'TT' || ' is empty' +); +SELECT is_empty( + format($$SELECT unnest(%I.extension_drop__sanity_check())$$, :'extension_drop_schema') + , 'No stale registration' +); + +-- vi: expandtab sw=2 ts=2 diff --git a/test/install/load.sql b/test/install/load.sql index 6e4ea52..135e3e9 100644 --- a/test/install/load.sql +++ b/test/install/load.sql @@ -152,6 +152,8 @@ SELECT 'extension_drop test schema ' || substr(md5(random()::text), 1, 12) AS ex \gset CREATE SCHEMA :"extension_drop_test_schema"; +-- extension_drop refuses to install without it (see extension_drop.sql) +GRANT USAGE ON SCHEMA :"extension_drop_test_schema" TO PUBLIC; /* * CASCADE auto-installs cat_tools on PG10+; pre-PG10 needs it created diff --git a/test/sql/drop_denied.sql b/test/sql/drop_denied.sql new file mode 100644 index 0000000..cdc0f40 --- /dev/null +++ b/test/sql/drop_denied.sql @@ -0,0 +1,279 @@ +\set ECHO none +\i test/pgxntool/setup.sql + +/* + * Dropping an extension needs no privileges on extension_drop's registration table, for the three commands + * the trigger fires for, whether or not the extension is registered. Also covered: registered SQL runs as + * the dropping role, XD001 for a stale registration (and its text), drops involving no extension, and + * the planted-operator attack on the dropping function. Scenarios are grouped by the state they need; + * pg_temp.xd_scenario rolls back whatever each one does. + */ +SELECT plan( + 1 -- table privileges + + 9 -- DROP SCHEMA CASCADE and DROP OWNED BY, registered SQL's error, stale registration + + 3 -- XD001 text + + 2 -- temp table of the same name + + 1 -- dropping function outside the trigger + + 6 -- planted operators + + 2 -- member functions + + 3 -- DROP EXTENSION by the owner + + 4 -- drops involving no extension + + + 1 -- extension_drop's schema should not be on search_path (test/finish.sql) +); + +-- Hide version-specific NOTICE/WARNING text from the drops +SET client_min_messages = ERROR; + +/* + * Optionally unregister (unreg), insert a stale registration (stale) and run setup (as the current role; + * @S@ is extension_drop's schema), then run drop_sql as role (the current role if NULL) and check it + * succeeds, or fails with state and msg. ran_as checks the registered SQL ran as that role and the + * registration is gone; hijack checks the planted operators did not run. Everything is rolled back. + */ +CREATE FUNCTION pg_temp.xd_scenario( + descr text, role name, drop_sql text + , unreg boolean DEFAULT false, stale boolean DEFAULT false, setup text DEFAULT '' + , state text DEFAULT NULL, msg text DEFAULT NULL + , ran_as name DEFAULT NULL, hijack boolean DEFAULT false +) RETURNS SETOF text LANGUAGE plpgsql AS $f$ +DECLARE + sch text := quote_ident((SELECT n.nspname FROM pg_extension x JOIN pg_namespace n ON n.oid = x.extnamespace + WHERE x.extname = 'extension_drop')) + ; + run text := replace(drop_sql, '@S@', sch); + remaining int; + actual text := ''; + expected text := ''; +BEGIN + IF role IS NOT NULL THEN + run := format('SELECT pg_temp.xd_as(%L, %L)', role, run); + END IF; + PERFORM set_config('extension_drop_test.ran_as', 'none', false), set_config('extension_drop_test.hijacked', 'no', false); + BEGIN + IF unreg THEN + EXECUTE format('SELECT %s.extension_drop__remove(''extension_drop_test'')', sch); + END IF; + IF stale THEN + EXECUTE format('INSERT INTO %s.extension_drop__commands VALUES(''extension_drop_test_stale'', ''SELECT 1'')', sch); + END IF; + IF setup <> '' THEN + EXECUTE replace(setup, '@S@', sch); + END IF; + + IF state IS NULL THEN + RETURN NEXT lives_ok(run, descr); + ELSE + RETURN NEXT throws_ok(run, state, msg, descr); + END IF; + + IF ran_as IS NOT NULL THEN + EXECUTE format('SELECT count(*) FROM %s.extension_drop__commands', sch) INTO remaining; + actual := format('ran as %s, %s registrations left', current_setting('extension_drop_test.ran_as'), remaining); + expected := format('ran as %s, 0 registrations left', ran_as); + END IF; + IF hijack THEN + actual := actual || ' hijacked=' || current_setting('extension_drop_test.hijacked'); + expected := expected || ' hijacked=no'; + END IF; + IF expected <> '' THEN + RETURN NEXT is(actual, expected, descr || ': effects'); + END IF; + + RAISE EXCEPTION 'rollback' USING ERRCODE = 'XD999'; + EXCEPTION WHEN SQLSTATE 'XD999' THEN + NULL; + END; +END $f$; + +CREATE TEMP VIEW xd_members AS + SELECT p.proname, p.prosecdef, p.proconfig + FROM pg_depend d JOIN pg_proc p ON p.oid = d.objid + WHERE d.classid = 'pg_proc'::regclass AND d.refclassid = 'pg_extension'::regclass AND d.deptype = 'e' + AND d.refobjid = (SELECT e.oid FROM pg_extension e WHERE e.extname = 'extension_drop') +; + +\set REGISTER_RECORDER 'SELECT ' :"extension_drop_schema" '.extension_drop__update(''extension_drop_test'', $$SELECT set_config(''extension_drop_test.ran_as'', current_user, false)$$)' '\\g /dev/null' + +CREATE ROLE extension_drop_test_plain; +-- Created as superuser, so the role only owns the schema +CREATE SCHEMA extension_drop_test_plain_schema AUTHORIZATION extension_drop_test_plain; +CREATE EXTENSION extension_drop_test SCHEMA extension_drop_test_plain_schema; +:REGISTER_RECORDER + +SELECT table_privs_are( + :'extension_drop_schema', 'extension_drop__commands', 'extension_drop_test_plain', '{}'::name[] + , 'The role has no privileges on extension_drop__commands' +); + +-- Registered SQL runs as the dropping role and the registration is removed; unregistered drops just work +SELECT * FROM pg_temp.xd_scenario('Registered: DROP SCHEMA CASCADE with no table privileges' + , 'extension_drop_test_plain', 'DROP SCHEMA extension_drop_test_plain_schema CASCADE' + , ran_as => 'extension_drop_test_plain' +); +SELECT * FROM pg_temp.xd_scenario('Registered: DROP OWNED BY with no table privileges' + , 'extension_drop_test_plain', 'DROP OWNED BY extension_drop_test_plain CASCADE' + , ran_as => 'extension_drop_test_plain' +); +SELECT * FROM pg_temp.xd_scenario('Unregistered: DROP SCHEMA CASCADE with no table privileges' + , 'extension_drop_test_plain', 'DROP SCHEMA extension_drop_test_plain_schema CASCADE', unreg => true +); +SELECT * FROM pg_temp.xd_scenario('Unregistered: DROP OWNED BY with no table privileges' + , 'extension_drop_test_plain', 'DROP OWNED BY extension_drop_test_plain CASCADE', unreg => true +); + +-- A privilege error from the registered SQL itself surfaces unchanged +SELECT * FROM pg_temp.xd_scenario('Registered SQL''s own privilege error surfaces unchanged' + , 'extension_drop_test_plain', 'DROP SCHEMA extension_drop_test_plain_schema CASCADE' + , setup => $$SELECT @S@.extension_drop__update('extension_drop_test', 'CREATE ROLE extension_drop_test_never')$$ + , state => '42501', msg => 'permission denied to create role' +); + +-- A stale registration fails the drop whether or not the extension is registered +SELECT * FROM pg_temp.xd_scenario('Registered: DROP SCHEMA CASCADE with a stale registration present' + , 'extension_drop_test_plain', 'DROP SCHEMA extension_drop_test_plain_schema CASCADE' + , stale => true, state => 'XD001', msg => 'unexpected drop commands' +); +SELECT * FROM pg_temp.xd_scenario('Unregistered: DROP SCHEMA CASCADE with a stale registration present' + , 'extension_drop_test_plain', 'DROP SCHEMA extension_drop_test_plain_schema CASCADE' + , unreg => true, stale => true, state => 'XD001', msg => 'unexpected drop commands' +); + +/* + * Every path that raises XD001 gives the same message, DETAIL and HINT: sanity_assert, which both + * extension_drop__get() and the event trigger (via _extension_drop__dropping) raise from. + */ +SAVEPOINT stale; +INSERT INTO :"extension_drop_schema".extension_drop__commands VALUES('extension_drop_test_stale', 'SELECT 1'); +SELECT format('SELECT %I.extension_drop__sanity_assert()', :'extension_drop_schema') AS "SANITY_ASSERT" \gset +SELECT results_eq( + format('SELECT message, detail, hint FROM pg_temp.xd_capture(%L, ''XD001'')', :'SANITY_ASSERT') + , $$VALUES ( + 'unexpected drop commands' + , 'This extension does not exist: extension_drop_test_stale' + , E'This should not happen unless someone manually inserted into "extension_drop__commands" or messed with the "extension_drop" event trigger.\n Use SELECT extension_drop__repair() to fix this.')$$ + , 'sanity_assert raises XD001 with the expected message, DETAIL and HINT' +); +SELECT results_eq( + $$SELECT message, detail, hint FROM pg_temp.xd_capture('DROP EXTENSION extension_drop_test', 'XD001')$$ + , format('SELECT message, detail, hint FROM pg_temp.xd_capture(%L, ''XD001'')', :'SANITY_ASSERT') + , 'The event trigger raises the same message, DETAIL and HINT' +); +INSERT INTO :"extension_drop_schema".extension_drop__commands VALUES('extension_drop_test_stale2', 'SELECT 1'); +-- Names come out in no particular order +SELECT matches( + (SELECT detail FROM pg_temp.xd_capture(:'SANITY_ASSERT', 'XD001')) + , '^These extensions do not exist: (extension_drop_test_stale, extension_drop_test_stale2|extension_drop_test_stale2, extension_drop_test_stale)$' + , 'Plural DETAIL names both stale extensions' +); +ROLLBACK TO SAVEPOINT stale; + +-- A temp table named like ours must not hide the real registration from the dropping function +SELECT * FROM pg_temp.xd_scenario('A role with a temp table of the same name drops a registered extension' + , 'extension_drop_test_plain' + , 'CREATE TEMP TABLE extension_drop__commands(extension_name name, sql text); DROP SCHEMA extension_drop_test_plain_schema CASCADE' + , ran_as => 'extension_drop_test_plain' +); + +-- Called directly, the dropping function fails before deleting anything: pg_event_trigger_dropped_objects() refuses outside the trigger +SELECT * FROM pg_temp.xd_scenario('_extension_drop__dropping outside the event trigger fails for a plain role' + , 'extension_drop_test_plain', 'SELECT @S@._extension_drop__dropping()' + , state => '39P03', msg => 'pg_event_trigger_dropped_objects() can only be called in a sql_drop event trigger function' +); + +/* + * A role with CREATE on extension_drop's schema must not be able to run code as anyone who calls into it. + * The planted operators are on the types the functions actually compare (name, name) and (name, text); + * an exact match in the schema beats pg_catalog's for any function whose path puts the schema first. + */ +SAVEPOINT planted; +GRANT CREATE ON SCHEMA :"extension_drop_schema" TO extension_drop_test_plain; +SELECT format($q$ + CREATE FUNCTION %1$I.xd_test_hijack(name, name) RETURNS boolean LANGUAGE plpgsql AS + $f$ BEGIN PERFORM set_config('extension_drop_test.hijacked', 'yes', false); RETURN true; END $f$; + CREATE FUNCTION %1$I.xd_test_hijack(name, text) RETURNS boolean LANGUAGE plpgsql AS + $f$ BEGIN PERFORM set_config('extension_drop_test.hijacked', 'yes', false); RETURN true; END $f$; + CREATE OPERATOR %1$I.= (LEFTARG = name, RIGHTARG = name, FUNCTION = %1$I.xd_test_hijack(name, name)); + CREATE OPERATOR %1$I.= (LEFTARG = name, RIGHTARG = text, FUNCTION = %1$I.xd_test_hijack(name, text)); + CREATE OPERATOR %1$I.<> (LEFTARG = name, RIGHTARG = name, FUNCTION = %1$I.xd_test_hijack(name, name)); + CREATE OPERATOR %1$I.<> (LEFTARG = name, RIGHTARG = text, FUNCTION = %1$I.xd_test_hijack(name, text)); + $q$, :'extension_drop_schema') AS plant \gset +SELECT pg_temp.xd_as('extension_drop_test_plain', :'plant') \g /dev/null + +SELECT * FROM pg_temp.xd_scenario('Registered: DROP SCHEMA CASCADE by the role with the operators planted' + , 'extension_drop_test_plain', 'DROP SCHEMA extension_drop_test_plain_schema CASCADE', hijack => true +); +-- With a stale row the dropping function runs sanity_assert as the owner; the planted operators still must not run +SELECT * FROM pg_temp.xd_scenario('DROP SCHEMA CASCADE with a stale registration and the operators planted' + , 'extension_drop_test_plain', 'DROP SCHEMA extension_drop_test_plain_schema CASCADE' + , stale => true, state => 'XD001', msg => 'unexpected drop commands', hijack => true +); +-- The invoker paths run with the caller's own rights, so a superuser is the interesting caller +SELECT * FROM pg_temp.xd_scenario('Superuser extension_drop__get and drop of a registered extension with the operators planted' + , NULL + , $$SELECT * FROM @S@.extension_drop__get('extension_drop_test'); DROP SCHEMA extension_drop_test_plain_schema CASCADE$$ + , hijack => true +); +ROLLBACK TO SAVEPOINT planted; + +/* + * Every function runs with a pinned search_path, and only _extension_drop__dropping is SECURITY DEFINER (so + * the event trigger, and everything it runs, is the dropping role's own). + * Not functions_are(): in existing mode the schema may hold other objects. + * Matching (name, prosecdef) rows makes an added overload or definer function fail. + */ +SELECT bag_eq( + 'SELECT proname, prosecdef FROM pg_temp.xd_members' + , $$VALUES ('extension_drop__sanity_check', false), ('extension_drop__sanity_assert', false), ('extension_drop__repair', false) + , ('extension_drop__get', false), ('extension_drop__add', false), ('extension_drop__remove', false) + , ('extension_drop__update', false), ('extension_drop__event_trigger', false), ('extension_drop__usage_guard', false) + , ('_extension_drop__dropping', true)$$ + , 'extension_drop''s member functions are exactly these, and only _extension_drop__dropping is SECURITY DEFINER' +); +-- pgTAP has no assertion for proconfig +SELECT is_empty( + $$SELECT proname FROM pg_temp.xd_members WHERE proconfig IS DISTINCT FROM ARRAY['search_path=pg_catalog, pg_temp']$$ + , 'Every extension_drop function pins search_path to pg_catalog, pg_temp' +); + +-- DROP EXTENSION needs the extension's owner; create it as a role that is then demoted +DROP SCHEMA extension_drop_test_plain_schema CASCADE; +CREATE ROLE extension_drop_test_owner SUPERUSER; +SELECT pg_temp.xd_as('extension_drop_test_owner', 'CREATE EXTENSION extension_drop_test') \g /dev/null +:REGISTER_RECORDER +ALTER ROLE extension_drop_test_owner NOSUPERUSER; + +SELECT * FROM pg_temp.xd_scenario('Registered: DROP EXTENSION by the extension''s non-superuser owner with no table privileges' + , 'extension_drop_test_owner', 'DROP EXTENSION extension_drop_test' + , ran_as => 'extension_drop_test_owner' +); +SELECT * FROM pg_temp.xd_scenario('Unregistered: DROP EXTENSION by the extension''s non-superuser owner with no table privileges' + , 'extension_drop_test_owner', 'DROP EXTENSION extension_drop_test', unreg => true +); + +/* + * Drops involving no extension must not depend on the caller's privileges or on the state of + * extension_drop__commands. + */ +SELECT :"extension_drop_schema".extension_drop__remove('extension_drop_test') \g /dev/null +DROP EXTENSION extension_drop_test; +CREATE SCHEMA extension_drop_test_unrelated AUTHORIZATION extension_drop_test_plain CREATE TABLE t(i int); +INSERT INTO :"extension_drop_schema".extension_drop__commands VALUES('extension_drop_test_stale', 'SELECT 1'); +SELECT results_eq( + format($$SELECT %I.extension_drop__sanity_check()$$, :'extension_drop_schema') + , $$SELECT '{extension_drop_test_stale}'::name[]$$ + , 'Stale registration is present' +); +SELECT * FROM pg_temp.xd_scenario('Non-superuser DROP SCHEMA CASCADE of a schema with no extension' + , 'extension_drop_test_plain', 'DROP SCHEMA extension_drop_test_unrelated CASCADE' +); +SELECT * FROM pg_temp.xd_scenario('Non-superuser DROP OWNED BY with no extension' + , 'extension_drop_test_plain', 'DROP OWNED BY extension_drop_test_plain' +); +SELECT * FROM pg_temp.xd_scenario('Superuser DROP SCHEMA with stale registration' + , NULL, 'CREATE SCHEMA extension_drop_test_su_schema; DROP SCHEMA extension_drop_test_su_schema' +); + +\i test/finish.sql + +-- vi: expandtab sw=2 ts=2 diff --git a/test/sql/public_usage.sql b/test/sql/public_usage.sql new file mode 100644 index 0000000..1d56cd4 --- /dev/null +++ b/test/sql/public_usage.sql @@ -0,0 +1,183 @@ +\set ECHO none +\i test/pgxntool/setup.sql + +/* + * extension_drop calls _extension_drop__dropping() as whichever role drops an extension, so PUBLIC + * must keep USAGE on its schema: install and update refuse without it, REVOKE / DROP OWNED that would + * remove it are rolled back (ddl_command_end), and every REVOKE / DROP OWNED is refused up front while + * PUBLIC already lacks it (ddl_command_start). + */ +SELECT plan( + 1 -- setup + + 8 -- REVOKE and DROP OWNED rejected, state unchanged + + 5 -- guard bypassed: REVOKE and DROP OWNED refused up front, recovery + + 7 -- reinstall; install and update refused without PUBLIC USAGE + + + 1 -- extension_drop's schema should not be on search_path (test/finish.sql) +); + +-- Primary messages always double-quote the name; the HINT's GRANT quotes it only when needed +SELECT quote_ident(:'extension_drop_schema') AS qschema + , '"' || replace(:'extension_drop_schema', '"', '""') || '"' AS dqschema +\gset +SELECT format('cannot remove USAGE on schema %s from PUBLIC', :'dqschema') AS removal_msg + , format('PUBLIC lacks USAGE on schema %s', :'dqschema') AS lacks_msg + , format('Run GRANT USAGE ON SCHEMA %s TO PUBLIC.', :'qschema') AS lacks_hint +\gset + +-- The query returning the HINT and DETAIL of the USAGE error (55000) that sql raises +SELECT $$SELECT hint, detail FROM pg_temp.xd_capture(%L, '55000')$$ AS capture_query +\gset + +SELECT lives_ok( + 'CREATE ROLE extension_drop_test_grantor' + , 'Create role' +); + +SELECT throws_ok( + format('REVOKE USAGE ON SCHEMA %I FROM PUBLIC', :'extension_drop_schema') + , '55000' + , :'removal_msg' + , 'REVOKE USAGE ON SCHEMA ... FROM PUBLIC is rejected' +); +-- Not schema_privs_are(): it asserts PUBLIC's exact privilege set, and in existing mode PUBLIC may also have CREATE +SELECT is( + has_schema_privilege('public', :'extension_drop_schema', 'USAGE') + , true + , 'PUBLIC still has USAGE' +); + +SELECT throws_ok( + format('REVOKE ALL ON SCHEMA %I FROM PUBLIC', :'extension_drop_schema') + , '55000' + , :'removal_msg' + , 'REVOKE ALL ON SCHEMA ... FROM PUBLIC is rejected' +); +-- No GRANT HINT: the command was prevented, nothing to fix +SELECT results_eq( + format(:'capture_query', format('REVOKE USAGE ON SCHEMA %I FROM PUBLIC', :'extension_drop_schema')) + , $$VALUES ('', 'extension_drop requires PUBLIC to have USAGE on the schema it is installed in. DDL command: REVOKE')$$ + , 'HINT is empty and DETAIL explains the requirement and names the command' +); + +-- Only PUBLIC's USAGE matters +SELECT lives_ok( + format('GRANT USAGE ON SCHEMA %1$I TO extension_drop_test_grantor; REVOKE USAGE ON SCHEMA %1$I FROM extension_drop_test_grantor', :'extension_drop_schema') + , 'REVOKE from a role other than PUBLIC is allowed' +); + +/* + * PUBLIC's USAGE can survive a REVOKE by the owner because another role granted it too; DROP OWNED BY + * that role then removes it. + */ +SELECT lives_ok( + format($q$GRANT USAGE ON SCHEMA %1$I TO extension_drop_test_grantor WITH GRANT OPTION; + SELECT pg_temp.xd_as('extension_drop_test_grantor', %2$L); + REVOKE USAGE ON SCHEMA %1$I FROM PUBLIC$q$, :'extension_drop_schema' + , format('GRANT USAGE ON SCHEMA %I TO PUBLIC', :'extension_drop_schema')) + , 'PUBLIC keeps USAGE through the grantor''s own grant' +); +SELECT throws_ok( + 'DROP OWNED BY extension_drop_test_grantor' + , '55000' + , :'removal_msg' + , 'DROP OWNED BY the grantor of PUBLIC''s only USAGE is rejected' +); +SELECT lives_ok( + format($q$GRANT USAGE ON SCHEMA %I TO PUBLIC; DROP OWNED BY extension_drop_test_grantor$q$, :'extension_drop_schema') + , 'DROP OWNED BY the grantor is allowed once PUBLIC has USAGE from the owner' +); + +/* + * A superuser can bypass the guard; afterwards every REVOKE and DROP OWNED fails before running, naming the + * state and the fix. + */ +SELECT lives_ok( + format('SET LOCAL session_replication_role = replica; REVOKE USAGE ON SCHEMA %I FROM PUBLIC; RESET session_replication_role', :'extension_drop_schema') + , 'Remove PUBLIC''s USAGE with event triggers bypassed' +); +SELECT throws_ok( + format('REVOKE USAGE ON SCHEMA %I FROM extension_drop_test_grantor', :'extension_drop_schema') + , '55000' + , :'lacks_msg' + , 'An unrelated REVOKE reports the missing USAGE' +); +SELECT results_eq( + format(:'capture_query', format('REVOKE USAGE ON SCHEMA %I FROM extension_drop_test_grantor', :'extension_drop_schema')) + , format($$VALUES (%L, 'extension_drop requires PUBLIC to have USAGE on the schema it is installed in. DDL command: REVOKE')$$, :'lacks_hint') + , 'HINT gives the GRANT; DETAIL explains the requirement and names the command' +); +SELECT throws_ok( + 'DROP OWNED BY extension_drop_test_grantor' + , '55000' + , :'lacks_msg' + , 'DROP OWNED reports the missing USAGE' +); +SELECT lives_ok( + format('GRANT USAGE ON SCHEMA %I TO PUBLIC', :'extension_drop_schema') + , 'The GRANT in the HINT recovers' +); + +/* + * Install and update. This file's transaction is rolled back, so extension_drop can be dropped and + * reinstalled elsewhere regardless of how the suite installed it. CASCADE: existing mode plants a + * dependent guard object, whose drop notice is hidden to keep the output mode-independent. + */ +SET LOCAL client_min_messages = warning; +SELECT lives_ok( + 'DROP EXTENSION extension_drop CASCADE' + , 'Drop extension_drop' +); + +CREATE SCHEMA "xd no usage"; +SELECT throws_ok( + 'CREATE EXTENSION extension_drop SCHEMA "xd no usage"' + , '55000' + , 'cannot install extension_drop in schema "xd no usage"' + , 'Install into a schema without PUBLIC USAGE fails' +); +SELECT results_eq( + format(:'capture_query', $q$CREATE EXTENSION extension_drop SCHEMA "xd no usage"$q$) + , $$VALUES ( + 'Run GRANT USAGE ON SCHEMA "xd no usage" TO PUBLIC (creating the schema first if needed), then retry.' + , 'extension_drop requires PUBLIC to have USAGE on the schema it is installed in.')$$ + , 'HINT gives the exact GRANT; DETAIL explains the requirement' +); + +-- The 0.1.1 install script predates the requirement; the update must enforce it, and cope with any schema name +CREATE SCHEMA "x$body$y"; +/* + * The frozen 0.1.1 script forces its own client_min_messages and calls a deprecated cat_tools function; + * terse verbosity drops the server-version-dependent LOCATION line from that warning. + */ +\set VERBOSITY terse +CREATE EXTENSION extension_drop VERSION '0.1.1' SCHEMA "x$body$y"; +\set VERBOSITY verbose +SELECT throws_ok( + 'ALTER EXTENSION extension_drop UPDATE' + , '55000' + , 'cannot update extension_drop in schema "x$body$y"' + , 'Update of an install without PUBLIC USAGE fails' +); +SELECT results_eq( + format(:'capture_query', $q$ALTER EXTENSION extension_drop UPDATE$q$) + , $$VALUES ( + 'Run GRANT USAGE ON SCHEMA "x$body$y" TO PUBLIC (creating the schema first if needed), then retry.' + , 'extension_drop requires PUBLIC to have USAGE on the schema it is installed in.')$$ + , 'HINT gives the exact GRANT; DETAIL explains the requirement' +); +GRANT USAGE ON SCHEMA "x$body$y" TO PUBLIC; +SELECT lives_ok( + 'ALTER EXTENSION extension_drop UPDATE' + , 'Update succeeds once PUBLIC has USAGE, in a schema named x$body$y' +); +-- pgTAP has no assertion for an extension's installed version +SELECT is( + (SELECT extversion FROM pg_extension WHERE extname = 'extension_drop') + , (SELECT default_version FROM pg_available_extensions WHERE name = 'extension_drop') + , 'Updated to the current version' +); + +\i test/finish.sql + +-- vi: expandtab sw=2 ts=2 diff --git a/test/sql/sanity_assert_overload.sql b/test/sql/sanity_assert_overload.sql new file mode 100644 index 0000000..35700a4 --- /dev/null +++ b/test/sql/sanity_assert_overload.sql @@ -0,0 +1,57 @@ +\set ECHO none +\i test/pgxntool/setup.sql + +/* + * A role with CREATE on extension_drop's schema can plant a zero-argument extension_drop__sanity_assert() + * next to the real one; every call must pass the argument explicitly or it becomes ambiguous. plpgsql keeps + * the plan it resolved, so the overload is planted first and each caller below is first run afterwards, in + * this file's own session: a caller that already ran in the session would hide a missing argument. Both + * a registered and an unregistered extension are dropped, since the dropping function runs for either. + */ +SELECT plan( + 2 -- setup + + 3 -- registered extension + + 2 -- unregistered extension + + + 1 -- extension_drop's schema should not be on search_path (test/finish.sql) +); + +SET client_min_messages = ERROR; + +SELECT lives_ok( + format('CREATE ROLE extension_drop_test_plain; GRANT CREATE ON SCHEMA %I TO extension_drop_test_plain', :'extension_drop_schema') + , 'Create a role with CREATE on extension_drop''s schema' +); +SELECT lives_ok( + format('SELECT pg_temp.xd_as(''extension_drop_test_plain'', %L)' + , format('CREATE FUNCTION %I.extension_drop__sanity_assert() RETURNS void LANGUAGE sql AS ''SELECT''', :'extension_drop_schema')) + , 'Plant a zero-argument extension_drop__sanity_assert()' +); + +SELECT lives_ok( + 'CREATE EXTENSION extension_drop_test' + , 'CREATE EXTENSION of an extension that registers drop commands' +); +SELECT lives_ok( + format($$SELECT * FROM %I.extension_drop__get('extension_drop_test')$$, :'extension_drop_schema') + , 'extension_drop__get' +); +SAVEPOINT registered; +SELECT lives_ok( + 'DROP EXTENSION extension_drop_test' + , 'DROP EXTENSION runs the event trigger' +); +ROLLBACK TO SAVEPOINT registered; + +SELECT lives_ok( + format($$SELECT %I.extension_drop__remove('extension_drop_test')$$, :'extension_drop_schema') + , 'Unregister it' +); +SELECT lives_ok( + 'DROP EXTENSION extension_drop_test' + , 'DROP EXTENSION of an unregistered extension' +); + +\i test/finish.sql + +-- vi: expandtab sw=2 ts=2 diff --git a/test/sql/simple.sql b/test/sql/simple.sql index fd4582a..82db16c 100644 --- a/test/sql/simple.sql +++ b/test/sql/simple.sql @@ -1,20 +1,30 @@ \set ECHO none \i test/pgxntool/setup.sql +/* + * Registered SQL runs when the extension is dropped, by whichever command drops it. Each scenario below the + * first section ends with a ROLLBACK TO SAVEPOINT; the file's single open transaction makes that possible. + */ SELECT plan( - 0 - - + 1 -- Insert into test table + 1 -- test/helpers/test_ext__insert.sql + + 11 -- lifecycle - + 1 -- Create test extension - + 1 -- Verify test extension drop command - + 1 -- Drop test extension - + 1 -- Verify test table is empty + -- Other commands that drop an extension + + 2 -- setup + + 1 -- test/helpers/test_ext__insert.sql + + 3 -- DROP OWNED BY + + 3 -- test/helpers/test_ext__verify_dropped.sql + + 4 -- test/helpers/test_ext__create_drop.sql + + 1 -- test/helpers/test_ext__insert.sql + + 3 -- DROP SCHEMA CASCADE + + 3 -- test/helpers/test_ext__verify_dropped.sql + + 4 -- test/helpers/test_ext__create_drop.sql - + 1 -- Create test extension again - + 2 -- Test __remove and add - + 1 -- Drop fails - + 2 -- __remove and drop succeeds + -- Several registered extensions + + 5 -- setup + + 3 -- DROP EXTENSION naming both + + 4 -- nested _extension_drop__dropping() + + 4 -- extension_drop__update() and extension_drop__remove() + 1 -- extension_drop's schema should not be on search_path (test/finish.sql) ); @@ -25,16 +35,20 @@ SELECT lives_ok( 'CREATE EXTENSION extension_drop_test' , 'Create test extension' ); +SELECT lives_ok( + 'CREATE EXTENSION extension_drop_test_b' + , 'Create second test extension' +); SELECT bag_eq( format($$SELECT * FROM %I.extension_drop__get('extension_drop_test')$$, :'extension_drop_schema') - , $$SELECT 'extension_drop_test'::name, 'DELETE FROM extension_drop_test_table'::text$$ + , $$SELECT 'extension_drop_test'::name, 'DELETE FROM pg_temp.extension_drop_test_table'::text$$ , 'Verify extension_drop__get()' ); SELECT lives_ok( - $$DROP EXTENSION extension_drop_test$$ - , 'Drop test extension' + $$DROP EXTENSION extension_drop_test, extension_drop_test_b$$ + , 'Drop both test extensions with one command' ); SELECT is_empty( @@ -72,6 +86,151 @@ SELECT lives_ok( , 'Drop test extension' ); +/* + * DROP OWNED BY and DROP SCHEMA CASCADE can drop an extension too; its registered command must run and the + * registration must go away, or the stale row makes every later DROP EXTENSION fail. + */ +-- Hide the version-specific "drop cascades to" NOTICE +SET client_min_messages = WARNING; + +SELECT lives_ok( + 'CREATE ROLE extension_drop_test_owner SUPERUSER' + , 'Create role' +); +SELECT lives_ok( + 'CREATE SCHEMA extension_drop_test_schema' + , 'Create schema' +); +SAVEPOINT clean; + +\i test/helpers/test_ext__insert.sql +-- ALTER EXTENSION can't change the owner, so create it as that role +SELECT lives_ok( + $$SELECT pg_temp.xd_as('extension_drop_test_owner', 'CREATE EXTENSION extension_drop_test')$$ + , 'Create test extension as role' +); +SELECT bag_eq( + format($$SELECT * FROM %I.extension_drop__get('extension_drop_test')$$, :'extension_drop_schema') + , $$SELECT 'extension_drop_test'::name, 'DELETE FROM pg_temp.extension_drop_test_table'::text$$ + , 'Verify extension_drop__get()' +); +SELECT lives_ok( + 'DROP OWNED BY extension_drop_test_owner' + , 'Drop owned' +); +\i test/helpers/test_ext__verify_dropped.sql +\i test/helpers/test_ext__create_drop.sql +ROLLBACK TO SAVEPOINT clean; + +\i test/helpers/test_ext__insert.sql +SELECT lives_ok( + 'CREATE EXTENSION extension_drop_test SCHEMA extension_drop_test_schema' + , 'Create test extension in schema' +); +SELECT bag_eq( + format($$SELECT * FROM %I.extension_drop__get('extension_drop_test')$$, :'extension_drop_schema') + , $$SELECT 'extension_drop_test'::name, 'DELETE FROM pg_temp.extension_drop_test_table'::text$$ + , 'Verify extension_drop__get()' +); +SELECT lives_ok( + 'DROP SCHEMA extension_drop_test_schema CASCADE' + , 'Drop schema cascade' +); +\i test/helpers/test_ext__verify_dropped.sql +\i test/helpers/test_ext__create_drop.sql +ROLLBACK TO SAVEPOINT clean; + +/* + * One command dropping several registered extensions runs every registered SQL, each under the event + * trigger's pinned search_path (an earlier one changing it must not leak into the next), and removes every + * registration. A registered SQL that calls _extension_drop__dropping() again can't remove a surviving + * extension's registration. With two extensions registered, extension_drop__update() and + * extension_drop__remove() touch only the named one. + */ +SELECT lives_ok( + 'CREATE TEMP TABLE extension_drop_test_ran(name text, path text)' + , 'Create recording table' +); +SELECT lives_ok('CREATE EXTENSION extension_drop_test_b', 'Create extension_drop_test_b'); +SELECT lives_ok('CREATE EXTENSION extension_drop_test', 'Create extension_drop_test'); + +-- Each registered SQL records the path it starts with, then changes it +SELECT lives_ok( + format($$SELECT %I.extension_drop__update(%L, %L)$$ + , :'extension_drop_schema', n + , format($s$INSERT INTO pg_temp.extension_drop_test_ran VALUES (%L, current_setting('search_path')); + SELECT set_config('search_path', 'pg_catalog, public, pg_temp', true)$s$, n)) + , 'Register recording SQL for ' || n +) + FROM unnest(ARRAY['extension_drop_test_b', 'extension_drop_test']) n +; + +-- A query returning extension_drop_test_b's registered row, to prove it survives +SELECT format($$SELECT 'extension_drop_test_b'::name, %L::text$$, sql) AS "B_ROW" + FROM :"extension_drop_schema".extension_drop__commands WHERE extension_name = 'extension_drop_test_b' +\gset + +SAVEPOINT both_registered; + +SELECT lives_ok( + 'DROP EXTENSION extension_drop_test_b, extension_drop_test' + , 'Drop both extensions with one command' +); +SELECT bag_eq( + 'SELECT name, path FROM extension_drop_test_ran' + , $$VALUES ('extension_drop_test', 'pg_catalog, pg_temp'), ('extension_drop_test_b', 'pg_catalog, pg_temp')$$ + , 'Every registered SQL ran, each starting under the pinned search_path' +); +SELECT is_empty( + format('SELECT * FROM %I.extension_drop__commands', :'extension_drop_schema') + , 'Registrations removed' +); +ROLLBACK TO SAVEPOINT both_registered; + +SELECT lives_ok( + format($$SELECT %I.extension_drop__update('extension_drop_test', %L)$$ + , :'extension_drop_schema' + , format($s$INSERT INTO pg_temp.extension_drop_test_ran(name, path) + SELECT CASE WHEN EXISTS (SELECT 1 FROM %I._extension_drop__dropping()) + THEN 'nested dropping call returned rows' ELSE 'nested dropping call returned nothing' END + , current_setting('search_path')$s$ + , :'extension_drop_schema')) + , 'Register SQL that calls _extension_drop__dropping()' +); + +SELECT lives_ok('DROP EXTENSION extension_drop_test', 'Drop extension_drop_test only'); +SELECT bag_eq( + 'SELECT name, path FROM extension_drop_test_ran' + , $$VALUES ('nested dropping call returned nothing', 'pg_catalog, pg_temp')$$ + , 'The nested dropping call returned no rows, under the pinned search_path' +); +SELECT results_eq( + format('SELECT extension_name, sql FROM %I.extension_drop__commands', :'extension_drop_schema') + , :'B_ROW' + , 'The surviving extension keeps its registration' +); +ROLLBACK TO SAVEPOINT both_registered; + +SELECT lives_ok( + format($$SELECT %I.extension_drop__update('extension_drop_test', 'SELECT 1')$$, :'extension_drop_schema') + , 'Update extension_drop_test registration' +); +SELECT bag_eq( + format('SELECT extension_name, sql FROM %I.extension_drop__commands', :'extension_drop_schema') + , :'B_ROW' || $$ UNION ALL SELECT 'extension_drop_test'::name, 'SELECT 1'::text$$ + , 'Update left the other registration unchanged' +); + +SELECT lives_ok( + format($$SELECT %I.extension_drop__remove('extension_drop_test')$$, :'extension_drop_schema') + , 'Remove extension_drop_test registration' +); +SELECT results_eq( + format('SELECT extension_name, sql FROM %I.extension_drop__commands', :'extension_drop_schema') + , :'B_ROW' + , 'Remove left the other registration in place' +); + \i test/finish.sql -- vi: expandtab sw=2 ts=2