Repository navigation
Fire the event trigger for DROP SCHEMA and DROP OWNED - #55
Conversation
`DROP SCHEMA ... CASCADE` and `DROP OWNED BY` can drop an extension, but the trigger only fired for `DROP EXTENSION`. The registered SQL never ran and the leftover row in `extension_drop__commands` made every later `DROP EXTENSION` raise `XD001`. The trigger's `WHEN tag` list now includes both tags. The update script recreates the trigger, since `ALTER EVENT TRIGGER` cannot change `WHEN`. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
|
Claude finished @jnasbyupgrade's task in 30s —— View job Review of PR #55: fire the event trigger for DROP SCHEMA and DROP OWNEDI read the diff and the trigger and sanity-check code. I did not build the extension or run the test suite. The The change is small and consistent. The trigger Concern: the trigger now fires for ordinary users (not verified by running it)
Event triggers run with the privileges of the user who issued the command. So a non-superuser running There is a second, related effect. Any stale row in Suggestions:
Minor
|
Now that the trigger fires for every `DROP SCHEMA` and `DROP OWNED`, it must not read `extension_drop__commands` or run the sanity assert for drops that involve no extension: a non-superuser's ordinary drops failed with a permission error, and a stale row broke unrelated drops. The row variable is a `record` so the function compiles without access to the extension's schema. Adds tests for non-superuser and stale-row drops, and factors the shared post-drop assertions into a helper. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
Claude here. Addressing the review's non-superuser concern (confirmed by running it: a plain role's |
|
Claude finished @jnasbyupgrade's task in 21s —— View job Review of PR #55: fire the event trigger for DROP SCHEMA and DROP OWNEDI read the diff, including the trigger SQL, the update script and I found no bugs. The earlier review's two concerns are both handled in the current head:
The fresh-install and 0.1.1→stable paths are consistent:
Minor notes (no action required)
|
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
Claude here. Decisions needed from the maintainer:
|
|
Claude finished @jnasbyupgrade's task in 16s —— View job Review of PR #55: fire the event trigger for DROP SCHEMA and DROP OWNEDI read the full diff: the install and update SQL, README/HISTORY, and the three new tests plus the helper. I did not build the extension or run the tests. The I found no bugs.
Minor notes (no action required)
|
|
Claude finished @jnasbyupgrade's task in 18s —— View job Review of PR #55: fire the event trigger for DROP SCHEMA and DROP OWNEDI read the diff of the install SQL, the 0.1.1→stable update script, and I found no bugs.
Minor notes (no action required)
|
| , $body$ | ||
| DECLARE | ||
| r extension_drop__commands; | ||
| r record; -- Not extension_drop__commands: the type must not resolve before the early return |
There was a problem hiding this comment.
Need to actually explain why that matters.
There was a problem hiding this comment.
Claude here. Fixed in 0cae837: the comment now says why. A typed variable is resolved when plpgsql compiles the function on first call, before the early return, so a role that cannot see the extension's schema fails every unrelated DROP with type "extension_drop__commands" does not exist. Reverting to the typed variable makes the unrelated_drops non-superuser DROP SCHEMA CASCADE and DROP OWNED BY tests fail; with record they pass. Same wording applied to sql/extension_drop--0.1.1--stable.sql.
A typed variable is resolved when the function compiles, before the early return, so a role without access to the extension's schema fails unrelated drops.
|
Claude finished @jnasbyupgrade's task in 11s —— View job Review of PR #55The No new bugs found. jnasbyupgrade's review comment said the The early return, the |
…om unrelated_drops The non-superuser role now owns schemas created via CREATE SCHEMA ... AUTHORIZATION, so it needs no CREATE privilege on the database.
| SELECT plan( | ||
| 0 | ||
|
|
||
| + 1 -- Create non-superuser role |
There was a problem hiding this comment.
Lets consolidate these some... we definitely don't need a +1 for each line. Apply to the rest of the new test files as well.
There was a problem hiding this comment.
Claude here. Consolidated in 823be14: unrelated_drops.sql plan() is now 4 lines (was 8), and drop_owned.sql and drop_schema_cascade.sql are 5 lines each, grouped by purpose. The totals in those two are unchanged.
There was a problem hiding this comment.
Claude here. 50bf9be consolidates the plan() terms in drop_owned, drop_schema_cascade and unrelated_drops into one labelled line per group, and each helper's count now has its own line labelled with the helper's path; totals are unchanged.
| , 'Create non-superuser role' | ||
| ); | ||
| SELECT lives_ok( | ||
| format('GRANT CREATE ON DATABASE %I TO extension_drop_test_plain', current_database()) |
There was a problem hiding this comment.
Uh... can't you just do this when creating the role?
|
Claude finished @jnasbyupgrade's task in 14s —— View job Review of PR #55The I found no bugs.
Minor notes (no action required)
|
Group the per-file assertion counts into a single term and label the helper terms with the helper's path. Totals are unchanged.
|
Claude finished @jnasbyupgrade's task in 12s —— View job Review of PR #55The I found no bugs.
Minor notes (no action required)
|
|
Claude finished @jnasbyupgrade's task in 11s —— View job Review of PR #55The I found no bugs.
Minor notes (no action required)
|
…ommands A role that drops an extension (via DROP EXTENSION, DROP SCHEMA ... CASCADE or DROP OWNED) without access to extension_drop__commands got a bare "permission denied for table". The trigger now checks USAGE on the table's schema plus SELECT and DELETE on the table, after the early return for drops that involve no extension, and raises insufficient_privilege with a DETAIL naming the table and a HINT naming its owner and the grants that would fix it. The table is located through pg_extension and pg_class rather than by name, since name lookup skips a schema the caller can't use. The function stays SECURITY INVOKER: SECURITY DEFINER would run registered SQL as the owner.
|
Claude finished @jnasbyupgrade's task in 11s —— View job Review of PR #55The I found no bugs.
Minor notes (no action required)
|
The event trigger now reads and deletes the dropped extensions' registrations in one statement wrapped in an exception block for insufficient_privilege and undefined_table (a caller without USAGE on the schema gets "does not exist"). Registered SQL runs afterward, outside the block, so a privilege error from it is never mistaken for extension_drop's own. The handler raises the same actionable insufficient_privilege error, with the original message added to the DETAIL; the table owner and name for the HINT are looked up there, through pg_extension and pg_class, since the caller may lack USAGE. drop_denied now also covers SELECT without DELETE, a fully granted role dropping successfully, and a privilege error from registered SQL surfacing unchanged.
drop_denied now applies the grants the HINT names (directly, and through a group role) and checks the drop succeeds. HISTORY.asc and README.md no longer describe DROP EXTENSION as newly restricted, describe the trigger's current order (registration removed, then registered SQL run), and note that the registered SQL runs as the caller and may need further privileges.
|
Claude finished @jnasbyupgrade's task in 20s —— View job Review of PR #55The I found no bugs.
Minor notes (no action required)
|
…mmands Add a SECURITY DEFINER extension_drop__registered(name[]) that the event trigger uses to find which dropped extensions are registered. Only those go through the trapped DELETE as the caller.
|
Claude finished @jnasbyupgrade's task in 13s —— View job Review of PR #55The I found no bugs in the code I read.
Notes
|
|
Claude finished @jnasbyupgrade's task in 21s —— View job Review of PR #55 (head
|
|
Claude finished @jnasbyupgrade's task in 14s —— View job Review of PR #55 (head
|
|
Claude here. Suite layout after 931c5a3, in answer to the review of all new suites. Rule applied: a scenario shares a suite with whatever already does similar setup, unless it needs something the shared file can't give it. Folded into Kept as separate files:
Done (6420a17, 1eaa519, 9866690; the two helpers I had left pending):
Decided against:
|
pg_temp.xd_as(role, sql) replaces every SET LOCAL ROLE / RESET ROLE DO block. drop_denied defines the member-function query once; the member-function names are asserted with set_eq and SECURITY INVOKER is checked for every member other than the claim function, so a member added later cannot skip the check. The raw prosecdef query is gone.
pg_depend row order differs after binary pg_upgrade, which reordered the output in existing mode.
|
Claude finished @jnasbyupgrade's task in 15s —— View job Review of PR #55 (head
|
… the redundant xd_as handler bag_eq over (proname, prosecdef) catches an added overload or definer function that a by-name check missed. Pass inner SQL literals through %L.
|
Claude finished @jnasbyupgrade's task in 13s —— View job Review of PR #55 (head
|
|
Claude finished @jnasbyupgrade's task in 17s —— View job Review of PR #55 (head
|
| FOR r IN SELECT * FROM @[email protected]_drop__claim() LOOP | ||
| RAISE DEBUG E'extension "%" is being dropped; executing SQL:\n%', r.extension_name, r.sql; | ||
| -- Reset to the pinned path: an earlier registration may have changed it (qualified so it can't be hijacked) | ||
| PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); |
There was a problem hiding this comment.
If we're going to do this we either need to set it back to what it was or ensure that we're in a savepoint/substrans (which AFAIK will mean it gets reset due to LOCAL). The way to ensure we're in a savepoint is to put an exception handler in the block.
There was a problem hiding this comment.
Claude here. Done in 165516f: the trigger saves current_setting('search_path') before the loop and restores it with pg_catalog.set_config(..., true) after each EXECUTE r.sql; the pre-EXECUTE reset is gone.
A savepoint/exception handler isn't needed. I checked in a transaction: the function's own SET search_path clause already restores the caller's path on exit even after set_config(..., true) inside it, and an inner BEGIN ... EXCEPTION block that completes does not undo a set_config made inside it (on the error path the transaction aborts anyway). So the per-iteration restore only stops one registration's path leaking into the next.
| -- Hide version-specific NOTICE/WARNING text from the drops | ||
| SET client_min_messages = ERROR; | ||
|
|
||
| \set DROP_SCHEMA 'SELECT pg_temp.xd_as(''extension_drop_test_plain'', ''DROP SCHEMA extension_drop_test_plain_schema CASCADE'')' |
There was a problem hiding this comment.
The psql variable thing is starting to get out of hand. Is there a way to consolidate some of this or reduce overall verbosity? (IE, would creating a temp function for unregister that returns tap output reduce total script line count?)
Also, are these tests in optimal order? And do we really need all of them?
There was a problem hiding this comment.
Claude here. Consolidated in 165516f. drop_denied.sql went from 356 to 264 lines and from 51 to 33 tests; psql variables from 13 (DROP_SCHEMA, DROP_OWNED, DROP_EXTENSION, MEMBER_FUNCS, RECREATE, UNREGISTER, CAPTURE_XD001, SANITY_ASSERT, RECORD_ROLE, NEEDS_CREATEROLE, INSERT_STALE, PLANT, GRANT_CREATE) to 3 (REGISTER_RECORDER, SANITY_ASSERT, plant).
A temp function pg_temp.xd_scenario(...) now does "optionally unregister / insert a stale row / run setup, run the drop as a role, check the outcome" and returns TAP; it rolls back its own work, so scenarios need no savepoints. xd_members is a temp view replacing MEMBER_FUNCS.
Cut or merged, and why it's safe:
- Setup (create role/schema, register SQL, demote role, insert stale row, remove stale row, the plant step, drop the extension) is now plain statements; a failure still shows in the regression output.
- Registered scenarios: "lives / ran as / registration removed" is one helper call (the last two merged into one assertion). Temp-table scenario: 3 assertions to 2 (lives, effects).
- Claim outside the trigger: the superuser variant is gone, the plain-role one stays (the superuser path adds no privilege-sensitive coverage; the error is raised before any privilege matters) plus the still-registered check.
- The two planted-operator scenarios share one plant step; "hijacked = no" is folded into the helper's effects assertion.
- One behaviour change: the plain-role no-extension drops now run with a stale row present (it's inserted once for the group), which is a superset of the old no-stale check.
- Nothing dropped: all three commands registered and unregistered, ran-as, the registered SQL's privilege error, XD001 with/without registration plus message/DETAIL/HINT equality and the plural DETAIL, no-extension drops, claim outside the trigger, temp-table shadowing, the member-function list and pinned search_path, and the planted-operator checks on the claim path, the claim-with-stale-row path and the invoker path.
- Mutation check: removing SECURITY DEFINER from claim, making claim delete nothing, and removing its sanity_assert each turn drop_denied red.
Order: yes, reordered. Scenarios are grouped by state: all drops that need the extension in the plain role's schema first (savepoint only for the XD001-text and planted-operator groups that need shared setup), then the member-function checks, then the DROP EXTENSION owner scenarios, then the no-extension drops last (the extension has to be gone). That removes the "drop the schema, recreate" churn and nearly all savepoint rollbacks.
…d tests The event trigger restores the search_path it entered with after each registration instead of resetting it before. drop_denied.sql runs its scenarios through one temp function that returns TAP output.
…l-registered check
…p it from the public function list
| -- 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'); |
There was a problem hiding this comment.
Multi-line need to have ; on their own line. Update all modified/new lines in PR.
There was a problem hiding this comment.
(Or they can end with something like ); in cases where that makes more sense; the point is to make it clearer where a new statement starts)
There was a problem hiding this comment.
Claude here. Done in f0b1d58: the terminator of every multi-line statement this PR adds or modifies is now on its own line (or on a closing ); line). Updated: test/sql/drop_denied.sql, test/sql/simple.sql, sql/extension_drop.sql and sql/extension_drop--0.1.1--stable.sql (same changes in both). Layout only; the token stream is unchanged.
I left dollar-quote closers such as END $f$; and $$; as they are (treated like the ); case) and did not touch SQL inside string literals or psql meta-commands. Say if you want the END $f$;-style closers changed too.
…oc nits Close the multi-line HINT literal with `$$` and put `;` on its own line in both sql/extension_drop.sql and the 0.1.1--stable update script. CLAUDE.md: the search_path is restored after each registration, not reset before. README: name the heading instead of "section 1".
|
Claude finished @jnasbyupgrade's task in 13s —— View job Review of PR #55 (head
|
BREAKING: registered SQL now runs with
search_path = pg_catalog, pg_temp, so SQL registered withextension_drop__add()/extension_drop__update()must schema-qualify everything it uses or theDROPfails. See README.md and HISTORY.asc.extension_drop's event trigger now fires forDROP SCHEMAandDROP OWNEDas well asDROP EXTENSION, so an extension dropped byDROP SCHEMA ... CASCADEorDROP OWNED BYruns its registered SQL and has its registration removed instead of leaving a stale row inextension_drop__commands(which makes every laterDROP EXTENSIONraiseXD001).These three are the only commands that can drop an extension: an extension has ordinary
pg_dependrows only on its schema and on any extension it requires, so it goes away viaDROP EXTENSION(including cascading to dependents),DROP SCHEMA ... CASCADE, orDROP OWNED, which walksshdepend.User-visible behavior. Any role that can drop an extension can do so without privileges on
extension_drop__commands, whether or not the extension is registered. The registered SQL runs as the dropping role, so that role needs whatever the SQL needs. A stale registration still fails the drop withXD001.Mechanism. After an early return for drops that involve no extension, the event trigger (SECURITY INVOKER) calls
_extension_drop__dropping()and executes each returned SQL statement as the dropping role, in no particular order._extension_drop__dropping()is the only SECURITY DEFINER function: pinned topg_catalog, pg_temp, executable byPUBLIC, it runsDELETE ... USING pg_event_trigger_dropped_objects() ... RETURNING, thenextension_drop__sanity_assert(), and returns the deleted(extension_name, sql)rows. It never executes the SQL. Called outside asql_droptrigger,pg_event_trigger_dropped_objects()errors, so a direct call cannot delete the registration of a live extension.extension_drop__sanity_assert()andextension_drop__sanity_check()run with the owner's rights when called from the dropping function; both carry a warning comment and were reviewed as definer code (pinned path, own objects only through@extension_schema@, no dynamic SQL, arguments only compared).Every permanent function sets
search_path = pg_catalog, pg_tempand references its own objects through the extension schema. Registered SQL runs under the trigger's ownsearch_path = pg_catalog, pg_temp, restored after each registration so one registration's path change doesn't reach the next, so it must schema-qualify everything it uses (its own extension's objects, cat_tools, extension_drop's functions). This can break existing registrations and is flagged in HISTORY.asc and README.PUBLIC USAGE.
PUBLICmust have USAGE on extension_drop's schema, since the trigger calls the dropping function as the dropping role.CREATE EXTENSIONandALTER EXTENSION ... UPDATEfail otherwise, and two event triggers onREVOKEandDROP OWNED(extension_drop__usage_guard,extension_drop__usage_guard_start) protect it afterwards. The errors follow the PostgreSQL message style guide: a short primary message (cannot install extension_drop in schema "x",cannot update extension_drop in schema "x",PUBLIC lacks USAGE on schema "x",cannot remove USAGE on schema "x" from PUBLIC), the requirement andDDL command: <tag>in DETAIL, and a HINT with the exactGRANTwhere there is something to run.ALTER EVENT TRIGGERcan't changeWHEN, soextension_drop--0.1.1--stable.sqldrops and recreates the trigger and replaces every function through the samecreate_functioncalls as the install script.Tests. Suites:
simple(also coversDROP OWNED,DROP SCHEMA ... CASCADE, several registered extensions dropped by one command, the registered-SQLsearch_path, a nested_extension_drop__dropping(), andextension_drop__update()/__remove()touching only the named registration),drop_denied(privileges, definer checks, theXD001text, unrelated drops),public_usage,sanity_assert_overload(own file: plpgsql caches plans per session) anddependency_guard. Indrop_denied, most scenarios run throughpg_temp.xd_scenario, which rolls back each one in an exception subblock; only thestaleandplantedgroups still use explicit savepoints.simpleandsanity_assert_overloaduse savepoints directly.test/deps.sqlhas a HINT/DETAIL capture helper (xd_capture) and a role helper (xd_as(role, sql): runs the SQL as the role, then resets it), each used at every site. Native pgTAP assertions replace raw catalog queries where one exists (table_privs_are,is_empty);drop_denieddefines the member-function query once, as the temp viewxd_membersrather than a psql variable, and asserts the member functions as(proname, prosecdef)rows withbag_eqagainst the expected set (only_extension_drop__droppingis SECURITY DEFINER), so an added function, overload or definer flag fails the test;bag_eqis order-insensitive;has_schema_privilege, theproconfigandextversionchecks stay raw, each with a comment (schema_privs_are/functions_areassert exact sets, which fail in existing mode where the extension sharespublic).Verified. At head d3d6e18:
make teston PG17 (6/6 plus build) andmake test-updatepass,make lintreturns rc=0,make test PG_CONFIG=/usr/lib/postgresql/12/bin/pg_configon PG12 passes (6/6 plus build), and CI is green on PG12-17, the three binary pg_upgrade legs (12 → 13, 12 → 17, 16 → 17), pg_tle 12-17, SQL Lint andall-checks-passedat d3d6e18 (run 41914413381; CodeRabbit and claude-review skipped). Thebin/test_existingruns (PG17, scratch database, no real pg_upgrade; the real pg_upgrade legs ran in CI) were at 007d795 and were not re-run at d3d6e18. Commits after d3d6e18 change only the placement of statement terminators in the two SQL scripts,test/sql/drop_denied.sqlandtest/sql/simple.sql, plus README.md (the pg_dump restore Known issues) and one CLAUDE.md word. The full CI matrix last ran on f0b1d58 and again at the current head 5d440df (run 41934572570, all jobs green, matrix not skipped); ea11739's SQL layout change was never matrix-tested on its own head, because its run was cancelled by the next push and the pushes after it were skipped as docs-only.make test(6/6 plus build),make test-update(6/6 plus build) andmake lint(rc=0) were run locally on PG17 at 5d440df. 5d440df is an empty commit that changes no file.Mutations at 36f69ec (before the dropping function was renamed to
_extension_drop__dropping; not re-run after the rename, which changed no SQL logic), each turning the suite red: resetting the dropping function'ssearch_pathpin (drop_denied), making the event trigger SECURITY DEFINER (drop_denied), neutering the PUBLIC USAGE guard (public_usage), an extra SECURITY DEFINER member function with a new name, a SECURITY DEFINER overload ofextension_drop__get, a SECURITY DEFINER overload of_extension_drop__dropping(all three caught by thebag_eq), the dropping function no longer SECURITY DEFINER (caught by thebag_eqand the drop scenarios), and removingxd_as'sRESET ROLE(drop_denied,public_usageandsanity_assert_overload). Re-run against the rewritten tests at 165516f, both failed as expected: deleting the install script's per-registrationsearch_pathrestore (simplewent red), and giving the dropping function an unpinnedsearch_path(the planted-operator and pin tests went red). The update script'ssearch_pathrestore has not been mutated. Each replaced assertion's mutation was run only at earlier heads and is not re-run. The remaining claims below were run at 4384701/d5cc8e7; later commits change no SQL logic besides thesearch_pathrestore.SELECT extension_drop__add('my_extension', format('SELECT %s.extension_drop__get(%L)', extnamespace::regnamespace, 'my_extension')) FROM pg_extension WHERE extname = 'extension_drop') run in psql on PG17 with extension_drop installed in schemas"xD s"andplain: the registered SQL wasSELECT "xD s".extension_drop__get('extension_drop_test')andSELECT plain.extension_drop__get(...), and running the stored SQL returned the registered row.%Ion the same value double-quotes it.make test,make test-updateandmake lintpass (PG12 viaPG_CONFIG=/usr/lib/postgresql/12/bin/pg_config).bin/test_existing prepareplusrun-suitepass on PG17 against a scratch database (no real pg_upgrade; not run on PG12).proacl, owner, comments,proconfig, event triggers, columns and schema ACLs, on PG12 and PG17, for schemas"xD s","a""b%s"and"x$body$y". The event trigger'smd5(prosrc)was compared again for the restore at 36f69ec (PG17): identical.ORDER BYremains in either SQL script. Neither the dropping function norextension_drop__sanity_check()orders its output; the pluralXD001DETAIL lists names in no particular order.simplechecks every registered SQL ran and every registration was removed as sets;drop_deniedchecks the plural wording and each name separately.CREATE EXTENSION, or theALTER EXTENSION ... UPDATEthat first created it (checked with two superuser roles on PG17 at an earlier head; the SQL for it has not changed since).extension_drop__update()andextension_drop__remove()compared the unqualified argument name, which resolves to the table column, so with two registrations each changed (update) or deleted (remove) every row. The argument is now qualified with the function name in both scripts;simpleupdates one of two registrations and removes one, and checks the other is unchanged.pg_dumprestore problems were reproduced and each workaround tested on PG12 and PG17, with and without-x, in custom format (pg_restore) and plain SQL (psql); the commands were then extracted from the README and run verbatim on both versions. Not tested: restoring with a different major version than the dump, a non-superuser restoring role, schema names that need quoting.